Skip to content

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

Sync with build 609: Beta 2

Dan22c052686776
diff --git a/README.md b/README.md
index 24d1f5b..9ee1ee8 100644
--- a/README.md
+++ b/README.md
@@ -233,7 +233,7 @@ The ISO is written to `out/`. The first build downloads about 3 GB of packages;
| Path | What's in it |
| --- | --- |
| `build/` | Image build: builder container, package list, chroot hooks, boot menu, patches to upstream packages |
-| `packages/` | Wild OS's own Debian packages: base system, desktop and shell, Settings, Files, Store, Mail and Calendar (`wildos-mail`), Write and Tables (`wildos-office`), Remote (`wildos-remote`), PDF (`wildos-pdf`), Capture (`wildos-capture`), Notes (`wildos-notes`), Music (`wildos-music`), Videos (`wildos-videos`), Archive (`wildos-archive`), Voice (`wildos-voice`), Backup (`wildos-backup`), Report a problem (`wildos-report`), Terminal, Task Manager, lighting, welcome, installer and Windows mode (`wildos-winmode`) |
+| `packages/` | Wild OS's own Debian packages: base system, desktop and shell, Settings, Files, Store, Mail and Calendar (`wildos-mail`), Write and Tables (`wildos-write` and `wildos-tables`, sharing `wildos-office`), Remote (`wildos-remote`), PDF (`wildos-pdf`), Capture (`wildos-capture`), Notes (`wildos-notes`), Music (`wildos-music`), Videos (`wildos-videos`), Archive (`wildos-archive`), Voice (`wildos-voice`), Backup (`wildos-backup`), Report a problem (`wildos-report`), Terminal, Task Manager, lighting, welcome, installer and Windows mode (`wildos-winmode`) |
| `branding/` | Logo, glyphs and wallpaper |
| `docs/assets/` | The images on this page |
diff --git a/build/build.sh b/build/build.sh
index b5aa816..10feb0f 100644
--- a/build/build.sh
+++ b/build/build.sh
@@ -616,6 +616,94 @@ COPYRIGHT
fi
cp "$cached"/*.deb "$WORK/repo/"
)
+# kactivitymanagerd, which keeps the recent files history, with the patch
+# from build/patches/kactivitymanagerd: Forget Recent Files on one app's
+# taskbar menu forgets only that app's files instead of emptying Start's
+# recent list too.
+(
+ cd "$WORK"
+ version=$(apt-cache policy kactivitymanagerd | sed -n 's/^ Candidate: //p')
+ if [ -z "$version" ] || [ "$version" = "(none)" ]; then
+ apt-get update -qq
+ version=$(apt-cache policy kactivitymanagerd | sed -n 's/^ Candidate: //p')
+ fi
+ stamp=$(cat "$SRC"/build/patches/kactivitymanagerd/*.patch | sha256sum | cut -c1-12)
+ cached="$REBUILDS/kactivitymanagerd/$version$(wildos_suffix kactivitymanagerd)-$stamp"
+ if [ ! -d "$cached" ]; then
+ log "Building patched kactivitymanagerd $version"
+ echo "deb-src http://deb.debian.org/debian $SUITE main" > /etc/apt/sources.list.d/wildos-src.list
+ apt-get update -qq
+ DEBIAN_FRONTEND=noninteractive apt-get build-dep -y -qq "kactivitymanagerd=$version" >/dev/null
+ rm -rf kactivitymanagerd-src && mkdir kactivitymanagerd-src && cd kactivitymanagerd-src
+ apt-get source -qq "kactivitymanagerd=$version" >/dev/null
+ cd kactivitymanagerd-*/
+ mkdir -p debian/patches
+ for patch in "$SRC"/build/patches/kactivitymanagerd/*.patch; do
+ cp "$patch" debian/patches/
+ basename "$patch" >> debian/patches/series
+ done
+ {
+ printf 'kactivitymanagerd (%s%s) %s; urgency=medium\n\n' "$version" "$(wildos_suffix kactivitymanagerd)" "$SUITE"
+ printf ' * Wild OS patches: %s\n\n' "$(cd "$SRC/build/patches/kactivitymanagerd" && ls *.patch | tr '\n' ' ')"
+ printf ' -- Wild OS Developers <[email protected]> %s\n\n' "$(date -R)"
+ cat debian/changelog
+ } > debian/changelog.new
+ mv debian/changelog.new debian/changelog
+ DEB_BUILD_OPTIONS="nocheck nodoc parallel=$BUILD_THREADS" dpkg-buildpackage -us -uc -b >/dev/null
+ fill="$cached.part.$BASHPID"
+ rm -rf "$fill" && mkdir -p "$fill"
+ cp ../*+wildos[0-9]*_*.deb "$fill/"
+ rm -f "$fill"/*dbgsym*
+ cd "$WORK" && rm -rf kactivitymanagerd-src
+ # Another build may have made the same one meanwhile; either copy is good.
+ mv -T "$fill" "$cached" 2>/dev/null || rm -rf "$fill"
+ fi
+ cp "$cached"/*.deb "$WORK/repo/"
+)
+# Plasma's platform theme for Qt apps with the patch from
+# build/patches/plasma-integration: a Qt or KDE app's Open and Save dialog
+# (Wild OS's, through the desktop portal) is attached to the app's window on
+# Wayland, with no taskbar button of its own. Republished +wildos1 like KIO.
+(
+ cd "$WORK"
+ version=$(apt-cache policy plasma-integration | sed -n 's/^ Candidate: //p')
+ if [ -z "$version" ] || [ "$version" = "(none)" ]; then
+ apt-get update -qq
+ version=$(apt-cache policy plasma-integration | sed -n 's/^ Candidate: //p')
+ fi
+ stamp=$(cat "$SRC"/build/patches/plasma-integration/*.patch | sha256sum | cut -c1-12)
+ cached="$REBUILDS/plasma-integration/$version$(wildos_suffix plasma-integration)-$stamp"
+ if [ ! -d "$cached" ]; then
+ log "Building patched plasma-integration $version"
+ echo "deb-src http://deb.debian.org/debian $SUITE main" > /etc/apt/sources.list.d/wildos-src.list
+ apt-get update -qq
+ DEBIAN_FRONTEND=noninteractive apt-get build-dep -y -qq "plasma-integration=$version" >/dev/null
+ rm -rf plasma-integration-src && mkdir plasma-integration-src && cd plasma-integration-src
+ apt-get source -qq "plasma-integration=$version" >/dev/null
+ cd plasma-integration-*/
+ mkdir -p debian/patches
+ for patch in "$SRC"/build/patches/plasma-integration/*.patch; do
+ cp "$patch" debian/patches/
+ basename "$patch" >> debian/patches/series
+ done
+ {
+ printf 'plasma-integration (%s%s) %s; urgency=medium\n\n' "$version" "$(wildos_suffix plasma-integration)" "$SUITE"
+ printf ' * Wild OS patches: %s\n\n' "$(cd "$SRC/build/patches/plasma-integration" && ls *.patch | tr '\n' ' ')"
+ printf ' -- Wild OS Developers <[email protected]> %s\n\n' "$(date -R)"
+ cat debian/changelog
+ } > debian/changelog.new
+ mv debian/changelog.new debian/changelog
+ DEB_BUILD_OPTIONS="nocheck nodoc parallel=$BUILD_THREADS" dpkg-buildpackage -us -uc -b >/dev/null
+ fill="$cached.part.$BASHPID"
+ rm -rf "$fill" && mkdir -p "$fill"
+ cp ../*+wildos[0-9]*_*.deb "$fill/"
+ rm -f "$fill"/*dbgsym*
+ cd "$WORK" && rm -rf plasma-integration-src
+ # Another build may have made the same one meanwhile; either copy is good.
+ mv -T "$fill" "$cached" 2>/dev/null || rm -rf "$fill"
+ fi
+ cp "$cached"/*.deb "$WORK/repo/"
+)
# evolution-data-server with Camel's mail modules (IMAP, SMTP and the rest)
# split into evolution-data-server-camel-providers, which needs only
# libcamel, and its calendar and contacts services into
@@ -962,6 +1050,9 @@ log "Bootstrapping root filesystem"
# adduser goes in straight after the essential packages: security-misc
# creates groups in its preinst, which runs before apt has configured
# adduser unless something else pulled adduser in earlier.
+# wildos-base's apt pins go in before anything is chosen, so the image gets
+# the same kernel, firmware, Mesa and FreeRDP versions as an updated PC
+# rather than trixie's own.
mmdebstrap \
--mode=root \
--variant=apt \
@@ -972,6 +1063,7 @@ mmdebstrap \
--skip=essential/unlink \
--setup-hook='mkdir -p "$1/var/cache/apt/archives" "$1/usr/share/keyrings" "$1/var/lib/security-misc" "$1/etc/dpkg/dpkg.cfg.d" "$1/etc/apt/preferences.d"' \
--setup-hook="copy-in $SRC/packages/wildos-base/files/apt/wildos-freerdp.pref /etc/apt/preferences.d/" \
+ --setup-hook="copy-in $SRC/packages/wildos-base/files/apt/wildos-newer.pref /etc/apt/preferences.d/" \
--setup-hook="copy-in $SRC/build/90-wildos-slim /etc/dpkg/dpkg.cfg.d/" \
--essential-hook='APT_CONFIG="$MMDEBSTRAP_APT_CONFIG" apt-get install --yes -qq adduser >/dev/null' \
--setup-hook='touch "$1/var/lib/security-misc/skip_install_check"' \
diff --git a/build/patches/calamares/wildos-disk-page.patch b/build/patches/calamares/wildos-disk-page.patch
index 44414e4..255bcac 100644
--- a/build/patches/calamares/wildos-disk-page.patch
+++ b/build/patches/calamares/wildos-disk-page.patch
@@ -14,7 +14,9 @@ Description: The "Where should Wild OS go?" page and the disk editor of the Wild
X GB of its space" and the disk's name and size under it. "Replace a
partition" is not offered. Alongside is the first choice when possible.
The wording names the system found ("Install alongside Windows",
- "Replace Windows with Wild OS").
+ "Replace Windows with Wild OS"). An earlier Wild OS install, which
+ os-prober cannot see (encrypted, or in a Btrfs subvolume), is found by
+ its partition names and named on the page too.
* alongsideBlocked in global storage (from the installer's own checks:
"bitlocker", "faststartup", "dirty" or "space") keeps Alongside visible
but unavailable, with the reason on its card; nothing is preselected
@@ -974,12 +976,24 @@ Forwarded: no
}
}
-@@ -1729,93 +2058,60 @@ ChoicePage::shouldShowEncryptWidget( Config::InstallChoice choice ) const
- void
- ChoicePage::updateActionDescriptionsTr()
+@@ -1726,96 +2055,97 @@ ChoicePage::shouldShowEncryptWidget( Config::InstallChoice choice ) const
+ return suitableChoice && m_enableEncryptionWidget && suitableFS;
+ }
+
+-void
+-ChoicePage::updateActionDescriptionsTr()
++/** @brief Whether @p device holds an earlier Wild OS install
++ *
++ * os-prober never reports one: its root is encrypted, and even without
++ * encryption the system sits in a Btrfs subvolume os-prober does not look
++ * in. The partitions keep the names partition.conf gives them.
++ */
++static bool
++hasWildOsInstall( Device* device )
{
- if ( m_osproberEntriesCount == 0 )
-- {
++ if ( !device )
+ {
- cDebug() << "Setting texts for 0 osprober entries";
- m_messageLabel->setText( tr( "This storage device does not seem to have an operating system on it. "
- "What would you like to do?<br/>"
@@ -997,46 +1011,13 @@ Forwarded: no
- m_replaceButton->setText( tr( "<strong>Replace a partition</strong><br/>"
- "Replaces a partition with %1." )
- .arg( Calamares::Branding::instance()->shortVersionedName() ) );
-- }
++ return false;
+ }
- if ( m_osproberEntriesCount == 1 )
-- {
++ for ( auto it = PartitionIterator::begin( device ); it != PartitionIterator::end( device ); ++it )
+ {
- if ( !m_osproberOneEntryName.isEmpty() )
-+ if ( m_osproberEntriesCount < 0 || !m_eraseButton )
-+ {
-+ return; // Nothing scanned yet
-+ }
-+ const QString product = Calamares::Branding::instance()->shortProductName();
-+ const QString other = otherSystemName();
-+ const bool keepPossible = m_alongsideButton && !m_alongsideButton->isHidden();
-+
-+ if ( m_osproberEntriesCount <= 0 )
-+ {
-+ m_messageLabel->setText( tr( "There is no other system on this disk, so %1 can use all of it." ).arg( product ) );
-+ m_eraseButton->setText( cardText( tr( "Replace everything on this disk" ),
-+ tr( "Erases the whole disk. Copy anything you want to keep somewhere "
-+ "safe first." ) ) );
-+ }
-+ else if ( !other.isEmpty() )
-+ {
-+ m_messageLabel->setText(
-+ keepPossible ? tr( "We found %1 on this computer. You can keep it and choose which one to use each "
-+ "time you start up." )
-+ .arg( other )
-+ : tr( "We found %1 on this computer, but %2 cannot make room beside it. It may be short "
-+ "of free space, or locked with BitLocker." )
-+ .arg( other, product ) );
-+ m_eraseButton->setText(
-+ cardText( tr( "Replace %1 with %2" ).arg( other, product ),
-+ tr( "Erases the whole disk, %1 and your files included. Copy anything you want to keep "
-+ "somewhere safe first." )
-+ .arg( other ) ) );
-+ m_alongsideButton->setText(
-+ cardText( tr( "Install alongside %1" ).arg( other ),
-+ alongsideBlockedReason().isEmpty()
-+ ? tr( "Keeps %1 and all your files. Drag the divider to share the space." ).arg( other )
-+ : alongsideBlockedReason() ) );
-+ if ( keepPossible && !m_alongsideButton->isEnabled() )
- {
+- {
- cDebug() << "Setting texts for 1 non-empty osprober entry";
- m_messageLabel->setText( tr( "This storage device has %1 on it. "
- "What would you like to do?<br/>"
@@ -1057,7 +1038,9 @@ Forwarded: no
- .arg( Calamares::Branding::instance()->shortVersionedName() ) );
- }
- else
-- {
++ const QString name = ( *it )->label();
++ if ( name == QStringLiteral( "wildos-root" ) || name == QStringLiteral( "wildos-boot" ) )
+ {
- cDebug() << "Setting texts for 1 empty osprober entry";
- m_messageLabel->setText( tr( "This storage device already has an operating system on it. "
- "What would you like to do?<br/>"
@@ -1075,9 +1058,7 @@ Forwarded: no
- m_replaceButton->setText( tr( "<strong>Replace a partition</strong><br/>"
- "Replaces a partition with %1." )
- .arg( Calamares::Branding::instance()->shortVersionedName() ) );
-+ m_messageLabel->setText( tr( "We found %1 on this computer. To keep it, first change the Windows "
-+ "settings listed in Before we start." )
-+ .arg( other ) );
++ return true;
}
}
- if ( m_osproberEntriesCount >= 2 )
@@ -1096,11 +1077,66 @@ Forwarded: no
- m_eraseButton->setText( tr( "<strong>Erase disk</strong><br/>"
- "This will <font color=\"red\">delete</font> all data "
- "currently present on the selected storage device." ) );
--
++ return false;
++}
+
- m_replaceButton->setText( tr( "<strong>Replace a partition</strong><br/>"
- "Replaces a partition with %1." )
- .arg( Calamares::Branding::instance()->shortVersionedName() ) );
-- }
++void
++ChoicePage::updateActionDescriptionsTr()
++{
++ if ( m_osproberEntriesCount < 0 || !m_eraseButton )
++ {
++ return; // Nothing scanned yet
++ }
++ const QString product = Calamares::Branding::instance()->shortProductName();
++ const QString other = otherSystemName();
++ const bool keepPossible = m_alongsideButton && !m_alongsideButton->isHidden();
++
++ if ( m_osproberEntriesCount <= 0 && hasWildOsInstall( selectedDevice() ) )
++ {
++ m_messageLabel->setText( tr( "%1 is already installed on this disk. Installing it again replaces it, "
++ "and everything else on the disk." )
++ .arg( product ) );
++ m_eraseButton->setText( cardText( tr( "Replace everything on this disk" ),
++ tr( "Erases the whole disk, the %1 already on it and your files "
++ "included. Copy anything you want to keep somewhere safe first." )
++ .arg( product ) ) );
++ }
++ else if ( m_osproberEntriesCount <= 0 )
++ {
++ m_messageLabel->setText( tr( "There is no other system on this disk, so %1 can use all of it." ).arg( product ) );
++ m_eraseButton->setText( cardText( tr( "Replace everything on this disk" ),
++ tr( "Erases the whole disk. Copy anything you want to keep somewhere "
++ "safe first." ) ) );
++ }
++ else if ( !other.isEmpty() )
++ {
++ m_messageLabel->setText(
++ keepPossible ? tr( "We found %1 on this computer. You can keep it and choose which one to use each "
++ "time you start up." )
++ .arg( other )
++ : tr( "We found %1 on this computer, but %2 cannot make room beside it. It may be short "
++ "of free space, or locked with BitLocker." )
++ .arg( other, product ) );
++ m_eraseButton->setText(
++ cardText( tr( "Replace %1 with %2" ).arg( other, product ),
++ tr( "Erases the whole disk, %1 and your files included. Copy anything you want to keep "
++ "somewhere safe first." )
++ .arg( other ) ) );
++ m_alongsideButton->setText(
++ cardText( tr( "Install alongside %1" ).arg( other ),
++ alongsideBlockedReason().isEmpty()
++ ? tr( "Keeps %1 and all your files. Drag the divider to share the space." ).arg( other )
++ : alongsideBlockedReason() ) );
++ if ( keepPossible && !m_alongsideButton->isEnabled() )
++ {
++ m_messageLabel->setText( tr( "We found %1 on this computer. To keep it, first change the Windows "
++ "settings listed in Before we start." )
++ .arg( other ) );
++ }
+ }
- if ( m_osproberEntriesCount < 0 )
+ else
{
diff --git a/build/patches/kactivitymanagerd/wildos-forget-app-only.patch b/build/patches/kactivitymanagerd/wildos-forget-app-only.patch
new file mode 100644
index 0000000..02d118f
--- /dev/null
+++ b/build/patches/kactivitymanagerd/wildos-forget-app-only.patch
@@ -0,0 +1,55 @@
+Description: Forgetting one app's recent files keeps every other app's
+ A task manager jump list's Forget Recent Files deletes that app's history
+ with DeleteStatsForResource for every resource ("*"). The history rows are
+ filtered by the app, but the resources' mimetype and title rows were
+ deleted for every resource, and lists filtered by type, like Start's
+ recent files, then dropped every file. Now a resource's mimetype and
+ title go only once no history, score or link refers to it.
+Author: Wild OS Developers <[email protected]>
+Forwarded: no
+
+--- a/src/service/plugins/sqlite/StatsPlugin.cpp
++++ b/src/service/plugins/sqlite/StatsPlugin.cpp
+@@ -540,11 +540,6 @@
+
+ const auto clientFilter = client == ANY_AGENT_TAG ? " 1 " : QStringLiteral(" initiatingAgent = '%1' ").arg(client);
+
+- auto removeResourceInfoQuery = resourcesDatabase()->createQuery();
+- removeResourceInfoQuery.prepare(
+- "DELETE FROM ResourceInfo "
+- "WHERE targettedResource LIKE :targettedResource ESCAPE '\\'");
+-
+ auto removeEventsQuery = resourcesDatabase()->createQuery();
+ removeEventsQuery.prepare(
+ "DELETE FROM ResourceEvent "
+@@ -557,14 +552,28 @@
+ "WHERE "
+ + activityFilter + " AND " + clientFilter + " AND " + "targettedResource LIKE :targettedResource ESCAPE '\\'");
+
+- const auto pattern = Common::starPatternToLike(resource);
++ // A resource's mimetype and title are shared by every app and activity
++ // that used it, and lists filtered by type, like the launchers' recent
++ // files, drop a resource without them. Forgetting one app's resources
++ // (all of them, "*", from a task manager jump list) deleted them for
++ // every resource, so only the ones nothing refers to any more go now,
++ // after the app's own rows.
++ auto removeResourceInfoQuery = resourcesDatabase()->createQuery();
++ removeResourceInfoQuery.prepare(
++ "DELETE FROM ResourceInfo "
++ "WHERE targettedResource LIKE :targettedResource ESCAPE '\\' "
++ "AND NOT EXISTS (SELECT 1 FROM ResourceEvent e WHERE e.targettedResource = ResourceInfo.targettedResource) "
++ "AND NOT EXISTS (SELECT 1 FROM ResourceScoreCache c WHERE c.targettedResource = ResourceInfo.targettedResource) "
++ "AND NOT EXISTS (SELECT 1 FROM ResourceLink l WHERE l.targettedResource = ResourceInfo.targettedResource)");
+
+- Utils::exec(*resourcesDatabase(), Utils::FailOnError, removeResourceInfoQuery, ":targettedResource", pattern);
++ const auto pattern = Common::starPatternToLike(resource);
+
+ Utils::exec(*resourcesDatabase(), Utils::FailOnError, removeEventsQuery, ":targettedResource", pattern);
+
+ Utils::exec(*resourcesDatabase(), Utils::FailOnError, removeScoreCachesQuery, ":targettedResource", pattern);
+
++ Utils::exec(*resourcesDatabase(), Utils::FailOnError, removeResourceInfoQuery, ":targettedResource", pattern);
++
+ Q_EMIT ResourceScoreDeleted(activity, client, resource);
+ }
+
diff --git a/build/patches/libreoffice/wildos-window-app-id.patch b/build/patches/libreoffice/wildos-window-app-id.patch
new file mode 100644
index 0000000..a92d263
--- /dev/null
+++ b/build/patches/libreoffice/wildos-window-app-id.patch
@@ -0,0 +1,58 @@
+Description: Each window keeps its app's taskbar button on Wayland
+ With the Qt and KDE plugins on Wayland a window's app_id comes from the
+ application's desktop file name at the moment the window is shown, and
+ LibreOffice starts with libreoffice-startcenter there. SetIcon set the
+ module's own (libreoffice-writer, libreoffice-calc...) only for a window
+ already on screen, by hiding and showing it. wildos-load-window.patch shows
+ a document's window only once the document is in it, after its icon is
+ set, so every Write and Tables window came up as libreoffice-startcenter and
+ sat on a taskbar button of its own instead of on Write's or Tables'. The
+ frame now remembers the app_id SetIcon chose and Show gives it to the
+ window when it first appears.
+Author: Wild OS Developers <[email protected]>
+Forwarded: not-needed
+
+--- a/vcl/inc/qt5/QtFrame.hxx
++++ b/vcl/inc/qt5/QtFrame.hxx
+@@ -102,6 +102,9 @@
+ bool m_bFullScreenSpanAll;
+ sal_uInt32 m_nRestoreScreen;
+ QRect m_aRestoreGeometry;
++ // Wild OS: the Wayland app_id SetIcon chose, for Show to give a window
++ // that was not on screen yet.
++ QString m_sAppId;
+
+ #if !defined EMSCRIPTEN
+ SessionManagerInhibitor m_SessionManagerInhibitor;
+--- a/vcl/qt5/QtFrame.cxx
++++ b/vcl/qt5/QtFrame.cxx
+@@ -360,6 +360,12 @@
+ QIcon aIcon = QIcon::fromTheme(appicon);
+ m_pQWidget->window()->setWindowIcon(aIcon);
+
++ // Wild OS: a document's window is shown only once the document is in it,
++ // after its icon is set here, so Show gives it this app_id. Without it the
++ // window came up as libreoffice-startcenter and sat apart from its
++ // app's taskbar button.
++ m_sAppId = appicon;
++
+ if (QGuiApplication::platformName() == "wayland" && m_pQWidget->window()->isVisible())
+ {
+ // Qt currently doesn't provide API to directly set the app_id for a single
+@@ -414,7 +420,16 @@
+ SetDefaultSize();
+
+ QWidget* const pChild = asChild();
++ // Wild OS: Qt takes a Wayland window's app_id from the application's
++ // desktop file name when the window first shows, so lend it this frame's.
++ const bool bAppId = !m_sAppId.isEmpty() && pChild == m_pQWidget->window()
++ && QGuiApplication::platformName() == "wayland";
++ const QString sOrigDesktopFileName = QGuiApplication::desktopFileName();
++ if (bAppId)
++ QGuiApplication::setDesktopFileName(m_sAppId);
+ pChild->setVisible(true);
++ if (bAppId)
++ QGuiApplication::setDesktopFileName(sOrigDesktopFileName);
+ pChild->raise();
+ if (!bNoActivate)
+ {
diff --git a/build/patches/libreoffice/wildos-window-parents.patch b/build/patches/libreoffice/wildos-window-parents.patch
new file mode 100644
index 0000000..be77fc1
--- /dev/null
+++ b/build/patches/libreoffice/wildos-window-parents.patch
@@ -0,0 +1,193 @@
+Description: Dialogs that belong to no window yet sit on their app's taskbar pin, and Open and Save dialogs attach to their window
+ Document Recovery, and the dialog that saves documents when LibreOffice
+ crashes, come up before any document window, so they kept LibreOffice's
+ own icon and, on Wayland, the libreoffice-startcenter app_id: a plain
+ taskbar button of their own. They now take the icon of the app whose
+ documents they save or recover (Writer's when none is known), which with
+ wildos-window-app-id.patch also gives them that app's app_id.
+ .
+ The Qt file picker asked the desktop portal for its Open and Save dialog
+ with no parent window, so the dialog had a taskbar button of its own and
+ the document stayed usable behind it. It now names the window the way
+ Qt's own portal dialogs do, through Qt's private platform services: on
+ Wayland an xdg-foreign handle. The window LibreOffice names for a picker
+ can be a hidden one there (window ids mean nothing on Wayland), so the
+ active window stands in for it.
+Author: Wild OS Developers <[email protected]>
+Forwarded: not-needed
+
+--- a/svx/source/dialog/docrecovery.cxx
++++ b/svx/source/dialog/docrecovery.cxx
+@@ -26,6 +26,9 @@
+ #include <comphelper/sequenceashashmap.hxx>
+ #include <comphelper/string.hxx>
+ #include <svtools/imagemgr.hxx>
++#include <toolkit/helper/vclunohelper.hxx>
++#include <unotools/moduleoptions.hxx>
++#include <vcl/syswin.hxx>
+ #include <sfx2/filedlghelper.hxx>
+ #include <tools/urlobj.hxx>
+ #include <utility>
+@@ -52,6 +55,33 @@
+ #define COLUMN_STATUSIMAGE 1
+ #define COLUMN_STATUSTEXT 2
+
++namespace
++{
++// Wild OS: these dialogs come up before any document window, so they had
++// LibreOffice's own icon and, on Wayland, its app_id: a plain taskbar button
++// of their own. Give them the icon of the app whose documents they save or
++// recover (Writer's when none is known), which also puts them on that app's
++// taskbar button.
++void lcl_wildosAppIcon(weld::Dialog& rDialog, const TURLList& rURLs)
++{
++ SvtModuleOptions::EFactory eFactory = SvtModuleOptions::EFactory::WRITER;
++ for (const TURLInfo& rInfo : rURLs)
++ {
++ const SvtModuleOptions::EFactory eDoc
++ = SvtModuleOptions::ClassifyFactoryByServiceName(rInfo.Module);
++ if (eDoc != SvtModuleOptions::EFactory::UNKNOWN_FACTORY)
++ {
++ eFactory = eDoc;
++ break;
++ }
++ }
++ VclPtr<vcl::Window> pWindow = VCLUnoHelper::GetWindow(rDialog.GetXWindow());
++ if (pWindow && pWindow->IsSystemWindow())
++ static_cast<SystemWindow*>(pWindow.get())
++ ->SetIcon(static_cast<sal_uInt16>(SvtModuleOptions().GetFactoryIcon(eFactory)));
++}
++}
++
+ RecoveryCore::RecoveryCore(css::uno::Reference< css::uno::XComponentContext > xContext,
+ bool bUsedForSaving)
+ : m_xContext (std::move( xContext ))
+@@ -593,6 +623,8 @@
+ {
+ m_xFileListLB->append(u""_ustr, rInfo.DisplayName, rInfo.StandardImageId);
+ }
++
++ lcl_wildosAppIcon(*m_xDialog, rURLs);
+ }
+
+ SaveDialog::~SaveDialog()
+@@ -727,6 +759,8 @@
+ // mark first item
+ if (m_xFileListLB->n_children())
+ m_xFileListLB->set_cursor(0);
++
++ lcl_wildosAppIcon(*m_xDialog, rURLList);
+ }
+
+ RecoveryDialog::~RecoveryDialog()
+--- a/vcl/Library_vclplug_qt6.mk
++++ b/vcl/Library_vclplug_qt6.mk
+@@ -39,6 +39,17 @@
+ # Wild OS: the file picker talks to the desktop portal.
+ $(eval $(call gb_Library_add_libs,vclplug_qt6,-lQt6DBus))
+
++# Wild OS: and names its parent window there the way Qt's own portal dialogs
++# do, through Qt's private platform services.
++wildos_qt_gui := $(lastword $(wildcard /usr/include/*/qt6/QtGui/6.*))
++wildos_qt_core := $(subst /QtGui/,/QtCore/,$(wildos_qt_gui))
++$(eval $(call gb_Library_add_cxxflags,vclplug_qt6,\
++ -isystem $(dir $(wildos_qt_core)) -isystem $(wildos_qt_core) -isystem $(wildos_qt_core)/QtCore \
++ -isystem $(dir $(wildos_qt_gui)) -isystem $(wildos_qt_gui) -isystem $(wildos_qt_gui)/QtGui \
++ -isystem $(lastword $(wildcard /usr/lib/*/qt6/mkspecs/linux-g++)) \
++ -DWILDOS_QT_PRIVATE \
++))
++
+ $(eval $(call gb_Library_use_libraries,vclplug_qt6,\
+ tl \
+ utl \
+--- a/vcl/qt5/QtFilePicker.cxx
++++ b/vcl/qt5/QtFilePicker.cxx
+@@ -74,6 +74,11 @@
+ #include <QtDBus/QDBusMessage>
+ #include <QtDBus/QDBusMetaType>
+ #include <QtDBus/QDBusObjectPath>
++#ifdef WILDOS_QT_PRIVATE
++#include <QtGui/private/qgenericunixservices_p.h>
++#include <QtGui/private/qguiapplication_p.h>
++#include <QtGui/qpa/qplatformintegration.h>
++#endif
+
+ #include <unx/geninst.h>
+ #include <fpicker/strings.hrc>
+@@ -323,6 +328,47 @@
+ }
+ }
+
++namespace
++{
++// The window a file dialog belongs to: the one LibreOffice named, else the
++// active one.
++QWidget* lcl_transientParent(QWidget* pParentWidget)
++{
++ if (pParentWidget)
++ return pParentWidget;
++ vcl::Window* pWindow = ::Application::GetActiveTopWindow();
++ if (!pWindow)
++ return nullptr;
++ QtFrame* pFrame = dynamic_cast<QtFrame*>(pWindow->ImplGetFrame());
++ assert(pFrame);
++ return pFrame ? pFrame->asChild() : nullptr;
++}
++
++// Wild OS: the portal's name for the window a dialog belongs to ("wayland:"
++// and an xdg-foreign handle, or "x11:" and its id), so the dialog opens
++// attached to it, in front of it and without a taskbar button of its own.
++// On Wayland the window LibreOffice names can be a hidden one (window ids
++// mean nothing there), so then the active window. Empty without either.
++QString lcl_portalParent(QWidget* pParent)
++{
++#ifdef WILDOS_QT_PRIVATE
++ auto aShown = [](QWidget* pWidget) -> QWindow* {
++ QWindow* pWindow = pWidget ? pWidget->window()->windowHandle() : nullptr;
++ return pWindow && pWindow->isVisible() ? pWindow : nullptr;
++ };
++ QWindow* pWindow = aShown(pParent);
++ if (!pWindow)
++ pWindow = aShown(lcl_transientParent(nullptr));
++ auto pServices = dynamic_cast<QGenericUnixServices*>(
++ QGuiApplicationPrivate::platformIntegration()->services());
++ return pWindow && pServices ? pServices->portalWindowIdentifier(pWindow) : QString();
++#else
++ (void)pParent;
++ return QString();
++#endif
++}
++}
++
+ bool QtFilePicker::execPortal(int& rResult)
+ {
+ using namespace wildosportal;
+@@ -417,7 +463,7 @@
+ sDesktop, QStringLiteral("/org/freedesktop/portal/desktop"),
+ QStringLiteral("org.freedesktop.portal.FileChooser"),
+ bSave ? QStringLiteral("SaveFile") : QStringLiteral("OpenFile"));
+- aCall << QString() << m_pFileDialog->windowTitle() << aOptions;
++ aCall << lcl_portalParent(m_pParentWidget) << m_pFileDialog->windowTitle() << aOptions;
+ const QDBusMessage aReply = aBus.call(aCall);
+ if (aReply.type() != QDBusMessage::ReplyMessage || aReply.arguments().isEmpty())
+ {
+@@ -507,18 +553,7 @@
+
+ void QtFilePicker::prepareExecute()
+ {
+- QWidget* pTransientParent = m_pParentWidget;
+- if (!pTransientParent)
+- {
+- vcl::Window* pWindow = ::Application::GetActiveTopWindow();
+- if (pWindow)
+- {
+- QtFrame* pFrame = dynamic_cast<QtFrame*>(pWindow->ImplGetFrame());
+- assert(pFrame);
+- if (pFrame)
+- pTransientParent = pFrame->asChild();
+- }
+- }
++ QWidget* pTransientParent = lcl_transientParent(m_pParentWidget);
+
+ if (!m_aNamedFilterList.isEmpty())
+ m_pFileDialog->setNameFilters(m_aNamedFilterList);
diff --git a/build/patches/plasma-integration/wildos-portal-parent.patch b/build/patches/plasma-integration/wildos-portal-parent.patch
new file mode 100644
index 0000000..3579242
--- /dev/null
+++ b/build/patches/plasma-integration/wildos-portal-parent.patch
@@ -0,0 +1,64 @@
+Description: Open and Save dialogs attach to their app's window on Wayland
+ Qt and KDE apps ask the desktop portal for their Open and Save dialog
+ through this platform theme's copy of Qt's portal file dialog, which names
+ the parent window "x11:" and its id even on Wayland, where that names no
+ window. The dialog then came up on its own with a taskbar button of its
+ own, and could fall behind its app. It now asks Qt's platform services
+ for the name, as Qt's own portal code does: "wayland:" and an xdg-foreign
+ handle on Wayland, "x11:" and the id on X11.
+Author: Wild OS Developers <[email protected]>
+Forwarded: not-needed
+
+--- a/qt6/src/platformtheme/qxdgdesktopportalfiledialog.cpp
++++ b/qt6/src/platformtheme/qxdgdesktopportalfiledialog.cpp
+@@ -25,8 +25,13 @@
+ #include <QMimeDatabase>
+ #include <QMimeType>
+ #include <QRandomGenerator>
++#include <QPointer>
+ #include <QWindow>
+
++#include <private/qgenericunixservices_p.h>
++#include <private/qguiapplication_p.h>
++#include <qpa/qplatformintegration.h>
++
+ QT_BEGIN_NAMESPACE
+
+ QDBusArgument &operator<<(QDBusArgument &arg, const QXdgDesktopPortalFileDialog::FilterCondition &filterCondition)
+@@ -80,6 +85,7 @@
+ }
+
+ WId winId = 0;
++ QPointer<QWindow> parent;
+ bool modal = false;
+ bool multipleFiles = false;
+ bool selectDirectory = false;
+@@ -149,7 +155,19 @@
+ QStringLiteral("/org/freedesktop/portal/desktop"),
+ QStringLiteral("org.freedesktop.portal.FileChooser"),
+ d->saveFile ? QStringLiteral("SaveFile") : QStringLiteral("OpenFile"));
+- QString parentWindowId = QStringLiteral("x11:") + QString::number(d->winId, 16);
++ // Wild OS: on Wayland an X11 id names no window, so the dialog came up
++ // as a window of its own, with its own taskbar button, instead of
++ // attached to the app's. Qt's platform services name the parent the way
++ // the session needs: "wayland:" and an xdg-foreign handle, or "x11:".
++ QString parentWindowId;
++ if (d->parent) {
++ if (auto services = dynamic_cast<QGenericUnixServices *>(QGuiApplicationPrivate::platformIntegration()->services())) {
++ parentWindowId = services->portalWindowIdentifier(d->parent);
++ }
++ }
++ if (parentWindowId.isEmpty()) {
++ parentWindowId = QStringLiteral("x11:") + QString::number(d->winId, 16);
++ }
+
+ QVariantMap options;
+ if (!d->acceptLabel.isEmpty())
+@@ -357,6 +375,7 @@
+
+ d->modal = windowModality != Qt::NonModal;
+ d->winId = parent ? parent->winId() : 0;
++ d->parent = parent;
+
+ if (d->nativeFileDialog && (options()->fileMode() == QFileDialogOptions::Directory || options()->fileMode() == QFileDialogOptions::DirectoryOnly))
+ return d->nativeFileDialog->show(windowFlags, windowModality, parent);
diff --git a/packages/wildos-archive/debian/changelog b/packages/wildos-archive/debian/changelog
index c7930f5..386cb57 100644
--- a/packages/wildos-archive/debian/changelog
+++ b/packages/wildos-archive/debian/changelog
@@ -1,3 +1,10 @@
+wildos-archive (0.1.3) trixie; urgency=medium
+
+ * The search box has the right-click menu with Cut, Copy, Paste and
+ Select all. The Menu key and Shift+F10 open it too.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 08:54:22 +0000
+
wildos-archive (0.1.2) trixie; urgency=medium
* Opens password-protected 7z and RAR archives, hidden file names
diff --git a/packages/wildos-archive/debian/control b/packages/wildos-archive/debian/control
index 83fab95..bdf8da4 100644
--- a/packages/wildos-archive/debian/control
+++ b/packages/wildos-archive/debian/control
@@ -20,7 +20,7 @@ Architecture: any
Depends:
${shlibs:Depends},
${misc:Depends},
- wildos-ui (>= 0.1.3),
+ wildos-ui (>= 0.1.11),
qml6-module-qtcore,
qml6-module-qtquick,
qml6-module-qtquick-controls,
diff --git a/packages/wildos-archive/qml/Main.qml b/packages/wildos-archive/qml/Main.qml
index 2595f6d..52f82d1 100644
--- a/packages/wildos-archive/qml/Main.qml
+++ b/packages/wildos-archive/qml/Main.qml
@@ -272,6 +272,16 @@ UI.AppWindow {
window.focusList();
}
Keys.onDownPressed: window.focusList()
+ Keys.onPressed: event => {
+ if (searchMenu.isMenuKey(event)) {
+ searchMenu.openAtCaret();
+ event.accepted = true;
+ }
+ }
+
+ UI.TextMenu {
+ id: searchMenu
+ }
UI.Label {
anchors.verticalCenter: parent.verticalCenter
diff --git a/packages/wildos-backup/debian/changelog b/packages/wildos-backup/debian/changelog
index 3a11072..0577486 100644
--- a/packages/wildos-backup/debian/changelog
+++ b/packages/wildos-backup/debian/changelog
@@ -1,3 +1,16 @@
+wildos-backup (0.1.3) trixie; urgency=medium
+
+ * Backup's password boxes take only what is typed: nothing can be
+ pasted into them.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 10:30:00 +0000
+
+wildos-backup (0.1.2) trixie; urgency=medium
+
+ * The backup password can be copied from a right-click menu.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 08:54:22 +0000
+
wildos-backup (0.1.1) trixie; urgency=medium
* Drives plugged in lists every drive you plug in. One Backup can't use
diff --git a/packages/wildos-backup/debian/control b/packages/wildos-backup/debian/control
index 6a1345a..004e01f 100644
--- a/packages/wildos-backup/debian/control
+++ b/packages/wildos-backup/debian/control
@@ -24,7 +24,7 @@ Depends:
restic,
udisks2,
pkexec,
- wildos-ui (>= 0.1.6),
+ wildos-ui (>= 0.1.12),
qml6-module-qtcore,
qml6-module-qtquick,
qml6-module-qtquick-controls,
diff --git a/packages/wildos-backup/qml/AskPasswordDialog.qml b/packages/wildos-backup/qml/AskPasswordDialog.qml
index 74fe15e..b16d3dc 100644
--- a/packages/wildos-backup/qml/AskPasswordDialog.qml
+++ b/packages/wildos-backup/qml/AskPasswordDialog.qml
@@ -28,6 +28,7 @@ UI.Dialog {
Layout.fillWidth: true
echoMode: TextInput.Password
revealable: true
+ UI.NoPaste {}
placeholderText: qsTr("Backup password")
error: dialog.error.length > 0
onAccepted: {
diff --git a/packages/wildos-backup/qml/PasswordDialog.qml b/packages/wildos-backup/qml/PasswordDialog.qml
index fec9b1c..e154958 100644
--- a/packages/wildos-backup/qml/PasswordDialog.qml
+++ b/packages/wildos-backup/qml/PasswordDialog.qml
@@ -45,6 +45,16 @@ UI.Dialog {
selectedTextColor: UI.Style.ink
selectionColor: UI.Style.textSelection
Accessible.name: qsTr("Backup password")
+ Keys.onPressed: event => {
+ if (passwordMenu.isMenuKey(event)) {
+ passwordMenu.openAtCaret();
+ event.accepted = true;
+ }
+ }
+
+ UI.TextMenu {
+ id: passwordMenu
+ }
}
}
diff --git a/packages/wildos-backup/qml/RestorePage.qml b/packages/wildos-backup/qml/RestorePage.qml
index 58eb6ce..c4391d6 100644
--- a/packages/wildos-backup/qml/RestorePage.qml
+++ b/packages/wildos-backup/qml/RestorePage.qml
@@ -158,6 +158,7 @@ Item {
Layout.preferredWidth: 280
echoMode: TextInput.Password
revealable: true
+ UI.NoPaste {}
placeholderText: qsTr("Backup password")
onAccepted: Restore.givePassword(text)
}
diff --git a/packages/wildos-base/debian/changelog b/packages/wildos-base/debian/changelog
index fca5b6e..76df4bf 100644
--- a/packages/wildos-base/debian/changelog
+++ b/packages/wildos-base/debian/changelog
@@ -1,3 +1,73 @@
+wildos-base (0.1.9) trixie; urgency=medium
+
+ * The guest session from Settings > Privacy and security > Advanced
+ protection: a Guest account on the sign-in screen with no password,
+ a fresh empty Home in memory each time, and everything the guest
+ left on the PC wiped when they sign out. The guest can't open other
+ accounts' files, ask for an administrator's password, use Windows
+ mode, share folders or install anything for the whole PC. Turning it
+ off removes the account.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 14:56:10 +0000
+
+wildos-base (0.1.8) trixie; urgency=medium
+
+ * Wild OS calls this release 0.1 Beta 2, and its support and problem
+ report links go to the right place on GitHub.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 14:53:57 +0000
+
+wildos-base (0.1.7) trixie; urgency=medium
+
+ * At Standard protection the kernel no longer forces Meltdown protection
+ on processors that do not have the flaw, which made opening, copying
+ and saving many files slower. Processors with the flaw still get it,
+ and Extra processor protection, Strict and Maximum still force it.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 14:17:55 +0000
+
+wildos-base (0.1.6) trixie; urgency=medium
+
+ * On a PC that also starts Windows (the installer wrote its start-up
+ menu entry), the hardware clock is kept in local time as Windows keeps
+ it, so the clock no longer starts hours off after using Windows and
+ Windows' clock is no longer put off by Wild OS. Done once, at the next
+ start-up.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 08:45:00 +0000
+
+wildos-base (0.1.5) trixie; urgency=medium
+
+ * Linux 7.2 and Mesa 26.1: newer kernel and graphics, for speed, newer
+ hardware and games. The previous kernel stays in the start-up menu.
+ * NVIDIA's driver gets the version that builds for Linux 7.2.
+ * "Wild OS (previous version)" in the start-up menu starts the last
+ kernel that reached the desktop.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 22:47:33 +0000
+
+wildos-base (0.1.4) trixie; urgency=medium
+
+ * Snappier under load: the kernel puts what you are using ahead of
+ background work sooner.
+ * When memory runs out, the app using the most is closed straight away
+ instead of the whole computer freezing.
+ * Encrypted SSDs stay fast: TRIM now reaches the drive, and disk
+ encryption works without an extra queue.
+ * The start-up image unpacks faster.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 17:15:00 +0000
+
+wildos-base (0.1.3) trixie; urgency=medium
+
+ * Faster on most processors: every processor thread runs where the
+ processor is safe for it, and protections for flaws the processor
+ doesn't have are no longer forced on. Extra processor protection in
+ Settings, and Strict and Maximum, keep the full set. Takes effect
+ after a restart.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 16:30:00 +0000
+
wildos-base (0.1.2) trixie; urgency=medium
* A Btrfs system starts from its @ subvolume, and the safe graphics
diff --git a/packages/wildos-base/debian/install b/packages/wildos-base/debian/install
index 1a54bfd..b492e9d 100644
--- a/packages/wildos-base/debian/install
+++ b/packages/wildos-base/debian/install
@@ -9,11 +9,22 @@ files/apt/wildos.sources etc/apt/sources.list.d/
files/apt/wildos-updates-keyring.asc usr/share/keyrings/
files/apt/wildos.pref etc/apt/preferences.d/
files/apt/wildos-freerdp.pref etc/apt/preferences.d/
+files/apt/wildos-newer.pref etc/apt/preferences.d/
+files/apt/wildos-nvidia.sources etc/apt/sources.list.d/
files/grub/10_wildos usr/lib/wildos/grub.d/
files/grub/31_wildos_firmware usr/lib/wildos/grub.d/
files/systemd/* usr/lib/systemd/system/
files/performance/50-wildos.conf usr/lib/systemd/zram-generator.conf.d/
files/performance/999-wildos-performance.conf usr/lib/sysctl.d/
+files/performance/wildos-mglru.conf usr/lib/tmpfiles.d/
+files/performance/90-wildos-initramfs.conf usr/lib/dracut/dracut.conf.d/
+files/libexec/crypttab-speed usr/libexec/wildos/
+files/libexec/windows-clock usr/libexec/wildos/
files/udev/60-wildos-io-scheduler.rules usr/lib/udev/rules.d/
files/oomd/wildos.conf usr/lib/systemd/system/[email protected]/
files/oomd/oomd.conf usr/lib/systemd/oomd.conf.d/
+files/guest/guest-account usr/libexec/wildos/
+files/guest/advanced-protection.d/guest usr/lib/wildos/advanced-protection.d/
+files/guest/05-wildos-guest.rules usr/share/polkit-1/rules.d/
+files/guest/50-wildos-guest.conf usr/lib/systemd/logind.conf.d/
+files/guest/skel/.config usr/share/wildos/guest-skel/
diff --git a/packages/wildos-base/debian/links b/packages/wildos-base/debian/links
index c34c483..e18886d 100644
--- a/packages/wildos-base/debian/links
+++ b/packages/wildos-base/debian/links
@@ -10,3 +10,7 @@ usr/lib/wildos/grub.d/31_wildos_firmware etc/grub.d/31_wildos_firmware
# use for it, and NFSv4 shares still mount without it, so it is masked.
dev/null etc/systemd/system/rpcbind.service
dev/null etc/systemd/system/rpcbind.socket
+
+# Turned on for every installed system; it only acts where the installer
+# found Windows on the same computer.
+usr/lib/systemd/system/wildos-windows-clock.service usr/lib/systemd/system/multi-user.target.wants/wildos-windows-clock.service
diff --git a/packages/wildos-base/debian/postinst b/packages/wildos-base/debian/postinst
index ebc0aa3..2793a01 100644
--- a/packages/wildos-base/debian/postinst
+++ b/packages/wildos-base/debian/postinst
@@ -45,6 +45,29 @@ if [ "$1" = "configure" ]; then
hand_over_unconfigured_scripts
disarm_hidden_scripts
+ # Faster encrypted SSDs and a start-up image that unpacks faster, on PCs
+ # installed before these: the start-up image carries its own crypttab
+ # and is built with the compression of its day, so it is rebuilt once.
+ # The image build has no grub.cfg and makes its own.
+ if [ -e /boot/grub/grub.cfg ]; then
+ speed=$(/usr/libexec/wildos/crypttab-speed || true)
+ if [ "$speed" = changed ] || [ ! -e /var/lib/wildos/initramfs-zstd ]; then
+ if command -v dracut >/dev/null && dracut --force --regenerate-all >/dev/null 2>&1; then
+ mkdir -p /var/lib/wildos
+ : > /var/lib/wildos/initramfs-zstd
+ else
+ echo "wildos-base: rebuilding the start-up image failed; it is rebuilt on the next update" >&2
+ fi
+ fi
+ fi
+ if [ -d /run/systemd/system ]; then
+ systemd-tmpfiles --create wildos-mglru.conf >/dev/null 2>&1 || true
+ fi
+
+ # Settings used to write the processor thread choice as its own start-up
+ # file; 40_wildos.cfg reads /etc/wildos/cpu-threads itself now.
+ rm -f /etc/default/grub.d/41_wildos_cpu_threads.cfg
+
# Installed systems pick up the new menu now. The image has no grub.cfg
# (the installer makes one), so its build skips this.
if [ -e /boot/grub/grub.cfg ] && command -v update-grub >/dev/null; then
@@ -63,6 +86,8 @@ fi
# sign in (the console group) gets it here.
if [ "$1" = "configure" ] && getent group privleap >/dev/null && getent group console >/dev/null; then
for account in $(getent group console | cut -d: -f4 | tr ',' ' '); do
+ # The guest session's account gets no more than it was made with.
+ [ "$account" != guest ] || continue
id -nG "$account" 2>/dev/null | tr ' ' '\n' | grep -qx privleap || usermod -aG privleap "$account" || true
done
fi
@@ -76,6 +101,8 @@ if [ "$1" = "configure" ] && [ -d /run/systemd/system ]; then
systemctl daemon-reload || true
systemctl start [email protected] || true
systemctl enable --now systemd-oomd.service || true
+ # The guest session's sign-out rule (50-wildos-guest.conf).
+ systemctl reload systemd-logind.service || true
elif [ "$1" = "configure" ]; then
systemctl enable systemd-oomd.service || true
fi
diff --git a/packages/wildos-base/debian/prerm b/packages/wildos-base/debian/prerm
new file mode 100644
index 0000000..6709196
--- /dev/null
+++ b/packages/wildos-base/debian/prerm
@@ -0,0 +1,10 @@
+#!/bin/sh
+set -e
+
+# Removing Wild OS's base takes the guest session with it, so its account
+# must not stay behind without the parts that wipe it.
+if [ "$1" = remove ] && [ -x /usr/libexec/wildos/guest-account ]; then
+ /usr/libexec/wildos/guest-account off || true
+fi
+
+#DEBHELPER#
diff --git a/packages/wildos-base/debian/rules b/packages/wildos-base/debian/rules
index 952cfa0..f5596d3 100644
--- a/packages/wildos-base/debian/rules
+++ b/packages/wildos-base/debian/rules
@@ -7,3 +7,7 @@
# scripts in /etc/grub.d that are executable.
execute_after_dh_fixperms:
chmod 0755 debian/wildos-base/usr/lib/wildos/grub.d/*
+ chmod 0755 debian/wildos-base/usr/libexec/wildos/crypttab-speed
+ chmod 0755 debian/wildos-base/usr/libexec/wildos/windows-clock
+ chmod 0755 debian/wildos-base/usr/libexec/wildos/guest-account
+ chmod 0755 debian/wildos-base/usr/lib/wildos/advanced-protection.d/guest
diff --git a/packages/wildos-base/files/40_wildos.cfg b/packages/wildos-base/files/40_wildos.cfg
index 729524a..2867cf9 100644
--- a/packages/wildos-base/files/40_wildos.cfg
+++ b/packages/wildos-base/files/40_wildos.cfg
@@ -16,8 +16,12 @@ GRUB_TIMEOUT_STYLE=hidden
GRUB_RECORDFAIL_TIMEOUT=5
GRUB_CMDLINE_LINUX_DEFAULT="$GRUB_CMDLINE_LINUX_DEFAULT quiet splash loglevel=3 rd.udev.log_level=3 vt.global_cursor_default=0"
-# Hyper-threading is not decided here: it stays off unless "Use every
-# processor thread" in Settings writes 41_wildos_cpu_threads.cfg.
+# Full preemption: the kernel can stop background work at almost any point to
+# run what you are clicking or typing into, instead of waiting for it to
+# offer a break (Debian's default, "voluntary"). Costs about a percent of
+# throughput; at every protection level, as it has nothing to do with
+# security.
+GRUB_CMDLINE_LINUX_DEFAULT="$GRUB_CMDLINE_LINUX_DEFAULT preempt=full"
# At Standard protection, speed over the last few percent of hardening on a
# personal PC. Strict and Maximum keep every Kicksecure option. Sorts after
@@ -42,5 +46,54 @@ strict | maximum) ;;
-e 's/ init_on_free=1//g' \
-e 's/ iommu.strict=1/ iommu.strict=0/g' \
-e 's/ kvm-intel.vmentry_l1d_flush=always/ kvm-intel.vmentry_l1d_flush=cond/g')"
+
+ # Processor flaw protections. Kicksecure forces several on whether or
+ # not the processor has the flaw, as a guard for processors too new for
+ # the kernel's lists, and keeps the second thread of every core off.
+ # Unless "Extra processor protection" is on in Settings > Privacy and
+ # security (/etc/wildos/cpu-protection), the kernel decides from its
+ # own list of affected processors instead:
+ # - spectre_v2=on also forces the cross-thread protection (STIBP) on
+ # every program; the default keeps the kernel protected and gives it
+ # to programs that ask for it.
+ # - kvm.nx_huge_pages, indirect_target_selection and vmscape go back to
+ # their defaults, which still protect processors that have the flaw.
+ # Their forced forms mostly slow Windows mode.
+ # - pti=on (with kpti=1, its Arm spelling) forces kernel page table
+ # isolation, the Meltdown protection, even on processors the kernel
+ # knows are not affected. There it only hides the kernel's layout a
+ # little better, and every system call pays for it: file-heavy work
+ # ran about 30% slower in testing. The kernel still turns it on by
+ # itself on every processor that has the flaw.
+ # - Threads: "Use every processor thread" in Settings > System > Power
+ # and battery writes /etc/wildos/cpu-threads. Until it is touched,
+ # the kernel keeps the second thread of each core off only on
+ # processors it lists as unsafe for sharing a core (the ",nosmt"
+ # options and l1tf=full), and runs every thread everywhere else. "on"
+ # runs every thread even there; l1tf=flush still clears the cache each
+ # time a virtual machine runs. "off" keeps them off everywhere.
+ if [ "$(cat /etc/wildos/cpu-protection 2>/dev/null || true)" != extra ]; then
+ GRUB_CMDLINE_LINUX="$(printf '%s\n' "$GRUB_CMDLINE_LINUX" | sed \
+ -e 's/ spectre_v2=on//g' \
+ -e 's/ kvm.nx_huge_pages=force//g' \
+ -e 's/ indirect_target_selection=force//g' \
+ -e 's/ vmscape=force//g' \
+ -e 's/ pti=on//g' \
+ -e 's/ kpti=1//g')"
+ case "$(cat /etc/wildos/cpu-threads 2>/dev/null || true)" in
+ off) ;;
+ on)
+ GRUB_CMDLINE_LINUX="$(printf '%s\n' "$GRUB_CMDLINE_LINUX" | sed \
+ -e 's/ nosmt=force//g' \
+ -e 's/,nosmt//g' \
+ -e 's/l1tf=full,force/l1tf=flush/g')"
+ ;;
+ *)
+ GRUB_CMDLINE_LINUX="$(printf '%s\n' "$GRUB_CMDLINE_LINUX" | sed \
+ -e 's/ nosmt=force//g' \
+ -e 's/l1tf=full,force/l1tf=full/g')"
+ ;;
+ esac
+ fi
;;
esac
diff --git a/packages/wildos-base/files/apt/wildos-newer.pref b/packages/wildos-base/files/apt/wildos-newer.pref
new file mode 100644
index 0000000..a4ba60b
--- /dev/null
+++ b/packages/wildos-base/files/apt/wildos-newer.pref
@@ -0,0 +1,21 @@
+# Newer kernel and graphics than Debian 13 ships, from Debian's own
+# backports: Linux 7.2 (faster scheduling, newer hardware, ntsync for games)
+# with the firmware it expects, and Mesa 26.1 (Intel and AMD graphics,
+# Vulkan for games). Same priority as trixie, so the newer version wins.
+# A src: name covers only 64-bit packages; the :i386 form adds the 32-bit
+# ones Steam uses, which must match their 64-bit versions.
+Package: src:linux src:linux-signed-amd64 src:linux-base src:firmware-nonfree src:mesa src:mesa:i386
+Pin: release n=trixie-backports
+Pin-Priority: 500
+
+# NVIDIA's driver in trixie and its backport won't build for Linux 7.2;
+# Debian's 550.163.01-6 has the fixes, so this one driver comes from
+# Debian's development branch (wildos-nvidia.sources). Kept to the 550
+# series: newer ones drop older cards. Nothing else comes from there.
+Package: src:nvidia-graphics-drivers src:nvidia-graphics-drivers:i386
+Pin: version 550.163.01-*
+Pin-Priority: 500
+
+Package: *
+Pin: release n=sid
+Pin-Priority: -1
diff --git a/packages/wildos-base/files/apt/wildos-nvidia.sources b/packages/wildos-base/files/apt/wildos-nvidia.sources
new file mode 100644
index 0000000..99514f9
--- /dev/null
+++ b/packages/wildos-base/files/apt/wildos-nvidia.sources
@@ -0,0 +1,9 @@
+# Only for NVIDIA's driver (see /etc/apt/preferences.d/wildos-newer.pref,
+# which keeps everything else here from installing). The non-free parts
+# only, so checking for updates fetches a small list.
+Types: deb
+URIs: tor+https://deb.debian.org/debian
+Suites: sid
+Components: non-free non-free-firmware
+Architectures: amd64 i386
+Signed-By: /usr/share/keyrings/debian-archive-keyring.gpg
diff --git a/packages/wildos-base/files/grub/10_wildos b/packages/wildos-base/files/grub/10_wildos
index f6a5368..e2ec307 100644
--- a/packages/wildos-base/files/grub/10_wildos
+++ b/packages/wildos-base/files/grub/10_wildos
@@ -97,6 +97,14 @@ entry "Wild OS" wildos "gnulinux-simple-$device_id" "$args"
entry "Wild OS (safe graphics)" wildos-safe-graphics "wildos-safe-graphics-$device_id" "$args nomodeset \${wildos_safe}"
previous=$(echo "$kernels" | sed -n 2p)
+# After a new kernel failed to reach the desktop, the PC starts this entry
+# (wildos-recovery's 15_wildos_recovery). Point it at the last kernel that
+# did, when that is still installed, rather than simply the second newest,
+# which after a further update could be the one that failed.
+ok=$(grub-editenv /boot/grub/grubenv list 2>/dev/null | sed -n 's/^wildos_kernel_ok=//p')
+if [ -n "$ok" ] && [ "/boot/vmlinuz-$ok" != "$(echo "$kernels" | sed -n 1p)" ] && grub_file_is_not_garbage "/boot/vmlinuz-$ok"; then
+ previous=/boot/vmlinuz-$ok
+fi
if [ -n "$previous" ]; then
use_kernel "$previous"
# The way back when an update leaves Wild OS unable to start. The id
diff --git a/packages/wildos-base/files/guest/05-wildos-guest.rules b/packages/wildos-base/files/guest/05-wildos-guest.rules
new file mode 100644
index 0000000..a051c69
--- /dev/null
+++ b/packages/wildos-base/files/guest/05-wildos-guest.rules
@@ -0,0 +1,38 @@
+// The guest session (guest-account): the guest may sign out, shut down,
+// use Wi-Fi and the networks already set up, and plug in a USB stick, and
+// nothing else that asks the system. Everything else is refused outright,
+// so no administrator password prompt even comes up. Being a list of what
+// is allowed, anything added to Wild OS later is refused for the guest too.
+polkit.addRule(function(action, subject) {
+ if (subject.user !== "guest") {
+ return polkit.Result.NOT_HANDLED;
+ }
+ var id = action.id;
+ var allowed = [
+ // KWin needs it to take the screen for the guest's own session.
+ "org.freedesktop.login1.chvt",
+ "org.freedesktop.login1.power-off",
+ "org.freedesktop.login1.reboot",
+ "org.freedesktop.login1.suspend",
+ "org.freedesktop.login1.hibernate",
+ "org.freedesktop.login1.lock-sessions",
+ "org.freedesktop.login1.set-reboot-to-firmware-setup",
+ "org.freedesktop.udisks2.filesystem-mount",
+ "org.freedesktop.udisks2.encrypted-unlock",
+ "org.freedesktop.udisks2.eject-media",
+ "org.freedesktop.udisks2.power-off-drive",
+ "org.freedesktop.NetworkManager.network-control",
+ "org.freedesktop.NetworkManager.enable-disable-network",
+ "org.freedesktop.NetworkManager.enable-disable-wifi",
+ "org.freedesktop.NetworkManager.enable-disable-wwan",
+ "org.freedesktop.NetworkManager.wifi.scan",
+ "org.freedesktop.NetworkManager.settings.modify.own",
+ "org.freedesktop.RealtimeKit1.acquire-high-priority",
+ "org.freedesktop.RealtimeKit1.acquire-real-time"
+ ];
+ if (allowed.indexOf(id) >= 0 || id.indexOf("org.freedesktop.login1.inhibit-") === 0
+ || id.indexOf("org.freedesktop.UPower.") === 0 || id.indexOf("org.kde.powerdevil.") === 0) {
+ return polkit.Result.NOT_HANDLED;
+ }
+ return polkit.Result.NO;
+});
diff --git a/packages/wildos-base/files/guest/50-wildos-guest.conf b/packages/wildos-base/files/guest/50-wildos-guest.conf
new file mode 100644
index 0000000..f56ef2c
--- /dev/null
+++ b/packages/wildos-base/files/guest/50-wildos-guest.conf
@@ -0,0 +1,6 @@
+# The guest session (guest-account): when the guest signs out, every process
+# they started ends with it, so nothing keeps running for the next person
+# and their Home can be wiped. Everyone else's processes are left alone.
+[Login]
+KillUserProcesses=yes
+KillOnlyUsers=guest
diff --git a/packages/wildos-base/files/guest/advanced-protection.d/guest b/packages/wildos-base/files/guest/advanced-protection.d/guest
new file mode 100644
index 0000000..b7f22c7
--- /dev/null
+++ b/packages/wildos-base/files/guest/advanced-protection.d/guest
@@ -0,0 +1,8 @@
+#!/bin/sh
+# Advanced protection: Guest session (guest). Run as root by
+# advanced-protection-apply with the new value: on makes the guest account,
+# off signs any guest out and removes it.
+case "${1:-}" in
+ on|off) exec /usr/libexec/wildos/guest-account "$1" ;;
+ *) echo "usage: guest on|off" >&2; exit 2 ;;
+esac
diff --git a/packages/wildos-base/files/guest/guest-account b/packages/wildos-base/files/guest/guest-account
new file mode 100644
index 0000000..e40bef0
--- /dev/null
+++ b/packages/wildos-base/files/guest/guest-account
@@ -0,0 +1,156 @@
+#!/bin/sh
+# The guest session (Settings > Privacy and security > Advanced protection >
+# Guest session): an account called guest, offered on the sign-in screen
+# without a password, whose Home is an empty folder in memory for each
+# visit, gone at sign-out with everything it left elsewhere on the PC.
+#
+# on make the account
+# off sign the guest out if they are in, then remove the account
+# start (user-runtime-dir@UID, as the guest signs in) a fresh Home
+# stop (user-runtime-dir@UID, after the last guest process ended)
+# Home and the rest wiped
+#
+# What the guest can't do: open other accounts' files (other homes lose any
+# access for others here), use sudo or give an administrator's password
+# (no admin groups; 05-wildos-guest.rules refuses every system request
+# beyond signing out, Wi-Fi and plugging in a USB stick), use Windows mode,
+# share folders on the network, or install anything system-wide. logind
+# ends every guest process at sign-out (50-wildos-guest.conf), so nothing
+# keeps running to see the next visitor.
+#
+# Every failure ends with one plain sentence on stderr.
+
+set -eu
+
+NAME=guest
+HOME_DIR=/home/guest
+MARK=/etc/wildos/guest-account
+SKEL=/usr/share/wildos/guest-skel
+DROPIN_NAME=50-wildos-guest.conf
+GROUPS_WANTED="console audio video"
+
+fail() {
+ echo "$1" >&2
+ exit "${2:-1}"
+}
+
+ours() {
+ [ -f "$MARK" ] && getent passwd "$NAME" >/dev/null &&
+ [ "$(getent passwd "$NAME" | cut -d: -f3)" = "$(cat "$MARK")" ]
+}
+
+dropin_dir() {
+ echo "/etc/systemd/system/user-runtime-dir@$1.service.d"
+}
+
+wipe_leftovers() {
+ uid=$1
+ # Files the guest left outside Home: shared temporary folders, shared
+ # memory, mail, scheduled jobs, lingering, crash dumps and the guest's
+ # own journal.
+ for dir in /tmp /var/tmp /dev/shm; do
+ find "$dir" -xdev -mindepth 1 -user "$uid" -delete 2>/dev/null || true
+ done
+ rm -f "/var/mail/$NAME" "/var/spool/cron/crontabs/$NAME" "/var/lib/systemd/linger/$NAME"
+ find /var/spool/cron/atjobs -user "$uid" -delete 2>/dev/null || true
+ find /var/lib/systemd/coredump -name "core.*.$uid.*" -delete 2>/dev/null || true
+ journalctl --rotate >/dev/null 2>&1 || true
+ find /var/log/journal /run/log/journal -name "user-$uid.journal*" -delete 2>/dev/null || true
+ find /var/log/journal /run/log/journal -name "user-$uid@*" -delete 2>/dev/null || true
+ # Wi-Fi networks the guest added for themselves only (their passwords
+ # included) are stored system-wide by NetworkManager.
+ if command -v nmcli >/dev/null 2>&1; then
+ nmcli -t -f UUID connection show 2>/dev/null | while read -r uuid; do
+ if nmcli -g connection.permissions connection show "$uuid" 2>/dev/null | tr ',' '\n' | grep -qx "user:$NAME"; then
+ nmcli connection delete "$uuid" >/dev/null 2>&1 || true
+ fi
+ done
+ fi
+}
+
+case "${1:-}" in
+ on)
+ if getent passwd "$NAME" >/dev/null; then
+ ours && exit 0
+ fail "An account called guest already exists, so the guest session can't use that name."
+ fi
+ getent group console >/dev/null || fail "Wild OS is missing the console group, so a guest could not sign in."
+ groups=""
+ for g in $GROUPS_WANTED; do
+ if getent group "$g" >/dev/null; then groups="$groups,$g"; fi
+ done
+ useradd --no-create-home --home-dir "$HOME_DIR" --shell /bin/bash --comment Guest \
+ --user-group --groups "${groups#,}" "$NAME" || fail "The guest account could not be made."
+ uid=$(id -u "$NAME")
+ # No password. The sign-in screen shows an account as passwordless
+ # only when its passwd entry, not just its shadow one, is empty.
+ passwd --delete "$NAME" >/dev/null
+ sed -i "s/^$NAME:x:/$NAME::/" /etc/passwd
+ mkdir -p "$(dirname "$MARK")"
+ echo "$uid" > "$MARK"
+ # The empty folder Home is mounted over. Only root can write to it,
+ # so nothing lands on the disk when no guest is in.
+ mkdir -p "$HOME_DIR"
+ chown root:root "$HOME_DIR"
+ chmod 0755 "$HOME_DIR"
+ mkdir -p "$(dropin_dir "$uid")"
+ cat > "$(dropin_dir "$uid")/$DROPIN_NAME" <<EOF
+# The guest session (wildos-base guest-account): a fresh Home in memory as
+# the guest signs in, and everything wiped once their last process is gone.
+[Service]
+ExecStartPre=/usr/libexec/wildos/guest-account start
+ExecStopPost=/usr/libexec/wildos/guest-account stop
+EOF
+ # Homes of people are only theirs: drop any access others have.
+ getent passwd | while IFS=: read -r user _ id _ _ home shell; do
+ if [ "$id" -ge 1000 ] && [ "$id" -lt 60000 ] && [ "$user" != "$NAME" ] && [ -d "$home" ] &&
+ [ "${home#/home/}" != "$home" ]; then
+ chmod o-rwx "$home"
+ fi
+ done
+ systemctl daemon-reload
+ ;;
+ off)
+ getent passwd "$NAME" >/dev/null || { rm -f "$MARK"; exit 0; }
+ ours || fail "The account called guest isn't the guest session's, so it was left alone."
+ uid=$(id -u "$NAME")
+ if loginctl show-user "$uid" >/dev/null 2>&1; then
+ loginctl terminate-user "$uid" 2>/dev/null || true
+ for _ in $(seq 1 20); do
+ systemctl is-active --quiet "user-runtime-dir@$uid.service" || break
+ sleep 0.5
+ done
+ fi
+ pkill -KILL -u "$uid" 2>/dev/null || true
+ if mountpoint -q "$HOME_DIR"; then umount -l "$HOME_DIR"; fi
+ wipe_leftovers "$uid"
+ userdel "$NAME" 2>/dev/null || [ $? -eq 12 ] || fail "The guest account could not be removed."
+ getent group "$NAME" >/dev/null && groupdel "$NAME" 2>/dev/null || true
+ rm -f "/var/lib/AccountsService/users/$NAME" "/var/lib/AccountsService/icons/$NAME"
+ rmdir "$HOME_DIR" 2>/dev/null || true
+ rm -rf "$(dropin_dir "$uid")"
+ rm -f "$MARK"
+ systemctl daemon-reload
+ ;;
+ start)
+ ours || fail "There is no guest account."
+ uid=$(id -u "$NAME")
+ gid=$(id -g "$NAME")
+ if mountpoint -q "$HOME_DIR"; then umount -l "$HOME_DIR"; fi
+ mount -t tmpfs -o "size=50%,mode=0700,uid=$uid,gid=$gid,nosuid,nodev" wildos-guest "$HOME_DIR"
+ cp -a /etc/skel/. "$HOME_DIR/"
+ if [ -d "$SKEL" ]; then cp -a "$SKEL/." "$HOME_DIR/"; fi
+ chown -R "$uid:$gid" "$HOME_DIR"
+ ;;
+ stop)
+ ours || exit 0
+ uid=$(id -u "$NAME")
+ pkill -KILL -u "$uid" 2>/dev/null || true
+ if mountpoint -q "$HOME_DIR"; then umount "$HOME_DIR" 2>/dev/null || umount -l "$HOME_DIR"; fi
+ wipe_leftovers "$uid"
+ ;;
+ *)
+ echo "usage: guest-account on|off|start|stop" >&2
+ exit 2
+ ;;
+esac
diff --git a/packages/wildos-base/files/guest/skel/.config/kscreenlockerrc b/packages/wildos-base/files/guest/skel/.config/kscreenlockerrc
new file mode 100644
index 0000000..12e90df
--- /dev/null
+++ b/packages/wildos-base/files/guest/skel/.config/kscreenlockerrc
@@ -0,0 +1,5 @@
+# A guest session has no password to unlock with, and nothing of its own to
+# protect from the next person, so it never locks by itself.
+[Daemon]
+Autolock=false
+LockOnResume=false
diff --git a/packages/wildos-base/files/guest/skel/.config/wildos-welcomerc b/packages/wildos-base/files/guest/skel/.config/wildos-welcomerc
new file mode 100644
index 0000000..498afdc
--- /dev/null
+++ b/packages/wildos-base/files/guest/skel/.config/wildos-welcomerc
@@ -0,0 +1,2 @@
+[General]
+ShowWelcome=false
diff --git a/packages/wildos-base/files/libexec/crypttab-speed b/packages/wildos-base/files/libexec/crypttab-speed
new file mode 100644
index 0000000..552a3e0
--- /dev/null
+++ b/packages/wildos-base/files/libexec/crypttab-speed
@@ -0,0 +1,49 @@
+#!/bin/sh
+# Adds the encrypted disk options that keep SSDs fast to every entry in
+# /etc/crypttab, and says "changed" when it edits the file, so the caller can
+# rebuild the start-up image, which carries its own copy.
+#
+# - discard: lets TRIM through the encryption, so the drive knows which
+# blocks are free and its writes stay fast. Calamares clears the options
+# of the system partition when /boot is not encrypted, which is Wild OS's
+# layout, so installs before this had none. TRIM shows an observer of the
+# raw disk which blocks are unused, not what is in them.
+# - no-read-workqueue, no-write-workqueue: decrypt and encrypt straight
+# away instead of queueing the work for a kernel thread, which only adds
+# delay on a fast drive.
+#
+# crypttab-speed [ROOT] ROOT defaults to /
+
+set -eu
+
+root=${1:-}
+file="$root/etc/crypttab"
+[ -f "$file" ] || exit 0
+want="discard no-read-workqueue no-write-workqueue"
+
+tmp=$(mktemp)
+awk -v want="$want" '
+ /^[[:space:]]*(#|$)/ { print; next }
+ {
+ opts = (NF >= 4) ? $4 : ""
+ if (opts == "none" || opts == "-") opts = ""
+ n = split(want, w, " ")
+ for (i = 1; i <= n; i++) {
+ if (("," opts ",") !~ ("," w[i] ",")) opts = (opts == "" ? w[i] : opts "," w[i])
+ }
+ key = (NF >= 3) ? $3 : "none"
+ line = $1 " " $2 " " key " " opts
+ if (line != $0) changed = 1
+ print line
+ }
+ END { if (changed) print "changed" > "/dev/stderr" }
+' "$file" > "$tmp" 2> "$tmp.changed"
+
+if grep -q changed "$tmp.changed"; then
+ chmod --reference="$file" "$tmp"
+ mv -f "$tmp" "$file"
+ echo changed
+else
+ rm -f "$tmp"
+fi
+rm -f "$tmp.changed"
diff --git a/packages/wildos-base/files/libexec/windows-clock b/packages/wildos-base/files/libexec/windows-clock
new file mode 100644
index 0000000..1e82136
--- /dev/null
+++ b/packages/wildos-base/files/libexec/windows-clock
@@ -0,0 +1,28 @@
+#!/bin/sh
+# Windows keeps the computer's hardware clock in local time; Linux reads it
+# as UTC. On a PC that also starts Windows the clock came up off by the time
+# zone's offset (8 hours in California) after every Windows session, so
+# updates failed until sdwdate set the clock through Tor minutes later, and
+# sdwdate then wrote UTC back, which put Windows' clock off in turn. Keeping
+# the hardware clock in local time, as Windows does, keeps both right.
+#
+# Done once, so someone who sets it back to UTC (timedatectl set-local-rtc 0)
+# keeps their choice. The clock of this start-up is left alone: whether the
+# hardware clock holds UTC or local time now depends on which system ran
+# last, and sdwdate sets it either way, then writes local time from here on.
+set -e
+
+marker=/var/lib/wildos/windows-clock
+
+if [ "$(sed -n 3p /etc/adjtime 2>/dev/null)" ]; then
+ sed -i '3s/.*/LOCAL/' /etc/adjtime
+else
+ # No file, or one without the mode line: hwclock's defaults for the
+ # drift lines it would write itself.
+ drift=$(sed -n 1p /etc/adjtime 2>/dev/null || true)
+ last=$(sed -n 2p /etc/adjtime 2>/dev/null || true)
+ printf '%s\n%s\nLOCAL\n' "${drift:-0.0 0 0.0}" "${last:-0}" > /etc/adjtime
+fi
+
+mkdir -p "${marker%/*}"
+: > "$marker"
diff --git a/packages/wildos-base/files/os-release b/packages/wildos-base/files/os-release
index 2d95511..249ebe5 100644
--- a/packages/wildos-base/files/os-release
+++ b/packages/wildos-base/files/os-release
@@ -1,12 +1,12 @@
-PRETTY_NAME="Wild OS 0.1 Alpha 2"
+PRETTY_NAME="Wild OS 0.1 Beta 2"
NAME="Wild OS"
VERSION_ID="0.1"
-VERSION="0.1 Alpha 2"
+VERSION="0.1 Beta 2"
VERSION_CODENAME=trixie
DEBIAN_CODENAME=trixie
ID=wildos
ID_LIKE=debian
HOME_URL="https://wildos.io"
-SUPPORT_URL="https://github.com/wildos-io/wildos/discussions"
-BUG_REPORT_URL="https://github.com/wildos-io/wildos/issues"
+SUPPORT_URL="https://github.com/wildorigins/wildos/discussions"
+BUG_REPORT_URL="https://github.com/wildorigins/wildos/issues"
LOGO=wildos
diff --git a/packages/wildos-base/files/performance/90-wildos-initramfs.conf b/packages/wildos-base/files/performance/90-wildos-initramfs.conf
new file mode 100644
index 0000000..fac5c1b
--- /dev/null
+++ b/packages/wildos-base/files/performance/90-wildos-initramfs.conf
@@ -0,0 +1,4 @@
+# The start-up image unpacks several times faster with zstd than with the xz
+# that dist-base-files (60-dist-base-files.conf) asks for, at a little more
+# size on /boot.
+compress="zstd"
diff --git a/packages/wildos-base/files/performance/wildos-mglru.conf b/packages/wildos-base/files/performance/wildos-mglru.conf
new file mode 100644
index 0000000..ca71cee
--- /dev/null
+++ b/packages/wildos-base/files/performance/wildos-mglru.conf
@@ -0,0 +1,7 @@
+# When memory runs out, the kernel never evicts pages used in the last
+# second. Without this it can keep throwing out and reloading the app in
+# use, which freezes the whole computer until systemd-oomd steps in after
+# 20 seconds; with it, the kernel closes the largest app at once instead.
+# 1000 ms is the value the kernel documentation suggests for removing lags
+# a person would notice (Documentation/admin-guide/mm/multigen_lru.rst).
+w- /sys/kernel/mm/lru_gen/min_ttl_ms - - - - 1000
diff --git a/packages/wildos-base/files/systemd/wildos-windows-clock.service b/packages/wildos-base/files/systemd/wildos-windows-clock.service
new file mode 100644
index 0000000..32cad2f
--- /dev/null
+++ b/packages/wildos-base/files/systemd/wildos-windows-clock.service
@@ -0,0 +1,15 @@
+[Unit]
+Description=Keep the hardware clock in local time, as Windows does
+# The installer writes this start-up menu entry only when Windows is on the
+# same computer.
+ConditionPathExists=/etc/grub.d/30_windows
+ConditionPathExists=!/var/lib/wildos/windows-clock
+# Before sdwdate's first setting, which writes the hardware clock.
+Before=sdwdate.service
+
+[Service]
+Type=oneshot
+ExecStart=/usr/libexec/wildos/windows-clock
+
+[Install]
+WantedBy=multi-user.target
diff --git a/packages/wildos-branding/debian/changelog b/packages/wildos-branding/debian/changelog
index 1078295..675f850 100644
--- a/packages/wildos-branding/debian/changelog
+++ b/packages/wildos-branding/debian/changelog
@@ -1,3 +1,269 @@
+wildos-branding (0.1.64) trixie; urgency=medium
+
+ * The Updates icon is on the taskbar again when updates are waiting or
+ one failed, with its dot, not only while they install.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 16:00:00 +0000
+
+wildos-branding (0.1.63) trixie; urgency=medium
+
+ * A USB device plugged into a locked PC is asked about once you sign
+ in, not behind the lock screen.
+ * The sign-in screen only offers the fingerprint when it would be
+ accepted.
+ * A light on the taskbar, left of the shield, whenever any app uses the
+ microphone (amber) or the camera (green), sandboxed or not. Clicking it
+ shows which app and since when, with Stop to cut it off, which app used
+ the other one last, and a switch for each that blocks it for every app.
+ Each use is noted in Settings > System > History.
+ * The Updates icon is only on the taskbar while an update downloads or
+ installs, as the two-arrow icon, and only turns while the work is under
+ way.
+ * Notifications that arrive while the screen is locked now show on the
+ lock screen. With "Quiet lock screen" on, as it is to begin with, only
+ the apps and how many arrived; turned off, the title and text too.
+ * Panic key, in Advanced protection: with it on, Ctrl+Alt+End locks the
+ screen, clears the clipboard, its history and pinned items, and cuts
+ the network and Bluetooth in one press. After unlocking, a
+ notification offers to turn them back on.
+ * With the guest session on, Guest is one of the accounts on the
+ sign-in screen. It signs in without a password and says the desktop
+ is wiped at sign-out. The screen still opens on the PC's own people
+ after a guest was the last to sign in.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 14:56:10 +0000
+
+wildos-branding (0.1.62) trixie; urgency=medium
+
+ * The start-up animation flies through the W onto your desktop, taskbar
+ and icons included, plays a little faster and ends as it lands. It
+ loads its picture at screen size, so it starts sooner and uses less
+ memory.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 13:52:18 +0000
+
+wildos-branding (0.1.61) trixie; urgency=medium
+
+ * Updating from an older Wild OS no longer stops to ask about the
+ taskbar's app rules or leaves them out, which showed some apps with
+ the wrong icon.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 11:00:00 +0000
+
+wildos-branding (0.1.60) trixie; urgency=medium
+
+ * The Wi-Fi password box in quick settings takes only what is typed:
+ nothing can be pasted into it.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 10:30:00 +0000
+
+wildos-branding (0.1.59) trixie; urgency=medium
+
+ * The sign-in and lock screen password boxes take only what is typed:
+ nothing can be pasted into them.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 09:45:00 +0000
+
+wildos-branding (0.1.58) trixie; urgency=medium
+
+ * The sign-in and lock screen password boxes have no right-click menu
+ again, as in Windows. Ctrl+V still pastes.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 09:30:00 +0000
+
+wildos-branding (0.1.57) trixie; urgency=medium
+
+ * The sign-in and lock screen password boxes have a right-click menu
+ with Paste, and the Menu key or Shift+F10 opens it.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 09:04:45 +0000
+
+wildos-branding (0.1.56) trixie; urgency=medium
+
+ * The taskbar's Updates icon waits for sdwdate to set a clock that is
+ hours behind before it reports a failed check, and then says how far
+ behind the clock is, as Settings > Updates does.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 08:33:55 +0000
+
+wildos-branding (0.1.55) trixie; urgency=medium
+
+ * Double-clicking a window's top or bottom edge stretches it to the full
+ height of the screen, and its left or right edge to the full width, as
+ in Windows. Double-click again to put it back.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 08:45:00 +0000
+
+wildos-branding (0.1.54) trixie; urgency=medium
+
+ * The keyboard light is on at every start-up. It stayed off when the lid
+ closing or the screen going idle had turned it off just before the
+ last shut down. A lower step you picked is still kept.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 08:30:00 +0000
+
+wildos-branding (0.1.53) trixie; urgency=medium
+
+ * KWin's Blend Changes is off; wildos-shell's colour change fade takes
+ its place.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 08:20:00 +0000
+
+wildos-branding (0.1.52) trixie; urgency=medium
+
+ * The taskbar shows LM Studio's own icon, and an app Wild OS can't
+ match to a Start entry gets the Wild OS mark instead of a plain W.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 08:10:00 +0000
+
+wildos-branding (0.1.51) trixie; urgency=medium
+
+ * Pointing at an app on the taskbar no longer sometimes shows a thin
+ empty bar instead of the window preview. It happened after the app
+ briefly hid or replaced its window while its preview was up, as
+ Report a problem does when it opens a picture, and stayed until you
+ pointed at an app with a different number of windows.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 22:50:00 +0000
+
+wildos-branding (0.1.50) trixie; urgency=medium
+
+ * The Updates icon on the taskbar no longer says it could not check
+ right after start-up: while the connection, Tor or the clock is still
+ settling it tries again quietly for about three minutes, as Settings >
+ Updates does. When a check really fails it gives the same reason as
+ Settings, and Debian and Kicksecure sources reached through Tor are no
+ longer taken for other software's.
+ * The Updates icon and Settings > Updates share one check and always
+ show the same state: a check started in either shows in both.
+ * With no connection at all, once start-up has settled, the check says
+ so at once instead of waiting minutes on Tor.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 19:23:03 +0000
+
+wildos-branding (0.1.49) trixie; urgency=medium
+
+ * The security shield lists "Firewall is off" with Turn on while the
+ firewall is off, so it stays amber until it's back on.
+ * Searching Start for "firewall" finds Settings > Privacy and security >
+ Firewall.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 19:01:35 +0000
+
+wildos-branding (0.1.48) trixie; urgency=medium
+
+ * End task is no longer in an app's right-click menu on the taskbar
+ unless it is turned on in Settings > Personalisation > Taskbar, as on
+ Windows 11. Close window, which lets an app ask to save, is always
+ there.
+ * Searching Start for "end task", "kill" or "force close" finds the
+ Taskbar settings.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 18:44:54 +0000
+
+wildos-branding (0.1.47) trixie; urgency=medium
+
+ * A pinned app no longer pulses on the taskbar after you close it. Its
+ starting line also stops as soon as the app has a window, even when
+ that window shows under another button.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 19:00:00 +0000
+
+wildos-branding (0.1.46) trixie; urgency=medium
+
+ * Start opens smoothly the first time after signing in.
+ * The battery icon shows the bolt whenever the charger is in, also when
+ the battery is full.
+ * Built-in devices such as Bluetooth are never held back by Block new
+ USB devices when they reset themselves after start-up.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 18:30:00 +0000
+
+wildos-branding (0.1.45) trixie; urgency=medium
+
+ * The sign-in screen uses your own pointer from Settings too. It gets a
+ checked copy, as the sign-in screen can't read your home folder.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 18:17:04 +0000
+
+wildos-branding (0.1.44) trixie; urgency=medium
+
+ * Closing the lid when it is set to shut down shuts the PC down. It used
+ to go to sleep halfway through instead, and woke to a black screen.
+ * A shutdown started by the lid or the power button is no longer called
+ off by an app asking about unsaved changes: after 15 seconds it shuts
+ down anyway, and the next sign-in says which apps were closed.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 17:48:54 +0000
+
+wildos-branding (0.1.43) trixie; urgency=medium
+
+ * The taskbar uses far less processor time when nothing is happening:
+ the USB watcher no longer rescans every device each second, the
+ Windows mode item asks Windows mode directly instead of starting a
+ program every ten seconds, and the updates icon checks every two
+ minutes.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 18:05:00 +0000
+
+wildos-branding (0.1.42) trixie; urgency=medium
+
+ * The keyboard light comes on at start-up, so the disk unlock password is
+ no longer typed in the dark, and stays at the level it was last left at
+ once you sign in.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 17:24:05 +0000
+
+wildos-branding (0.1.41) trixie; urgency=medium
+
+ * The mouse pointer is white with a dark edge by default, as on Windows,
+ on the desktop, the sign-in screen and in every app. Settings >
+ Accessibility > Pointer colour still changes it.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 17:30:00 +0000
+
+wildos-branding (0.1.40) trixie; urgency=medium
+
+ * Start finds Settings > System > History and Devices when you search for
+ them.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 15:39:43 +0000
+
+wildos-branding (0.1.39) trixie; urgency=medium
+
+ * The list of recently opened files is kept for 3 months instead of
+ forever, unless you chose otherwise in Activity history.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 16:20:00 +0000
+
+wildos-branding (0.1.38) trixie; urgency=medium
+
+ * Uninstall in Start works for Wild OS's own apps and Windows apps,
+ and is never offered for parts of Wild OS that can't be removed.
+ * A taskbar pin for an app that was uninstalled no longer shows as a
+ blank button, and comes back if the app is reinstalled.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 13:36:51 +0000
+
+wildos-branding (0.1.37) trixie; urgency=medium
+
+ * Pin to taskbar from Start search or the pinned grid pins the app
+ itself, and taskbar pins left blank by it before are repaired.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 10:21:27 +0000
+
+wildos-branding (0.1.36) trixie; urgency=medium
+
+ * Uninstall in Start works for apps installed in the home folder.
+
+ -- Wild OS Developers <[email protected]> Thu, 12 Nov 2026 21:30:51 +0000
+
+wildos-branding (0.1.35) trixie; urgency=medium
+
+ * Plugging in ends battery saver and returns the PC to balanced.
+
+ -- Wild OS Developers <[email protected]> Thu, 12 Nov 2026 21:07:25 +0000
+
wildos-branding (0.1.34) trixie; urgency=medium
* Start search results show each app's own icon again, not a
diff --git a/packages/wildos-branding/debian/control b/packages/wildos-branding/debian/control
index 5b1796d..e9215c6 100644
--- a/packages/wildos-branding/debian/control
+++ b/packages/wildos-branding/debian/control
@@ -11,7 +11,7 @@ Architecture: all
Depends:
${misc:Depends},
wildos-fonts,
- wildos-ui (>= 0.1.3),
+ wildos-ui (>= 0.1.12),
wildos-overlays,
wildos-desktop-view,
wildos-fluent-icons,
@@ -39,6 +39,7 @@ Depends:
qml6-module-qtquick-window,
qml6-module-qtquick-shapes,
qml6-module-qtqml,
+ qml6-module-qtcore,
qml6-module-qtqml-workerscript,
qml6-module-qt-labs-folderlistmodel,
qml6-module-org-kde-kirigami,
@@ -58,6 +59,8 @@ Depends:
qml6-module-org-kde-kitemmodels,
qml6-module-org-kde-plasma-plasma5support,
qml6-module-org-kde-pipewire,
+ pipewire-bin,
+ wireplumber,
procps,
libkf6config-bin,
dbus-bin,
diff --git a/packages/wildos-branding/debian/install b/packages/wildos-branding/debian/install
index 6238610..cabf6bf 100644
--- a/packages/wildos-branding/debian/install
+++ b/packages/wildos-branding/debian/install
@@ -9,6 +9,9 @@ files/plymouth/wildos/* usr/share/plymouth/themes/wildos/
files/icons/WildOS/* usr/share/icons/WildOS/
files/icons/WildOS-dark/* usr/share/icons/WildOS-dark/
files/dracut/* etc/dracut.conf.d/
+files/dracut-modules/* usr/lib/dracut/modules.d/
+files/udev/* usr/lib/udev/rules.d/
+files/usbguard/40-wildos-built-in.conf etc/usbguard/rules.d/
files/systemd/* usr/lib/systemd/system/
files/systemd-user/* usr/lib/systemd/user/
files/sddm.conf.d/* etc/sddm.conf.d/
@@ -16,6 +19,8 @@ files/sddm/wildos/* usr/share/sddm/themes/wildos/
files/lockscreen-shim/LockScreen.qml usr/share/plasma/shells/org.kde.plasma.desktop/contents/lockscreen/
files/kwin/tabbox/* usr/share/kwin/tabbox/
files/kwin/effects/* usr/share/kwin/effects/
+files/kwin/scripts/* usr/share/kwin/scripts/
+files/advanced-protection.d/* usr/lib/wildos/advanced-protection.d/
files/kvantum/WildOS/* usr/share/Kvantum/WildOS/
files/kvantum/WildOSLight/* usr/share/Kvantum/WildOSLight/
files/kvantum/WildOSOffice/* usr/share/Kvantum/WildOSOffice/
@@ -28,3 +33,5 @@ files/grub/45_wildos_theme.cfg etc/default/grub.d/
files/pam-configs/* usr/share/pam-configs/
files/sounds/wildos usr/share/sounds/
icons/apps/fluent-ui-system-icons.txt usr/share/wildos-branding/licences/
+files/cursor/white.theme usr/share/wildos/cursor/
+files/xdg-share/taskmanagerrulesrc usr/share/wildos/xdg/
diff --git a/packages/wildos-branding/debian/links b/packages/wildos-branding/debian/links
index db3c9cd..5f3632e 100644
--- a/packages/wildos-branding/debian/links
+++ b/packages/wildos-branding/debian/links
@@ -8,3 +8,9 @@ usr/share/icons/WildOS/16x16 usr/share/icons/WildOS-dark/16x16
usr/share/icons/WildOS/scalable usr/share/icons/WildOS-dark/scalable
usr/share/icons/Fluent-yellow/scalable/places/user-trash.svg usr/share/icons/WildOS/scalable/places/user-trash.svg
usr/share/icons/Fluent-yellow/scalable/places/user-trash-full.svg usr/share/icons/WildOS/scalable/places/user-trash-full.svg
+usr/lib/systemd/user/wildos-shutdown-guard.service usr/lib/systemd/user/default.target.wants/wildos-shutdown-guard.service
+usr/lib/systemd/user/wildos-shutdown-notice.service usr/lib/systemd/user/plasma-ksplash-ready.service.wants/wildos-shutdown-notice.service
+usr/share/wildos/xdg/taskmanagerrulesrc etc/xdg/taskmanagerrulesrc
+usr/lib/systemd/user/wildos-camera-mic.service usr/lib/systemd/user/graphical-session.target.wants/wildos-camera-mic.service
+usr/lib/systemd/user/wildos-panic-key.service usr/lib/systemd/user/plasma-workspace.target.wants/wildos-panic-key.service
+usr/lib/systemd/user/wildos-panic-key.path usr/lib/systemd/user/plasma-workspace.target.wants/wildos-panic-key.path
diff --git a/packages/wildos-branding/debian/postinst b/packages/wildos-branding/debian/postinst
index 4483e78..9b202f1 100644
--- a/packages/wildos-branding/debian/postinst
+++ b/packages/wildos-branding/debian/postinst
@@ -2,6 +2,12 @@
set -e
if [ "$1" = "configure" ]; then
+ # 0.1.52 to 0.1.60 shipped the taskbar's app rules as a conffile at the
+ # path diverted from Plasma, and an upgrade that kept the old conffiles
+ # left the new copy as .dpkg-dist with no rules file at all. It is a link
+ # now (debian/links), so the leftover goes.
+ rm -f /etc/xdg/taskmanagerrulesrc.dpkg-dist /etc/xdg/taskmanagerrulesrc.dpkg-new
+
# Select the Wild OS boot screen with Plymouth's own tool: the initramfs
# helper only honours a theme set this way, and silently fell back to
# Debian's when the line was edited in by hand. The initramfs itself is
@@ -26,6 +32,30 @@ if [ "$1" = "configure" ]; then
dracut --regenerate-all --force >/dev/null 2>&1 || echo "wildos-branding: could not rebuild the initramfs; the new boot screen shows after the next kernel update" >&2
fi
+ # Before 0.1.42 keyboard lights always started off, and systemd-backlight
+ # saved that at every shut down as if someone had chosen it, so from now
+ # on it would keep turning them off after the unlock prompt. A light that
+ # is off now and was saved off (or never saved) comes on once, and the
+ # next shut down saves that. One saved on and off now was turned off in
+ # this session, so it is left alone.
+ if [ -n "$2" ] && dpkg --compare-versions "$2" lt 0.1.42 \
+ && [ -d /run/systemd/system ] && [ ! -d /run/initramfs/live ]; then
+ for led in /sys/class/leds/*::kbd_backlight*; do
+ [ -e "$led/brightness" ] || continue
+ name=${led##*/}
+ saved=0
+ for f in /var/lib/systemd/backlight/*:leds:"$name" /var/lib/systemd/backlight/leds:"$name"; do
+ [ -f "$f" ] && read -r saved < "$f" || true
+ done
+ [ "$saved" = 0 ] || continue
+ /usr/libexec/wildos/kbd-backlight-default "$name" || true
+ read -r level < "$led/brightness" || continue
+ for f in /var/lib/systemd/backlight/*:leds:"$name" /var/lib/systemd/backlight/leds:"$name"; do
+ [ -f "$f" ] && echo "$level" > "$f" || true
+ done
+ done
+ fi
+
# USBGuard blocks new devices by switching each USB controller's
# authorized_default to 0, and by default leaves it there when it stops.
# Turning USB protection off in Settings stops the service, so without
@@ -44,6 +74,10 @@ if [ "$1" = "configure" ]; then
if [ -d /run/systemd/system ] && ! systemctl is-active --quiet usbguard.service; then
/usr/libexec/wildos/usb-release || true
fi
+ # The rule for built-in devices applies now, not at the next restart.
+ if [ -d /run/systemd/system ] && systemctl is-active --quiet usbguard.service; then
+ systemctl try-restart usbguard.service || true
+ fi
# The sign-in screen picks up the last person's accessibility choices
# through a PAM session step (see /usr/libexec/wildos/greeter-access);
@@ -59,4 +93,28 @@ if [ "$1" = "configure" ]; then
fi
fi
+if [ "$1" = "configure" ]; then
+ # The white pointer for everything that doesn't read KDE's own setting:
+ # GTK and X11 apps, and anything started before the desktop. Debian's
+ # only candidate is Adwaita's black pointer at priority 90; a choice
+ # made by hand with update-alternatives is left alone.
+ update-alternatives --install /usr/share/icons/default/index.theme x-cursor-theme /usr/share/wildos/cursor/white.theme 100
+
+ # The shutdown guard starts with each session. People signed in while
+ # this is installed get it (or its new version) now, so the next lid
+ # shutdown is covered without signing out first.
+ if [ -d /run/systemd/system ]; then
+ for dir in /run/user/*; do
+ uid=${dir##*/}
+ [ "$uid" -ge 1000 ] 2>/dev/null || continue
+ user=$(id -nu "$uid" 2>/dev/null) || continue
+ systemctl --user -M "$user@" daemon-reload >/dev/null 2>&1 || true
+ systemctl --user -M "$user@" restart wildos-shutdown-guard.service >/dev/null 2>&1 || true
+ # The camera and microphone lights, likewise, without waiting
+ # for the next sign-in.
+ systemctl --user -M "$user@" restart wildos-camera-mic.service >/dev/null 2>&1 || true
+ done
+ fi
+fi
+
#DEBHELPER#
diff --git a/packages/wildos-branding/debian/postrm b/packages/wildos-branding/debian/postrm
index 55077b6..909c2ce 100644
--- a/packages/wildos-branding/debian/postrm
+++ b/packages/wildos-branding/debian/postrm
@@ -8,6 +8,8 @@ if [ "$1" = "remove" ] || [ "$1" = "purge" ] || [ "$1" = "abort-install" ]; then
--divert "$SHIM.plasma" "$SHIM" >/dev/null || true
dpkg-divert --package wildos-branding --remove --rename \
--divert /etc/xdg/arkrc.ark /etc/xdg/arkrc >/dev/null || true
+ dpkg-divert --package wildos-branding --remove --rename \
+ --divert /etc/xdg/taskmanagerrulesrc.plasma /etc/xdg/taskmanagerrulesrc >/dev/null || true
fi
if [ "$1" = "remove" ] || [ "$1" = "purge" ]; then
@@ -23,4 +25,8 @@ if [ "$1" = "remove" ] || [ "$1" = "purge" ]; then
fi
fi
+if [ "$1" = "remove" ] || [ "$1" = "purge" ]; then
+ update-alternatives --remove x-cursor-theme /usr/share/wildos/cursor/white.theme || true
+fi
+
#DEBHELPER#
diff --git a/packages/wildos-branding/debian/preinst b/packages/wildos-branding/debian/preinst
index 4fbcc36..5d0bbcc 100644
--- a/packages/wildos-branding/debian/preinst
+++ b/packages/wildos-branding/debian/preinst
@@ -12,6 +12,9 @@ if [ "$1" = "install" ] || [ "$1" = "upgrade" ]; then
# Ark ships its own defaults file; ours replaces it.
dpkg-divert --package wildos-branding --add --rename \
--divert /etc/xdg/arkrc.ark /etc/xdg/arkrc >/dev/null
+ # Plasma's app matching rules, with our additions.
+ dpkg-divert --package wildos-branding --add --rename \
+ --divert /etc/xdg/taskmanagerrulesrc.plasma /etc/xdg/taskmanagerrulesrc >/dev/null
fi
#DEBHELPER#
diff --git a/packages/wildos-branding/debian/rules b/packages/wildos-branding/debian/rules
index 60dd9b9..1447552 100644
--- a/packages/wildos-branding/debian/rules
+++ b/packages/wildos-branding/debian/rules
@@ -84,3 +84,7 @@ execute_after_dh_install:
# executable bit and have to get it back here.
execute_after_dh_fixperms:
chmod 0755 debian/wildos-branding/usr/libexec/wildos/*
+ chmod 0755 debian/wildos-branding/usr/lib/wildos/advanced-protection.d/*
+ # USBGuard refuses rule files other users can read.
+ chmod 0600 debian/wildos-branding/etc/usbguard/rules.d/40-wildos-built-in.conf
+ chmod 0755 debian/wildos-branding/usr/lib/dracut/modules.d/*/*.sh
diff --git a/packages/wildos-branding/debian/wildos-branding.maintscript b/packages/wildos-branding/debian/wildos-branding.maintscript
new file mode 100644
index 0000000..fe2167a
--- /dev/null
+++ b/packages/wildos-branding/debian/wildos-branding.maintscript
@@ -0,0 +1 @@
+rm_conffile /etc/xdg/taskmanagerrulesrc 0.1.61~ wildos-branding
diff --git a/packages/wildos-branding/files/advanced-protection.d/lights b/packages/wildos-branding/files/advanced-protection.d/lights
new file mode 100644
index 0000000..31619cd
--- /dev/null
+++ b/packages/wildos-branding/files/advanced-protection.d/lights
@@ -0,0 +1,4 @@
+#!/bin/sh
+# The camera and microphone lights have no switch: they are always on, and
+# this only tells Settings > Privacy and security > Advanced protection so.
+exit 0
diff --git a/packages/wildos-branding/files/advanced-protection.d/panic_key b/packages/wildos-branding/files/advanced-protection.d/panic_key
new file mode 100644
index 0000000..46aab4c
--- /dev/null
+++ b/packages/wildos-branding/files/advanced-protection.d/panic_key
@@ -0,0 +1,5 @@
+#!/bin/sh
+# Panic key. Nothing to do as root: each signed-in account follows the switch
+# through wildos-panic-key.path, which loads or unloads the Ctrl+Alt+End
+# shortcut in its own KWin ("panic-key switch").
+exit 0
diff --git a/packages/wildos-branding/files/advanced-protection.d/quiet_lock b/packages/wildos-branding/files/advanced-protection.d/quiet_lock
new file mode 100644
index 0000000..d4faa1f
--- /dev/null
+++ b/packages/wildos-branding/files/advanced-protection.d/quiet_lock
@@ -0,0 +1,6 @@
+#!/bin/sh
+# Quiet lock screen. Nothing to do as root: the lock screen reads quiet_lock
+# from /etc/wildos/advanced-protection each time it starts
+# (look-and-feel/contents/lockscreen/LockNotifications.qml), so the next lock
+# follows the switch.
+exit 0
diff --git a/packages/wildos-branding/files/cursor/white.theme b/packages/wildos-branding/files/cursor/white.theme
new file mode 100644
index 0000000..22a1b50
--- /dev/null
+++ b/packages/wildos-branding/files/cursor/white.theme
@@ -0,0 +1,2 @@
+[Icon Theme]
+Inherits=Breeze_Light
diff --git a/packages/wildos-branding/files/dracut-modules/91wildos-kbd-backlight/module-setup.sh b/packages/wildos-branding/files/dracut-modules/91wildos-kbd-backlight/module-setup.sh
new file mode 100644
index 0000000..7706fa0
--- /dev/null
+++ b/packages/wildos-branding/files/dracut-modules/91wildos-kbd-backlight/module-setup.sh
@@ -0,0 +1,45 @@
+#!/bin/bash
+# The keyboard light comes on at the disk unlock prompt, which runs in the
+# initramfs, long before the installed system's udev rules can see it.
+
+check() {
+ [ -x /usr/libexec/wildos/kbd-backlight-default ] || return 1
+ return 0
+}
+
+depends() {
+ echo udev-rules
+ return 0
+}
+
+install() {
+ inst_multiple mkdir
+ inst_script /usr/libexec/wildos/kbd-backlight-default
+ inst_rules 90-wildos-kbd-backlight.rules
+}
+
+# The drivers behind this PC's keyboard lights, found from the lights
+# themselves so every make works the same (dell-laptop, thinkpad_acpi,
+# asus-nb-wmi, hid-asus, system76 and the rest). No disk uses them, so a
+# host-only initramfs would leave them out. The live image is not built
+# host-only and has no unlock prompt, so it gets none.
+installkernel() {
+ [[ $hostonly ]] || return 0
+ local led dev
+ local -a mods=()
+ for led in /sys/class/leds/*::kbd_backlight*; do
+ [[ -e $led/device ]] || continue
+ dev=$(readlink -f "$led/device")
+ while [[ $dev == /sys/devices/* ]]; do
+ if [[ -e $dev/driver/module ]]; then
+ mods+=("$(basename "$(readlink -f "$dev/driver/module")")")
+ break
+ fi
+ dev=${dev%/*}
+ done
+ done
+ if ((${#mods[@]})); then
+ hostonly='' instmods "${mods[@]}"
+ fi
+ return 0
+}
diff --git a/packages/wildos-branding/files/icons/WildOS/scalable/apps/wayland.svg b/packages/wildos-branding/files/icons/WildOS/scalable/apps/wayland.svg
new file mode 100644
index 0000000..7d14137
--- /dev/null
+++ b/packages/wildos-branding/files/icons/WildOS/scalable/apps/wayland.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="18 -10.5 150 150"><defs><linearGradient id="ka" gradientUnits="userSpaceOnUse" x1="0" y1="17" x2="0" y2="113"><stop offset="0" stop-color="#b4caff"></stop><stop offset="0.5" stop-color="#7d97ec"></stop><stop offset="1" stop-color="#f0a3ae"></stop></linearGradient><linearGradient id="kb" gradientUnits="userSpaceOnUse" x1="0" y1="17" x2="0" y2="113"><stop offset="0" stop-color="#90a8f2"></stop><stop offset="1" stop-color="#de8c9c"></stop></linearGradient></defs><path d="M37 17 L50.34 40 L64.75 64.84 L79.16 40 L92.5 17 L105.84 40 L134.26 89 L120.76 112.28 L92.5 63.55 L64.91 111.12 L23.66 40Z" fill="url(#ka)"></path><path d="M148.5 17 L162 40 L148.5 63 L135 40Z" fill="url(#ka)"></path></svg>
\ No newline at end of file
diff --git a/packages/wildos-branding/files/kwin/scripts/org.wildos.panickey/contents/code/main.js b/packages/wildos-branding/files/kwin/scripts/org.wildos.panickey/contents/code/main.js
new file mode 100644
index 0000000..15e77fc
--- /dev/null
+++ b/packages/wildos-branding/files/kwin/scripts/org.wildos.panickey/contents/code/main.js
@@ -0,0 +1,15 @@
+// The panic key (Settings > Privacy and security > Advanced protection). The
+// shortcut lives in KWin so it works whatever has the keyboard, a full-screen
+// game included. The work runs as a user service, which this only starts:
+// it then carries on even if KWin is busy with the lock.
+//
+// Loaded only while the switch is on ("panic-key switch", which
+// wildos-panic-key.path runs when it changes), so with it off Ctrl+Alt+End
+// reaches apps, such as Remote, which sends it on as Ctrl+Alt+Del.
+
+function panic() {
+ callDBus("org.freedesktop.systemd1", "/org/freedesktop/systemd1", "org.freedesktop.systemd1.Manager",
+ "StartUnit", "wildos-panic.service", "replace");
+}
+
+registerShortcut("Wild OS panic key", "Lock the screen, clear the clipboard and cut the network", "Ctrl+Alt+End", panic);
diff --git a/packages/wildos-branding/files/kwin/scripts/org.wildos.panickey/metadata.json b/packages/wildos-branding/files/kwin/scripts/org.wildos.panickey/metadata.json
new file mode 100644
index 0000000..9c520f3
--- /dev/null
+++ b/packages/wildos-branding/files/kwin/scripts/org.wildos.panickey/metadata.json
@@ -0,0 +1,20 @@
+{
+ "KPackageStructure": "KWin/Script",
+ "KPlugin": {
+ "Authors": [
+ {
+ "Email": "[email protected]",
+ "Name": "Wild OS"
+ }
+ ],
+ "Description": "Ctrl+Alt+End locks the screen, clears the clipboard and cuts the network",
+ "EnabledByDefault": false,
+ "Id": "org.wildos.panickey",
+ "License": "GPL-3.0-or-later",
+ "Name": "Panic key",
+ "Version": "0.1.0",
+ "Website": "https://wildos.io"
+ },
+ "X-Plasma-API": "javascript",
+ "X-Plasma-MainScript": "code/main.js"
+}
diff --git a/packages/wildos-branding/files/libexec/camera-mic b/packages/wildos-branding/files/libexec/camera-mic
new file mode 100644
index 0000000..b448358
--- /dev/null
+++ b/packages/wildos-branding/files/libexec/camera-mic
@@ -0,0 +1,733 @@
+#!/usr/bin/python3 -I
+"""The camera and microphone lights on the taskbar.
+
+Runs in each person's session (wildos-camera-mic.service) and watches the
+devices themselves, not the permission prompts, so every app is caught,
+sandboxed or not:
+
+ - PipeWire: every capture stream linked to a microphone (an Audio/Source
+ node) or a camera (a V4L2 or libcamera Video/Source node). Flatpak apps,
+ browsers on the portal and anything using PulseAudio or ALSA's default
+ device all come through here.
+ - The device files: an app that opens /dev/video* or an ALSA capture
+ device (/dev/snd/pcmC*D*c) itself, bypassing PipeWire. inotify says when
+ one is opened or closed, and the open files under /proc say by whom.
+ Only this account's own processes can be seen.
+
+The tray reads $XDG_RUNTIME_DIR/wildos-camera-mic.json, which says for each
+device which apps are using it and since when, whether it is switched off
+for every app, and which app used it last. Each use goes to the journal as
+"USE {json}" when it starts and again when it ends, for Settings > System >
+History (settings-history).
+
+ camera-mic watch the service
+ camera-mic wait VERSION prints the state once its version is not
+ VERSION (straight away if it already isn't)
+ camera-mic stop KEY cuts the access of the use with this key
+
+Switching a device off for every app is camera-mic-block's job (root,
+through pkexec); this only follows the switches it leaves in /etc/wildos.
+"""
+
+import ctypes
+import hashlib
+import json
+import os
+import re
+import select
+import signal
+import subprocess
+import sys
+import time
+
+RUNTIME = os.environ.get("XDG_RUNTIME_DIR") or "/tmp"
+STATE_NAME = "wildos-camera-mic.json"
+STATE = os.path.join(RUNTIME, STATE_NAME)
+HOME_STATE = os.path.join(os.environ.get("XDG_STATE_HOME") or os.path.expanduser("~/.local/state"), "wildos")
+MEMORY = os.path.join(HOME_STATE, "camera-mic.json")
+
+FLAGS_DIR = "/etc/wildos"
+BLOCKED = {"microphone": os.path.join(FLAGS_DIR, "microphone-off"), "camera": os.path.join(FLAGS_DIR, "camera-off")}
+# Maximum protection (settings-protection) keeps the camera's driver out.
+MAXIMUM_CAMERA = "/etc/modprobe.d/60-wildos-protection-camera.conf"
+BLOCK_HELPER = "/usr/libexec/wildos/camera-mic-block"
+
+# PipeWire's own processes open the devices for the streams counted above;
+# they are never the app.
+PLUMBING = {"pipewire", "wireplumber", "pipewire-pulse", "pw-dump"}
+WINDOWS_APPS = ("wildos-rdp",)
+DEVICES = ("microphone", "camera")
+
+IN_CLOSE_WRITE = 0x08
+IN_CLOSE_NOWRITE = 0x10
+IN_OPEN = 0x20
+IN_MOVED_FROM = 0x40
+IN_MOVED_TO = 0x80
+IN_CREATE = 0x100
+IN_DELETE = 0x200
+IN_Q_OVERFLOW = 0x4000
+IN_IGNORED = 0x8000
+IN_NONBLOCK = 0o4000
+IN_CLOEXEC = 0o2000000
+
+libc = ctypes.CDLL(None, use_errno=True)
+
+
+class Inotify:
+ def __init__(self):
+ self.fd = libc.inotify_init1(IN_NONBLOCK | IN_CLOEXEC)
+ if self.fd < 0:
+ raise OSError(ctypes.get_errno(), "inotify_init1")
+ self.paths = {}
+
+ def add(self, path, mask):
+ wd = libc.inotify_add_watch(self.fd, os.fsencode(path), mask)
+ if wd >= 0:
+ self.paths[wd] = path
+ return wd
+
+ def read(self):
+ """[(path, mask, name)] for what has happened since the last read."""
+ out = []
+ while True:
+ try:
+ data = os.read(self.fd, 65536)
+ except BlockingIOError:
+ return out
+ if not data:
+ return out
+ at = 0
+ while at + 16 <= len(data):
+ wd = int.from_bytes(data[at:at + 4], "little", signed=True)
+ mask = int.from_bytes(data[at + 4:at + 8], "little")
+ size = int.from_bytes(data[at + 12:at + 16], "little")
+ name = data[at + 16:at + 16 + size].split(b"\0", 1)[0].decode("utf-8", "replace")
+ at += 16 + size
+ if mask & IN_IGNORED:
+ self.paths.pop(wd, None)
+ continue
+ out.append((self.paths.get(wd, ""), mask, name))
+
+
+def read_text(path, limit=65536):
+ try:
+ with open(path, encoding="utf-8", errors="replace") as f:
+ return f.read(limit)
+ except OSError:
+ return ""
+
+
+def write_json(path, data):
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ tmp = "%s.%d" % (path, os.getpid())
+ with open(tmp, "w", encoding="utf-8") as f:
+ json.dump(data, f, sort_keys=True)
+ os.replace(tmp, path)
+
+
+def read_json(path):
+ try:
+ with open(path, encoding="utf-8") as f:
+ data = json.load(f)
+ return data if isinstance(data, dict) else {}
+ except (OSError, ValueError):
+ return {}
+
+
+# ------------------------------------------------------------ who is it
+
+class Apps:
+ """Names and icons from the Start menu entries, looked up by desktop id,
+ Flatpak id or program."""
+
+ def __init__(self):
+ self.cache = {}
+ self.loaded = 0
+
+ def dirs(self):
+ data_home = os.environ.get("XDG_DATA_HOME") or os.path.expanduser("~/.local/share")
+ dirs = [os.path.join(data_home, "applications"),
+ os.path.join(data_home, "flatpak/exports/share/applications"),
+ "/var/lib/flatpak/exports/share/applications"]
+ for d in (os.environ.get("XDG_DATA_DIRS") or "/usr/local/share:/usr/share").split(":"):
+ if d:
+ dirs.append(os.path.join(d, "applications"))
+ return dirs
+
+ def load(self):
+ # Apps come and go; a minute old is fresh enough for a name.
+ if time.monotonic() - self.loaded < 60:
+ return
+ self.loaded = time.monotonic()
+ entries = {}
+ for d in reversed(self.dirs()):
+ try:
+ names = os.listdir(d)
+ except OSError:
+ continue
+ for n in names:
+ if n.endswith(".desktop"):
+ entry = self.parse(os.path.join(d, n))
+ if entry:
+ entries[n[:-8]] = entry
+ self.cache = entries
+
+ @staticmethod
+ def parse(path):
+ name = icon = exe = ""
+ hidden = False
+ group = ""
+ for line in read_text(path).splitlines():
+ line = line.strip()
+ if line.startswith("["):
+ group = line
+ continue
+ if group != "[Desktop Entry]" or "=" not in line:
+ continue
+ key, value = line.split("=", 1)
+ if key == "Name" and not name:
+ name = value
+ elif key == "Icon" and not icon:
+ icon = value
+ elif key == "Exec" and not exe:
+ words = [w for w in value.split() if "=" not in w or w.startswith("/")]
+ exe = os.path.basename(words[0]) if words else ""
+ elif key in ("NoDisplay", "Hidden") and value.lower() == "true":
+ hidden = True
+ return {"name": name, "icon": icon, "exe": exe, "hidden": hidden} if name else None
+
+ def by_id(self, desktop_id):
+ self.load()
+ e = self.cache.get(desktop_id)
+ return {"app": e["name"], "icon": e["icon"] or desktop_id, "id": desktop_id} if e else None
+
+ def by_program(self, *programs):
+ self.load()
+ wanted = {p for p in programs if p}
+ for did, e in sorted(self.cache.items()):
+ if not e["hidden"] and e["exe"] in wanted:
+ return {"app": e["name"], "icon": e["icon"] or did, "id": did}
+ return None
+
+
+def unescape_unit(name):
+ return re.sub(r"\\x([0-9a-fA-F]{2})", lambda m: chr(int(m.group(1), 16)), name)
+
+
+def cgroup_app(pid):
+ """(flatpak id, desktop id) from the unit the session started the app in."""
+ for line in read_text("/proc/%d/cgroup" % pid).splitlines():
+ unit = line.rsplit("/", 1)[-1]
+ m = re.match(r"app-flatpak-(.+)-\d+\.scope$", unit)
+ if m:
+ return unescape_unit(m.group(1)), ""
+ m = re.match(r"app-(?:[a-zA-Z0-9]+-)??(.+?)(?:@[^.]*\.service|-[0-9a-zA-Z]+\.scope)$", unit)
+ if m:
+ return "", unescape_unit(m.group(1))
+ return "", ""
+
+
+def who(pid, apps, props=None):
+ """{app, icon, id} for a process, by the most trustworthy name known."""
+ props = props or {}
+ try:
+ exe = os.path.basename(os.readlink("/proc/%d/exe" % pid))
+ except OSError:
+ exe = ""
+ comm = read_text("/proc/%d/comm" % pid, 64).strip()
+ if exe in WINDOWS_APPS or exe.startswith("qemu-system"):
+ return {"app": "Windows apps", "icon": "wildos-windows-app", "id": "windows"}
+ flatpak, desktop = cgroup_app(pid) if pid > 0 else ("", "")
+ flatpak = props.get("pipewire.access.portal.app_id") or flatpak
+ if flatpak:
+ return apps.by_id(flatpak) or {"app": props.get("application.name") or flatpak, "icon": flatpak, "id": flatpak}
+ if desktop:
+ # Some launchers put their own name first (app-gnome-ID-N.scope).
+ for candidate in (desktop, desktop.split("-", 1)[-1]):
+ found = apps.by_id(candidate)
+ if found:
+ return found
+ found = apps.by_program(exe, comm, props.get("application.process.binary", ""))
+ if found:
+ return found
+ name = props.get("application.name") or comm or exe or "An app"
+ return {"app": name, "icon": props.get("application.icon-name") or "", "id": "program:" + (exe or name)}
+
+
+# ------------------------------------------------------------ PipeWire
+
+class Graph:
+ """The PipeWire objects pw-dump reports, kept up to date from its
+ monitor output."""
+
+ def __init__(self):
+ self.objects = {}
+ self.proc = None
+ self.buffer = ""
+ self.decoder = json.JSONDecoder()
+ self.restart_at = 0
+
+ def start(self):
+ self.objects = {}
+ self.buffer = ""
+ try:
+ self.proc = subprocess.Popen(["pw-dump", "--monitor", "--no-colors"], stdout=subprocess.PIPE,
+ stderr=subprocess.DEVNULL, stdin=subprocess.DEVNULL)
+ os.set_blocking(self.proc.stdout.fileno(), False)
+ except OSError:
+ self.proc = None
+ self.restart_at = time.monotonic() + 10
+
+ def fd(self):
+ return self.proc.stdout.fileno() if self.proc else None
+
+ def feed(self):
+ """Reads what pw-dump wrote; False once it has gone."""
+ try:
+ chunk = os.read(self.proc.stdout.fileno(), 1 << 20)
+ except BlockingIOError:
+ return True
+ if not chunk:
+ self.proc.wait()
+ self.proc = None
+ self.objects = {}
+ # PipeWire restarting takes pw-dump with it.
+ self.restart_at = time.monotonic() + 2
+ return False
+ self.buffer += chunk.decode("utf-8", "replace")
+ while True:
+ text = self.buffer.lstrip()
+ if not text:
+ self.buffer = ""
+ break
+ try:
+ batch, end = self.decoder.raw_decode(text)
+ except ValueError:
+ self.buffer = text
+ break
+ self.buffer = text[end:]
+ for o in batch if isinstance(batch, list) else []:
+ if not isinstance(o, dict) or "id" not in o:
+ continue
+ if o.get("info") is None:
+ self.objects.pop(o["id"], None)
+ else:
+ self.objects[o["id"]] = o
+ return True
+
+ def of_type(self, kind):
+ return [o for o in self.objects.values() if o.get("type") == "PipeWire:Interface:" + kind]
+
+ @staticmethod
+ def props(o):
+ return (o.get("info") or {}).get("props") or {}
+
+ def uses(self, running=True):
+ """[(device, stream node, client props, source node)] for every app
+ stream reading a microphone or camera now, or with running=False,
+ linked to one whether or not it is reading yet."""
+ nodes = {n["id"]: n for n in self.of_type("Node")}
+ clients = {c["id"]: self.props(c) for c in self.of_type("Client")}
+ out = []
+ seen = set()
+ for link in self.of_type("Link"):
+ info = link.get("info") or {}
+ source = nodes.get(info.get("output-node-id"))
+ stream = nodes.get(info.get("input-node-id"))
+ if not source or not stream or info.get("state") == "error":
+ continue
+ device = source_kind(self.props(source))
+ sp = self.props(stream)
+ if not device or not str(sp.get("media.class", "")).startswith("Stream/Input/"):
+ continue
+ if sp.get("stream.monitor") in (True, "true"):
+ continue
+ if running and (stream.get("info") or {}).get("state") != "running":
+ continue
+ client = clients.get(sp.get("client.id"), {})
+ if (device, stream["id"]) in seen:
+ continue
+ seen.add((device, stream["id"]))
+ out.append((device, stream, client, source))
+ return out
+
+ def sources(self, device):
+ return [n for n in self.of_type("Node") if source_kind(self.props(n)) == device]
+
+
+def source_kind(p):
+ media = str(p.get("media.class", ""))
+ if media.startswith("Audio/Source"):
+ return "microphone"
+ if media == "Video/Source" and (p.get("device.api") in ("v4l2", "libcamera")
+ or str(p.get("node.name", "")).startswith(("v4l2_input", "libcamera_input"))):
+ return "camera"
+ return ""
+
+
+def node_muted(node):
+ for p in ((node.get("info") or {}).get("params") or {}).get("Props") or []:
+ if isinstance(p, dict) and "mute" in p:
+ return p["mute"] is True
+ return False
+
+
+# Commands the service starts and does not wait for: (process, when).
+running = []
+
+
+def spawn(*args):
+ """Starts a PipeWire command without waiting for it, so a slow answer
+ never holds up the light. Finished ones are reaped, and one still going
+ after ten seconds is stopped."""
+ now = time.monotonic()
+ for entry in running[:]:
+ proc, at = entry
+ if proc.poll() is not None:
+ running.remove(entry)
+ elif now - at > 10:
+ proc.kill()
+ try:
+ running.append((subprocess.Popen(list(args), stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL), now))
+ except OSError:
+ pass
+
+
+def pw(*args):
+ try:
+ return subprocess.run(list(args), capture_output=True, text=True, timeout=10).returncode == 0
+ except (OSError, subprocess.TimeoutExpired):
+ return False
+
+
+# ------------------------------------------------------------ device files
+
+def device_nodes():
+ """{path: device} for the cameras and capture devices there are now."""
+ out = {}
+ try:
+ for n in os.listdir("/dev"):
+ if re.match(r"video\d+$", n):
+ out["/dev/" + n] = "camera"
+ except OSError:
+ pass
+ try:
+ for n in os.listdir("/dev/snd"):
+ if re.match(r"pcmC\d+D\d+c$", n):
+ out["/dev/snd/" + n] = "microphone"
+ except OSError:
+ pass
+ return out
+
+
+def raw_users(nodes):
+ """{pid: set(paths)} for this account's processes holding a camera or
+ capture device open themselves."""
+ out = {}
+ me = os.getuid()
+ for entry in os.scandir("/proc"):
+ if not entry.name.isdigit():
+ continue
+ pid = int(entry.name)
+ try:
+ if entry.stat().st_uid != me:
+ continue
+ fds = os.listdir("/proc/%d/fd" % pid)
+ except OSError:
+ continue
+ found = set()
+ for fd in fds:
+ try:
+ target = os.readlink("/proc/%d/fd/%s" % (pid, fd))
+ except OSError:
+ continue
+ if target in nodes:
+ found.add(target)
+ if found and read_text("/proc/%d/comm" % pid, 64).strip() not in PLUMBING:
+ out[pid] = found
+ return out
+
+
+# ------------------------------------------------------------ the service
+
+def uvc(path):
+ try:
+ return os.path.basename(os.readlink("/sys/class/video4linux/%s/device/driver" % os.path.basename(path))) == "uvcvideo"
+ except OSError:
+ return False
+
+
+def stoppable(use):
+ """A stream PipeWire carries can be ended. A device an app holds open
+ itself can only be taken away by unplugging it in software, which the
+ kernel allows for USB cameras (uvcvideo); for a capture device ALSA
+ gives no way to take back an open one short of closing the app."""
+ if use.get("raw"):
+ return use["device"] == "camera" and all(uvc(p) for p in use.get("paths", []))
+ return bool(use.get("nodes"))
+
+
+def blocked_state():
+ out = {d: os.path.exists(BLOCKED[d]) for d in DEVICES}
+ maximum = os.path.exists(MAXIMUM_CAMERA)
+ return out, maximum
+
+
+class Watcher:
+ def __init__(self):
+ self.apps = Apps()
+ self.graph = Graph()
+ self.notify = Inotify()
+ self.nodes = {}
+ self.raw = {}
+ # key -> use: {device, app, icon, id, since, nodes, pids, key}
+ self.active = {}
+ memory = read_json(MEMORY)
+ self.last = memory.get("last") if isinstance(memory.get("last"), dict) else {}
+ self.version = int(time.time() * 1000)
+ # When a device file was last opened or closed, so the open files
+ # are read once the burst has settled.
+ self.dirty_at = time.monotonic()
+ self.proc_at = 0
+ self.memory_at = 0
+ # Microphones muted here while switched off, by node name (ids change
+ # when PipeWire restarts), so switching back on unmutes only those,
+ # even after this service restarts.
+ self.muted = set(memory.get("muted") or [])
+ self.mute_at = {}
+ self.saved_muted = set(self.muted)
+ # Streams already told to go: id -> when, so a stream PipeWire has
+ # yet to report gone is not destroyed again on every change.
+ self.destroyed = {}
+ # A use left open by a session that ended without saying so ends
+ # when it was last seen.
+ for use in (memory.get("open") or {}).values():
+ if isinstance(use, dict) and use.get("key"):
+ self.history(use, use.get("seen") or use.get("since"))
+
+ def watch_devices(self):
+ current = device_nodes()
+ for path in current:
+ if path not in self.nodes:
+ self.notify.add(path, IN_OPEN | IN_CLOSE_WRITE | IN_CLOSE_NOWRITE)
+ self.nodes = current
+
+ def run(self):
+ signal.signal(signal.SIGTERM, lambda *_: self.stop())
+ signal.signal(signal.SIGINT, lambda *_: self.stop())
+ self.notify.add("/dev", IN_CREATE | IN_DELETE)
+ self.notify.add("/dev/snd", IN_CREATE | IN_DELETE)
+ self.watch_flags()
+ self.watch_devices()
+ self.graph.start()
+ self.blocked, self.maximum = blocked_state()
+ self.update()
+ while True:
+ fds = [self.notify.fd] + ([self.graph.fd()] if self.graph.proc else [])
+ timeout = 0.3 if self.dirty_at else 30
+ ready, _, _ = select.select(fds, [], [], timeout)
+ changed = False
+ if self.notify.fd in ready:
+ for path, mask, _ in self.notify.read():
+ if path in (FLAGS_DIR, "/etc", "/etc/modprobe.d"):
+ self.watch_flags()
+ changed = True
+ continue
+ if path in ("/dev", "/dev/snd"):
+ self.watch_devices()
+ self.dirty_at = self.dirty_at or time.monotonic()
+ if self.graph.proc and self.graph.fd() in ready:
+ self.graph.feed()
+ changed = True
+ if not self.graph.proc and time.monotonic() >= self.graph.restart_at:
+ self.graph.start()
+ # The open files are read a moment after a device is opened or
+ # closed (a burst of them is one read, but a steady stream of
+ # them never puts it off for more than a second), and every
+ # half minute in case an event was missed.
+ quiet = not ready or time.monotonic() - self.dirty_at > 1
+ if (self.dirty_at and quiet) or time.monotonic() - self.proc_at > 30:
+ self.raw = raw_users(self.nodes)
+ self.proc_at = time.monotonic()
+ self.dirty_at = 0
+ changed = True
+ if changed:
+ self.update()
+
+ def watch_flags(self):
+ if os.path.isdir(FLAGS_DIR):
+ self.notify.add(FLAGS_DIR, IN_CREATE | IN_DELETE | IN_MOVED_TO | IN_MOVED_FROM)
+ else:
+ self.notify.add("/etc", IN_CREATE | IN_MOVED_TO)
+ self.notify.add("/etc/modprobe.d", IN_CREATE | IN_DELETE | IN_MOVED_TO | IN_MOVED_FROM)
+
+ def enforce(self):
+ """While a device is off for every app, no stream gets to read it,
+ and microphones stay muted, so even PipeWire's open device is
+ silent until it lets go of it."""
+ now = time.monotonic()
+ self.destroyed = {k: v for k, v in self.destroyed.items() if now - v < 5}
+ for device, stream, _, _ in self.graph.uses(running=False):
+ if (self.blocked.get(device) or (device == "camera" and self.maximum)) and stream["id"] not in self.destroyed:
+ self.destroyed[stream["id"]] = now
+ spawn("pw-cli", "destroy", str(stream["id"]))
+ if self.blocked.get("microphone"):
+ # Muted again if anything unmutes it while it is off.
+ for node in self.graph.sources("microphone"):
+ name = str(Graph.props(node).get("node.name", node["id"]))
+ if not node_muted(node) and now - self.mute_at.get(name, -60) > 30:
+ self.mute_at[name] = now
+ self.muted.add(name)
+ spawn("wpctl", "set-mute", str(node["id"]), "1")
+ elif self.muted and self.graph.objects:
+ for node in self.graph.sources("microphone"):
+ if str(Graph.props(node).get("node.name", node["id"])) in self.muted:
+ spawn("wpctl", "set-mute", str(node["id"]), "0")
+ self.muted = set()
+
+ def update(self):
+ self.blocked, self.maximum = blocked_state()
+ self.enforce()
+ now = time.time()
+ found = {}
+ for device, stream, client, _ in self.graph.uses():
+ if self.blocked.get(device):
+ continue
+ sp = Graph.props(stream)
+ try:
+ pid = int(client.get("pipewire.sec.pid") or sp.get("application.process.id") or 0)
+ except (TypeError, ValueError):
+ pid = 0
+ # PipeWire's own streams (a filter between a microphone and an
+ # app) are not an app; the app on the far side is counted.
+ if pid and read_text("/proc/%d/comm" % pid, 64).strip() in PLUMBING:
+ continue
+ props = dict(client)
+ props.update({k: v for k, v in sp.items() if k.startswith(("application.", "pipewire.access"))})
+ app = who(pid, self.apps, props)
+ use = found.setdefault((device, app["id"]), dict(app, device=device, nodes=[], pids=[], raw=False))
+ use["nodes"].append(stream["id"])
+ if pid:
+ use["pids"].append(pid)
+ for pid, paths in self.raw.items():
+ app = who(pid, self.apps)
+ for path in paths:
+ device = self.nodes.get(path)
+ if not device:
+ continue
+ use = found.setdefault((device, app["id"]), dict(app, device=device, nodes=[], pids=[], raw=False))
+ use["raw"] = True
+ use.setdefault("paths", []).append(path)
+ if pid not in use["pids"]:
+ use["pids"].append(pid)
+ by_slot = {(u["device"], u["id"]): u for u in self.active.values()}
+ active = {}
+ for slot, use in found.items():
+ old = by_slot.get(slot)
+ use["since"] = old["since"] if old else round(now, 3)
+ use["key"] = old["key"] if old else hashlib.sha1(("%s|%s|%s" % (slot[0], slot[1], use["since"])).encode()).hexdigest()[:16]
+ use["seen"] = round(now, 3)
+ active[use["key"]] = use
+ if not old:
+ self.history(use, None)
+ for key, use in self.active.items():
+ if key not in active:
+ self.history(use, now)
+ self.last[use["device"]] = {"app": use["app"], "t": round(now, 3)}
+ self.active = active
+ self.publish()
+
+ def history(self, use, end):
+ record = {"device": use["device"], "app": use["app"], "id": use["id"], "start": use["since"], "key": use["key"],
+ "how": "device" if use.get("raw") and not use.get("nodes") else "pipewire"}
+ if end is not None:
+ record["end"] = round(end, 3)
+ print("USE " + json.dumps(record, sort_keys=True), flush=True)
+
+ def publish(self):
+ devices = {}
+ for d in DEVICES:
+ uses = sorted((u for u in self.active.values() if u["device"] == d), key=lambda u: u["since"])
+ devices[d] = {
+ "uses": [{"key": u["key"], "app": u["app"], "icon": u["icon"], "since": u["since"], "device": d,
+ "stoppable": stoppable(u),
+ "nodes": u["nodes"], "raw": u["raw"]} for u in uses],
+ "blocked": bool(self.blocked.get(d)) or (d == "camera" and self.maximum),
+ "maximum": d == "camera" and self.maximum,
+ "last": self.last.get(d),
+ }
+ state = {"devices": devices}
+ previous = read_json(STATE)
+ previous.pop("version", None)
+ if previous != state:
+ self.version += 1
+ state["version"] = self.version
+ write_json(STATE, state)
+ if previous != state or (self.active and time.monotonic() - self.memory_at > 60) or self.muted != self.saved_muted:
+ self.saved_muted = set(self.muted)
+ self.memory_at = time.monotonic()
+ write_json(MEMORY, {"last": self.last, "open": self.active, "muted": sorted(self.muted)})
+
+ def stop(self):
+ now = time.time()
+ for use in self.active.values():
+ self.history(use, now)
+ self.last[use["device"]] = {"app": use["app"], "t": round(now, 3)}
+ self.active = {}
+ try:
+ write_json(MEMORY, {"last": self.last, "open": {}, "muted": sorted(self.muted)})
+ os.unlink(STATE)
+ except OSError:
+ pass
+ if self.graph.proc:
+ self.graph.proc.terminate()
+ sys.exit(0)
+
+
+# ------------------------------------------------------------ the commands
+
+def wait(version):
+ notify = Inotify()
+ notify.add(RUNTIME, IN_MOVED_TO | IN_CREATE | IN_DELETE)
+ deadline = time.monotonic() + 600
+ while True:
+ state = read_json(STATE)
+ if str(state.get("version", "")) != version or time.monotonic() > deadline:
+ print(json.dumps(state))
+ return
+ select.select([notify.fd], [], [], max(1, deadline - time.monotonic()))
+ notify.read()
+
+
+def stop(key):
+ use = None
+ for d in read_json(STATE).get("devices", {}).values():
+ for u in d.get("uses", []):
+ if u.get("key") == key:
+ use = u
+ if not use:
+ return 1
+ ok = True
+ for node in use.get("nodes") or []:
+ ok = pw("pw-cli", "destroy", str(int(node))) and ok
+ if use.get("raw") and use.get("device") == "camera":
+ ok = pw("pkexec", BLOCK_HELPER, "release", "camera") and ok
+ return 0 if ok else 1
+
+
+def main():
+ what = sys.argv[1] if len(sys.argv) > 1 else ""
+ if what == "watch":
+ Watcher().run()
+ elif what == "wait" and len(sys.argv) == 3:
+ wait(sys.argv[2])
+ elif what == "stop" and len(sys.argv) == 3 and re.match(r"^[0-9a-f]{16}$", sys.argv[2]):
+ sys.exit(stop(sys.argv[2]))
+ else:
+ print(__doc__.strip(), file=sys.stderr)
+ sys.exit(2)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/packages/wildos-branding/files/libexec/camera-mic-block b/packages/wildos-branding/files/libexec/camera-mic-block
new file mode 100644
index 0000000..6c6e725
--- /dev/null
+++ b/packages/wildos-branding/files/libexec/camera-mic-block
@@ -0,0 +1,95 @@
+#!/bin/sh
+# The switches in the camera and microphone panel on the taskbar: each one
+# blocks its device for every app and every account, until it is switched
+# back on. Runs as root through pkexec (org.wildos.camera-mic.policy).
+# Takes only the requests below.
+#
+# block microphone Capture devices become root's alone (udev,
+# 72-wildos-camera-mic.rules), so neither PipeWire
+# nor an app opening the device itself can start
+# listening. The session's camera-mic service ends
+# the streams already running and mutes the
+# microphones.
+# block camera The same for cameras, and the USB camera driver
+# (uvcvideo) is taken out and kept out, which also
+# cuts off an app that already has the camera open.
+# unblock DEVICE Back as Wild OS ships it.
+# release camera The Stop button for an app that opened a USB camera
+# itself: the camera is unplugged in software and
+# plugged back, which closes it for whoever has it.
+
+set -eu
+export LC_ALL=C
+PATH=/usr/sbin:/usr/bin:/sbin:/bin
+
+FLAGS=/etc/wildos
+CAMERA_DRIVER_BLOCK=/etc/modprobe.d/60-wildos-camera-off.conf
+# Maximum protection's own block, which this never removes.
+MAXIMUM_BLOCK=/etc/modprobe.d/60-wildos-protection-camera.conf
+
+uvc_interfaces() {
+ for dev in /sys/bus/usb/drivers/uvcvideo/*:*; do
+ [ -e "$dev" ] && basename "$dev"
+ done
+}
+
+# Switched off: udev forgets the devices and finds them again, so the rules
+# start afresh without the uaccess tag a device keeps from earlier events
+# (logind would otherwise give the access list back at the next sign-in).
+# Mode 0600 also empties the access list already on the device file.
+# Takes udevadm trigger's matches for the devices.
+lock() {
+ udevadm trigger --action=remove "$@" >/dev/null 2>&1 || true
+ udevadm settle --timeout=10 >/dev/null 2>&1 || true
+ udevadm trigger --action=add "$@" >/dev/null 2>&1 || true
+ udevadm settle --timeout=10 >/dev/null 2>&1 || true
+}
+
+# Switched on: owner, group, mode and the signed-in person's access list
+# come back from the rules as Wild OS ships them. udev only sets the owner
+# and group of a device it is adding, so it is found again here too.
+unlock() {
+ lock "$@"
+}
+
+case "${1:-}:${2:-}" in
+ block:microphone)
+ mkdir -p "$FLAGS"
+ : > "$FLAGS/microphone-off"
+ lock --subsystem-match=sound --sysname-match="pcmC*D*c"
+ ;;
+ unblock:microphone)
+ rm -f "$FLAGS/microphone-off"
+ unlock --subsystem-match=sound --sysname-match="pcmC*D*c"
+ ;;
+ block:camera)
+ mkdir -p "$FLAGS"
+ : > "$FLAGS/camera-off"
+ printf '%s\n' '# Written by the camera switch on the taskbar: the camera is off for every app.' \
+ 'install uvcvideo /bin/false' > "$CAMERA_DRIVER_BLOCK"
+ # Unbinding first takes the camera from an app holding it open,
+ # which would otherwise keep the driver from unloading.
+ for intf in $(uvc_interfaces); do
+ echo "$intf" > /sys/bus/usb/drivers/uvcvideo/unbind 2>/dev/null || true
+ done
+ modprobe -r uvcvideo 2>/dev/null || true
+ lock --subsystem-match=video4linux --subsystem-match=media
+ ;;
+ unblock:camera)
+ rm -f "$FLAGS/camera-off" "$CAMERA_DRIVER_BLOCK"
+ if [ ! -e "$MAXIMUM_BLOCK" ]; then
+ modprobe uvcvideo 2>/dev/null || true
+ fi
+ unlock --subsystem-match=video4linux --subsystem-match=media
+ ;;
+ release:camera)
+ for intf in $(uvc_interfaces); do
+ echo "$intf" > /sys/bus/usb/drivers/uvcvideo/unbind 2>/dev/null || true
+ echo "$intf" > /sys/bus/usb/drivers/uvcvideo/bind 2>/dev/null || true
+ done
+ ;;
+ *)
+ echo "usage: camera-mic-block block|unblock microphone|camera, or release camera" >&2
+ exit 2
+ ;;
+esac
diff --git a/packages/wildos-branding/files/libexec/greeter-access b/packages/wildos-branding/files/libexec/greeter-access
index 02bfed8..8fa267f 100644
--- a/packages/wildos-branding/files/libexec/greeter-access
+++ b/packages/wildos-branding/files/libexec/greeter-access
@@ -90,13 +90,43 @@ 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.
+# The account's own pointer (Settings > Accessibility > Your own) lives in
+# the home folder, which the sign-in screen cannot read. pointer-import hands
+# it across as a stream: read as the person, then checked and written again
+# picture by picture as the sddm user, so only well-formed pointer pictures
+# reach the sign-in screen. The stamp changes with each new pointer, so an
+# unchanged one is not copied again at every sign-in and sign-out.
+copy_custom_pointer() {
+ import=/usr/libexec/wildos/pointer-import
+ own="$home/.local/share/icons/WildOS-Custom"
+ target="$greeter_home/.local/share/icons/WildOS-Custom"
+ [ -x "$import" ] || return 1
+ stamp=$(as_user kreadconfig6 --file "$own/index.theme" --group "Wild OS" --key Stamp --default "" 2>/dev/null)
+ case $stamp in
+ '' | *[!0-9a-f]*) return 1 ;;
+ esac
+ have=$(as_greeter kreadconfig6 --file "$target/index.theme" --group "Wild OS" --key Stamp --default "" 2>/dev/null)
+ [ "$stamp" = "$have" ] && return 0
+ as_greeter mkdir -p "$greeter_home/.local/share/icons" || return 1
+ as_user "$import" export "$own" | as_greeter "$import" import "$target" "$stamp"
+}
+
+# The pointer, only as one of the themes installed here or the account's own.
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"
+if [ "$theme" = WildOS-Custom ]; then
+ if copy_custom_pointer; then
+ write_key kcminputrc Mouse cursorTheme --type=string WildOS-Custom
+ else
+ write_key kcminputrc Mouse cursorTheme --type=string Breeze_Light
+ fi
+else
+ as_greeter rm -rf "$greeter_home/.local/share/icons/WildOS-Custom"
+ if [ -n "$theme" ] && [ -f "/usr/share/icons/$theme/index.theme" ]; then
+ write_key kcminputrc Mouse cursorTheme --type=string "$theme"
+ fi
fi
copy_int kcminputrc Mouse cursorSize 24 16 256
diff --git a/packages/wildos-branding/files/libexec/kbd-backlight-default b/packages/wildos-branding/files/libexec/kbd-backlight-default
new file mode 100644
index 0000000..bd8faa9
--- /dev/null
+++ b/packages/wildos-branding/files/libexec/kbd-backlight-default
@@ -0,0 +1,52 @@
+#!/bin/sh
+# Keyboard lights are on at every start-up.
+#
+# kbd-backlight-default <led> from udev, as each light appears
+# kbd-backlight-default --restored <unit> after systemd-backlight's restore
+#
+# Laptops start with the light off, so the disk unlock password was typed in
+# the dark: the first time a light appears in a start-up, from the initramfs
+# on, it comes on. The marker in /run outlives the move from the initramfs to
+# the system, so the second "add" udev replays there, or a driver reload
+# later on, leaves the level alone.
+#
+# Once the disk is open, systemd-backlight puts back the level saved at the
+# last shut down. That keeps the step someone picked, but a saved "off" is
+# nearly always the lid closing or the screen going idle just before the
+# save, so the light comes on again instead of staying dark.
+
+if [ "$1" = --restored ]; then
+ # systemd-backlight's instance, such as leds:dell::kbd_backlight.
+ case $2 in
+ leds:*::kbd_backlight*) led=${2#leds:} ;;
+ *) exit 0 ;;
+ esac
+ restored=1
+else
+ led=$1
+fi
+dir=/sys/class/leds/$led
+marks=/run/wildos/kbd-backlight
+
+[ -n "$led" ] && [ -e "$dir/brightness" ] || exit 0
+if [ -z "$restored" ]; then
+ [ -e "$marks/$led" ] && exit 0
+ mkdir -p "$marks" && : > "$marks/$led" || exit 0
+fi
+
+read -r max < "$dir/max_brightness" || exit 0
+read -r now < "$dir/brightness" || exit 0
+[ "$max" -gt 0 ] 2>/dev/null || exit 0
+# Some firmware keeps the level from the last start-up (or the one set in
+# its own setup screen); that is a choice too.
+[ "$now" = 0 ] || exit 0
+
+# Two or three steps (off, low, high) are made to be used at the top one;
+# a light with many steps is bright enough at half.
+if [ "$max" -le 3 ]; then
+ level=$max
+else
+ level=$(( (max + 1) / 2 ))
+fi
+echo "$level" > "$dir/brightness"
+exit 0
diff --git a/packages/wildos-branding/files/libexec/panic-key b/packages/wildos-branding/files/libexec/panic-key
new file mode 100644
index 0000000..6943867
--- /dev/null
+++ b/packages/wildos-branding/files/libexec/panic-key
@@ -0,0 +1,113 @@
+#!/bin/sh
+# The panic key from Advanced protection, Ctrl+Alt+End while "Panic key" is
+# on (panic_key in /etc/wildos/advanced-protection, off unless set to on).
+#
+# panic-key the key itself (wildos-panic.service, which the
+# org.wildos.panickey KWin script starts)
+# panic-key switch load or unload that KWin script for this account, at
+# sign-in and whenever the switch changes
+# (wildos-panic-key.service and .path)
+# panic-key offer once the screen is unlocked, offer to turn the network
+# back on (wildos-panic-offer.service)
+#
+# The network stays off until the person turns it back on: after they
+# unlock, a notification offers to, and every sign-in offers again for as
+# long as it is still off.
+
+set -u
+
+state=${XDG_STATE_HOME:-$HOME/.local/state}/wildos
+cut=$state/panic-network
+store=/etc/wildos/advanced-protection
+
+panic() {
+ # The screen locker answers once the lock screen is up. loginctl is the
+ # way round when it is missing, with the account's graphical session
+ # named, as this service is not in one.
+ if ! busctl --user call org.freedesktop.ScreenSaver /ScreenSaver org.freedesktop.ScreenSaver Lock >/dev/null 2>&1; then
+ session=$(loginctl show-user "$(id -un)" -p Display --value 2>/dev/null)
+ loginctl lock-session ${session:+"$session"}
+ fi
+
+ # The history Win+V shows lives in wildos-clipboard, which empties it
+ # and its pins (kept on disk, pictures and all), then the clipboard and
+ # the middle-click selection.
+ wildos-clipboard --clear >/dev/null 2>&1
+
+ # Only what this turns off comes back later, added to what an earlier
+ # press turned off. NetworkManager lets the person at the screen switch
+ # networking off and on without a password (polkit
+ # org.freedesktop.NetworkManager.enable-disable-network); Bluetooth goes
+ # through the same switch as Quick settings.
+ networking=no
+ bluetooth=no
+ [ -r "$cut" ] && . "$cut"
+ if [ "$(nmcli networking 2>/dev/null)" = enabled ]; then
+ nmcli networking off && networking=yes
+ fi
+ if rfkill list bluetooth 2>/dev/null | grep -q 'Soft blocked: no'; then
+ rfkill block bluetooth && bluetooth=yes
+ fi
+ if [ "$networking" = yes ] || [ "$bluetooth" = yes ]; then
+ mkdir -p "$state"
+ printf 'networking=%s\nbluetooth=%s\n' "$networking" "$bluetooth" > "$cut"
+ systemctl --user start --no-block wildos-panic-offer.service
+ fi
+}
+
+switch() {
+ value=$(sed -n 's/^panic_key=//p' "$store" 2>/dev/null | tail -n 1 | tr -d "\"' ")
+ if [ "$value" = on ]; then
+ kwriteconfig6 --file kwinrc --group Plugins --key org.wildos.panickeyEnabled true
+ busctl --user call org.kde.KWin /Scripting org.kde.kwin.Scripting start >/dev/null 2>&1
+ else
+ kwriteconfig6 --file kwinrc --group Plugins --key org.wildos.panickeyEnabled false
+ busctl --user call org.kde.KWin /Scripting org.kde.kwin.Scripting unloadScript s org.wildos.panickey >/dev/null 2>&1
+ fi
+ if [ -e "$cut" ]; then
+ systemctl --user start --no-block wildos-panic-offer.service
+ fi
+}
+
+offer() {
+ [ -r "$cut" ] || exit 0
+ networking=no
+ bluetooth=no
+ . "$cut"
+
+ # Nothing is offered over the lock screen, where it could not be seen.
+ while busctl --user call org.freedesktop.ScreenSaver /ScreenSaver org.freedesktop.ScreenSaver GetActive 2>/dev/null |
+ grep -q true; do
+ sleep 2
+ done
+
+ # Turned back on some other way meanwhile: nothing to offer.
+ if [ "$networking" = yes ] && [ "$(nmcli networking 2>/dev/null)" = enabled ]; then
+ networking=no
+ fi
+ if [ "$bluetooth" = yes ] && ! rfkill list bluetooth 2>/dev/null | grep -q 'Soft blocked: yes'; then
+ bluetooth=no
+ fi
+ if [ "$networking" = no ] && [ "$bluetooth" = no ]; then
+ rm -f "$cut"
+ exit 0
+ fi
+
+ # Critical, so it waits on screen until answered instead of timing out
+ # into the history, where its button would no longer work.
+ answer=$(notify-send --app-name="Wild OS" --icon=network-offline --urgency=critical \
+ --action=on="Turn back on" --wait \
+ "The network is off" "The panic key cut it. Turn it back on when you are ready.")
+ [ "$answer" = on ] || exit 0
+
+ [ "$networking" = yes ] && nmcli networking on
+ [ "$bluetooth" = yes ] && rfkill unblock bluetooth
+ rm -f "$cut"
+}
+
+case ${1:-} in
+ "") panic ;;
+ switch) switch ;;
+ offer) offer ;;
+ *) echo "usage: panic-key [switch|offer]" >&2; exit 2 ;;
+esac
diff --git a/packages/wildos-branding/files/libexec/security-notify b/packages/wildos-branding/files/libexec/security-notify
index 3873ca0..fadee26 100644
--- a/packages/wildos-branding/files/libexec/security-notify
+++ b/packages/wildos-branding/files/libexec/security-notify
@@ -11,6 +11,12 @@
export LC_ALL=C
icon=/usr/share/plasma/plasmoids/org.wildos.protected/contents/images/shield.svg
+# The screen lock (kscreenlocker's org.freedesktop.ScreenSaver).
+locked() {
+ gdbus call --session --dest org.freedesktop.ScreenSaver --object-path /ScreenSaver \
+ --method org.freedesktop.ScreenSaver.GetActive 2>/dev/null | grep -q true
+}
+
# A notification left unanswered for six hours has been seen and ignored;
# the device simply stays blocked and the flyout still offers the choice.
send() {
@@ -21,6 +27,16 @@ case $1 in
usb)
port=$2
printf '%s' "$port" | grep -qE '^[0-9]+-[0-9]+(\.[0-9]+)*$' || exit 2
+ # Nobody can answer from behind the lock screen, and while it is
+ # locked wildos-usb-lock holds every new device back anyway. At
+ # sign-in it reconnects those, so the device is looked at again
+ # once that has settled.
+ if locked; then
+ while locked; do
+ sleep 3
+ done
+ sleep 3
+ fi
line=$(/usr/libexec/wildos/usb-devices list | awk -F '\t' -v p="$port" '$1 == p')
[ -n "$line" ] || exit 0
kind=$(printf '%s' "$line" | cut -f2)
diff --git a/packages/wildos-branding/files/libexec/shutdown-guard b/packages/wildos-branding/files/libexec/shutdown-guard
new file mode 100644
index 0000000..9b629df
--- /dev/null
+++ b/packages/wildos-branding/files/libexec/shutdown-guard
@@ -0,0 +1,318 @@
+#!/usr/bin/python3
+"""Sees a shutdown or restart through to the end once Plasma has started it.
+
+Plasma signs out before it shuts down: plasma-shutdown asks ksmserver and
+KWin to close every app, stops the session's services and only then asks
+logind to power off. Two things went wrong on the way.
+
+The lid. PowerDevil holds logind's handle-lid-switch lock for the whole
+session and is one of the services stopped while signing out. If the lid is
+closed at that moment (closing it is what started a lid shutdown), logind
+sees a closed lid nobody is handling and suspends, a fraction of a second
+before plasma-shutdown's PowerOff, which logind then refuses because a
+suspend is under way. The PC slept instead of shutting down and woke up to
+a black screen with the session gone. So from the moment a shutdown or
+restart is asked for, this process holds the lid lock itself; it is not
+part of the graphical session, so signing out leaves it running.
+
+Apps with unsaved work. KWin asks each window to close; one that answers
+with "save changes?" stops the sign-out and ksmserver calls the whole thing
+off. That is right when someone is at the screen, but a lid or power button
+shutdown is asked for by someone walking away, so like Windows it gives the
+apps a while and then shuts down anyway. Whatever was still open then is
+written down, and `shutdown-guard --notice` says which apps were closed
+once the desktop is up at the next sign-in.
+"""
+
+import json
+import os
+import sys
+import time
+
+from gi.repository import Gio, GLib
+
+# How long a lid or power button shutdown waits for apps before going ahead.
+GRACE = 15
+# After plasma-shutdown goes away, how long to wait for logind's
+# PrepareForShutdown before deciding the shutdown was called off.
+SETTLE = 3
+
+LOGIND = ("org.freedesktop.login1", "/org/freedesktop/login1", "org.freedesktop.login1.Manager")
+# PowerDevil's name on the session bus: lid, power button and low battery
+# actions come from it, other shutdowns from someone at the screen.
+POWERDEVIL = "org.kde.Solid.PowerManagement"
+ACTIONS = {"logoutAndShutdown": "PowerOff", "logoutAndReboot": "Reboot"}
+
+STATE_DIR = os.path.join(os.environ.get("XDG_STATE_HOME") or os.path.expanduser("~/.local/state"), "wildos")
+NOTICE = os.path.join(STATE_DIR, "closed-at-shutdown.json")
+
+
+def log(*args):
+ print(*args, flush=True)
+
+
+class Guard:
+ def __init__(self):
+ self.session = Gio.bus_get_sync(Gio.BusType.SESSION, None)
+ self.system = Gio.bus_get_sync(Gio.BusType.SYSTEM, None)
+ self.powerdevil = None
+ self.lock = None
+ self.pending = None
+ self.timer = 0
+ Gio.bus_watch_name_on_connection(self.session, POWERDEVIL, Gio.BusNameWatcherFlags.NONE,
+ self._powerdevil_up, self._powerdevil_gone)
+ Gio.bus_watch_name_on_connection(self.session, "org.kde.Shutdown", Gio.BusNameWatcherFlags.NONE,
+ None, self._shutdown_gone)
+ self.system.signal_subscribe(LOGIND[0], LOGIND[2], "PrepareForShutdown", LOGIND[1], None,
+ Gio.DBusSignalFlags.NONE, self._prepare, None)
+ self._monitor()
+
+ def _powerdevil_up(self, conn, name, owner):
+ self.powerdevil = owner
+
+ def _powerdevil_gone(self, conn, name):
+ # Kept: PowerDevil stops during the sign-out its own call started,
+ # and the call is matched to it after that.
+ pass
+
+ def _monitor(self):
+ """org.kde.Shutdown's calls, seen as a monitor on a connection of
+ their own: every way of shutting down in Plasma goes through them."""
+ address = Gio.dbus_address_get_for_bus_sync(Gio.BusType.SESSION, None)
+ self.monitor = Gio.DBusConnection.new_for_address_sync(
+ address, Gio.DBusConnectionFlags.AUTHENTICATION_CLIENT | Gio.DBusConnectionFlags.MESSAGE_BUS_CONNECTION,
+ None, None)
+ self.monitor.add_filter(self._filter)
+ rules = ["type='method_call',interface='org.kde.Shutdown',member='%s'" % m for m in ACTIONS]
+ self.monitor.call_sync("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus.Monitoring",
+ "BecomeMonitor", GLib.Variant("(asu)", (rules, 0)), None, Gio.DBusCallFlags.NONE, 3000, None)
+
+ def _filter(self, conn, message, incoming):
+ # GDBus's worker thread: hand over to the main loop. The lid lock has
+ # to be taken within the fraction of a second before PowerDevil
+ # stops, so this is the first thing that happens.
+ if incoming and message.get_message_type() == Gio.DBusMessageType.METHOD_CALL \
+ and message.get_interface() == "org.kde.Shutdown" and message.get_member() in ACTIONS:
+ GLib.idle_add(self._asked, message.get_member(), message.get_sender())
+ return None
+ return message
+
+ def _asked(self, member, sender):
+ action = ACTIONS[member]
+ self._hold_lid()
+ unattended = bool(sender) and sender == self.powerdevil
+ lid = self._lid_closed()
+ log("%s asked for by %s%s" % (action, "PowerDevil" if unattended else sender or "someone",
+ ", lid closed" if lid else ""))
+ if unattended:
+ if self.timer:
+ GLib.source_remove(self.timer)
+ self.pending = {"action": action, "lid": lid, "at": time.time()}
+ self.timer = GLib.timeout_add_seconds(GRACE, self._deadline)
+ return False
+
+ def _hold_lid(self):
+ if self.lock is not None:
+ return
+ try:
+ reply, fds = self.system.call_with_unix_fd_list_sync(
+ LOGIND[0], LOGIND[1], LOGIND[2], "Inhibit",
+ GLib.Variant("(ssss)", ("handle-lid-switch", "Wild OS", "Shutting down", "block")),
+ GLib.VariantType("(h)"), Gio.DBusCallFlags.NONE, 3000, None, None)
+ self.lock = fds.steal_fds()[reply.unpack()[0]]
+ except GLib.Error as e:
+ log("could not hold the lid:", e.message)
+
+ def _release_lid(self):
+ if self.lock is not None:
+ os.close(self.lock)
+ self.lock = None
+
+ def _lid_closed(self):
+ try:
+ reply = self.system.call_sync(LOGIND[0], LOGIND[1], "org.freedesktop.DBus.Properties", "Get",
+ GLib.Variant("(ss)", (LOGIND[2], "LidClosed")), GLib.VariantType("(v)"),
+ Gio.DBusCallFlags.NONE, 3000, None)
+ return bool(reply.unpack()[0])
+ except GLib.Error:
+ return False
+
+ def _shutting_down(self):
+ try:
+ reply = self.system.call_sync(LOGIND[0], LOGIND[1], "org.freedesktop.DBus.Properties", "Get",
+ GLib.Variant("(ss)", (LOGIND[2], "PreparingForShutdown")),
+ GLib.VariantType("(v)"), Gio.DBusCallFlags.NONE, 3000, None)
+ return bool(reply.unpack()[0])
+ except GLib.Error:
+ return False
+
+ def _prepare(self, conn, sender, path, iface, signal, params, data):
+ if params.unpack()[0]:
+ # Under way: logind ignores the lid from here on, and this
+ # process ends with the session.
+ if self.timer:
+ GLib.source_remove(self.timer)
+ self.timer = 0
+ self.pending = None
+
+ def _shutdown_gone(self, conn, name):
+ # plasma-shutdown quits once it has asked logind, or when the
+ # sign-out was called off. Someone at the screen who called it off
+ # gets the lid back; an unattended shutdown waits for its deadline.
+ if self.lock is not None and self.pending is None:
+ GLib.timeout_add_seconds(SETTLE, self._settle)
+
+ def _settle(self):
+ if self.pending is None and not self._shutting_down():
+ log("the shutdown was called off")
+ self._release_lid()
+ return False
+
+ def _deadline(self):
+ self.timer = 0
+ pending, self.pending = self.pending, None
+ if pending is None or self._shutting_down():
+ return False
+ apps = open_apps()
+ log("apps still open after %d s: %s; going ahead without them" % (GRACE, ", ".join(apps) or "none"))
+ if apps:
+ os.makedirs(STATE_DIR, exist_ok=True)
+ with open(NOTICE + ".new", "w") as f:
+ json.dump({"t": round(pending["at"]), "lid": pending["lid"], "apps": apps,
+ "action": pending["action"]}, f)
+ os.replace(NOTICE + ".new", NOTICE)
+ try:
+ self.system.call_sync(LOGIND[0], LOGIND[1], LOGIND[2], pending["action"], GLib.Variant("(b)", (False,)),
+ None, Gio.DBusCallFlags.NONE, 10000, None)
+ except GLib.Error as e:
+ # Better asleep with the lid shut than on all night.
+ log("logind refused %s: %s" % (pending["action"], e.message))
+ try:
+ os.unlink(NOTICE)
+ except OSError:
+ pass
+ self._release_lid()
+ return False
+
+
+def unescape(s):
+ out, i = "", 0
+ while i < len(s):
+ if s.startswith("\\x", i) and i + 4 <= len(s):
+ try:
+ out += chr(int(s[i + 2:i + 4], 16))
+ i += 4
+ continue
+ except ValueError:
+ pass
+ out += s[i]
+ i += 1
+ return out
+
+
+def app_name(unit, description):
+ """The app's own name for a systemd unit Plasma started it in:
+ app-<id>@<n>.service or app-<id>-<n>.scope, the id its .desktop file."""
+ base = unit[4:]
+ if base.endswith(".service"):
+ base = base[:-8].split("@", 1)[0]
+ elif base.endswith(".scope"):
+ base = base[:-6].rsplit("-", 1)[0]
+ base = unescape(base)
+ candidates = [base]
+ if "-" in base:
+ # A launcher's prefix: app-flatpak-<id>-<n>.scope and the like.
+ candidates.append(base.split("-", 1)[1])
+ for desktop_id in candidates:
+ try:
+ info = Gio.DesktopAppInfo.new(desktop_id + ".desktop")
+ except TypeError:
+ info = None
+ if info:
+ return info.get_name()
+ return description if description and not description.startswith("app-") else base
+
+
+def open_apps():
+ """Apps still running in the session: the ones that didn't close when
+ asked. Things started at sign-in (@autostart) are the desktop's own."""
+ try:
+ session = Gio.bus_get_sync(Gio.BusType.SESSION, None)
+ reply = session.call_sync("org.freedesktop.systemd1", "/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager", "ListUnitsByPatterns",
+ GLib.Variant("(asas)", (["active"], ["app-*.service", "app-*.scope"])),
+ None, Gio.DBusCallFlags.NONE, 5000, None)
+ except GLib.Error as e:
+ log("could not list the open apps:", e.message)
+ return []
+ names = []
+ for unit in reply.unpack()[0]:
+ name, description = unit[0], unit[1]
+ # What Plasma opens gets a unit of its own, named with a random
+ # instance (app-<id>@<n>.service). Packaged background services
+ # such as the remote desktop server have no instance, and those
+ # started at sign-in have "autostart" as theirs.
+ if name.endswith(".service") and ("@" not in name or "@autostart." in name):
+ continue
+ label = app_name(name, description)
+ if label and label not in names:
+ names.append(label)
+ return sorted(names)
+
+
+def notice():
+ """Says which apps the last unattended shutdown closed. Run once the
+ desktop is up (wildos-shutdown-notice.service): a notification sent
+ while Plasma is still starting goes straight to its history unseen."""
+ try:
+ with open(NOTICE) as f:
+ data = json.load(f)
+ except FileNotFoundError:
+ return 0
+ except (OSError, ValueError):
+ data = {}
+ apps = [a for a in data.get("apps", []) if isinstance(a, str)]
+ if not apps:
+ os.unlink(NOTICE)
+ return 0
+ names = apps[0] if len(apps) == 1 else ", ".join(apps[:-1]) + " and " + apps[-1]
+ one = len(apps) == 1
+ did = "restarted" if data.get("action") == "Reboot" else "shut down"
+ if data.get("lid"):
+ start = "You closed the lid while %s %s still open" % (names, "was" if one else "were")
+ else:
+ start = "The PC %s while %s %s still open" % (did, names, "was" if one else "were")
+ body = ("%s. %s didn't close within %d seconds, so Wild OS %s anyway. Anything you hadn't saved in %s may be lost."
+ % (start, "It" if one else "They", GRACE, did, "it" if one else "them"))
+ title = "%s was closed without saving" % apps[0] if one else "Apps were closed without saving"
+ try:
+ session = Gio.bus_get_sync(Gio.BusType.SESSION, None)
+ session.call_sync("org.freedesktop.Notifications", "/org/freedesktop/Notifications",
+ "org.freedesktop.Notifications", "Notify",
+ GLib.Variant("(susssasa{sv}i)", ("Wild OS", 0, "dialog-warning", title, body, [],
+ {"urgency": GLib.Variant("y", 1)},
+ # Stays until read: it is about lost work.
+ 0)),
+ None, Gio.DBusCallFlags.NONE, 10000, None)
+ except GLib.Error as e:
+ # Kept for the next sign-in.
+ log("could not show the notice:", e.message)
+ return 1
+ os.unlink(NOTICE)
+ log("told the person:", body)
+ return 0
+
+
+def main():
+ if sys.argv[1:] == ["--notice"]:
+ return notice()
+ if len(sys.argv) > 1:
+ print("usage: shutdown-guard [--notice]", file=sys.stderr)
+ return 2
+ Guard()
+ GLib.MainLoop().run()
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/packages/wildos-branding/files/libexec/taskbar-items b/packages/wildos-branding/files/libexec/taskbar-items
index dd0e91e..b3d810d 100644
--- a/packages/wildos-branding/files/libexec/taskbar-items
+++ b/packages/wildos-branding/files/libexec/taskbar-items
@@ -9,7 +9,7 @@ set -u
state=${XDG_STATE_HOME:-$HOME/.local/state}/wildos
# Each change: its marker and its script.
pending=""
-for change in winmode-added:taskbar-winmode.js winmode-left:taskbar-winmode-left.js updates-added:taskbar-updates.js; do
+for change in winmode-added:taskbar-winmode.js winmode-left:taskbar-winmode-left.js updates-added:taskbar-updates.js lights-added:taskbar-lights.js; do
[ -e "$state/taskbar-${change%%:*}" ] || pending="$pending $change"
done
[ -n "$pending" ] || exit 0
diff --git a/packages/wildos-branding/files/libexec/taskbar-lights.js b/packages/wildos-branding/files/libexec/taskbar-lights.js
new file mode 100644
index 0000000..a6c8d36
--- /dev/null
+++ b/packages/wildos-branding/files/libexec/taskbar-lights.js
@@ -0,0 +1,44 @@
+// Puts the camera and microphone lights on a taskbar made before they
+// existed, just left of the security chip. New accounts get them from the
+// Wild OS layout, and a taskbar that has them already, or has no security
+// chip to sit beside, is left alone. taskbar-items runs this once per
+// account, on a running shell.
+panels().forEach(function (p) {
+ var chips = p.widgets("org.wildos.protected");
+ if (chips.length === 0 || p.widgets("org.wildos.lights").length > 0) {
+ return;
+ }
+ var chip = chips[0].geometry;
+ // Plasma's scripting can't say where in a panel a widget goes, but a
+ // panel puts one dropped on the right half of another just after it.
+ // The chip is too narrow to aim at its left half (the bar's coordinates
+ // sit a few pixels off the ones a drop is measured in), so the drop goes
+ // near the right end of whatever is before it: the spacer that centres
+ // the apps, which is wide.
+ var before = null;
+ var all = p.widgets();
+ for (var i = 0; i < all.length; i++) {
+ var g = all[i].geometry;
+ if (g.x + g.width <= chip.x + 2 && (before === null || g.x + g.width > before.x + before.width)) {
+ before = g;
+ }
+ }
+ if (before === null) {
+ return;
+ }
+ // The layout locks the bar, and Plasma adds nothing to a locked one.
+ var locked = p.locked;
+ p.locked = false;
+ var x = before.x + before.width - Math.min(12, before.width / 4);
+ // The size has to be given too: without one the position is ignored
+ // and the widget lands at the start of the bar.
+ var item = p.addWidget("org.wildos.lights", x, chip.y + chip.height / 2, 44, chip.height);
+ if (item) {
+ // Locked like the rest of the bar (see the layout), so it can't be
+ // removed or moved by accident.
+ item.currentConfigGroup = [];
+ item.writeConfig("immutability", 2);
+ item.locked = true;
+ }
+ p.locked = locked;
+});
diff --git a/packages/wildos-branding/files/libexec/update-status b/packages/wildos-branding/files/libexec/update-status
index 37c89e8..4e67639 100644
--- a/packages/wildos-branding/files/libexec/update-status
+++ b/packages/wildos-branding/files/libexec/update-status
@@ -10,24 +10,42 @@ Keys, in the order printed:
"na" in the live session or without PackageKit, with
why=live or why=missing after it.
"installing" and "checking" while anyone is doing it:
- Settings, the Store, this icon or apt's own timers.
- "error" when the last check from this icon failed and
- nothing has checked successfully since. "unchecked"
+ Settings, the Store, this icon or apt's own timers,
+ including the quiet waits between a check's tries.
+ "error" when the last check, from this icon or from
+ Settings > Updates, failed and nothing has checked
+ successfully since. "unchecked"
when the list has not been refreshed for a week, so
"current" would be a guess.
by=you|auto Who is installing or checking: "auto" is apt's daily
refresh and the automatic security updates.
+ waiting=yes|no The install is queued, or waiting for apt's lock or
+ the password, so nothing is downloading or installing
+ at this moment.
updates=N Updates ready to install, as Settings lists them.
security=N How many of those are security fixes.
checked=EPOCH When the list of updates was last refreshed; 0 if never.
restart=yes|no An installed update takes effect after a restart.
auto=on|off Security updates install by themselves.
- error=TEXT Why the last check failed, when state is error.
+ error=TEXT Why the last check failed, when state is error, in the
+ same words as Settings > Updates.
update-status check refreshes the list through PackageKit first, as
- Check now in Settings does, then reports.
+ Check now in Settings does, then reports. It tries
+ again quietly in the same cases as Settings, and
+ follows a check Settings is already running
+ instead of starting a second one.
+
+Settings > Updates and this script share one result in
+$XDG_RUNTIME_DIR/wildos-updates: "checking" names the process running a
+check (its pid, then its name, then "clock N" while it waits for sdwdate to
+set a clock at least N seconds behind), "failed" holds the last failed check (when
+the lists had last been refreshed as it failed, the reasons one per line,
+an empty line, then PackageKit's and apt's details). The failure stands
+until a refresh is newer than that, which holds however the clock moves. Whoever checks writes them, so both always show the same thing.
"""
+import calendar
import os
import re
import subprocess
@@ -47,19 +65,62 @@ TX = "org.freedesktop.PackageKit.Transaction"
ROLE_REFRESH_CACHE = 13
ROLE_UPDATE_PACKAGES = 22
ROLE_UPGRADE_SYSTEM = 33
+# A transaction queued behind another or waiting for apt's lock or the
+# password is not working yet.
+STATUS_WAIT = 1
+STATUS_WAITING_FOR_LOCK = 30
+STATUS_WAITING_FOR_AUTH = 31
+WAITING = (STATUS_WAIT, STATUS_WAITING_FOR_LOCK, STATUS_WAITING_FOR_AUTH)
INFO_IMPORTANT = 7
INFO_SECURITY = 8
INFO_BLOCKED = 9
EXIT_SUCCESS = 1
+EXIT_CANCELLED = 3
FILTER_NONE = 1 << 1
+ERROR_UNKNOWN = 0
ERROR_NO_NETWORK = 2
+ERROR_GPG_FAILURE = 5
+ERROR_PACKAGE_DOWNLOAD_FAILED = 10
+ERROR_TRANSACTION_CANCELLED = 17
ERROR_NO_CACHE = 18
ERROR_CANNOT_GET_LOCK = 26
+ERROR_BAD_GPG_SIGNATURE = 30
+ERROR_MISSING_GPG_SIGNATURE = 31
ERROR_REPO_NOT_AVAILABLE = 37
+ERROR_NO_MORE_MIRRORS_TO_TRY = 43
+ERROR_NO_SPACE_ON_DEVICE = 46
ERROR_NOT_AUTHORIZED = 48
+ERROR_CANNOT_UPDATE_REPO_UNSIGNED = 51
ERROR_CANNOT_FETCH_SOURCES = 64
ERROR_LOCK_REQUIRED = 67
+LOCK_ERRORS = (ERROR_CANNOT_GET_LOCK, ERROR_LOCK_REQUIRED)
+SIGNING_ERRORS = (ERROR_GPG_FAILURE, ERROR_BAD_GPG_SIGNATURE, ERROR_MISSING_GPG_SIGNATURE,
+ ERROR_CANNOT_UPDATE_REPO_UNSIGNED)
+CONNECTION_ERRORS = (ERROR_NO_NETWORK, ERROR_NO_CACHE, ERROR_REPO_NOT_AVAILABLE, ERROR_CANNOT_FETCH_SOURCES,
+ ERROR_PACKAGE_DOWNLOAD_FAILED, ERROR_NO_MORE_MIRRORS_TO_TRY)
+
+# NetworkManager's states that mean no connection: asleep, disconnected,
+# disconnecting and a link-local address only.
+NM_OFFLINE = (10, 20, 30, 50)
+
+# The same waits as Settings > Updates. A check that fails while the
+# connection, Tor or the clock is still settling tries again, after 5 s and
+# then less often, for about three minutes before it says why; in the first
+# five minutes after start-up any failure counts. apt's lock, held by the
+# automatic security updates, is waited out for half an hour.
+QUIET_RETRY = 3 * 60
+FIRST_RETRY = 5
+LONGEST_RETRY = 60
+SETTLING = 5 * 60
+LOCK_PATIENCE = 30 * 60
+LOCK_RETRY = 15
+# A clock sdwdate has yet to set is waited for this long at most, looking
+# every few seconds whether it has. Its first run after start-up took four
+# minutes on the PC this was seen on, with two onion sites timing out.
+CLOCK_WAIT = 15 * 60
+CLOCK_POLL = 2
+SDWDATE_SET = "/run/sdwdate/first_success"
LISTS = "/var/lib/apt/lists"
WEEK = 7 * 86400
@@ -69,11 +130,16 @@ state_dir = os.path.join(os.environ.get("XDG_STATE_HOME") or os.path.expanduser(
# The counts, kept until dpkg or the lists change, because asking PackageKit
# starts it and reads every package.
counts_file = os.path.join(runtime, "wildos-update-counts.%d" % os.getuid())
-# When PackageKit last refreshed the lists. It only knows while it runs, and
-# it stops when idle, so the last answer is kept.
+# When the list was last refreshed, by PackageKit or by a check that only
+# missed sources added by other software, which PackageKit does not record.
+# PackageKit only knows while it runs, and it stops when idle, so the last
+# answer is kept. Settings > Updates reads it too.
checked_file = os.path.join(state_dir, "updates-checked")
-# Why this icon's last check failed: the time, then the words.
-failed_file = os.path.join(state_dir, "updates-check-failed")
+# The result Settings > Updates and this script share (see above). In the
+# runtime folder, so a failure is forgotten at the next start-up.
+shared_dir = os.path.join(runtime, "wildos-updates")
+checking_file = os.path.join(shared_dir, "checking")
+failed_file = os.path.join(shared_dir, "failed")
def mtime(path):
@@ -102,6 +168,13 @@ def write_lines(path, lines):
pass
+def remove(path):
+ try:
+ os.remove(path)
+ except OSError:
+ pass
+
+
def number(text):
try:
return int(text)
@@ -130,9 +203,41 @@ def auto_updates():
return "on" if 'APT::Periodic::Unattended-Upgrade "1";' in result.stdout else "off"
+def system_property(bus, name, path, interface, prop):
+ try:
+ return bus.call_sync(name, path, "org.freedesktop.DBus.Properties", "Get",
+ GLib.Variant("(ss)", (interface, prop)), GLib.VariantType("(v)"),
+ Gio.DBusCallFlags.NO_AUTO_START, 3000, None)[0]
+ except GLib.Error:
+ return None
+
+
+def offline(bus):
+ """NetworkManager says there is no connection. Unknown when it is not
+ running, which counts as connected, as in Settings."""
+ state = system_property(bus, "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager",
+ "org.freedesktop.NetworkManager", "State")
+ return state in NM_OFFLINE
+
+
+def seconds_since_start(bus):
+ """Since start-up finished, not since the kernel started: the wait at the
+ disk password comes before Tor, sdwdate and the network even start."""
+ finished = system_property(bus, "org.freedesktop.systemd1", "/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager", "FinishTimestampMonotonic")
+ if finished:
+ return max(0, int(time.clock_gettime(time.CLOCK_MONOTONIC) - finished / 1e6))
+ try:
+ with open("/proc/uptime", encoding="utf-8") as f:
+ return int(float(f.read().split()[0]))
+ except (OSError, ValueError, IndexError):
+ return -1
+
+
class PackageKit:
def __init__(self):
self.bus = Gio.bus_get_sync(Gio.BusType.SYSTEM, None)
+ self.statuses = {}
def call(self, path, interface, method, args=None, reply=None, timeout=5000):
return self.bus.call_sync(PK, path, interface, method, args,
@@ -157,7 +262,9 @@ class PackageKit:
return False
def roles(self):
- """What the transactions running now are doing. Never starts PackageKit."""
+ """What the transactions running now are doing. Never starts PackageKit.
+ Their statuses, by role, are left in self.statuses."""
+ self.statuses = {}
if not self.running():
return []
roles = []
@@ -170,6 +277,9 @@ class PackageKit:
role = self.call(path, "org.freedesktop.DBus.Properties", "Get",
GLib.Variant("(ss)", (TX, "Role")), "(v)")[0]
roles.append(role)
+ status = self.call(path, "org.freedesktop.DBus.Properties", "Get",
+ GLib.Variant("(ss)", (TX, "Status")), "(v)")[0]
+ self.statuses.setdefault(role, []).append(status)
except GLib.Error:
pass
return roles
@@ -183,13 +293,13 @@ class PackageKit:
return seconds if seconds < 10 * 365 * 86400 else None
def transaction(self, method, args, on_package=None, timeout=60):
- """Runs one transaction to the end. Returns (succeeded, error code, details)."""
+ """Runs one transaction to the end. Returns (exit, error code, details)."""
loop = GLib.MainLoop()
outcome = {"exit": 0, "error": 0, "details": ""}
try:
path = self.call(PK_PATH, PK, "CreateTransaction", reply="(o)")[0]
except GLib.Error:
- return False, 0, ""
+ return 0, 0, ""
def signal(_bus, _sender, _path, _iface, name, params):
if name == "Package" and on_package:
@@ -209,11 +319,11 @@ class PackageKit:
self.call(path, TX, method, args)
except GLib.Error:
self.bus.signal_unsubscribe(sub)
- return False, 0, ""
+ return 0, 0, ""
GLib.timeout_add_seconds(timeout, loop.quit)
loop.run()
self.bus.signal_unsubscribe(sub)
- return outcome["exit"] == EXIT_SUCCESS, outcome["error"], outcome["details"]
+ return outcome["exit"], outcome["error"], outcome["details"]
def updates(self):
"""(updates, security fixes), as Settings counts them, or None."""
@@ -227,62 +337,329 @@ class PackageKit:
if info in (INFO_SECURITY, INFO_IMPORTANT):
found["security"] += 1
- ok, _, _ = self.transaction("GetUpdates", GLib.Variant("(t)", (FILTER_NONE,)), package, timeout=45)
- return (found["all"], found["security"]) if ok else None
+ result, _, _ = self.transaction("GetUpdates", GLib.Variant("(t)", (FILTER_NONE,)), package, timeout=45)
+ return (found["all"], found["security"]) if result == EXIT_SUCCESS else None
-def error_text(code):
- if code in (ERROR_NO_NETWORK, ERROR_NO_CACHE, ERROR_REPO_NOT_AVAILABLE, ERROR_CANNOT_FETCH_SOURCES):
- return "Wild OS could not reach the update servers. Check your internet connection and try again."
- if code == ERROR_NOT_AUTHORIZED:
- return "Checking needs the administrator password, and it was not given."
- if code in (ERROR_CANNOT_GET_LOCK, ERROR_LOCK_REQUIRED):
- return "Another app is installing software. Try again when it has finished."
- return "Wild OS could not check for updates. Try again in a few minutes."
+def hosts_in(path):
+ try:
+ with open(path, encoding="utf-8") as f:
+ return {h.lower() for h in re.findall(r"https?://([^/\s]+)", f.read())}
+ except OSError:
+ return set()
+
+
+def wildos_hosts():
+ """The servers Wild OS's own packages come from."""
+ return {"deb.wildos.io"} | hosts_in("/etc/apt/sources.list.d/wildos.sources")
def own_hosts():
- hosts = {"deb.wildos.io"}
- try:
- with open("/etc/apt/sources.list.d/wildos.sources", encoding="utf-8") as f:
- hosts.update(h.lower() for h in re.findall(r"https?://([^/\s]+)", f.read()))
- except OSError:
- pass
+ """Every server the system itself updates from: Wild OS's, and Debian's
+ and Kicksecure's, which Kicksecure lists in debian.sources and the image
+ in sources.list, mostly through Tor. Any other source was added by the
+ person or by an app's installer (Steam, Chrome, VS Code)."""
+ hosts = wildos_hosts() | {"deb.debian.org", "security.debian.org", "fasttrack.debian.net", "deb.kicksecure.com"}
+ for path in ("/etc/apt/sources.list.d/debian.sources", "/etc/apt/sources.list"):
+ hosts |= hosts_in(path)
return hosts
+ADDRESS = re.compile(r"(?:tor\+)?https?://([^/\s'\"]+)")
+
+
+def source_lines(details):
+ """apt's lines that name a source, without its notices about sources
+ that are fine, such as one without 32-bit packages on a PC with 32-bit
+ support turned on."""
+ return [line for line in details.splitlines()
+ if line.strip() and "Skipping acquire" not in line and "support architecture" not in line]
+
+
+def about_signing(line):
+ lower = line.lower()
+ return any(word.lower() in lower for word in (
+ "signature", "not signed", "NO_PUBKEY", "EXPKEYSIG", "Signing key", "OpenPGP", "not valid yet", "is expired"))
+
+
+def signed_later(line):
+ """A signature from after the time the clock shows. Right after start-up
+ sdwdate can set the clock back a minute or two, and a source signed in
+ that gap (Wild OS's, right after a release) fails until the clock passes
+ the signing time again. Seen as sqv's "created after the --not-after
+ date" and "Not live until <time>"; the second is also what a clock
+ hours behind gives (a PC whose hardware clock kept local time for
+ Windows)."""
+ lower = line.lower()
+ return "not-after" in line or "created after" in line or "not valid yet" in lower or "not live until" in lower
+
+
+def clock_problem(details):
+ return any(signed_later(line) for line in source_lines(details))
+
+
+STAMP = re.compile(r"not live until (\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ)", re.IGNORECASE)
+
+
+def seconds_behind(details):
+ """How far behind the clock is at least: the newest signing time apt
+ named that is still in the future. 0 when none is."""
+ newest = 0
+ for stamp in STAMP.findall(details):
+ try:
+ newest = max(newest, calendar.timegm(time.strptime(stamp, "%Y-%m-%dT%H:%M:%SZ")))
+ except ValueError:
+ pass
+ return max(0, newest - int(time.time())) if newest else 0
+
+
+def duration_text(seconds):
+ # Rounded down: the signing times only show the clock is at least this
+ # far behind.
+ def count(n, one, many):
+ return "%d %s" % (n, one if n == 1 else many)
+ if seconds >= 2 * 86400:
+ return count(seconds // 86400, "day", "days")
+ if seconds >= 3600:
+ return count(seconds // 3600, "hour", "hours")
+ return count(max(1, seconds // 60), "minute", "minutes")
+
+
+def secure_time_running():
+ result = subprocess.run(["systemctl", "is-active", "sdwdate.service"], capture_output=True, text=True)
+ return result.stdout.strip() in ("active", "activating", "reloading")
+
+
+def clock_being_set():
+ """sdwdate sets the clock through Tor a few minutes after start-up and
+ leaves this marker in /run once it has; until then a clock hours off is
+ still expected to be put right without anyone's help."""
+ return not os.path.exists(SDWDATE_SET) and secure_time_running()
+
+
+def through_tor(line):
+ """apt reaches Debian through Tor's SOCKS port; a Tor that is not running
+ or has not finished connecting fails every one of those sources."""
+ return "tor+http" in line or ":9050" in line
+
+
def only_others_failed(details):
"""True when every source apt named as failing was added by other
software (Steam's, with a signing key Debian no longer accepts).
PackageKit fails the whole refresh for one bad source though apt
refreshed the rest, and Settings > Updates counts that as checked."""
failed = set()
- for line in details.splitlines():
- # Notices name sources that are fine, such as one without 32-bit
- # packages on a PC with 32-bit support turned on.
- if "Skipping acquire" in line or "support architecture" in line:
- continue
- match = re.search(r"(?:tor\+)?https?://([^/\s'\"]+)", line)
+ for line in source_lines(details):
+ match = ADDRESS.search(line)
if match:
failed.add(match.group(1).lower())
return bool(failed) and not failed & own_hosts()
+def retry_quietly(bus, code, details):
+ """Whether a failed check is worth trying again by itself, as Settings
+ decides it: in the first minutes after start-up, or when the connection,
+ Tor or the clock was not ready. A refusal, a full disk or a bad
+ signature after that will not change, and with no connection at all
+ after start-up Settings says so at once."""
+ if code in (ERROR_NOT_AUTHORIZED, ERROR_TRANSACTION_CANCELLED, ERROR_NO_SPACE_ON_DEVICE) + LOCK_ERRORS:
+ return False
+ lines = source_lines(details)
+ up = seconds_since_start(bus)
+ settling = 0 <= up < SETTLING
+ is_offline = offline(bus)
+ if is_offline and not settling:
+ return False
+ # apt's lines for a signature from the future include one that only says
+ # verification failed, so one line naming the time is enough, and
+ # PackageKit may still call it a signing error.
+ clock_behind = any(signed_later(line) for line in lines)
+ signing = not clock_behind and (code in SIGNING_ERRORS or any(about_signing(line) for line in lines))
+ connection = (code in CONNECTION_ERRORS or any(through_tor(line) for line in lines)
+ or is_offline or clock_behind)
+ return settling or (connection and not signing)
+
+
+def why_failed(bus, code, details):
+ """Why a check failed, one line for each likely cause, in the words
+ Settings > Updates uses."""
+ if code == ERROR_NOT_AUTHORIZED:
+ return ["Checking needs the administrator password, and it was not given."]
+ if code in LOCK_ERRORS:
+ return ["Another install is still running, such as the automatic security updates. Try again when it has finished."]
+ if code == ERROR_NO_SPACE_ON_DEVICE:
+ return ["There is not enough free space to check for updates."]
+ if offline(bus) or code == ERROR_NO_NETWORK:
+ return ["This computer is not connected to the internet."]
+ # A clock far behind fails every source, so it is the one reason given.
+ behind = seconds_behind(details) if clock_problem(details) else 0
+ if behind >= 60:
+ return ["The clock on this computer is at least %s behind, so the updates look as if they "
+ "were signed in the future." % duration_text(behind),
+ "Wild OS sets the clock through Tor after start-up and has not managed to yet. "
+ "Set the date and time in Settings > Date and time, then try again." if clock_being_set()
+ else "Set the date and time in Settings > Date and time, then try again."]
+ wildos = wildos_hosts()
+ own = own_hosts()
+ lines = source_lines(details)
+ # Every server reached directly failing to resolve is no internet at
+ # all, though NetworkManager still has a connection (a router with no
+ # line behind it).
+ unresolved = set()
+ failed_otherwise = False
+ for line in lines:
+ match = ADDRESS.search(line)
+ if not match or through_tor(line):
+ continue
+ if "Temporary failure resolving" in line or "Could not resolve" in line:
+ unresolved.add(match.group(1).lower())
+ else:
+ failed_otherwise = True
+ if len(unresolved) >= 2 and not failed_otherwise:
+ return ["This computer is not connected to the internet."]
+ wildos_down = debian_down = tor_down = False
+ signing = code in SIGNING_ERRORS
+ for line in lines:
+ match = ADDRESS.search(line)
+ host = match.group(1).lower() if match else ""
+ if about_signing(line):
+ signing = signing or not host or host in own
+ elif through_tor(line):
+ tor_down = True
+ elif host in wildos:
+ wildos_down = True
+ elif host in own:
+ debian_down = True
+ reasons = []
+ if wildos_down:
+ reasons.append("Wild OS's update server could not be reached.")
+ if tor_down:
+ # Long after start-up, waiting for Tor is no longer the likely fix.
+ up = seconds_since_start(bus)
+ if 0 <= up < 2 * SETTLING:
+ reasons.append("Debian's updates could not be reached through Tor. "
+ "Tor can take a few minutes to connect after start-up.")
+ else:
+ reasons.append("Debian's updates could not be reached through Tor.")
+ elif debian_down:
+ reasons.append("Debian's update servers could not be reached.")
+ if signing:
+ reasons.append("The updates' signatures could not be checked. "
+ "This happens when the date and time on this computer are wrong.")
+ if not reasons:
+ if code in (ERROR_NO_CACHE, ERROR_REPO_NOT_AVAILABLE, ERROR_CANNOT_FETCH_SOURCES, ERROR_PACKAGE_DOWNLOAD_FAILED):
+ reasons.append("The update servers could not be reached. Check your internet connection.")
+ else:
+ reasons.append("Something went wrong while checking. Try again in a few minutes.")
+ return reasons
+
+
+def alive(pid, name):
+ try:
+ with open("/proc/%d/comm" % pid, encoding="utf-8") as f:
+ return f.read().strip() == name
+ except OSError:
+ return False
+
+
+def checker():
+ """The pid of a process running a check now, from this script or
+ Settings, or 0. A checker that quit or crashed no longer counts."""
+ lines = read_lines(checking_file)
+ pid = number(lines[0]) if lines else 0
+ return pid if pid > 0 and len(lines) > 1 and alive(pid, lines[1]) else 0
+
+
+def my_name():
+ try:
+ with open("/proc/self/comm", encoding="utf-8") as f:
+ return f.read().strip()
+ except OSError:
+ return "update-status"
+
+
+def record_failure(pk, reasons, details):
+ # Takes in PackageKit's own record first, so it cannot clear the
+ # failure later.
+ last_checked(pk)
+ write_lines(failed_file, [refreshed_on_disk()] + reasons + [""] + details.strip().splitlines())
+
+
def check(pk):
- ok, code, details = pk.transaction("RefreshCache", GLib.Variant("(b)", (True,)), timeout=600)
- if ok or only_others_failed(details):
- try:
- os.remove(failed_file)
- except OSError:
- pass
- write_lines(checked_file, [int(time.time())])
- else:
- write_lines(failed_file, [int(time.time()), error_text(code)])
+ # One check at a time: when Settings is already checking, its result is
+ # this one's too.
+ other = checker()
+ if other and other != os.getpid():
+ while checker():
+ time.sleep(2)
+ return
+ write_lines(checking_file, [os.getpid(), my_name()])
+ try:
+ refresh_until_done(pk)
+ finally:
+ remove(checking_file)
+
+
+def wait_for_clock(behind, since):
+ """Waits while sdwdate sets the clock, saying so in the checking file
+ (a third line, "clock" and the seconds behind) for Settings to show."""
+ write_lines(checking_file, [os.getpid(), my_name(), "clock %d" % max(behind, 1)])
+ while clock_being_set() and time.monotonic() - since < CLOCK_WAIT:
+ time.sleep(CLOCK_POLL)
+ write_lines(checking_file, [os.getpid(), my_name()])
+
+
+def refresh_until_done(pk):
+ quiet_since = None
+ lock_since = None
+ clock_since = None
+ delay = FIRST_RETRY
+ while True:
+ # With no connection at all a refresh waits minutes on Tor before it
+ # fails, so it is not started.
+ if offline(pk.bus):
+ result, code, details = 0, ERROR_NO_NETWORK, ""
+ else:
+ result, code, details = pk.transaction("RefreshCache", GLib.Variant("(b)", (True,)), timeout=600)
+ if result == EXIT_SUCCESS or (code and only_others_failed(details)):
+ remove(failed_file)
+ write_lines(checked_file, [int(time.time())])
+ return
+ if result == EXIT_CANCELLED and code not in LOCK_ERRORS:
+ record_failure(pk, ["The check was cancelled."], details)
+ return
+ if code in LOCK_ERRORS:
+ lock_since = lock_since or time.monotonic()
+ if time.monotonic() - lock_since < LOCK_PATIENCE:
+ time.sleep(LOCK_RETRY)
+ continue
+ print("Update check failed: PackageKit error %d %s" % (code, details.strip()), file=sys.stderr)
+ # A clock hours behind stays so until sdwdate sets it through Tor,
+ # so the check waits for that rather than for a fixed time.
+ if clock_problem(details) and clock_being_set():
+ clock_since = clock_since or time.monotonic()
+ if time.monotonic() - clock_since < CLOCK_WAIT:
+ wait_for_clock(seconds_behind(details), clock_since)
+ # The usual quiet retries start over: sdwdate's first
+ # setting can leave the clock a moment before a source
+ # signed just now.
+ quiet_since = None
+ delay = FIRST_RETRY
+ continue
+ if retry_quietly(pk.bus, code, details):
+ quiet_since = quiet_since or time.monotonic()
+ if time.monotonic() - quiet_since + delay <= QUIET_RETRY:
+ time.sleep(delay)
+ delay = min(delay * 2, LONGEST_RETRY)
+ continue
+ record_failure(pk, why_failed(pk.bus, code, details),
+ "PackageKit error %d%s" % (code, "\n" + details if details.strip() else ""))
+ return
-def last_checked(pk):
- # apt's own refreshes (the daily timer) leave the lists' times and apt's
- # stamp; PackageKit's leave its record, which is the one Settings shows.
+def refreshed_on_disk():
+ """apt's own refreshes (the daily timer) leave the lists' times and
+ apt's stamp, and checks through PackageKit the checked file."""
checked = mtime("/var/lib/apt/periodic/update-success-stamp")
try:
for name in os.listdir(LISTS):
@@ -290,13 +667,20 @@ def last_checked(pk):
checked = max(checked, mtime(os.path.join(LISTS, name)))
except OSError:
pass
+ return max(checked, number((read_lines(checked_file) or ["0"])[0]))
+
+
+def last_checked(pk):
+ # PackageKit's record is the one Settings shows.
+ checked = refreshed_on_disk()
known = number((read_lines(checked_file) or ["0"])[0])
if pk.running() or known == 0:
seconds = pk.seconds_since_refresh()
if seconds is not None:
at = int(time.time()) - seconds
- # Within a minute is the same answer again.
- if abs(at - known) > 60:
+ # Within a minute is the same answer again; an older one is a
+ # check that only missed other software's sources.
+ if at > known + 60:
known = at
write_lines(checked_file, [known])
return max(checked, known)
@@ -317,11 +701,14 @@ def main():
check(pk)
roles = pk.roles()
+ waiting = False
if unit_busy("apt-daily-upgrade.service"):
busy, by = "installing", "auto"
elif ROLE_UPDATE_PACKAGES in roles or ROLE_UPGRADE_SYSTEM in roles:
busy, by = "installing", "you"
- elif ROLE_REFRESH_CACHE in roles:
+ statuses = pk.statuses.get(ROLE_UPDATE_PACKAGES, []) + pk.statuses.get(ROLE_UPGRADE_SYSTEM, [])
+ waiting = len(statuses) > 0 and all(st in WAITING for st in statuses)
+ elif ROLE_REFRESH_CACHE in roles or checker():
busy, by = "checking", "you"
elif unit_busy("apt-daily.service"):
busy, by = "checking", "auto"
@@ -343,8 +730,14 @@ def main():
write_lines(counts_file, [key, "%d %d" % answer])
failed = read_lines(failed_file)
- failed_at = number(failed[0]) if failed else 0
- error = failed[1] if len(failed) > 1 and failed_at > checked else ""
+ refreshed_before = number(failed[0]) if failed else 0
+ reasons = []
+ for line in failed[1:]:
+ if not line:
+ break
+ reasons.append(line)
+ # Nothing has refreshed the lists since the check failed.
+ error = " ".join(reasons) if reasons and refreshed_on_disk() <= refreshed_before else ""
if busy:
state = busy
@@ -361,6 +754,7 @@ def main():
print("state=" + state)
print("by=" + by)
+ print("waiting=" + ("yes" if waiting else "no"))
print("updates=%d" % updates)
print("security=%d" % security)
print("checked=%d" % checked)
diff --git a/packages/wildos-branding/files/libexec/usb-devices b/packages/wildos-branding/files/libexec/usb-devices
index cd19754..27b7d2f 100644
--- a/packages/wildos-branding/files/libexec/usb-devices
+++ b/packages/wildos-branding/files/libexec/usb-devices
@@ -85,7 +85,10 @@ case $1 in
mkfifo -m 600 "$fifo" || exit 1
udevadm monitor --udev --subsystem-match=usb/usb_device > "$fifo" 2>/dev/null &
monitor=$!
- timeout 600 grep -q -m1 '^UDEV' < "$fifo"
+ # Events start "UDEV [": udevadm's own heading line also starts with
+ # UDEV, and matching it made this return at once, so the taskbar
+ # restarted the watch and rescanned every device each second.
+ timeout 600 grep -q -m1 '^UDEV *\[' < "$fifo"
kill "$monitor" 2>/dev/null
rm -f "$fifo"
# USBGuard rules on a new device a moment after udev announces it.
diff --git a/packages/wildos-branding/files/look-and-feel/contents/defaults b/packages/wildos-branding/files/look-and-feel/contents/defaults
index c715b4e..110bf12 100644
--- a/packages/wildos-branding/files/look-and-feel/contents/defaults
+++ b/packages/wildos-branding/files/look-and-feel/contents/defaults
@@ -24,7 +24,7 @@ ShowToolTips=false
LayoutName=org.wildos.switcher
[kcminputrc][Mouse]
-cursorTheme=breeze_cursors
+cursorTheme=Breeze_Light
[ksplashrc][KSplash]
Engine=KSplashQML
diff --git a/packages/wildos-branding/files/look-and-feel/contents/layouts/org.kde.plasma.desktop-layout.js b/packages/wildos-branding/files/look-and-feel/contents/layouts/org.kde.plasma.desktop-layout.js
index 5b9657c..767a72b 100644
--- a/packages/wildos-branding/files/look-and-feel/contents/layouts/org.kde.plasma.desktop-layout.js
+++ b/packages/wildos-branding/files/look-and-feel/contents/layouts/org.kde.plasma.desktop-layout.js
@@ -1,7 +1,8 @@
// The Wild OS desktop: the taskbar docked along the bottom, Windows mode's
// status at the left end (it takes no room until Windows mode is set up),
-// Start and the apps centred on the screen, and the security chip, the
-// Updates icon, a divider, quick settings and the clock at the right end. Sizes follow the Taskbar artboard
+// Start and the apps centred on the screen, and the camera and microphone
+// lights, the security chip, the Updates icon, a divider, quick settings and
+// the clock at the right end. Sizes follow the Taskbar artboard
// in the design. Settings > Personalisation can switch it to floating glass
// pills instead.
//
@@ -74,7 +75,11 @@ var rightSpacer = bar.addWidget("org.kde.plasma.panelspacer");
rightSpacer.currentConfigGroup = ["General"];
rightSpacer.writeConfig("expanding", "true");
+// The camera and microphone lights, left of the shield. They take no room
+// until an app uses one or one is switched off.
+bar.addWidget("org.wildos.lights");
bar.addWidget("org.wildos.protected");
+// Only there while an update downloads or installs.
bar.addWidget("org.wildos.updates");
// The design leaves 2 px between items in the status pill against the
diff --git a/packages/wildos-branding/files/look-and-feel/contents/lockscreen/LockNotifications.qml b/packages/wildos-branding/files/look-and-feel/contents/lockscreen/LockNotifications.qml
new file mode 100644
index 0000000..7b950bc
--- /dev/null
+++ b/packages/wildos-branding/files/look-and-feel/contents/lockscreen/LockNotifications.qml
@@ -0,0 +1,97 @@
+pragma Singleton
+
+import QtQuick
+import QtCore
+import org.kde.notificationmanager as NotificationManager
+
+// Notifications that arrive while the screen is locked. Plasma's popups never
+// reach a locked screen (KWin shows only the greeter there), so the lock
+// screen asks Plasma's notification server for a copy of each one, through
+// the watcher interface it offers for exactly this (Plasma Mobile's lock
+// screen uses it). One copy for every screen, since the server talks to one
+// watcher per process.
+//
+// "Quiet lock screen" (Settings > Privacy and security > Advanced protection,
+// quiet_lock in /etc/wildos/advanced-protection, on unless set to off) keeps
+// only the app's name and icon: the title and text are dropped as they arrive,
+// so they are never in the lock screen's memory, let alone on it.
+QtObject {
+ id: tally
+
+ readonly property bool quiet: store.value("quiet_lock", "on") !== "off"
+
+ // Newest first: notificationId, appName, iconName, and in full mode
+ // summary and body.
+ readonly property ListModel arrived: ListModel {}
+
+ readonly property var appIcons: {
+ const seen = [];
+ for (let i = 0; i < arrived.count && seen.length < 3; i++) {
+ const icon = arrived.get(i).iconName;
+ if (seen.indexOf(icon) < 0)
+ seen.push(icon);
+ }
+ return seen;
+ }
+
+ readonly property Settings store: Settings {
+ location: "file:///etc/wildos/advanced-protection"
+ }
+
+ readonly property NotificationManager.WatchedNotificationsModel watcher: NotificationManager.WatchedNotificationsModel {}
+
+ function role(row, name) {
+ return watcher.data(watcher.index(row, 0), NotificationManager.Notifications[name]);
+ }
+
+ function entry(row) {
+ const icon = role(row, "ApplicationIconNameRole") || role(row, "IconNameRole") || "preferences-desktop-notification-bell";
+ const item = {
+ notificationId: role(row, "IdRole"),
+ appName: role(row, "ApplicationNameRole") || "",
+ iconName: icon,
+ summary: "",
+ body: "",
+ };
+ if (!quiet) {
+ item.summary = role(row, "SummaryRole") || "";
+ item.body = role(row, "BodyRole") || "";
+ }
+ return item;
+ }
+
+ function indexOf(notificationId) {
+ for (let i = 0; i < arrived.count; i++) {
+ if (arrived.get(i).notificationId === notificationId)
+ return i;
+ }
+ return -1;
+ }
+
+ // The watcher drops a notification when its popup would have timed out,
+ // so what arrived is kept here instead, for as long as the screen stays
+ // locked. An app that updates a notification (a download, a chat) changes
+ // its entry rather than adding another.
+ readonly property Connections watcherEvents: Connections {
+ target: tally.watcher
+
+ function onRowsInserted(parent, first, last) {
+ for (let row = first; row <= last; row++) {
+ const item = tally.entry(row);
+ const at = tally.indexOf(item.notificationId);
+ if (at >= 0)
+ tally.arrived.remove(at);
+ tally.arrived.insert(0, item);
+ }
+ }
+
+ function onDataChanged(topLeft, bottomRight) {
+ for (let row = topLeft.row; row <= bottomRight.row; row++) {
+ const item = tally.entry(row);
+ const at = tally.indexOf(item.notificationId);
+ if (at >= 0)
+ tally.arrived.set(at, item);
+ }
+ }
+ }
+}
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 ca6f5db..81ec988 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
@@ -251,6 +251,13 @@ Item {
y: Math.round(lockScreenRoot.height * 96 / 900) + mainStack.y
}
+ LockNotices {
+ anchors.horizontalCenter: parent.horizontalCenter
+ y: clock.y + clock.height + 20
+ backdrop: lockScreenUi.backdrop
+ availableHeight: mainStack.y + mainBlock.contentTop - y - 20
+ }
+
StackView {
id: mainStack
diff --git a/packages/wildos-branding/files/look-and-feel/contents/lockscreen/MainBlock.qml b/packages/wildos-branding/files/look-and-feel/contents/lockscreen/MainBlock.qml
index 85b475e..7a4418b 100644
--- a/packages/wildos-branding/files/look-and-feel/contents/lockscreen/MainBlock.qml
+++ b/packages/wildos-branding/files/look-and-feel/contents/lockscreen/MainBlock.qml
@@ -35,6 +35,8 @@ FocusScope {
// How far down the screen the virtual keyboard must leave visible.
readonly property real visibleBoundary: column.y + pill.y + pill.height + 12
+ // Where the avatar starts, so what sits above can keep clear of it.
+ readonly property real contentTop: column.y
signal passwordResult(string password)
signal switchUserRequested()
diff --git a/packages/wildos-branding/files/look-and-feel/contents/lockscreen/components/LockNotices.qml b/packages/wildos-branding/files/look-and-feel/contents/lockscreen/components/LockNotices.qml
new file mode 100644
index 0000000..72a60d0
--- /dev/null
+++ b/packages/wildos-branding/files/look-and-feel/contents/lockscreen/components/LockNotices.qml
@@ -0,0 +1,161 @@
+import QtQuick
+import org.kde.kirigami as Kirigami
+import WildOS.UI as UI
+
+import ".."
+
+// What arrived while the screen was locked, under the clock. With "Quiet lock
+// screen" on, one glass pill: the apps' icons and how many arrived. With it
+// off, the newest as cards with the app, title and text, as many as fit above
+// the sign-in block, then how many more.
+Item {
+ id: notices
+
+ property Item backdrop: null
+ // The room left between the clock and the sign-in block.
+ property real availableHeight: 0
+
+ readonly property int count: LockNotifications.arrived.count
+ readonly property int cardHeight: 72
+ readonly property int cardsShown: LockNotifications.quiet ? 0
+ : Math.max(1, Math.min(3, count, Math.floor((availableHeight - 24 + 8) / (cardHeight + 8))))
+
+ implicitWidth: 400
+ implicitHeight: count === 0 ? 0 : LockNotifications.quiet ? 40 : content.implicitHeight
+ visible: count > 0
+
+ Accessible.role: Accessible.StaticText
+ Accessible.name: summaryText
+
+ readonly property string summaryText: count === 1 ? "1 new notification" : count + " new notifications"
+
+ Item {
+ id: pill
+ visible: LockNotifications.quiet
+ anchors.horizontalCenter: parent.horizontalCenter
+ width: pillRow.implicitWidth + 28
+ height: 40
+
+ Glass {
+ anchors.fill: parent
+ backdrop: notices.backdrop
+ tint: UI.Style.glassOnWallpaper
+ blurRadius: 64
+ }
+
+ Row {
+ id: pillRow
+ anchors.centerIn: parent
+ spacing: 8
+
+ Row {
+ anchors.verticalCenter: parent.verticalCenter
+ spacing: 4
+
+ Repeater {
+ model: LockNotifications.appIcons
+ Kirigami.Icon {
+ required property string modelData
+ width: 18
+ height: 18
+ source: modelData
+ fallback: "preferences-desktop-notification-bell"
+ }
+ }
+ }
+
+ UI.Label {
+ anchors.verticalCenter: parent.verticalCenter
+ text: notices.summaryText
+ color: UI.Style.inkOnWallpaper
+ }
+ }
+ }
+
+ Column {
+ id: content
+ visible: !LockNotifications.quiet
+ width: parent.width
+ spacing: 8
+
+ Repeater {
+ model: LockNotifications.arrived
+
+ Item {
+ id: card
+
+ required property int index
+ required property string appName
+ required property string iconName
+ required property string summary
+ required property string body
+
+ visible: index < notices.cardsShown
+ width: content.width
+ height: visible ? notices.cardHeight : 0
+
+ Glass {
+ anchors.fill: parent
+ backdrop: notices.backdrop
+ tint: UI.Style.glassOnWallpaperField
+ radius: 18
+ blurRadius: 64
+ }
+
+ Kirigami.Icon {
+ id: appIcon
+ anchors.left: parent.left
+ anchors.leftMargin: 16
+ anchors.top: parent.top
+ anchors.topMargin: 14
+ width: 20
+ height: 20
+ source: card.iconName
+ fallback: "preferences-desktop-notification-bell"
+ }
+
+ Column {
+ anchors.left: appIcon.right
+ anchors.leftMargin: 10
+ anchors.right: parent.right
+ anchors.rightMargin: 16
+ anchors.verticalCenter: parent.verticalCenter
+ spacing: 1
+
+ UI.Label {
+ width: parent.width
+ visible: text.length > 0
+ text: card.appName
+ size: 12
+ color: UI.Style.inkOnWallpaperMuted
+ }
+ UI.Label {
+ width: parent.width
+ visible: text.length > 0
+ text: card.summary
+ font.weight: UI.Style.weightSemiBold
+ color: UI.Style.inkOnWallpaper
+ }
+ UI.Label {
+ width: parent.width
+ visible: text.length > 0
+ // The server has already cut the body down to the
+ // few tags notifications may use.
+ textFormat: Text.StyledText
+ text: card.body
+ size: 12
+ color: UI.Style.inkOnWallpaper
+ }
+ }
+ }
+ }
+
+ UI.Label {
+ anchors.horizontalCenter: parent.horizontalCenter
+ visible: notices.count > notices.cardsShown
+ text: notices.count - notices.cardsShown + " more"
+ size: 12
+ color: UI.Style.inkOnWallpaperMuted
+ }
+ }
+}
diff --git a/packages/wildos-branding/files/look-and-feel/contents/lockscreen/components/PasswordPill.qml b/packages/wildos-branding/files/look-and-feel/contents/lockscreen/components/PasswordPill.qml
index 2b36c39..da7b13b 100644
--- a/packages/wildos-branding/files/look-and-feel/contents/lockscreen/components/PasswordPill.qml
+++ b/packages/wildos-branding/files/look-and-feel/contents/lockscreen/components/PasswordPill.qml
@@ -70,6 +70,7 @@ FocusScope {
font.letterSpacing: pill.secret && text.length > 0 ? 1.5 : 0
echoMode: pill.secret ? TextInput.Password : TextInput.Normal
passwordCharacter: "•"
+ UI.NoPaste { enabled: pill.secret }
placeholderText: pill.placeholder
placeholderTextColor: UI.Style.inkOnWallpaperMuted
inputMethodHints: pill.secret ? (Qt.ImhHiddenText | Qt.ImhSensitiveData | Qt.ImhNoAutoUppercase | Qt.ImhNoPredictiveText)
diff --git a/packages/wildos-branding/files/look-and-feel/contents/lockscreen/qmldir b/packages/wildos-branding/files/look-and-feel/contents/lockscreen/qmldir
index 2252a06..aa052fd 100644
--- a/packages/wildos-branding/files/look-and-feel/contents/lockscreen/qmldir
+++ b/packages/wildos-branding/files/look-and-feel/contents/lockscreen/qmldir
@@ -1,4 +1,5 @@
singleton PasswordSync 1.0 PasswordSync.qml
+singleton LockNotifications 1.0 LockNotifications.qml
LockScreen 1.0 LockScreen.qml
LockScreenUi 1.0 LockScreenUi.qml
MainBlock 1.0 MainBlock.qml
diff --git a/packages/wildos-branding/files/look-and-feel/contents/splash/Splash.qml b/packages/wildos-branding/files/look-and-feel/contents/splash/Splash.qml
index 351154d..66bca82 100644
--- a/packages/wildos-branding/files/look-and-feel/contents/splash/Splash.qml
+++ b/packages/wildos-branding/files/look-and-feel/contents/splash/Splash.qml
@@ -36,27 +36,79 @@ Item {
// wallpaper framed as the desktop frames it, no scrim) is the one that
// fades.
property bool played: false
+ // Plasma has drawn the desktop under this window, taskbar and Start's
+ // unseen first draw included (Session.desktopReady in wildos-shell).
+ // After a boot the W then opens onto it, so by the end of the flight
+ // there is nothing left to fade in. Plasma's own "desktop" stage comes
+ // before the taskbar has loaded, so it is not enough on its own.
+ readonly property bool live: desktopReady.registered
+
+ DBus.DBusServiceWatcher {
+ id: desktopReady
+ busType: DBus.BusType.Session
+ watchedService: "org.wildos.shell.DesktopReady"
+ }
+ readonly property bool showingDesktop: live && (booting || played)
+ // Same decode as the start-up animation's photo, so the two share it.
+ readonly property real dpr: Screen.devicePixelRatio > 0 ? Screen.devicePixelRatio : 1
+ readonly property int photoDecodeWidth: Math.ceil(1.18 * Math.max(width * dpr, height * dpr * 16 / 9))
function reveal() {
- if (stage >= readyStage && !booting && !fadeOut.running && content.opacity > 0)
- fadeOut.start();
+ if (stage < readyStage || booting || fadeOut.running || content.opacity <= 0)
+ return;
+ if (played) {
+ // The desktop is showing through: nothing left to uncover. Until
+ // then the photo stays and the backdrop crossfades onto the
+ // desktop when it is ready, unless that never came.
+ if (backdrop.opacity === 0)
+ content.opacity = 0;
+ else if (!showingDesktop && doneSent)
+ fadeOut.start();
+ return;
+ }
+ fadeOut.start();
+ }
+
+ // Tells splash-hold the splash can close. After the animation that is
+ // once the desktop is actually showing, so closing never cuts off the
+ // crossfade onto it; if the desktop never says it is ready, a little
+ // later anyway.
+ property bool doneSent: false
+ function sendDone() {
+ if (doneSent)
+ return;
+ doneSent = true;
+ DBus.SessionBus.asyncCall({
+ service: "org.freedesktop.systemd1",
+ path: "/org/freedesktop/systemd1",
+ iface: "org.freedesktop.systemd1.Manager",
+ member: "StartUnit",
+ arguments: [new DBus.string("wildos-splash-done.target"), new DBus.string("replace")],
+ signature: "(ss)"
+ });
+ reveal();
+ }
+ function maybeDone() {
+ if (played && !booting && backdrop.opacity === 0)
+ sendDone();
+ }
+ Timer {
+ id: doneFallback
+ interval: 3000
+ onTriggered: root.sendDone()
}
onStageChanged: reveal()
+ onLiveChanged: reveal()
onBootingChanged: {
if (booting) {
played = true;
return;
}
- if (played)
- DBus.SessionBus.asyncCall({
- service: "org.freedesktop.systemd1",
- path: "/org/freedesktop/systemd1",
- iface: "org.freedesktop.systemd1.Manager",
- member: "StartUnit",
- arguments: [new DBus.string("wildos-splash-done.target"), new DBus.string("replace")],
- signature: "(ss)"
- });
+ if (played) {
+ maybeDone();
+ doneFallback.start();
+ }
reveal();
}
@@ -65,33 +117,50 @@ Item {
anchors.fill: parent
// Inside what fades, so the fade uncovers the desktop rather than a
- // dark screen.
- Rectangle {
+ // dark screen. Gives way to the desktop as soon as it is drawn, in
+ // case the flight ended before it was.
+ Item {
+ id: backdrop
anchors.fill: parent
- color: "#000000"
- }
+ opacity: root.showingDesktop ? 0 : 1
+ visible: opacity > 0
+ onOpacityChanged: root.maybeDone()
+ // Long enough for the desktop to paint its wallpaper underneath:
+ // it draws its first full frame only once something above it lets
+ // it show, about a third of a second on software rendering.
+ Behavior on opacity {
+ NumberAnimation { duration: 400; easing.type: Easing.InOutQuad }
+ }
- Image {
- id: photo
-
- readonly property real coverScale: implicitWidth > 0
- ? Math.max(root.width / implicitWidth, root.height / implicitHeight) : 1
-
- // Framed as the desktop frames its wallpaper after a boot, as the
- // sign-in screen frames it otherwise.
- width: implicitWidth * coverScale
- height: implicitHeight * coverScale
- x: (root.width - width) / 2
- y: (root.height - height) * (root.played ? 0.5 : 0.45)
- source: "file://" + root.wallpaper
- asynchronous: false
- smooth: true
- }
+ Rectangle {
+ anchors.fill: parent
+ color: "#000000"
+ }
- Rectangle {
- anchors.fill: parent
- visible: !root.played
- color: Qt.rgba(15 / 255, 17 / 255, 21 / 255, 0.22)
+ Image {
+ id: photo
+
+ readonly property real coverScale: implicitWidth > 0
+ ? Math.max(root.width / implicitWidth, root.height / implicitHeight) : 1
+
+ // Framed as the desktop frames its wallpaper after a boot, as
+ // the sign-in screen frames it otherwise.
+ width: implicitWidth * coverScale
+ height: implicitHeight * coverScale
+ x: (root.width - width) / 2
+ y: (root.height - height) * (root.played ? 0.5 : 0.45)
+ source: "file://" + root.wallpaper
+ sourceSize.width: root.photoDecodeWidth
+ asynchronous: false
+ cache: true
+ smooth: true
+ }
+
+ Rectangle {
+ anchors.fill: parent
+ visible: !root.played
+ color: Qt.rgba(15 / 255, 17 / 255, 21 / 255, 0.22)
+ }
}
// Installed with the sign-in screen by the same package.
@@ -103,9 +172,17 @@ Item {
photoSource: photo.source,
photoItem: photo,
photoFocus: 0.5,
- scrim: false
+ scrim: false,
+ endOnLanding: true
})
}
+
+ Binding {
+ target: handoff.item
+ property: "live"
+ value: root.live
+ when: handoff.status === Loader.Ready
+ }
}
SequentialAnimation {
diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.lights/contents/ui/Glyphs.qml b/packages/wildos-branding/files/plasmoids/org.wildos.lights/contents/ui/Glyphs.qml
new file mode 100644
index 0000000..5c0d8e1
--- /dev/null
+++ b/packages/wildos-branding/files/plasmoids/org.wildos.lights/contents/ui/Glyphs.qml
@@ -0,0 +1,11 @@
+pragma Singleton
+
+import QtQuick
+
+// The board's line icons (TaskbarCamMic.dc), on a 24 px grid.
+QtObject {
+ readonly property string mic: "M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3zM19 10v2a7 7 0 0 1-14 0v-2M12 19v3"
+ readonly property string micOff: "M2 2l20 20M18.89 13.23A7.12 7.12 0 0 0 19 12v-2M5 10v2a7 7 0 0 0 12 5M15 9.34V5a3 3 0 0 0-5.68-1.33M9 9v3a3 3 0 0 0 5.12 2.12M12 19v3"
+ readonly property string camera: "M16 13l5.223 3.482a0.5 0.5 0 0 0 0.777-0.416V7.87a0.5 0.5 0 0 0-0.752-0.432L16 10.5M4 6h10a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2z"
+ readonly property string cameraOff: "M10.66 6H14a2 2 0 0 1 2 2v2.5l5.248-3.062A0.5 0.5 0 0 1 22 7.87v8.196M16 16a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h2M2 2l20 20"
+}
diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.lights/contents/ui/Light.qml b/packages/wildos-branding/files/plasmoids/org.wildos.lights/contents/ui/Light.qml
new file mode 100644
index 0000000..b34c6c0
--- /dev/null
+++ b/packages/wildos-branding/files/plasmoids/org.wildos.lights/contents/ui/Light.qml
@@ -0,0 +1,101 @@
+import QtQuick
+import QtQuick.Layouts
+import WildOS.UI as UI
+
+// The taskbar light: a 36 px tall pill, 10 px padding, its device's colour
+// at 20% behind a 17 px icon and a 7 px dot, amber for the microphone and
+// green for the camera; both pills when both are in use. A device switched
+// off for every app, and not in use, shows its struck-through icon in a
+// plain 32 px cell like the shield's, so the switch can be found again.
+MouseArea {
+ id: light
+
+ required property var lights
+
+ property bool wasExpanded: false
+
+ readonly property var pills: [
+ { name: "microphone", on: lights.micInUse, off: lights.microphone.blocked, color: lights.amber, path: Glyphs.mic, offPath: Glyphs.micOff },
+ { name: "camera", on: lights.cameraInUse, off: lights.camera.blocked, color: lights.green, path: Glyphs.camera, offPath: Glyphs.cameraOff }
+ ].filter(p => p.on || p.off)
+
+ Layout.minimumWidth: lights.shown ? row.implicitWidth : 0
+ Layout.preferredWidth: Layout.minimumWidth
+ Layout.maximumWidth: Layout.minimumWidth
+ Layout.minimumHeight: 44
+
+ hoverEnabled: true
+ Accessible.role: Accessible.Button
+ Accessible.name: lights.summary
+ Accessible.description: lights.toolTipSubText
+
+ // Remembering the state at press time stops a click that closes the popup
+ // (it loses focus first) from opening it again straight away.
+ onPressed: wasExpanded = lights.expanded
+ onClicked: lights.expanded = !wasExpanded
+
+ Row {
+ id: row
+ anchors.verticalCenter: parent.verticalCenter
+ spacing: 4
+ visible: light.lights.shown
+
+ Repeater {
+ model: light.pills
+
+ Rectangle {
+ id: pill
+ required property var modelData
+ readonly property bool lit: modelData.on
+ width: lit ? 10 + 17 + 7 + 7 + 10 : 32
+ height: 36
+ radius: lit ? 10 : 8
+ color: {
+ const c = modelData.color;
+ const base = lit ? Qt.rgba(c.r, c.g, c.b, 0.20) : "transparent";
+ if (light.pressed) {
+ return lit ? Qt.rgba(c.r, c.g, c.b, 0.34) : UI.Style.surfacePressed;
+ }
+ if (light.lights.expanded || light.containsMouse) {
+ return lit ? Qt.rgba(c.r, c.g, c.b, 0.28) : light.lights.expanded ? UI.Style.surfaceSelected : UI.Style.surfaceHover;
+ }
+ return base;
+ }
+ Behavior on color {
+ ColorAnimation { duration: UI.Style.hoverDuration }
+ }
+
+ UI.Glyph {
+ visible: pill.lit
+ x: 10
+ anchors.verticalCenter: parent.verticalCenter
+ width: 17
+ height: 17
+ path: pill.modelData.path
+ strokeWidth: 2.2
+ color: pill.modelData.color
+ }
+
+ Rectangle {
+ visible: pill.lit
+ x: 10 + 17 + 7
+ anchors.verticalCenter: parent.verticalCenter
+ width: 7
+ height: 7
+ radius: 3.5
+ color: pill.modelData.color
+ }
+
+ UI.Glyph {
+ visible: !pill.lit
+ anchors.centerIn: parent
+ width: 16
+ height: 16
+ path: pill.modelData.offPath
+ strokeWidth: 2
+ color: UI.Style.iconInk
+ }
+ }
+ }
+ }
+}
diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.lights/contents/ui/Panel.qml b/packages/wildos-branding/files/plasmoids/org.wildos.lights/contents/ui/Panel.qml
new file mode 100644
index 0000000..b3dc7cc
--- /dev/null
+++ b/packages/wildos-branding/files/plasmoids/org.wildos.lights/contents/ui/Panel.qml
@@ -0,0 +1,264 @@
+pragma ComponentBehavior: Bound
+
+import QtQuick
+import QtQuick.Layouts
+import org.kde.kirigami as Kirigami
+import org.kde.ksvg as KSvg
+import WildOS.UI as UI
+
+// The panel from TaskbarCamMic.dc: 380 wide with 18 px inside and 14 px
+// between rows. What is in use now, each app with when it started and Stop;
+// then each idle device with the app that used it last; a switch per
+// device that blocks it for every app; and the way to this week's use in
+// History. Plasma's theme draws the glass, so its frame margins come off
+// the board's outer edge, as on the other flyouts.
+FocusScope {
+ id: panel
+
+ required property var lights
+
+ readonly property int panelWidth: 380
+ readonly property int pad: 18
+
+ KSvg.FrameSvgItem {
+ id: frame
+ imagePath: "dialogs/background"
+ visible: false
+ }
+
+ readonly property real contentWidth: panelWidth - frame.margins.left - frame.margins.right
+ readonly property real contentHeight: 2 * pad + body.implicitHeight - frame.margins.top - frame.margins.bottom
+
+ Layout.minimumWidth: contentWidth
+ Layout.preferredWidth: contentWidth
+ Layout.maximumWidth: contentWidth
+ Layout.minimumHeight: contentHeight
+ Layout.preferredHeight: contentHeight
+ Layout.maximumHeight: contentHeight
+
+ focus: true
+
+ // In use first, oldest first, then the devices nobody is using.
+ readonly property var uses: lights.microphone.uses.map(u => Object.assign({ device: "microphone" }, u))
+ .concat(lights.camera.uses.map(u => Object.assign({ device: "camera" }, u)))
+ .sort((a, b) => a.since - b.since)
+ readonly property var idle: [
+ { name: "Microphone", info: lights.microphone, path: Glyphs.micOff, busy: lights.micInUse },
+ { name: "Camera", info: lights.camera, path: Glyphs.cameraOff, busy: lights.cameraInUse }
+ ].filter(d => !d.busy)
+
+ Connections {
+ target: panel.lights
+ function onExpandedChanged() {
+ if (panel.lights.expanded) {
+ panel.forceActiveFocus();
+ }
+ }
+ }
+
+ Keys.onPressed: event => {
+ if (event.key === Qt.Key_Escape) {
+ lights.expanded = false;
+ event.accepted = true;
+ }
+ }
+
+ component Divider: Rectangle {
+ Layout.fillWidth: true
+ implicitHeight: 1
+ color: UI.Style.tone(0.07)
+ }
+
+ component TwoLines: ColumnLayout {
+ property alias title: titleLabel.text
+ property alias detail: detailLabel.text
+ Layout.fillWidth: true
+ spacing: 2
+
+ UI.Label {
+ id: titleLabel
+ Layout.fillWidth: true
+ size: 13.5
+ font.weight: 500
+ elide: Text.ElideRight
+ }
+
+ UI.Label {
+ id: detailLabel
+ Layout.fillWidth: true
+ size: 12.5
+ color: UI.Style.inkMuted
+ wrapMode: Text.Wrap
+ elide: Text.ElideNone
+ }
+ }
+
+ component Switch: RowLayout {
+ id: switchRow
+ required property string name
+ required property string path
+ required property var device
+ spacing: 12
+ Layout.fillWidth: true
+
+ Item {
+ Layout.preferredWidth: 30
+ Layout.preferredHeight: 19
+
+ UI.Glyph {
+ anchors.centerIn: parent
+ width: 19
+ height: 19
+ path: switchRow.path
+ strokeWidth: 1.8
+ color: UI.Style.ink
+ }
+ }
+
+ TwoLines {
+ title: switchRow.name === "camera" ? "Camera" : "Microphone"
+ detail: "Off here blocks it for every app."
+ }
+
+ UI.Toggle {
+ // Read again whenever a request ends, so a cancelled password
+ // prompt leaves the switch where the device really is.
+ checked: !switchRow.device.blocked && panel.lights.requestCount >= 0
+ locked: switchRow.device.maximum
+ lockedReason: "Maximum protection keeps the camera off"
+ Accessible.name: switchRow.name === "camera" ? "Camera" : "Microphone"
+ onToggled: panel.lights.setAllowed(switchRow.name, checked)
+ }
+ }
+
+ ColumnLayout {
+ id: body
+ x: panel.pad - frame.margins.left
+ y: panel.pad - frame.margins.top
+ width: panel.panelWidth - 2 * panel.pad
+ spacing: 14
+
+ UI.Label {
+ visible: panel.uses.length > 0
+ text: "IN USE NOW"
+ size: 12.5
+ font.weight: 600
+ font.letterSpacing: 0.25
+ color: UI.Style.inkSubtle
+ }
+
+ Repeater {
+ model: panel.uses
+
+ RowLayout {
+ id: useRow
+ required property var modelData
+ Layout.fillWidth: true
+ spacing: 12
+
+ Item {
+ Layout.preferredWidth: 30
+ Layout.preferredHeight: 30
+
+ Kirigami.Icon {
+ id: appIcon
+ anchors.fill: parent
+ source: useRow.modelData.icon || ""
+ visible: valid && source !== ""
+ }
+
+ UI.Glyph {
+ visible: !appIcon.visible
+ anchors.centerIn: parent
+ width: 19
+ height: 19
+ path: useRow.modelData.device === "camera" ? Glyphs.camera : Glyphs.mic
+ strokeWidth: 1.8
+ color: useRow.modelData.device === "camera" ? panel.lights.green : panel.lights.amber
+ }
+ }
+
+ TwoLines {
+ title: useRow.modelData.app + " is using the " + panel.lights.deviceWord(useRow.modelData.device)
+ detail: "Since " + panel.lights.timeText(useRow.modelData.since) + "."
+ }
+
+ UI.Button {
+ visible: useRow.modelData.stoppable === true
+ text: "Stop"
+ Accessible.name: "Stop " + useRow.modelData.app + " using the " + panel.lights.deviceWord(useRow.modelData.device)
+ onClicked: panel.lights.stopUse(useRow.modelData.key)
+ }
+ }
+ }
+
+ Repeater {
+ model: panel.idle
+
+ RowLayout {
+ id: idleRow
+ required property var modelData
+ Layout.fillWidth: true
+ spacing: 12
+
+ Item {
+ Layout.preferredWidth: 30
+ Layout.preferredHeight: 19
+
+ UI.Glyph {
+ anchors.centerIn: parent
+ width: 19
+ height: 19
+ path: idleRow.modelData.path
+ strokeWidth: 1.8
+ color: UI.Style.inkMuted
+ }
+ }
+
+ TwoLines {
+ title: idleRow.modelData.name
+ detail: panel.lights.idleText(idleRow.modelData.info)
+ }
+ }
+ }
+
+ Divider {}
+
+ Switch {
+ name: "microphone"
+ path: Glyphs.mic
+ device: panel.lights.microphone
+ }
+
+ Switch {
+ name: "camera"
+ path: Glyphs.camera
+ device: panel.lights.camera
+ }
+
+ Divider {}
+
+ RowLayout {
+ Layout.fillWidth: true
+ spacing: 0
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: "Amber is the microphone. Green is the camera."
+ size: 12.5
+ color: UI.Style.inkMuted
+ wrapMode: Text.Wrap
+ elide: Text.ElideNone
+ }
+
+ UI.LinkButton {
+ // The link's own padding sits outside the panel's edge, so
+ // its words line up with the switches above.
+ Layout.rightMargin: -4
+ text: "This week"
+ Accessible.name: "This week's camera and microphone use in History"
+ onClicked: panel.lights.openHistory()
+ }
+ }
+ }
+}
diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.lights/contents/ui/main.qml b/packages/wildos-branding/files/plasmoids/org.wildos.lights/contents/ui/main.qml
new file mode 100644
index 0000000..68232ff
--- /dev/null
+++ b/packages/wildos-branding/files/plasmoids/org.wildos.lights/contents/ui/main.qml
@@ -0,0 +1,216 @@
+pragma ComponentBehavior: Bound
+
+import QtQuick
+import org.kde.plasma.plasmoid
+import org.kde.plasma.core as PlasmaCore
+import org.kde.plasma.plasma5support as P5Support
+import WildOS.UI as UI
+
+// The camera and microphone lights (TaskbarCamMic.dc), left of the shield:
+// amber while any app is using the microphone, green while one is using the
+// camera, and the panel that says which app, since when, and cuts it off.
+// Everything shown comes from /usr/libexec/wildos/camera-mic, which watches
+// the devices themselves, so no app goes unseen by asking nobody. There is
+// no setting that turns the light off.
+PlasmoidItem {
+ id: lights
+
+ readonly property string libexec: "/usr/libexec/wildos/"
+
+ // The amber and green of the board; deeper on a light taskbar so they
+ // still read as lit.
+ readonly property color amber: UI.Style.dark ? "#ffb454" : "#a35f00"
+ readonly property color green: UI.Style.dark ? "#5fd38d" : "#1d7a4c"
+
+ // What camera-mic last reported. Not "state": Item has one.
+ property var report: ({})
+ readonly property var microphone: device("microphone")
+ readonly property var camera: device("camera")
+ readonly property bool micInUse: microphone.uses.length > 0
+ readonly property bool cameraInUse: camera.uses.length > 0
+ readonly property bool inUse: micInUse || cameraInUse
+ // Shown while switched off too: the panel is the only way to switch the
+ // device back on.
+ readonly property bool shown: inUse || microphone.blocked || camera.blocked
+ property real now: Date.now()
+ // Bumped when a switch's request ends, which puts the switch back on
+ // the real state if nothing changed (a cancelled password prompt).
+ property int requestCount: 0
+
+ function device(name: string): var {
+ const d = (report.devices || {})[name] || {};
+ return { uses: d.uses || [], blocked: d.blocked === true, maximum: d.maximum === true, last: d.last || null };
+ }
+
+ function deviceWord(name: string): string {
+ return name === "camera" ? "camera" : "microphone";
+ }
+
+ function timeText(seconds: real): string {
+ return Qt.locale().toString(new Date(seconds * 1000), UI.TimeFormat.shortFormat);
+ }
+
+ // "today", "yesterday", a weekday within the week, then the date.
+ function dayText(seconds: real): string {
+ const when = new Date(seconds * 1000);
+ const today = new Date(now);
+ today.setHours(0, 0, 0, 0);
+ const days = Math.round((today.getTime() - new Date(when.getFullYear(), when.getMonth(), when.getDate()).getTime()) / 86400000);
+ if (days <= 0) {
+ return "today";
+ }
+ if (days === 1) {
+ return "yesterday";
+ }
+ if (days < 7) {
+ return "on " + Qt.locale("en_GB").dayName(when.getDay(), Locale.LongFormat);
+ }
+ return "on " + Qt.locale("en_GB").toString(when, "d MMMM");
+ }
+
+ function idleText(d: var): string {
+ return d.last && d.last.app ? "Not in use. Last used " + dayText(d.last.t) + " by " + d.last.app + "." : "Not in use.";
+ }
+
+ readonly property string summary: {
+ const parts = [];
+ for (const u of microphone.uses) {
+ parts.push("Microphone in use by " + u.app);
+ }
+ for (const u of camera.uses) {
+ parts.push("Camera in use by " + u.app);
+ }
+ if (parts.length === 0) {
+ if (microphone.blocked) {
+ parts.push("Microphone off for every app");
+ }
+ if (camera.blocked) {
+ parts.push("Camera off for every app");
+ }
+ }
+ return parts.join(". ");
+ }
+
+ // camera-mic wait answers as soon as the state is newer than the
+ // version it is given, so the light comes on as the app starts.
+ P5Support.DataSource {
+ id: watcher
+ engine: "executable"
+ property string version: "0"
+ // Each wait is its own source (a numbered comment): the engine hands
+ // a source it already has its last output.
+ property int count: 0
+ readonly property string command: lights.libexec + "camera-mic wait " + version + " #" + count
+ onNewData: (source, data) => {
+ disconnectSource(source);
+ let next = {};
+ try {
+ next = JSON.parse(String(data.stdout));
+ } catch (e) {
+ next = {};
+ }
+ lights.report = next;
+ lights.now = Date.now();
+ const v = String(next.version || "0");
+ // Without the service there is nothing to wait for; asking again
+ // straight away would only spin.
+ if (v === version || data["exit code"] !== 0) {
+ retry.restart();
+ } else {
+ version = v;
+ count += 1;
+ Qt.callLater(() => watcher.connectSource(watcher.command));
+ }
+ }
+ }
+
+ Timer {
+ id: retry
+ interval: 5000
+ onTriggered: {
+ watcher.count += 1;
+ watcher.connectSource(watcher.command);
+ }
+ }
+
+ P5Support.DataSource {
+ id: shell
+ engine: "executable"
+ onNewData: (source, data) => {
+ disconnectSource(source);
+ if (source.indexOf("camera-mic-block") >= 0) {
+ lights.requestCount += 1;
+ }
+ }
+ }
+
+ property int runCount: 0
+
+ function run(command: string): void {
+ runCount += 1;
+ shell.connectSource(command + " #" + runCount);
+ }
+
+ function stopUse(key: string): void {
+ if (/^[0-9a-f]{16}$/.test(key)) {
+ run(libexec + "camera-mic stop " + key);
+ }
+ }
+
+ function setAllowed(name: string, on: bool): void {
+ if (name === "microphone" || name === "camera") {
+ run("pkexec " + libexec + "camera-mic-block " + (on ? "unblock " : "block ") + name);
+ }
+ }
+
+ // Settings ships with Wild OS, but if it has gone the click still says
+ // something rather than doing nothing.
+ function openHistory(): void {
+ run("if command -v wildos-settings >/dev/null; then setsid -f wildos-settings --page history-camera >/dev/null 2>&1; "
+ + "else notify-send -a 'Wild OS' -i preferences-system 'Settings is missing' "
+ + "'Reinstall it from the Store to see History.'; fi");
+ expanded = false;
+ }
+
+ onExpandedChanged: () => {
+ if (lights.expanded) {
+ now = Date.now();
+ }
+ }
+
+ // Nothing to show, nothing to open.
+ onShownChanged: () => {
+ if (!lights.shown) {
+ lights.expanded = false;
+ }
+ }
+
+ Timer {
+ running: lights.expanded
+ interval: 30000
+ repeat: true
+ onTriggered: lights.now = Date.now()
+ }
+
+ Plasmoid.backgroundHints: PlasmaCore.Types.NoBackground
+ Plasmoid.icon: "camera-web"
+ Plasmoid.title: "Camera and microphone"
+ Plasmoid.status: shown ? PlasmaCore.Types.ActiveStatus : PlasmaCore.Types.HiddenStatus
+ toolTipMainText: summary
+ toolTipSubText: "Click for details"
+
+ preferredRepresentation: compactRepresentation
+ compactRepresentation: Light {
+ lights: lights
+ }
+ fullRepresentation: Panel {
+ lights: lights
+ }
+
+ Component.onCompleted: {
+ if (Plasmoid.hasOwnProperty("activationTogglesExpanded")) {
+ Plasmoid.activationTogglesExpanded = true;
+ }
+ watcher.connectSource(watcher.command);
+ }
+}
diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.lights/contents/ui/qmldir b/packages/wildos-branding/files/plasmoids/org.wildos.lights/contents/ui/qmldir
new file mode 100644
index 0000000..edbb923
--- /dev/null
+++ b/packages/wildos-branding/files/plasmoids/org.wildos.lights/contents/ui/qmldir
@@ -0,0 +1 @@
+singleton Glyphs 1.0 Glyphs.qml
diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.lights/metadata.json b/packages/wildos-branding/files/plasmoids/org.wildos.lights/metadata.json
new file mode 100644
index 0000000..7151da0
--- /dev/null
+++ b/packages/wildos-branding/files/plasmoids/org.wildos.lights/metadata.json
@@ -0,0 +1,15 @@
+{
+ "KPlugin": {
+ "Authors": [{ "Email": "[email protected]", "Name": "Wild OS" }],
+ "Category": "System Information",
+ "Description": "A light while any app uses the camera or microphone, and the switches that block them",
+ "Icon": "camera-web",
+ "Id": "org.wildos.lights",
+ "License": "GPL-3.0-or-later",
+ "Name": "Camera and microphone",
+ "Version": "0.1.0",
+ "Website": "https://wildos.io"
+ },
+ "KPackageStructure": "Plasma/Applet",
+ "X-Plasma-API-Minimum-Version": "6.0"
+}
diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.protected/contents/ui/main.qml b/packages/wildos-branding/files/plasmoids/org.wildos.protected/contents/ui/main.qml
index e2bb1fa..c827c1b 100644
--- a/packages/wildos-branding/files/plasmoids/org.wildos.protected/contents/ui/main.qml
+++ b/packages/wildos-branding/files/plasmoids/org.wildos.protected/contents/ui/main.qml
@@ -78,6 +78,13 @@ PlasmoidItem {
const row = (id, icon, title, text, tone, action, run) =>
list.push({ id: id, icon: icon, title: title, status: text, tone: tone, action: action, run: run });
+ // Only a row while it is off, switched off in Settings or failed to
+ // load, and never one that can be ignored: the shield stays amber
+ // until the firewall is back.
+ if (s.firewall === "off") {
+ row("firewall", "firewall", "Firewall", "Firewall is off", "warn", "Turn on", "settings:firewall");
+ }
+
if (s.encryption === "on") {
row("encryption", "lock", "Disk encryption", "Your files are encrypted", "ok", "", "privacy");
} else if (s.encryption === "off") {
@@ -412,6 +419,8 @@ PlasmoidItem {
openPrivacy();
} else if (what === "updates") {
openUpdates();
+ } else if (what === "settings:firewall") {
+ openSettings("firewall");
} else if (what.indexOf("ignore:") === 0 || what.indexOf("unignore:") === 0) {
const at = what.indexOf(":");
const key = what.slice(at + 1);
diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.quicksettings/contents/ui/BatteryGlyph.qml b/packages/wildos-branding/files/plasmoids/org.wildos.quicksettings/contents/ui/BatteryGlyph.qml
index 98e9a0a..291f18b 100644
--- a/packages/wildos-branding/files/plasmoids/org.wildos.quicksettings/contents/ui/BatteryGlyph.qml
+++ b/packages/wildos-branding/files/plasmoids/org.wildos.quicksettings/contents/ui/BatteryGlyph.qml
@@ -3,7 +3,7 @@ import QtQuick.Shapes
import WildOS.UI as UI
// The design's battery: a 21 by 12 body with a nub, filled to the charge
-// level. Charging swaps the fill for a bolt, and a nearly empty battery that
+// level. Being plugged in swaps the fill for a bolt, and a nearly empty battery that
// is not plugged in fills in the warning colour.
Item {
id: glyph
diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.quicksettings/contents/ui/Flyout.qml b/packages/wildos-branding/files/plasmoids/org.wildos.quicksettings/contents/ui/Flyout.qml
index e9b788b..6479129 100644
--- a/packages/wildos-branding/files/plasmoids/org.wildos.quicksettings/contents/ui/Flyout.qml
+++ b/packages/wildos-branding/files/plasmoids/org.wildos.quicksettings/contents/ui/Flyout.qml
@@ -617,7 +617,7 @@ FocusScope {
Layout.preferredWidth: 22
Layout.preferredHeight: 18
percent: flyout.power ? flyout.power.percent : 0
- charging: flyout.power ? flyout.power.charging : false
+ charging: flyout.power ? flyout.power.pluggedIn : false
low: flyout.quick.batteryLow
}
diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.quicksettings/contents/ui/TrayButton.qml b/packages/wildos-branding/files/plasmoids/org.wildos.quicksettings/contents/ui/TrayButton.qml
index 7283773..8ed3b29 100644
--- a/packages/wildos-branding/files/plasmoids/org.wildos.quicksettings/contents/ui/TrayButton.qml
+++ b/packages/wildos-branding/files/plasmoids/org.wildos.quicksettings/contents/ui/TrayButton.qml
@@ -141,7 +141,10 @@ MouseArea {
Layout.preferredWidth: 22
Layout.preferredHeight: 18
percent: button.quick.power ? button.quick.power.percent : 0
- charging: button.quick.power ? button.quick.power.charging : false
+ // The bolt shows whenever the charger is in, as on Windows: a full
+ // battery, or one held at a charge limit, isn't charging but is
+ // still plugged in.
+ charging: button.quick.power ? button.quick.power.pluggedIn : false
low: button.quick.batteryLow
}
diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.quicksettings/contents/ui/WifiPage.qml b/packages/wildos-branding/files/plasmoids/org.wildos.quicksettings/contents/ui/WifiPage.qml
index ba1a958..3ca4887 100644
--- a/packages/wildos-branding/files/plasmoids/org.wildos.quicksettings/contents/ui/WifiPage.qml
+++ b/packages/wildos-branding/files/plasmoids/org.wildos.quicksettings/contents/ui/WifiPage.qml
@@ -203,6 +203,7 @@ FocusScope {
Layout.topMargin: 2
visible: row.needsPassword && row.connState === PlasmaNM.Enums.Deactivated
revealable: true
+ UI.NoPaste {}
inputMethodHints: Qt.ImhSensitiveData | Qt.ImhNoPredictiveText | Qt.ImhNoAutoUppercase
placeholderText: "Password"
Accessible.name: "Password for " + row.title
@@ -319,6 +320,7 @@ FocusScope {
id: hiddenPassword
Layout.fillWidth: true
revealable: true
+ UI.NoPaste {}
placeholderText: "Password, if it has one"
inputMethodHints: Qt.ImhSensitiveData | Qt.ImhNoPredictiveText | Qt.ImhNoAutoUppercase
onAccepted: {
diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.start/contents/ui/SearchView.qml b/packages/wildos-branding/files/plasmoids/org.wildos.start/contents/ui/SearchView.qml
index 9ab4556..1d146f0 100644
--- a/packages/wildos-branding/files/plasmoids/org.wildos.start/contents/ui/SearchView.qml
+++ b/packages/wildos-branding/files/plasmoids/org.wildos.start/contents/ui/SearchView.qml
@@ -137,6 +137,14 @@ FocusScope {
if (calc) {
items.push({ header: false, kind: "calc", src: -1, title: calc.value, subtitle: calc.expression, detail: calc.expression + " =", icon: "accessories-calculator", plain: calc.plain });
}
+ // Wild OS's own Settings pages, which KRunner doesn't know: first
+ // when the name was typed, after the rest when only a keyword was.
+ const pages = (filter === "all" || filter === "settings" ? Helpers.wildosPageMatches(launcher.query) : [])
+ .map(p => ({ header: false, kind: "settings", src: -1, page: p.page, title: p.title, subtitle: p.category, detail: p.category,
+ icon: "preferences-system", plain: "", named: p.named }));
+ for (const p of pages.filter(p => p.named)) {
+ items.push(p);
+ }
for (let i = 0; i < matches.count; i++) {
const entry = matches.objectAt(i);
if (!entry) {
@@ -154,6 +162,9 @@ FocusScope {
const icon = entry.model.decoration || (kind === "folders" ? "folder" : "unknown");
items.push({ header: false, kind: kind, src: i, title: text.title, subtitle: text.subtitle, detail: text.detail, icon: icon, plain: "" });
}
+ for (const p of pages.filter(p => !p.named)) {
+ items.push(p);
+ }
const out = [];
if (items.length > 0) {
@@ -216,7 +227,7 @@ FocusScope {
return;
}
if (entry.kind === "settings") {
- const page = Helpers.settingsPage(modelOf(entry).model.url);
+ const page = entry.page ? { page: entry.page } : Helpers.settingsPage(modelOf(entry).model.url);
if (!page || !launcher.openSettingsPage(page.page)) {
launcher.settingsMissing();
}
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 0274fce..f3a861f 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
@@ -39,7 +39,14 @@ const newAccountPins = ["org.wildos.music.desktop", "org.wildos.videos.desktop"]
// Apps that make up the system itself. Windows does not offer to uninstall
// these from Start either.
-const coreApps = ["org.wildos.files", "org.wildos.store", "org.kde.dolphin", "org.kde.discover", "systemsettings", "org.wildos.settings", "org.wildos.terminal", "org.kde.konsole"];
+const coreApps = ["org.wildos.files", "org.wildos.store", "org.kde.dolphin", "org.kde.discover", "systemsettings", "org.wildos.settings", "org.kde.konsole",
+ "org.wildos.report", "org.wildos.taskmanager", "org.wildos.welcome", "org.wildos.winmode", "org.wildos.run", "org.wildos.security", "org.wildos.access"];
+
+// Wild OS's own apps, which the Store does not list: Settings removes them.
+function isOwnApp(favoriteId) {
+ const id = storageId(favoriteId);
+ return id.indexOf("org.wildos.") === 0 || id === "libreoffice-writer" || id === "libreoffice-calc";
+}
function isCoreApp(favoriteId) {
return coreApps.includes(storageId(favoriteId));
@@ -99,6 +106,36 @@ const settingsPages = {
"kcm_virtualkeyboard": ["On-screen keyboard", "Accessibility", "accessibility"],
};
+// Wild OS Settings pages with no KDE module behind them, which the search
+// above can never return, matched here on their own words.
+const wildosPages = [
+ { page: "history", title: "History", category: "System",
+ keywords: "history event viewer events event log logs what happened reliability crash crashes closed unexpectedly problems errors sign in sign-ins signed in failed password wrong password fingerprint shut down shutdown restart restarted sleep woke lid start-up startup boot usb drive firewall blocked updates installed restore point backup" },
+ { page: "hardware", title: "Devices", category: "System",
+ keywords: "device manager devices hardware drivers driver missing driver unknown device firmware graphics card gpu wifi adapter network adapter sound card webcam camera fingerprint reader touchpad battery health disk health drive health smart usb device pci" },
+ { page: "taskbar", title: "Taskbar", category: "Personalisation",
+ keywords: "taskbar panel auto hide autohide clock seconds full date battery percentage show desktop peek end task kill force close force quit not responding frozen hung windows mode status" },
+ { page: "firewall", title: "Firewall", category: "Privacy and security",
+ keywords: "firewall windows defender firewall network protection public network home network allow app allow port open port blocked connections incoming connections network discovery file sharing remote desktop rdp ssh" },
+ { page: "advancedprotection", title: "Advanced protection", category: "Privacy and security",
+ keywords: "advanced protection extra protection hardening locked usb devices quiet lock screen fingerprint password restart when locked wi-fi bluetooth switch off encrypted dns dns over tls quad9 mullvad cloudflare vpn only kill switch clipboard passwords presenting mode screen sharing personal details metadata password-locked usb sticks encrypt drive guest session safe box panic key reset to defaults" },
+];
+
+// Pages from wildosPages for a query: every word typed starts a word of
+// the page's title or keywords; named when they all start its title.
+function wildosPageMatches(query) {
+ const words = String(query ?? "").toLowerCase().trim().split(/\s+/).filter(w => w.length > 0);
+ if (words.length === 0 || words.join(" ").length < 2) {
+ return [];
+ }
+ const found = wildosPages.filter(p => {
+ const hay = " " + (p.title + " " + p.keywords).toLowerCase();
+ return words.every(w => hay.includes(" " + w));
+ });
+ const titled = p => words.every(w => (" " + p.title.toLowerCase()).includes(" " + w));
+ return found.map(p => Object.assign({ named: titled(p) }, p));
+}
+
function settingsPage(url) {
const text = String(url ?? "");
const id = text.substring(text.lastIndexOf("/") + 1).replace(/\.desktop$/, "");
@@ -125,6 +162,22 @@ function storageId(favoriteId) {
return id;
}
+// The taskbar launcher URL for an app in Start. Kicker gives an app's id
+// bare in All apps ("org.wildos.report.desktop") but already prefixed in
+// search results and the pinned grid ("applications:org.wildos.report.desktop"),
+// so the prefix is put back on the bare id rather than added to whatever
+// came. An app known only by its file keeps a file URL.
+function taskbarUrl(favoriteId) {
+ const id = String(favoriteId ?? "");
+ if (id.startsWith("file:")) {
+ return id;
+ }
+ if (id.startsWith("/")) {
+ return "file://" + encodeURI(id);
+ }
+ return "applications:" + storageId(id) + ".desktop";
+}
+
function appName(favoriteId, display) {
const id = storageId(favoriteId);
return friendlyNames[id] ?? display ?? "";
diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.start/contents/ui/main.qml b/packages/wildos-branding/files/plasmoids/org.wildos.start/contents/ui/main.qml
index b6a7fab..786e528 100644
--- a/packages/wildos-branding/files/plasmoids/org.wildos.start/contents/ui/main.qml
+++ b/packages/wildos-branding/files/plasmoids/org.wildos.start/contents/ui/main.qml
@@ -223,13 +223,43 @@ PlasmoidItem {
}
function canUninstall(favoriteId: string): bool {
- return hasStore && favoriteId.length > 0 && !Helpers.isCoreApp(favoriteId);
+ if (favoriteId.length === 0 || Helpers.isCoreApp(favoriteId)) {
+ return false;
+ }
+ return isHomeApp(favoriteId) || isWindowsApp(favoriteId) || Helpers.isOwnApp(favoriteId) || hasStore;
+ }
+
+ // A Windows app in Windows mode: Windows uninstalls it, through
+ // Settings > Installed apps.
+ function isWindowsApp(favoriteId: string): bool {
+ return Helpers.storageId(favoriteId).indexOf("wildos-winmode-") === 0;
+ }
+
+ // An app that installed itself in the home folder (its own install
+ // script, an AppImage). The Store has never heard of it, so Settings
+ // removes it. Windows mode's launchers live there too; isWindowsApp
+ // covers them.
+ function isHomeApp(favoriteId: string): bool {
+ const row = appRow(favoriteId);
+ if (row < 0) {
+ return false;
+ }
+ const url = String(start.appIndex.objectAt(row).url);
+ return url.indexOf("/.local/share/applications/") >= 0 && Helpers.storageId(favoriteId).indexOf("wildos-") !== 0;
}
// Removing software is the Store's job, as on Windows, so Uninstall
- // opens the app's page there.
+ // opens the app's page there; Wild OS's own apps and apps in the home
+ // folder or in Windows mode open their Uninstall in Settings > Installed
+ // apps.
function uninstallApp(favoriteId: string): void {
- Qt.openUrlExternally("appstream://" + Helpers.storageId(favoriteId));
+ if (isHomeApp(favoriteId) || isWindowsApp(favoriteId) || Helpers.isOwnApp(favoriteId)) {
+ if (!openSettingsPage("uninstall:" + Helpers.storageId(favoriteId))) {
+ settingsMissing();
+ }
+ } else {
+ Qt.openUrlExternally("appstream://" + Helpers.storageId(favoriteId));
+ }
start.close();
}
@@ -270,7 +300,7 @@ PlasmoidItem {
const commands = [];
const taskbar = favoriteId.endsWith(".desktop") ? taskbarApplet() : null;
if (taskbar) {
- const url = "applications:" + favoriteId;
+ const url = Helpers.taskbarUrl(favoriteId);
const launchers = Array.from(taskbar.configuration.launchers);
if (launchers.indexOf(url) >= 0) {
commands.push({ text: "Unpin from taskbar", icon: "menu-unpin", run: () => taskbar.configuration.launchers = launchers.filter(l => l !== url) });
@@ -307,6 +337,11 @@ PlasmoidItem {
toolTipSubText: ""
preferredRepresentation: compactRepresentation
+ // Start is built when the taskbar loads instead of on the first click,
+ // which made that first open stutter while it compiled the menu and read
+ // every icon. It resets itself each time it opens (StartMenu's
+ // onExpandedChanged), so building it early changes nothing else.
+ preloadFullRepresentation: true
compactRepresentation: StartButton {
launcher: start
}
diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.tasks/contents/ui/StartingTask.qml b/packages/wildos-branding/files/plasmoids/org.wildos.tasks/contents/ui/StartingTask.qml
index 3a678a1..f05839e 100644
--- a/packages/wildos-branding/files/plasmoids/org.wildos.tasks/contents/ui/StartingTask.qml
+++ b/packages/wildos-branding/files/plasmoids/org.wildos.tasks/contents/ui/StartingTask.qml
@@ -82,7 +82,7 @@ Item {
}
SequentialAnimation {
- running: !starting.reducedMotion
+ running: starting.visible && !starting.reducedMotion
loops: Animation.Infinite
ParallelAnimation {
NumberAnimation { target: mark; property: "width"; from: Style.markWidth; to: Style.startingWidth; duration: Style.startingCycle * 0.6; easing.type: Easing.InOutSine }
diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.tasks/contents/ui/Task.qml b/packages/wildos-branding/files/plasmoids/org.wildos.tasks/contents/ui/Task.qml
index 0d945e3..2fa10f2 100644
--- a/packages/wildos-branding/files/plasmoids/org.wildos.tasks/contents/ui/Task.qml
+++ b/packages/wildos-branding/files/plasmoids/org.wildos.tasks/contents/ui/Task.qml
@@ -32,10 +32,17 @@ Item {
readonly property var tasksModel: tasksRoot.tasksModel
readonly property var backend: tasksRoot.backend
+ // A pin whose app was uninstalled: Plasma keeps it, as a blank page
+ // that only plays the error sound. It stays in the list, out of sight,
+ // so putting the app back from the Store brings its pin back where it
+ // was.
+ readonly property bool orphaned: model.IsLauncher === true && String(model.AppId || "") === ""
+
+ visible: !orphaned
width: Style.button
height: Style.button
- activeFocusOnTab: true
+ activeFocusOnTab: !orphaned
readonly property string launcherKey: String(model.LauncherUrlWithoutIcon || "")
readonly property string appKey: String(model.AppId || "").replace(/\.desktop$/, "")
@@ -78,10 +85,15 @@ Item {
awaitingTimer.restart();
}
+ property int lastChildCount: childCount
onChildCountChanged: {
if (awaitingWindow && isWindow && childCount > childCountAtLaunch) {
awaitingWindow = false;
}
+ if (isWindow && childCount > lastChildCount) {
+ tasksRoot.windowOpened([launcherKey, appKey, desktopKey]);
+ }
+ lastChildCount = childCount;
}
Timer {
@@ -90,6 +102,15 @@ Item {
onTriggered: task.awaitingWindow = false
}
+ Connections {
+ target: task.tasksRoot
+ function onLaunchFinished(key: string): void {
+ if (key === task.desktopKey) {
+ task.awaitingWindow = false;
+ }
+ }
+ }
+
Accessible.role: Accessible.Button
Accessible.name: model.display || ""
Accessible.description: starting ? "Starting"
@@ -181,6 +202,7 @@ Item {
}
if (isWindow) {
+ tasksRoot.windowOpened([launcherKey, appKey, desktopKey]);
publishGeometry.start();
updateAudioStreams();
}
@@ -189,6 +211,7 @@ Item {
onIsWindowChanged: {
if (isWindow) {
awaitingWindow = false;
+ tasksRoot.windowOpened([launcherKey, appKey, desktopKey]);
publishGeometry.start();
updateAudioStreams();
}
@@ -306,7 +329,7 @@ Item {
// The fill keyframes: widest and brightest 60% of the way through.
SequentialAnimation {
id: stretch
- running: task.starting && !task.reducedMotion
+ running: task.starting && task.visible && !task.reducedMotion
loops: Animation.Infinite
onRunningChanged: {
if (!running) {
diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.tasks/contents/ui/TaskMenu.qml b/packages/wildos-branding/files/plasmoids/org.wildos.tasks/contents/ui/TaskMenu.qml
index b4daa2d..ff78ec7 100644
--- a/packages/wildos-branding/files/plasmoids/org.wildos.tasks/contents/ui/TaskMenu.qml
+++ b/packages/wildos-branding/files/plasmoids/org.wildos.tasks/contents/ui/TaskMenu.qml
@@ -8,8 +8,9 @@
Wild OS fork of the Plasma 6.3.6 task manager's ContextMenu.qml. The
jump list a right click opens on an app (MenusShell.dc "Taskbar app"):
its pinned places or recent files under small headings, the app's own
- tasks, then the app itself in 600, pin or unpin, close and End task,
- nearest the taskbar as on Windows 11. A Windows app adds one quiet line
+ tasks, then the app itself in 600, pin or unpin, close and, when it is
+ turned on in Settings > Personalisation > Taskbar, End task, nearest
+ the taskbar as on Windows 11. A Windows app adds one quiet line
saying it runs in Windows mode and a way to its settings. It is the
shared Wild OS menu in a window of its own, as the taskbar is too short
to hold it.
@@ -24,6 +25,7 @@ import org.kde.plasma.core as PlasmaCore
import org.kde.plasma.plasmoid
import org.kde.plasma.plasma5support as P5Support
import org.kde.plasma.private.mpris as Mpris
+import org.wildos.shell as WildOS
import WildOS.UI as UI
UI.Menu {
@@ -207,10 +209,12 @@ UI.Menu {
enabled: get(atm.IsClosable) !== false
});
- // Every Windows app's window comes from the one Windows mode
- // viewer, so ending it would close all of them at once.
- const pids = appPids(group);
- if (!windowsApp && pids.length > 0) {
+ // Off by default, as on Windows 11: Close window lets the app
+ // ask about unsaved work, End task does not. Every Windows app's
+ // window comes from the one Windows mode viewer, so ending it
+ // would close all of them at once.
+ const pids = WildOS.TaskbarStyle.endTask === true && !windowsApp ? appPids(group) : [];
+ if (pids.length > 0) {
list.push({ text: "End task", icon: "menu-task-manager", run: () => menu.endTask(pids) });
}
}
diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.tasks/contents/ui/WindowPreview.qml b/packages/wildos-branding/files/plasmoids/org.wildos.tasks/contents/ui/WindowPreview.qml
index eed4562..6138ec0 100644
--- a/packages/wildos-branding/files/plasmoids/org.wildos.tasks/contents/ui/WindowPreview.qml
+++ b/packages/wildos-branding/files/plasmoids/org.wildos.tasks/contents/ui/WindowPreview.qml
@@ -36,6 +36,14 @@ PlasmaCore.Dialog {
readonly property bool group: task !== null && task.model.IsGroupParent === true
readonly property int windowCount: task === null || !task.isWindow ? 0 : group ? task.childCount : 1
+ // The glass is sized for the last count that had windows. When the
+ // button goes away under the preview (its app hides a window for a
+ // moment, or the row is rebuilt), the count drops to 0 a moment before
+ // the preview hides; sized from that, Plasma shrinks the window to its
+ // bare frame, and the next hover maps that sliver before growing it,
+ // where it can stay.
+ property int sizedCount: 1
+ onWindowCountChanged: if (windowCount > 0) sizedCount = windowCount
// Titles and minimised states change while the preview is up; every
// tile reads them again when the model says something changed.
@@ -53,7 +61,7 @@ PlasmaCore.Dialog {
readonly property int pictureWidth: {
const screen = tasksModel.screenGeometry;
const room = (screen.width > 0 ? screen.width : 1920) - 32 - 2 * (glassBorder + pad);
- const n = Math.max(1, windowCount);
+ const n = sizedCount;
const tile = Math.floor((room + tileGap) / n - tileGap);
return Math.max(120, Math.min(200, tile - 2 * tilePad));
}
@@ -61,7 +69,7 @@ PlasmaCore.Dialog {
readonly property int tileWidth: pictureWidth + 2 * tilePad
readonly property int tileHeight: tilePad + headerHeight + 4 + pictureHeight + tilePad
- readonly property real glassWidth: 2 * (glassBorder + pad) + windowCount * tileWidth + Math.max(0, windowCount - 1) * tileGap
+ readonly property real glassWidth: 2 * (glassBorder + pad) + sizedCount * tileWidth + (sizedCount - 1) * tileGap
readonly property real glassHeight: 2 * (glassBorder + pad) + tileHeight
// A notification-type window is placed exactly where it is told, never
@@ -79,8 +87,13 @@ PlasmaCore.Dialog {
} else {
backend.cancelHighlightWindows();
// Closing the last window hides it too; the next hover waits
- // again rather than opening at once.
- shown = false;
+ // again rather than opening at once. Later, as visible is bound
+ // to shown.
+ Qt.callLater(() => {
+ if (!preview.visible) {
+ preview.shown = false;
+ }
+ });
}
}
onShownChanged: if (shown) place()
@@ -110,10 +123,18 @@ PlasmaCore.Dialog {
y = Math.round(barTop - gap - height);
}
- // Plasma can still be sizing the window as it appears.
+ // Plasma can still be sizing the window as it appears. It only resizes
+ // when the content's size changes, so a window mapped at a stale size
+ // would keep it on every hover of a button with the same count.
property Timer settle: Timer {
interval: 120
- onTriggered: preview.place()
+ onTriggered: {
+ if (Math.round(preview.width) !== Math.round(preview.glassWidth) || Math.round(preview.height) !== Math.round(preview.glassHeight)) {
+ preview.width = preview.glassWidth;
+ preview.height = preview.glassHeight;
+ }
+ preview.place();
+ }
}
function highlight(winId: string, on: bool): void {
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 048f5b0..19cafc1 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
@@ -72,6 +72,27 @@ PlasmoidItem {
return keys.some(key => key && launches[key] !== undefined && now - launches[key] < 15000);
}
+ // A window of the app turned up, so its start is over. Without this, a
+ // pin that Plasma brings back when that window closes would take the
+ // recent launch for one still on its way and pulse.
+ function windowOpened(keys: var): void {
+ const ids = keys.filter(key => key);
+ if (ids.some(key => launches[key] !== undefined)) {
+ const next = Object.assign({}, launches);
+ ids.forEach(key => delete next[key]);
+ launches = next;
+ }
+ if (ids.some(key => daemonIds[key] === true && settled[key] !== true)) {
+ const next = Object.assign({}, settled);
+ ids.forEach(key => {
+ if (daemonIds[key] === true) {
+ next[key] = true;
+ }
+ });
+ settled = next;
+ }
+ }
+
// What wildos-launchd is still opening, by lower-case desktop id. KWin's
// launch feedback (Plasma's IsStartup) stops the moment another window
// is activated, while the daemon keeps waiting for the app's window. The watcher lives in
@@ -85,7 +106,65 @@ PlasmoidItem {
component.destroy();
return watcher;
}
- readonly property var daemonLaunches: launchWatcher ? launchWatcher.launches : []
+ readonly property var allDaemonLaunches: launchWatcher ? launchWatcher.launches : []
+ readonly property var daemonIds: {
+ const ids = {};
+ allDaemonLaunches.forEach(launch => ids[launch.desktopId] = true);
+ return ids;
+ }
+ // Launches the daemon still lists although the app has shown a window
+ // since, under an id it did not recognise. They never count as starting.
+ property var settled: ({})
+
+ // The daemon ended a launch it was following: the window is there, under
+ // whatever button it went to, or the app gave up. The button's own wait
+ // ends with it.
+ signal launchFinished(key: string)
+ property var followed: ({})
+ onAllDaemonLaunchesChanged: {
+ const listed = {};
+ const now = {};
+ allDaemonLaunches.forEach(launch => {
+ listed[launch.desktopId] = true;
+ if (launch.confirmed) {
+ now[launch.desktopId] = true;
+ }
+ });
+ const ended = Object.keys(followed).filter(key => listed[key] !== true);
+ followed = now;
+ if (ended.length > 0) {
+ const next = Object.assign({}, launches);
+ Object.keys(next).forEach(key => {
+ if (ended.indexOf(desktopIdOf(key)) >= 0) {
+ delete next[key];
+ }
+ });
+ launches = next;
+ ended.forEach(key => launchFinished(key));
+ }
+ }
+
+ // A launcher URL or app id as a lower-case desktop id, as the daemon
+ // names its launches.
+ function desktopIdOf(key: string): string {
+ return String(key).replace(/^.*[\/:]/, "").replace(/\.desktop$/, "").toLowerCase();
+ }
+
+ onDaemonIdsChanged: {
+ const next = {};
+ let dropped = false;
+ Object.keys(settled).forEach(key => {
+ if (daemonIds[key] === true) {
+ next[key] = true;
+ } else {
+ dropped = true;
+ }
+ });
+ if (dropped) {
+ settled = next;
+ }
+ }
+ readonly property var daemonLaunches: allDaemonLaunches.filter(launch => settled[launch.desktopId] !== true)
readonly property var daemonStarting: {
const ids = {};
daemonLaunches.forEach(launch => ids[launch.desktopId] = true);
@@ -237,7 +316,7 @@ PlasmoidItem {
}
Component.onCompleted: {
- launcherList = Plasmoid.configuration.launchers;
+ launcherList = tasks.mendLaunchers(Plasmoid.configuration.launchers);
groupingAppIdBlacklist = Plasmoid.configuration.groupingAppIdBlacklist;
groupingLauncherUrlBlacklist = Plasmoid.configuration.groupingLauncherUrlBlacklist;
@@ -279,7 +358,7 @@ PlasmoidItem {
target: Plasmoid.configuration
function onLaunchersChanged(): void {
- tasksModel.launcherList = Plasmoid.configuration.launchers;
+ tasksModel.launcherList = tasks.mendLaunchers(Plasmoid.configuration.launchers);
}
function onGroupingAppIdBlacklistChanged(): void {
tasksModel.groupingAppIdBlacklist = Plasmoid.configuration.groupingAppIdBlacklist;
@@ -440,6 +519,21 @@ PlasmoidItem {
readonly property bool supportsLaunchers: true
+ // Start's Pin to taskbar once wrote "applications:applications:<app>"
+ // for apps picked from search or the pinned grid, which Plasma cannot
+ // resolve: a blank button that only plays the error sound. Such pins are
+ // mended where they are read, and the mended list is saved back.
+ function mendLaunchers(launchers: var): var {
+ const mended = [];
+ Array.from(launchers ?? []).forEach(launcher => {
+ const url = String(launcher).replace(/^(applications:)+/, "applications:");
+ if (!mended.includes(url)) {
+ mended.push(url);
+ }
+ });
+ return mended;
+ }
+
function hasLauncher(url: url): bool {
return tasksModel.launcherPosition(url) !== -1;
}
diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.updates/contents/ui/Flyout.qml b/packages/wildos-branding/files/plasmoids/org.wildos.updates/contents/ui/Flyout.qml
index 759446c..644004b 100644
--- a/packages/wildos-branding/files/plasmoids/org.wildos.updates/contents/ui/Flyout.qml
+++ b/packages/wildos-branding/files/plasmoids/org.wildos.updates/contents/ui/Flyout.qml
@@ -91,18 +91,31 @@ FocusScope {
radius: 22
color: flyout.attention ? UI.Style.warning : UI.Style.accent
+ readonly property bool done: flyout.updates.phase === "current" && !flyout.updates.restartNeeded
+
UI.Icon {
- id: badgeIcon
+ visible: flyout.updates.failed || badge.done
anchors.centerIn: parent
- readonly property bool done: flyout.updates.phase === "current" && !flyout.updates.restartNeeded
- name: flyout.updates.failed ? "warning" : done ? "check" : "update"
+ name: flyout.updates.failed ? "warning" : "check"
size: 24
- strokeWidth: done ? 2.6 : 2.2
+ strokeWidth: badge.done ? 2.6 : 2.2
+ color: UI.Style.textOnAccent
+ }
+
+ // The taskbar's two-arrow icon.
+ UI.Glyph {
+ id: badgeIcon
+ visible: !flyout.updates.failed && !badge.done
+ anchors.centerIn: parent
+ width: 22
+ height: 22
+ path: "M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8M21 3v5h-5M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16M8 16H3v5"
+ strokeWidth: 2.2
color: UI.Style.textOnAccent
RotationAnimator {
target: badgeIcon
- running: flyout.updates.busy
+ running: flyout.updates.busy && (flyout.updates.phase !== "installing" || flyout.updates.working)
from: 0
to: 360
duration: 1200
@@ -179,7 +192,7 @@ FocusScope {
visible: flyout.updates.phase !== "installing"
size: "small"
kind: flyout.updates.ready ? "text" : "secondary"
- text: flyout.updates.phase === "checking" ? "Checking" : "Check now"
+ text: flyout.updates.phase === "checking" ? "Checking" : flyout.updates.failed ? "Try again" : "Check now"
busy: flyout.updates.phase === "checking"
enabled: flyout.updates.canCheck
focusPolicy: Qt.NoFocus
diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.updates/contents/ui/UpdateButton.qml b/packages/wildos-branding/files/plasmoids/org.wildos.updates/contents/ui/UpdateButton.qml
index a87c73a..ef2fb68 100644
--- a/packages/wildos-branding/files/plasmoids/org.wildos.updates/contents/ui/UpdateButton.qml
+++ b/packages/wildos-branding/files/plasmoids/org.wildos.updates/contents/ui/UpdateButton.qml
@@ -2,11 +2,12 @@ import QtQuick
import QtQuick.Layouts
import WildOS.UI as UI
-// The taskbar button: a 16 px update icon in a 32 px cell with a 32 by 36
-// hover, the same as the tray's icons and the security button beside it. A dot on the
-// icon when updates are ready to install (sand when security fixes are
-// among them), the icon turning while something checks or installs, and
-// the warning sign when the last check failed.
+// The taskbar button, there only while an update downloads or installs:
+// the two-arrow refresh icon in white, a little smaller than the shield
+// beside it because it fills more of its square, so the two look the same
+// size. It turns while the work is under way, and stands still while the
+// install waits its turn. A 32 px cell with a 32 by 36 hover, the same as
+// the tray's icons and the shield.
MouseArea {
id: button
@@ -43,13 +44,15 @@ MouseArea {
}
}
- UI.Icon {
+ UI.Glyph {
id: icon
anchors.centerIn: parent
- name: button.updates.failed ? "warning" : "update"
- size: 16
- strokeWidth: 2
- color: button.updates.failed ? UI.Style.warning : UI.Style.iconInk
+ width: 14
+ height: 14
+ path: "M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8M21 3v5h-5M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16M8 16H3v5"
+ // The shield's line weight at 16 px, drawn at 14.
+ strokeWidth: 2.3
+ color: button.updates.failed ? UI.Style.warning : UI.Style.dark ? "#ffffff" : UI.Style.iconInk
// A plain number animation, not an animator, so the angle is known
// when the work ends and the turn can finish instead of snapping back
@@ -63,7 +66,7 @@ MouseArea {
to: 360
duration: 1200
loops: Animation.Infinite
- running: button.updates.busy
+ running: button.updates.working
}
NumberAnimation {
id: settle
@@ -75,8 +78,8 @@ MouseArea {
}
Connections {
target: button.updates
- function onBusyChanged() {
- if (button.updates.busy) {
+ function onWorkingChanged() {
+ if (button.updates.working) {
settle.stop();
} else if (icon.rotation > 0) {
settle.duration = Math.max(200, 2 * (360 - icon.rotation) / 360 * 1200);
@@ -86,8 +89,7 @@ MouseArea {
}
}
- // On the arrow's end, top right of the icon, where it reads as a badge
- // without covering the arrow.
+ // Updates are waiting: amber when one of them fixes a security problem.
Rectangle {
visible: button.updates.ready
x: icon.x + icon.width - width + 1
diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.updates/contents/ui/main.qml b/packages/wildos-branding/files/plasmoids/org.wildos.updates/contents/ui/main.qml
index d06198d..c08c837 100644
--- a/packages/wildos-branding/files/plasmoids/org.wildos.updates/contents/ui/main.qml
+++ b/packages/wildos-branding/files/plasmoids/org.wildos.updates/contents/ui/main.qml
@@ -6,8 +6,9 @@ import org.kde.plasma.core as PlasmaCore
import org.kde.plasma.plasma5support as P5Support
import WildOS.UI as UI
-// The Updates icon beside Protection on the taskbar and its flyout: whether
-// updates are waiting, checking for them, and installing them through
+// The Updates icon beside the shield on the taskbar and its flyout. The icon
+// is only there while an update downloads or installs, turning while that
+// work is under way; the flyout says what is happening and installs through
// Settings, which asks for the password. Everything shown comes from
// /usr/libexec/wildos/update-status, which asks PackageKit, so it always
// agrees with Settings > Updates and the Store.
@@ -27,6 +28,10 @@ PlasmoidItem {
readonly property int count: number(status.updates)
readonly property int securityCount: number(status.security)
readonly property bool busy: phase === "checking" || phase === "installing"
+ // Downloading or installing: the only time the icon is on the taskbar.
+ readonly property bool installing: phase === "installing"
+ // Queued, or waiting for apt's lock or the password: there, but still.
+ readonly property bool working: installing && status.waiting !== "yes"
readonly property bool byAuto: status.by === "auto"
readonly property bool restartNeeded: status.restart === "yes"
readonly property bool ready: phase === "available"
@@ -175,10 +180,51 @@ PlasmoidItem {
Timer {
running: true
repeat: true
- interval: updates.busy || updates.expanded || updates.justAsked ? 4000 : 30000
+ // Every two minutes when nothing is happening: each check starts a
+ // program, and nothing the icon shows needs to be fresher.
+ interval: updates.busy || updates.expanded || updates.justAsked || updates.packageKitUp ? 4000 : 120000
onTriggered: updates.refreshStatus()
}
+ // Settings > Updates and update-status keep the check they share in one
+ // folder (who is checking, why the last check failed). Its time changes
+ // whenever either writes, so a check started or finished in Settings
+ // shows here within seconds, for the price of one stat. Whether
+ // PackageKit and the automatic security updates are running goes with
+ // it, so the icon comes up within seconds of an install starting,
+ // however it was started, without asking PackageKit (which would start
+ // it) every few seconds.
+ property string sharedStamp: ""
+ readonly property bool packageKitUp: / (active|activating)/.test(sharedStamp)
+ property int stampCount: 0
+
+ P5Support.DataSource {
+ id: stamp
+ engine: "executable"
+ onNewData: (source, data) => {
+ disconnectSource(source);
+ const next = String(data.stdout).trim();
+ if (next !== updates.sharedStamp) {
+ const first = updates.sharedStamp === "";
+ updates.sharedStamp = next;
+ if (!first) {
+ updates.refreshStatus();
+ }
+ }
+ }
+ }
+
+ Timer {
+ running: updates.loaded && updates.phase !== "na"
+ repeat: true
+ interval: 5000
+ onTriggered: {
+ updates.stampCount += 1;
+ stamp.connectSource("{ stat -c %.9Y \"${XDG_RUNTIME_DIR:-/tmp}/wildos-updates\" 2>/dev/null || echo none; "
+ + "systemctl is-active packagekit.service apt-daily-upgrade.service; } | tr '\n' ' ' #" + updates.stampCount);
+ }
+ }
+
// One-off commands; a check answers with the status once it is done.
P5Support.DataSource {
id: shell
@@ -238,7 +284,9 @@ PlasmoidItem {
Plasmoid.backgroundHints: PlasmaCore.Types.NoBackground
Plasmoid.icon: "system-software-update"
Plasmoid.title: "Updates"
- Plasmoid.status: ready || failed ? PlasmaCore.Types.ActiveStatus : PlasmaCore.Types.PassiveStatus
+ // On the taskbar while an update is under way, waiting to install or
+ // has failed: the last two need the person.
+ Plasmoid.status: installing || ready || failed ? PlasmaCore.Types.ActiveStatus : PlasmaCore.Types.PassiveStatus
toolTipMainText: summary
toolTipSubText: loaded && phase !== "na" ? checkedText : ""
diff --git a/packages/wildos-branding/files/plasmoids/org.wildos.winmode/contents/ui/main.qml b/packages/wildos-branding/files/plasmoids/org.wildos.winmode/contents/ui/main.qml
index 7add502..b069493 100644
--- a/packages/wildos-branding/files/plasmoids/org.wildos.winmode/contents/ui/main.qml
+++ b/packages/wildos-branding/files/plasmoids/org.wildos.winmode/contents/ui/main.qml
@@ -311,7 +311,63 @@ PlasmoidItem {
property int readCount: 0
property int misses: 0
+ // With the agent up, both services are asked over D-Bus, as the
+ // command-line tool does: starting that tool every ten seconds cost
+ // about one percent of a processor core. The tool stays for PCs where
+ // the agent isn't running, since asking it over D-Bus would start it.
+ property bool asking: false
+
+ function unanswered(): void {
+ asking = false;
+ receive(JSON.stringify({ agent: null, system: null, answering: false }));
+ }
+
+ function refreshOverDBus(): void {
+ if (asking) {
+ return;
+ }
+ asking = true;
+ const agentReply = DBus.SessionBus.asyncCall({
+ service: "org.wildos.WindowsMode1",
+ path: "/org/wildos/WindowsMode1",
+ iface: "org.wildos.WindowsMode1",
+ member: "Status"
+ });
+ agentReply.finished.connect(() => {
+ if (agentReply.isError) {
+ unanswered();
+ return;
+ }
+ const hostReply = DBus.SystemBus.asyncCall({
+ service: "org.wildos.WindowsMode1",
+ path: "/org/wildos/WindowsMode1",
+ iface: "org.wildos.WindowsMode1.Host",
+ member: "Status"
+ });
+ hostReply.finished.connect(() => {
+ if (hostReply.isError) {
+ unanswered();
+ return;
+ }
+ let agentStatus, hostStatus;
+ try {
+ agentStatus = JSON.parse(String(agentReply.value));
+ hostStatus = JSON.parse(String(hostReply.value));
+ } catch (e) {
+ unanswered();
+ return;
+ }
+ asking = false;
+ receive(JSON.stringify({ agent: agentStatus, system: hostStatus }));
+ });
+ });
+ }
+
function refresh(): void {
+ if (agentWatcher.registered) {
+ refreshOverDBus();
+ return;
+ }
if (reader.current !== "") {
return;
}
diff --git a/packages/wildos-branding/files/polkit/org.wildos.camera-mic.policy b/packages/wildos-branding/files/polkit/org.wildos.camera-mic.policy
new file mode 100644
index 0000000..27b4983
--- /dev/null
+++ b/packages/wildos-branding/files/polkit/org.wildos.camera-mic.policy
@@ -0,0 +1,52 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE policyconfig PUBLIC
+ "-//freedesktop//DTD PolicyKit Policy Configuration 1.0//EN"
+ "http://www.freedesktop.org/standards/PolicyKit/1/policyconfig.dtd">
+<!-- The switches and the Stop button in the taskbar's camera and microphone
+ panel. Only /usr/libexec/wildos/camera-mic-block runs under these, and
+ it takes nothing but the device. Switching a device off, and stopping
+ an app, never asks: they only take access away. Switching one back on
+ asks for the password, so an app cannot quietly turn it on again. -->
+<policyconfig>
+ <vendor>Wild OS</vendor>
+ <vendor_url>https://wildos.io</vendor_url>
+
+ <action id="org.wildos.camera-mic.block">
+ <description>Turn off the camera or microphone for every app</description>
+ <message>Turn off the camera or microphone for every app?</message>
+ <icon_name>security-high</icon_name>
+ <defaults>
+ <allow_any>no</allow_any>
+ <allow_inactive>no</allow_inactive>
+ <allow_active>yes</allow_active>
+ </defaults>
+ <annotate key="org.freedesktop.policykit.exec.path">/usr/libexec/wildos/camera-mic-block</annotate>
+ <annotate key="org.freedesktop.policykit.exec.argv1">block</annotate>
+ </action>
+
+ <action id="org.wildos.camera-mic.release">
+ <description>Stop an app using the camera</description>
+ <message>Stop the app using the camera?</message>
+ <icon_name>security-high</icon_name>
+ <defaults>
+ <allow_any>no</allow_any>
+ <allow_inactive>no</allow_inactive>
+ <allow_active>yes</allow_active>
+ </defaults>
+ <annotate key="org.freedesktop.policykit.exec.path">/usr/libexec/wildos/camera-mic-block</annotate>
+ <annotate key="org.freedesktop.policykit.exec.argv1">release</annotate>
+ </action>
+
+ <action id="org.wildos.camera-mic.unblock">
+ <description>Turn the camera or microphone back on</description>
+ <message>Turn this back on for every app?</message>
+ <icon_name>security-high</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/camera-mic-block</annotate>
+ <annotate key="org.freedesktop.policykit.exec.argv1">unblock</annotate>
+ </action>
+</policyconfig>
diff --git a/packages/wildos-branding/files/sddm.conf.d/30-wildos-pointer.conf b/packages/wildos-branding/files/sddm.conf.d/30-wildos-pointer.conf
new file mode 100644
index 0000000..ddc7855
--- /dev/null
+++ b/packages/wildos-branding/files/sddm.conf.d/30-wildos-pointer.conf
@@ -0,0 +1,3 @@
+# The sign-in screen uses the same white pointer as the desktop.
+[Theme]
+CursorTheme=Breeze_Light
diff --git a/packages/wildos-branding/files/sddm/wildos/Main.qml b/packages/wildos-branding/files/sddm/wildos/Main.qml
index 9a6bbd5..7da559d 100644
--- a/packages/wildos-branding/files/sddm/wildos/Main.qml
+++ b/packages/wildos-branding/files/sddm/wildos/Main.qml
@@ -36,6 +36,11 @@ Item {
// PAM profile). Whose finger is enrolled can't be seen from here, so the
// hint follows the reader alone.
property bool fingerprintReader: false
+ // Advanced protection can ask for the password once after a restart
+ // and again after some hours; until then the finger is turned down, so
+ // it isn't offered.
+ readonly property bool fingerprintNow: fingerprintReader && UI.System.fingerprintAllowed !== undefined
+ && UI.System.fingerprintAllowed(hasUserList ? currentUserName : usernamePill.text.trim())
property bool triedFingerprint: false
// Values for the chosen user, read through a Repeater because SDDM's
@@ -44,6 +49,9 @@ Item {
property string currentRealName: ""
property string currentIcon: ""
property bool currentNeedsPassword: true
+ // The guest session's account (Advanced protection > Guest session),
+ // made without a password; only it is called guest and has none.
+ property bool currentIsGuest: false
property string currentSessionName: ""
function signIn() {
@@ -57,7 +65,7 @@ Item {
failureMessage = "";
infoMessage = "";
busy = true;
- triedFingerprint = fingerprintReader && passwordPill.text.length === 0;
+ triedFingerprint = fingerprintNow && passwordPill.text.length === 0;
sddm.login(user, passwordPill.text, sessionIndex);
}
@@ -118,12 +126,19 @@ Item {
required property string icon
required property bool needsPassword
readonly property bool chosen: index === root.userIndex
+ readonly property bool guest: name === "guest" && !needsPassword
visible: false
onChosenChanged: sync()
Component.onCompleted: {
const list = root.users.slice();
- list[index] = { name: name, realName: realName };
+ list[index] = { name: name, realName: realName, guest: guest };
root.users = list;
+ // The screen opens on the PC's own people, even after a
+ // guest was the last to sign in.
+ if (chosen && guest && userModel.count > 1) {
+ root.userIndex = index === 0 ? 1 : 0;
+ return;
+ }
sync();
}
function sync() {
@@ -133,6 +148,7 @@ Item {
root.currentRealName = realName.length > 0 ? realName : name;
root.currentIcon = icon;
root.currentNeedsPassword = needsPassword;
+ root.currentIsGuest = guest;
}
}
}
@@ -320,7 +336,7 @@ Item {
anchors.horizontalCenter: parent.horizontalCenter
width: parent.width
spacing: 6
- visible: failureNotice.shown || hintNotice.shown || capsNotice.shown || infoNotice.shown || fingerprintNotice.shown
+ visible: failureNotice.shown || hintNotice.shown || capsNotice.shown || infoNotice.shown || fingerprintNotice.shown || guestNotice.shown
Notice {
id: failureNotice
@@ -340,11 +356,17 @@ Item {
}
Notice {
id: fingerprintNotice
- shown: root.fingerprintReader && passwordPill.visible && !root.busy && passwordPill.text.length === 0
+ shown: root.fingerprintNow && passwordPill.visible && !root.busy && passwordPill.text.length === 0
&& root.failureMessage.length === 0 && root.infoMessage.length === 0
text: "Or press Enter and touch the fingerprint reader"
muted: true
}
+ Notice {
+ id: guestNotice
+ shown: root.hasUserList && root.currentIsGuest && root.failureMessage.length === 0
+ text: "A clean desktop, wiped when you sign out."
+ muted: true
+ }
Notice {
id: capsNotice
shown: keyboard.capsLock
@@ -381,7 +403,7 @@ Item {
value: root.currentRealName
choices: root.users.map((user, index) => ({
text: user.realName.length > 0 ? user.realName : user.name,
- detail: user.realName.length > 0 && user.realName !== user.name ? user.name : "",
+ detail: user.guest ? "Wiped when they sign out" : user.realName.length > 0 && user.realName !== user.name ? user.name : "",
checked: index === root.userIndex,
run: () => {
root.userIndex = index;
diff --git a/packages/wildos-branding/files/sddm/wildos/components/BootHandoff.qml b/packages/wildos-branding/files/sddm/wildos/components/BootHandoff.qml
index c62b222..5efa60b 100644
--- a/packages/wildos-branding/files/sddm/wildos/components/BootHandoff.qml
+++ b/packages/wildos-branding/files/sddm/wildos/components/BootHandoff.qml
@@ -34,6 +34,15 @@ Item {
// Typing into these skips to the end.
property Item input
property Item secondInput
+ // Plays the boards' timeline this much faster.
+ property real speed: 1.15
+ // Set by the session splash once Plasma has drawn the desktop: the W then
+ // opens onto the real desktop, taskbar and windows included, instead of
+ // the photo, so nothing is left to fade in when the flight ends.
+ property bool live: false
+ // Ends as the flight lands instead of after the sign-in screen's clock
+ // fades in: the desktop has no clock to wait for.
+ property bool endOnLanding: false
readonly property bool active: markerImage.status === Image.Ready && !done
readonly property bool afterUnlock: unlockedImage.status === Image.Ready
@@ -82,6 +91,10 @@ Item {
property real d: 0
property real skip: 0
property bool done: false
+ // Decode the photo at the size it is shown, grown 1.18 times at most,
+ // rather than at its full 4K: decoding it twice at full size held up the
+ // first frame. Wild OS photos are 16:9.
+ readonly property int photoDecodeWidth: Math.ceil(1.18 * Math.max(screenW, screenH * 16 / 9))
readonly property string assets: "file:///usr/share/plymouth/themes/wildos/"
readonly property string handoffAssets: "file:///usr/share/wildos/boot-handoff/"
@@ -167,14 +180,21 @@ Item {
Rectangle {
anchors.fill: parent
color: handoff.k.background
+ visible: !(handoff.live && handoff.d >= handoff.k.cover)
}
// The wallpaper, there from the moment the cover goes up, settling from
- // 1.18 to its place as the screen flies through the W.
+ // 1.18 to its place as the screen flies through the W. When the desktop
+ // is ready before the cover goes up it never shows; when it is ready
+ // later, it gives way to the desktop part way through.
Item {
id: photoLayer
anchors.fill: parent
- visible: handoff.d >= handoff.k.cover
+ visible: handoff.d >= handoff.k.cover && opacity > 0
+ opacity: handoff.live ? 0 : 1
+ Behavior on opacity {
+ NumberAnimation { duration: 400; easing.type: Easing.InOutQuad }
+ }
Image {
id: photo
@@ -191,10 +211,12 @@ Item {
x: (photoLayer.width - width) / 2
y: (photoLayer.height - height) * handoff.photoFocus
source: handoff.active ? handoff.photoSource : ""
+ sourceSize.width: handoff.photoDecodeWidth
// Loaded before the first frame; until then the screen still
- // shows Plymouth's identical last frame.
+ // shows Plymouth's identical last frame. Cached, so the screen
+ // around this shares the one decode.
asynchronous: false
- cache: false
+ cache: true
smooth: true
mipmap: true
transform: Scale {
@@ -390,8 +412,8 @@ Item {
Component.onCompleted: d = k.start
function tick() {
- const end = k.clockEnd + 0.4;
- d = Math.min(end, k.start + (Date.now() - startedAt) / 1000);
+ const end = endOnLanding ? k.zoom[1] : k.clockEnd + 0.4;
+ d = Math.min(end, k.start + speed * (Date.now() - startedAt) / 1000);
if (d >= end) {
done = true;
finished();
diff --git a/packages/wildos-branding/files/sddm/wildos/components/PasswordPill.qml b/packages/wildos-branding/files/sddm/wildos/components/PasswordPill.qml
index 697a7bb..2be92af 100644
--- a/packages/wildos-branding/files/sddm/wildos/components/PasswordPill.qml
+++ b/packages/wildos-branding/files/sddm/wildos/components/PasswordPill.qml
@@ -70,6 +70,7 @@ FocusScope {
font.letterSpacing: pill.secret && text.length > 0 ? 1.5 : 0
echoMode: pill.secret ? TextInput.Password : TextInput.Normal
passwordCharacter: "•"
+ UI.NoPaste { enabled: pill.secret }
placeholderText: pill.placeholder
placeholderTextColor: UI.Style.inkOnWallpaperMuted
inputMethodHints: pill.secret ? (Qt.ImhHiddenText | Qt.ImhSensitiveData | Qt.ImhNoAutoUppercase | Qt.ImhNoPredictiveText)
diff --git a/packages/wildos-branding/files/systemd-user/wildos-camera-mic.service b/packages/wildos-branding/files/systemd-user/wildos-camera-mic.service
new file mode 100644
index 0000000..f6f3877
--- /dev/null
+++ b/packages/wildos-branding/files/systemd-user/wildos-camera-mic.service
@@ -0,0 +1,14 @@
+[Unit]
+Description=Camera and microphone lights on the taskbar
+Documentation=file:///usr/libexec/wildos/camera-mic
+PartOf=graphical-session.target
+After=graphical-session.target pipewire.service
+# The sign-in screen's account has no apps.
+ConditionUser=!@system
+
+[Service]
+ExecStart=/usr/libexec/wildos/camera-mic watch
+# Its "USE" lines are how Settings > System > History learns of each use.
+SyslogIdentifier=wildos-camera-mic
+Restart=always
+RestartSec=2
diff --git a/packages/wildos-branding/files/systemd-user/wildos-panic-key.path b/packages/wildos-branding/files/systemd-user/wildos-panic-key.path
new file mode 100644
index 0000000..86f4d24
--- /dev/null
+++ b/packages/wildos-branding/files/systemd-user/wildos-panic-key.path
@@ -0,0 +1,7 @@
+[Unit]
+Description=Follow the panic key switch in Advanced protection
+ConditionUser=!@system
+
+[Path]
+PathChanged=/etc/wildos/advanced-protection
+Unit=wildos-panic-key.service
diff --git a/packages/wildos-branding/files/systemd-user/wildos-panic-key.service b/packages/wildos-branding/files/systemd-user/wildos-panic-key.service
new file mode 100644
index 0000000..dfd3e23
--- /dev/null
+++ b/packages/wildos-branding/files/systemd-user/wildos-panic-key.service
@@ -0,0 +1,8 @@
+[Unit]
+Description=Turn the panic key on or off for this account
+ConditionUser=!@system
+After=plasma-kwin_wayland.service
+
+[Service]
+Type=oneshot
+ExecStart=/usr/libexec/wildos/panic-key switch
diff --git a/packages/wildos-branding/files/systemd-user/wildos-panic-offer.service b/packages/wildos-branding/files/systemd-user/wildos-panic-offer.service
new file mode 100644
index 0000000..00c69fe
--- /dev/null
+++ b/packages/wildos-branding/files/systemd-user/wildos-panic-offer.service
@@ -0,0 +1,7 @@
+[Unit]
+Description=Offer to turn the network back on after the panic key
+ConditionUser=!@system
+
+[Service]
+Type=exec
+ExecStart=/usr/libexec/wildos/panic-key offer
diff --git a/packages/wildos-branding/files/systemd-user/wildos-panic.service b/packages/wildos-branding/files/systemd-user/wildos-panic.service
new file mode 100644
index 0000000..cdaece5
--- /dev/null
+++ b/packages/wildos-branding/files/systemd-user/wildos-panic.service
@@ -0,0 +1,7 @@
+[Unit]
+Description=Panic key: lock the screen, clear the clipboard and cut the network
+ConditionUser=!@system
+
+[Service]
+Type=oneshot
+ExecStart=/usr/libexec/wildos/panic-key
diff --git a/packages/wildos-branding/files/systemd-user/wildos-shutdown-guard.service b/packages/wildos-branding/files/systemd-user/wildos-shutdown-guard.service
new file mode 100644
index 0000000..afa44b1
--- /dev/null
+++ b/packages/wildos-branding/files/systemd-user/wildos-shutdown-guard.service
@@ -0,0 +1,9 @@
+[Unit]
+Description=Finish shutdowns the lid or power button started
+# Not part of the graphical session: it has to outlive the sign-out that
+# every shutdown starts with. The sign-in screen's account has no apps.
+ConditionUser=!@system
+
+[Service]
+ExecStart=/usr/libexec/wildos/shutdown-guard
+Restart=on-failure
diff --git a/packages/wildos-branding/files/systemd-user/wildos-shutdown-notice.service b/packages/wildos-branding/files/systemd-user/wildos-shutdown-notice.service
new file mode 100644
index 0000000..83d7e08
--- /dev/null
+++ b/packages/wildos-branding/files/systemd-user/wildos-shutdown-notice.service
@@ -0,0 +1,16 @@
+[Unit]
+Description=Say which apps the last shutdown closed without saving
+# Once the start-up splash has gone: Plasma keeps a notification sent while
+# something fills the screen out of sight, in its history only.
+After=plasma-ksplash-ready.service plasma-ksplash.service
+PartOf=graphical-session.target
+ConditionUser=!@system
+ConditionPathExists=%S/wildos/closed-at-shutdown.json
+
+[Service]
+Type=oneshot
+# The taskbar's notification area, which draws the pop-ups, loads a few
+# seconds after the splash has gone; until then a notification only goes
+# to the history.
+ExecStartPre=/bin/sleep 6
+ExecStart=/usr/libexec/wildos/shutdown-guard --notice
diff --git a/packages/wildos-branding/files/systemd/[email protected]/wildos-kbd-light.conf b/packages/wildos-branding/files/systemd/[email protected]/wildos-kbd-light.conf
new file mode 100644
index 0000000..158664a
--- /dev/null
+++ b/packages/wildos-branding/files/systemd/[email protected]/wildos-kbd-light.conf
@@ -0,0 +1,5 @@
+# systemd-backlight puts back the level saved at the last shut down. A lid
+# close or idle screen turns the keyboard light off just before that save,
+# so a saved "off" would leave it dark at the next start; it comes on again.
+[Service]
+ExecStartPost=-/usr/libexec/wildos/kbd-backlight-default --restored %I
diff --git a/packages/wildos-branding/files/udev/72-wildos-camera-mic.rules b/packages/wildos-branding/files/udev/72-wildos-camera-mic.rules
new file mode 100644
index 0000000..6f15c66
--- /dev/null
+++ b/packages/wildos-branding/files/udev/72-wildos-camera-mic.rules
@@ -0,0 +1,11 @@
+# The switches in the taskbar's camera and microphone panel
+# (/usr/libexec/wildos/camera-mic-block). While one is off, its devices
+# belong to root alone: no group, so the audio and video groups every
+# account is in give nothing, and no uaccess, so logind gives the person at
+# the screen no access list either. Before 73-seat-late.rules, which is
+# where uaccess is applied.
+
+SUBSYSTEM=="sound", KERNEL=="pcmC[0-9]*D[0-9]*c", TEST=="/etc/wildos/microphone-off", TAG-="uaccess", GROUP="root", MODE="0600"
+
+SUBSYSTEM=="video4linux", TEST=="/etc/wildos/camera-off", TAG-="uaccess", GROUP="root", MODE="0600"
+SUBSYSTEM=="media", TEST=="/etc/wildos/camera-off", TAG-="uaccess", GROUP="root", MODE="0600"
diff --git a/packages/wildos-branding/files/udev/90-wildos-kbd-backlight.rules b/packages/wildos-branding/files/udev/90-wildos-kbd-backlight.rules
new file mode 100644
index 0000000..773ee21
--- /dev/null
+++ b/packages/wildos-branding/files/udev/90-wildos-kbd-backlight.rules
@@ -0,0 +1,2 @@
+# Keyboard lights start on, from the disk unlock prompt onwards.
+ACTION=="add", SUBSYSTEM=="leds", KERNEL=="*::kbd_backlight*", RUN+="/usr/libexec/wildos/kbd-backlight-default %k"
diff --git a/packages/wildos-branding/files/usbguard/40-wildos-built-in.conf b/packages/wildos-branding/files/usbguard/40-wildos-built-in.conf
new file mode 100644
index 0000000..6f26cbc
--- /dev/null
+++ b/packages/wildos-branding/files/usbguard/40-wildos-built-in.conf
@@ -0,0 +1,9 @@
+# Devices inside the computer (Bluetooth, fingerprint reader, webcam, card
+# reader) sit on USB ports the firmware marks as not reachable from outside:
+# "hardwired", or "not used" for a port with no socket. Some of them reset
+# themselves after start-up and come back looking newly plugged in, which held
+# Bluetooth back until it was allowed by hand. Ports with a socket report
+# "hotplug" and still follow Block new USB devices. After Kicksecure's
+# 30_security-misc.conf, so its refusals of risky interfaces still come first.
+allow with-connect-type "hardwired"
+allow with-connect-type "not used"
diff --git a/packages/wildos-branding/files/xdg-share/taskmanagerrulesrc b/packages/wildos-branding/files/xdg-share/taskmanagerrulesrc
new file mode 100644
index 0000000..602bbd5
--- /dev/null
+++ b/packages/wildos-branding/files/xdg-share/taskmanagerrulesrc
@@ -0,0 +1,19 @@
+# Plasma's own rules, plus apps whose window names a different app than
+# their Start entry, so the taskbar shows the app's icon and pins match.
+[Mapping]
+Gimp-2.8=GIMP
+Gimp-2.10=GIMP
+Gimp-2.12=GIMP
+Google-chrome=Google Chrome
+Google-chrome-stable=Google Chrome
+Systemsettings=System Settings
+oracle-ide-boot-Launcher=Oracle SQL Developer
+Dragon=dragonplayer
+VirtualBox Manager=virtualbox
+VirtualBox Machine=virtualbox
+ai.elementlabs.lmstudio=ai.lmstudio.lm-studio
+
+[Settings]
+MatchCommandLineFirst=perl
+TryIgnoreRuntimes=perl
+SkipTaskbar=Soffice
diff --git a/packages/wildos-branding/files/xdg/kactivitymanagerd-pluginsrc b/packages/wildos-branding/files/xdg/kactivitymanagerd-pluginsrc
new file mode 100644
index 0000000..f284170
--- /dev/null
+++ b/packages/wildos-branding/files/xdg/kactivitymanagerd-pluginsrc
@@ -0,0 +1,6 @@
+# Recent files are kept for 3 months, not KDE's default of forever: enough
+# for Start and Files to offer what you worked on lately, without keeping a
+# record of every file ever opened. Settings > Privacy and security >
+# Activity history changes it for your account.
+[Plugin-org.kde.ActivityManager.Resources.Scoring]
+keep-history-for=3
diff --git a/packages/wildos-branding/files/xdg/kcminputrc b/packages/wildos-branding/files/xdg/kcminputrc
index 9d267ad..e8b134b 100644
--- a/packages/wildos-branding/files/xdg/kcminputrc
+++ b/packages/wildos-branding/files/xdg/kcminputrc
@@ -5,3 +5,8 @@
# keep the usual direction, as on Windows.
[Libinput][Defaults][Touchpad]
NaturalScroll=true
+
+# A white pointer with a dark edge, as on Windows. Settings > Accessibility >
+# Pointer colour changes it for your account.
+[Mouse]
+cursorTheme=Breeze_Light
diff --git a/packages/wildos-branding/files/xdg/kwinrc b/packages/wildos-branding/files/xdg/kwinrc
index 935bc87..65fd4ed 100644
--- a/packages/wildos-branding/files/xdg/kwinrc
+++ b/packages/wildos-branding/files/xdg/kwinrc
@@ -24,6 +24,10 @@ org.wildos.launchEnabled=true
# showing the desktop, so only one may run.
windowapertureEnabled=false
org.wildos.peekfadeEnabled=true
+# wildos-shell's fade between the old and new colours when the theme or
+# accent changes takes the place of KWin's, which flashed a darker shadow
+# round each window. Both answer the same D-Bus call, so only one may run.
+blendchangesEnabled=false
# Mica, as on Windows 11: the wallpaper behind glass is blurred until no shapes
# show, only a soft gradient of its colours, under a mostly opaque tint
diff --git a/packages/wildos-branding/files/xdg/powerdevilrc b/packages/wildos-branding/files/xdg/powerdevilrc
index e092b63..df28b68 100644
--- a/packages/wildos-branding/files/xdg/powerdevilrc
+++ b/packages/wildos-branding/files/xdg/powerdevilrc
@@ -16,3 +16,24 @@ PowerProfile=power-saver
# battery changes either.
[AC][SuspendAndShutdown]
AutoSuspendAction=0
+
+# Battery saver ends when the PC is plugged in, as on Windows. powerdevil
+# changes the power mode only for a profile that names one, so without this
+# the PC stayed in power-saver after charging, at a fraction of its speed,
+# and kept it across restarts. Settings > Home still changes the mode by hand.
+[AC][Performance]
+PowerProfile=balanced
+
+# The keyboard light keeps whatever level it was left at: every start-up
+# turns it on (kbd-backlight-default) at the step used at the last shut
+# down. A level per profile would undo that at every sign-in and every time
+# the charger went in or out. While the screen dims for being idle the
+# light goes off, and it comes back with the next key press or touch.
+[AC][Keyboard]
+UseProfileSpecificKeyboardBrightness=false
+
+[Battery][Keyboard]
+UseProfileSpecificKeyboardBrightness=false
+
+[LowBattery][Keyboard]
+UseProfileSpecificKeyboardBrightness=false
diff --git a/packages/wildos-capture/CMakeLists.txt b/packages/wildos-capture/CMakeLists.txt
index 49b427c..1cb571f 100644
--- a/packages/wildos-capture/CMakeLists.txt
+++ b/packages/wildos-capture/CMakeLists.txt
@@ -1,5 +1,5 @@
cmake_minimum_required(VERSION 3.25)
-project(wildos-capture VERSION 0.1.1 LANGUAGES C CXX)
+project(wildos-capture VERSION 0.1.4 LANGUAGES C CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
@@ -19,6 +19,10 @@ find_package(KPipeWire REQUIRED)
find_package(PlasmaWaylandProtocols REQUIRED)
find_package(WaylandScanner REQUIRED)
find_package(Wayland REQUIRED COMPONENTS Client)
+# Scanning goes through SANE: sane-airscan for driverless network scanners,
+# SANE's own backends for USB ones.
+find_package(PkgConfig REQUIRED)
+pkg_check_modules(SANE REQUIRED IMPORTED_TARGET sane-backends)
qt_standard_project_setup(REQUIRES 6.8)
@@ -42,6 +46,9 @@ qt_add_qml_module(wildos-capture
src/recorder.cpp src/recorder.h
src/sharer.cpp src/sharer.h
src/frozenimage.cpp src/frozenimage.h
+ src/scanner.cpp src/scanner.h
+ src/scanworker.cpp src/scanworker.h
+ src/scanprocess.cpp src/scanprocess.h
)
# The recording stream comes from KWin's screencast protocol.
@@ -54,6 +61,7 @@ target_link_libraries(wildos-capture PRIVATE
Qt6::Widgets Qt6::DBus Qt6::Qml Qt6::Quick Qt6::QuickControls2 Qt6::WaylandClient
KF6::Notifications KF6::DBusAddons KF6::GuiAddons KF6::WindowSystem KF6::ConfigCore KF6::Purpose
K::KPipeWireRecord
+ PkgConfig::SANE
Wayland::Client
)
diff --git a/packages/wildos-capture/data/org.wildos.screenshot.desktop b/packages/wildos-capture/data/org.wildos.screenshot.desktop
index 3123236..4658d0c 100644
--- a/packages/wildos-capture/data/org.wildos.screenshot.desktop
+++ b/packages/wildos-capture/data/org.wildos.screenshot.desktop
@@ -7,9 +7,9 @@ Icon=wildos-capture
Exec=/usr/bin/wildos-screenshot
Terminal=false
Categories=Qt;Utility;Graphics;
-Keywords=screenshot;snip;snipping tool;print screen;capture;record;screen recording;mark up;annotate;
+Keywords=screenshot;snip;snipping tool;print screen;capture;record;screen recording;mark up;annotate;scan;scanner;scanning;document;
StartupNotify=false
-Actions=Record;
+Actions=Record;Scan;
# Win+Shift+S and Print Screen, as in Windows 11; Win+Shift+R records.
X-KDE-Shortcuts=Meta+Shift+S,Print
X-KDE-DBUS-Restricted-Interfaces=org.kde.KWin.ScreenShot2
@@ -21,3 +21,7 @@ X-DBUS-ServiceName=org.wildos.screenshot
Name=Record the screen
Exec=/usr/bin/wildos-screenshot --record
X-KDE-Shortcuts=Meta+Shift+R
+
+[Desktop Action Scan]
+Name=Scan a document
+Exec=/usr/bin/wildos-screenshot --scan
diff --git a/packages/wildos-capture/data/org.wildos.screenshot.metainfo.xml b/packages/wildos-capture/data/org.wildos.screenshot.metainfo.xml
index 718ff4b..9e59f65 100644
--- a/packages/wildos-capture/data/org.wildos.screenshot.metainfo.xml
+++ b/packages/wildos-capture/data/org.wildos.screenshot.metainfo.xml
@@ -16,6 +16,11 @@
pen, highlighter, arrow, box, text, blur and crop. It saves to
Pictures, in Screenshots. Nothing is sent anywhere.
</p>
+ <p>
+ The Scan tab scans paper from a network or USB scanner, from the glass
+ or the feeder, and saves the pages as a PDF or as pictures, or opens
+ them in PDF to sign.
+ </p>
</description>
<launchable type="desktop-id">org.wildos.screenshot.desktop</launchable>
<icon type="stock">wildos-capture</icon>
diff --git a/packages/wildos-capture/debian/changelog b/packages/wildos-capture/debian/changelog
index 177f635..c71fc26 100644
--- a/packages/wildos-capture/debian/changelog
+++ b/packages/wildos-capture/debian/changelog
@@ -1,3 +1,20 @@
+wildos-capture (0.1.5) trixie; urgency=medium
+
+ * Text you type onto a screenshot has the right-click menu with Cut,
+ Copy, Paste and Select all.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 08:54:22 +0000
+
+wildos-capture (0.1.4) trixie; urgency=medium
+
+ * Capture scans paper: a Scan tab next to Screenshot and Record finds
+ network scanners without a driver and USB scanners, scans from the
+ glass or the feeder, straightens each page, and saves the pages as a
+ PDF or as pictures or opens them in PDF to sign.
+ * wildos-capture --scan opens straight on the Scan tab.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 17:20:00 +0000
+
wildos-capture (0.1.3) trixie; urgency=medium
* Report a problem in the Options menu opens Report a problem with Capture
diff --git a/packages/wildos-capture/debian/control b/packages/wildos-capture/debian/control
index 5052de4..ee269d1 100644
--- a/packages/wildos-capture/debian/control
+++ b/packages/wildos-capture/debian/control
@@ -19,6 +19,8 @@ Build-Depends:
libkf6config-dev,
libkf6purpose-dev,
libkpipewire-dev,
+ libsane-dev,
+ pkgconf,
Standards-Version: 4.7.0
Rules-Requires-Root: no
@@ -27,7 +29,7 @@ Architecture: any
Depends:
${shlibs:Depends},
${misc:Depends},
- wildos-ui (>= 0.1.3),
+ wildos-ui (>= 0.1.11),
wildos-overlays (>= 0.1.1),
kwin-wayland,
layer-shell-qt,
@@ -40,9 +42,9 @@ Depends:
qml6-module-qtquick-window,
qml6-module-qtqml-workerscript,
libkf6purpose-bin,
-Breaks: wildos-overlays (<< 0.1.1)
+Breaks: wildos-overlays (<< 0.1.1), wildos-pdf (<< 0.1.4)
Replaces: wildos-overlays (<< 0.1.1)
-Description: Wild OS Capture: screenshots and screen recording
+Description: Wild OS Capture: screenshots, screen recording and scanning
Print Screen and Win+Shift+S bring up the Capture toolbar over a frozen
screen: take a screenshot or record, of an area, a window, the full
screen or a freeform shape, now or after a delay. Win+Shift+R starts it
@@ -52,3 +54,7 @@ Description: Wild OS Capture: screenshots and screen recording
pen, highlighter, arrow, box, text, blur and crop in five colours. It
saves to Pictures/Screenshots; recordings go to Videos/Screen recordings.
KWin takes the pictures and PipeWire carries the recordings.
+ .
+ The Scan tab scans paper from a network scanner (eSCL and WSD, through
+ sane-airscan) or a USB one (SANE), from the glass or the feeder, and
+ saves the pages as a PDF or as pictures, or opens them in PDF to sign.
diff --git a/packages/wildos-capture/qml/CaptureIcons.qml b/packages/wildos-capture/qml/CaptureIcons.qml
index 1997a25..d04a431 100644
--- a/packages/wildos-capture/qml/CaptureIcons.qml
+++ b/packages/wildos-capture/qml/CaptureIcons.qml
@@ -3,7 +3,7 @@ pragma Singleton
import QtQuick
// Capture's own line icons, on the system set's 24px grid, taken from the
-// boards (AppCapture.dc, AppCaptureEdit.dc). Anything not here comes from
+// boards (AppCapture.dc, AppCaptureEdit.dc, CaptureScan.dc). Anything not here comes from
// WildOS.UI Icons.
QtObject {
readonly property var paths: ({
@@ -29,6 +29,10 @@ QtObject {
"redo": "M15 14l5 -5l-5 -5M20 9H9.5A5.5 5.5 0 0 0 4 14.5A5.5 5.5 0 0 0 9.5 20H13",
"copy": "M10 8h10a2 2 0 0 1 2 2v10a2 2 0 0 1 -2 2H10a2 2 0 0 1 -2 -2V10a2 2 0 0 1 2 -2zM4 16c-1.1 0 -2 -0.9 -2 -2V4c0 -1.1 0.9 -2 2 -2h10c1.1 0 2 0.9 2 2",
"share": "M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2 -2v-8M16 6l-4 -4l-4 4M12 2v13",
+ "scan": "M3 7V5a2 2 0 0 1 2 -2h2M17 3h2a2 2 0 0 1 2 2v2M21 17v2a2 2 0 0 1 -2 2h-2M7 21H5a2 2 0 0 1 -2 -2v-2M7 12h10",
+ "rotate": "M21 12a9 9 0 1 1 -9 -9c2.52 0 4.93 1 6.74 2.74L21 8M21 3v5h-5",
+ "remove": "M3 6h18M19 6v14c0 1 -1 2 -2 2H7c-1 0 -2 -1 -2 -2V6M8 6V4c0 -1 1 -2 2 -2h4c1 0 2 1 2 2v2",
+ "plus": "M5 12h14M12 5v14",
"save": "M15.2 3a2 2 0 0 1 1.4 0.6l3.8 3.8a2 2 0 0 1 0.6 1.4V19a2 2 0 0 1 -2 2H5a2 2 0 0 1 -2 -2V5a2 2 0 0 1 2 -2zM17 21v-7a1 1 0 0 0 -1 -1H8a1 1 0 0 0 -1 1v7M7 3v4a1 1 0 0 0 1 1h7"
})
}
diff --git a/packages/wildos-capture/qml/Editor.qml b/packages/wildos-capture/qml/Editor.qml
index f13b071..c14021e 100644
--- a/packages/wildos-capture/qml/Editor.qml
+++ b/packages/wildos-capture/qml/Editor.qml
@@ -27,15 +27,26 @@ UI.AppWindow {
required property string path
property bool saved: false
+ // A scanned page from the Scan tab: Save puts it back in the scan.
+ property bool scanPage: false
+
// Closing for good, after any question about saving.
signal done()
+ // Save wrote the picture to `path`.
+ signal wrote(string path)
readonly property string fileName: path.substring(path.lastIndexOf("/") + 1)
+ // A scanned page's file carries its page's number after a #, for the
+ // Scan tab; the title leaves it out.
+ readonly property string shownName: scanPage ? fileName.replace(/ #\d+\.png$/, "") : fileName
readonly property string placeName: path.indexOf("/Pictures/Screenshots/") >= 0 ? qsTr("Pictures › Screenshots")
: path.substring(0, path.lastIndexOf("/")).replace(/^.*\//, "")
// Line widths and text are drawn at the screen's scale, so a mark looks
// the same size on the picture as it did on screen.
- readonly property real unit: Math.max(1, Screen.devicePixelRatio)
+ // A scanned page is far bigger than the screen, so there the unit is
+ // what one screen pixel is on the page, shown whole.
+ readonly property real unit: scanPage ? Math.max(1, base.implicitHeight / Math.max(200, Screen.desktopAvailableHeight - 362))
+ : Math.max(1, Screen.devicePixelRatio)
readonly property int imageWidth: base.implicitWidth
readonly property int imageHeight: base.implicitHeight
@@ -90,7 +101,7 @@ UI.AppWindow {
}
deep: true
- title: fileName
+ title: shownName
width: Math.round(Math.min(Math.max(900, imageWidth / unit + 200), Screen.desktopAvailableWidth - 80))
height: Math.round(Math.min(Math.max(560, imageHeight / unit + 266), Screen.desktopAvailableHeight - 80))
minimumWidth: 880
@@ -271,12 +282,13 @@ UI.AppWindow {
if (CaptureApp.saveImage(image, cropArgument(), path)) {
saved = true;
dirty = false;
- status = qsTr("Saved to %1").arg(placeName);
+ status = scanPage ? qsTr("Put back in the scan") : qsTr("Saved to %1").arg(placeName);
+ win.wrote(path);
if (then) {
then();
}
} else {
- status = qsTr("Couldn't save to %1").arg(placeName);
+ status = scanPage ? qsTr("Couldn't put it back in the scan") : qsTr("Couldn't save to %1").arg(placeName);
}
});
}
@@ -369,7 +381,7 @@ UI.AppWindow {
}
UI.Label {
anchors.verticalCenter: parent.verticalCenter
- text: win.fileName
+ text: win.shownName
font.weight: UI.Style.weightMedium
color: win.active ? UI.Style.ink : UI.Style.inkMuted
}
@@ -887,7 +899,20 @@ UI.AppWindow {
cursorVisible: win.typing
Accessible.name: qsTr("Text to add")
onAccepted: win.finishText()
- onActiveFocusChanged: if (!activeFocus && win.typing) win.finishText()
+ // The text menu holds focus while it is open; the text is
+ // still being typed.
+ onActiveFocusChanged: if (!activeFocus && win.typing && !textMenu.opened) win.finishText()
+ Keys.onPressed: event => {
+ if (textMenu.isMenuKey(event)) {
+ textMenu.openAtCaret();
+ event.accepted = true;
+ }
+ }
+
+ UI.TextMenu {
+ id: textMenu
+ onFocusLeft: win.finishText()
+ }
}
}
}
@@ -932,7 +957,7 @@ UI.AppWindow {
UI.Label {
size: 12
color: UI.Style.inkMuted
- text: qsTr("Saves to %1").arg(win.placeName)
+ text: win.scanPage ? qsTr("Save puts it back in the scan") : qsTr("Saves to %1").arg(win.placeName)
}
}
}
diff --git a/packages/wildos-capture/qml/Main.qml b/packages/wildos-capture/qml/Main.qml
index 55d10e1..34f8c34 100644
--- a/packages/wildos-capture/qml/Main.qml
+++ b/packages/wildos-capture/qml/Main.qml
@@ -3,8 +3,8 @@ import QtQuick.Window
import WildOS.UI as UI
// Everything Capture shows: the frozen overlay on every screen, the
-// countdown for a delayed capture, the bar while recording, and the editor
-// and Share windows.
+// countdown for a delayed capture, the bar while recording, the editor,
+// the Share window and the Scan tab's window.
QtObject {
id: root
@@ -21,7 +21,25 @@ QtObject {
Connections {
target: CaptureApp
function onEditRequested(source, key, path, saved) {
- root.openEditor(source, key, path, saved);
+ root.openEditor(source, key, path, saved, false);
+ }
+ function onScanPageEditRequested(source, path) {
+ root.openEditor(source, "", path, true, true);
+ }
+ function onScanRequested() {
+ if (!root.scanWindow) {
+ root.scanWindow = scanComponent.createObject(root);
+ }
+ const w = root.scanWindow;
+ // On Wayland a window is never told it was minimised, and
+ // can't bring itself back by asking; shown afresh, it comes
+ // back to the front.
+ if (!w.active) {
+ w.hide();
+ w.show();
+ }
+ w.raise();
+ w.requestActivate();
}
function onShareRequested(file) {
const window = shareWindow.createObject(root, { file: file });
@@ -32,14 +50,15 @@ QtObject {
]
property var opening: []
+ property var scanWindow: null
// The editor is built a little at a time behind the splash (SplashDaily.dc
// in Capture's colours), which only comes up if that takes more than a
// third of a second, so a quick open never flashes.
- function openEditor(source: url, key: string, path: string, saved: bool): void {
+ function openEditor(source: url, key: string, path: string, saved: bool, scanPage: bool): void {
const name = path.substring(path.lastIndexOf("/") + 1);
const splash = splashComponent.createObject(root, { status: qsTr("Opening %1").arg(name) });
- const incubator = editorComponent.incubateObject(root, { source: source, key: key, path: path, saved: saved, visible: false }, Qt.Asynchronous);
+ const incubator = editorComponent.incubateObject(root, { source: source, key: key, path: path, saved: saved, scanPage: scanPage, visible: false }, Qt.Asynchronous);
// Held until the window is made, so the incubator is not collected
// half way.
root.opening = root.opening.concat([incubator]);
@@ -88,6 +107,11 @@ QtObject {
property Component editorComponent: Component {
Editor {
+ onWrote: path => {
+ if (scanPage) {
+ CaptureApp.scanner.markedUp(path);
+ }
+ }
onDone: {
CaptureApp.editorClosed(key);
destroy(1000);
@@ -95,6 +119,16 @@ QtObject {
}
}
+ property Component scanComponent: Component {
+ ScanWindow {
+ onDone: {
+ CaptureApp.scanClosed();
+ root.scanWindow = null;
+ destroy(1000);
+ }
+ }
+ }
+
property Component shareWindow: Component {
ShareWindow {
onClosing: {
diff --git a/packages/wildos-capture/qml/ScanWindow.qml b/packages/wildos-capture/qml/ScanWindow.qml
new file mode 100644
index 0000000..acc3ab9
--- /dev/null
+++ b/packages/wildos-capture/qml/ScanWindow.qml
@@ -0,0 +1,898 @@
+pragma ComponentBehavior: Bound
+
+import QtQuick
+import QtQuick.Effects
+import QtQuick.Layouts
+import QtQuick.Shapes
+import QtQuick.Templates as T
+import QtQuick.Window
+import WildOS.UI as UI
+
+// Capture's Scan tab (CaptureScan.dc, board 15.30): Screenshot, Record and
+// Scan along the toolbar with Rotate, Crop, Mark up and Remove page; the
+// scanner and its settings on the left; the page just scanned in the
+// middle; the pages so far on the right with Add page; Save as pictures,
+// Open in PDF to sign and Save as PDF along the foot.
+UI.AppWindow {
+ id: win
+
+ readonly property var scanner: CaptureApp.scanner
+ readonly property var pages: scanner.pages
+ readonly property var page: scanner.current >= 0 && scanner.current < pages.length ? pages[scanner.current] : null
+ readonly property bool ready: scanner.device.length > 0 && !scanner.opening
+ readonly property bool canEdit: page !== null && !scanner.scanning && !scanner.busy
+ property bool cropping: false
+ // Pages scanned or changed since the last save, which closing asks
+ // about.
+ property bool unsaved: false
+ property bool closeAfterSave: false
+ property bool closingNow: false
+ property real lastLook: 0
+
+ signal done()
+
+ function band(darkAlpha: real, lightAlpha: real): color {
+ return UI.Style.dark ? UI.Style.shade(darkAlpha, 0) : UI.Style.layer(0, false, lightAlpha);
+ }
+ function megabytes(bytes: real): string {
+ return bytes >= 1024 * 1024 ? qsTr("%1 MB").arg((bytes / 1024 / 1024).toLocaleString(Qt.locale(), "f", 1))
+ : qsTr("%1 KB").arg(Math.max(1, Math.round(bytes / 1024)));
+ }
+ function scanLabel(): string {
+ if (scanner.source === "feeder" && scanner.hasFeeder) {
+ return pages.length > 0 ? qsTr("Scan more from the feeder") : qsTr("Scan the feeder");
+ }
+ return pages.length > 0 ? qsTr("Scan the next page") : qsTr("Scan");
+ }
+ function startCapture(record: bool): void {
+ cropping = false;
+ win.showMinimized();
+ CaptureApp.startCapture(record);
+ }
+ function markUp(): void {
+ cropping = false;
+ CaptureApp.markUpScanPage(scanner.pageFile());
+ }
+ function closeNow(): void {
+ closingNow = true;
+ close();
+ }
+
+ deep: true
+ title: qsTr("Scan")
+ width: Math.round(Math.min(1384, Screen.desktopAvailableWidth - 56))
+ height: Math.round(Math.min(802, Screen.desktopAvailableHeight - 56))
+ minimumWidth: 980
+ minimumHeight: 620
+
+ onClosing: close => {
+ if (closingNow) {
+ scanner.cancel();
+ scanner.forget();
+ done();
+ return;
+ }
+ if (unsaved && pages.length > 0) {
+ close.accepted = false;
+ unsavedDialog.open();
+ return;
+ }
+ scanner.cancel();
+ scanner.forget();
+ done();
+ }
+
+ Connections {
+ target: win.scanner
+ function onPagesChanged() {
+ win.unsaved = win.pages.length > 0;
+ }
+ function onSaid(message, file) {
+ toast.file = file;
+ toast.show(message, file === "undo" ? qsTr("Undo") : file.length > 0 ? qsTr("Show in folder") : "");
+ if (file.length > 0 && file !== "undo") {
+ win.unsaved = false;
+ if (win.closeAfterSave) {
+ win.closeNow();
+ }
+ }
+ win.closeAfterSave = false;
+ }
+ // With pages on screen a problem is a note; with none it fills the
+ // middle, where the pages would be.
+ function onProblemChanged() {
+ if (win.scanner.problem.title && win.pages.length > 0) {
+ toast.file = "";
+ toast.show(win.scanner.problem.title, "");
+ }
+ }
+ }
+
+ Shortcut { sequences: [StandardKey.Undo]; enabled: win.scanner.canUndo && !win.scanner.scanning; onActivated: win.scanner.undo() }
+ Shortcut { sequences: [StandardKey.Delete]; enabled: win.canEdit; onActivated: win.scanner.removePage() }
+ Shortcut { sequences: [StandardKey.Save]; enabled: win.pages.length > 0 && !win.scanner.busy; onActivated: win.scanner.savePdf() }
+ Shortcut { sequences: [StandardKey.Close]; onActivated: win.close() }
+ Shortcut {
+ sequence: "Escape"
+ onActivated: {
+ if (win.cropping) {
+ win.cropping = false;
+ } else if (win.scanner.scanning) {
+ win.scanner.cancel();
+ } else {
+ win.close();
+ }
+ }
+ }
+
+ component Divider: Rectangle {
+ Layout.preferredWidth: 1
+ Layout.preferredHeight: 22
+ Layout.leftMargin: 6
+ Layout.rightMargin: 6
+ color: UI.Style.divider
+ }
+
+ component FieldLabel: UI.Label {
+ size: 12.5
+ color: UI.Style.inkMuted
+ }
+
+ // The toolbar's Screenshot and Record pill, with a third choice.
+ component Choices: Rectangle {
+ id: choices
+ property var options: []
+ property string value
+ property var available: []
+ signal chosen(string value)
+
+ Layout.fillWidth: true
+ Layout.preferredHeight: 32
+ radius: 7
+ color: UI.Style.surfaceRest
+ border.width: 1
+ border.color: UI.Style.borderField
+
+ Row {
+ anchors.left: parent.left
+ anchors.leftMargin: 3
+ anchors.verticalCenter: parent.verticalCenter
+
+ Repeater {
+ model: choices.options
+ delegate: UI.SegmentButton {
+ required property var modelData
+ height: 26
+ checkable: false
+ text: modelData.text
+ checked: choices.value === modelData.value
+ enabled: choices.available.length === 0 || choices.available.indexOf(modelData.value) >= 0
+ onClicked: choices.chosen(modelData.value)
+ }
+ }
+ }
+ }
+
+ ColumnLayout {
+ anchors.fill: parent
+ anchors.margins: win.maximised ? 0 : 1
+ spacing: 0
+
+ UI.TitleBar {
+ Layout.fillWidth: true
+ frame: win.frame
+ showTitle: false
+
+ Row {
+ anchors.left: parent.left
+ anchors.leftMargin: -2
+ anchors.verticalCenter: parent.verticalCenter
+ spacing: 10
+
+ Image {
+ anchors.verticalCenter: parent.verticalCenter
+ width: 20
+ height: 20
+ source: "qrc:/qt/qml/WildOS/Capture/data/wildos-capture.svg"
+ sourceSize.width: 40
+ sourceSize.height: 40
+ }
+ UI.Label {
+ anchors.verticalCenter: parent.verticalCenter
+ text: qsTr("Scan")
+ font.weight: UI.Style.weightMedium
+ color: win.active ? UI.Style.ink : UI.Style.inkMuted
+ }
+ UI.Label {
+ anchors.verticalCenter: parent.verticalCenter
+ text: qsTr("Capture")
+ color: UI.Style.inkSubtle
+ }
+ }
+ }
+
+ // The toolbar, as the editor's: 50px on a deeper band.
+ Rectangle {
+ Layout.fillWidth: true
+ Layout.preferredHeight: 50
+ color: win.band(0.2, 0.01)
+
+ Rectangle {
+ anchors.bottom: parent.bottom
+ width: parent.width
+ height: 1
+ color: UI.Style.divider
+ }
+
+ RowLayout {
+ anchors.fill: parent
+ anchors.leftMargin: 12
+ anchors.rightMargin: 12
+ spacing: 4
+
+ ToolButton {
+ iconName: "camera"
+ text: qsTr("Screenshot")
+ enabled: !win.scanner.scanning
+ onClicked: win.startCapture(false)
+ }
+ ToolButton {
+ iconName: "record"
+ text: qsTr("Record")
+ enabled: CaptureApp.canRecord && !win.scanner.scanning
+ onClicked: win.startCapture(true)
+ }
+ ToolButton {
+ iconName: "scan"
+ text: qsTr("Scan")
+ active: true
+ }
+
+ Item { Layout.fillWidth: true }
+
+ ToolButton {
+ iconName: "rotate"
+ text: qsTr("Rotate")
+ tip: qsTr("Turn the page a quarter to the right")
+ enabled: win.canEdit
+ onClicked: {
+ win.cropping = false;
+ win.scanner.rotate();
+ }
+ }
+ ToolButton {
+ iconName: "crop"
+ text: qsTr("Crop")
+ tip: win.cropping ? qsTr("Drag over the part to keep") : ""
+ active: win.cropping
+ enabled: win.canEdit
+ onClicked: win.cropping = !win.cropping
+ }
+ ToolButton {
+ iconName: "pen"
+ text: qsTr("Mark up")
+ enabled: win.canEdit
+ onClicked: win.markUp()
+ }
+ Divider {}
+ ToolButton {
+ iconName: "remove"
+ text: qsTr("Remove page")
+ enabled: win.canEdit
+ onClicked: {
+ win.cropping = false;
+ win.scanner.removePage();
+ }
+ }
+ }
+ }
+
+ RowLayout {
+ Layout.fillWidth: true
+ Layout.fillHeight: true
+ spacing: 0
+
+ // The scanner and how to scan.
+ Rectangle {
+ Layout.preferredWidth: 300
+ Layout.fillHeight: true
+ color: win.band(0.12, 0.01)
+
+ Rectangle {
+ anchors.right: parent.right
+ width: 1
+ height: parent.height
+ color: UI.Style.divider
+ }
+
+ ColumnLayout {
+ anchors.fill: parent
+ anchors.margins: 18
+ anchors.rightMargin: 19
+ spacing: 14
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 6
+ FieldLabel { text: qsTr("Scanner") }
+ UI.ComboBox {
+ id: scannerBox
+ Layout.fillWidth: true
+ readonly property var choices: win.scanner.devices.map(d => ({ value: d.id, text: d.name }))
+ model: choices.length > 0 ? choices
+ : [{ value: "", text: win.scanner.looking ? qsTr("Looking for scanners…") : qsTr("No scanner found") }]
+ currentIndex: Math.max(0, model.findIndex(o => o.value === win.scanner.device))
+ enabled: choices.length > 0 && !win.scanner.scanning
+ onActivated: win.scanner.choose(currentValue)
+ }
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 6
+ FieldLabel { text: qsTr("Scan from") }
+ Choices {
+ options: [{ value: "glass", text: qsTr("Glass") }, { value: "feeder", text: qsTr("Feeder") }]
+ value: win.scanner.hasFeeder ? win.scanner.source : "glass"
+ available: win.ready ? [win.scanner.hasGlass ? "glass" : "", win.scanner.hasFeeder ? "feeder" : ""] : ["glass"]
+ enabled: !win.scanner.scanning
+ onChosen: value => win.scanner.source = value
+ }
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 6
+ FieldLabel { text: qsTr("Colour") }
+ Choices {
+ options: [{ value: "colour", text: qsTr("Colour") }, { value: "grey", text: qsTr("Grey") }, { value: "bw", text: qsTr("Black and white") }]
+ value: win.scanner.colour
+ enabled: !win.scanner.scanning
+ onChosen: value => win.scanner.colour = value
+ }
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 6
+ FieldLabel { text: qsTr("Quality") }
+ UI.ComboBox {
+ Layout.fillWidth: true
+ model: win.scanner.qualities
+ currentIndex: Math.max(0, model.findIndex(o => o.value === win.scanner.dpi))
+ enabled: !win.scanner.scanning
+ onActivated: win.scanner.dpi = currentValue
+ }
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 6
+ FieldLabel { text: qsTr("Paper size") }
+ UI.ComboBox {
+ Layout.fillWidth: true
+ model: win.scanner.paperSizes
+ currentIndex: Math.max(0, model.findIndex(o => o.value === win.scanner.paper))
+ enabled: !win.scanner.scanning
+ onActivated: win.scanner.paper = currentValue
+ }
+ }
+
+ RowLayout {
+ Layout.fillWidth: true
+ spacing: 10
+ UI.Label {
+ Layout.fillWidth: true
+ text: qsTr("Straighten and crop each page")
+ }
+ UI.Toggle {
+ Accessible.name: qsTr("Straighten and crop each page")
+ checked: win.scanner.straighten
+ onToggled: win.scanner.straighten = checked
+ }
+ }
+
+ Item { Layout.fillHeight: true }
+
+ ToolButton {
+ Layout.fillWidth: true
+ visible: !win.scanner.scanning
+ primary: true
+ iconName: "scan"
+ text: win.scanLabel()
+ enabled: win.ready && !win.scanner.busy
+ onClicked: {
+ win.cropping = false;
+ win.scanner.scan();
+ }
+ }
+ UI.Button {
+ Layout.fillWidth: true
+ Layout.preferredHeight: 32
+ visible: win.scanner.scanning
+ text: win.scanner.cancelling ? qsTr("Stopping…") : qsTr("Cancel")
+ enabled: !win.scanner.cancelling
+ onClicked: win.scanner.cancel()
+ }
+
+ UI.Label {
+ Layout.fillWidth: true
+ size: 12
+ color: UI.Style.inkMuted
+ wrapMode: Text.Wrap
+ lineHeight: 1.25
+ text: qsTr("Scans stay on this PC.")
+ }
+ }
+ }
+
+ // The page, centred on the deeper ground.
+ Rectangle {
+ id: stage
+ Layout.fillWidth: true
+ Layout.fillHeight: true
+ color: win.band(0.22, 0.03)
+ clip: true
+
+ readonly property bool showPage: win.page !== null && !win.scanner.scanning
+
+ UI.Label {
+ x: 18
+ y: 14
+ visible: stage.showPage
+ size: 12.5
+ color: UI.Style.inkMuted
+ text: win.page ? qsTr("Page %1 of %2").arg(win.scanner.current + 1).arg(win.pages.length)
+ + (win.page.note.length > 0 ? " · " + win.page.note : "") : ""
+ }
+
+ Rectangle {
+ id: card
+ x: view.x
+ y: view.y
+ width: view.width
+ height: view.height
+ radius: 3
+ color: "#fbfbfd"
+ visible: false
+ }
+ MultiEffect {
+ anchors.fill: card
+ visible: stage.showPage
+ source: card
+ shadowEnabled: true
+ shadowColor: UI.Style.shadowWindow
+ shadowBlur: 0.8
+ shadowVerticalOffset: 8
+ autoPaddingEnabled: true
+ }
+
+ Item {
+ id: view
+ readonly property real pw: win.page ? win.page.width : 1
+ readonly property real ph: win.page ? win.page.height : 1
+ readonly property real fit: Math.max(0.01, Math.min((stage.width - 96) / pw, (stage.height - 96) / ph))
+ visible: stage.showPage
+ width: Math.round(pw * fit)
+ height: Math.round(ph * fit)
+ x: Math.round((stage.width - width) / 2)
+ y: Math.round((stage.height - height) / 2)
+
+ Image {
+ anchors.fill: parent
+ source: win.page ? win.page.source : ""
+ sourceSize.width: Math.min(view.pw, Math.ceil(view.width * Screen.devicePixelRatio))
+ asynchronous: true
+ cache: false
+ smooth: true
+ mipmap: true
+ }
+
+ // Crop: the part kept stays clear and the rest dims, as
+ // in the editor.
+ Item {
+ id: cropLayer
+ anchors.fill: parent
+ visible: win.cropping
+ property rect r: Qt.rect(0, 0, 0, 0)
+ readonly property color dim: Qt.rgba(0, 0, 0, 0.5)
+
+ Rectangle { width: parent.width; height: cropLayer.r.height > 0 ? cropLayer.r.y : parent.height; color: cropLayer.dim }
+ Rectangle { visible: cropLayer.r.height > 0; y: cropLayer.r.y; width: cropLayer.r.x; height: cropLayer.r.height; color: cropLayer.dim }
+ Rectangle { visible: cropLayer.r.height > 0; x: cropLayer.r.x + cropLayer.r.width; y: cropLayer.r.y; width: parent.width - x; height: cropLayer.r.height; color: cropLayer.dim }
+ Rectangle { visible: cropLayer.r.height > 0; y: cropLayer.r.y + cropLayer.r.height; width: parent.width; height: parent.height - y; color: cropLayer.dim }
+ Rectangle {
+ x: cropLayer.r.x
+ y: cropLayer.r.y
+ width: cropLayer.r.width
+ height: cropLayer.r.height
+ color: "transparent"
+ border.width: 1.5
+ border.color: UI.Style.inkOnWallpaper
+ }
+
+ MouseArea {
+ anchors.fill: parent
+ cursorShape: Qt.CrossCursor
+ property point start
+ onPressed: mouse => {
+ start = Qt.point(mouse.x, mouse.y);
+ cropLayer.r = Qt.rect(mouse.x, mouse.y, 0, 0);
+ }
+ onPositionChanged: mouse => {
+ const x = Math.max(0, Math.min(width, mouse.x));
+ const y = Math.max(0, Math.min(height, mouse.y));
+ cropLayer.r = Qt.rect(Math.min(start.x, x), Math.min(start.y, y), Math.abs(x - start.x), Math.abs(y - start.y));
+ }
+ onReleased: {
+ // A copy: a rect read from a property follows
+ // the property, which is cleared next.
+ const r = Qt.rect(cropLayer.r.x, cropLayer.r.y, cropLayer.r.width, cropLayer.r.height);
+ cropLayer.r = Qt.rect(0, 0, 0, 0);
+ if (r.width >= 8 && r.height >= 8) {
+ win.scanner.crop(Qt.rect(r.x / width, r.y / height, r.width / width, r.height / height));
+ win.cropping = false;
+ }
+ }
+ }
+ }
+ }
+
+ // Instead of a page: looking, no scanner, a problem, nothing
+ // scanned yet, or a page on its way.
+ ColumnLayout {
+ anchors.centerIn: parent
+ width: Math.min(400, parent.width - 48)
+ visible: !stage.showPage
+ spacing: 10
+
+ readonly property string state: win.scanner.scanning ? "scanning"
+ : win.scanner.problem.title ? "problem"
+ : win.scanner.looking && win.scanner.devices.length === 0 ? "looking"
+ : win.scanner.devices.length === 0 ? "none"
+ : win.scanner.opening ? "opening" : "ready"
+
+ UI.Spinner {
+ Layout.alignment: Qt.AlignHCenter
+ Layout.bottomMargin: 4
+ visible: parent.state === "looking" || parent.state === "opening" || (parent.state === "scanning" && win.scanner.progress < 0)
+ size: 28
+ }
+ CaptureIcon {
+ Layout.alignment: Qt.AlignHCenter
+ Layout.bottomMargin: 4
+ visible: parent.state === "none" || parent.state === "ready" || parent.state === "problem"
+ name: parent.state === "problem" ? "warning" : "scan"
+ size: 32
+ strokeWidth: 1.6
+ color: UI.Style.inkSubtle
+ }
+ UI.Label {
+ Layout.fillWidth: true
+ horizontalAlignment: Text.AlignHCenter
+ size: UI.Style.fontSection
+ font.weight: UI.Style.weightSemiBold
+ wrapMode: Text.Wrap
+ text: {
+ switch (parent.state) {
+ case "scanning": return win.scanner.cancelling ? qsTr("Stopping the scan") : qsTr("Scanning page %1").arg(win.scanner.scanningPage);
+ case "problem": return win.scanner.problem.title;
+ case "looking": return qsTr("Looking for scanners");
+ case "opening": return qsTr("Getting the scanner ready");
+ case "none": return qsTr("No scanner found");
+ default: return win.scanner.source === "feeder" && win.scanner.hasFeeder ? qsTr("Put the pages in the feeder") : qsTr("Put a page face down on the glass");
+ }
+ }
+ }
+ UI.Label {
+ Layout.fillWidth: true
+ horizontalAlignment: Text.AlignHCenter
+ color: UI.Style.inkMuted
+ wrapMode: Text.Wrap
+ lineHeight: 1.25
+ text: {
+ switch (parent.state) {
+ case "scanning": return !win.scanner.cancelling && win.scanner.source === "feeder" && win.scanner.hasFeeder ? qsTr("Each page shows here as it comes through.") : "";
+ case "problem": return win.scanner.problem.text;
+ case "looking": return qsTr("On your network and connected to this PC.");
+ case "opening": return "";
+ case "none": return qsTr("Switch your scanner on and connect it to this PC or your network. Most made since 2014 work without a driver.");
+ default: return qsTr("Then press %1.").arg(win.scanLabel());
+ }
+ }
+ }
+ UI.ProgressBar {
+ Layout.alignment: Qt.AlignHCenter
+ Layout.preferredWidth: 240
+ Layout.topMargin: 6
+ visible: parent.state === "scanning" && win.scanner.progress >= 0
+ value: Math.max(0, win.scanner.progress)
+ }
+ UI.Button {
+ Layout.alignment: Qt.AlignHCenter
+ Layout.topMargin: 6
+ visible: parent.state === "none" || (parent.state === "problem" && win.scanner.devices.length === 0)
+ text: qsTr("Look again")
+ onClicked: {
+ win.scanner.clearProblem();
+ win.look();
+ }
+ }
+ }
+ }
+
+ // The pages so far, then Add page.
+ Rectangle {
+ Layout.preferredWidth: 138
+ Layout.fillHeight: true
+ color: win.band(0.12, 0.01)
+
+ Rectangle {
+ width: 1
+ height: parent.height
+ color: UI.Style.divider
+ }
+
+ ListView {
+ id: strip
+ anchors.fill: parent
+ anchors.leftMargin: 1
+ topMargin: 18
+ bottomMargin: 18
+ spacing: 14
+ clip: true
+ model: win.pages
+ currentIndex: win.scanner.current
+ boundsBehavior: Flickable.StopAtBounds
+ highlightFollowsCurrentItem: false
+ onCurrentIndexChanged: positionViewAtIndex(currentIndex, ListView.Contain)
+ T.ScrollBar.vertical: UI.ScrollBar {}
+
+ delegate: Item {
+ id: thumb
+ required property var modelData
+ required property int index
+ readonly property bool current: index === win.scanner.current
+ width: strip.width
+ height: Math.round(90 * Math.min(2, modelData.height / Math.max(1, modelData.width)))
+
+ Rectangle {
+ id: sheet
+ anchors.horizontalCenter: parent.horizontalCenter
+ width: 90
+ height: parent.height
+ radius: 2
+ color: "#fbfbfd"
+ visible: false
+ }
+ MultiEffect {
+ anchors.fill: sheet
+ source: sheet
+ shadowEnabled: true
+ shadowColor: UI.Style.shadowWindow
+ shadowBlur: 0.3
+ shadowVerticalOffset: 2
+ autoPaddingEnabled: true
+ }
+ Image {
+ anchors.fill: sheet
+ source: thumb.modelData.source
+ sourceSize.width: 180
+ asynchronous: true
+ cache: false
+ smooth: true
+ fillMode: Image.PreserveAspectFit
+ }
+ Rectangle {
+ anchors.fill: sheet
+ anchors.margins: -4
+ radius: 5
+ color: "transparent"
+ visible: thumb.current
+ border.width: 2
+ border.color: UI.Style.accent
+ }
+ Rectangle {
+ x: sheet.x + 6
+ anchors.bottom: sheet.bottom
+ anchors.bottomMargin: 6
+ width: number.implicitWidth + 12
+ height: number.implicitHeight + 2
+ radius: 4
+ color: Qt.rgba(0, 0, 0, 0.6)
+ UI.Label {
+ id: number
+ anchors.centerIn: parent
+ size: 11
+ color: "#ffffff"
+ text: thumb.index + 1
+ }
+ }
+ MouseArea {
+ anchors.fill: sheet
+ cursorShape: Qt.PointingHandCursor
+ Accessible.role: Accessible.Button
+ Accessible.name: qsTr("Page %1").arg(thumb.index + 1)
+ onClicked: {
+ win.cropping = false;
+ win.scanner.current = thumb.index;
+ }
+ }
+ }
+
+ footer: Item {
+ width: strip.width
+ height: 127 + (win.pages.length > 0 ? 14 : 0)
+
+ Item {
+ id: add
+ anchors.horizontalCenter: parent.horizontalCenter
+ anchors.bottom: parent.bottom
+ width: 90
+ height: 127
+ opacity: addArea.enabled ? 1 : 0.45
+
+ Shape {
+ anchors.fill: parent
+ preferredRendererType: Shape.CurveRenderer
+ ShapePath {
+ strokeColor: addArea.containsMouse ? UI.Style.borderControl : UI.Style.borderField
+ strokeWidth: 1.5
+ strokeStyle: ShapePath.DashLine
+ dashPattern: [3, 2.5]
+ fillColor: addArea.containsMouse ? UI.Style.surfaceHover : "transparent"
+ PathRectangle {
+ x: 0.75
+ y: 0.75
+ width: add.width - 1.5
+ height: add.height - 1.5
+ radius: 4
+ }
+ }
+ }
+ Column {
+ anchors.centerIn: parent
+ spacing: 6
+ CaptureIcon {
+ anchors.horizontalCenter: parent.horizontalCenter
+ name: "plus"
+ size: 16
+ color: UI.Style.inkMuted
+ }
+ UI.Label {
+ anchors.horizontalCenter: parent.horizontalCenter
+ size: 12
+ color: UI.Style.inkMuted
+ text: qsTr("Add page")
+ }
+ }
+ MouseArea {
+ id: addArea
+ anchors.fill: parent
+ hoverEnabled: true
+ enabled: win.ready && !win.scanner.scanning && !win.scanner.busy
+ cursorShape: Qt.PointingHandCursor
+ Accessible.role: Accessible.Button
+ Accessible.name: qsTr("Add page")
+ onClicked: {
+ win.cropping = false;
+ win.scanner.scan();
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // The foot: how many pages and the PDF's size; the three ways out.
+ Rectangle {
+ Layout.fillWidth: true
+ Layout.preferredHeight: 56
+ color: win.band(0.3, 0.02)
+ bottomLeftRadius: win.maximised ? 0 : UI.Style.windowRadius - 1
+ bottomRightRadius: bottomLeftRadius
+
+ Rectangle {
+ width: parent.width
+ height: 1
+ color: UI.Style.divider
+ }
+
+ RowLayout {
+ anchors.fill: parent
+ anchors.leftMargin: 16
+ anchors.rightMargin: 16
+ spacing: 10
+
+ UI.Label {
+ Layout.fillWidth: true
+ size: 12.5
+ color: UI.Style.inkMuted
+ text: win.pages.length === 0 ? qsTr("No pages yet")
+ : (win.pages.length === 1 ? qsTr("1 page") : qsTr("%1 pages").arg(win.pages.length)) + (win.scanner.pdfSize > 0 ? " · " + qsTr("about %1 as a PDF").arg(win.megabytes(win.scanner.pdfSize)) : "")
+ }
+ UI.Button {
+ Layout.preferredHeight: 32
+ text: qsTr("Save as pictures")
+ enabled: win.pages.length > 0 && !win.scanner.busy && !win.scanner.scanning
+ onClicked: win.scanner.savePictures()
+ }
+ UI.Button {
+ Layout.preferredHeight: 32
+ visible: win.scanner.canSign
+ iconName: "pencil"
+ text: qsTr("Open in PDF to sign")
+ enabled: win.pages.length > 0 && !win.scanner.busy && !win.scanner.scanning
+ onClicked: win.scanner.openToSign()
+ }
+ UI.Button {
+ Layout.preferredHeight: 32
+ kind: "primary"
+ text: win.scanner.busy ? qsTr("Saving…") : qsTr("Save as PDF")
+ enabled: win.pages.length > 0 && !win.scanner.busy && !win.scanner.scanning
+ onClicked: win.scanner.savePdf()
+ }
+ }
+ }
+ }
+
+ UI.Toast {
+ id: toast
+ property string file
+ anchors.horizontalCenter: parent.horizontalCenter
+ anchors.bottom: parent.bottom
+ anchors.bottomMargin: 72
+ onActionClicked: {
+ if (file === "undo") {
+ win.scanner.undo();
+ } else if (file.length > 0) {
+ CaptureApp.showInFolder("file://" + file);
+ }
+ hide();
+ }
+ }
+
+ UI.Dialog {
+ id: unsavedDialog
+ title: qsTr("Save these pages?")
+ text: qsTr("The pages you scanned are lost if you don't save them.")
+ buttons: [
+ UI.Button {
+ text: qsTr("Don't save")
+ onClicked: {
+ unsavedDialog.close();
+ win.closeNow();
+ }
+ },
+ UI.Button {
+ text: qsTr("Cancel")
+ onClicked: unsavedDialog.close()
+ },
+ UI.Button {
+ kind: "primary"
+ text: qsTr("Save as PDF")
+ onClicked: {
+ unsavedDialog.close();
+ win.closeAfterSave = true;
+ win.scanner.savePdf();
+ }
+ }
+ ]
+ }
+
+ function look(): void {
+ lastLook = Date.now();
+ scanner.lookAgain();
+ }
+
+ // A scanner switched on or plugged in while Capture was in the
+ // background shows up when the window comes back to the front.
+ onActiveChanged: {
+ if (active && !scanner.scanning && !scanner.busy && Date.now() - lastLook > 20000) {
+ look();
+ }
+ }
+
+ Component.onCompleted: look()
+}
diff --git a/packages/wildos-capture/qml/Toolbar.qml b/packages/wildos-capture/qml/Toolbar.qml
index a8b6d42..31fab29 100644
--- a/packages/wildos-capture/qml/Toolbar.qml
+++ b/packages/wildos-capture/qml/Toolbar.qml
@@ -3,8 +3,8 @@ import QtQuick.Effects
import WildOS.UI as UI
// The Capture toolbar at the top of the main screen (AppCapture.dc): 6px
-// in, radius 12, on the panel glass with a 16px 40px shadow. Screenshot or
-// Record; area, window, full screen or freeform; the delay; options; the
+// in, radius 12, on the panel glass with a 16px 40px shadow. Screenshot,
+// Record or Scan (which opens the Scan window); area, window, full screen or freeform; the delay; options; the
// accent Capture button and Close. Nothing in it takes the keyboard, so
// Space, Enter and Escape always reach the overlay.
Item {
@@ -110,6 +110,18 @@ Item {
checked: CaptureApp.recordMode
onClicked: CaptureApp.recordMode = true
}
+ // Paper rather than the screen: opens the Scan window.
+ UI.SegmentButton {
+ height: 26
+ focusPolicy: Qt.NoFocus
+ checkable: false
+ text: qsTr("Scan")
+ checked: false
+ onClicked: {
+ CaptureApp.cancel();
+ CaptureApp.openScan();
+ }
+ }
}
}
diff --git a/packages/wildos-capture/src/captureapp.cpp b/packages/wildos-capture/src/captureapp.cpp
index 83033a4..3c06217 100644
--- a/packages/wildos-capture/src/captureapp.cpp
+++ b/packages/wildos-capture/src/captureapp.cpp
@@ -72,6 +72,7 @@ CaptureApp::CaptureApp(QObject *parent)
, m_grabber(new Grabber(this))
, m_recorder(new Recorder(this))
, m_sharer(new Sharer(this))
+ , m_scanner(new Scanner(this))
{
const KConfigGroup config = settings();
m_delay = config.readEntry("Delay", 0);
@@ -128,7 +129,7 @@ CaptureApp::CaptureApp(QObject *parent)
m_idleTimer.setSingleShot(true);
m_idleTimer.setInterval(800);
connect(&m_idleTimer, &QTimer::timeout, this, [this] {
- if (m_selecting || m_countdown > 0 || m_recorder->recording() || m_openWindows > 0) {
+ if (m_selecting || m_countdown > 0 || m_recorder->recording() || m_openWindows > 0 || m_scanner->scanning() || m_scanner->busy()) {
return;
}
for (const auto &notification : std::as_const(m_notifications)) {
@@ -235,6 +236,13 @@ void CaptureApp::handle(const QStringList &arguments)
openEditorFor(QUrl::fromUserInput(arguments.at(edit + 1), QDir::currentPath(), QUrl::AssumeLocalFile));
return;
}
+ if (arguments.contains(QStringLiteral("--scan"))) {
+ if (m_selecting) {
+ cancel();
+ }
+ openScan();
+ return;
+ }
if (m_recorder->recording()) {
// The shortcut again while recording ends the recording, as Stop
// does.
@@ -326,6 +334,11 @@ void CaptureApp::cancel()
Q_EMIT countdownChanged();
m_selecting = false;
Q_EMIT selectingChanged();
+ // Back to the Scan window the toolbar was opened from.
+ if (m_fromScan && m_scanOpen) {
+ Q_EMIT scanRequested();
+ }
+ m_fromScan = false;
quitWhenIdle();
}
@@ -334,6 +347,7 @@ void CaptureApp::cancel()
// the picture. Without one it happens at once.
void CaptureApp::after(std::function<void()> action)
{
+ m_fromScan = false;
m_selecting = false;
Q_EMIT selectingChanged();
if (m_delay <= 0) {
@@ -647,6 +661,48 @@ void CaptureApp::editorClosed(const QString &key)
windowClosed();
}
+void CaptureApp::openScan()
+{
+ m_fromScan = false;
+ if (!m_scanOpen) {
+ m_scanOpen = true;
+ ++m_openWindows;
+ }
+ Q_EMIT scanRequested();
+}
+
+void CaptureApp::scanClosed()
+{
+ if (m_scanOpen) {
+ m_scanOpen = false;
+ windowClosed();
+ }
+}
+
+void CaptureApp::startCapture(bool record)
+{
+ if (m_selecting || m_countdown > 0 || m_recorder->recording()) {
+ return;
+ }
+ m_returnPath.clear();
+ m_fromScan = true;
+ setRecordMode(record && canRecord());
+ // The Scan window is minimised first; this gives KWin time to take it
+ // off the screen before the screen is frozen.
+ QTimer::singleShot(400, this, [this] {
+ freeze();
+ });
+}
+
+void CaptureApp::markUpScanPage(const QString &path)
+{
+ if (path.isEmpty()) {
+ return;
+ }
+ ++m_openWindows;
+ Q_EMIT scanPageEditRequested(QUrl::fromLocalFile(path), path);
+}
+
void CaptureApp::windowClosed()
{
m_openWindows = std::max(0, m_openWindows - 1);
diff --git a/packages/wildos-capture/src/captureapp.h b/packages/wildos-capture/src/captureapp.h
index c0216b0..1c1137c 100644
--- a/packages/wildos-capture/src/captureapp.h
+++ b/packages/wildos-capture/src/captureapp.h
@@ -14,6 +14,7 @@
#include <functional>
#include "recorder.h"
+#include "scanner.h"
#include "sharer.h"
class FrozenImages;
@@ -43,6 +44,7 @@ class CaptureApp : public QObject
Q_PROPERTY(bool canRecord READ canRecord CONSTANT)
Q_PROPERTY(Recorder *recorder READ recorder CONSTANT)
Q_PROPERTY(Sharer *sharer READ sharer CONSTANT)
+ Q_PROPERTY(Scanner *scanner READ scanner CONSTANT)
Q_PROPERTY(QString message READ message NOTIFY messageChanged)
// The toolbar goes on the main screen only.
Q_PROPERTY(QString primaryScreen READ primaryScreen NOTIFY selectingChanged)
@@ -75,6 +77,7 @@ public:
bool canRecord() const;
Recorder *recorder() const { return m_recorder; }
Sharer *sharer() const { return m_sharer; }
+ Scanner *scanner() const { return m_scanner; }
QString message() const { return m_message; }
QString primaryScreen() const;
QString pickedScreen() const { return m_pickedScreen; }
@@ -87,8 +90,8 @@ public:
bool includePointer() const { return m_includePointer; }
void setIncludePointer(bool on);
- // From the command line, or a second launch: --record, --mode <name>,
- // --edit <file>.
+ // From the command line, or a second launch: --record, --scan,
+ // --mode <name>, --edit <file>.
void handle(const QStringList &arguments);
// The overlay's choices, in each screen's own logical coordinates.
@@ -110,6 +113,12 @@ public:
Q_INVOKABLE void openFile(const QUrl &file);
Q_INVOKABLE void showInFolder(const QUrl &file);
Q_INVOKABLE void editorClosed(const QString &key);
+ // The Scan tab: opened from the toolbar's Scan or --scan, and its
+ // Screenshot and Record going back to the toolbar.
+ Q_INVOKABLE void openScan();
+ Q_INVOKABLE void scanClosed();
+ Q_INVOKABLE void startCapture(bool record);
+ Q_INVOKABLE void markUpScanPage(const QString &path);
Q_INVOKABLE void windowClosed();
Q_SIGNALS:
@@ -125,6 +134,9 @@ Q_SIGNALS:
// `saved` whether the picture is there already.
void editRequested(const QUrl &source, const QString &key, const QString &path, bool saved);
void shareRequested(const QUrl &file);
+ void scanRequested();
+ // A scanned page in the editor; saving it there sends it back.
+ void scanPageEditRequested(const QUrl &source, const QString &path);
private:
void freeze();
@@ -142,6 +154,10 @@ private:
Grabber *m_grabber;
Recorder *m_recorder;
Sharer *m_sharer;
+ Scanner *m_scanner;
+ bool m_scanOpen = false;
+ // The toolbar came from the Scan window's Screenshot or Record.
+ bool m_fromScan = false;
bool m_selecting = false;
QString m_mode = QStringLiteral("rectangle");
bool m_recordMode = false;
diff --git a/packages/wildos-capture/src/main.cpp b/packages/wildos-capture/src/main.cpp
index d623932..6f63f46 100644
--- a/packages/wildos-capture/src/main.cpp
+++ b/packages/wildos-capture/src/main.cpp
@@ -3,6 +3,7 @@
// wildos-capture the toolbar over a frozen screen
// wildos-capture --record the same, ready to record
// wildos-capture --edit FILE a picture in the editor
+// wildos-capture --scan the Scan tab, for paper on a scanner
// wildos-capture --to FILE a screenshot written to FILE and nothing
// else, for Report a problem; cancelling
// writes FILE.cancelled instead
@@ -78,6 +79,7 @@ int main(int argc, char *argv[])
engine.setIncubationController(&incubation);
engine.rootContext()->setContextProperty(QStringLiteral("CaptureApp"), &capture);
engine.addImageProvider(QStringLiteral("frozen"), capture.frozen());
+ engine.addImageProvider(QStringLiteral("scan"), capture.scanner()->images());
engine.loadFromModule("WildOS.Capture", "Main");
if (engine.rootObjects().isEmpty()) {
return 1;
diff --git a/packages/wildos-capture/src/scanner.cpp b/packages/wildos-capture/src/scanner.cpp
new file mode 100644
index 0000000..576e169
--- /dev/null
+++ b/packages/wildos-capture/src/scanner.cpp
@@ -0,0 +1,887 @@
+#include "scanner.h"
+#include "scanworker.h"
+
+#include <KConfigGroup>
+#include <KSharedConfig>
+
+#include <QBuffer>
+#include <QCoreApplication>
+#include <QDateTime>
+#include <QDir>
+#include <QFile>
+#include <QFileInfo>
+#include <QLocale>
+#include <QPageSize>
+#include <QPainter>
+#include <QPdfWriter>
+#include <QPointer>
+#include <QProcess>
+#include <QStandardPaths>
+#include <QThreadPool>
+#include <QTransform>
+
+#include <cmath>
+
+namespace
+{
+KConfigGroup settings()
+{
+ return KSharedConfig::openConfig(QStringLiteral("wildosscreenshotrc"))->group(QStringLiteral("Scan"));
+}
+
+struct Paper {
+ const char *id;
+ const char *name;
+ double width;
+ double height;
+};
+// The sizes people scan; "glass" is all the glass can take.
+const Paper papers[] = {
+ {"a4", QT_TRANSLATE_NOOP("Scanner", "A4"), 210, 297},
+ {"letter", QT_TRANSLATE_NOOP("Scanner", "Letter"), 215.9, 279.4},
+ {"legal", QT_TRANSLATE_NOOP("Scanner", "Legal"), 215.9, 355.6},
+ {"a5", QT_TRANSLATE_NOOP("Scanner", "A5"), 148, 210},
+};
+
+// Pages as they are written out: a copy, so a save can run on its own
+// thread while the window goes on.
+struct OutPage {
+ QImage image;
+ int dpi;
+ bool bw;
+};
+
+bool isBlackAndWhite(const QImage &image)
+{
+ if (image.format() != QImage::Format_Grayscale8) {
+ return false;
+ }
+ // A sample is enough: Black and white pages are made of 0 and 255 only.
+ const int step = std::max(1, image.height() / 200);
+ for (int y = 0; y < image.height(); y += step) {
+ const uchar *line = image.constScanLine(y);
+ for (int x = 0; x < image.width(); x += 3) {
+ if (line[x] != 0 && line[x] != 255) {
+ return false;
+ }
+ }
+ }
+ return true;
+}
+
+// Each page at its own size: the pixels over the resolution they were
+// scanned at, so a printed copy comes out the size of the paper.
+bool writePdfPages(QIODevice *device, const QList<OutPage> &pages, const QString &title)
+{
+ if (pages.isEmpty()) {
+ return false;
+ }
+ QPdfWriter writer(device);
+ writer.setCreator(QStringLiteral("Wild OS Capture"));
+ writer.setTitle(title);
+ QPainter painter;
+ for (int i = 0; i < pages.size(); ++i) {
+ const OutPage &page = pages.at(i);
+ const QSizeF mm(page.image.width() * 25.4 / page.dpi, page.image.height() * 25.4 / page.dpi);
+ writer.setPageSize(QPageSize(mm, QPageSize::Millimeter, QString(), QPageSize::ExactMatch));
+ writer.setPageMargins(QMarginsF(0, 0, 0, 0));
+ writer.setResolution(page.dpi);
+ if (i == 0) {
+ if (!painter.begin(&writer)) {
+ return false;
+ }
+ } else if (!writer.newPage()) {
+ return false;
+ }
+ // Black and white goes in without JPEG: Qt would otherwise store it
+ // as a colour JPEG, seven times the size, with smudged edges.
+ painter.setRenderHint(QPainter::LosslessImageRendering, page.bw);
+ painter.drawImage(QRectF(QPointF(0, 0), QSizeF(page.image.size())), page.image);
+ }
+ return painter.end();
+}
+
+QString placeName(const QString &folder)
+{
+ const QString documents = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
+ const QString pictures = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation);
+ if (folder.startsWith(documents)) {
+ return QCoreApplication::translate("Scanner", "Documents › Scans");
+ }
+ if (folder.startsWith(pictures)) {
+ return QCoreApplication::translate("Scanner", "Pictures › Scans");
+ }
+ return QFileInfo(folder).fileName();
+}
+
+// Letter where it is the usual paper, A4 everywhere else.
+QString defaultPaper()
+{
+ const QLocale::Territory place = QLocale::system().territory();
+ const bool letter = place == QLocale::UnitedStates || place == QLocale::Canada || place == QLocale::Mexico || place == QLocale::Philippines
+ || place == QLocale::Chile || place == QLocale::Colombia;
+ return letter ? QStringLiteral("letter") : QStringLiteral("a4");
+}
+}
+
+ScanPages::ScanPages()
+ : QQuickImageProvider(QQuickImageProvider::Image)
+{
+}
+
+QImage ScanPages::requestImage(const QString &id, QSize *size, const QSize &requestedSize)
+{
+ // image://scan/<page>/<revision>: the revision only makes the address
+ // new when the page changes.
+ const QImage image = get(id.section(QLatin1Char('/'), 0, 0).toInt());
+ if (size) {
+ *size = image.size();
+ }
+ if (image.isNull() || (requestedSize.width() <= 0 && requestedSize.height() <= 0)) {
+ return image;
+ }
+ const QSize want = image.size().scaled(QSize(requestedSize.width() > 0 ? requestedSize.width() : INT_MAX,
+ requestedSize.height() > 0 ? requestedSize.height() : INT_MAX),
+ Qt::KeepAspectRatio);
+ return want.width() < image.width() ? image.scaled(want, Qt::KeepAspectRatio, Qt::SmoothTransformation) : image;
+}
+
+void ScanPages::set(int id, const QImage &image)
+{
+ QMutexLocker lock(&m_mutex);
+ m_images.insert(id, image);
+}
+
+QImage ScanPages::get(int id) const
+{
+ QMutexLocker lock(&m_mutex);
+ return m_images.value(id);
+}
+
+void ScanPages::remove(int id)
+{
+ QMutexLocker lock(&m_mutex);
+ m_images.remove(id);
+}
+
+Scanner::Scanner(QObject *parent)
+ : QObject(parent)
+ , m_images(new ScanPages)
+{
+ qRegisterMetaType<ScannerCaps>();
+ const KConfigGroup config = settings();
+ m_paper = config.readEntry("Paper", defaultPaper());
+ m_source = config.readEntry("Source", QStringLiteral("glass"));
+ m_colour = config.readEntry("Colour", QStringLiteral("colour"));
+ m_dpi = config.readEntry("Resolution", 300);
+ m_straighten = config.readEntry("Straighten", true);
+ m_workDir = QDir::tempPath() + QStringLiteral("/wildos-scan-") + QString::number(QCoreApplication::applicationPid());
+
+ m_measureTimer.setSingleShot(true);
+ m_measureTimer.setInterval(400);
+ connect(&m_measureTimer, &QTimer::timeout, this, &Scanner::measure);
+}
+
+Scanner::~Scanner()
+{
+ if (m_worker) {
+ m_worker->cancelNow();
+ QMetaObject::invokeMethod(m_worker, &ScanWorker::stop, Qt::BlockingQueuedConnection);
+ m_thread.quit();
+ m_thread.wait();
+ delete m_worker;
+ }
+ QDir(m_workDir).removeRecursively();
+}
+
+void Scanner::startWorker()
+{
+ if (m_worker) {
+ return;
+ }
+ m_worker = new ScanWorker;
+ m_worker->moveToThread(&m_thread);
+ m_thread.setObjectName(QStringLiteral("scan"));
+ m_thread.start();
+ QMetaObject::invokeMethod(m_worker, &ScanWorker::start);
+
+ connect(m_worker, &ScanWorker::devicesFound, this, [this](const QVariantList &found) {
+ m_devices = found;
+ m_looking = false;
+ m_looked = true;
+ Q_EMIT devicesChanged();
+ // Found again by name: airscan numbers its scanners in the order
+ // it hears them, so the same one can come back as e1 after e0.
+ QString keep;
+ const QString saved = settings().readEntry("Scanner", QString());
+ for (const QString &want : {m_deviceName, saved}) {
+ for (const QVariant &d : found) {
+ const QVariantMap entry = d.toMap();
+ if (keep.isEmpty() && !want.isEmpty() && entry.value(QStringLiteral("name")).toString() == want) {
+ keep = entry.value(QStringLiteral("id")).toString();
+ }
+ }
+ }
+ if (keep.isEmpty() && !found.isEmpty()) {
+ keep = found.first().toMap().value(QStringLiteral("id")).toString();
+ }
+ m_deviceName = nameOf(keep);
+ if (keep.isEmpty()) {
+ m_device.clear();
+ m_caps = {};
+ m_opening = false;
+ Q_EMIT deviceChanged();
+ return;
+ }
+ // Opened again even when it is the same: listing let it go.
+ m_device = keep;
+ m_opening = true;
+ Q_EMIT deviceChanged();
+ QMetaObject::invokeMethod(m_worker, "open", Q_ARG(QString, keep));
+ });
+ connect(m_worker, &ScanWorker::opened, this, [this](const QString &name, const ScannerCaps &caps) {
+ if (name != m_device) {
+ return;
+ }
+ m_caps = caps;
+ m_opening = false;
+ pickDefaults();
+ Q_EMIT deviceChanged();
+ });
+ connect(m_worker, &ScanWorker::openFailed, this, [this](const QString &name, const QString &outcome) {
+ if (name != m_device) {
+ return;
+ }
+ m_opening = false;
+ m_caps = {};
+ Q_EMIT deviceChanged();
+ if (outcome == QLatin1String("busy")) {
+ setProblem(tr("The scanner is busy"), tr("Another computer or app is using it. Try again when it has finished."));
+ } else {
+ setProblem(tr("Couldn't reach the scanner"), tr("Check it's switched on and connected, then choose it again."));
+ }
+ });
+ connect(m_worker, &ScanWorker::pageStarted, this, [this](int) {
+ m_scanningPage = int(m_pages.size()) + 1;
+ Q_EMIT scanningChanged();
+ });
+ connect(m_worker, &ScanWorker::progress, this, [this](qreal fraction) {
+ m_progress = fraction;
+ Q_EMIT progressChanged();
+ });
+ connect(m_worker, &ScanWorker::pageScanned, this, [this](const QImage &image, int dpi, const QString &note) {
+ ++m_pagesThisScan;
+ addPage(image, dpi, note);
+ });
+ connect(m_worker, &ScanWorker::finished, this, [this](const QString &outcome, int pages) {
+ m_scanning = false;
+ m_cancelling = false;
+ m_progress = -1;
+ Q_EMIT scanningChanged();
+ Q_EMIT progressChanged();
+ const QString kept = pages > 0 ? tr(" The pages scanned before that are kept.") : QString();
+ if (outcome == QLatin1String("cancelled")) {
+ Q_EMIT said(pages == 1 ? tr("Scan stopped. The page scanned before that is kept.")
+ : pages > 1 ? tr("Scan stopped. The %1 pages scanned before that are kept.").arg(pages)
+ : tr("Scan cancelled"),
+ QString());
+ } else if (outcome == QLatin1String("busy")) {
+ setProblem(tr("The scanner is busy"), tr("Another computer or app is using it. Try again when it has finished."));
+ } else if (outcome == QLatin1String("offline")) {
+ setProblem(tr("The scanner stopped answering"), tr("Check it's switched on and connected, then try again.") + kept);
+ lookAgain();
+ } else if (outcome == QLatin1String("empty")) {
+ setProblem(tr("The feeder is empty"), tr("Put the pages in the feeder, then press Scan."));
+ } else if (outcome == QLatin1String("jammed")) {
+ setProblem(tr("Paper is stuck in the feeder"), tr("Clear it as the scanner shows, then scan the rest.") + kept);
+ } else if (outcome == QLatin1String("cover")) {
+ setProblem(tr("The scanner's lid is open"), tr("Close it, then try again."));
+ } else if (outcome != QLatin1String("done")) {
+ setProblem(tr("The scan didn't work"), tr("Try again. If it keeps happening, switch the scanner off and on.") + kept);
+ }
+ });
+}
+
+bool Scanner::canSign() const
+{
+ return !QStandardPaths::findExecutable(QStringLiteral("wildos-pdf")).isEmpty();
+}
+
+void Scanner::saveSetting(const char *key, const QVariant &value)
+{
+ KConfigGroup group = settings();
+ group.writeEntry(key, value);
+ group.sync();
+}
+
+void Scanner::setSource(const QString &source)
+{
+ if (m_source != source) {
+ m_source = source;
+ saveSetting("Source", source);
+ Q_EMIT settingsChanged();
+ }
+}
+
+void Scanner::setColour(const QString &colour)
+{
+ if (m_colour != colour) {
+ m_colour = colour;
+ saveSetting("Colour", colour);
+ Q_EMIT settingsChanged();
+ m_measureTimer.start();
+ }
+}
+
+void Scanner::setDpi(int dpi)
+{
+ if (m_dpi != dpi) {
+ m_dpi = dpi;
+ saveSetting("Resolution", dpi);
+ Q_EMIT settingsChanged();
+ }
+}
+
+void Scanner::setPaper(const QString &paper)
+{
+ if (m_paper != paper) {
+ m_paper = paper;
+ saveSetting("Paper", paper);
+ Q_EMIT settingsChanged();
+ }
+}
+
+void Scanner::setStraighten(bool on)
+{
+ if (m_straighten != on) {
+ m_straighten = on;
+ saveSetting("Straighten", on);
+ Q_EMIT settingsChanged();
+ }
+}
+
+QVariantList Scanner::qualities() const
+{
+ const QList<int> offered = m_caps.resolutions.isEmpty() ? QList<int>{150, 300, 600} : m_caps.resolutions;
+ struct Preset {
+ int dpi;
+ const char *name;
+ };
+ const Preset presets[] = {{150, QT_TR_NOOP("Draft")}, {300, QT_TR_NOOP("Document")}, {600, QT_TR_NOOP("Photo")}};
+ QVariantList out;
+ QList<int> used;
+ for (const Preset &p : presets) {
+ int nearest = offered.first();
+ for (int r : offered) {
+ if (std::abs(r - p.dpi) < std::abs(nearest - p.dpi)) {
+ nearest = r;
+ }
+ }
+ if (used.contains(nearest)) {
+ continue;
+ }
+ used << nearest;
+ out << QVariantMap{{QStringLiteral("value"), nearest}, {QStringLiteral("text"), tr("%1, %2 dpi").arg(tr(p.name)).arg(nearest)}};
+ }
+ return out;
+}
+
+QVariantList Scanner::paperSizes() const
+{
+ QVariantList out;
+ for (const Paper &p : papers) {
+ // A size the glass can't take isn't offered, with a little room
+ // for glass that is a hair short of its paper.
+ if (m_caps.maxWidthMm > 0 && (p.width > m_caps.maxWidthMm + 3 || p.height > m_caps.maxHeightMm + 3)) {
+ continue;
+ }
+ out << QVariantMap{{QStringLiteral("value"), QString::fromLatin1(p.id)}, {QStringLiteral("text"), tr(p.name)}};
+ }
+ out << QVariantMap{{QStringLiteral("value"), QStringLiteral("glass")}, {QStringLiteral("text"), tr("All of the glass")}};
+ return out;
+}
+
+void Scanner::pickDefaults()
+{
+ // From what was last chosen, not from what the previous scanner had
+ // to fall back to: A4 picked on one scanner stays A4 on the next one
+ // that can take it.
+ const KConfigGroup config = settings();
+ m_source = config.readEntry("Source", QStringLiteral("glass"));
+ m_colour = config.readEntry("Colour", QStringLiteral("colour"));
+ m_dpi = config.readEntry("Resolution", 300);
+ m_paper = config.readEntry("Paper", defaultPaper());
+ if (m_source == QLatin1String("feeder") && !hasFeeder()) {
+ m_source = QStringLiteral("glass");
+ } else if (m_source == QLatin1String("glass") && !hasGlass()) {
+ m_source = QStringLiteral("feeder");
+ }
+ if (m_colour == QLatin1String("grey") && m_caps.greyMode.isEmpty() && !m_caps.colourMode.isEmpty()) {
+ m_colour = QStringLiteral("colour");
+ }
+ const QVariantList q = qualities();
+ bool found = false;
+ int best = 0;
+ for (const QVariant &v : q) {
+ const int dpi = v.toMap().value(QStringLiteral("value")).toInt();
+ found = found || dpi == m_dpi;
+ if (best == 0 || std::abs(dpi - 300) < std::abs(best - 300)) {
+ best = dpi;
+ }
+ }
+ if (!found) {
+ m_dpi = best;
+ }
+ bool paperFound = false;
+ for (const QVariant &v : paperSizes()) {
+ paperFound = paperFound || v.toMap().value(QStringLiteral("value")).toString() == m_paper;
+ }
+ if (!paperFound) {
+ m_paper = QStringLiteral("glass");
+ }
+ Q_EMIT settingsChanged();
+}
+
+void Scanner::lookAgain()
+{
+ startWorker();
+ if (m_looking || m_scanning) {
+ return;
+ }
+ m_looking = true;
+ Q_EMIT devicesChanged();
+ QMetaObject::invokeMethod(m_worker, &ScanWorker::listDevices);
+}
+
+void Scanner::choose(const QString &device)
+{
+ startWorker();
+ if (device == m_device || m_scanning) {
+ return;
+ }
+ clearProblem();
+ m_device = device;
+ m_deviceName = nameOf(device);
+ m_opening = true;
+ m_caps = {};
+ saveSetting("Scanner", m_deviceName);
+ Q_EMIT deviceChanged();
+ QMetaObject::invokeMethod(m_worker, "open", Q_ARG(QString, device));
+}
+
+QString Scanner::nameOf(const QString &id) const
+{
+ for (const QVariant &d : m_devices) {
+ if (d.toMap().value(QStringLiteral("id")).toString() == id) {
+ return d.toMap().value(QStringLiteral("name")).toString();
+ }
+ }
+ return {};
+}
+
+void Scanner::setProblem(const QString &title, const QString &text)
+{
+ m_problem = {{QStringLiteral("title"), title}, {QStringLiteral("text"), text}};
+ Q_EMIT problemChanged();
+}
+
+void Scanner::clearProblem()
+{
+ if (!m_problem.isEmpty()) {
+ m_problem.clear();
+ Q_EMIT problemChanged();
+ }
+}
+
+void Scanner::setBusy(bool on)
+{
+ if (m_busy != on) {
+ m_busy = on;
+ Q_EMIT busyChanged();
+ }
+}
+
+void Scanner::scan()
+{
+ if (m_scanning || m_device.isEmpty() || !m_worker) {
+ return;
+ }
+ clearProblem();
+ const bool feeder = m_source == QLatin1String("feeder") && hasFeeder();
+ QString mode;
+ bool lineart = false;
+ if (m_colour == QLatin1String("colour")) {
+ mode = m_caps.colourMode;
+ } else if (m_colour == QLatin1String("grey")) {
+ mode = m_caps.greyMode;
+ } else {
+ // Scanners' own black and white is often a coarse halftone, and
+ // some have none; a grey scan split here reads better.
+ mode = m_caps.greyMode.isEmpty() ? m_caps.lineartMode : m_caps.greyMode;
+ lineart = !m_caps.greyMode.isEmpty() || m_caps.lineartMode.isEmpty();
+ }
+ double width = m_caps.maxWidthMm > 0 ? m_caps.maxWidthMm : 215.9;
+ double height = m_caps.maxHeightMm > 0 ? m_caps.maxHeightMm : 297;
+ for (const Paper &p : papers) {
+ if (m_paper == QLatin1String(p.id)) {
+ width = m_caps.maxWidthMm > 0 ? std::min(p.width, m_caps.maxWidthMm) : p.width;
+ height = m_caps.maxHeightMm > 0 ? std::min(p.height, m_caps.maxHeightMm) : p.height;
+ }
+ }
+ const QVariantMap request{{QStringLiteral("device"), m_device},
+ {QStringLiteral("feeder"), feeder},
+ {QStringLiteral("source"), feeder ? m_caps.feederSource : m_caps.glassSource},
+ {QStringLiteral("mode"), mode},
+ {QStringLiteral("lineart"), lineart},
+ {QStringLiteral("dpi"), m_dpi},
+ {QStringLiteral("widthMm"), width},
+ {QStringLiteral("heightMm"), height},
+ {QStringLiteral("straighten"), m_straighten}};
+ m_scanning = true;
+ m_cancelling = false;
+ m_pagesThisScan = 0;
+ m_scanningPage = int(m_pages.size()) + 1;
+ m_progress = -1;
+ Q_EMIT scanningChanged();
+ Q_EMIT progressChanged();
+ QMetaObject::invokeMethod(m_worker, "scan", Q_ARG(QVariantMap, request));
+}
+
+void Scanner::cancel()
+{
+ if (!m_scanning || !m_worker) {
+ return;
+ }
+ m_cancelling = true;
+ Q_EMIT scanningChanged();
+ m_worker->cancelNow();
+}
+
+QVariantList Scanner::pages() const
+{
+ QVariantList out;
+ for (const Page &p : m_pages) {
+ const QImage image = m_images->get(p.id);
+ out << QVariantMap{{QStringLiteral("id"), p.id},
+ {QStringLiteral("source"), QStringLiteral("image://scan/%1/%2").arg(p.id).arg(p.rev)},
+ {QStringLiteral("width"), image.width()},
+ {QStringLiteral("height"), image.height()},
+ {QStringLiteral("note"), p.note}};
+ }
+ return out;
+}
+
+void Scanner::setCurrent(int index)
+{
+ index = m_pages.isEmpty() ? -1 : std::clamp(index, 0, int(m_pages.size()) - 1);
+ if (m_current != index) {
+ m_current = index;
+ Q_EMIT currentChanged();
+ }
+}
+
+void Scanner::addPage(const QImage &image, int dpi, const QString &note)
+{
+ Page page{m_nextId++, 1, dpi, note};
+ m_images->set(page.id, image);
+ m_pages << page;
+ Q_EMIT pagesChanged();
+ setCurrent(int(m_pages.size()) - 1);
+ m_measureTimer.start();
+}
+
+void Scanner::remember(const QString &kind, int index)
+{
+ const Page &page = m_pages.at(index);
+ m_history << Undo{kind, index, page, m_images->get(page.id)};
+ // Each copy is a whole page; ten steps back is plenty.
+ while (m_history.size() > 10) {
+ m_history.removeFirst();
+ }
+}
+
+void Scanner::changed(int index, const QImage &image, const QString &kind)
+{
+ if (index < 0 || index >= m_pages.size() || image.isNull()) {
+ return;
+ }
+ remember(kind, index);
+ Page &page = m_pages[index];
+ m_images->set(page.id, image);
+ ++page.rev;
+ page.pdfBytes = -1;
+ Q_EMIT pagesChanged();
+ m_measureTimer.start();
+}
+
+void Scanner::rotate()
+{
+ if (m_current < 0) {
+ return;
+ }
+ changed(m_current, m_images->get(m_pages.at(m_current).id).transformed(QTransform().rotate(90)), QStringLiteral("rotate"));
+}
+
+void Scanner::crop(const QRectF &fraction)
+{
+ if (m_current < 0) {
+ return;
+ }
+ const QImage image = m_images->get(m_pages.at(m_current).id);
+ const QRect area = QRect(int(std::lround(fraction.x() * image.width())), int(std::lround(fraction.y() * image.height())),
+ int(std::lround(fraction.width() * image.width())), int(std::lround(fraction.height() * image.height())))
+ .intersected(image.rect());
+ if (area.width() < 8 || area.height() < 8 || area == image.rect()) {
+ return;
+ }
+ changed(m_current, image.copy(area), QStringLiteral("crop"));
+}
+
+void Scanner::removePage()
+{
+ if (m_current < 0) {
+ return;
+ }
+ const int index = m_current;
+ remember(QStringLiteral("remove"), index);
+ m_images->remove(m_pages.at(index).id);
+ m_pages.removeAt(index);
+ Q_EMIT pagesChanged();
+ m_current = -1;
+ setCurrent(std::min(index, int(m_pages.size()) - 1));
+ Q_EMIT currentChanged();
+ m_measureTimer.start();
+ Q_EMIT said(tr("Page %1 removed").arg(index + 1), QStringLiteral("undo"));
+}
+
+void Scanner::undo()
+{
+ if (m_history.isEmpty()) {
+ return;
+ }
+ const Undo step = m_history.takeLast();
+ if (step.kind == QLatin1String("remove")) {
+ const int at = std::clamp(step.index, 0, int(m_pages.size()));
+ m_pages.insert(at, step.page);
+ m_images->set(step.page.id, step.image);
+ Q_EMIT pagesChanged();
+ m_current = -1;
+ setCurrent(at);
+ } else {
+ for (int i = 0; i < m_pages.size(); ++i) {
+ if (m_pages.at(i).id == step.page.id) {
+ m_images->set(step.page.id, step.image);
+ ++m_pages[i].rev;
+ m_pages[i].pdfBytes = -1;
+ Q_EMIT pagesChanged();
+ setCurrent(i);
+ }
+ }
+ }
+ m_measureTimer.start();
+}
+
+QString Scanner::pageFile()
+{
+ if (m_current < 0) {
+ return {};
+ }
+ QDir().mkpath(m_workDir);
+ const Page &page = m_pages.at(m_current);
+ // Named for the page, which is what the editor's title bar shows.
+ const QString path = m_workDir + QStringLiteral("/") + tr("Scanned page %1").arg(m_current + 1) + QStringLiteral(" #%1.png").arg(page.id);
+ return m_images->get(page.id).save(path, "PNG") ? path : QString();
+}
+
+void Scanner::markedUp(const QString &path)
+{
+ const int hash = int(path.lastIndexOf(QLatin1Char('#')));
+ const int id = hash < 0 ? -1 : path.mid(hash + 1).section(QLatin1Char('.'), 0, 0).toInt();
+ QImage image(path);
+ for (int i = 0; i < m_pages.size(); ++i) {
+ if (m_pages.at(i).id == id && !image.isNull()) {
+ // The editor writes ARGB; a scan has no see-through parts.
+ const QImage old = m_images->get(id);
+ image = image.convertToFormat(old.format() == QImage::Format_Grayscale8 && image.allGray() ? QImage::Format_Grayscale8 : QImage::Format_RGB888);
+ changed(i, image, QStringLiteral("markup"));
+ setCurrent(i);
+ }
+ }
+}
+
+void Scanner::measure()
+{
+ // The PDF's size, page by page: each one written to memory on a spare
+ // thread and added up, so the figure under the pages is real.
+ QPointer<Scanner> self(this);
+ qint64 total = 0;
+ bool waiting = false;
+ for (const Page &page : std::as_const(m_pages)) {
+ if (page.pdfBytes >= 0) {
+ total += page.pdfBytes;
+ continue;
+ }
+ waiting = true;
+ const int id = page.id;
+ const int rev = page.rev;
+ const QImage image = m_images->get(id);
+ const int dpi = page.dpi;
+ QThreadPool::globalInstance()->start([self, id, rev, image, dpi] {
+ QByteArray bytes;
+ QBuffer buffer(&bytes);
+ buffer.open(QIODevice::WriteOnly);
+ writePdfPages(&buffer, {OutPage{image, dpi, isBlackAndWhite(image)}}, QString());
+ const qint64 size = bytes.size();
+ QMetaObject::invokeMethod(QCoreApplication::instance(), [self, id, rev, size] {
+ if (!self) {
+ return;
+ }
+ for (Page &p : self->m_pages) {
+ if (p.id == id && p.rev == rev) {
+ p.pdfBytes = size;
+ }
+ }
+ self->m_measureTimer.start();
+ });
+ });
+ }
+ if (!waiting && total != m_pdfSize) {
+ m_pdfSize = total;
+ Q_EMIT pdfSizeChanged();
+ }
+ if (m_pages.isEmpty() && m_pdfSize != 0) {
+ m_pdfSize = 0;
+ Q_EMIT pdfSizeChanged();
+ }
+}
+
+QString Scanner::nextName(const QString &folder, const QString &suffix) const
+{
+ const QString stem = folder + QStringLiteral("/") + tr("Scan") + QLatin1Char(' ') + QDateTime::currentDateTime().toString(QStringLiteral("yyyy-MM-dd HHmmss"));
+ QString path = stem + suffix;
+ for (int n = 2; QFileInfo::exists(path); ++n) {
+ path = stem + QStringLiteral(" (%1)").arg(n) + suffix;
+ }
+ return path;
+}
+
+void Scanner::savePdf()
+{
+ writePdf(false);
+}
+
+void Scanner::writePdf(bool sign)
+{
+ if (m_pages.isEmpty() || m_busy) {
+ return;
+ }
+ setBusy(true);
+ QString documents = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
+ if (documents.isEmpty()) {
+ documents = QDir::homePath() + QStringLiteral("/Documents");
+ }
+ const QString folder = documents + QStringLiteral("/") + tr("Scans");
+ QDir().mkpath(folder);
+ const QString path = nextName(folder, QStringLiteral(".pdf"));
+ QList<OutPage> out;
+ for (const Page &p : std::as_const(m_pages)) {
+ const QImage image = m_images->get(p.id);
+ out << OutPage{image, p.dpi, isBlackAndWhite(image)};
+ }
+ QPointer<Scanner> self(this);
+ QThreadPool::globalInstance()->start([self, path, out, sign] {
+ QFile file(path);
+ const bool ok = file.open(QIODevice::WriteOnly) && writePdfPages(&file, out, QFileInfo(path).completeBaseName());
+ if (!ok) {
+ file.remove();
+ }
+ QMetaObject::invokeMethod(QCoreApplication::instance(), [self, path, ok, sign] {
+ if (!self) {
+ return;
+ }
+ self->setBusy(false);
+ if (!ok) {
+ Q_EMIT self->said(tr("Couldn't save the PDF to %1").arg(placeName(QFileInfo(path).absolutePath())), QString());
+ return;
+ }
+ if (sign) {
+ const QString pdf = QStandardPaths::findExecutable(QStringLiteral("wildos-pdf"));
+ QProcess::startDetached(pdf, {QStringLiteral("--sign"), path});
+ Q_EMIT self->said(tr("Saved to %1 and opened in PDF").arg(placeName(QFileInfo(path).absolutePath())), path);
+ return;
+ }
+ Q_EMIT self->said(tr("Saved to %1").arg(placeName(QFileInfo(path).absolutePath())), path);
+ });
+ });
+}
+
+void Scanner::openToSign()
+{
+ if (!canSign()) {
+ return;
+ }
+ writePdf(true);
+}
+
+void Scanner::savePictures()
+{
+ if (m_pages.isEmpty() || m_busy) {
+ return;
+ }
+ setBusy(true);
+ QString pictures = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation);
+ if (pictures.isEmpty()) {
+ pictures = QDir::homePath() + QStringLiteral("/Pictures");
+ }
+ const QString folder = pictures + QStringLiteral("/") + tr("Scans");
+ QDir().mkpath(folder);
+ const QString stem = nextName(folder, QString());
+ QList<OutPage> out;
+ for (const Page &p : std::as_const(m_pages)) {
+ const QImage image = m_images->get(p.id);
+ out << OutPage{image, p.dpi, isBlackAndWhite(image)};
+ }
+ QPointer<Scanner> self(this);
+ QThreadPool::globalInstance()->start([self, stem, out, folder] {
+ bool ok = true;
+ QString first;
+ for (int i = 0; i < out.size(); ++i) {
+ const OutPage &page = out.at(i);
+ // Black and white keeps its sharp edges as PNG; anything with
+ // shades is a JPEG a tenth the size.
+ const QString path = stem + (out.size() > 1 ? QStringLiteral(" ") + tr("page %1").arg(i + 1) : QString())
+ + (page.bw ? QStringLiteral(".png") : QStringLiteral(".jpg"));
+ QImage image = page.bw ? page.image.convertToFormat(QImage::Format_Mono, Qt::ThresholdDither) : page.image;
+ image.setDotsPerMeterX(int(std::lround(page.dpi / 0.0254)));
+ image.setDotsPerMeterY(int(std::lround(page.dpi / 0.0254)));
+ ok = ok && (page.bw ? image.save(path, "PNG") : image.save(path, "JPEG", 92));
+ if (first.isEmpty()) {
+ first = path;
+ }
+ }
+ const int count = int(out.size());
+ QMetaObject::invokeMethod(QCoreApplication::instance(), [self, ok, first, folder, count] {
+ if (!self) {
+ return;
+ }
+ self->setBusy(false);
+ Q_EMIT self->said(ok ? (count == 1 ? tr("Saved to %1").arg(placeName(folder)) : tr("%1 pictures saved to %2").arg(count).arg(placeName(folder)))
+ : tr("Couldn't save the pictures to %1").arg(placeName(folder)),
+ ok ? first : QString());
+ });
+ });
+}
+
+void Scanner::forget()
+{
+ for (const Page &p : std::as_const(m_pages)) {
+ m_images->remove(p.id);
+ }
+ m_pages.clear();
+ m_history.clear();
+ m_current = -1;
+ Q_EMIT pagesChanged();
+ Q_EMIT currentChanged();
+ clearProblem();
+ m_measureTimer.start();
+}
diff --git a/packages/wildos-capture/src/scanner.h b/packages/wildos-capture/src/scanner.h
new file mode 100644
index 0000000..8b42bd9
--- /dev/null
+++ b/packages/wildos-capture/src/scanner.h
@@ -0,0 +1,221 @@
+#pragma once
+
+#include <QHash>
+#include <QImage>
+#include <QMutex>
+#include <QObject>
+#include <QQuickImageProvider>
+#include <QThread>
+#include <QTimer>
+#include <QVariantList>
+#include <QVariantMap>
+
+#include <atomic>
+
+class ScanWorker;
+
+// What a scanner can do, read from its SANE options when it is opened.
+struct ScannerCaps {
+ QString glassSource;
+ QString feederSource;
+ // SANE's own mode names for colour, grey and black and white; empty
+ // when the scanner has no such mode.
+ QString colourMode;
+ QString greyMode;
+ QString lineartMode;
+ QList<int> resolutions;
+ double maxWidthMm = 0;
+ double maxHeightMm = 0;
+};
+Q_DECLARE_METATYPE(ScannerCaps)
+
+// The pages scanned so far, kept for the image provider, which Qt calls
+// from its own threads.
+class ScanPages : public QQuickImageProvider
+{
+public:
+ ScanPages();
+ QImage requestImage(const QString &id, QSize *size, const QSize &requestedSize) override;
+
+ void set(int id, const QImage &image);
+ QImage get(int id) const;
+ void remove(int id);
+
+private:
+ mutable QMutex m_mutex;
+ QHash<int, QImage> m_images;
+};
+
+// The Scan tab (CaptureScan.dc, board 15.30): finds scanners through SANE,
+// driverless network ones first (eSCL and WSD through sane-airscan), then
+// USB ones through SANE's backends; scans from the glass or the feeder;
+// keeps the pages for rotating, cropping, marking up and removing; and
+// writes them out as a PDF or as pictures. Every SANE call happens on one
+// worker thread, so a scanner that takes its time never holds up the
+// window.
+class Scanner : public QObject
+{
+ Q_OBJECT
+
+ Q_PROPERTY(QVariantList devices READ devices NOTIFY devicesChanged)
+ Q_PROPERTY(bool looking READ looking NOTIFY devicesChanged)
+ Q_PROPERTY(bool looked READ looked NOTIFY devicesChanged)
+ Q_PROPERTY(QString device READ device NOTIFY deviceChanged)
+ Q_PROPERTY(bool opening READ opening NOTIFY deviceChanged)
+ Q_PROPERTY(bool hasGlass READ hasGlass NOTIFY deviceChanged)
+ Q_PROPERTY(bool hasFeeder READ hasFeeder NOTIFY deviceChanged)
+ Q_PROPERTY(QVariantList qualities READ qualities NOTIFY deviceChanged)
+ Q_PROPERTY(QVariantList paperSizes READ paperSizes NOTIFY deviceChanged)
+
+ Q_PROPERTY(QString source READ source WRITE setSource NOTIFY settingsChanged)
+ Q_PROPERTY(QString colour READ colour WRITE setColour NOTIFY settingsChanged)
+ Q_PROPERTY(int dpi READ dpi WRITE setDpi NOTIFY settingsChanged)
+ Q_PROPERTY(QString paper READ paper WRITE setPaper NOTIFY settingsChanged)
+ Q_PROPERTY(bool straighten READ straighten WRITE setStraighten NOTIFY settingsChanged)
+
+ Q_PROPERTY(bool scanning READ scanning NOTIFY scanningChanged)
+ Q_PROPERTY(bool cancelling READ cancelling NOTIFY scanningChanged)
+ Q_PROPERTY(int scanningPage READ scanningPage NOTIFY scanningChanged)
+ Q_PROPERTY(qreal progress READ progress NOTIFY progressChanged)
+ Q_PROPERTY(bool busy READ busy NOTIFY busyChanged)
+
+ Q_PROPERTY(QVariantList pages READ pages NOTIFY pagesChanged)
+ Q_PROPERTY(int current READ current WRITE setCurrent NOTIFY currentChanged)
+ Q_PROPERTY(bool canUndo READ canUndo NOTIFY pagesChanged)
+ Q_PROPERTY(qint64 pdfSize READ pdfSize NOTIFY pdfSizeChanged)
+ Q_PROPERTY(QVariantMap problem READ problem NOTIFY problemChanged)
+ Q_PROPERTY(bool canSign READ canSign CONSTANT)
+
+public:
+ explicit Scanner(QObject *parent = nullptr);
+ ~Scanner() override;
+
+ ScanPages *images() const { return m_images; }
+
+ QVariantList devices() const { return m_devices; }
+ bool looking() const { return m_looking; }
+ bool looked() const { return m_looked; }
+ QString device() const { return m_device; }
+ bool opening() const { return m_opening; }
+ bool hasGlass() const { return !m_caps.glassSource.isEmpty() || m_caps.feederSource.isEmpty(); }
+ bool hasFeeder() const { return !m_caps.feederSource.isEmpty(); }
+ QVariantList qualities() const;
+ QVariantList paperSizes() const;
+
+ QString source() const { return m_source; }
+ void setSource(const QString &source);
+ QString colour() const { return m_colour; }
+ void setColour(const QString &colour);
+ int dpi() const { return m_dpi; }
+ void setDpi(int dpi);
+ QString paper() const { return m_paper; }
+ void setPaper(const QString &paper);
+ bool straighten() const { return m_straighten; }
+ void setStraighten(bool on);
+
+ bool scanning() const { return m_scanning; }
+ bool cancelling() const { return m_cancelling; }
+ int scanningPage() const { return m_scanningPage; }
+ qreal progress() const { return m_progress; }
+ bool busy() const { return m_busy; }
+
+ QVariantList pages() const;
+ int current() const { return m_current; }
+ void setCurrent(int index);
+ bool canUndo() const { return !m_history.isEmpty(); }
+ qint64 pdfSize() const { return m_pdfSize; }
+ QVariantMap problem() const { return m_problem; }
+ bool canSign() const;
+
+ Q_INVOKABLE void lookAgain();
+ Q_INVOKABLE void choose(const QString &device);
+ Q_INVOKABLE void scan();
+ Q_INVOKABLE void cancel();
+ Q_INVOKABLE void rotate();
+ Q_INVOKABLE void crop(const QRectF &fraction);
+ Q_INVOKABLE void removePage();
+ Q_INVOKABLE void undo();
+ Q_INVOKABLE void clearProblem();
+ // Mark up: the page goes to the Capture editor as a picture, and comes
+ // back when the editor saves it.
+ Q_INVOKABLE QString pageFile();
+ Q_INVOKABLE void markedUp(const QString &path);
+ Q_INVOKABLE void savePdf();
+ Q_INVOKABLE void savePictures();
+ Q_INVOKABLE void openToSign();
+ Q_INVOKABLE void forget();
+
+Q_SIGNALS:
+ void devicesChanged();
+ void deviceChanged();
+ void settingsChanged();
+ void scanningChanged();
+ void progressChanged();
+ void busyChanged();
+ void pagesChanged();
+ void currentChanged();
+ void pdfSizeChanged();
+ void problemChanged();
+ // A short note for the window's toast. `file` is what Show in folder
+ // shows, or "undo" when the note offers Undo instead.
+ void said(const QString &message, const QString &file);
+
+private:
+ struct Page {
+ int id;
+ int rev;
+ int dpi;
+ QString note;
+ // Size as a one-page PDF, measured in the background; -1 until then.
+ qint64 pdfBytes = -1;
+ };
+ struct Undo {
+ QString kind;
+ int index;
+ Page page;
+ QImage image;
+ };
+
+ void startWorker();
+ void setProblem(const QString &title, const QString &text);
+ QString nameOf(const QString &id) const;
+ void setBusy(bool on);
+ void addPage(const QImage &image, int dpi, const QString &note);
+ void changed(int index, const QImage &image, const QString &kind);
+ void remember(const QString &kind, int index);
+ void measure();
+ void pickDefaults();
+ QString nextName(const QString &folder, const QString &suffix) const;
+ void writePdf(bool sign);
+ void saveSetting(const char *key, const QVariant &value);
+
+ QThread m_thread;
+ ScanWorker *m_worker = nullptr;
+ ScanPages *m_images;
+ QVariantList m_devices;
+ bool m_looking = false;
+ bool m_looked = false;
+ QString m_device;
+ QString m_deviceName;
+ bool m_opening = false;
+ ScannerCaps m_caps;
+ QString m_source = QStringLiteral("glass");
+ QString m_colour = QStringLiteral("colour");
+ int m_dpi = 300;
+ QString m_paper;
+ bool m_straighten = true;
+ bool m_scanning = false;
+ bool m_cancelling = false;
+ int m_scanningPage = 0;
+ int m_pagesThisScan = 0;
+ qreal m_progress = -1;
+ bool m_busy = false;
+ QList<Page> m_pages;
+ QList<Undo> m_history;
+ int m_current = -1;
+ int m_nextId = 1;
+ qint64 m_pdfSize = 0;
+ QVariantMap m_problem;
+ QTimer m_measureTimer;
+ QString m_workDir;
+};
diff --git a/packages/wildos-capture/src/scanprocess.cpp b/packages/wildos-capture/src/scanprocess.cpp
new file mode 100644
index 0000000..035718a
--- /dev/null
+++ b/packages/wildos-capture/src/scanprocess.cpp
@@ -0,0 +1,243 @@
+#include "scanprocess.h"
+
+#include <QColor>
+#include <QList>
+#include <QStringList>
+#include <QPainter>
+#include <QPoint>
+#include <QTransform>
+
+#include <algorithm>
+#include <array>
+#include <vector>
+#include <cmath>
+#include <random>
+
+namespace
+{
+int otsu(const QImage &grey)
+{
+ std::array<qint64, 256> hist{};
+ for (int y = 0; y < grey.height(); ++y) {
+ const uchar *line = grey.constScanLine(y);
+ for (int x = 0; x < grey.width(); ++x) {
+ ++hist[line[x]];
+ }
+ }
+ const qint64 total = qint64(grey.width()) * grey.height();
+ double sum = 0;
+ for (int i = 0; i < 256; ++i) {
+ sum += double(i) * hist[i];
+ }
+ double sumB = 0, best = -1;
+ qint64 wB = 0;
+ int threshold = 128;
+ for (int t = 0; t < 256; ++t) {
+ wB += hist[t];
+ if (wB == 0) {
+ continue;
+ }
+ const qint64 wF = total - wB;
+ if (wF == 0) {
+ break;
+ }
+ sumB += double(t) * hist[t];
+ const double mB = sumB / wB;
+ const double mF = (sum - sumB) / wF;
+ const double between = double(wB) * double(wF) * (mB - mF) * (mB - mF);
+ if (between > best) {
+ best = between;
+ threshold = t;
+ }
+ }
+ return threshold;
+}
+
+QImage greyOf(const QImage &image)
+{
+ return image.format() == QImage::Format_Grayscale8 ? image : image.convertToFormat(QImage::Format_Grayscale8);
+}
+
+// Lines of text, at the angle they really run at, stack their ink into a
+// few rows with clean gaps between, so the row counts change sharply from
+// one row to the next. That sharpness is the score.
+double score(const QList<QPoint> &points, double degrees, int height, int width)
+{
+ const double a = degrees * M_PI / 180.0;
+ const double s = std::sin(a), c = std::cos(a);
+ const int offset = width + 2;
+ std::vector<int> rows(size_t(height + 2 * offset), 0);
+ for (const QPoint &p : points) {
+ const int r = int(std::lround(p.y() * c - p.x() * s)) + offset;
+ if (r >= 0 && r < int(rows.size())) {
+ ++rows[size_t(r)];
+ }
+ }
+ double total = 0;
+ for (size_t i = 1; i < rows.size(); ++i) {
+ const double d = rows[i] - rows[i - 1];
+ total += d * d;
+ }
+ return total;
+}
+
+int meanOf(const QImage &grey, const QRect &area)
+{
+ qint64 sum = 0, n = 0;
+ const QRect r = area.intersected(grey.rect());
+ for (int y = r.top(); y <= r.bottom(); ++y) {
+ const uchar *line = grey.constScanLine(y);
+ for (int x = r.left(); x <= r.right(); ++x) {
+ sum += line[x];
+ ++n;
+ }
+ }
+ return n ? int(sum / n) : 255;
+}
+}
+
+double ScanProcess::skewAngle(const QImage &image)
+{
+ const QImage grey = greyOf(image);
+ const int threshold = otsu(grey);
+ // Strokes, not areas: a dark pixel counts only with paper a few pixels
+ // to one side, so a dark lid round a crooked page adds its edges,
+ // which lean with the page, and not its bulk, which leans nowhere.
+ QList<QPoint> ink;
+ const int reach = 3;
+ for (int y = reach; y < grey.height() - reach; ++y) {
+ const uchar *line = grey.constScanLine(y);
+ const uchar *above = grey.constScanLine(y - reach);
+ const uchar *below = grey.constScanLine(y + reach);
+ for (int x = reach; x < grey.width() - reach; ++x) {
+ if (line[x] < threshold
+ && (line[x - reach] >= threshold || line[x + reach] >= threshold || above[x] >= threshold || below[x] >= threshold)) {
+ ink << QPoint(x, y);
+ }
+ }
+ }
+ if (ink.size() < 300) {
+ return 0;
+ }
+ if (ink.size() > 120000) {
+ std::mt19937 random(7);
+ std::shuffle(ink.begin(), ink.end(), random);
+ ink.resize(120000);
+ }
+ const double flat = score(ink, 0, grey.height(), grey.width());
+ double best = 0, bestScore = flat;
+ for (double a = -6; a <= 6.001; a += 0.25) {
+ const double s = score(ink, a, grey.height(), grey.width());
+ if (s > bestScore) {
+ best = a;
+ bestScore = s;
+ }
+ }
+ const double coarse = best;
+ for (double a = coarse - 0.25; a <= coarse + 0.25; a += 0.02) {
+ const double s = score(ink, a, grey.height(), grey.width());
+ if (s > bestScore) {
+ best = a;
+ bestScore = s;
+ }
+ }
+ // Too slight a gain is noise, not a lean.
+ return bestScore > flat * 1.03 ? best : 0;
+}
+
+QImage ScanProcess::straightenAndCrop(const QImage &page, QString *note)
+{
+ QStringList done;
+ const QImage small = greyOf(page.width() > 1000 ? page.scaledToWidth(1000, Qt::SmoothTransformation) : page);
+ const int ring = std::max(2, small.width() / 100);
+ const int border = (meanOf(small, QRect(0, 0, small.width(), ring)) + meanOf(small, QRect(0, small.height() - ring, small.width(), ring))
+ + meanOf(small, QRect(0, 0, ring, small.height())) + meanOf(small, QRect(small.width() - ring, 0, ring, small.height())))
+ / 4;
+ // Corners a turn uncovers take the colour round the edge, so a white
+ // lid stays white and a dark one is trimmed with the rest.
+ const QColor fill(border, border, border);
+
+ QImage result = page;
+ const double angle = skewAngle(small);
+ if (std::abs(angle) >= 0.1) {
+ QImage turned(page.size(), QImage::Format_RGB32);
+ turned.fill(fill);
+ {
+ QPainter painter(&turned);
+ painter.setRenderHint(QPainter::SmoothPixmapTransform);
+ const QPointF centre(page.width() / 2.0, page.height() / 2.0);
+ painter.translate(centre);
+ painter.rotate(-angle);
+ painter.translate(-centre);
+ painter.drawImage(0, 0, page);
+ }
+ result = page.format() == QImage::Format_Grayscale8 ? turned.convertToFormat(QImage::Format_Grayscale8) : turned.convertToFormat(QImage::Format_RGB888);
+ done << QStringLiteral("straightened");
+ }
+
+ // Dark bands round the paper: the lid's shadow, the glass's edge, or
+ // the corners a turned page leaves. A row or column that is mostly
+ // darker than the paper is trimmed, from the outside in.
+ const QImage look = greyOf(result.width() > 1000 ? result.scaledToWidth(1000, Qt::SmoothTransformation) : result);
+ const int paper = meanOf(look, QRect(look.width() / 4, look.height() / 4, look.width() / 2, look.height() / 2));
+ const int dark = std::min((border + paper) / 2, paper * 6 / 10);
+ auto darkRow = [&look, dark](int y) {
+ const uchar *line = look.constScanLine(y);
+ int n = 0;
+ for (int x = 0; x < look.width(); ++x) {
+ n += line[x] < dark;
+ }
+ return n * 2 > look.width();
+ };
+ auto darkColumn = [&look, dark](int x, int top, int bottom) {
+ int n = 0;
+ for (int y = top; y <= bottom; ++y) {
+ n += look.constScanLine(y)[x] < dark;
+ }
+ return n * 2 > bottom - top + 1;
+ };
+ int top = 0, bottom = look.height() - 1;
+ while (top < look.height() / 4 && darkRow(top)) {
+ ++top;
+ }
+ while (bottom > look.height() * 3 / 4 && darkRow(bottom)) {
+ --bottom;
+ }
+ int left = 0, right = look.width() - 1;
+ while (left < look.width() / 4 && darkColumn(left, top, bottom)) {
+ ++left;
+ }
+ while (right > look.width() * 3 / 4 && darkColumn(right, top, bottom)) {
+ --right;
+ }
+ const double scale = double(result.width()) / look.width();
+ const int edge = std::max(2, look.width() / 250);
+ if (top > 0 || left > 0 || bottom < look.height() - 1 || right < look.width() - 1) {
+ // A little more, so no grey line is left along the cut.
+ const QRect keep = QRect(QPoint(int(std::ceil((left + (left > 0 ? edge : 0)) * scale)), int(std::ceil((top + (top > 0 ? edge : 0)) * scale))),
+ QPoint(int(std::floor((right - (right < look.width() - 1 ? edge : 0)) * scale)),
+ int(std::floor((bottom - (bottom < look.height() - 1 ? edge : 0)) * scale))))
+ .intersected(result.rect());
+ if (keep.width() > result.width() / 2 && keep.height() > result.height() / 2 && keep != result.rect()) {
+ result = result.copy(keep);
+ done << QStringLiteral("edges trimmed");
+ }
+ }
+ if (note) {
+ *note = done.join(QStringLiteral(", "));
+ }
+ return result;
+}
+
+QImage ScanProcess::blackAndWhite(const QImage &page)
+{
+ QImage grey = greyOf(page);
+ const int threshold = otsu(grey);
+ for (int y = 0; y < grey.height(); ++y) {
+ uchar *line = grey.scanLine(y);
+ for (int x = 0; x < grey.width(); ++x) {
+ line[x] = line[x] < threshold ? 0 : 255;
+ }
+ }
+ return grey;
+}
diff --git a/packages/wildos-capture/src/scanprocess.h b/packages/wildos-capture/src/scanprocess.h
new file mode 100644
index 0000000..c022ce4
--- /dev/null
+++ b/packages/wildos-capture/src/scanprocess.h
@@ -0,0 +1,20 @@
+#pragma once
+
+#include <QImage>
+#include <QString>
+
+// What "Straighten and crop each page" and "Black and white" do to a
+// scanned page, on the scan's own thread.
+namespace ScanProcess
+{
+// Turns the page level by the lines of its text (or its own edges, on a
+// dark lid), then trims the dark bands left round it. `note` says what
+// was done, for the line above the page: "straightened, edges trimmed".
+QImage straightenAndCrop(const QImage &page, QString *note);
+// Ink and paper only, split where the page's own histogram parts them
+// (Otsu), for scanners without a mode of their own for it.
+QImage blackAndWhite(const QImage &page);
+// The angle, in degrees, the page's lines lean by; 0 when there is too
+// little to go on.
+double skewAngle(const QImage &grey);
+}
diff --git a/packages/wildos-capture/src/scanworker.cpp b/packages/wildos-capture/src/scanworker.cpp
new file mode 100644
index 0000000..2fe2308
--- /dev/null
+++ b/packages/wildos-capture/src/scanworker.cpp
@@ -0,0 +1,524 @@
+#include "scanworker.h"
+#include "scanprocess.h"
+
+#include <QHash>
+#include <QRegularExpression>
+#include <QThread>
+
+#include <sane/sane.h>
+#include <sane/saneopts.h>
+
+#include <cmath>
+#include <cstring>
+
+namespace
+{
+SANE_Handle handleOf(const std::atomic<void *> &handle)
+{
+ return static_cast<SANE_Handle>(handle.load());
+}
+
+QString outcomeOf(SANE_Status status)
+{
+ switch (status) {
+ case SANE_STATUS_GOOD:
+ case SANE_STATUS_EOF:
+ return QStringLiteral("done");
+ case SANE_STATUS_CANCELLED:
+ return QStringLiteral("cancelled");
+ case SANE_STATUS_DEVICE_BUSY:
+ return QStringLiteral("busy");
+ case SANE_STATUS_NO_DOCS:
+ return QStringLiteral("empty");
+ case SANE_STATUS_JAMMED:
+ return QStringLiteral("jammed");
+ case SANE_STATUS_COVER_OPEN:
+ return QStringLiteral("cover");
+ case SANE_STATUS_IO_ERROR:
+ case SANE_STATUS_INVAL:
+ case SANE_STATUS_ACCESS_DENIED:
+ return QStringLiteral("offline");
+ default:
+ return QStringLiteral("failed");
+ }
+}
+
+// The scan modes SANE backends name differently: SANE's own Color, Gray
+// and Lineart, and what airscan, escl and others call them.
+bool isColour(const QString &mode)
+{
+ return mode.compare(QLatin1String(SANE_VALUE_SCAN_MODE_COLOR), Qt::CaseInsensitive) == 0 || mode.contains(QLatin1String("color"), Qt::CaseInsensitive)
+ || mode.contains(QLatin1String("colour"), Qt::CaseInsensitive) || mode.contains(QLatin1String("rgb"), Qt::CaseInsensitive);
+}
+bool isGrey(const QString &mode)
+{
+ return mode.contains(QLatin1String("gray"), Qt::CaseInsensitive) || mode.contains(QLatin1String("grey"), Qt::CaseInsensitive);
+}
+bool isLineart(const QString &mode)
+{
+ return mode.contains(QLatin1String("lineart"), Qt::CaseInsensitive) || mode.contains(QLatin1String("binary"), Qt::CaseInsensitive)
+ || mode.contains(QLatin1String("black"), Qt::CaseInsensitive);
+}
+bool isFeeder(const QString &source)
+{
+ return source.contains(QLatin1String("adf"), Qt::CaseInsensitive) || source.contains(QLatin1String("feeder"), Qt::CaseInsensitive);
+}
+// A duplex feeder or the back of the page is a choice for later; the
+// first plain feeder is the one offered.
+bool isPlainFeeder(const QString &source)
+{
+ return isFeeder(source) && !source.contains(QLatin1String("duplex"), Qt::CaseInsensitive) && !source.contains(QLatin1String("back"), Qt::CaseInsensitive)
+ && !source.contains(QLatin1String("rear"), Qt::CaseInsensitive);
+}
+bool isGlass(const QString &source)
+{
+ return source.contains(QLatin1String("flatbed"), Qt::CaseInsensitive) || source.contains(QLatin1String("platen"), Qt::CaseInsensitive)
+ || source.contains(QLatin1String("glass"), Qt::CaseInsensitive) || source.contains(QLatin1String("normal"), Qt::CaseInsensitive);
+}
+
+double numberOf(const SANE_Option_Descriptor *d, SANE_Word word)
+{
+ return d->type == SANE_TYPE_FIXED ? SANE_UNFIX(word) : double(word);
+}
+}
+
+ScanWorker::ScanWorker() = default;
+
+ScanWorker::~ScanWorker()
+{
+ stop();
+}
+
+void ScanWorker::start()
+{
+ SANE_Int version = 0;
+ m_initialised = sane_init(&version, nullptr) == SANE_STATUS_GOOD;
+}
+
+void ScanWorker::stop()
+{
+ closeDevice();
+ if (m_initialised) {
+ sane_exit();
+ m_initialised = false;
+ }
+}
+
+void ScanWorker::listDevices()
+{
+ QVariantList network;
+ QVariantList local;
+ if (m_initialised) {
+ // A device that is open is not always listed again by its backend,
+ // so it is let go first and opened again when it is needed.
+ closeDevice();
+ const SANE_Device **list = nullptr;
+ if (sane_get_devices(&list, SANE_FALSE) == SANE_STATUS_GOOD && list) {
+ QHash<QString, bool> seen;
+ for (int i = 0; list[i]; ++i) {
+ const SANE_Device *d = list[i];
+ const QString name = QString::fromUtf8(d->name);
+ const QString type = QString::fromUtf8(d->type ? d->type : "");
+ // SANE's v4l and gphoto backends list webcams and cameras,
+ // which are no use for paper.
+ if (type.contains(QLatin1String("camera"), Qt::CaseInsensitive) || type.contains(QLatin1String("video"), Qt::CaseInsensitive)
+ || name.startsWith(QLatin1String("v4l:")) || name.startsWith(QLatin1String("gphoto2:"))) {
+ continue;
+ }
+ const QString vendor = QString::fromUtf8(d->vendor ? d->vendor : "").trimmed();
+ const QString model = QString::fromUtf8(d->model ? d->model : "").trimmed();
+ const bool driverless = name.startsWith(QLatin1String("airscan:")) || name.startsWith(QLatin1String("escl:"));
+ // airscan names a network scanner as it announces itself
+ // ("Office printer"), the name Settings shows too.
+ QString title = driverless || vendor.isEmpty() || model.startsWith(vendor, Qt::CaseInsensitive) ? model : vendor + QLatin1Char(' ') + model;
+ if (title.isEmpty()) {
+ title = name;
+ }
+ const QString key = title.toLower();
+ if (driverless && seen.contains(key)) {
+ continue;
+ }
+ const QVariantMap entry{{QStringLiteral("id"), name}, {QStringLiteral("name"), title}, {QStringLiteral("network"), driverless}};
+ if (name.startsWith(QLatin1String("airscan:"))) {
+ seen.insert(key, true);
+ network.prepend(entry);
+ } else if (driverless) {
+ network.append(entry);
+ } else {
+ local.append(entry);
+ }
+ }
+ // escl finds the same scanners airscan does; airscan's copy is
+ // kept, being listed first.
+ QVariantList kept;
+ QHash<QString, bool> names;
+ for (const QVariant &v : network) {
+ const QString key = v.toMap().value(QStringLiteral("name")).toString().toLower();
+ if (!names.contains(key)) {
+ names.insert(key, true);
+ kept << v;
+ }
+ }
+ // A USB scanner that ipp-usb also offers over eSCL is listed
+ // once, as the driverless one. Two of the same model on USB are
+ // both kept, numbered.
+ QHash<QString, int> count;
+ for (const QVariant &v : local) {
+ QVariantMap entry = v.toMap();
+ const QString name = entry.value(QStringLiteral("name")).toString();
+ if (names.contains(name.toLower())) {
+ continue;
+ }
+ const int n = ++count[name.toLower()];
+ if (n > 1) {
+ entry.insert(QStringLiteral("name"), QStringLiteral("%1 (%2)").arg(name).arg(n));
+ }
+ kept << entry;
+ }
+ Q_EMIT devicesFound(kept);
+ return;
+ }
+ }
+ Q_EMIT devicesFound({});
+}
+
+void ScanWorker::closeDevice()
+{
+ if (SANE_Handle h = handleOf(m_handle)) {
+ m_handle = nullptr;
+ sane_close(h);
+ }
+ m_name.clear();
+}
+
+bool ScanWorker::ensureOpen(const QString &name, QString *outcome)
+{
+ if (m_handle.load() && m_name == name) {
+ return true;
+ }
+ closeDevice();
+ if (!m_initialised) {
+ *outcome = QStringLiteral("failed");
+ return false;
+ }
+ SANE_Handle h = nullptr;
+ const SANE_Status status = sane_open(name.toUtf8().constData(), &h);
+ if (status != SANE_STATUS_GOOD || !h) {
+ *outcome = outcomeOf(status == SANE_STATUS_GOOD ? SANE_STATUS_IO_ERROR : status);
+ return false;
+ }
+ m_handle = h;
+ m_name = name;
+ return true;
+}
+
+void ScanWorker::open(const QString &name)
+{
+ QString outcome;
+ if (!ensureOpen(name, &outcome)) {
+ Q_EMIT openFailed(name, outcome);
+ return;
+ }
+ // The glass's limits: a feeder can be narrower, and a few backends
+ // only show the glass's area while it is the source.
+ ScannerCaps caps = readCaps();
+ if (!caps.glassSource.isEmpty()) {
+ setString(SANE_NAME_SCAN_SOURCE, caps.glassSource);
+ const ScannerCaps glass = readCaps();
+ caps.maxWidthMm = glass.maxWidthMm;
+ caps.maxHeightMm = glass.maxHeightMm;
+ }
+ Q_EMIT opened(name, caps);
+}
+
+int ScanWorker::optionIndex(const char *name) const
+{
+ SANE_Handle h = handleOf(m_handle);
+ if (!h) {
+ return -1;
+ }
+ for (SANE_Int i = 1;; ++i) {
+ const SANE_Option_Descriptor *d = sane_get_option_descriptor(h, i);
+ if (!d) {
+ return -1;
+ }
+ if (d->name && std::strcmp(d->name, name) == 0) {
+ return SANE_OPTION_IS_ACTIVE(d->cap) ? i : -1;
+ }
+ }
+}
+
+ScannerCaps ScanWorker::readCaps()
+{
+ ScannerCaps caps;
+ SANE_Handle h = handleOf(m_handle);
+ if (!h) {
+ return caps;
+ }
+ auto strings = [h](int index) {
+ QStringList out;
+ const SANE_Option_Descriptor *d = index > 0 ? sane_get_option_descriptor(h, index) : nullptr;
+ if (d && d->constraint_type == SANE_CONSTRAINT_STRING_LIST) {
+ for (int i = 0; d->constraint.string_list[i]; ++i) {
+ out << QString::fromUtf8(d->constraint.string_list[i]);
+ }
+ }
+ return out;
+ };
+ for (const QString &s : strings(optionIndex(SANE_NAME_SCAN_SOURCE))) {
+ if (caps.feederSource.isEmpty() && isPlainFeeder(s)) {
+ caps.feederSource = s;
+ } else if (caps.glassSource.isEmpty() && isGlass(s)) {
+ caps.glassSource = s;
+ }
+ }
+ for (const QString &m : strings(optionIndex(SANE_NAME_SCAN_MODE))) {
+ if (caps.colourMode.isEmpty() && isColour(m)) {
+ caps.colourMode = m;
+ } else if (caps.greyMode.isEmpty() && isGrey(m)) {
+ caps.greyMode = m;
+ } else if (caps.lineartMode.isEmpty() && isLineart(m) && !m.contains(QLatin1String("halftone"), Qt::CaseInsensitive)) {
+ caps.lineartMode = m;
+ }
+ }
+ const int res = optionIndex(SANE_NAME_SCAN_RESOLUTION);
+ if (const SANE_Option_Descriptor *d = res > 0 ? sane_get_option_descriptor(h, res) : nullptr) {
+ if (d->constraint_type == SANE_CONSTRAINT_WORD_LIST) {
+ for (int i = 1; i <= d->constraint.word_list[0]; ++i) {
+ caps.resolutions << int(std::lround(numberOf(d, d->constraint.word_list[i])));
+ }
+ } else if (d->constraint_type == SANE_CONSTRAINT_RANGE) {
+ const double lo = numberOf(d, d->constraint.range->min);
+ const double hi = numberOf(d, d->constraint.range->max);
+ for (int v : {75, 100, 150, 200, 300, 400, 600, 1200}) {
+ if (v >= lo && v <= hi) {
+ caps.resolutions << v;
+ }
+ }
+ }
+ }
+ auto maxOf = [h, this](const char *name) {
+ const int index = optionIndex(name);
+ const SANE_Option_Descriptor *d = index > 0 ? sane_get_option_descriptor(h, index) : nullptr;
+ if (!d || d->unit != SANE_UNIT_MM || d->constraint_type != SANE_CONSTRAINT_RANGE) {
+ return 0.0;
+ }
+ return numberOf(d, d->constraint.range->max);
+ };
+ caps.maxWidthMm = maxOf(SANE_NAME_SCAN_BR_X);
+ caps.maxHeightMm = maxOf(SANE_NAME_SCAN_BR_Y);
+ return caps;
+}
+
+bool ScanWorker::setString(const char *name, const QString &value)
+{
+ SANE_Handle h = handleOf(m_handle);
+ const int index = optionIndex(name);
+ const SANE_Option_Descriptor *d = index > 0 ? sane_get_option_descriptor(h, index) : nullptr;
+ if (!d || d->type != SANE_TYPE_STRING || !SANE_OPTION_IS_SETTABLE(d->cap)) {
+ return false;
+ }
+ QByteArray buffer = value.toUtf8();
+ buffer.resize(std::max<qsizetype>(d->size, buffer.size() + 1), '\0');
+ SANE_Int info = 0;
+ return sane_control_option(h, index, SANE_ACTION_SET_VALUE, buffer.data(), &info) == SANE_STATUS_GOOD;
+}
+
+bool ScanWorker::setNumber(const char *name, double value)
+{
+ SANE_Handle h = handleOf(m_handle);
+ const int index = optionIndex(name);
+ const SANE_Option_Descriptor *d = index > 0 ? sane_get_option_descriptor(h, index) : nullptr;
+ if (!d || (d->type != SANE_TYPE_INT && d->type != SANE_TYPE_FIXED) || !SANE_OPTION_IS_SETTABLE(d->cap)) {
+ return false;
+ }
+ if (d->constraint_type == SANE_CONSTRAINT_RANGE) {
+ value = std::clamp(value, numberOf(d, d->constraint.range->min), numberOf(d, d->constraint.range->max));
+ }
+ SANE_Word word = d->type == SANE_TYPE_FIXED ? SANE_FIX(value) : SANE_Word(std::lround(value));
+ SANE_Int info = 0;
+ return sane_control_option(h, index, SANE_ACTION_SET_VALUE, &word, &info) == SANE_STATUS_GOOD;
+}
+
+void ScanWorker::cancelNow()
+{
+ m_cancel = true;
+ if (SANE_Handle h = handleOf(m_handle)) {
+ sane_cancel(h);
+ }
+}
+
+void ScanWorker::scan(const QVariantMap &settings)
+{
+ m_cancel = false;
+ QString outcome;
+ const QString name = settings.value(QStringLiteral("device")).toString();
+ const bool fresh = !m_handle.load() || m_name != name;
+ if (!ensureOpen(name, &outcome)) {
+ Q_EMIT finished(outcome, 0);
+ return;
+ }
+ // Opened again after it went away: what it can do may have been
+ // unknown since, so the window hears it again.
+ if (fresh) {
+ Q_EMIT opened(name, readCaps());
+ }
+ const bool feeder = settings.value(QStringLiteral("feeder")).toBool();
+ // Source first: some backends change the other options' limits with it.
+ if (const QString source = settings.value(QStringLiteral("source")).toString(); !source.isEmpty()) {
+ setString(SANE_NAME_SCAN_SOURCE, source);
+ }
+ if (const QString mode = settings.value(QStringLiteral("mode")).toString(); !mode.isEmpty()) {
+ setString(SANE_NAME_SCAN_MODE, mode);
+ }
+ setNumber(SANE_NAME_BIT_DEPTH, 8);
+ const int dpi = settings.value(QStringLiteral("dpi")).toInt();
+ setNumber(SANE_NAME_SCAN_RESOLUTION, dpi);
+ setNumber(SANE_NAME_SCAN_TL_X, 0);
+ setNumber(SANE_NAME_SCAN_TL_Y, 0);
+ setNumber(SANE_NAME_SCAN_BR_X, settings.value(QStringLiteral("widthMm")).toDouble());
+ setNumber(SANE_NAME_SCAN_BR_Y, settings.value(QStringLiteral("heightMm")).toDouble());
+ const bool straighten = settings.value(QStringLiteral("straighten")).toBool();
+ const bool lineart = settings.value(QStringLiteral("lineart")).toBool();
+
+ int pages = 0;
+ for (;;) {
+ Q_EMIT pageStarted(pages + 1);
+ Q_EMIT progress(-1);
+ QImage image = readPage(&outcome);
+ if (image.isNull()) {
+ // The feeder running out after the first page is the end of
+ // the pile, not a problem.
+ if (outcome == QLatin1String("empty") && pages > 0) {
+ outcome = QStringLiteral("done");
+ }
+ break;
+ }
+ ++pages;
+ QString note;
+ if (straighten) {
+ image = ScanProcess::straightenAndCrop(image, &note);
+ }
+ if (lineart) {
+ image = ScanProcess::blackAndWhite(image);
+ }
+ Q_EMIT pageScanned(image, dpi, note);
+ if (!feeder || m_cancel) {
+ outcome = m_cancel ? QStringLiteral("cancelled") : QStringLiteral("done");
+ break;
+ }
+ }
+ if (SANE_Handle h = handleOf(m_handle)) {
+ sane_cancel(h);
+ }
+ // After the scanner went away, a fresh handle next time.
+ if (outcome == QLatin1String("offline") || outcome == QLatin1String("failed")) {
+ closeDevice();
+ }
+ Q_EMIT finished(outcome, pages);
+}
+
+// One page, all its frames, as an image: grey or colour, 8 or 16 bits,
+// or 1-bit line art.
+QImage ScanWorker::readPage(QString *outcome)
+{
+ SANE_Handle h = handleOf(m_handle);
+ if (!h || m_cancel) {
+ *outcome = QStringLiteral("cancelled");
+ return {};
+ }
+ QImage result;
+ QByteArray channels[3];
+ SANE_Parameters p{};
+ for (;;) {
+ SANE_Status started = sane_start(h);
+ // Straight after a cancelled scan, airscan can still be closing the
+ // old job and turns the next one away as cancelled too; it takes a
+ // few seconds at most.
+ for (int i = 0; started == SANE_STATUS_CANCELLED && !m_cancel && i < 20; ++i) {
+ QThread::msleep(500);
+ started = sane_start(h);
+ }
+ if (started != SANE_STATUS_GOOD) {
+ *outcome = m_cancel ? QStringLiteral("cancelled") : outcomeOf(started);
+ return {};
+ }
+ if (sane_get_parameters(h, &p) != SANE_STATUS_GOOD || p.bytes_per_line <= 0) {
+ *outcome = QStringLiteral("failed");
+ return {};
+ }
+ QByteArray data;
+ if (p.lines > 0) {
+ data.reserve(qsizetype(p.bytes_per_line) * p.lines);
+ }
+ const qint64 expected = p.lines > 0 ? qint64(p.bytes_per_line) * p.lines : 0;
+ QByteArray chunk(256 * 1024, Qt::Uninitialized);
+ qint64 lastReported = 0;
+ for (;;) {
+ SANE_Int got = 0;
+ const SANE_Status status = sane_read(h, reinterpret_cast<SANE_Byte *>(chunk.data()), SANE_Int(chunk.size()), &got);
+ if (got > 0) {
+ data.append(chunk.constData(), got);
+ }
+ if (status == SANE_STATUS_EOF) {
+ break;
+ }
+ if (status != SANE_STATUS_GOOD || m_cancel) {
+ *outcome = m_cancel ? QStringLiteral("cancelled") : outcomeOf(status);
+ return {};
+ }
+ if (expected > 0 && data.size() - lastReported > expected / 100) {
+ lastReported = data.size();
+ Q_EMIT progress(qreal(data.size()) / expected);
+ }
+ }
+ const int lines = int(data.size() / p.bytes_per_line);
+ if (lines <= 0) {
+ *outcome = QStringLiteral("failed");
+ return {};
+ }
+ const int w = p.pixels_per_line;
+ if (p.format == SANE_FRAME_GRAY || p.format == SANE_FRAME_RGB) {
+ const bool rgb = p.format == SANE_FRAME_RGB;
+ result = QImage(w, lines, rgb ? QImage::Format_RGB888 : QImage::Format_Grayscale8);
+ for (int y = 0; y < lines; ++y) {
+ const uchar *in = reinterpret_cast<const uchar *>(data.constData()) + qsizetype(y) * p.bytes_per_line;
+ uchar *out = result.scanLine(y);
+ if (p.depth == 8) {
+ std::memcpy(out, in, size_t(w) * (rgb ? 3 : 1));
+ } else if (p.depth == 16) {
+ // Host byte order: the high byte of each sample.
+ const quint16 *samples = reinterpret_cast<const quint16 *>(in);
+ for (int i = 0; i < w * (rgb ? 3 : 1); ++i) {
+ out[i] = uchar(samples[i] >> 8);
+ }
+ } else if (p.depth == 1) {
+ // In SANE's line art a set bit is black.
+ const int samples = w * (rgb ? 3 : 1);
+ for (int i = 0; i < samples; ++i) {
+ out[i] = (in[i / 8] & (0x80 >> (i % 8))) ? 0 : 255;
+ }
+ }
+ }
+ break;
+ }
+ // Three-pass scanners send red, green and blue one after another.
+ const int c = p.format == SANE_FRAME_RED ? 0 : p.format == SANE_FRAME_GREEN ? 1 : 2;
+ channels[c] = data;
+ if (p.last_frame) {
+ result = QImage(w, lines, QImage::Format_RGB888);
+ for (int y = 0; y < lines; ++y) {
+ uchar *out = result.scanLine(y);
+ for (int x = 0; x < w; ++x) {
+ for (int k = 0; k < 3; ++k) {
+ const qsizetype at = qsizetype(y) * p.bytes_per_line + (p.depth == 16 ? x * 2 + 1 : x);
+ out[x * 3 + k] = at < channels[k].size() ? uchar(channels[k].at(at)) : 255;
+ }
+ }
+ }
+ break;
+ }
+ }
+ *outcome = QStringLiteral("done");
+ return result;
+}
diff --git a/packages/wildos-capture/src/scanworker.h b/packages/wildos-capture/src/scanworker.h
new file mode 100644
index 0000000..a6a4ae0
--- /dev/null
+++ b/packages/wildos-capture/src/scanworker.h
@@ -0,0 +1,58 @@
+#pragma once
+
+#include "scanner.h"
+
+#include <QImage>
+#include <QObject>
+#include <QVariantMap>
+
+#include <atomic>
+
+// Every SANE call, on the Scan tab's own thread. SANE is not made for
+// calls from several threads at once, apart from sane_cancel, which the
+// window may call at any time to stop a page part way.
+class ScanWorker : public QObject
+{
+ Q_OBJECT
+
+public:
+ ScanWorker();
+ ~ScanWorker() override;
+
+ // From the window's thread, while a scan runs.
+ void cancelNow();
+
+public Q_SLOTS:
+ void start();
+ void listDevices();
+ void open(const QString &name);
+ // { device, source, mode, dpi, widthMm, heightMm, feeder, straighten,
+ // lineart }: `lineart` asks for black and white made here from grey,
+ // for scanners without a mode of their own for it.
+ void scan(const QVariantMap &settings);
+ void stop();
+
+Q_SIGNALS:
+ void devicesFound(const QVariantList &devices);
+ void opened(const QString &name, const ScannerCaps &caps);
+ void openFailed(const QString &name, const QString &outcome);
+ void pageStarted(int page);
+ void progress(qreal fraction);
+ void pageScanned(const QImage &image, int dpi, const QString &note);
+ // done, cancelled, busy, offline, empty, jammed, cover or failed.
+ void finished(const QString &outcome, int pages);
+
+private:
+ bool ensureOpen(const QString &name, QString *outcome);
+ void closeDevice();
+ ScannerCaps readCaps();
+ int optionIndex(const char *name) const;
+ bool setString(const char *name, const QString &value);
+ bool setNumber(const char *name, double value);
+ QImage readPage(QString *outcome);
+
+ bool m_initialised = false;
+ QString m_name;
+ std::atomic<void *> m_handle{nullptr};
+ std::atomic<bool> m_cancel{false};
+};
diff --git a/packages/wildos-desktop-view/debian/changelog b/packages/wildos-desktop-view/debian/changelog
index 352b511..8099549 100644
--- a/packages/wildos-desktop-view/debian/changelog
+++ b/packages/wildos-desktop-view/debian/changelog
@@ -1,3 +1,18 @@
+wildos-desktop-view (0.1.8) trixie; urgency=medium
+
+ * New in the right-click menu offers a Write document and a Tables
+ spreadsheet, made as Word and Excel files like everything Write and
+ Tables save, instead of LibreOffice's Writer and Calc names and formats.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 16:20:00 +0000
+
+wildos-desktop-view (0.1.7) trixie; urgency=medium
+
+ * Renaming on the desktop has the right-click menu with Cut, Copy,
+ Paste and Select all. The rename stays open while the menu is up.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 08:54:22 +0000
+
wildos-desktop-view (0.1.6) trixie; urgency=medium
* Renaming an icon works like Explorer: the arrow keys move within the
diff --git a/packages/wildos-desktop-view/debian/control b/packages/wildos-desktop-view/debian/control
index 6e768da..21a707a 100644
--- a/packages/wildos-desktop-view/debian/control
+++ b/packages/wildos-desktop-view/debian/control
@@ -20,7 +20,7 @@ Architecture: any
Depends:
${shlibs:Depends},
${misc:Depends},
- wildos-ui,
+ wildos-ui (>= 0.1.11),
plasma-workspace (>= 4:6.3),
kio6,
qml6-module-qtquick,
diff --git a/packages/wildos-desktop-view/qml/RenameField.qml b/packages/wildos-desktop-view/qml/RenameField.qml
index 8640e90..94167ac 100644
--- a/packages/wildos-desktop-view/qml/RenameField.qml
+++ b/packages/wildos-desktop-view/qml/RenameField.qml
@@ -77,8 +77,17 @@ Rectangle {
// Characters a name cannot hold are refused as they are typed.
if (event.text === "/") {
event.accepted = true;
+ } else if (nameMenu.isMenuKey(event)) {
+ nameMenu.openAtCaret();
+ event.accepted = true;
}
}
- onActiveFocusChanged: if (!activeFocus) field.finish(true)
+ // The text menu holds focus while it is open; the rename is not over.
+ onActiveFocusChanged: if (!activeFocus && !nameMenu.opened) field.finish(true)
+
+ UI.TextMenu {
+ id: nameMenu
+ onFocusLeft: field.finish(true)
+ }
}
}
diff --git a/packages/wildos-desktop-view/src/newitems.cpp b/packages/wildos-desktop-view/src/newitems.cpp
index 919cd2c..006f8eb 100644
--- a/packages/wildos-desktop-view/src/newitems.cpp
+++ b/packages/wildos-desktop-view/src/newitems.cpp
@@ -67,8 +67,8 @@ const QStringList &commonNouns()
return nouns;
}
-// "Text document" makes "New text document"; "Writer document" keeps its
-// capital and makes "New Writer document", as Windows names new items.
+// "Text document" makes "New text document"; "Write document" keeps its
+// capital and makes "New Write document", as Windows names new items.
QString newBase(const QString &text)
{
const QString first = text.section(QLatin1Char(' '), 0, 0);
@@ -159,10 +159,18 @@ QList<Template> templates()
};
if (hasService({QStringLiteral("libreoffice-writer"), QStringLiteral("org.libreoffice.LibreOffice.writer")})) {
- builtIn(QStringLiteral("writer"), QStringLiteral("Writer document"), QStringLiteral("application/vnd.oasis.opendocument.text"), QStringLiteral(".odt"));
+ // Write and Tables save as Word and Excel files, so new ones start
+ // that way too; an empty file opens as a new document of its kind.
+ // LibreOffice's own OpenDocument templates are left out, or they
+ // would show beside these under LibreOffice's names.
+ builtIn(QStringLiteral("writer"), QStringLiteral("Write document"),
+ QStringLiteral("application/vnd.openxmlformats-officedocument.wordprocessingml.document"), QStringLiteral(".docx"));
+ installed.remove(QStringLiteral("application/vnd.oasis.opendocument.text"));
}
if (hasService({QStringLiteral("libreoffice-calc"), QStringLiteral("org.libreoffice.LibreOffice.calc")})) {
- builtIn(QStringLiteral("calc"), QStringLiteral("Calc spreadsheet"), QStringLiteral("application/vnd.oasis.opendocument.spreadsheet"), QStringLiteral(".ods"));
+ builtIn(QStringLiteral("calc"), QStringLiteral("Tables spreadsheet"),
+ QStringLiteral("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"), QStringLiteral(".xlsx"));
+ installed.remove(QStringLiteral("application/vnd.oasis.opendocument.spreadsheet"));
}
if (hasService({QStringLiteral("libreoffice-impress"), QStringLiteral("org.libreoffice.LibreOffice.impress")})) {
builtIn(QStringLiteral("impress"), QStringLiteral("Impress presentation"), QStringLiteral("application/vnd.oasis.opendocument.presentation"), QStringLiteral(".odp"));
diff --git a/packages/wildos-desktop/debian/changelog b/packages/wildos-desktop/debian/changelog
index b78a3e8..c81eb45 100644
--- a/packages/wildos-desktop/debian/changelog
+++ b/packages/wildos-desktop/debian/changelog
@@ -1,3 +1,36 @@
+wildos-desktop (0.1.18) trixie; urgency=medium
+
+ * The fingerprint keeps working after a restart again: asking for the
+ password after a restart or every so many hours is off unless you
+ switch it on in Advanced protection (Strict and Maximum switch it on).
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 16:00:00 +0000
+
+wildos-desktop (0.1.17) trixie; urgency=medium
+
+ * With Advanced protection's "Fingerprint needs your password
+ sometimes" on, as it is unless switched off, the fingerprint works
+ only once the password has been typed since the last restart, and
+ only for 48 hours after that, or the time chosen.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 14:56:10 +0000
+
+wildos-desktop (0.1.16) trixie; urgency=medium
+
+ * sudo asks for a password or fingerprint in one go, with no empty
+ password needed first.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 15:30:00 +0000
+
+wildos-desktop (0.1.15) trixie; urgency=medium
+
+ * Wild OS's own apps can be uninstalled one by one and put back from
+ the Store. Write and Tables are separate apps.
+ * LibreOffice's own Writer and Calc stay out of Start once Write or
+ Tables is removed.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 13:36:51 +0000
+
wildos-desktop (0.1.14) trixie; urgency=medium
* Depend on wildos-recovery: restore points, start-up recovery and
diff --git a/packages/wildos-desktop/debian/control b/packages/wildos-desktop/debian/control
index 1fb37ff..32dde39 100644
--- a/packages/wildos-desktop/debian/control
+++ b/packages/wildos-desktop/debian/control
@@ -15,33 +15,22 @@ Depends:
wildos-shell,
wildos-ui,
wildos-desktop-view,
- wildos-system-dialogs,
- wildos-settings,
- wildos-files,
+# fingerprint-turn reads the notes fingerprint-stamp writes.
+ wildos-system-dialogs (>= 0.1.14),
+ wildos-settings (>= 0.1.54),
+ wildos-files (>= 0.1.13),
wildos-store,
wildos-welcome,
wildos-appbridge,
wildos-winmode,
- wildos-terminal,
wildos-launch,
wildos-lighting,
wildos-setup,
wildos-portal,
wildos-taskmanager,
wildos-recovery,
- wildos-mail,
- wildos-office,
- wildos-remote,
- wildos-pdf,
- wildos-capture,
- wildos-notes,
- wildos-music,
- wildos-videos,
- wildos-archive,
- wildos-voice,
- wildos-backup,
wildos-report,
- wildos-overlays,
+ wildos-overlays (>= 0.1.3),
kde-plasma-desktop,
plasma-workspace,
kwin-wayland,
@@ -103,7 +92,24 @@ Conflicts:
desktop-base,
sddm-theme-debian-breeze,
xwaylandvideobridge,
+# Wild OS's own apps are recommended, not required: each can be uninstalled
+# from Settings or the Store without taking the desktop with it, and put back
+# from the Store. The image installs them all, and apt never
+# brings one back on its own once it has been removed.
Recommends:
+ wildos-mail,
+ wildos-write,
+ wildos-tables,
+ wildos-remote,
+ wildos-pdf,
+ wildos-capture,
+ wildos-notes,
+ wildos-music,
+ wildos-videos,
+ wildos-archive,
+ wildos-voice,
+ wildos-backup,
+ wildos-terminal,
dolphin,
kwrite,
okular,
diff --git a/packages/wildos-desktop/debian/install b/packages/wildos-desktop/debian/install
index dbeb4b6..0e34d7d 100644
--- a/packages/wildos-desktop/debian/install
+++ b/packages/wildos-desktop/debian/install
@@ -2,6 +2,7 @@ files/10-wildos.conf etc/sddm.conf.d/
files/pam-kde etc/pam.d/
files/pam-kde-fingerprint etc/pam.d/
files/pam-configs/wildos-fingerprint usr/share/pam-configs/
+files/pam-configs/wildos-fingerprint-stamp usr/share/pam-configs/
files/fingerprint-turn usr/libexec/wildos/
files/wildos-app-names usr/libexec/wildos/
files/wildos-strings usr/libexec/wildos/
diff --git a/packages/wildos-desktop/debian/prerm b/packages/wildos-desktop/debian/prerm
index 5bac3e3..1bac867 100644
--- a/packages/wildos-desktop/debian/prerm
+++ b/packages/wildos-desktop/debian/prerm
@@ -4,7 +4,7 @@ set -e
# Takes fingerprint sign-in out of common-auth while its PAM profile and
# fingerprint-turn are still on disk.
if [ "$1" = "remove" ] && command -v pam-auth-update >/dev/null; then
- pam-auth-update --package --remove wildos-fingerprint
+ pam-auth-update --package --remove wildos-fingerprint wildos-fingerprint-stamp
fi
#DEBHELPER#
diff --git a/packages/wildos-desktop/files/fingerprint-turn b/packages/wildos-desktop/files/fingerprint-turn
index 83b4da4..9935bc1 100644
--- a/packages/wildos-desktop/files/fingerprint-turn
+++ b/packages/wildos-desktop/files/fingerprint-turn
@@ -39,6 +39,22 @@ case "$PAM_USER" in
''|.|..|*/*) exit 1 ;;
esac
+# Settings > Privacy and security > Advanced protection: "Fingerprint needs
+# your password sometimes" (fingerprint_hours, off unless set; Strict and
+# Maximum set it).
+# The finger is turned down after every restart until the password has
+# been typed once, and again once that many hours have passed since.
+# fingerprint-stamp notes each password sign-in in /run, which a restart
+# empties, in seconds since start-up so changing the clock moves nothing.
+hours=$(sed -n 's/^fingerprint_hours=//p' /etc/wildos/advanced-protection 2>/dev/null | tail -n 1)
+case "$hours" in ''|*[!0-9]*) hours=0 ;; esac
+if [ "$hours" -gt 0 ]; then
+ typed=$(cat "/run/wildos/fingerprint/$PAM_USER" 2>/dev/null) || exit 1
+ case "$typed" in ''|*[!0-9]*) exit 1 ;; esac
+ now=$(cut -d. -f1 /proc/uptime)
+ [ "$now" -ge "$typed" ] && [ $((now - typed)) -lt $((hours * 3600)) ] || exit 1
+fi
+
# The lock screen runs this as the signed-in person, who can read neither
# the prints nor the password's state; pam_fprintd after it checks for an
# enrolled finger itself, and the account is already signed in.
diff --git a/packages/wildos-desktop/files/pam-configs/wildos-fingerprint b/packages/wildos-desktop/files/pam-configs/wildos-fingerprint
index f03a05d..17c5076 100644
--- a/packages/wildos-desktop/files/pam-configs/wildos-fingerprint
+++ b/packages/wildos-desktop/files/pam-configs/wildos-fingerprint
@@ -4,6 +4,7 @@ Priority: 400
Conflicts: fprintd
Auth-Type: Primary
Auth:
+ [success=2 ignore=ignore abort=die auth_err=die default=ignore] pam_wildos_fingerprint.so
[success=ok default=2] pam_exec.so quiet seteuid expose_authtok /usr/libexec/wildos/fingerprint-turn
[success=ok default=die] pam_fprintd.so max-tries=3 timeout=30
[success=end default=ignore] pam_faillock.so authsucc
diff --git a/packages/wildos-desktop/files/pam-configs/wildos-fingerprint-stamp b/packages/wildos-desktop/files/pam-configs/wildos-fingerprint-stamp
new file mode 100644
index 0000000..a8ff687
--- /dev/null
+++ b/packages/wildos-desktop/files/pam-configs/wildos-fingerprint-stamp
@@ -0,0 +1,6 @@
+Name: Note password sign-ins for fingerprint sign-in (Wild OS)
+Default: yes
+Priority: 0
+Auth-Type: Additional
+Auth:
+ optional pam_exec.so quiet seteuid expose_authtok /usr/libexec/wildos/fingerprint-stamp
diff --git a/packages/wildos-desktop/files/pam-kde b/packages/wildos-desktop/files/pam-kde
index 7c68cff..d5f933b 100644
--- a/packages/wildos-desktop/files/pam-kde
+++ b/packages/wildos-desktop/files/pam-kde
@@ -13,6 +13,10 @@ auth required pam_succeed_if.so user != root quiet_success
# nullok: the live session user has no password; installed accounts always
# do, because the installer refuses an empty one.
auth required pam_unix.so nullok try_first_pass
+# A password unlock lets the fingerprint back in for Advanced protection's
+# "Fingerprint needs your password sometimes". fingerprint-stamp checks
+# the password again itself, so a wrong one notes nothing.
+auth optional pam_exec.so quiet seteuid expose_authtok /usr/libexec/wildos/fingerprint-stamp
auth optional pam_kwallet5.so
@include common-account
diff --git a/packages/wildos-desktop/files/wildos-app-names b/packages/wildos-desktop/files/wildos-app-names
index a29e83c..74edb00 100644
--- a/packages/wildos-desktop/files/wildos-app-names
+++ b/packages/wildos-desktop/files/wildos-app-names
@@ -93,12 +93,20 @@ for f in /usr/share/wildos/launchers/*.desktop; do
cp "$f" "$DST/$id.desktop.new"
mv "$DST/$id.desktop.new" "$DST/$id.desktop"
done
-# With Write and Tables in place, LibreOffice's own start centre stays out of
+# With Write or Tables in place, LibreOffice's own start centre stays out of
# menus. Impress and the rest show up as themselves if installed from the Store.
-if [ -f /usr/share/wildos/launchers/libreoffice-writer.desktop ]; then
+if [ -f /usr/share/wildos/launchers/libreoffice-writer.desktop ] || [ -f /usr/share/wildos/launchers/libreoffice-calc.desktop ]; then
hide libreoffice-startcenter
hide libreoffice-xsltfilter
fi
+# Write and Tables are removed one at a time. Until apt takes away the
+# LibreOffice part a removed one used, its stock launcher would show up in
+# Start as "LibreOffice Calc" in place of the app someone just removed.
+if [ -d /usr/lib/libreoffice/share/extensions/wildos-office ]; then
+ for id in libreoffice-writer libreoffice-calc; do
+ [ -f "/usr/share/wildos/launchers/$id.desktop" ] || hide "$id"
+ done
+fi
rename org.kde.kcalc "Calculator" "Calculator"
rename org.kde.kwrite "Text editor" "Text editor"
rename org.kde.okular "Documents" "Document viewer"
diff --git a/packages/wildos-files/CMakeLists.txt b/packages/wildos-files/CMakeLists.txt
index ab6f99b..d310f1f 100644
--- a/packages/wildos-files/CMakeLists.txt
+++ b/packages/wildos-files/CMakeLists.txt
@@ -15,6 +15,8 @@ find_package(KF6WindowSystem REQUIRED)
find_package(KF6Purpose REQUIRED)
find_package(KF6Archive REQUIRED)
find_package(KF6FileMetaData REQUIRED)
+find_package(PkgConfig REQUIRED)
+pkg_check_modules(SECCOMP REQUIRED IMPORTED_TARGET libseccomp)
qt_standard_project_setup(REQUIRES 6.8)
@@ -45,6 +47,10 @@ qt_add_qml_module(wildos-files
src/filemeta.cpp src/filemeta.h
src/imageproviders.cpp src/imageproviders.h
src/previewsource.cpp src/previewsource.h
+ src/programs.cpp src/programs.h
+ src/protection.cpp src/protection.h
+ src/protectionops.cpp
+ src/safeboxplan.cpp src/safeboxplan.h
)
target_include_directories(wildos-files PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src)
@@ -56,6 +62,12 @@ target_link_libraries(wildos-files PRIVATE
KF6::Archive KF6::FileMetaData
)
+# The safe box: a small program of its own, so the box outlives the Files
+# window it was opened from.
+add_executable(wildos-safebox src/safebox/main.cpp src/safeboxplan.cpp src/programs.cpp)
+target_include_directories(wildos-safebox PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src)
+target_link_libraries(wildos-safebox PRIVATE Qt6::Core Qt6::DBus KF6::KIOCore KF6::Service PkgConfig::SECCOMP)
+
if(WILDOS_FILES_TESTS)
find_package(Qt6 REQUIRED COMPONENTS Test)
enable_testing()
@@ -65,7 +77,11 @@ if(WILDOS_FILES_TESTS)
add_test(NAME formatsafety COMMAND formatsafety-test)
endif()
-install(TARGETS wildos-files RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
+install(TARGETS wildos-files wildos-safebox RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
+install(PROGRAMS data/remove-details DESTINATION ${CMAKE_INSTALL_PREFIX}/libexec/wildos)
+# Advanced protection's rows for these two appear when their hooks exist;
+# Files itself reads the switches (src/protection.cpp).
+install(PROGRAMS data/advanced-protection/scrub_files data/advanced-protection/safebox DESTINATION lib/wildos/advanced-protection.d)
install(FILES data/org.wildos.files.desktop DESTINATION ${CMAKE_INSTALL_DATADIR}/applications)
install(FILES data/org.wildos.Files.service data/org.wildos.files.FileManager1.service DESTINATION ${CMAKE_INSTALL_DATADIR}/dbus-1/services)
install(FILES data/fm-shim-wildos-files.conf DESTINATION lib/systemd/user/fm-shim.service.d RENAME 50-wildos-files.conf)
diff --git a/packages/wildos-files/data/advanced-protection/safebox b/packages/wildos-files/data/advanced-protection/safebox
new file mode 100644
index 0000000..76f2537
--- /dev/null
+++ b/packages/wildos-files/data/advanced-protection/safebox
@@ -0,0 +1,10 @@
+#!/bin/sh
+# Advanced protection: Safe box (safebox). Run as root by
+# advanced-protection-apply with the new value, on or off. Files reads the
+# switch from /etc/wildos/advanced-protection and offers Open in safe box
+# only while it is on, so there is nothing system-wide to change here. This
+# file being here is what puts the row on the Settings page.
+case "${1:-}" in
+ on|off) exit 0 ;;
+ *) echo "usage: safebox on|off" >&2; exit 2 ;;
+esac
diff --git a/packages/wildos-files/data/advanced-protection/scrub_files b/packages/wildos-files/data/advanced-protection/scrub_files
new file mode 100644
index 0000000..5ec41df
--- /dev/null
+++ b/packages/wildos-files/data/advanced-protection/scrub_files
@@ -0,0 +1,10 @@
+#!/bin/sh
+# Advanced protection: Remove personal details from files (scrub_files).
+# Run as root by advanced-protection-apply with the new value, on or off.
+# There is nothing system-wide to change: Files reads the switch from
+# /etc/wildos/advanced-protection and shows or hides its menu entry at once.
+# This file being here is what puts the row on the Settings page.
+case "${1:-}" in
+ on|off) exit 0 ;;
+ *) echo "usage: scrub_files on|off" >&2; exit 2 ;;
+esac
diff --git a/packages/wildos-files/data/remove-details b/packages/wildos-files/data/remove-details
new file mode 100644
index 0000000..7b9de31
--- /dev/null
+++ b/packages/wildos-files/data/remove-details
@@ -0,0 +1,524 @@
+#!/usr/bin/python3 -I
+"""Saves a copy of a file without the personal details it carries.
+
+ remove-details [--location] [--device] [--authors] FILE...
+
+Each FILE gets a copy beside it named "NAME (no details).EXT"; the original
+is never changed. One JSON line per file goes to stdout:
+{"file", "copy", "error"}, with error empty on success. Files runs this for
+the "Remove personal details" menu entry, with the choices the person made
+in "Choose what is removed".
+
+Photos and MP4/MOV videos go through exiftool, PDFs through exiftool and
+then qpdf (exiftool alone appends its change and keeps the old details
+recoverable in the file; qpdf writes the file out again without the old
+revision). MP3, FLAC and Ogg audio go through mutagen. Word, Excel,
+PowerPoint and OpenDocument files are ZIP archives of XML, edited here, and
+the pictures inside them go through exiftool too. Every copy is read back
+and checked before it is kept.
+"""
+
+import argparse
+import json
+import os
+import re
+import shutil
+import subprocess
+import sys
+import tempfile
+import zipfile
+
+EXIFTOOL = "/usr/bin/exiftool"
+QPDF = "/usr/bin/qpdf"
+
+PHOTO = {"jpg", "jpeg", "jpe", "png", "heic", "heif", "avif", "webp", "tif", "tiff", "gif", "dng"}
+MOVIE = {"mp4", "m4v", "mov", "3gp", "3g2", "m4a"}
+AUDIO = {"mp3", "flac", "ogg", "oga", "opus"}
+OOXML = {"docx", "docm", "dotx", "dotm", "xlsx", "xlsm", "xltx", "xltm", "pptx", "pptm", "potx", "potm", "ppsx", "ppsm"}
+ODF = {"odt", "ott", "ods", "ots", "odp", "otp", "odg", "otg"}
+PDF = {"pdf"}
+
+# exiftool arguments for each choice. Tag names are scoped to their group
+# where the same name means something else elsewhere: PDF "Creator" is the
+# program that made the file, XMP dc:creator is the person.
+EXIF_ARGS = {
+ "location": [
+ "-gps:all=", "-gps*=", "-location*=", "-city=", "-state=", "-province-state=",
+ "-country*=", "-sub-location=", "-sublocation=", "-contentlocation*=",
+ "-xmp-drone-dji:all=",
+ ],
+ "device": [
+ "-make=", "-model=", "-*serial*=", "-lens*=", "-software=", "-hostcomputer=",
+ "-makernotes:all=", "-uniquecameramodel=", "-localizedcameramodel=",
+ "-xmp-xmp:creatortool=", "-xmp-xmpmm:history=", "-xmp-aux:all=", "-android*=",
+ "-quicktime:encoder=", "-firmware*=", "-imageuniqueid=", "-png:source=",
+ "-pdf:creator=", "-pdf:producer=", "-xmp-pdf:producer=",
+ ],
+ "authors": [
+ "-artist=", "-author=", "-xpauthor=", "-ownername=", "-cameraownername=",
+ "-copyright=", "-copyrightnotice=", "-rights=", "-by-line=", "-by-linetitle=",
+ "-writer-editor=", "-credit=", "-contact=", "-xmp-dc:creator=", "-xmp-dc:contributor=",
+ "-xmp-photoshop:authorsposition=", "-xmp-photoshop:captionwriter=",
+ "-xmp-iptccore:creator*=", "-xmp-xmprights:owner=", "-xmp-plus:all=",
+ "-xmp-xmpdm:artist=", "-xmp-xmpdm:composer=", "-xmp-xmpdm:engineer=", "-xmp-xmpdm:director=",
+ "-quicktime:albumartist=", "-quicktime:composer=", "-quicktime:director=",
+ "-quicktime:producer=", "-quicktime:performer=", "-quicktime:encodedby=",
+ "-lastmodifiedby=", "-pdf:company=", "-pdf:manager=",
+ ],
+}
+
+# What must not be left after the copy is written, by tag name as exiftool
+# reports it with -G0:1. Groups exiftool computes itself are not in the file.
+CHECK = {
+ "location": re.compile(r"^(GPS|Location|City$|State$|Province|Country|Sub-?[Ll]ocation|ContentLocation)"),
+ "device": re.compile(r"^(Make|Model|.*Serial.*|Lens.*|Software|HostComputer|UniqueCameraModel|"
+ r"LocalizedCameraModel|CreatorTool|History.*|Android.*|Encoder|Firmware.*|ImageUniqueID)$"),
+ "authors": re.compile(r"^(Artist|Author|XPAuthor|OwnerName|CameraOwnerName|Copyright|CopyrightNotice|Rights|"
+ r"By-line|By-lineTitle|Writer-Editor|Credit|Contact|Contributor|AuthorsPosition|"
+ r"CaptionWriter|Creator(Address|City|Country|PostalCode|Region|WorkEmail|WorkTelephone|WorkURL|ContactInfo).*|"
+ r"Owner|AlbumArtist|Composer|Director|Performer|EncodedBy|LastModifiedBy|Engineer|Company|Manager)$"),
+}
+CHECK_GROUP_SKIP = re.compile(r"^(File|System|Composite|ExifTool):")
+
+
+class Refused(Exception):
+ """A plain sentence for the person, shown as it is."""
+
+
+def copy_name(path):
+ folder, name = os.path.split(path)
+ stem, dot, ext = name.rpartition(".")
+ if not dot or not stem:
+ stem, ext = name, ""
+ suffix = "." + ext if ext else ""
+ # Numbered the way Files numbers any name that is taken.
+ candidate = os.path.join(folder, f"{stem} (no details){suffix}")
+ n = 2
+ while os.path.lexists(candidate):
+ candidate = os.path.join(folder, f"{stem} (no details) ({n}){suffix}")
+ n += 1
+ return candidate
+
+
+def run(args, what):
+ try:
+ done = subprocess.run(args, capture_output=True, text=True, timeout=600)
+ except FileNotFoundError:
+ raise Refused(f"Wild OS is missing {what}, which this needs.")
+ except subprocess.TimeoutExpired:
+ raise Refused("This file took too long to clean.")
+ return done
+
+
+def exif_clean(src, dest, choices, kind):
+ args = [EXIFTOOL, "-q", "-q", "-m", "-P", "-o", dest]
+ for choice in choices:
+ args += EXIF_ARGS[choice]
+ args.append(src)
+ done = run(args, "exiftool")
+ if done.returncode != 0 or not os.path.exists(dest):
+ message = done.stderr.strip()
+ if "encrypt" in message.lower() or "password" in message.lower():
+ raise Refused("This file is password protected, so its details can't be changed.")
+ raise Refused(f"The details in this {kind} couldn't be changed. It may be damaged.")
+
+
+def exif_left(path, choices):
+ done = run([EXIFTOOL, "-j", "-G0:1", "-a", "-s", "-m", path], "exiftool")
+ if done.returncode != 0:
+ return []
+ try:
+ tags = json.loads(done.stdout)[0]
+ except (ValueError, IndexError):
+ return []
+ left = []
+ for key, value in tags.items():
+ group, _, name = key.rpartition(":")
+ if CHECK_GROUP_SKIP.match(key) or value in ("", None):
+ continue
+ family0 = group.split(":")[0]
+ for choice in choices:
+ if CHECK[choice].match(name) or (choice == "device" and family0 == "MakerNotes"):
+ left.append(choice)
+ return sorted(set(left))
+
+
+def clean_photo(src, dest, choices):
+ exif_clean(src, dest, choices, "picture")
+ return exif_left(dest, choices)
+
+
+def clean_movie(src, dest, choices):
+ exif_clean(src, dest, choices, "video")
+ return exif_left(dest, choices)
+
+
+# PDF comments name their writer in /T; exiftool does not reach them. Form
+# fields also have /T, as their name, and are left alone.
+def pdf_comment_authors(pdf):
+ done = run([QPDF, "--json=2", "--json-key=qpdf", "--json-stream-data=none", pdf], "qpdf")
+ if done.returncode not in (0, 3):
+ raise Refused("This PDF couldn't be read. It may be damaged.")
+ try:
+ objects = json.loads(done.stdout)["qpdf"][1]
+ except (ValueError, KeyError, IndexError):
+ raise Refused("This PDF couldn't be read. It may be damaged.")
+ changed = {}
+ for key, obj in objects.items():
+ value = obj.get("value") if isinstance(obj, dict) else None
+ if not isinstance(value, dict) or "/T" not in value or value["/T"] == "u:Author":
+ continue
+ annot = value.get("/Type") == "/Annot" or ("/Subtype" in value and "/Rect" in value)
+ if annot and value.get("/Subtype") != "/Widget" and "/FT" not in value:
+ value = dict(value)
+ value["/T"] = "u:Author"
+ changed[key] = {"value": value}
+ return changed
+
+
+def clean_pdf(src, dest, choices):
+ work = tempfile.mkdtemp(prefix="remove-details-")
+ try:
+ step = os.path.join(work, "a.pdf")
+ exif_clean(src, step, choices, "PDF")
+ args = [QPDF, "--object-streams=preserve", "--remove-unreferenced-resources=no"]
+ if "authors" in choices:
+ changed = pdf_comment_authors(step)
+ if changed:
+ update = os.path.join(work, "update.json")
+ with open(update, "w") as f:
+ json.dump({"qpdf": [{"jsonversion": 2, "pushedinheritedpageresources": False, "calledgetallpages": False, "maxobjectid": 0}, changed]}, f)
+ args.append(f"--update-from-json={update}")
+ # Writing the file out again keeps only the newest revision, so the
+ # details exiftool replaced are no longer anywhere in it.
+ done = run(args + [step, dest], "qpdf")
+ if done.returncode not in (0, 3) or not os.path.exists(dest):
+ raise Refused("This PDF couldn't be written again. It may be damaged.")
+ left = exif_left(dest, choices)
+ if "authors" in choices and pdf_comment_authors(dest):
+ left.append("authors")
+ return left
+ finally:
+ shutil.rmtree(work, ignore_errors=True)
+
+
+# ID3 frames and Vorbis comment fields for each choice.
+ID3_FRAMES = {
+ "location": [],
+ "device": ["TSSE"],
+ "authors": ["TPE1", "TPE2", "TPE3", "TPE4", "TCOM", "TEXT", "TOLY", "TOPE", "TENC", "TOWN", "TCOP", "TIPL", "TMCL", "IPLS", "WOAR"],
+}
+ID3_TXXX = {
+ "location": re.compile(r"^(location|gps.*|city|country)$", re.I),
+ "device": re.compile(r"^(encoder.*|software|device|make|model)$", re.I),
+ "authors": re.compile(r"^(artists?|album ?artist|author|composer|lyricist|performer|conductor|arranger|"
+ r"engineer|producer|mixer|copyright|owner|encoded ?by|contact)$", re.I),
+}
+VORBIS = {
+ "location": re.compile(r"^(LOCATION|GPS.*|CITY|COUNTRY)$"),
+ "device": re.compile(r"^(ENCODER.*|SOFTWARE|DEVICE|MAKE|MODEL)$"),
+ "authors": re.compile(r"^(ARTISTS?|ALBUMARTIST|ALBUM ARTIST|AUTHOR|COMPOSER|LYRICIST|PERFORMER|CONDUCTOR|"
+ r"ARRANGER|ENGINEER|PRODUCER|MIXER|COPYRIGHT|OWNER|ENCODEDBY|ENCODED-BY|CONTACT|ORGANIZATION)$"),
+}
+
+
+def clean_audio(src, dest, choices):
+ try:
+ import mutagen
+ from mutagen.id3 import ID3, ID3NoHeaderError
+ except ImportError:
+ raise Refused("Wild OS is missing mutagen, which this needs.")
+ shutil.copyfile(src, dest)
+ ext = dest.rsplit(".", 1)[-1].lower()
+ try:
+ if ext == "mp3":
+ try:
+ tags = ID3(dest)
+ except ID3NoHeaderError:
+ tags = None
+ if tags is not None:
+ for key in list(tags.keys()):
+ frame = key.split(":")[0]
+ for choice in choices:
+ if frame in ID3_FRAMES[choice] or (frame == "TXXX" and ID3_TXXX[choice].match(tags[key].desc or "")):
+ del tags[key]
+ break
+ # ID3v1 at the end of the file has its own artist field;
+ # v1=0 drops it (the v2 tag above keeps the title).
+ tags.save(dest, v1=0)
+ return _audio_left(dest, choices)
+ audio = mutagen.File(dest)
+ if audio is None or audio.tags is None:
+ return []
+ for key in list(audio.tags.keys()):
+ upper = key.upper()
+ if any(VORBIS[c].match(upper) for c in choices):
+ del audio.tags[key]
+ # Vorbis comments open with the encoder's name, which can't be left
+ # out, only emptied.
+ if "device" in choices and getattr(audio.tags, "vendor", ""):
+ audio.tags.vendor = ""
+ audio.save()
+ return _audio_left(dest, choices)
+ except mutagen.MutagenError:
+ os.unlink(dest)
+ raise Refused("The details in this audio file couldn't be changed. It may be damaged.")
+
+
+def _has_id3v1(path):
+ with open(path, "rb") as f:
+ f.seek(0, os.SEEK_END)
+ if f.tell() < 128:
+ return False
+ f.seek(-128, os.SEEK_END)
+ return f.read(3) == b"TAG"
+
+
+def _audio_left(path, choices):
+ import mutagen
+ left = set()
+ audio = mutagen.File(path)
+ if audio is None or audio.tags is None:
+ return []
+ for key in audio.tags.keys():
+ if path.lower().endswith(".mp3"):
+ frame = key.split(":")[0]
+ desc = getattr(audio.tags[key], "desc", "") or ""
+ for c in choices:
+ if frame in ID3_FRAMES[c] or (frame == "TXXX" and ID3_TXXX[c].match(desc)):
+ left.add(c)
+ else:
+ for c in choices:
+ if VORBIS[c].match(key.upper()):
+ left.add(c)
+ if "device" in choices and getattr(audio.tags, "vendor", ""):
+ left.add("device")
+ if path.lower().endswith(".mp3") and "authors" in choices and _has_id3v1(path):
+ left.add("authors")
+ return sorted(left)
+
+
+# Office documents. Elements are matched with any namespace prefix, as the
+# prefix is the writer's choice; the files are edited as text so every other
+# byte, prefixes and markup compatibility declarations included, stays as it
+# was. Names that the format requires are replaced with "Author", as Word's
+# own Document Inspector does; optional ones are removed.
+def _drop_elements(xml, names):
+ for name in names:
+ xml = re.sub(rf"<((?:[\w.-]+:)?{name})(?:\s[^>]*)?/>", "", xml)
+ xml = re.sub(rf"<((?:[\w.-]+:)?{name})(?:\s[^>]*)?>.*?</\1\s*>", "", xml, flags=re.S)
+ return xml
+
+
+def _set_text(xml, names, text):
+ for name in names:
+ xml = re.sub(rf"(<((?:[\w.-]+:)?{name})(?:\s[^>]*)?>).*?(</\2\s*>)", rf"\g<1>{text}\g<3>", xml, flags=re.S)
+ return xml
+
+
+def _set_attrs(xml, names, text):
+ for name in names:
+ xml = re.sub(rf'(\s(?:[\w.-]+:)?{name}=)("[^"]*"|\'[^\']*\')', rf'\g<1>"{text}"', xml)
+ return xml
+
+
+def _ooxml_part(name, xml, choices):
+ if "authors" in choices:
+ if name == "docProps/core.xml":
+ xml = _drop_elements(xml, ["creator", "lastModifiedBy"])
+ elif name == "docProps/app.xml":
+ xml = _drop_elements(xml, ["Company", "Manager"])
+ elif name.endswith("people.xml"):
+ xml = _set_attrs(xml, ["author"], "Author")
+ xml = _drop_elements(xml, ["presenceInfo"])
+ elif re.match(r"xl/persons/.*\.xml$", name):
+ xml = _set_attrs(xml, ["displayName"], "Author")
+ xml = _set_attrs(xml, ["userId"], "")
+ xml = _set_attrs(xml, ["providerId"], "None")
+ elif re.match(r"xl/comments\d*\.xml$", name):
+ xml = _set_text(xml, ["author"], "Author")
+ elif name in ("ppt/commentAuthors.xml", "ppt/authors.xml"):
+ xml = _set_attrs(xml, ["name"], "Author")
+ xml = _set_attrs(xml, ["initials"], "A")
+ xml = _set_attrs(xml, ["userId"], "")
+ xml = _set_attrs(xml, ["providerId"], "None")
+ elif re.match(r"(word|xl|ppt)/.*\.xml$", name):
+ # Tracked changes and comments carry w:author and w:initials.
+ xml = _set_attrs(xml, ["author"], "Author")
+ xml = _set_attrs(xml, ["initials"], "A")
+ if "device" in choices and name == "docProps/app.xml":
+ xml = _drop_elements(xml, ["Application", "AppVersion"])
+ return xml
+
+
+def _odf_part(name, xml, choices):
+ if "authors" in choices:
+ if name == "meta.xml":
+ xml = _drop_elements(xml, ["initial-creator", "creator", "printed-by"])
+ elif name in ("content.xml", "styles.xml"):
+ # Comments and tracked changes name their writer in dc:creator.
+ xml = _set_text(xml, ["creator"], "Author")
+ xml = _set_text(xml, ["creator-initials"], "A")
+ xml = _set_attrs(xml, ["sender-initials"], "A")
+ if "device" in choices:
+ if name == "meta.xml":
+ xml = _drop_elements(xml, ["generator"])
+ elif name == "settings.xml":
+ xml = re.sub(r'(<(?:[\w.-]+:)?config-item\s[^>]*name="(?:PrinterName|PrinterSetup|PrinterPaperFromSetup)"[^>]*>).*?(</(?:[\w.-]+:)?config-item>)',
+ r"\g<1>\g<2>", xml, flags=re.S)
+ return xml
+
+
+def _office_left(names_xml, choices, odf):
+ left = set()
+ for name, xml in names_xml.items():
+ if odf:
+ if "authors" in choices:
+ if name == "meta.xml" and re.search(r"<(?:[\w.-]+:)?(initial-creator|creator|printed-by)\b", xml):
+ left.add("authors")
+ if name in ("content.xml", "styles.xml") and re.search(r"<((?:[\w.-]+:)?creator)(?:\s[^>]*)?>(?!Author</)[^<]+</\1", xml):
+ left.add("authors")
+ if "device" in choices and name == "meta.xml" and re.search(r"<(?:[\w.-]+:)?generator\b", xml):
+ left.add("device")
+ else:
+ if "authors" in choices:
+ if name == "docProps/core.xml" and re.search(r"<(?:[\w.-]+:)?(creator|lastModifiedBy)\b", xml):
+ left.add("authors")
+ if re.match(r"(word|xl|ppt)/.*\.xml$", name) and re.search(r'\s(?:[\w.-]+:)?author="(?!Author")[^"]+"', xml):
+ left.add("authors")
+ if "device" in choices and name == "docProps/app.xml" and re.search(r"<(?:[\w.-]+:)?(Application|AppVersion)\b", xml):
+ left.add("device")
+ return left
+
+
+MEDIA = re.compile(r"^(word/media|xl/media|ppt/media|docProps|Pictures|Thumbnails)/[^/]+\.(jpe?g|png|tiff?|heic|webp|gif)$", re.I)
+
+
+def clean_office(src, dest, choices, odf):
+ if not zipfile.is_zipfile(src):
+ raise Refused("This document is password protected or isn't in a format Wild OS can change.")
+ work = tempfile.mkdtemp(prefix="remove-details-")
+ left = set()
+ checked = {}
+ try:
+ with zipfile.ZipFile(src) as zin, zipfile.ZipFile(dest, "w") as zout:
+ infos = zin.infolist()
+ # OpenDocument needs its mimetype entry first and stored as it is.
+ infos.sort(key=lambda i: 0 if i.filename == "mimetype" else 1)
+ for info in infos:
+ data = zin.read(info.filename)
+ if info.filename.endswith(".xml") or info.filename.endswith(".rels"):
+ try:
+ text = data.decode("utf-8")
+ except UnicodeDecodeError:
+ text = None
+ if text is not None:
+ new = _odf_part(info.filename, text, choices) if odf else _ooxml_part(info.filename, text, choices)
+ checked[info.filename] = new
+ data = new.encode("utf-8")
+ elif MEDIA.match(info.filename) and ("location" in choices or "device" in choices or "authors" in choices):
+ ext = info.filename.rsplit(".", 1)[-1]
+ a = os.path.join(work, "in." + ext)
+ b = os.path.join(work, "out." + ext)
+ with open(a, "wb") as f:
+ f.write(data)
+ if os.path.exists(b):
+ os.unlink(b)
+ exif_clean(a, b, choices, "document's pictures")
+ left.update(exif_left(b, choices))
+ with open(b, "rb") as f:
+ data = f.read()
+ out = zipfile.ZipInfo(info.filename, date_time=info.date_time)
+ out.compress_type = info.compress_type
+ out.external_attr = info.external_attr
+ out.create_system = info.create_system
+ zout.writestr(out, data)
+ left.update(_office_left(checked, choices, odf))
+ return sorted(left)
+ finally:
+ shutil.rmtree(work, ignore_errors=True)
+
+
+def kind_of(path):
+ ext = path.rsplit(".", 1)[-1].lower() if "." in os.path.basename(path) else ""
+ for kind, exts in (("photo", PHOTO), ("movie", MOVIE), ("audio", AUDIO), ("pdf", PDF), ("ooxml", OOXML), ("odf", ODF)):
+ if ext in exts:
+ return kind
+ return None
+
+
+NAMES = {"location": "location", "device": "device details", "authors": "author names"}
+
+
+def clean(path, choices):
+ if not os.path.isfile(path):
+ raise Refused("This file is no longer there.")
+ kind = kind_of(path)
+ if kind is None:
+ raise Refused("Wild OS can't remove details from this kind of file.")
+ dest = copy_name(path)
+ folder = os.path.dirname(dest) or "."
+ if not os.access(folder, os.W_OK):
+ raise Refused("A copy can't be saved in this folder. Copy the file somewhere in Home and try again.")
+ # Written under a hidden name first, so a half-written copy never shows
+ # under the final one.
+ fd, temp = tempfile.mkstemp(prefix=".no-details-", suffix=os.path.splitext(dest)[1], dir=folder)
+ os.close(fd)
+ os.unlink(temp)
+ try:
+ if kind == "photo":
+ left = clean_photo(path, temp, choices)
+ elif kind == "movie":
+ left = clean_movie(path, temp, choices)
+ elif kind == "audio":
+ left = clean_audio(path, temp, choices)
+ elif kind == "pdf":
+ left = clean_pdf(path, temp, choices)
+ else:
+ left = clean_office(path, temp, choices, kind == "odf")
+ if left:
+ raise Refused("Some " + " and ".join(NAMES[c] for c in left) + " couldn't be removed, so no copy was kept.")
+ os.chmod(temp, os.stat(path).st_mode & 0o777)
+ # A name taken meanwhile is not overwritten.
+ os.link(temp, dest)
+ os.unlink(temp)
+ return dest
+ except BaseException:
+ if os.path.lexists(temp):
+ os.unlink(temp)
+ raise
+
+
+def main():
+ parser = argparse.ArgumentParser(description="Save copies of files without personal details.")
+ parser.add_argument("--location", action="store_true")
+ parser.add_argument("--device", action="store_true")
+ parser.add_argument("--authors", action="store_true")
+ parser.add_argument("--can", action="store_true", help="only say, for each file, whether it is a kind this can clean")
+ parser.add_argument("files", nargs="+")
+ args = parser.parse_args()
+ if args.can:
+ for path in args.files:
+ print(json.dumps({"file": path, "can": kind_of(path) is not None}))
+ return 0
+ choices = [c for c in ("location", "device", "authors") if getattr(args, c)]
+ if not choices:
+ print("Choose at least one kind of detail to remove.", file=sys.stderr)
+ return 2
+ failed = 0
+ for path in args.files:
+ result = {"file": path, "copy": "", "error": ""}
+ try:
+ result["copy"] = clean(os.path.abspath(path), choices)
+ except Refused as e:
+ result["error"] = str(e)
+ failed += 1
+ except OSError:
+ result["error"] = "A copy couldn't be saved here. The drive may be full or read-only."
+ failed += 1
+ print(json.dumps(result), flush=True)
+ return 1 if failed else 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/packages/wildos-files/debian/changelog b/packages/wildos-files/debian/changelog
index 903a83f..c531ea0 100644
--- a/packages/wildos-files/debian/changelog
+++ b/packages/wildos-files/debian/changelog
@@ -1,3 +1,33 @@
+wildos-files (0.1.14) trixie; urgency=medium
+
+ * New in the right-click menu offers a Write document and a Tables
+ spreadsheet, made as Word and Excel files like everything Write and
+ Tables save, instead of LibreOffice's Writer and Calc names and formats.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 16:20:00 +0000
+
+wildos-files (0.1.13) trixie; urgency=medium
+
+ * The format window leaves "Encrypt this drive" out when
+ Password-locked USB sticks is off in Advanced protection.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 14:56:10 +0000
+
+wildos-files (0.1.12) trixie; urgency=medium
+
+ * The password box for an encrypted drive takes only what is typed:
+ nothing can be pasted into it.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 10:30:00 +0000
+
+wildos-files (0.1.11) trixie; urgency=medium
+
+ * The address bar and renaming have the right-click menu with Cut,
+ Copy, Paste and Select all, and the preview of a text file has
+ Copy and Select all. Renaming stays open while the menu is up.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 08:54:22 +0000
+
wildos-files (0.1.10) trixie; urgency=medium
* A USB stick, SD card or external drive with nothing on it, new or
diff --git a/packages/wildos-files/debian/control b/packages/wildos-files/debian/control
index 7b54b13..88b7a38 100644
--- a/packages/wildos-files/debian/control
+++ b/packages/wildos-files/debian/control
@@ -17,6 +17,8 @@ Build-Depends:
libkf6purpose-dev,
libkf6archive-dev,
libkf6filemetadata-dev,
+ libseccomp-dev,
+ pkgconf,
qml6-module-qtmultimedia,
qml6-module-qtquick-pdf,
Standards-Version: 4.7.0
@@ -27,12 +29,16 @@ Architecture: any
Depends:
${shlibs:Depends},
${misc:Depends},
+ bubblewrap,
dosfstools,
e2fsprogs,
exfatprogs,
fonts-jetbrains-mono,
kio6,
+ libimage-exiftool-perl,
ntfs-3g,
+ python3,
+ python3-mutagen,
qml6-module-qtcore,
qml6-module-qtmultimedia,
qml6-module-qtquick,
@@ -45,8 +51,9 @@ Depends:
qml6-module-qtquick-window,
qt6-image-formats-plugins,
qt6-svg-plugins,
+ qpdf,
udisks2,
- wildos-ui,
+ wildos-ui (>= 0.1.12),
Recommends:
kio-extras,
xdg-utils,
@@ -57,3 +64,8 @@ Description: Wild OS Files, the file manager
bar, and Home folders, drives and the Recycle Bin in the sidebar. File name
extensions are hidden for known types. Folders are read and changed
through KIO, so the Recycle Bin, network places and removable drives all work.
+ .
+ With Advanced protection, Files saves copies of photos, videos, audio,
+ PDFs and Office documents without their location, device and author
+ details, and opens unknown programs and attachments in a safe box sealed
+ off from Home and the network.
diff --git a/packages/wildos-files/qml/AddressBar.qml b/packages/wildos-files/qml/AddressBar.qml
index 7cc3cf0..3d2fc33 100644
--- a/packages/wildos-files/qml/AddressBar.qml
+++ b/packages/wildos-files/qml/AddressBar.qml
@@ -223,7 +223,20 @@ FocusScope {
address.finish();
address.view.focusContent();
}
- onActiveFocusChanged: if (!activeFocus) address.finish()
+ Keys.onPressed: event => {
+ if (addressMenu.isMenuKey(event)) {
+ addressMenu.openAtCaret();
+ event.accepted = true;
+ }
+ }
+ // The text menu holds focus while it is open; the address is still
+ // being typed.
+ onActiveFocusChanged: if (!activeFocus && !addressMenu.opened) address.finish()
+
+ UI.TextMenu {
+ id: addressMenu
+ onFocusLeft: address.finish()
+ }
}
CrumbButton {
diff --git a/packages/wildos-files/qml/FilesView.qml b/packages/wildos-files/qml/FilesView.qml
index 40afcd4..f1fe432 100644
--- a/packages/wildos-files/qml/FilesView.qml
+++ b/packages/wildos-files/qml/FilesView.qml
@@ -464,6 +464,10 @@ Item {
}
apps.push({ text: "Choose another app…", run: () => root.chooseApp(urls) });
entries.push({ text: "Open with", icon: "open-with", submenu: apps });
+ // Advanced protection's Safe box, while it is switched on.
+ if (local && FileOps.safeBoxPlan(urls[0]).ok) {
+ entries.push({ text: "Open in safe box", icon: "sandbox", run: () => FileOps.openInSafeBox(urls[0]) });
+ }
}
if (local && FileOps.areArchives(urls)) {
entries.push({ text: "Extract here", icon: "zip", enabled: FileOps.canWriteIn(f.url), run: () => FileOps.extractHere(urls) });
@@ -473,6 +477,11 @@ Item {
if (FileOps.canUseArchive()) {
entries.push({ text: "Compress…", icon: "zip", run: () => FileOps.compressWith(urls) });
}
+ // Advanced protection's Remove personal details, while it is
+ // switched on, for the kinds of file it can clean.
+ if (FileOps.canRemoveDetails(urls)) {
+ entries.push({ text: "Remove personal details", icon: "eye-off", run: () => FileOps.removeDetails(urls) });
+ }
const targets = FileOps.sendTargets(urls).map(t => ({
text: t.text,
icon: t.icon ?? "",
diff --git a/packages/wildos-files/qml/FormatDialog.qml b/packages/wildos-files/qml/FormatDialog.qml
index 087b04f..09a2d25 100644
--- a/packages/wildos-files/qml/FormatDialog.qml
+++ b/packages/wildos-files/qml/FormatDialog.qml
@@ -224,6 +224,7 @@ UI.Dialog {
Accessible.name: "Password"
placeholderText: "Password"
revealable: true
+ UI.NoPaste {}
error: dialog.tried && dialog.passwordProblem.length > 0
}
UI.TextField {
@@ -234,6 +235,7 @@ UI.Dialog {
Accessible.name: "Type the password again"
placeholderText: "Type the password again"
revealable: true
+ UI.NoPaste {}
error: dialog.tried && dialog.passwordProblem.length > 0
}
UI.Label {
diff --git a/packages/wildos-files/qml/QuickLook.qml b/packages/wildos-files/qml/QuickLook.qml
index 2277ada..b115d2c 100644
--- a/packages/wildos-files/qml/QuickLook.qml
+++ b/packages/wildos-files/qml/QuickLook.qml
@@ -471,6 +471,16 @@ UI.AppWindow {
color: UI.Style.ink
selectionColor: UI.Style.textSelection
selectedTextColor: UI.Style.ink
+ Keys.onPressed: event => {
+ if (codeMenu.isMenuKey(event)) {
+ codeMenu.openAtCaret();
+ event.accepted = true;
+ }
+ }
+
+ UI.TextMenu {
+ id: codeMenu
+ }
}
}
UI.Label {
diff --git a/packages/wildos-files/qml/RemoveDetailsWindow.qml b/packages/wildos-files/qml/RemoveDetailsWindow.qml
new file mode 100644
index 0000000..8969994
--- /dev/null
+++ b/packages/wildos-files/qml/RemoveDetailsWindow.qml
@@ -0,0 +1,154 @@
+import QtQuick
+import QtQuick.Layouts
+import QtQuick.Window
+import WildOS.Files
+import WildOS.UI as UI
+
+// "Choose what is removed", from Settings > Privacy and security >
+// Advanced protection: what Remove personal details takes out of the copy
+// it saves. A window of its own, laid out as Properties is. Each tick is
+// kept as soon as it changes, so Close is the only button.
+UI.AppWindow {
+ id: win
+
+ deep: true
+ width: 480
+ height: 560
+ minimumWidth: 420
+ minimumHeight: 480
+ title: "Choose what is removed"
+
+ component Choice: ColumnLayout {
+ id: choice
+ property alias text: box.text
+ property alias checked: box.checked
+ property string detail
+ signal toggled(bool on)
+ Layout.fillWidth: true
+ spacing: 2
+
+ UI.CheckBox {
+ id: box
+ Layout.fillWidth: true
+ font.weight: UI.Style.weightMedium
+ onToggled: choice.toggled(checked)
+ }
+ UI.Label {
+ Layout.fillWidth: true
+ Layout.leftMargin: 30
+ text: choice.detail
+ size: 12
+ color: UI.Style.inkMuted
+ wrapMode: Text.Wrap
+ elide: Text.ElideNone
+ }
+ }
+
+ ColumnLayout {
+ anchors.fill: parent
+ anchors.margins: win.maximised ? 0 : 1
+ spacing: 0
+
+ UI.TitleBar {
+ Layout.fillWidth: true
+ frame: win.frame
+ buttons.showMinimise: false
+ buttons.showMaximise: false
+
+ Row {
+ x: -2
+ height: parent.height
+ spacing: 10
+
+ UI.Icon {
+ anchors.verticalCenter: parent.verticalCenter
+ name: "eye-off"
+ size: 16
+ }
+ UI.Label {
+ anchors.verticalCenter: parent.verticalCenter
+ text: win.title
+ font.weight: UI.Style.weightMedium
+ color: win.active ? UI.Style.ink : UI.Style.inkMuted
+ }
+ }
+ }
+
+ Rectangle {
+ Layout.fillWidth: true
+ implicitHeight: 1
+ color: UI.Style.divider
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ Layout.fillHeight: true
+ Layout.margins: 24
+ spacing: 18
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: "Right-click a file in Files and choose Remove personal details to save a copy without what is ticked here. The file itself stays as it is."
+ wrapMode: Text.Wrap
+ elide: Text.ElideNone
+ }
+
+ Choice {
+ text: "Location"
+ detail: "GPS position and place names, such as the city and country, in photos, videos and audio."
+ checked: Protection.removeLocation
+ onToggled: on => Protection.removeLocation = on
+ }
+ Choice {
+ text: "Device"
+ detail: "The phone or camera's make, model and serial numbers, the lens, the camera maker's own notes, and the program that made or last saved the file. In documents, the printer it was set up for."
+ checked: Protection.removeDevice
+ onToggled: on => Protection.removeDevice = on
+ }
+ Choice {
+ text: "Author names"
+ detail: "Author, artist, owner and copyright names, and in documents who last saved it, the company, and the names on comments and tracked changes."
+ checked: Protection.removeAuthors
+ onToggled: on => Protection.removeAuthors = on
+ }
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: "Works with photos, MP4 and MOV videos, MP3, FLAC and Ogg audio, PDFs, and Word, Excel, PowerPoint and OpenDocument files. Anything that shows in the picture or the text itself is kept, and so is the date it was made. Pictures inside a PDF keep their own details."
+ size: 12
+ color: UI.Style.inkMuted
+ wrapMode: Text.Wrap
+ elide: Text.ElideNone
+ }
+
+ Item { Layout.fillHeight: true }
+ }
+
+ Rectangle {
+ Layout.fillWidth: true
+ implicitHeight: 1
+ color: UI.Style.divider
+ }
+
+ RowLayout {
+ Layout.fillWidth: true
+ Layout.preferredHeight: 60
+ Layout.leftMargin: 20
+ Layout.rightMargin: 20
+ spacing: 10
+
+ Item { Layout.fillWidth: true }
+
+ UI.Button {
+ kind: "primary"
+ text: "Close"
+ onClicked: win.close()
+ }
+ }
+ }
+
+ Shortcut {
+ sequences: ["Escape"]
+ onActivated: win.close()
+ }
+}
diff --git a/packages/wildos-files/qml/RenameField.qml b/packages/wildos-files/qml/RenameField.qml
index 45f4519..d719e37 100644
--- a/packages/wildos-files/qml/RenameField.qml
+++ b/packages/wildos-files/qml/RenameField.qml
@@ -76,8 +76,17 @@ Rectangle {
// Characters a name cannot hold are refused as they are typed.
if (event.text === "/") {
event.accepted = true;
+ } else if (nameMenu.isMenuKey(event)) {
+ nameMenu.openAtCaret();
+ event.accepted = true;
}
}
- onActiveFocusChanged: if (!activeFocus) field.finish(true)
+ // The text menu holds focus while it is open; the rename is not over.
+ onActiveFocusChanged: if (!activeFocus && !nameMenu.opened) field.finish(true)
+
+ UI.TextMenu {
+ id: nameMenu
+ onFocusLeft: field.finish(true)
+ }
}
}
diff --git a/packages/wildos-files/src/app.cpp b/packages/wildos-files/src/app.cpp
index 67dca3d..7e101f8 100644
--- a/packages/wildos-files/src/app.cpp
+++ b/packages/wildos-files/src/app.cpp
@@ -160,6 +160,38 @@ void App::openWindow(const QList<QUrl> &urls, const QString &formatUdi)
}
}
+void App::ChooseRemovedDetails()
+{
+ if (!m_engine) {
+ return;
+ }
+ // One window at a time: a second request brings the open one forward.
+ if (m_choices) {
+ m_choices->requestActivate();
+ KWindowSystem::activateWindow(m_choices);
+ return;
+ }
+ QQmlComponent component(m_engine, QStringLiteral("WildOS.Files"), QStringLiteral("RemoveDetailsWindow"));
+ QObject *object = component.create();
+ auto window = qobject_cast<QQuickWindow *>(object);
+ if (!window) {
+ qWarning() << component.errors();
+ delete object;
+ return;
+ }
+ object->setParent(this);
+ m_choices = window;
+ connect(window, &QQuickWindow::visibleChanged, window, [window] {
+ if (!window->isVisible()) {
+ window->deleteLater();
+ }
+ });
+ KWindowSystem::updateStartupId(window);
+ window->show();
+ window->requestActivate();
+ KWindowSystem::activateWindow(window);
+}
+
FileManager1::FileManager1(QObject *parent)
: QObject(parent)
{
diff --git a/packages/wildos-files/src/app.h b/packages/wildos-files/src/app.h
index 79ad7a9..f6c8af9 100644
--- a/packages/wildos-files/src/app.h
+++ b/packages/wildos-files/src/app.h
@@ -1,11 +1,13 @@
#pragma once
#include <QObject>
+#include <QPointer>
#include <QQmlEngine>
#include <QUrl>
class QQmlApplicationEngine;
class QQmlComponent;
+class QQuickWindow;
// Opens Files windows. Like Explorer, every launch opens a new window in
// the one running process, so they share the clipboard, the Recycle Bin watcher
@@ -30,6 +32,9 @@ public Q_SLOTS:
// UDisks2 block object path. A drive Files would not format gets a
// message instead.
Q_SCRIPTABLE void Format(const QString &device);
+ // "Choose what is removed" for Remove personal details, which Settings'
+ // Advanced protection page opens.
+ Q_SCRIPTABLE void ChooseRemovedDetails();
Q_INVOKABLE void openWindow(const QList<QUrl> &urls, const QString &formatUdi = QString());
Q_INVOKABLE void newWindow() { openWindow({}); }
@@ -38,6 +43,7 @@ private:
QQmlApplicationEngine *m_engine = nullptr;
QQmlComponent *m_component = nullptr;
+ QPointer<QQuickWindow> m_choices;
};
// org.freedesktop.FileManager1, so "Show in folder" in browsers and other
diff --git a/packages/wildos-files/src/driveformat.cpp b/packages/wildos-files/src/driveformat.cpp
index 362c5a8..6b8a0b5 100644
--- a/packages/wildos-files/src/driveformat.cpp
+++ b/packages/wildos-files/src/driveformat.cpp
@@ -10,6 +10,7 @@
#include <QDBusMetaType>
#include <QDBusObjectPath>
#include <QDBusReply>
+#include <QFile>
#include <QFileInfo>
#include <QPointer>
#include <QThread>
@@ -21,6 +22,24 @@ Q_DECLARE_METATYPE(ManagedObjects)
namespace
{
+// Settings > Privacy and security > Advanced protection's "Password-locked
+// USB sticks" (usb_encrypt in /etc/wildos/advanced-protection, on unless it
+// says off): off, the format window leaves "Encrypt this drive" out.
+bool encryptOffered()
+{
+ QFile store(QStringLiteral("/etc/wildos/advanced-protection"));
+ bool on = true;
+ if (store.open(QIODevice::ReadOnly | QIODevice::Text)) {
+ while (!store.atEnd()) {
+ const QByteArray line = store.readLine().trimmed();
+ if (line.startsWith("usb_encrypt=")) {
+ on = line.mid(12) != "off";
+ }
+ }
+ }
+ return on;
+}
+
const QString service = QStringLiteral("org.freedesktop.UDisks2");
const QString root = QStringLiteral("/org/freedesktop/UDisks2");
const QString blockPrefix = QStringLiteral("/org/freedesktop/UDisks2/block_devices/");
@@ -491,7 +510,7 @@ QVariantMap DriveFormat::describe(const QString &udi) const
}
out.insert(QStringLiteral("tools"), tools);
const QStringList crypt = manager.property("SupportedEncryptionTypes").toStringList();
- out.insert(QStringLiteral("canEncrypt"), crypt.contains(QStringLiteral("luks2")));
+ out.insert(QStringLiteral("canEncrypt"), crypt.contains(QStringLiteral("luks2")) && encryptOffered());
return out;
}
diff --git a/packages/wildos-files/src/fileops.cpp b/packages/wildos-files/src/fileops.cpp
index 4aa3bf2..68d28a0 100644
--- a/packages/wildos-files/src/fileops.cpp
+++ b/packages/wildos-files/src/fileops.cpp
@@ -2,6 +2,7 @@
#include "drives.h"
#include "format.h"
+#include "programs.h"
#include "settings.h"
#include "sharemodel.h"
@@ -56,88 +57,6 @@ QString folderName(const QUrl &url)
return name.isEmpty() ? QStringLiteral("this folder") : name;
}
-// Whether an ELF file asks for a program loader (PT_INTERP). Programs
-// built as position independent executables, which is most of them now,
-// share their MIME type with libraries, and this is what tells them apart.
-bool namesInterpreter(const QString &path)
-{
- QFile file(path);
- if (!file.open(QIODevice::ReadOnly)) {
- return false;
- }
- const QByteArray head = file.read(64);
- if (head.size() < 52 || !head.startsWith("\x7f" "ELF")) {
- return false;
- }
- const bool wide = head.at(4) == 2;
- const bool little = head.at(5) == 1;
- auto number = [little](const QByteArray &bytes, qsizetype at, int size) {
- quint64 value = 0;
- for (int i = 0; i < size; ++i) {
- value = (value << 8) | quint8(bytes.at(at + (little ? size - 1 - i : i)));
- }
- return value;
- };
- if (wide && head.size() < 64) {
- return false;
- }
- const quint64 offset = wide ? number(head, 32, 8) : number(head, 28, 4);
- const qsizetype entrySize = qsizetype(number(head, wide ? 54 : 42, 2));
- const qsizetype entries = qsizetype(number(head, wide ? 56 : 44, 2));
- if (entrySize < 4 || entrySize > 64 || entries == 0 || entries > 4096 || offset > quint64(file.size()) || !file.seek(qint64(offset))) {
- return false;
- }
- const QByteArray table = file.read(entrySize * entries);
- for (qsizetype at = 0; at + entrySize <= table.size(); at += entrySize) {
- if (number(table, at, 4) == 3) {
- return true;
- }
- }
- return false;
-}
-
-// The processor an ELF file is built for (e_machine), or 0 when it is not
-// ELF. A download for another processor, such as an ARM AppImage on a PC,
-// fails with "Exec format error" only after KIO has counted the launch as a
-// success, so nobody would hear about it unless it is caught before then.
-quint16 elfMachine(const QString &path)
-{
- QFile file(path);
- if (!file.open(QIODevice::ReadOnly)) {
- return 0;
- }
- const QByteArray head = file.read(20);
- if (head.size() < 20 || quint8(head.at(0)) != 0x7f || head.mid(1, 3) != "ELF") {
- return 0;
- }
- const quint16 a = quint8(head.at(18));
- const quint16 b = quint8(head.at(19));
- return head.at(5) == 1 ? quint16(a | (b << 8)) : quint16(b | (a << 8));
-}
-
-#if defined(__x86_64__)
-constexpr quint16 hostMachine = 62;
-#elif defined(__aarch64__)
-constexpr quint16 hostMachine = 183;
-#else
-constexpr quint16 hostMachine = 0;
-#endif
-
-// A Linux program or AppImage that a double click would run. Scripts are
-// left out: they open in their app, where people can read them.
-bool isLinuxProgram(const QUrl &url, const QMimeType &type)
-{
- if (!url.isLocalFile()) {
- return false;
- }
- const QString name = type.name();
- if (name == QLatin1String("application/x-executable") || type.inherits(QStringLiteral("application/vnd.appimage"))
- || type.inherits(QStringLiteral("application/x-iso9660-appimage"))) {
- return true;
- }
- return name == QLatin1String("application/x-sharedlib") && namesInterpreter(url.toLocalFile());
-}
-
QVariantMap appEntry(const KService::Ptr &service)
{
return {
@@ -578,8 +497,17 @@ void FileOps::askToRun(const QUrl &url)
prompt[QStringLiteral("text")] = QStringLiteral("This is a program that did not come with Wild OS or the Store, and nothing has checked it. "
"It can open and change any of your files. Only run it if you trust where it came from.");
prompt[QStringLiteral("primary")] = QStringLiteral("Run");
+ // With the safe box on, it can be tried sealed off first.
+ const bool box = safeBoxPlan(url).value(QStringLiteral("ok")).toBool();
+ if (box) {
+ prompt[QStringLiteral("secondary")] = QStringLiteral("Run in safe box");
+ }
prompt[QStringLiteral("cancelDefault")] = true;
- ask(prompt, [this, path, name](const QString &choice, bool) {
+ ask(prompt, [this, url, path, name](const QString &choice, bool) {
+ if (choice == QLatin1String("secondary")) {
+ openInSafeBox(url);
+ return;
+ }
if (choice != QLatin1String("primary")) {
return;
}
diff --git a/packages/wildos-files/src/fileops.h b/packages/wildos-files/src/fileops.h
index 15febef..149a51a 100644
--- a/packages/wildos-files/src/fileops.h
+++ b/packages/wildos-files/src/fileops.h
@@ -146,6 +146,13 @@ public:
Q_INVOKABLE void duplicate(const QUrl &url);
Q_INVOKABLE void applyProperties(const QUrl &url, const QString &fileName, bool isDir, const QString &typed, bool hidden);
+ // Advanced protection, see protectionops.cpp: a copy without personal
+ // details, and opening a file in the safe box.
+ Q_INVOKABLE bool canRemoveDetails(const QList<QUrl> &urls) const;
+ Q_INVOKABLE void removeDetails(const QList<QUrl> &urls);
+ Q_INVOKABLE QVariantMap safeBoxPlan(const QUrl &url) const;
+ Q_INVOKABLE void openInSafeBox(const QUrl &url);
+
Q_INVOKABLE void answer(const QString &choice, bool applyToAll);
Q_INVOKABLE void ejectDrive(const QString &udi);
diff --git a/packages/wildos-files/src/main.cpp b/packages/wildos-files/src/main.cpp
index e24a772..309af00 100644
--- a/packages/wildos-files/src/main.cpp
+++ b/packages/wildos-files/src/main.cpp
@@ -42,6 +42,8 @@ int main(int argc, char *argv[])
parser.addOption(selectOption);
QCommandLineOption formatOption(QStringLiteral("format"), QStringLiteral("Open the Format dialog for a removable drive, such as /dev/sdb1."), QStringLiteral("device"));
parser.addOption(formatOption);
+ QCommandLineOption choicesOption(QStringLiteral("remove-details-choices"), QStringLiteral("Open \"Choose what is removed\" for Remove personal details."));
+ parser.addOption(choicesOption);
// Started by D-Bus for a call such as "show this file in its folder";
// the call itself opens the window.
QCommandLineOption serviceOption(QStringLiteral("service"), QStringLiteral("Start without a window, waiting for D-Bus requests."));
@@ -64,7 +66,12 @@ int main(int argc, char *argv[])
return 0;
}
const QString formatDevice = parser.value(formatOption);
+ const bool choices = parser.isSet(choicesOption);
if (!preview && bus.isConnected() && bus.interface()->isServiceRegistered(serviceName)) {
+ if (choices) {
+ bus.call(QDBusMessage::createMethodCall(serviceName, objectPath, serviceName, QStringLiteral("ChooseRemovedDetails")), QDBus::Block, 5000);
+ return 0;
+ }
auto message = formatDevice.isEmpty() ? QDBusMessage::createMethodCall(serviceName, objectPath, serviceName, QStringLiteral("Open"))
: QDBusMessage::createMethodCall(serviceName, objectPath, serviceName, QStringLiteral("Format"));
if (formatDevice.isEmpty()) {
@@ -104,7 +111,9 @@ int main(int argc, char *argv[])
bus.registerService(QStringLiteral("org.freedesktop.FileManager1"));
}
- if (!formatDevice.isEmpty()) {
+ if (choices) {
+ files->ChooseRemovedDetails();
+ } else if (!formatDevice.isEmpty()) {
files->Format(formatDevice);
} else if (!service) {
files->Open(locations);
diff --git a/packages/wildos-files/src/newitems.cpp b/packages/wildos-files/src/newitems.cpp
index c035a9a..b627cf9 100644
--- a/packages/wildos-files/src/newitems.cpp
+++ b/packages/wildos-files/src/newitems.cpp
@@ -63,8 +63,8 @@ const QStringList &commonNouns()
return nouns;
}
-// "Text document" makes "New text document"; "Writer document" keeps its
-// capital and makes "New Writer document", as Windows names new items.
+// "Text document" makes "New text document"; "Write document" keeps its
+// capital and makes "New Write document", as Windows names new items.
QString newBase(const QString &text)
{
const QString first = text.section(QLatin1Char(' '), 0, 0);
@@ -155,10 +155,18 @@ QList<Template> templates()
};
if (hasService({QStringLiteral("libreoffice-writer"), QStringLiteral("org.libreoffice.LibreOffice.writer")})) {
- builtIn(QStringLiteral("writer"), QStringLiteral("Writer document"), QStringLiteral("application/vnd.oasis.opendocument.text"), QStringLiteral(".odt"));
+ // Write and Tables save as Word and Excel files, so new ones start
+ // that way too; an empty file opens as a new document of its kind.
+ // LibreOffice's own OpenDocument templates are left out, or they
+ // would show beside these under LibreOffice's names.
+ builtIn(QStringLiteral("writer"), QStringLiteral("Write document"),
+ QStringLiteral("application/vnd.openxmlformats-officedocument.wordprocessingml.document"), QStringLiteral(".docx"));
+ installed.remove(QStringLiteral("application/vnd.oasis.opendocument.text"));
}
if (hasService({QStringLiteral("libreoffice-calc"), QStringLiteral("org.libreoffice.LibreOffice.calc")})) {
- builtIn(QStringLiteral("calc"), QStringLiteral("Calc spreadsheet"), QStringLiteral("application/vnd.oasis.opendocument.spreadsheet"), QStringLiteral(".ods"));
+ builtIn(QStringLiteral("calc"), QStringLiteral("Tables spreadsheet"),
+ QStringLiteral("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"), QStringLiteral(".xlsx"));
+ installed.remove(QStringLiteral("application/vnd.oasis.opendocument.spreadsheet"));
}
if (hasService({QStringLiteral("libreoffice-impress"), QStringLiteral("org.libreoffice.LibreOffice.impress")})) {
builtIn(QStringLiteral("impress"), QStringLiteral("Impress presentation"), QStringLiteral("application/vnd.oasis.opendocument.presentation"), QStringLiteral(".odp"));
diff --git a/packages/wildos-files/src/programs.cpp b/packages/wildos-files/src/programs.cpp
new file mode 100644
index 0000000..1ba9da5
--- /dev/null
+++ b/packages/wildos-files/src/programs.cpp
@@ -0,0 +1,73 @@
+#include "programs.h"
+
+#include <QFile>
+#include <QMimeType>
+#include <QUrl>
+
+// Whether an ELF file asks for a program loader (PT_INTERP). Programs
+// built as position independent executables, which is most of them now,
+// share their MIME type with libraries, and this is what tells them apart.
+static bool namesInterpreter(const QString &path)
+{
+ QFile file(path);
+ if (!file.open(QIODevice::ReadOnly)) {
+ return false;
+ }
+ const QByteArray head = file.read(64);
+ if (head.size() < 52 || !head.startsWith("\x7f" "ELF")) {
+ return false;
+ }
+ const bool wide = head.at(4) == 2;
+ const bool little = head.at(5) == 1;
+ auto number = [little](const QByteArray &bytes, qsizetype at, int size) {
+ quint64 value = 0;
+ for (int i = 0; i < size; ++i) {
+ value = (value << 8) | quint8(bytes.at(at + (little ? size - 1 - i : i)));
+ }
+ return value;
+ };
+ if (wide && head.size() < 64) {
+ return false;
+ }
+ const quint64 offset = wide ? number(head, 32, 8) : number(head, 28, 4);
+ const qsizetype entrySize = qsizetype(number(head, wide ? 54 : 42, 2));
+ const qsizetype entries = qsizetype(number(head, wide ? 56 : 44, 2));
+ if (entrySize < 4 || entrySize > 64 || entries == 0 || entries > 4096 || offset > quint64(file.size()) || !file.seek(qint64(offset))) {
+ return false;
+ }
+ const QByteArray table = file.read(entrySize * entries);
+ for (qsizetype at = 0; at + entrySize <= table.size(); at += entrySize) {
+ if (number(table, at, 4) == 3) {
+ return true;
+ }
+ }
+ return false;
+}
+
+quint16 elfMachine(const QString &path)
+{
+ QFile file(path);
+ if (!file.open(QIODevice::ReadOnly)) {
+ return 0;
+ }
+ const QByteArray head = file.read(20);
+ if (head.size() < 20 || quint8(head.at(0)) != 0x7f || head.mid(1, 3) != "ELF") {
+ return 0;
+ }
+ const quint16 a = quint8(head.at(18));
+ const quint16 b = quint8(head.at(19));
+ return head.at(5) == 1 ? quint16(a | (b << 8)) : quint16(b | (a << 8));
+}
+
+bool isLinuxProgram(const QUrl &url, const QMimeType &type)
+{
+ if (!url.isLocalFile()) {
+ return false;
+ }
+ const QString name = type.name();
+ if (name == QLatin1String("application/x-executable") || type.inherits(QStringLiteral("application/vnd.appimage"))
+ || type.inherits(QStringLiteral("application/x-iso9660-appimage"))) {
+ return true;
+ }
+ return name == QLatin1String("application/x-sharedlib") && namesInterpreter(url.toLocalFile());
+}
diff --git a/packages/wildos-files/src/programs.h b/packages/wildos-files/src/programs.h
new file mode 100644
index 0000000..4c0b267
--- /dev/null
+++ b/packages/wildos-files/src/programs.h
@@ -0,0 +1,27 @@
+#pragma once
+
+#include <QtGlobal>
+
+class QMimeType;
+class QString;
+class QUrl;
+
+// Telling programs from documents, shared by Files and the safe box.
+
+// The processor an ELF file is built for (e_machine), or 0 when it is not
+// ELF. A download for another processor, such as an ARM AppImage on a PC,
+// fails with "Exec format error" only after KIO has counted the launch as a
+// success, so nobody would hear about it unless it is caught before then.
+quint16 elfMachine(const QString &path);
+
+#if defined(__x86_64__)
+constexpr quint16 hostMachine = 62;
+#elif defined(__aarch64__)
+constexpr quint16 hostMachine = 183;
+#else
+constexpr quint16 hostMachine = 0;
+#endif
+
+// A Linux program or AppImage that a double click would run. Scripts are
+// left out: they open in their app, where people can read them.
+bool isLinuxProgram(const QUrl &url, const QMimeType &type);
diff --git a/packages/wildos-files/src/protection.cpp b/packages/wildos-files/src/protection.cpp
new file mode 100644
index 0000000..93984f2
--- /dev/null
+++ b/packages/wildos-files/src/protection.cpp
@@ -0,0 +1,121 @@
+#include "protection.h"
+
+#include <KConfigGroup>
+#include <QFile>
+#include <QFileSystemWatcher>
+
+namespace
+{
+const QString storeDir = QStringLiteral("/etc/wildos");
+const QString store = QStringLiteral("/etc/wildos/advanced-protection");
+const char group[] = "RemoveDetails";
+}
+
+Protection *Protection::instance()
+{
+ static Protection *protection = new Protection;
+ return protection;
+}
+
+Protection *Protection::create(QQmlEngine *, QJSEngine *)
+{
+ auto protection = instance();
+ QJSEngine::setObjectOwnership(protection, QJSEngine::CppOwnership);
+ return protection;
+}
+
+Protection::Protection(QObject *parent)
+ : QObject(parent)
+ , m_watcher(new QFileSystemWatcher(this))
+ , m_config(KSharedConfig::openConfig(QStringLiteral("wildosfilesrc")))
+{
+ // The helper replaces the file rather than writing into it, so the
+ // folder is watched for it coming back.
+ m_watcher->addPath(storeDir);
+ if (QFile::exists(store)) {
+ m_watcher->addPath(store);
+ }
+ connect(m_watcher, &QFileSystemWatcher::directoryChanged, this, &Protection::read);
+ connect(m_watcher, &QFileSystemWatcher::fileChanged, this, &Protection::read);
+ read();
+}
+
+void Protection::read()
+{
+ if (QFile::exists(store) && !m_watcher->files().contains(store)) {
+ m_watcher->addPath(store);
+ }
+ bool scrub = true;
+ bool box = true;
+ QFile file(store);
+ if (file.open(QIODevice::ReadOnly)) {
+ while (!file.atEnd()) {
+ const QByteArray line = file.readLine().trimmed();
+ const qsizetype eq = line.indexOf('=');
+ if (eq <= 0) {
+ continue;
+ }
+ const QByteArray key = line.left(eq).trimmed();
+ const bool on = line.mid(eq + 1).trimmed() != "off";
+ if (key == "scrub_files") {
+ scrub = on;
+ } else if (key == "safebox") {
+ box = on;
+ }
+ }
+ }
+ if (scrub != m_scrubFiles || box != m_safeBox) {
+ m_scrubFiles = scrub;
+ m_safeBox = box;
+ Q_EMIT changed();
+ }
+}
+
+void Protection::write(const char *key, bool value)
+{
+ KConfigGroup(m_config, QString::fromLatin1(group)).writeEntry(key, value);
+ m_config->sync();
+ Q_EMIT choicesChanged();
+}
+
+bool Protection::removeLocation() const
+{
+ return KConfigGroup(m_config, QString::fromLatin1(group)).readEntry("Location", true);
+}
+
+void Protection::setRemoveLocation(bool on)
+{
+ write("Location", on);
+}
+
+bool Protection::removeDevice() const
+{
+ return KConfigGroup(m_config, QString::fromLatin1(group)).readEntry("Device", true);
+}
+
+void Protection::setRemoveDevice(bool on)
+{
+ write("Device", on);
+}
+
+bool Protection::removeAuthors() const
+{
+ return KConfigGroup(m_config, QString::fromLatin1(group)).readEntry("Authors", true);
+}
+
+void Protection::setRemoveAuthors(bool on)
+{
+ write("Authors", on);
+}
+
+bool Protection::safeBoxExplained() const
+{
+ return KConfigGroup(m_config, QStringLiteral("SafeBox")).readEntry("Explained", false);
+}
+
+void Protection::setSafeBoxExplained(bool done)
+{
+ KConfigGroup(m_config, QStringLiteral("SafeBox")).writeEntry("Explained", done);
+ m_config->sync();
+ Q_EMIT choicesChanged();
+}
diff --git a/packages/wildos-files/src/protection.h b/packages/wildos-files/src/protection.h
new file mode 100644
index 0000000..9d07b0f
--- /dev/null
+++ b/packages/wildos-files/src/protection.h
@@ -0,0 +1,59 @@
+#pragma once
+
+#include <KSharedConfig>
+#include <QObject>
+#include <QQmlEngine>
+
+class QFileSystemWatcher;
+
+// The Advanced protection switches Files acts on (Settings > Privacy and
+// security > Advanced protection), read from the system-wide store
+// /etc/wildos/advanced-protection that Settings' helper writes, and watched
+// so a change shows in open windows straight away. A key that is missing
+// has the board's default: both are on.
+//
+// Also the person's own choice of what "Remove personal details" removes,
+// kept in wildosfilesrc.
+class Protection : public QObject
+{
+ Q_OBJECT
+ QML_ELEMENT
+ QML_SINGLETON
+
+ Q_PROPERTY(bool scrubFiles READ scrubFiles NOTIFY changed)
+ Q_PROPERTY(bool safeBox READ safeBox NOTIFY changed)
+ Q_PROPERTY(bool removeLocation READ removeLocation WRITE setRemoveLocation NOTIFY choicesChanged)
+ Q_PROPERTY(bool removeDevice READ removeDevice WRITE setRemoveDevice NOTIFY choicesChanged)
+ Q_PROPERTY(bool removeAuthors READ removeAuthors WRITE setRemoveAuthors NOTIFY choicesChanged)
+ // Whether the safe box's limits have been explained once.
+ Q_PROPERTY(bool safeBoxExplained READ safeBoxExplained WRITE setSafeBoxExplained NOTIFY choicesChanged)
+
+public:
+ static Protection *instance();
+ static Protection *create(QQmlEngine *, QJSEngine *);
+
+ bool scrubFiles() const { return m_scrubFiles; }
+ bool safeBox() const { return m_safeBox; }
+ bool removeLocation() const;
+ void setRemoveLocation(bool on);
+ bool removeDevice() const;
+ void setRemoveDevice(bool on);
+ bool removeAuthors() const;
+ void setRemoveAuthors(bool on);
+ bool safeBoxExplained() const;
+ void setSafeBoxExplained(bool done);
+
+Q_SIGNALS:
+ void changed();
+ void choicesChanged();
+
+private:
+ explicit Protection(QObject *parent = nullptr);
+ void read();
+ void write(const char *key, bool value);
+
+ QFileSystemWatcher *m_watcher;
+ KSharedConfigPtr m_config;
+ bool m_scrubFiles = true;
+ bool m_safeBox = true;
+};
diff --git a/packages/wildos-files/src/protectionops.cpp b/packages/wildos-files/src/protectionops.cpp
new file mode 100644
index 0000000..c01f6f8
--- /dev/null
+++ b/packages/wildos-files/src/protectionops.cpp
@@ -0,0 +1,172 @@
+// The file menu's Advanced protection entries: Remove personal details and
+// Open in safe box. Both only show while their switch is on (Protection).
+
+#include "fileops.h"
+#include "protection.h"
+#include "safeboxplan.h"
+
+#include <QDir>
+#include <QFileInfo>
+#include <QJsonDocument>
+#include <QJsonObject>
+#include <QProcess>
+#include <QSet>
+
+namespace
+{
+const QString removeDetailsTool = QStringLiteral("/usr/libexec/wildos/remove-details");
+const QString safeBoxTool = QStringLiteral("/usr/bin/wildos-safebox");
+
+// The kinds remove-details can clean; the script has the same lists.
+const QSet<QString> &cleanable()
+{
+ static const QSet<QString> extensions{
+ QStringLiteral("jpg"), QStringLiteral("jpeg"), QStringLiteral("jpe"), QStringLiteral("png"), QStringLiteral("heic"), QStringLiteral("heif"),
+ QStringLiteral("avif"), QStringLiteral("webp"), QStringLiteral("tif"), QStringLiteral("tiff"), QStringLiteral("gif"), QStringLiteral("dng"),
+ QStringLiteral("mp4"), QStringLiteral("m4v"), QStringLiteral("mov"), QStringLiteral("3gp"), QStringLiteral("3g2"), QStringLiteral("m4a"),
+ QStringLiteral("mp3"), QStringLiteral("flac"), QStringLiteral("ogg"), QStringLiteral("oga"), QStringLiteral("opus"), QStringLiteral("pdf"),
+ QStringLiteral("docx"), QStringLiteral("docm"), QStringLiteral("dotx"), QStringLiteral("dotm"), QStringLiteral("xlsx"), QStringLiteral("xlsm"),
+ QStringLiteral("xltx"), QStringLiteral("xltm"), QStringLiteral("pptx"), QStringLiteral("pptm"), QStringLiteral("potx"), QStringLiteral("potm"),
+ QStringLiteral("ppsx"), QStringLiteral("ppsm"), QStringLiteral("odt"), QStringLiteral("ott"), QStringLiteral("ods"), QStringLiteral("ots"),
+ QStringLiteral("odp"), QStringLiteral("otp"), QStringLiteral("odg"), QStringLiteral("otg"),
+ };
+ return extensions;
+}
+}
+
+bool FileOps::canRemoveDetails(const QList<QUrl> &urls) const
+{
+ const Protection *protection = Protection::instance();
+ if (!protection->scrubFiles() || urls.isEmpty() || !QFileInfo::exists(removeDetailsTool)
+ || !(protection->removeLocation() || protection->removeDevice() || protection->removeAuthors())) {
+ return false;
+ }
+ for (const QUrl &url : urls) {
+ const QFileInfo info(url.toLocalFile());
+ if (!url.isLocalFile() || !info.isFile() || !cleanable().contains(info.suffix().toLower())) {
+ return false;
+ }
+ }
+ return true;
+}
+
+void FileOps::removeDetails(const QList<QUrl> &urls)
+{
+ if (!canRemoveDetails(urls)) {
+ return;
+ }
+ const Protection *protection = Protection::instance();
+ QStringList args;
+ if (protection->removeLocation()) {
+ args << QStringLiteral("--location");
+ }
+ if (protection->removeDevice()) {
+ args << QStringLiteral("--device");
+ }
+ if (protection->removeAuthors()) {
+ args << QStringLiteral("--authors");
+ }
+ args << QStringLiteral("--");
+ for (const QUrl &url : urls) {
+ args << url.toLocalFile();
+ }
+ auto process = new QProcess(this);
+ process->setProcessChannelMode(QProcess::SeparateChannels);
+ connect(process, &QProcess::finished, this, [this, process] {
+ process->deleteLater();
+ QHash<QUrl, QList<QUrl>> made;
+ QStringList problems;
+ int copies = 0;
+ const QList<QByteArray> lines = process->readAllStandardOutput().split('\n');
+ for (const QByteArray &line : lines) {
+ const QJsonObject result = QJsonDocument::fromJson(line).object();
+ if (result.isEmpty()) {
+ continue;
+ }
+ const QString error = result.value(QStringLiteral("error")).toString();
+ if (!error.isEmpty()) {
+ problems << QStringLiteral("%1: %2").arg(QFileInfo(result.value(QStringLiteral("file")).toString()).fileName(), error);
+ continue;
+ }
+ const QUrl copy = QUrl::fromLocalFile(result.value(QStringLiteral("copy")).toString());
+ made[copy.adjusted(QUrl::RemoveFilename | QUrl::StripTrailingSlash)].append(copy);
+ ++copies;
+ }
+ for (auto it = made.cbegin(); it != made.cend(); ++it) {
+ Q_EMIT created(it.key(), it.value(), false);
+ }
+ if (!problems.isEmpty()) {
+ // One file: its sentence alone. Several: each one named.
+ Q_EMIT failed(problems.size() == 1 && copies == 0 ? problems.first().section(QStringLiteral(": "), 1) : problems.join(QLatin1Char('\n')));
+ } else if (copies == 0) {
+ Q_EMIT failed(QStringLiteral("The personal details couldn't be removed."));
+ }
+ if (copies > 0) {
+ Q_EMIT notice(copies == 1 ? QStringLiteral("Saved a copy without personal details")
+ : QStringLiteral("Saved %1 copies without personal details").arg(copies));
+ }
+ });
+ connect(process, &QProcess::errorOccurred, this, [this, process](QProcess::ProcessError error) {
+ if (error == QProcess::FailedToStart) {
+ process->deleteLater();
+ Q_EMIT failed(QStringLiteral("The personal details couldn't be removed."));
+ }
+ });
+ process->start(removeDetailsTool, args);
+}
+
+QVariantMap FileOps::safeBoxPlan(const QUrl &url) const
+{
+ if (!Protection::instance()->safeBox() || !url.isLocalFile() || !QFileInfo::exists(safeBoxTool)) {
+ return {{QStringLiteral("ok"), false}};
+ }
+ const SafeBoxPlan plan = ::safeBoxPlan(url.toLocalFile());
+ return {
+ {QStringLiteral("ok"), plan.ok},
+ {QStringLiteral("program"), plan.program},
+ {QStringLiteral("app"), plan.appName},
+ {QStringLiteral("message"), plan.message},
+ };
+}
+
+void FileOps::openInSafeBox(const QUrl &url)
+{
+ const QVariantMap plan = safeBoxPlan(url);
+ if (!plan.value(QStringLiteral("ok")).toBool()) {
+ const QString message = plan.value(QStringLiteral("message")).toString();
+ if (!message.isEmpty()) {
+ Q_EMIT failed(message);
+ }
+ return;
+ }
+ const QString path = url.toLocalFile();
+ const auto launch = [this, path] {
+ if (!QProcess::startDetached(safeBoxTool, {path}, QFileInfo(path).absolutePath())) {
+ Q_EMIT failed(QStringLiteral("The safe box couldn't open."));
+ }
+ };
+ Protection *protection = Protection::instance();
+ if (protection->safeBoxExplained()) {
+ launch();
+ return;
+ }
+ // The first time, what the box does and does not do, in plain words.
+ const QString name = url.fileName();
+ const QString lead = plan.value(QStringLiteral("program")).toBool()
+ ? QStringLiteral("%1 runs").arg(name)
+ : QStringLiteral("%1 opens in %2,").arg(name, plan.value(QStringLiteral("app")).toString());
+ QVariantMap prompt;
+ prompt[QStringLiteral("kind")] = QStringLiteral("confirm");
+ prompt[QStringLiteral("title")] = QStringLiteral("Open in safe box?");
+ prompt[QStringLiteral("text")] = QStringLiteral("%1 sealed off from your files and the network, with no sound or camera. "
+ "Anything it saves is gone when it closes. This stops most harm, but a program "
+ "made to attack Wild OS itself could still break out.")
+ .arg(lead);
+ prompt[QStringLiteral("primary")] = QStringLiteral("Open in safe box");
+ ask(prompt, [protection, launch](const QString &choice, bool) {
+ if (choice == QLatin1String("primary")) {
+ protection->setSafeBoxExplained(true);
+ launch();
+ }
+ });
+}
diff --git a/packages/wildos-files/src/safebox/main.cpp b/packages/wildos-files/src/safebox/main.cpp
new file mode 100644
index 0000000..17c6a31
--- /dev/null
+++ b/packages/wildos-files/src/safebox/main.cpp
@@ -0,0 +1,360 @@
+// wildos-safebox FILE: opens a file, or runs a program, in a bubblewrap
+// sandbox that is thrown away when it closes (Settings > Privacy and
+// security > Advanced protection > Safe box).
+//
+// Inside the box: the system read-only, an empty Home in memory holding only
+// the file, no network (its own empty network namespace), no other
+// processes, a /dev with no hardware in it, and of the person's session only
+// the Wayland socket, so it can show a window. No D-Bus, no X11, no sound,
+// no camera. A seccomp filter turns down the system calls that only serve to
+// reach the kernel's less exposed corners, and new user namespaces are
+// refused, so nothing inside can build a sandbox of its own to escape from.
+//
+// What it can't stop: a flaw in the Linux kernel or in KWin could still be
+// used to get out, and a window in front can read what was copied.
+
+#include "safeboxplan.h"
+
+#include <KIO/DesktopExecParser>
+#include <QCoreApplication>
+#include <QDBusConnection>
+#include <QDBusMessage>
+#include <QDir>
+#include <QFileInfo>
+#include <QStandardPaths>
+#include <QUrl>
+
+#include <cerrno>
+#include <sched.h>
+#include <cstdio>
+#include <ctime>
+#include <fcntl.h>
+#include <seccomp.h>
+#include <sys/ioctl.h>
+#include <cstring>
+#include <sys/mman.h>
+#include <sys/prctl.h>
+#include <sys/stat.h>
+#include <sys/wait.h>
+#include <termios.h>
+#include <unistd.h>
+
+namespace
+{
+void notify(const QString &title, const QString &body)
+{
+ QDBusMessage message = QDBusMessage::createMethodCall(QStringLiteral("org.freedesktop.Notifications"), QStringLiteral("/org/freedesktop/Notifications"),
+ QStringLiteral("org.freedesktop.Notifications"), QStringLiteral("Notify"));
+ message << QStringLiteral("Safe box") << uint(0) << QStringLiteral("security-high") << title << body << QStringList() << QVariantMap() << int(-1);
+ QDBusConnection::sessionBus().call(message, QDBus::Block, 3000);
+}
+
+int fail(const QString &message)
+{
+ std::fprintf(stderr, "%s\n", qPrintable(message));
+ notify(QStringLiteral("The safe box couldn't open"), message);
+ return 3;
+}
+
+// Built in memory and handed to bwrap, which loads it just before the
+// program starts. Calls that are turned down fail with EPERM, as they would
+// for an unprivileged program, rather than killing it.
+int seccompFilter()
+{
+ scmp_filter_ctx ctx = seccomp_init(SCMP_ACT_ALLOW);
+ if (!ctx) {
+ return -1;
+ }
+ // 32-bit programs reach the same kernel through other numbers.
+ seccomp_arch_add(ctx, SCMP_ARCH_X86);
+ seccomp_arch_add(ctx, SCMP_ARCH_X32);
+ const int denied[] = {
+ // The kernel keyring is the person's, not the box's.
+ SCMP_SYS(add_key), SCMP_SYS(keyctl), SCMP_SYS(request_key),
+ // Large, often exploited interfaces no ordinary app needs.
+ SCMP_SYS(bpf), SCMP_SYS(perf_event_open), SCMP_SYS(userfaultfd),
+ SCMP_SYS(io_uring_setup), SCMP_SYS(io_uring_enter), SCMP_SYS(io_uring_register),
+ SCMP_SYS(kexec_load), SCMP_SYS(kexec_file_load), SCMP_SYS(init_module), SCMP_SYS(finit_module), SCMP_SYS(delete_module),
+ SCMP_SYS(mount), SCMP_SYS(umount2), SCMP_SYS(pivot_root), SCMP_SYS(move_mount), SCMP_SYS(open_tree), SCMP_SYS(fsopen),
+ SCMP_SYS(fsmount), SCMP_SYS(fsconfig), SCMP_SYS(fspick), SCMP_SYS(mount_setattr),
+ SCMP_SYS(unshare), SCMP_SYS(setns),
+ SCMP_SYS(acct), SCMP_SYS(swapon), SCMP_SYS(swapoff), SCMP_SYS(reboot), SCMP_SYS(syslog), SCMP_SYS(quotactl),
+ SCMP_SYS(uselib), SCMP_SYS(lookup_dcookie), SCMP_SYS(name_to_handle_at), SCMP_SYS(open_by_handle_at),
+ SCMP_SYS(vhangup), SCMP_SYS(ptrace), SCMP_SYS(process_vm_readv), SCMP_SYS(process_vm_writev),
+ };
+ for (int call : denied) {
+ // A call this processor does not have is skipped by libseccomp.
+ seccomp_rule_add(ctx, SCMP_ACT_ERRNO(EPERM), call, 0);
+ }
+ // Typing into the terminal the box was started from.
+ seccomp_rule_add(ctx, SCMP_ACT_ERRNO(EPERM), SCMP_SYS(ioctl), 1, SCMP_A1(SCMP_CMP_MASKED_EQ, 0xFFFFFFFFu, TIOCSTI));
+ seccomp_rule_add(ctx, SCMP_ACT_ERRNO(EPERM), SCMP_SYS(ioctl), 1, SCMP_A1(SCMP_CMP_MASKED_EQ, 0xFFFFFFFFu, TIOCLINUX));
+ // clone with a new namespace flag; bwrap's --disable-userns covers
+ // user namespaces, this covers the rest. clone3 keeps its flags in
+ // memory, where a filter can't look, so it gets ENOSYS and libc falls
+ // back to clone.
+ for (unsigned long flag : {CLONE_NEWNS, CLONE_NEWCGROUP, CLONE_NEWUTS, CLONE_NEWIPC, CLONE_NEWUSER, CLONE_NEWPID, CLONE_NEWNET}) {
+ seccomp_rule_add(ctx, SCMP_ACT_ERRNO(EPERM), SCMP_SYS(clone), 1, SCMP_A0(SCMP_CMP_MASKED_EQ, flag, flag));
+ }
+ seccomp_rule_add(ctx, SCMP_ACT_ERRNO(ENOSYS), SCMP_SYS(clone3), 0);
+
+ const int fd = memfd_create("wildos-safebox-seccomp", 0);
+ if (fd < 0 || seccomp_export_bpf(ctx, fd) != 0 || lseek(fd, 0, SEEK_SET) != 0) {
+ seccomp_release(ctx);
+ return -1;
+ }
+ seccomp_release(ctx);
+ return fd;
+}
+
+// /bin, /lib and the rest as the system has them: links into /usr on a
+// merged system, read-only folders otherwise.
+void hostLinkOrDir(QStringList &args, const QString &top)
+{
+ const QFileInfo info(top);
+ if (info.isSymLink()) {
+ args << QStringLiteral("--symlink") << info.symLinkTarget().mid(1) << top;
+ } else if (info.isDir()) {
+ args << QStringLiteral("--ro-bind") << top << top;
+ }
+}
+}
+
+// Inside the box, first in line: runs the app and stays until every process
+// it started has ended. Apps that hand over to a process of their own and
+// quit, as Write and Tables do with LibreOffice, would otherwise take the
+// whole box down with them, since the box ends when its first process does.
+// Returns the app's own exit code.
+int reap(char *argv[])
+{
+ prctl(PR_SET_CHILD_SUBREAPER, 1);
+ const pid_t app = fork();
+ if (app < 0) {
+ return 127;
+ }
+ if (app == 0) {
+ execvp(argv[0], argv);
+ _exit(127);
+ }
+ int code = 0;
+ for (;;) {
+ int wstatus = 0;
+ const pid_t done = wait(&wstatus);
+ if (done < 0) {
+ if (errno == EINTR) {
+ continue;
+ }
+ break;
+ }
+ if (done == app) {
+ code = WIFEXITED(wstatus) ? WEXITSTATUS(wstatus) : 128 + WTERMSIG(wstatus);
+ }
+ }
+ return code;
+}
+
+int main(int argc, char *argv[])
+{
+ if (argc > 3 && std::strcmp(argv[1], "--reap") == 0 && std::strcmp(argv[2], "--") == 0) {
+ return reap(argv + 3);
+ }
+ QCoreApplication app(argc, argv);
+ app.setApplicationName(QStringLiteral("wildos-safebox"));
+ const QStringList arguments = app.arguments();
+ if (arguments.size() != 2 || arguments.at(1).startsWith(QLatin1Char('-'))) {
+ std::fprintf(stderr, "usage: wildos-safebox FILE\n");
+ return 2;
+ }
+ const QFileInfo file(arguments.at(1));
+ const SafeBoxPlan plan = safeBoxPlan(file.absoluteFilePath());
+ if (!plan.ok) {
+ return fail(plan.message);
+ }
+
+ const QString home = QDir::homePath();
+ const QString runtime = QStringLiteral("/run/user/%1").arg(getuid());
+ QString wayland = qEnvironmentVariable("WAYLAND_DISPLAY", QStringLiteral("wayland-0"));
+ if (!wayland.startsWith(QLatin1Char('/'))) {
+ wayland = qEnvironmentVariable("XDG_RUNTIME_DIR", runtime) + QLatin1Char('/') + wayland;
+ }
+ if (!QFileInfo::exists(wayland)) {
+ return fail(QStringLiteral("The safe box needs the desktop's Wayland display, and it isn't there."));
+ }
+
+ // The file inside: a program is copied into the box, so it can be made
+ // runnable there without touching the original; a document is put there
+ // read-only, so the app can read it and nothing can change it.
+ const QString inside = home + QLatin1Char('/') + file.fileName();
+ int programFd = -1;
+ if (plan.program) {
+ programFd = open(QFile::encodeName(file.absoluteFilePath()).constData(), O_RDONLY | O_CLOEXEC);
+ if (programFd < 0) {
+ return fail(QStringLiteral("%1 can't be read.").arg(file.fileName()));
+ }
+ }
+
+ QStringList command;
+ if (plan.program) {
+ command << inside;
+ } else {
+ KIO::DesktopExecParser parser(*plan.app, {QUrl::fromLocalFile(inside)});
+ command = parser.resultingArguments();
+ if (command.isEmpty()) {
+ return fail(QStringLiteral("%1 can't be started in the safe box.").arg(plan.appName));
+ }
+ // Chromium-based apps build their own sandbox from user namespaces
+ // or a setuid helper, neither of which the box allows, and refuse to
+ // start without it. The box is the sandbox here.
+ const QString program = QFileInfo(command.first()).fileName();
+ if (program.contains(QLatin1String("brave")) || program.contains(QLatin1String("chrom")) || program.contains(QLatin1String("electron"))) {
+ command.insert(1, QStringLiteral("--no-sandbox"));
+ }
+ }
+
+ const int seccomp = seccompFilter();
+ if (seccomp < 0) {
+ return fail(QStringLiteral("The safe box's system call filter couldn't be set up."));
+ }
+ int status[2];
+ if (pipe2(status, O_CLOEXEC) != 0) {
+ return fail(QStringLiteral("The safe box couldn't be set up."));
+ }
+
+ QStringList args{
+ QStringLiteral("--unshare-all"),
+ QStringLiteral("--unshare-user"),
+ QStringLiteral("--disable-userns"),
+ QStringLiteral("--die-with-parent"),
+ QStringLiteral("--new-session"),
+ QStringLiteral("--cap-drop"), QStringLiteral("ALL"),
+ QStringLiteral("--hostname"), QStringLiteral("safe-box"),
+ QStringLiteral("--ro-bind"), QStringLiteral("/usr"), QStringLiteral("/usr"),
+ QStringLiteral("--ro-bind"), QStringLiteral("/etc"), QStringLiteral("/etc"),
+ QStringLiteral("--ro-bind-try"), QStringLiteral("/opt"), QStringLiteral("/opt"),
+ QStringLiteral("--proc"), QStringLiteral("/proc"),
+ QStringLiteral("--dev"), QStringLiteral("/dev"),
+ QStringLiteral("--tmpfs"), QStringLiteral("/tmp"),
+ QStringLiteral("--tmpfs"), QStringLiteral("/run"),
+ QStringLiteral("--dir"), QStringLiteral("/var"),
+ QStringLiteral("--tmpfs"), QStringLiteral("/var/tmp"),
+ QStringLiteral("--ro-bind-try"), QStringLiteral("/var/cache/fontconfig"), QStringLiteral("/var/cache/fontconfig"),
+ QStringLiteral("--dir"), runtime,
+ QStringLiteral("--chmod"), QStringLiteral("0700"), runtime,
+ QStringLiteral("--ro-bind"), wayland, runtime + QStringLiteral("/wayland-0"),
+ QStringLiteral("--tmpfs"), home,
+ QStringLiteral("--chmod"), QStringLiteral("0700"), home,
+ };
+ for (const char *top : {"/bin", "/sbin", "/lib", "/lib64", "/lib32", "/libx32"}) {
+ hostLinkOrDir(args, QString::fromLatin1(top));
+ }
+ if (plan.program) {
+ args << QStringLiteral("--perms") << QStringLiteral("0700") << QStringLiteral("--file") << QString::number(programFd) << inside;
+ } else {
+ args << QStringLiteral("--ro-bind") << file.absoluteFilePath() << inside;
+ }
+ args << QStringLiteral("--chdir") << home;
+
+ // Only what an app needs to draw itself in the person's language and
+ // look; nothing that points at the session's services.
+ args << QStringLiteral("--clearenv");
+ const auto setenv = [&args](const QString &name, const QString &value) {
+ args << QStringLiteral("--setenv") << name << value;
+ };
+ for (const char *name : {"LANG", "LANGUAGE", "LC_ALL", "LC_CTYPE", "LC_NUMERIC", "LC_TIME", "LC_COLLATE", "LC_MONETARY", "LC_MESSAGES",
+ "LC_PAPER", "LC_NAME", "LC_ADDRESS", "LC_TELEPHONE", "LC_MEASUREMENT", "XDG_CURRENT_DESKTOP", "KDE_FULL_SESSION",
+ "KDE_SESSION_VERSION", "QT_QPA_PLATFORMTHEME", "QT_STYLE_OVERRIDE", "XDG_DATA_DIRS", "XDG_CONFIG_DIRS", "TZ",
+ "XCURSOR_THEME", "XCURSOR_SIZE", "QT_SCALE_FACTOR", "QT_SCREEN_SCALE_FACTORS", "GDK_SCALE"}) {
+ if (qEnvironmentVariableIsSet(name)) {
+ setenv(QString::fromLatin1(name), qEnvironmentVariable(name));
+ }
+ }
+ setenv(QStringLiteral("HOME"), home);
+ setenv(QStringLiteral("USER"), qEnvironmentVariable("USER"));
+ setenv(QStringLiteral("LOGNAME"), qEnvironmentVariable("USER"));
+ setenv(QStringLiteral("PATH"), QStringLiteral("/usr/local/bin:/usr/bin:/bin"));
+ setenv(QStringLiteral("TMPDIR"), QStringLiteral("/tmp"));
+ setenv(QStringLiteral("XDG_RUNTIME_DIR"), runtime);
+ setenv(QStringLiteral("WAYLAND_DISPLAY"), QStringLiteral("wayland-0"));
+ setenv(QStringLiteral("XDG_SESSION_TYPE"), QStringLiteral("wayland"));
+ setenv(QStringLiteral("QT_QPA_PLATFORM"), QStringLiteral("wayland"));
+ setenv(QStringLiteral("GDK_BACKEND"), QStringLiteral("wayland"));
+ setenv(QStringLiteral("SDL_VIDEODRIVER"), QStringLiteral("wayland"));
+ setenv(QStringLiteral("MOZ_ENABLE_WAYLAND"), QStringLiteral("1"));
+ setenv(QStringLiteral("ELECTRON_OZONE_PLATFORM_HINT"), QStringLiteral("wayland"));
+ // There are no graphics devices in the box, so drawing is done in
+ // software.
+ setenv(QStringLiteral("LIBGL_ALWAYS_SOFTWARE"), QStringLiteral("1"));
+ // AppImages normally mount themselves with FUSE, which the box has no
+ // device for; this unpacks them into the box's memory instead.
+ setenv(QStringLiteral("APPIMAGE_EXTRACT_AND_RUN"), QStringLiteral("1"));
+ // LibreOffice's KDE integration needs the session's D-Bus and falls
+ // back to X11, which the box has neither of; its plain Qt one draws on
+ // Wayland.
+ setenv(QStringLiteral("SAL_USE_VCLPLUGIN"), QStringLiteral("qt6"));
+ // The same for Electron apps, AppImages included.
+ setenv(QStringLiteral("ELECTRON_DISABLE_SANDBOX"), QStringLiteral("1"));
+ // The accessibility bus is D-Bus, which the box has none of.
+ setenv(QStringLiteral("NO_AT_BRIDGE"), QStringLiteral("1"));
+
+ args << QStringLiteral("--seccomp") << QString::number(seccomp);
+ args << QStringLiteral("--json-status-fd") << QString::number(status[1]);
+ args << QStringLiteral("--") << QStringLiteral("/usr/bin/wildos-safebox") << QStringLiteral("--reap") << QStringLiteral("--") << command;
+
+ QList<QByteArray> encoded;
+ encoded << QByteArrayLiteral("bwrap");
+ for (const QString &arg : std::as_const(args)) {
+ encoded << QFile::encodeName(arg);
+ }
+ std::vector<char *> argvOut;
+ for (QByteArray &a : encoded) {
+ argvOut.push_back(a.data());
+ }
+ argvOut.push_back(nullptr);
+
+ const time_t started = time(nullptr);
+ const pid_t child = fork();
+ if (child < 0) {
+ return fail(QStringLiteral("The safe box couldn't be set up."));
+ }
+ if (child == 0) {
+ // bwrap reads these by number, so they must survive exec.
+ fcntl(seccomp, F_SETFD, 0);
+ fcntl(status[1], F_SETFD, 0);
+ if (programFd >= 0) {
+ fcntl(programFd, F_SETFD, 0);
+ }
+ execvp("/usr/bin/bwrap", argvOut.data());
+ _exit(127);
+ }
+ close(status[1]);
+ close(seccomp);
+ if (programFd >= 0) {
+ close(programFd);
+ }
+
+ // bwrap reports {"child-pid": N} once the app is running inside, and
+ // its exit code when it ends. No child-pid means the box never opened.
+ QByteArray report;
+ char buffer[512];
+ ssize_t got;
+ while ((got = read(status[0], buffer, sizeof buffer)) > 0 || (got < 0 && errno == EINTR)) {
+ if (got > 0) {
+ report.append(buffer, got);
+ }
+ }
+ close(status[0]);
+ int wstatus = 0;
+ while (waitpid(child, &wstatus, 0) < 0 && errno == EINTR) {
+ }
+ const int code = WIFEXITED(wstatus) ? WEXITSTATUS(wstatus) : 128 + WTERMSIG(wstatus);
+ if (!report.contains("child-pid")) {
+ return fail(QStringLiteral("Wild OS couldn't make the sealed space for it."));
+ }
+ // An app that closes at once with an error most likely needs something
+ // the box keeps out, such as the network or its own sandbox.
+ if (code != 0 && time(nullptr) - started < 4) {
+ notify(QStringLiteral("%1 closed straight away").arg(plan.appName),
+ QStringLiteral("It may need something the safe box keeps out, such as the internet."));
+ }
+ return code;
+}
diff --git a/packages/wildos-files/src/safeboxplan.cpp b/packages/wildos-files/src/safeboxplan.cpp
new file mode 100644
index 0000000..a0acd6b
--- /dev/null
+++ b/packages/wildos-files/src/safeboxplan.cpp
@@ -0,0 +1,78 @@
+#include "safeboxplan.h"
+
+#include "programs.h"
+
+#include <KApplicationTrader>
+#include <QFileInfo>
+#include <QMimeDatabase>
+#include <QUrl>
+
+namespace
+{
+bool runsInBox(const KService::Ptr &service)
+{
+ if (!service || service->noDisplay()) {
+ return false;
+ }
+ const QString exec = service->exec();
+ const QString program = exec.section(QLatin1Char(' '), 0, 0);
+ if (program.endsWith(QLatin1String("flatpak")) || service->property<QString>(QStringLiteral("X-Flatpak")).length() > 0) {
+ return false;
+ }
+ // App Bridge's Windows programs and Windows mode itself live in the
+ // Windows virtual PC, which a box can't reach.
+ if (service->storageId().startsWith(QLatin1String("wildos-winapp-")) || program.endsWith(QLatin1String("wild-run"))
+ || program.endsWith(QLatin1String("wildos-winmode"))) {
+ return false;
+ }
+ // Something that only opens a terminal has no window of its own here.
+ return !service->terminal();
+}
+}
+
+SafeBoxPlan safeBoxPlan(const QString &path)
+{
+ SafeBoxPlan plan;
+ const QFileInfo info(path);
+ if (!info.isFile()) {
+ plan.message = QStringLiteral("Only files can open in the safe box.");
+ return plan;
+ }
+ const QMimeType type = QMimeDatabase().mimeTypeForFile(info);
+ if (type.inherits(QStringLiteral("application/x-ms-dos-executable")) || type.inherits(QStringLiteral("application/x-msi"))
+ || type.inherits(QStringLiteral("application/x-msdownload")) || type.inherits(QStringLiteral("application/vnd.microsoft.portable-executable"))) {
+ plan.message = QStringLiteral("Windows programs can't run in the safe box.");
+ return plan;
+ }
+ if (isLinuxProgram(QUrl::fromLocalFile(info.absoluteFilePath()), type)) {
+ const quint16 machine = elfMachine(info.absoluteFilePath());
+ if (machine != 0 && hostMachine != 0 && machine != hostMachine) {
+ plan.message = QStringLiteral("%1 is made for a different type of processor, so it cannot run on this PC.").arg(info.fileName());
+ return plan;
+ }
+ plan.ok = true;
+ plan.program = true;
+ plan.appName = info.completeBaseName();
+ return plan;
+ }
+ const KService::Ptr preferred = KApplicationTrader::preferredService(type.name());
+ if (runsInBox(preferred)) {
+ plan.app = preferred;
+ } else {
+ const auto services = KApplicationTrader::queryByMimeType(type.name());
+ for (const KService::Ptr &service : services) {
+ if (runsInBox(service)) {
+ plan.app = service;
+ break;
+ }
+ }
+ }
+ if (!plan.app) {
+ plan.message = preferred ? QStringLiteral("%1 can't run in the safe box, and no other app opens this kind of file.").arg(preferred->name())
+ : QStringLiteral("No app opens this kind of file.");
+ return plan;
+ }
+ plan.ok = true;
+ plan.appName = plan.app->name();
+ return plan;
+}
diff --git a/packages/wildos-files/src/safeboxplan.h b/packages/wildos-files/src/safeboxplan.h
new file mode 100644
index 0000000..63d880e
--- /dev/null
+++ b/packages/wildos-files/src/safeboxplan.h
@@ -0,0 +1,20 @@
+#pragma once
+
+#include <KService>
+#include <QString>
+
+// What "Open in safe box" would do with a file: run it, when it is a Linux
+// program, or open it in the app that opens it on a double click. Apps that
+// bring their own sandbox (Flatpak) or need Windows mode can't run inside
+// one, so the next app for the type is taken, or the file is turned down
+// with a sentence saying why. Shared by Files, which decides whether to
+// offer it, and wildos-safebox, which does it.
+struct SafeBoxPlan {
+ bool ok = false;
+ bool program = false;
+ QString message;
+ KService::Ptr app;
+ QString appName;
+};
+
+SafeBoxPlan safeBoxPlan(const QString &path);
diff --git a/packages/wildos-installer/debian/changelog b/packages/wildos-installer/debian/changelog
index fd0319f..a2be975 100644
--- a/packages/wildos-installer/debian/changelog
+++ b/packages/wildos-installer/debian/changelog
@@ -1,3 +1,49 @@
+wildos-installer (0.1.11) trixie; urgency=medium
+
+ * The keyboard search finds layouts by country, language and key order
+ too: Belgium or AZERTY find Belgian.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 12:20:00 +0000
+
+wildos-installer (0.1.10) trixie; urgency=medium
+
+ * The disk password and account password boxes take only what is typed:
+ nothing can be pasted into them.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 09:45:00 +0000
+
+wildos-installer (0.1.9) trixie; urgency=medium
+
+ * Encrypted installs get TRIM and the faster encryption settings.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 17:15:00 +0000
+
+wildos-installer (0.1.8) trixie; urgency=medium
+
+ * Closing the installer before the install starts no longer ends on a
+ crash report.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 17:00:00 +0000
+
+wildos-installer (0.1.7) trixie; urgency=medium
+
+ * The first step is a licence page: Wild OS is free software under the
+ GNU GPL with no warranty, its makers are not liable, and the box must
+ be ticked to go on. The full licence opens at sections 15 and 16 and
+ can be saved. Quit leaves the PC untouched.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 12:00:00 +0000
+
+wildos-installer (0.1.6) trixie; urgency=medium
+
+ * The install page says when a step is still working and for how long,
+ with the bar gently pulsing, instead of sitting on one number. The
+ bar's shares follow the time each step takes.
+ * The install keeps its own log in /var/log/wildos-install.log, readable
+ only by the administrator.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 11:00:00 +0000
+
wildos-installer (0.1.5) trixie; urgency=medium
* Remove everything no longer asks to remove a USB stick or mentions a trial.
diff --git a/packages/wildos-installer/debian/control b/packages/wildos-installer/debian/control
index a7755ed..ad9ae4e 100644
--- a/packages/wildos-installer/debian/control
+++ b/packages/wildos-installer/debian/control
@@ -29,7 +29,7 @@ Depends:
qml6-module-qtquick-window,
wildos-fonts,
wildos-branding,
- wildos-ui (>= 0.1.6),
+ wildos-ui (>= 0.1.12),
Description: Wild OS installer
Calamares configuration, branding and helper scripts that install Wild OS
from the live session to disk, with full disk encryption and a recovery
diff --git a/packages/wildos-installer/debian/rules b/packages/wildos-installer/debian/rules
index 2222d4e..43d2bb8 100644
--- a/packages/wildos-installer/debian/rules
+++ b/packages/wildos-installer/debian/rules
@@ -9,3 +9,4 @@ execute_after_dh_fixperms:
chmod 0755 debian/wildos-installer/usr/bin/install-wildos
chmod 0755 debian/wildos-installer/usr/libexec/wildos-installer/*
chmod 0755 debian/wildos-installer/usr/share/wildos-installer/modules/wildosrecovery/main.py
+ chmod 0755 debian/wildos-installer/usr/share/wildos-installer/modules/wildoslicence/main.py
diff --git a/packages/wildos-installer/files/calamares/branding/wildos/LicenceWindow.qml b/packages/wildos-installer/files/calamares/branding/wildos/LicenceWindow.qml
new file mode 100644
index 0000000..20556e3
--- /dev/null
+++ b/packages/wildos-installer/files/calamares/branding/wildos/LicenceWindow.qml
@@ -0,0 +1,369 @@
+/* The full licence (InstallerLicenceFull.dc), opened by "Read the full
+ * licence". The text is the system's own copy of the GPL, read at run time
+ * and shown word for word in English whatever the installer's language,
+ * because the licence only allows verbatim copies. It opens on section 15
+ * with 15 and 16, warranty and liability, outlined.
+ *
+ * A window over the whole screen, so it can dim the installer sheet behind
+ * it the way the board does.
+ */
+import QtQuick
+import QtQuick.Layouts
+import QtQuick.Window
+import QtQuick.Templates as T
+import WildOS.Installer
+import WildOS.UI as UI
+
+Window {
+ id: win
+
+ readonly property var sections: Installer.licenceSections()
+ readonly property var numbered: sections.filter(function(s) { return s.number >= 0; })
+ // The section whose text is at the top of the view.
+ property int current: 15
+ property bool jumping: false
+ property string saveProblem: ""
+ readonly property color amber: "#f5c27a"
+
+ function openAtWarranty() {
+ x = screen.virtualX;
+ y = screen.virtualY;
+ width = screen.width;
+ height = screen.height;
+ saveProblem = "";
+ show();
+ raise();
+ requestActivate();
+ // After the first layout, or the list has no height to jump in.
+ Qt.callLater(jumpTo, 15);
+ }
+
+ function jumpTo(number) {
+ for (var i = 0; i < sections.length; ++i) {
+ if (sections[i].number === number) {
+ jumping = true;
+ current = number;
+ text.positionViewAtIndex(i, ListView.Beginning);
+ // Keep the list's top margin above the section, as at the start.
+ scrollTo(text.contentY - text.topMargin);
+ jumping = false;
+ return;
+ }
+ }
+ }
+
+ function scrollTo(y) {
+ var top = text.originY - text.topMargin;
+ var bottom = text.originY + text.contentHeight + text.bottomMargin - text.height;
+ text.contentY = Math.max(top, Math.min(y, Math.max(top, bottom)));
+ }
+
+ // Window-wide, so the keys scroll the text whatever has the focus.
+ Shortcut {
+ sequences: [StandardKey.MoveToNextPage]
+ onActivated: win.scrollTo(text.contentY + text.height - 60)
+ }
+ Shortcut {
+ sequences: [StandardKey.MoveToPreviousPage]
+ onActivated: win.scrollTo(text.contentY - text.height + 60)
+ }
+ Shortcut {
+ sequences: [StandardKey.MoveToStartOfDocument, "Home"]
+ onActivated: win.scrollTo(text.originY - text.topMargin)
+ }
+ Shortcut {
+ sequences: [StandardKey.MoveToEndOfDocument, "End"]
+ onActivated: win.scrollTo(text.originY + text.contentHeight)
+ }
+
+ flags: Qt.Dialog | Qt.FramelessWindowHint
+ modality: Qt.ApplicationModal
+ color: "transparent"
+ title: qsTr("GNU General Public License")
+
+ Shortcut {
+ sequences: [StandardKey.Cancel]
+ onActivated: win.close()
+ }
+
+ // The installer sheet, dimmed. Clicks on it go nowhere.
+ Rectangle {
+ anchors.centerIn: parent
+ width: 1040
+ height: 720
+ radius: UI.Style.radiusXl
+ color: Qt.rgba(0, 0, 0, 0.6)
+ MouseArea { anchors.fill: parent }
+ }
+
+ Rectangle {
+ id: dialog
+ anchors.centerIn: parent
+ width: 860
+ height: 600
+ radius: UI.Style.radiusLg
+ color: "#222428"
+ border.width: 1
+ border.color: UI.Style.borderDialog
+ Accessible.role: Accessible.Dialog
+ Accessible.name: qsTr("GNU General Public License, version 3")
+
+ ColumnLayout {
+ anchors.fill: parent
+ anchors.margins: 1
+ spacing: 0
+
+ RowLayout {
+ Layout.fillWidth: true
+ Layout.preferredHeight: 55
+ Layout.leftMargin: 21
+ Layout.rightMargin: 21
+ spacing: 12
+
+ Text {
+ text: qsTr("GNU General Public License")
+ color: UI.Style.ink
+ font.family: UI.Style.fontFamily
+ font.letterSpacing: UI.Style.tracking(15)
+ font.pixelSize: 15
+ font.weight: UI.Style.weightSemiBold
+ }
+ Text {
+ text: qsTr("Version 3, 29 June 2007")
+ color: UI.Style.inkMuted
+ font.family: UI.Style.fontFamily
+ font.letterSpacing: UI.Style.tracking(13)
+ font.pixelSize: 13
+ }
+ Item { Layout.fillWidth: true }
+ Text {
+ text: qsTr("The full, unchanged text. In English only.")
+ color: UI.Style.inkMuted
+ font.family: UI.Style.fontFamily
+ font.letterSpacing: UI.Style.tracking(12)
+ font.pixelSize: 12
+ }
+ }
+
+ Rectangle {
+ Layout.fillWidth: true
+ height: 1
+ color: Qt.rgba(1, 1, 1, 0.08)
+ }
+
+ RowLayout {
+ Layout.fillWidth: true
+ Layout.fillHeight: true
+ spacing: 0
+
+ // Contents: the numbered sections, each a jump.
+ Rectangle {
+ Layout.preferredWidth: 250
+ Layout.fillHeight: true
+ color: "#1a1c20"
+
+ ListView {
+ id: contents
+ anchors.fill: parent
+ anchors.topMargin: 14
+ anchors.bottomMargin: 14
+ anchors.leftMargin: 12
+ anchors.rightMargin: 12
+ clip: true
+ spacing: 2
+ boundsBehavior: Flickable.StopAtBounds
+ model: win.numbered
+ currentIndex: win.numbered.findIndex(function(s) { return s.number === win.current; })
+ onCurrentIndexChanged: if (currentIndex >= 0) positionViewAtIndex(currentIndex, ListView.Contain)
+ T.ScrollBar.vertical: UI.ScrollBar {}
+
+ delegate: T.AbstractButton {
+ id: entry
+ required property var modelData
+ readonly property bool isCurrent: modelData.number === win.current
+
+ width: ListView.view.width
+ height: 30
+ hoverEnabled: true
+ focusPolicy: Qt.StrongFocus
+ Accessible.role: Accessible.Link
+ Accessible.name: modelData.number + ". " + modelData.title
+ onClicked: win.jumpTo(modelData.number)
+
+ background: Rectangle {
+ radius: 6
+ color: entry.isCurrent ? Qt.rgba(1, 1, 1, 0.09)
+ : entry.hovered ? Qt.rgba(1, 1, 1, 0.05) : "transparent"
+ border.width: entry.visualFocus ? 2 : 0
+ border.color: "#8fb4ff"
+ }
+ contentItem: RowLayout {
+ spacing: 8
+ Text {
+ Layout.leftMargin: 10
+ Layout.preferredWidth: 18
+ horizontalAlignment: Text.AlignRight
+ text: entry.modelData.number
+ color: UI.Style.inkSubtle
+ font.family: UI.Style.fontFamily
+ font.pixelSize: 12
+ font.features: { "tnum": 1 }
+ }
+ Text {
+ Layout.fillWidth: true
+ Layout.rightMargin: 10
+ text: entry.modelData.title
+ elide: Text.ElideRight
+ textFormat: Text.PlainText
+ color: entry.isCurrent ? UI.Style.ink : UI.Style.inkMuted
+ font.family: UI.Style.fontFamily
+ font.letterSpacing: UI.Style.tracking(12)
+ font.pixelSize: 12
+ font.weight: entry.isCurrent ? UI.Style.weightSemiBold : UI.Style.weightRegular
+ }
+ }
+ }
+ }
+
+ Rectangle {
+ anchors.top: parent.top
+ anchors.bottom: parent.bottom
+ anchors.right: parent.right
+ width: 1
+ color: Qt.rgba(1, 1, 1, 0.07)
+ }
+ }
+
+ ListView {
+ id: text
+ Layout.fillWidth: true
+ Layout.fillHeight: true
+ clip: true
+ focus: true
+ spacing: 14
+ topMargin: 18
+ bottomMargin: 18
+ // Every section is built up front, so jumps land exactly.
+ cacheBuffer: 1000000
+ boundsBehavior: Flickable.StopAtBounds
+ model: win.sections
+ T.ScrollBar.vertical: UI.ScrollBar {}
+
+ onContentYChanged: {
+ if (win.jumping)
+ return;
+ var i = indexAt(40, contentY + topMargin + 4);
+ // The title page and preamble light no entry.
+ if (i >= 0)
+ win.current = win.sections[i].number;
+ }
+
+
+ delegate: Item {
+ id: section
+ required property var modelData
+ readonly property bool outlined: modelData.number === 15 || modelData.number === 16
+
+ width: ListView.view.width
+ height: box.height
+
+ Rectangle {
+ id: box
+ x: 22
+ width: parent.width - 50
+ height: paragraphs.implicitHeight + (section.outlined ? 28 : 0)
+ radius: 10
+ color: section.outlined ? Qt.rgba(245 / 255, 194 / 255, 122 / 255, 0.07) : "transparent"
+ border.width: section.outlined ? 1 : 0
+ border.color: Qt.rgba(245 / 255, 194 / 255, 122 / 255, 0.28)
+
+ ColumnLayout {
+ id: paragraphs
+ x: section.outlined ? 16 : 0
+ y: section.outlined ? 14 : 0
+ width: box.width - 2 * x
+ spacing: 10
+
+ Repeater {
+ model: section.modelData.paragraphs
+ Text {
+ required property string modelData
+ required property int index
+ readonly property bool heading: index === 0 && section.modelData.number >= 0
+
+ Layout.fillWidth: true
+ text: modelData
+ textFormat: Text.PlainText
+ wrapMode: Text.Wrap
+ color: heading || section.outlined ? UI.Style.ink : UI.Style.inkMuted
+ font.family: UI.Style.fontFamily
+ font.letterSpacing: UI.Style.tracking(heading ? 14 : 13)
+ font.pixelSize: heading ? 14 : 13
+ font.weight: heading ? UI.Style.weightSemiBold : UI.Style.weightRegular
+ lineHeight: heading ? 1 : 1.62
+ }
+ }
+ }
+ }
+ }
+
+ Text {
+ anchors.centerIn: parent
+ width: parent.width - 80
+ visible: win.sections.length === 0
+ text: qsTr("The licence file is missing from this system. The GNU General Public License is at gnu.org/licenses/gpl-3.0.")
+ horizontalAlignment: Text.AlignHCenter
+ wrapMode: Text.WordWrap
+ color: UI.Style.inkMuted
+ font.family: UI.Style.fontFamily
+ font.pixelSize: 13
+ }
+ }
+ }
+
+ Rectangle {
+ Layout.fillWidth: true
+ Layout.preferredHeight: 60
+ color: Qt.rgba(1, 1, 1, 0.03)
+ bottomLeftRadius: UI.Style.radiusLg - 1
+ bottomRightRadius: UI.Style.radiusLg - 1
+
+ Rectangle {
+ anchors.top: parent.top
+ anchors.left: parent.left
+ anchors.right: parent.right
+ height: 1
+ color: Qt.rgba(1, 1, 1, 0.08)
+ }
+
+ RowLayout {
+ anchors.fill: parent
+ anchors.leftMargin: 21
+ anchors.rightMargin: 21
+ spacing: 10
+
+ Text {
+ Layout.fillWidth: true
+ text: win.saveProblem !== "" ? win.saveProblem
+ : qsTr("Sections 15 and 16 cover warranty and liability. A copy is installed with Wild OS.")
+ elide: Text.ElideRight
+ color: win.saveProblem !== "" ? win.amber : UI.Style.inkMuted
+ font.family: UI.Style.fontFamily
+ font.letterSpacing: UI.Style.tracking(12)
+ font.pixelSize: 12
+ }
+ UI.Button {
+ text: qsTr("Save a copy")
+ enabled: win.sections.length > 0
+ onClicked: win.saveProblem = Installer.saveLicence(win)
+ }
+ UI.Button {
+ kind: "primary"
+ text: qsTr("Close")
+ onClicked: win.close()
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/packages/wildos-installer/files/calamares/branding/wildos/WField.qml b/packages/wildos-installer/files/calamares/branding/wildos/WField.qml
index b9e7256..896f64b 100644
--- a/packages/wildos-installer/files/calamares/branding/wildos/WField.qml
+++ b/packages/wildos-installer/files/calamares/branding/wildos/WField.qml
@@ -35,6 +35,7 @@ ColumnLayout {
size: "large"
error: field.error !== ""
revealable: field.echoMode === TextInput.Password
+ UI.NoPaste { enabled: field.echoMode === TextInput.Password }
Accessible.name: field.label
}
diff --git a/packages/wildos-installer/files/calamares/branding/wildos/calamares-navigation.qml b/packages/wildos-installer/files/calamares/branding/wildos/calamares-navigation.qml
index c2d494f..535a83c 100644
--- a/packages/wildos-installer/files/calamares/branding/wildos/calamares-navigation.qml
+++ b/packages/wildos-installer/files/calamares/branding/wildos/calamares-navigation.qml
@@ -17,14 +17,21 @@ Item {
height: 76
readonly property int current: ViewManager.currentStepIndex
- readonly property int checksStep: 0
- readonly property int keyboardStep: 2
- readonly property int diskStep: 3
- readonly property int encryptionStep: 4
- readonly property int summaryStep: 5
- readonly property int installStep: 6
+ readonly property int licenceStep: 0
+ readonly property int checksStep: 1
+ readonly property int keyboardStep: 3
+ readonly property int diskStep: 4
+ readonly property int encryptionStep: 5
+ readonly property int summaryStep: 6
+ readonly property int installStep: 7
readonly property bool installing: current === installStep
readonly property bool atEnd: current > installStep
+
+ Binding {
+ target: Installer
+ property: "exitQuickly"
+ value: footer.current < footer.installStep
+ }
readonly property bool failed: Installer.finished ? Installer.finished.failed : false
// The disk step has two pages; the editor's note differs. Global storage
// has no change signal QML can safely use, so this looks while there.
@@ -48,6 +55,8 @@ Item {
readonly property string note: {
switch (current) {
+ case licenceStep:
+ return qsTr("Nothing on this PC has changed yet.");
case checksStep:
return Installer.alongsideBlocked !== "" ? qsTr("You can still replace Windows completely without changing anything.") : "";
case keyboardStep:
@@ -100,10 +109,19 @@ Item {
onClicked: Installer.runChecks()
}
+ // Nothing has been chosen yet, so Quit closes without asking.
+ WButton {
+ text: qsTr("Quit")
+ visible: footer.current === footer.licenceStep
+ onClicked: Installer.quitNow()
+ }
+
WButton {
text: qsTr("Back")
- visible: ViewManager.backAndNextVisible && footer.current > 0 && footer.current < footer.installStep
- enabled: ViewManager.backEnabled
+ visible: ViewManager.backAndNextVisible && footer.current > footer.licenceStep && footer.current < footer.installStep
+ // Calamares' welcome step always refuses Back, because it expects
+ // to be first; here the licence comes before it.
+ enabled: ViewManager.backEnabled || footer.current === footer.checksStep
onClicked: ViewManager.back()
}
@@ -112,6 +130,7 @@ Item {
text: ViewManager.nextIcon === "run-install" ? qsTr("Install") : qsTr("Continue")
visible: ViewManager.backAndNextVisible && footer.current < footer.installStep
enabled: ViewManager.nextEnabled
+ && (footer.current !== footer.licenceStep || Installer.licenceAccepted)
&& (footer.current !== footer.encryptionStep || Installer.encryptionReady)
&& (footer.current !== footer.checksStep || !Installer.checking)
onClicked: ViewManager.next()
diff --git a/packages/wildos-installer/files/calamares/branding/wildos/calamares-sidebar.qml b/packages/wildos-installer/files/calamares/branding/wildos/calamares-sidebar.qml
index 28c552e..b999713 100644
--- a/packages/wildos-installer/files/calamares/branding/wildos/calamares-sidebar.qml
+++ b/packages/wildos-installer/files/calamares/branding/wildos/calamares-sidebar.qml
@@ -2,9 +2,9 @@
*
* Calamares has one entry per module, more than people need to see, so
* several modules share a step here. The ranges follow the sequence in
- * settings.conf and must change with it: welcomeq and localeq (no page),
- * keyboardq, partition, notesqml@encryption, then summaryq, the install
- * itself and finishedq.
+ * settings.conf and must change with it: notesqml@licence, welcomeq and
+ * localeq (no page), keyboardq, partition, notesqml@encryption, then
+ * summaryq, the install itself and finishedq.
*/
import io.calamares.ui 1.0
import io.calamares.core 1.0
@@ -26,16 +26,17 @@ Rectangle {
bottomLeftRadius: 20
readonly property int current: ViewManager.currentStepIndex
- readonly property int diskStep: 3
- readonly property int encryptionStep: 4
- readonly property int installStep: 6
- readonly property int finishedStep: 7
+ readonly property int diskStep: 4
+ readonly property int encryptionStep: 5
+ readonly property int installStep: 7
+ readonly property int finishedStep: 8
readonly property var steps: [
- { label: qsTr("Before we start"), first: 0, last: 1 },
- { label: qsTr("Keyboard"), first: 2, last: 2 },
- { label: qsTr("Where to install"), first: 3, last: 3 },
- { label: qsTr("Encryption"), first: 4, last: 4 },
- { label: qsTr("Install"), first: 5, last: 7 }
+ { label: qsTr("Licence"), first: 0, last: 0 },
+ { label: qsTr("Before we start"), first: 1, last: 2 },
+ { label: qsTr("Keyboard"), first: 3, last: 3 },
+ { label: qsTr("Where to install"), first: 4, last: 4 },
+ { label: qsTr("Encryption"), first: 5, last: 5 },
+ { label: qsTr("Install"), first: 6, last: 8 }
]
Rectangle {
diff --git a/packages/wildos-installer/files/calamares/branding/wildos/encryption.qml b/packages/wildos-installer/files/calamares/branding/wildos/encryption.qml
index 9baa243..88aae42 100644
--- a/packages/wildos-installer/files/calamares/branding/wildos/encryption.qml
+++ b/packages/wildos-installer/files/calamares/branding/wildos/encryption.qml
@@ -73,6 +73,7 @@ WPage {
Layout.fillWidth: true
label: qsTr("Disk password")
echoMode: TextInput.Password
+ UI.NoPaste {}
}
RowLayout {
spacing: 8
@@ -112,6 +113,7 @@ WPage {
Layout.fillWidth: true
label: qsTr("Type it again")
echoMode: TextInput.Password
+ UI.NoPaste {}
}
RowLayout {
spacing: 6
diff --git a/packages/wildos-installer/files/calamares/branding/wildos/keyboardq.qml b/packages/wildos-installer/files/calamares/branding/wildos/keyboardq.qml
index 6942a24..653ea3f 100644
--- a/packages/wildos-installer/files/calamares/branding/wildos/keyboardq.qml
+++ b/packages/wildos-installer/files/calamares/branding/wildos/keyboardq.qml
@@ -31,6 +31,26 @@ WPage {
// Layouts for languages whose keyboard is not named after the country
// or the language code.
+ // What people search for besides a layout's name: its countries,
+ // languages and the letter order on the keys ("Belgium" or "AZERTY"
+ // find Belgian). Settings gets these from xkeyboard-config itself.
+ readonly property var searchWords: ({
+ "be": "belgium belgique belgie dutch flemish french german azerty",
+ "fr": "france french azerty", "ca": "canada canadian french",
+ "de": "germany deutschland german qwertz", "at": "austria german qwertz",
+ "ch": "switzerland swiss schweiz suisse german french italian qwertz",
+ "gb": "uk united kingdom britain british england scotland wales english", "ie": "ireland irish",
+ "us": "usa united states america english", "nl": "netherlands holland dutch",
+ "es": "spain espana spanish", "latam": "latin america mexico argentina colombia chile spanish",
+ "pt": "portugal portuguese", "br": "brazil brasil portuguese", "it": "italy italia italian",
+ "pl": "poland polska polish", "cz": "czechia czech republic czech qwertz", "sk": "slovakia slovak qwertz",
+ "hu": "hungary magyar hungarian qwertz", "ro": "romania romanian", "gr": "greece greek",
+ "tr": "turkey turkiye turkish", "ru": "russia russian", "ua": "ukraine ukrainian", "by": "belarus belarusian",
+ "se": "sweden swedish", "no": "norway norwegian", "dk": "denmark danish", "fi": "finland finnish",
+ "jp": "japan japanese", "kr": "korea korean", "cn": "china chinese", "tw": "taiwan chinese",
+ "in": "india hindi", "vn": "vietnam vietnamese", "ara": "arabic", "id": "indonesia indonesian"
+ })
+
readonly property var layoutFor: ({
"en": "us", "en_US": "us", "en_GB": "gb", "en_AU": "au", "en_CA": "ca", "en_IE": "ie",
"en_IN": "in", "en_NZ": "nz", "en_ZA": "za", "ast": "es", "ca": "es", "eu": "es", "gl": "es",
@@ -66,7 +86,11 @@ WPage {
var out = [];
var query = search.text.trim().toLowerCase();
var current = layouts.currentIndex;
- function matches(label) { return query === "" || label.toLowerCase().indexOf(query) >= 0; }
+ function matches(label, key) {
+ if (query === "" || label.toLowerCase().indexOf(query) >= 0)
+ return true;
+ return !!key && (key === query || (searchWords[key] || "").indexOf(query) >= 0);
+ }
function note(key, label) {
if (key === detectedKey)
return qsTr("Detected from your language");
@@ -77,12 +101,12 @@ WPage {
if (current >= 0) {
var label = cell(layouts, current, Qt.DisplayRole);
var key = cell(layouts, current, layoutKeyRole);
- if (matches(label))
+ if (matches(label, key))
out.push({ layout: current, variant: -1, label: label, note: note(key, label) });
for (var v = 0; v < variants.rowCount(); ++v) {
var vkey = cell(variants, v, variantKeyRole);
var vlabel = cell(variants, v, Qt.DisplayRole);
- if (vkey && matches(vlabel))
+ if (vkey && matches(vlabel, key))
out.push({ layout: current, variant: v, label: vlabel, note: note("", vlabel) });
}
}
@@ -91,7 +115,7 @@ WPage {
if (r === current)
continue;
var l = cell(layouts, r, Qt.DisplayRole);
- if (matches(l))
+ if (matches(l, cell(layouts, r, layoutKeyRole)))
others.push({ layout: r, variant: -1, label: l, note: "" });
}
others.sort(function(a, b) {
diff --git a/packages/wildos-installer/files/calamares/branding/wildos/licence.qml b/packages/wildos-installer/files/calamares/branding/wildos/licence.qml
new file mode 100644
index 0000000..1163ef5
--- /dev/null
+++ b/packages/wildos-installer/files/calamares/branding/wildos/licence.qml
@@ -0,0 +1,218 @@
+/* Licence (InstallerLicence.dc), a notesqml step and the first page. It says
+ * in plain words that Wild OS is GPL software with no warranty and that its
+ * makers are not liable, and the person ticks the box before going on.
+ *
+ * The tick lives in Installer.licenceAccepted, so it starts clear on every
+ * run and is still ticked after Back. Continue in the footer waits for it,
+ * and the wildoslicence job, first in the install, refuses to touch the
+ * disk unless wildosLicenceAccepted is in global storage.
+ */
+import io.calamares.core 1.0
+import io.calamares.ui 1.0
+import WildOS.Installer
+import WildOS.UI as UI
+
+import QtQuick
+import QtQuick.Layouts
+import QtQuick.Templates as T
+
+WPage {
+ id: page
+
+ readonly property color amber: "#f5c27a"
+
+ title: qsTr("Free software, with no warranty")
+ subtitle: qsTr("Wild OS is free and open source. Please read what that means before you install it.")
+ gap: 18
+
+ function store() {
+ Global.insert("wildosLicenceAccepted", Installer.licenceAccepted);
+ }
+ function onActivate() { store(); }
+ function onLeave() { store(); }
+
+ Connections {
+ target: Installer
+ function onLicenceAcceptedChanged() { page.store(); }
+ }
+
+ readonly property var rows: [
+ { title: qsTr("Yours to use, copy, change and share"),
+ body: qsTr("Wild OS is released under the GNU General Public License, version 3 or later. There is no fee and no account."),
+ icon: "M7 3h7l4 4v14H7z M14 3v4h4 M10 12h5 M10 16h5", warn: false, link: true },
+ { title: qsTr("It comes as it is, with no warranty"),
+ body: qsTr("Nobody promises that Wild OS will work on this PC, suit a particular job or be free of faults."),
+ icon: "M12 4L2.8 20h18.4L12 4z M12 10v4.5 M12 17.1v0.4", warn: true, link: false },
+ { title: qsTr("The people who make it are not liable"),
+ body: qsTr("If something goes wrong, including lost files, lost work or a PC that will not start, the Wild OS project and its contributors are not responsible, as far as the law allows."),
+ icon: "M12 4L2.8 20h18.4L12 4z M12 10v4.5 M12 17.1v0.4", warn: true, link: false },
+ { title: qsTr("Back up before you carry on"),
+ body: qsTr("Installing changes your disk. Copy anything you cannot afford to lose somewhere safe first."),
+ icon: "M6 5h12l2 9v4a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1v-4l2-9z M4 14h16 M8 16.8v0.4", warn: false, link: false }
+ ]
+
+ Rectangle {
+ Layout.fillWidth: true
+ implicitHeight: panel.implicitHeight + 2
+ radius: UI.Style.radiusMd
+ color: UI.Style.surfaceRaised
+ border.width: 1
+ border.color: UI.Style.borderSubtle
+
+ ColumnLayout {
+ id: panel
+ anchors.left: parent.left
+ anchors.right: parent.right
+ anchors.top: parent.top
+ anchors.topMargin: 1
+ spacing: 0
+
+ Repeater {
+ model: page.rows
+
+ ColumnLayout {
+ id: entry
+ required property var modelData
+ required property int index
+ Layout.fillWidth: true
+ spacing: 0
+
+ Rectangle {
+ Layout.fillWidth: true
+ visible: entry.index > 0
+ height: 1
+ color: UI.Style.divider
+ }
+
+ Item {
+ Layout.fillWidth: true
+ implicitHeight: Math.max(62, words.implicitHeight + 22)
+
+ RowLayout {
+ anchors.fill: parent
+ anchors.leftMargin: 18
+ anchors.rightMargin: 18
+ spacing: 16
+
+ WIcon {
+ Layout.preferredWidth: 20
+ Layout.preferredHeight: 20
+ stroke: entry.modelData.warn ? page.amber : UI.Style.accentText
+ path: entry.modelData.icon
+ }
+ ColumnLayout {
+ id: words
+ Layout.fillWidth: true
+ spacing: 2
+ Text {
+ Layout.fillWidth: true
+ text: entry.modelData.title
+ color: UI.Style.ink
+ font.family: UI.Style.fontFamily
+ font.letterSpacing: UI.Style.tracking(14)
+ font.pixelSize: 14
+ wrapMode: Text.WordWrap
+ }
+ Text {
+ Layout.fillWidth: true
+ text: entry.modelData.body
+ color: UI.Style.inkMuted
+ font.family: UI.Style.fontFamily
+ font.letterSpacing: UI.Style.tracking(12)
+ font.pixelSize: 12
+ lineHeight: 1.5
+ wrapMode: Text.WordWrap
+ }
+ }
+ T.AbstractButton {
+ id: readLink
+ visible: entry.modelData.link
+ text: qsTr("Read the full licence")
+ implicitWidth: linkText.implicitWidth
+ implicitHeight: linkText.implicitHeight + 6
+ hoverEnabled: true
+ focusPolicy: Qt.StrongFocus
+ Accessible.role: Accessible.Link
+ Accessible.name: text
+ onClicked: licenceWindow.openAtWarranty()
+
+ contentItem: Text {
+ id: linkText
+ text: readLink.text
+ color: readLink.hovered ? "#ffffff" : "#8fb4ff"
+ font.family: UI.Style.fontFamily
+ font.letterSpacing: UI.Style.tracking(13)
+ font.pixelSize: 13
+ font.underline: readLink.visualFocus
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ Text {
+ Layout.fillWidth: true
+ text: qsTr("Other software keeps its own terms: Brave, hardware drivers and anything you add from the Store. Windows mode needs your own Windows licence and Microsoft's terms.")
+ color: UI.Style.inkMuted
+ font.family: UI.Style.fontFamily
+ font.letterSpacing: UI.Style.tracking(12)
+ font.pixelSize: 12
+ lineHeight: 1.5
+ wrapMode: Text.WordWrap
+ }
+
+ // The whole panel ticks the box, as a label does; the box itself takes
+ // the keyboard focus, and Space ticks it.
+ Rectangle {
+ Layout.fillWidth: true
+ implicitHeight: acceptRow.implicitHeight + 28
+ radius: UI.Style.radiusMd
+ color: UI.Style.accentTint
+ border.width: 1
+ border.color: Qt.rgba(143 / 255, 180 / 255, 1, 0.4)
+
+ // Under the row, so a click on the box itself reaches only the box.
+ MouseArea {
+ anchors.fill: parent
+ cursorShape: Qt.PointingHandCursor
+ onClicked: Installer.licenceAccepted = !Installer.licenceAccepted
+ }
+
+ RowLayout {
+ id: acceptRow
+ anchors.fill: parent
+ anchors.leftMargin: 18
+ anchors.rightMargin: 18
+ spacing: 14
+
+ UI.CheckBox {
+ id: tick
+ Layout.alignment: Qt.AlignVCenter
+ checked: Installer.licenceAccepted
+ Accessible.name: acceptText.text
+ onToggled: {
+ Installer.licenceAccepted = checked;
+ checked = Qt.binding(() => Installer.licenceAccepted);
+ }
+ }
+ Text {
+ id: acceptText
+ Layout.fillWidth: true
+ text: qsTr("I have read this. I accept that Wild OS comes with no warranty and that I install it at my own risk.")
+ color: UI.Style.ink
+ font.family: UI.Style.fontFamily
+ font.letterSpacing: UI.Style.tracking(14)
+ font.pixelSize: 14
+ lineHeight: 1.5
+ wrapMode: Text.WordWrap
+ }
+ }
+ }
+
+ Item { Layout.fillHeight: true }
+
+ LicenceWindow { id: licenceWindow }
+}
diff --git a/packages/wildos-installer/files/calamares/branding/wildos/show.qml b/packages/wildos-installer/files/calamares/branding/wildos/show.qml
index 11b00b2..f43cb19 100644
--- a/packages/wildos-installer/files/calamares/branding/wildos/show.qml
+++ b/packages/wildos-installer/files/calamares/branding/wildos/show.qml
@@ -28,6 +28,13 @@ Item {
property bool keptWindows: false
// [{ stage, from, to }] in overall progress (0 to 1), from execModuleWeights.
property var spans: []
+ // When the progress last moved, and seconds since then. Some steps
+ // report nothing while they work (making the encrypted partition, the
+ // reset copy), and on some computers they take minutes: the page then
+ // says it is still working rather than sitting on one number.
+ property double movedAt: 0
+ property int stillFor: 0
+ readonly property bool waiting: stillFor >= 20
// The five stages, and the modules (settings.conf exec) in each.
readonly property var stages: [
@@ -89,6 +96,8 @@ Item {
function onActivate() {
startedAt = Date.now();
+ movedAt = startedAt;
+ stillFor = 0;
encrypted = Global.value("wildosEncrypt") !== false;
var plan = Global.value("wildosPlan") || {};
keptWindows = plan.mode === "alongside" && plan.other === "Windows";
@@ -101,6 +110,10 @@ Item {
function onProgress(percent, prettyName) {
if (show.spans.length === 0)
show.buildSpans();
+ if (percent > show.progress) {
+ show.movedAt = Date.now();
+ show.stillFor = 0;
+ }
show.progress = Math.max(show.progress, percent);
// After the first few per cent the pace is steady enough to go by.
var elapsed = (Date.now() - show.startedAt) / 1000;
@@ -109,6 +122,22 @@ Item {
}
}
+ Timer {
+ interval: 1000
+ repeat: true
+ running: show.activatedInCalamares && show.startedAt > 0 && show.progress < 1
+ onTriggered: show.stillFor = Math.round((Date.now() - show.movedAt) / 1000)
+ }
+
+ function stillText() {
+ var minutes = Math.floor(show.stillFor / 60);
+ var why = qsTr("Some computers take a few minutes here.");
+ if (minutes < 1)
+ return qsTr("Still working on this step.") + " " + why;
+ return (minutes === 1 ? qsTr("Still working on this step, 1 minute so far.")
+ : qsTr("Still working on this step, %1 minutes so far.").arg(minutes)) + " " + why;
+ }
+
ColumnLayout {
anchors.fill: parent
anchors.bottomMargin: 22
@@ -189,11 +218,21 @@ Item {
Accessible.name: qsTr("Installation progress")
Rectangle {
+ id: fill
width: parent.width * Math.min(1, show.progress)
height: parent.height
radius: 4
color: UI.Style.accent
Behavior on width { NumberAnimation { duration: 400 } }
+
+ // A step that reports nothing still shows it is at work.
+ SequentialAnimation on opacity {
+ running: show.waiting
+ loops: Animation.Infinite
+ onRunningChanged: if (!running) fill.opacity = 1
+ NumberAnimation { to: 0.45; duration: 900; easing.type: Easing.InOutSine }
+ NumberAnimation { to: 1; duration: 900; easing.type: Easing.InOutSine }
+ }
}
}
Text {
@@ -203,6 +242,16 @@ Item {
font.letterSpacing: UI.Style.tracking(12)
font.pixelSize: 12
}
+ Text {
+ Layout.fillWidth: true
+ visible: show.waiting
+ text: show.stillText()
+ wrapMode: Text.WordWrap
+ color: UI.Style.inkMuted
+ font.family: UI.Style.fontFamily
+ font.letterSpacing: UI.Style.tracking(12)
+ font.pixelSize: 12
+ }
}
}
diff --git a/packages/wildos-installer/files/calamares/branding/wildos/summaryq.qml b/packages/wildos-installer/files/calamares/branding/wildos/summaryq.qml
index c7775f3..60c9495 100644
--- a/packages/wildos-installer/files/calamares/branding/wildos/summaryq.qml
+++ b/packages/wildos-installer/files/calamares/branding/wildos/summaryq.qml
@@ -26,8 +26,8 @@ WPage {
readonly property string diskText: qsTr("%1, %2").arg(diskName).arg(gb(plan.diskSize || 0))
// The step indexes in settings.conf, for the Change links.
- readonly property int keyboardStep: 2
- readonly property int diskStep: 3
+ readonly property int keyboardStep: 3
+ readonly property int diskStep: 4
title: qsTr("Ready to install")
subtitle: qsTr("Check everything below. This is the last step before anything on your disk changes.")
diff --git a/packages/wildos-installer/files/calamares/modules/notesqml-licence.conf b/packages/wildos-installer/files/calamares/modules/notesqml-licence.conf
new file mode 100644
index 0000000..10358d5
--- /dev/null
+++ b/packages/wildos-installer/files/calamares/modules/notesqml-licence.conf
@@ -0,0 +1,7 @@
+# The Licence step, first of all: branding/wildos/licence.qml. Ticking its
+# box sets wildosLicenceAccepted in global storage, which the wildoslicence
+# job checks before anything on the disk changes.
+qmlSearch: branding
+qmlFilename: licence
+qmlLabel:
+ notes: "Licence"
diff --git a/packages/wildos-installer/files/calamares/modules/preservefiles.conf b/packages/wildos-installer/files/calamares/modules/preservefiles.conf
new file mode 100644
index 0000000..c5faec6
--- /dev/null
+++ b/packages/wildos-installer/files/calamares/modules/preservefiles.conf
@@ -0,0 +1,8 @@
+---
+# The installer's log, kept on the new system where only the administrator
+# can read it: it says how long each step took and why one failed. It
+# holds disk and partition names, never the disk password or recovery key.
+files:
+ - from: log
+ dest: /var/log/wildos-install.log
+ perm: root:root:0600
diff --git a/packages/wildos-installer/files/calamares/settings.conf b/packages/wildos-installer/files/calamares/settings.conf
index 7571cee..89ac5a8 100644
--- a/packages/wildos-installer/files/calamares/settings.conf
+++ b/packages/wildos-installer/files/calamares/settings.conf
@@ -3,12 +3,16 @@
modules-search: [ local, /usr/lib/calamares/modules, /usr/share/wildos-installer/modules ]
instances:
+ - id: licence
+ module: notesqml
+ config: notesqml-licence.conf
- id: bootloader-packages
module: shellprocess
config: shellprocess-bootloader-packages.conf
- id: finalize
module: shellprocess
config: shellprocess-finalize.conf
+ weight: 3
- id: encryption
module: notesqml
config: notesqml-encryption.conf
@@ -18,9 +22,19 @@ instances:
- id: resetcopy
module: shellprocess
config: shellprocess-resetcopy.conf
+ # Weights give each module its share of the progress bar. They follow
+ # the time each takes in a test install, so no step holds the bar still
+ # for long: making the encrypted partition (Argon2id takes time and
+ # memory on purpose) and preparing the system to start took far longer than their
+ # default share of one. wildosrecovery sets its own in module.desc.
+ - id: partition
+ module: partition
+ config: partition.conf
+ weight: 3
-# The sidebar shows five steps, and calamares-sidebar.qml and
-# calamares-navigation.qml count on this order:
+# The sidebar shows six steps, and calamares-sidebar.qml,
+# calamares-navigation.qml and summaryq.qml count on this order:
+# Licence notesqml@licence (no warranty, the box to tick)
# Before we start welcomeq (checks), localeq (no page: the time zone and
# language follow the boot language)
# Keyboard keyboardq
@@ -38,6 +52,7 @@ instances:
# and the setup account was started into the desktop.
sequence:
- show:
+ - notesqml@licence
- welcomeq
- localeq
- keyboardq
@@ -45,6 +60,8 @@ sequence:
- notesqml@encryption
- summaryq
- exec:
+ # First, so nothing touches the disk unless the licence was accepted.
+ - wildoslicence
- partition
# Right after the partitions are made, so a recovery key that cannot
# be added stops the install before anything is copied.
@@ -67,6 +84,9 @@ sequence:
- shellprocess@bootloader-packages
- bootloader
- shellprocess@finalize
+ # The install's own log, for working out later why a step was slow
+ # or failed.
+ - preservefiles
- umount
- show:
- finishedq
diff --git a/packages/wildos-installer/files/libexec/finalize-target b/packages/wildos-installer/files/libexec/finalize-target
index f18c1e2..88f9c4e 100644
--- a/packages/wildos-installer/files/libexec/finalize-target
+++ b/packages/wildos-installer/files/libexec/finalize-target
@@ -107,6 +107,14 @@ rm -f "$root/etc/sddm.conf"
install -d "$root/var/lib/wildos"
: > "$root/var/lib/wildos/first-boot-setup"
+# Calamares clears the system partition's crypttab options when /boot is not
+# encrypted, which is Wild OS's layout; put back TRIM and the faster
+# encryption settings (wildos-base's crypttab-speed) before the start-up image
+# copies crypttab.
+if [ -x "$root/usr/libexec/wildos/crypttab-speed" ]; then
+ in_target /usr/libexec/wildos/crypttab-speed >/dev/null || true
+fi
+
# The initramfs copied from the image was generated in the build container and
# knows nothing about this machine's disks or encryption. Regenerate it now
# that crypttab exists and the live packages are gone.
diff --git a/packages/wildos-installer/files/modules/wildoslicence/main.py b/packages/wildos-installer/files/modules/wildoslicence/main.py
new file mode 100644
index 0000000..a96042e
--- /dev/null
+++ b/packages/wildos-installer/files/modules/wildoslicence/main.py
@@ -0,0 +1,22 @@
+#!/usr/bin/env python3
+"""Refuses to install unless the licence was accepted.
+
+The Licence page keeps Continue disabled until its box is ticked, and
+writes the answer to global storage as wildosLicenceAccepted. This job runs
+first, before the partition jobs, so even a way past the page that nobody
+has thought of ends here with the disk untouched.
+"""
+
+import libcalamares
+
+
+def pretty_name():
+ return "Checking the licence was accepted"
+
+
+def run():
+ if libcalamares.globalstorage.value("wildosLicenceAccepted") is True:
+ return None
+ return ("The licence was not accepted",
+ "Wild OS installs only after the box on the first page is ticked. "
+ "Nothing on this computer has been changed.")
diff --git a/packages/wildos-installer/files/modules/wildoslicence/module.desc b/packages/wildos-installer/files/modules/wildoslicence/module.desc
new file mode 100644
index 0000000..e10360a
--- /dev/null
+++ b/packages/wildos-installer/files/modules/wildoslicence/module.desc
@@ -0,0 +1,6 @@
+# Stops the install before the disk is touched unless the licence page's
+# box was ticked. See main.py.
+type: "job"
+name: "wildoslicence"
+interface: "python"
+script: "main.py"
diff --git a/packages/wildos-installer/files/modules/wildosrecovery/module.desc b/packages/wildos-installer/files/modules/wildosrecovery/module.desc
index 4d5e970..500b7cd 100644
--- a/packages/wildos-installer/files/modules/wildosrecovery/module.desc
+++ b/packages/wildos-installer/files/modules/wildosrecovery/module.desc
@@ -5,3 +5,6 @@ type: "job"
name: "wildosrecovery"
interface: "python"
script: "main.py"
+# A share of the progress bar to match its time: the key slot derives an
+# Argon2id key, which takes several seconds on purpose.
+weight: 2
diff --git a/packages/wildos-installer/plugin/CMakeLists.txt b/packages/wildos-installer/plugin/CMakeLists.txt
index 795a4b6..c32098a 100644
--- a/packages/wildos-installer/plugin/CMakeLists.txt
+++ b/packages/wildos-installer/plugin/CMakeLists.txt
@@ -1,7 +1,7 @@
cmake_minimum_required(VERSION 3.21)
project(wildos-installer-qml LANGUAGES CXX)
-find_package(Qt6 6.5 REQUIRED COMPONENTS Core Qml)
+find_package(Qt6 6.5 REQUIRED COMPONENTS Core Gui Qml Widgets)
qt_standard_project_setup(REQUIRES 6.5)
include(GNUInstallDirs)
@@ -16,6 +16,10 @@ qt_add_qml_module(wildosinstaller
installer.h installer.cpp
)
+# Widgets for the licence's save dialog: Calamares is a widgets application,
+# so its file dialog is already loaded.
+target_link_libraries(wildosinstaller PRIVATE Qt6::Gui Qt6::Widgets)
+
set(WILDOS_QML_DIR "${CMAKE_INSTALL_LIBDIR}/qt6/qml/WildOS/Installer")
install(TARGETS wildosinstaller LIBRARY DESTINATION ${WILDOS_QML_DIR})
install(FILES ${CMAKE_BINARY_DIR}/WildOS/Installer/qmldir DESTINATION ${WILDOS_QML_DIR})
diff --git a/packages/wildos-installer/plugin/installer.cpp b/packages/wildos-installer/plugin/installer.cpp
index 128eed1..3cfee81 100644
--- a/packages/wildos-installer/plugin/installer.cpp
+++ b/packages/wildos-installer/plugin/installer.cpp
@@ -1,17 +1,37 @@
#include "installer.h"
+#include <QCoreApplication>
#include <QDir>
#include <QFile>
+#include <QFileDialog>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QProcess>
#include <QRandomGenerator>
+#include <QRegularExpression>
+#include <QWindow>
+
+#include <pwd.h>
+#include <unistd.h>
static const QString checker = QStringLiteral("/usr/libexec/wildos-installer/check-computer");
+// From base-files, so it is on every Debian system; the image's slimming
+// only drops /usr/share/doc.
+static const QString licenceFile = QStringLiteral("/usr/share/common-licenses/GPL-3");
Installer::Installer()
{
+ // Calamares 3.3.14 crashes while tearing its pages down after the event
+ // loop ends, so closing it (the sidebar's Close the installer, Alt+F4)
+ // ended on a crash report. Before the install step nothing is mounted
+ // or written, so it leaves here instead; after it, Calamares' own
+ // shutdown runs as before, so a finished install still restarts.
+ connect(qApp, &QCoreApplication::aboutToQuit, this, [this] {
+ if (m_exitQuickly)
+ ::_exit(0);
+ });
+
// Letters and digits that cannot be mistaken for one another when
// written down or read back: 32 of them, so 30 give 150 random bits.
static const QString alphabet = QStringLiteral("ABCDEFGHJKLMNPQRSTUVWXYZ23456789");
@@ -214,3 +234,97 @@ QString Installer::startMode() const
}
return mode;
}
+
+QVariantList Installer::licenceSections() const
+{
+ QFile file(licenceFile);
+ if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
+ return {};
+ const QString text = QString::fromUtf8(file.readAll());
+
+ // A heading is a paragraph of one line, " 15. Disclaimer of Warranty.",
+ // numbered one more than the last, so a number inside the terms can
+ // never start a section by mistake.
+ static const QRegularExpression heading(QStringLiteral(R"(^\s*(\d{1,2})\.\s+(.+)\.$)"));
+ QVariantList sections;
+ QVariantMap section{{QStringLiteral("number"), -1}, {QStringLiteral("title"), QString()}};
+ QStringList paragraphs;
+ int next = 0;
+ const auto flush = [&] {
+ section.insert(QStringLiteral("paragraphs"), paragraphs);
+ sections.append(section);
+ paragraphs.clear();
+ };
+
+ const QStringList blocks = text.split(QRegularExpression(QStringLiteral(R"(\n[ \t]*\n)")), Qt::SkipEmptyParts);
+ for (const QString &block : blocks) {
+ QStringList lines = block.split(u'\n');
+ for (QString &line : lines)
+ line = line.trimmed();
+ lines.removeAll(QString());
+ if (lines.isEmpty())
+ continue;
+ if (lines.size() == 1) {
+ const auto m = heading.match(lines.first());
+ if (m.hasMatch() && m.captured(1).toInt() == next) {
+ flush();
+ section = {{QStringLiteral("number"), next}, {QStringLiteral("title"), m.captured(2)}};
+ paragraphs.append(lines.first());
+ ++next;
+ continue;
+ }
+ }
+ paragraphs.append(lines.join(u' '));
+ }
+ flush();
+ return sections;
+}
+
+QString Installer::saveLicence(QObject *window)
+{
+ // Calamares runs as root through sudo; the copy belongs to the person
+ // in the live session, so it starts in their home folder and is theirs.
+ QString home = QDir::homePath();
+ uid_t uid = 0;
+ gid_t gid = 0;
+ if (const QByteArray user = qgetenv("SUDO_USER"); !user.isEmpty()) {
+ if (const passwd *pw = getpwnam(user.constData())) {
+ home = QString::fromLocal8Bit(pw->pw_dir);
+ uid = pw->pw_uid;
+ gid = pw->pw_gid;
+ }
+ }
+
+ QFileDialog dialog(nullptr, tr("Save a copy of the licence"), home + QStringLiteral("/GNU General Public License v3.txt"),
+ tr("Text files (*.txt)"));
+ dialog.setAcceptMode(QFileDialog::AcceptSave);
+ dialog.setDefaultSuffix(QStringLiteral("txt"));
+ dialog.winId();
+ if (auto *parent = qobject_cast<QWindow *>(window); parent && dialog.windowHandle())
+ dialog.windowHandle()->setTransientParent(parent);
+ if (dialog.exec() != QDialog::Accepted || dialog.selectedFiles().isEmpty())
+ return QString();
+ const QString target = dialog.selectedFiles().first();
+
+ QFile source(licenceFile);
+ if (!source.open(QIODevice::ReadOnly))
+ return tr("The licence file could not be read.");
+ const QByteArray bytes = source.readAll();
+ QFile out(target);
+ if (!out.open(QIODevice::WriteOnly | QIODevice::Truncate) || out.write(bytes) != bytes.size()) {
+ return tr("The licence could not be saved there. Try another folder or drive.");
+ }
+ out.close();
+ // FAT and NTFS drives have no owners and refuse; the copy is saved anyway.
+ if (uid != 0)
+ (void)::chown(QFile::encodeName(target).constData(), uid, gid);
+ run(QStringLiteral("sync"), {});
+ return QString();
+}
+
+void Installer::quitNow()
+{
+ // Straight out, without Calamares' "Close the installer?" question:
+ // on the first page nothing has been chosen.
+ ::_exit(0);
+}
diff --git a/packages/wildos-installer/plugin/installer.h b/packages/wildos-installer/plugin/installer.h
index 7520b12..9ab861d 100644
--- a/packages/wildos-installer/plugin/installer.h
+++ b/packages/wildos-installer/plugin/installer.h
@@ -15,7 +15,10 @@
* - the checks of the "Before we start" page, run by check-computer,
* - the disk password page's state and the recovery key, which never
* leaves this process except into the LUKS key slot and onto the USB
- * stick or paper the person chooses.
+ * stick or paper the person chooses,
+ * - whether the licence page's box is ticked, and the licence text it
+ * shows. The answer lives here, not in the page, so it starts unticked
+ * on every run and stays ticked when someone comes Back to the page.
*/
class Installer : public QObject
{
@@ -32,6 +35,10 @@ class Installer : public QObject
Q_PROPERTY(QVariantList checks READ checks NOTIFY checksChanged)
Q_PROPERTY(QString alongsideBlocked READ alongsideBlocked NOTIFY checksChanged)
+ Q_PROPERTY(bool licenceAccepted MEMBER m_licenceAccepted NOTIFY licenceAcceptedChanged)
+ /// True until the install step: the footer keeps it up to date. While
+ /// it holds, however the installer is closed it leaves at once.
+ Q_PROPERTY(bool exitQuickly MEMBER m_exitQuickly)
Q_PROPERTY(bool encryptionReady MEMBER m_encryptionReady NOTIFY encryptionReadyChanged)
Q_PROPERTY(QString recoveryKey READ recoveryKey CONSTANT)
Q_PROPERTY(bool keySaved MEMBER m_keySaved NOTIFY keySavedChanged)
@@ -59,6 +66,19 @@ public:
/// Runs check-computer again; checksChanged when it is done.
Q_INVOKABLE void runChecks();
+ /// The GPL as numbered sections for the full licence window:
+ /// [{ number, title, paragraphs }], number -1 for the title page and
+ /// preamble. The words are the file's own; only the line breaks of its
+ /// fixed-width layout are undone, so paragraphs wrap to the window.
+ Q_INVOKABLE QVariantList licenceSections() const;
+ /// Asks where to save the licence file and copies it there unchanged.
+ /// @p window is the licence window, so the file dialog opens above it.
+ /// Returns "" when saved or cancelled, else what went wrong.
+ Q_INVOKABLE QString saveLicence(QObject *window);
+ /// Closes the installer without asking: used before anything has been
+ /// chosen, when there is nothing to lose.
+ Q_INVOKABLE void quitNow();
+
/// Calamares' reversible scrambling for secrets in global storage
/// (KStringHandler::obscure), so they are not plain text in its logs.
Q_INVOKABLE QString obscure(const QString &text) const;
@@ -79,6 +99,7 @@ Q_SIGNALS:
void keyboardChanged();
void finishedChanged();
void checksChanged();
+ void licenceAcceptedChanged();
void encryptionReadyChanged();
void keySavedChanged();
void drivesChanged();
@@ -93,6 +114,8 @@ private:
bool m_checking = false;
QVariantList m_checks;
QString m_alongsideBlocked;
+ bool m_licenceAccepted = false;
+ bool m_exitQuickly = true;
bool m_encryptionReady = false;
QString m_recoveryKey;
bool m_keySaved = false;
diff --git a/packages/wildos-launch/debian/changelog b/packages/wildos-launch/debian/changelog
index 9d2c2b6..1c1681c 100644
--- a/packages/wildos-launch/debian/changelog
+++ b/packages/wildos-launch/debian/changelog
@@ -1,3 +1,11 @@
+wildos-launch (0.2.1) trixie; urgency=medium
+
+ * A launch ends when a window opens from the process it started, even
+ when the window names itself differently from the app (LibreOffice
+ Write and Tables did, so their starting line lasted 20 seconds).
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 19:00:00 +0000
+
wildos-launch (0.2.0) trixie; urgency=medium
* No more placeholder windows: the daemon only follows each launch for
diff --git a/packages/wildos-launch/src/launcher.cpp b/packages/wildos-launch/src/launcher.cpp
index 20f6be5..b2a2112 100644
--- a/packages/wildos-launch/src/launcher.cpp
+++ b/packages/wildos-launch/src/launcher.cpp
@@ -68,6 +68,21 @@ QStringList keysFrom(const QJsonValue &value)
return keys;
}
+// The systemd unit a process runs in, from the last part of its cgroup:
+// [email protected], as KIO starts it.
+QString unitOf(int pid)
+{
+ if (pid <= 0) {
+ return {};
+ }
+ QFile file(QStringLiteral("/proc/%1/cgroup").arg(pid));
+ if (!file.open(QIODevice::ReadOnly)) {
+ return {};
+ }
+ const QString line = QString::fromUtf8(file.readAll()).trimmed().section(QLatin1Char('\n'), -1);
+ return line.section(QLatin1Char('/'), -1);
+}
+
bool intersects(const QStringList &a, const QStringList &b)
{
for (const QString &key : a) {
@@ -231,14 +246,21 @@ void Launcher::Windows(const QString &json)
}
}
const QJsonObject added = report.value(QStringLiteral("added")).toObject();
- const QStringList keys = keysFrom(added.value(QStringLiteral("k")));
- if (keys.isEmpty()) {
+ if (added.isEmpty()) {
return;
}
+ const QStringList keys = keysFrom(added.value(QStringLiteral("k")));
+ // An app can name its window differently from its desktop file; the
+ // process it was started in still says which launch it belongs to.
+ const QString unit = unitOf(added.value(QStringLiteral("pid")).toInt());
const QStringList ids = m_launches.keys();
for (const QString &id : ids) {
const Launch &launch = m_launches[id];
- if (!intersects(keys, launch.keys)) {
+ const QString prefix = QStringLiteral("app-") + escapeUnitName(launch.desktopId);
+ const bool sameUnit = !unit.isEmpty()
+ && (unit == launch.unit || unit.startsWith(prefix + QLatin1Char('@'))
+ || (unit.startsWith(prefix + QLatin1Char('-')) && unit.endsWith(QLatin1String(".scope"))));
+ if (!sameUnit && !intersects(keys, launch.keys)) {
continue;
}
qInfo("wildos-launchd: %s opened in %lld ms", qPrintable(launch.desktopId), launch.clock.elapsed());
diff --git a/packages/wildos-mail/debian/changelog b/packages/wildos-mail/debian/changelog
index 2f3e20c..9ff44ad 100644
--- a/packages/wildos-mail/debian/changelog
+++ b/packages/wildos-mail/debian/changelog
@@ -1,3 +1,13 @@
+wildos-mail (0.2.5) trixie; urgency=medium
+
+ * Every text box in Mail has the right-click menu with Cut, Copy,
+ Paste and Select all: the subject, the message and the recipients,
+ signatures, event and contact notes, and task titles, steps and
+ notes. The Menu key and Shift+F10 open it too. Opening it in an
+ account's name boxes no longer saves and closes the box early.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 08:54:22 +0000
+
wildos-mail (0.2.4) trixie; urgency=medium
* Report a problem on the Help tab opens Report a problem with Mail chosen,
diff --git a/packages/wildos-mail/debian/control b/packages/wildos-mail/debian/control
index 101480b..1528dfa 100644
--- a/packages/wildos-mail/debian/control
+++ b/packages/wildos-mail/debian/control
@@ -25,7 +25,7 @@ Depends:
${misc:Depends},
evolution-data-server-camel-providers,
evolution-data-server-core,
- wildos-ui (>= 0.1.3),
+ wildos-ui (>= 0.1.11),
evolution-data-server-common,
qml6-module-qtcore,
qml6-module-qtquick,
diff --git a/packages/wildos-mail/qml/ComposePane.qml b/packages/wildos-mail/qml/ComposePane.qml
index 93eeb1e..815bffe 100644
--- a/packages/wildos-mail/qml/ComposePane.qml
+++ b/packages/wildos-mail/qml/ComposePane.qml
@@ -269,6 +269,16 @@ Rectangle {
clip: true
onTextEdited: composer.touch()
KeyNavigation.tab: editor
+ Keys.onPressed: event => {
+ if (subjectMenu.isMenuKey(event)) {
+ subjectMenu.openAtCaret();
+ event.accepted = true;
+ }
+ }
+
+ UI.TextMenu {
+ id: subjectMenu
+ }
}
}
}
@@ -380,8 +390,15 @@ Rectangle {
} else if ((event.modifiers & Qt.ControlModifier) && event.key === Qt.Key_U) {
formatter.toggleUnderline();
event.accepted = true;
+ } else if (editorMenu.isMenuKey(event)) {
+ editorMenu.openAtCaret();
+ event.accepted = true;
}
}
+
+ UI.TextMenu {
+ id: editorMenu
+ }
}
// The message being answered, under the reply.
diff --git a/packages/wildos-mail/qml/ContactEditor.qml b/packages/wildos-mail/qml/ContactEditor.qml
index 285921b..8225086 100644
--- a/packages/wildos-mail/qml/ContactEditor.qml
+++ b/packages/wildos-mail/qml/ContactEditor.qml
@@ -270,6 +270,16 @@ UI.Dialog {
border.width: 1
border.color: notesField.activeFocus ? UI.Style.accent : UI.Style.borderField
}
+ Keys.onPressed: event => {
+ if (notesMenu.isMenuKey(event)) {
+ notesMenu.openAtCaret();
+ event.accepted = true;
+ }
+ }
+
+ UI.TextMenu {
+ id: notesMenu
+ }
}
UI.Label {
diff --git a/packages/wildos-mail/qml/EventEditor.qml b/packages/wildos-mail/qml/EventEditor.qml
index 74af4f6..68815b4 100644
--- a/packages/wildos-mail/qml/EventEditor.qml
+++ b/packages/wildos-mail/qml/EventEditor.qml
@@ -225,6 +225,16 @@ Rectangle {
color: title.activeFocus ? UI.Style.accent : UI.Style.borderSubtle
}
Keys.onReturnPressed: editor.save(true)
+ Keys.onPressed: event => {
+ if (titleMenu.isMenuKey(event)) {
+ titleMenu.openAtCaret();
+ event.accepted = true;
+ }
+ }
+
+ UI.TextMenu {
+ id: titleMenu
+ }
}
component FormRow: RowLayout {
@@ -467,6 +477,16 @@ Rectangle {
border.width: 1
border.color: notes.activeFocus ? UI.Style.accent : UI.Style.borderField
}
+ Keys.onPressed: event => {
+ if (notesMenu.isMenuKey(event)) {
+ notesMenu.openAtCaret();
+ event.accepted = true;
+ }
+ }
+
+ UI.TextMenu {
+ id: notesMenu
+ }
}
}
}
diff --git a/packages/wildos-mail/qml/RecipientField.qml b/packages/wildos-mail/qml/RecipientField.qml
index 11bc6a9..68a3464 100644
--- a/packages/wildos-mail/qml/RecipientField.qml
+++ b/packages/wildos-mail/qml/RecipientField.qml
@@ -153,7 +153,9 @@ FocusScope {
}
field.edited();
}
- onEditingFinished: field.commit()
+ // The text menu holds focus while it is open; what is typed so
+ // far is not a whole address yet.
+ onEditingFinished: if (!inputMenu.opened) field.commit()
Text {
visible: input.text.length === 0 && field.people.length === 0
@@ -175,8 +177,16 @@ FocusScope {
field.people = field.people.slice(0, -1);
field.edited();
event.accepted = true;
+ } else if (inputMenu.isMenuKey(event)) {
+ inputMenu.openAtCaret();
+ event.accepted = true;
}
}
+
+ UI.TextMenu {
+ id: inputMenu
+ onFocusLeft: field.commit()
+ }
}
}
diff --git a/packages/wildos-mail/qml/SettingsPage.qml b/packages/wildos-mail/qml/SettingsPage.qml
index 3b43f0f..e7ca414 100644
--- a/packages/wildos-mail/qml/SettingsPage.qml
+++ b/packages/wildos-mail/qml/SettingsPage.qml
@@ -180,11 +180,15 @@ Rectangle {
UI.TextField {
width: 240
text: accountCard.modelData.fullName
- onEditingFinished: {
+ function save() {
const a = MailEngine.account(accountCard.modelData.id);
a.fullName = text.trim();
MailEngine.updateAccount(a);
}
+ // Saving rebuilds this card, and the open text menu
+ // with it; the menu holds focus while it is up.
+ onEditingFinished: if (!textMenuOpen) save()
+ onTextMenuFocusLeft: save()
}
}
UI.SettingRow {
@@ -193,11 +197,15 @@ Rectangle {
UI.TextField {
width: 240
text: accountCard.modelData.name
- onEditingFinished: {
+ function save() {
const a = MailEngine.account(accountCard.modelData.id);
a.name = text.trim() || a.email;
MailEngine.updateAccount(a);
}
+ // Saving rebuilds this card, and the open text menu
+ // with it; the menu holds focus while it is up.
+ onEditingFinished: if (!textMenuOpen) save()
+ onTextMenuFocusLeft: save()
}
}
UI.SettingRow {
@@ -295,6 +303,7 @@ Rectangle {
font.weight: UI.Style.weightSemiBold
}
QQC.TextArea {
+ id: signatureEdit
Layout.fillWidth: true
Layout.preferredHeight: 110
text: sigCard.modelData.signature
@@ -311,11 +320,25 @@ Rectangle {
border.width: 1
border.color: UI.Style.borderField
}
- onEditingFinished: {
+ function save() {
const a = MailEngine.account(sigCard.modelData.id);
a.signature = text;
MailEngine.updateAccount(a);
}
+ // Saving rebuilds this card, and the open text menu with
+ // it; the menu holds focus while it is up.
+ onEditingFinished: if (!signatureMenu.opened) save()
+ Keys.onPressed: event => {
+ if (signatureMenu.isMenuKey(event)) {
+ signatureMenu.openAtCaret();
+ event.accepted = true;
+ }
+ }
+
+ UI.TextMenu {
+ id: signatureMenu
+ onFocusLeft: signatureEdit.save()
+ }
}
}
}
diff --git a/packages/wildos-mail/qml/TasksPage.qml b/packages/wildos-mail/qml/TasksPage.qml
index 9f4e228..76188fc 100644
--- a/packages/wildos-mail/qml/TasksPage.qml
+++ b/packages/wildos-mail/qml/TasksPage.qml
@@ -645,6 +645,16 @@ Item {
page.pending = ({});
focus = false;
}
+ Keys.onPressed: event => {
+ if (newTaskMenu.isMenuKey(event)) {
+ newTaskMenu.openAtCaret();
+ event.accepted = true;
+ }
+ }
+
+ UI.TextMenu {
+ id: newTaskMenu
+ }
UI.Label {
anchors.verticalCenter: parent.verticalCenter
visible: newTask.text.length === 0
@@ -892,11 +902,25 @@ Item {
background: null
Keys.onReturnPressed: focus = false
Keys.onEnterPressed: focus = false
- onActiveFocusChanged: {
- if (!activeFocus && text.trim() && text.trim() !== page.current.rawTitle) {
+ function save() {
+ if (text.trim() && text.trim() !== page.current.rawTitle) {
TasksEngine.setTitle(page.current.key, text);
}
}
+ // The text menu holds focus while it is open; the
+ // title is saved once typing is over.
+ onActiveFocusChanged: if (!activeFocus && !titleMenu.opened) save()
+ Keys.onPressed: event => {
+ if (titleMenu.isMenuKey(event)) {
+ titleMenu.openAtCaret();
+ event.accepted = true;
+ }
+ }
+
+ UI.TextMenu {
+ id: titleMenu
+ onFocusLeft: titleEdit.save()
+ }
}
UI.IconButton {
Layout.alignment: Qt.AlignTop
@@ -997,6 +1021,16 @@ Item {
clip: true
Accessible.role: Accessible.EditableText
Accessible.name: qsTr("Add a step")
+ Keys.onPressed: event => {
+ if (newStepMenu.isMenuKey(event)) {
+ newStepMenu.openAtCaret();
+ event.accepted = true;
+ }
+ }
+
+ UI.TextMenu {
+ id: newStepMenu
+ }
onAccepted: {
const t = text.trim();
if (t) {
@@ -1107,11 +1141,25 @@ Item {
border.width: 1
border.color: notesEdit.activeFocus ? UI.Style.accent : UI.Style.borderSubtle
}
- onActiveFocusChanged: {
- if (!activeFocus && text !== (page.current.notes || "")) {
+ function save() {
+ if (text !== (page.current.notes || "")) {
TasksEngine.setNotes(page.current.key, text);
}
}
+ // The text menu holds focus while it is open; the
+ // note is saved once typing is over.
+ onActiveFocusChanged: if (!activeFocus && !notesMenu.opened) save()
+ Keys.onPressed: event => {
+ if (notesMenu.isMenuKey(event)) {
+ notesMenu.openAtCaret();
+ event.accepted = true;
+ }
+ }
+
+ UI.TextMenu {
+ id: notesMenu
+ onFocusLeft: notesEdit.save()
+ }
}
}
}
diff --git a/packages/wildos-music/debian/changelog b/packages/wildos-music/debian/changelog
index 3108ee7..a29eda3 100644
--- a/packages/wildos-music/debian/changelog
+++ b/packages/wildos-music/debian/changelog
@@ -1,3 +1,9 @@
+wildos-music (0.1.3) trixie; urgency=medium
+
+ * The mini player's close button closes Music.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 10:21:27 +0000
+
wildos-music (0.1.2) trixie; urgency=medium
* The empty Music folder message, Liked songs and empty playlists sit in
diff --git a/packages/wildos-music/src/main.cpp b/packages/wildos-music/src/main.cpp
index c4760be..a4b6504 100644
--- a/packages/wildos-music/src/main.cpp
+++ b/packages/wildos-music/src/main.cpp
@@ -114,6 +114,9 @@ int main(int argc, char *argv[])
Incubation incubation;
QQmlApplicationEngine engine;
engine.setIncubationController(&incubation);
+ // The mini player's close button calls Qt.quit(), which
+ // QQmlApplicationEngine only wires up when it loads a window itself.
+ QObject::connect(&engine, &QQmlEngine::quit, &app, &QCoreApplication::quit, Qt::QueuedConnection);
music->setEngine(&engine);
QObject::connect(&service, &KDBusService::activateRequested, music, [music](const QStringList &arguments, const QString &workingDirectory) {
music->handle(arguments, workingDirectory);
diff --git a/packages/wildos-notes/debian/changelog b/packages/wildos-notes/debian/changelog
index d22a818..baed646 100644
--- a/packages/wildos-notes/debian/changelog
+++ b/packages/wildos-notes/debian/changelog
@@ -1,3 +1,12 @@
+wildos-notes (0.1.2) trixie; urgency=medium
+
+ * The title and the note have the right-click menu with Undo, Cut,
+ Copy, Paste and Select all. Undo from the menu steps back just as
+ Ctrl+Z does. The empty search box stays open while its menu is up,
+ so you can paste into it.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 08:54:22 +0000
+
wildos-notes (0.1.1) trixie; urgency=medium
* Report a problem in a note's More menu opens Report a problem with Notes
diff --git a/packages/wildos-notes/debian/control b/packages/wildos-notes/debian/control
index 4633d26..27a6586 100644
--- a/packages/wildos-notes/debian/control
+++ b/packages/wildos-notes/debian/control
@@ -18,7 +18,7 @@ Architecture: any
Depends:
${shlibs:Depends},
${misc:Depends},
- wildos-ui (>= 0.1.3),
+ wildos-ui (>= 0.1.11),
qml6-module-qtcore,
qml6-module-qtquick,
qml6-module-qtquick-controls,
diff --git a/packages/wildos-notes/qml/EditorPane.qml b/packages/wildos-notes/qml/EditorPane.qml
index 4fd7d79..e5719b4 100644
--- a/packages/wildos-notes/qml/EditorPane.qml
+++ b/packages/wildos-notes/qml/EditorPane.qml
@@ -294,13 +294,14 @@ Item {
pane.doc.title = text;
}
}
- onActiveFocusChanged: {
- if (!activeFocus) {
- pane.syncTitle();
- }
- }
+ // Resetting the text would drop the selection the open text
+ // menu is about to copy; the menu holds focus while it is up.
+ onActiveFocusChanged: if (!activeFocus && !titleMenu.opened) pane.syncTitle()
Keys.onPressed: event => {
- if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter) {
+ if (titleMenu.isMenuKey(event)) {
+ titleMenu.openAtCaret();
+ event.accepted = true;
+ } else if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter) {
body.focusStart();
event.accepted = true;
} else if (event.key === Qt.Key_Down && cursorRectangle.y + cursorRectangle.height >= contentHeight - 2) {
@@ -309,6 +310,11 @@ Item {
}
}
+ UI.TextMenu {
+ id: titleMenu
+ onFocusLeft: pane.syncTitle()
+ }
+
UI.Label {
visible: titleEdit.length === 0
text: qsTr("Title")
diff --git a/packages/wildos-notes/qml/NoteEditor.qml b/packages/wildos-notes/qml/NoteEditor.qml
index 6867809..09f7e12 100644
--- a/packages/wildos-notes/qml/NoteEditor.qml
+++ b/packages/wildos-notes/qml/NoteEditor.qml
@@ -156,6 +156,11 @@ Item {
const selected = selectionStart !== selectionEnd;
const control = (event.modifiers & Qt.ControlModifier) !== 0;
const shift = (event.modifiers & Qt.ShiftModifier) !== 0;
+ if (textMenu.isMenuKey(event)) {
+ textMenu.openAtCaret();
+ event.accepted = true;
+ return;
+ }
if (readOnly) {
return;
}
@@ -212,6 +217,13 @@ Item {
}
}
+ // Undo goes through the editor, as Ctrl+Z does, so stepping back
+ // keeps each edit's line spacing with it.
+ UI.TextMenu {
+ id: textMenu
+ undoAction: () => editor.undo()
+ }
+
// Ctrl+click follows a link, as in other editors; a plain click
// puts the cursor in it to change it.
TapHandler {
diff --git a/packages/wildos-notes/qml/NoteList.qml b/packages/wildos-notes/qml/NoteList.qml
index d13e5aa..f5c62ff 100644
--- a/packages/wildos-notes/qml/NoteList.qml
+++ b/packages/wildos-notes/qml/NoteList.qml
@@ -88,8 +88,16 @@ Item {
onTextChanged: NoteStore.search = text
onEscapePressed: list.stopSearch()
onDownPressed: notes.forceActiveFocus()
+ // An empty box closes when you leave it, but not for the text
+ // menu, which holds focus while it is up and may be there to
+ // paste.
onActiveFocusChanged: {
- if (!activeFocus && text.length === 0) {
+ if (!activeFocus && !textMenuOpen && text.length === 0) {
+ list.searching = false;
+ }
+ }
+ onTextMenuFocusLeft: {
+ if (text.length === 0) {
list.searching = false;
}
}
diff --git a/packages/wildos-office/debian/changelog b/packages/wildos-office/debian/changelog
index db8be7c..388a9c7 100644
--- a/packages/wildos-office/debian/changelog
+++ b/packages/wildos-office/debian/changelog
@@ -1,3 +1,11 @@
+wildos-office (0.1.4) trixie; urgency=medium
+
+ * Write and Tables are their own packages, wildos-write and
+ wildos-tables, so either can be uninstalled and put back on its own.
+ A PC updating from before gets both.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 13:28:50 +0000
+
wildos-office (0.1.3) trixie; urgency=medium
* No navy left: surfaces, glass, shadows and the logo tile use the
diff --git a/packages/wildos-office/debian/control b/packages/wildos-office/debian/control
index 6201caf..03ce3c4 100644
--- a/packages/wildos-office/debian/control
+++ b/packages/wildos-office/debian/control
@@ -16,8 +16,7 @@ Architecture: any
Depends:
${shlibs:Depends},
${misc:Depends},
- libreoffice-writer,
- libreoffice-calc,
+ libreoffice-core,
libreoffice-kf6,
libreoffice-l10n-en-gb,
fonts-crosextra-carlito,
@@ -34,8 +33,33 @@ Depends:
qml6-module-qtquick-shapes,
qml6-module-qtquick-templates,
qt6-svg-plugins,
-Description: Wild OS Write and Tables
+Description: Wild OS Write and Tables, the parts both share
Documents and spreadsheets for Wild OS. Write and Tables are LibreOffice
Writer and Calc with Wild OS start screens, ribbons and defaults: Word and
Excel files open with them and save back as .docx and .xlsx unless asked
- otherwise.
+ otherwise. This package holds what they share; wildos-write and
+ wildos-tables are the apps, so each can be removed on its own.
+
+Package: wildos-write
+Architecture: all
+Depends:
+ ${misc:Depends},
+ wildos-office (>= 0.1.4),
+ libreoffice-writer,
+Breaks: wildos-office (<< 0.1.4~)
+Replaces: wildos-office (<< 0.1.4~)
+Description: Wild OS Write
+ Documents for Wild OS: LibreOffice Writer with the Wild OS start screen,
+ ribbon and defaults. Word files open with it and save back as .docx.
+
+Package: wildos-tables
+Architecture: all
+Depends:
+ ${misc:Depends},
+ wildos-office (>= 0.1.4),
+ libreoffice-calc,
+Breaks: wildos-office (<< 0.1.4~)
+Replaces: wildos-office (<< 0.1.4~)
+Description: Wild OS Tables
+ Spreadsheets for Wild OS: LibreOffice Calc with the Wild OS start screen,
+ ribbon and defaults. Excel files open with it and save back as .xlsx.
diff --git a/packages/wildos-office/debian/postinst b/packages/wildos-office/debian/postinst
new file mode 100644
index 0000000..757f491
--- /dev/null
+++ b/packages/wildos-office/debian/postinst
@@ -0,0 +1,17 @@
+#!/bin/sh
+set -e
+# Up to 0.1.3 this package was Write and Tables together. They are now
+# wildos-write and wildos-tables, so each can be removed on its own, and an
+# update brings in neither by itself. A PC updating from before the split
+# gets both a minute after dpkg has finished, or at the next start if that
+# fails.
+if [ "$1" = configure ] && [ -n "${2:-}" ] && dpkg --compare-versions "$2" lt 0.1.4~; then
+ mkdir -p /var/lib/wildos
+ touch /var/lib/wildos/office-split
+ if [ -d /run/systemd/system ]; then
+ systemd-run --quiet --on-active=60 --unit=wildos-office-split-soon \
+ systemctl start --no-block wildos-office-split.service || true
+ fi
+fi
+#DEBHELPER#
+exit 0
diff --git a/packages/wildos-office/debian/postrm b/packages/wildos-office/debian/postrm
index 5d1259c..8c1d728 100644
--- a/packages/wildos-office/debian/postrm
+++ b/packages/wildos-office/debian/postrm
@@ -6,4 +6,7 @@ UI=/usr/lib/libreoffice/share/config/soffice.cfg/vcl/ui/printdialog.ui
if [ "$1" = remove ] || [ "$1" = abort-install ] || [ "$1" = disappear ]; then
dpkg-divert --package wildos-office --rename --divert "$UI.libreoffice" --remove "$UI"
fi
+if [ "$1" = purge ]; then
+ rm -f /var/lib/wildos/office-split
+fi
exit 0
diff --git a/packages/wildos-office/debian/rules b/packages/wildos-office/debian/rules
index 2c5acaf..ea73384 100644
--- a/packages/wildos-office/debian/rules
+++ b/packages/wildos-office/debian/rules
@@ -5,3 +5,18 @@
override_dh_auto_configure:
dh_auto_configure -- -Wno-dev -DCMAKE_BUILD_TYPE=Release
+
+# Everything goes in wildos-office, the shared part, except the two
+# launchers: each is its app's own package, so Write and Tables can be
+# removed one at a time.
+L = usr/share/wildos/launchers
+override_dh_auto_install:
+ dh_auto_install --destdir=debian/wildos-office
+ mkdir -p debian/wildos-write/$(L) debian/wildos-tables/$(L)
+ mv debian/wildos-office/$(L)/libreoffice-writer.desktop debian/wildos-write/$(L)/
+ mv debian/wildos-office/$(L)/libreoffice-calc.desktop debian/wildos-tables/$(L)/
+ rmdir debian/wildos-office/$(L)
+
+# Started by postinst once dpkg has finished, never during the install.
+override_dh_installsystemd:
+ dh_installsystemd --name=wildos-office-split --no-start
diff --git a/packages/wildos-office/debian/wildos-office.wildos-office-split.service b/packages/wildos-office/debian/wildos-office.wildos-office-split.service
new file mode 100644
index 0000000..bb29d99
--- /dev/null
+++ b/packages/wildos-office/debian/wildos-office.wildos-office-split.service
@@ -0,0 +1,19 @@
+[Unit]
+Description=Install Write and Tables as their own packages
+# Left by postinst on a PC updating from before Write and Tables were split
+# out of wildos-office, and removed once both are in.
+ConditionPathExists=/var/lib/wildos/office-split
+Wants=network-online.target
+After=network-online.target
+
+[Service]
+Type=oneshot
+Environment=DEBIAN_FRONTEND=noninteractive
+# apt-get install also marks both as chosen, so removing one never takes the
+# other with it as no longer needed.
+ExecStart=/usr/bin/apt-get -o DPkg::Lock::Timeout=1800 -o Dpkg::Options::=--force-confold install -y -q --no-install-recommends wildos-write wildos-tables
+ExecStartPost=/usr/bin/rm -f /var/lib/wildos/office-split
+Nice=10
+
+[Install]
+WantedBy=multi-user.target
diff --git a/packages/wildos-overlays/CMakeLists.txt b/packages/wildos-overlays/CMakeLists.txt
index fc9645e..f8413fa 100644
--- a/packages/wildos-overlays/CMakeLists.txt
+++ b/packages/wildos-overlays/CMakeLists.txt
@@ -78,6 +78,7 @@ qt_add_qml_module(wildos-clipboard
QML_FILES ${CLIPBOARD_QML}
SOURCES
clipboard/panelapp.cpp clipboard/panelapp.h
+ clipboard/secretwiper.cpp clipboard/secretwiper.h
clipboard/pins.cpp clipboard/pins.h
clipboard/emojimodel.cpp clipboard/emojimodel.h
)
diff --git a/packages/wildos-overlays/clipboard/main.cpp b/packages/wildos-overlays/clipboard/main.cpp
index e21ee29..5d234ea 100644
--- a/packages/wildos-overlays/clipboard/main.cpp
+++ b/packages/wildos-overlays/clipboard/main.cpp
@@ -1,4 +1,5 @@
#include "panelapp.h"
+#include "secretwiper.h"
#include <KDBusService>
@@ -27,6 +28,7 @@ int main(int argc, char *argv[])
KDBusService service(KDBusService::Unique);
PanelApp panel;
+ SecretWiper wiper;
QObject::connect(&service, &KDBusService::activateRequested, &panel, [&panel](const QStringList &arguments, const QString &) {
panel.handle(arguments);
});
diff --git a/packages/wildos-overlays/clipboard/panelapp.cpp b/packages/wildos-overlays/clipboard/panelapp.cpp
index ffd0b38..84b1944 100644
--- a/packages/wildos-overlays/clipboard/panelapp.cpp
+++ b/packages/wildos-overlays/clipboard/panelapp.cpp
@@ -105,6 +105,11 @@ void PanelApp::setSkinTone(int tone)
void PanelApp::handle(const QStringList &arguments)
{
+ if (arguments.contains(QStringLiteral("--clear"))) {
+ setShown(false);
+ Q_EMIT clearRequested();
+ return;
+ }
if (arguments.contains(QStringLiteral("--daemon"))) {
return;
}
@@ -119,6 +124,13 @@ void PanelApp::handle(const QStringList &arguments)
setShown(true);
}
+void PanelApp::clearClipboard()
+{
+ auto *clipboard = KSystemClipboard::instance();
+ clipboard->clear(QClipboard::Clipboard);
+ clipboard->clear(QClipboard::Selection);
+}
+
void PanelApp::pasteIntoApp(bool terminal)
{
setShown(false);
diff --git a/packages/wildos-overlays/clipboard/panelapp.h b/packages/wildos-overlays/clipboard/panelapp.h
index 4ef6779..2253907 100644
--- a/packages/wildos-overlays/clipboard/panelapp.h
+++ b/packages/wildos-overlays/clipboard/panelapp.h
@@ -45,6 +45,8 @@ public:
// --emoji opens on the emoji tab, nothing (or --clipboard) on the
// clipboard; the same shortcut again hides it. --daemon starts hidden.
+ // --clear empties the history, the pins and the clipboard itself,
+ // without showing anything (the panic key).
void handle(const QStringList &arguments);
// After the clipboard has been set: hide, then paste into the app.
@@ -54,12 +56,16 @@ public:
Q_INVOKABLE void typeText(const QString &text, bool terminal);
Q_INVOKABLE void addRecentEmoji(const QString &emoji);
Q_INVOKABLE void copyText(const QString &text);
+ // After the history has gone: what is on the clipboard and the
+ // middle-click selection goes too.
+ Q_INVOKABLE void clearClipboard();
Q_SIGNALS:
void shownChanged();
void tabChanged();
void recentEmojiChanged();
void skinToneChanged();
+ void clearRequested();
private:
bool m_shown = false;
diff --git a/packages/wildos-overlays/clipboard/pins.cpp b/packages/wildos-overlays/clipboard/pins.cpp
index e11760d..5144a07 100644
--- a/packages/wildos-overlays/clipboard/pins.cpp
+++ b/packages/wildos-overlays/clipboard/pins.cpp
@@ -105,6 +105,18 @@ void Pins::unpin(const QString &key)
}
}
+void Pins::clear()
+{
+ for (const QVariant &value : std::as_const(m_items)) {
+ const QString image = QUrl(value.toMap().value(QStringLiteral("image")).toString()).toLocalFile();
+ if (!image.isEmpty()) {
+ QFile::remove(image);
+ }
+ }
+ m_items.clear();
+ save();
+}
+
void Pins::restore(const QString &key)
{
for (const QVariant &value : std::as_const(m_items)) {
diff --git a/packages/wildos-overlays/clipboard/pins.h b/packages/wildos-overlays/clipboard/pins.h
index 82441ad..2c697bd 100644
--- a/packages/wildos-overlays/clipboard/pins.h
+++ b/packages/wildos-overlays/clipboard/pins.h
@@ -30,6 +30,8 @@ public:
// Puts a pin back on the clipboard, for one that is no longer in the
// history after a restart.
Q_INVOKABLE void restore(const QString &key);
+ // Every pin and its picture gone from disk (the panic key).
+ Q_INVOKABLE void clear();
Q_SIGNALS:
void changed();
diff --git a/packages/wildos-overlays/clipboard/qml/ClipboardPage.qml b/packages/wildos-overlays/clipboard/qml/ClipboardPage.qml
index 6dee905..c9e3b23 100644
--- a/packages/wildos-overlays/clipboard/qml/ClipboardPage.qml
+++ b/packages/wildos-overlays/clipboard/qml/ClipboardPage.qml
@@ -152,6 +152,21 @@ Item {
function onDataChanged() { page.rebuild(); }
}
+ // The history goes first: Klipper puts its newest item back on the
+ // clipboard when the clipboard empties. Item by item, because Klipper's
+ // own clearHistory() asks first in a dialog, which the lock screen
+ // would hide until sign-in.
+ Connections {
+ target: PanelApp
+ function onClearRequested() {
+ for (let i = history.count - 1; i >= 0; i--) {
+ history.remove(String(history.data(history.index(i, 0), page.uuidRole)));
+ }
+ Pins.clear();
+ PanelApp.clearClipboard();
+ }
+ }
+
Connections {
target: Pins
function onChanged() { page.rebuild(); }
diff --git a/packages/wildos-overlays/clipboard/secretwiper.cpp b/packages/wildos-overlays/clipboard/secretwiper.cpp
new file mode 100644
index 0000000..e8d6bfc
--- /dev/null
+++ b/packages/wildos-overlays/clipboard/secretwiper.cpp
@@ -0,0 +1,95 @@
+#include "secretwiper.h"
+
+#include <KSystemClipboard>
+
+#include <QCryptographicHash>
+#include <QFile>
+#include <QMimeData>
+
+namespace
+{
+const QString storeDir = QStringLiteral("/etc/wildos");
+const QString storeFile = QStringLiteral("/etc/wildos/advanced-protection");
+const QString hint = QStringLiteral("x-kde-passwordManagerHint");
+constexpr int forgetAfter = 60 * 1000;
+}
+
+SecretWiper::SecretWiper(QObject *parent)
+ : QObject(parent)
+{
+ m_timer.setSingleShot(true);
+ m_timer.setInterval(forgetAfter);
+ connect(&m_timer, &QTimer::timeout, this, &SecretWiper::wipe);
+ connect(KSystemClipboard::instance(), &KSystemClipboard::changed, this, &SecretWiper::clipboardChanged);
+ // The store is replaced as a whole, so its folder is what changes.
+ m_watcher.addPath(storeDir);
+ connect(&m_watcher, &QFileSystemWatcher::directoryChanged, this, &SecretWiper::readChoice);
+ readChoice();
+ clipboardChanged(QClipboard::Clipboard);
+}
+
+void SecretWiper::readChoice()
+{
+ bool on = true;
+ QFile file(storeFile);
+ if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
+ while (!file.atEnd()) {
+ const QByteArray line = file.readLine().trimmed();
+ if (line.startsWith("clipboard_forget=")) {
+ on = line.mid(17) != "off";
+ }
+ }
+ }
+ if (on == m_on) {
+ return;
+ }
+ m_on = on;
+ if (!on) {
+ m_timer.stop();
+ m_secret.clear();
+ } else {
+ clipboardChanged(QClipboard::Clipboard);
+ }
+}
+
+QByteArray SecretWiper::fingerprint() const
+{
+ const QMimeData *data = KSystemClipboard::instance()->mimeData(QClipboard::Clipboard);
+ if (!data) {
+ return {};
+ }
+ QCryptographicHash hash(QCryptographicHash::Sha256);
+ for (const QString &format : data->formats()) {
+ hash.addData(format.toUtf8());
+ hash.addData(QByteArrayView("\0", 1));
+ hash.addData(data->data(format));
+ }
+ return hash.result();
+}
+
+void SecretWiper::clipboardChanged(QClipboard::Mode mode)
+{
+ if (mode != QClipboard::Clipboard || !m_on) {
+ return;
+ }
+ const QMimeData *data = KSystemClipboard::instance()->mimeData(QClipboard::Clipboard);
+ if (data && data->data(hint) == "secret") {
+ m_secret = fingerprint();
+ m_timer.start();
+ } else {
+ m_timer.stop();
+ m_secret.clear();
+ }
+}
+
+void SecretWiper::wipe()
+{
+ if (!m_on || m_secret.isEmpty()) {
+ return;
+ }
+ // Only the entry that was copied: anything copied since stays.
+ if (fingerprint() == m_secret) {
+ KSystemClipboard::instance()->clear(QClipboard::Clipboard);
+ }
+ m_secret.clear();
+}
diff --git a/packages/wildos-overlays/clipboard/secretwiper.h b/packages/wildos-overlays/clipboard/secretwiper.h
new file mode 100644
index 0000000..98e4d83
--- /dev/null
+++ b/packages/wildos-overlays/clipboard/secretwiper.h
@@ -0,0 +1,32 @@
+#pragma once
+
+#include <QByteArray>
+#include <QClipboard>
+#include <QFileSystemWatcher>
+#include <QObject>
+#include <QTimer>
+
+// Advanced protection's "Clipboard forgets passwords" (clipboard_forget in
+// /etc/wildos/advanced-protection, on unless it says off). Anything put on
+// the clipboard marked x-kde-passwordManagerHint=secret, as password
+// managers and Wild OS's own password boxes mark what they copy, is wiped
+// 60 seconds later, if the clipboard still holds it then. Lives in the
+// clipboard panel because that runs in every session from sign-in.
+class SecretWiper : public QObject
+{
+ Q_OBJECT
+
+public:
+ explicit SecretWiper(QObject *parent = nullptr);
+
+private:
+ void readChoice();
+ void clipboardChanged(QClipboard::Mode mode);
+ void wipe();
+ QByteArray fingerprint() const;
+
+ QFileSystemWatcher m_watcher;
+ QTimer m_timer;
+ QByteArray m_secret;
+ bool m_on = true;
+};
diff --git a/packages/wildos-overlays/debian/changelog b/packages/wildos-overlays/debian/changelog
index 31b2270..aad4f03 100644
--- a/packages/wildos-overlays/debian/changelog
+++ b/packages/wildos-overlays/debian/changelog
@@ -1,3 +1,13 @@
+wildos-overlays (0.1.3) trixie; urgency=medium
+
+ * Passwords copied from a password manager or a Wild OS password box
+ are wiped from the clipboard after 60 seconds, unless Clipboard
+ forgets passwords is off in Advanced protection.
+ * The panic key in Advanced protection can empty the clipboard history,
+ its pinned items and the clipboard itself.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 14:56:10 +0000
+
wildos-overlays (0.1.2) trixie; urgency=medium
* No navy left: surfaces, glass, shadows and the logo tile use the
diff --git a/packages/wildos-pdf/debian/changelog b/packages/wildos-pdf/debian/changelog
index 869ffa7..59e9a0e 100644
--- a/packages/wildos-pdf/debian/changelog
+++ b/packages/wildos-pdf/debian/changelog
@@ -1,3 +1,17 @@
+wildos-pdf (0.1.5) trixie; urgency=medium
+
+ * The page number box, text you type onto a page and form fields
+ have the right-click menu with Cut, Copy, Paste and Select all.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 08:54:22 +0000
+
+wildos-pdf (0.1.4) trixie; urgency=medium
+
+ * wildos-pdf --sign FILE opens the file with Sign chosen, for Capture's
+ Open in PDF to sign.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 17:20:00 +0000
+
wildos-pdf (0.1.3) trixie; urgency=medium
* A two-finger pinch on the touchpad zooms, and a two-finger twist turns
diff --git a/packages/wildos-pdf/debian/control b/packages/wildos-pdf/debian/control
index bd063b5..267dc5b 100644
--- a/packages/wildos-pdf/debian/control
+++ b/packages/wildos-pdf/debian/control
@@ -18,7 +18,7 @@ Architecture: any
Depends:
${shlibs:Depends},
${misc:Depends},
- wildos-ui (>= 0.1.3),
+ wildos-ui (>= 0.1.11),
qml6-module-qtcore,
qml6-module-qtquick,
qml6-module-qtquick-controls,
diff --git a/packages/wildos-pdf/qml/Main.qml b/packages/wildos-pdf/qml/Main.qml
index a2abc6b..4b8e13a 100644
--- a/packages/wildos-pdf/qml/Main.qml
+++ b/packages/wildos-pdf/qml/Main.qml
@@ -14,6 +14,8 @@ UI.AppWindow {
// From main.cpp: why the file it was started with didn't open.
property string openError
+ // From main.cpp: the tool to start with, "sign" for --sign.
+ property string startTool
property string tool: "select"
property bool showThumbnails: true
// Set while a save opens the saved file again, so the view stays put.
@@ -507,13 +509,35 @@ UI.AppWindow {
follow();
window.focusPages();
}
+ // The text menu holds focus while it is open, and coming
+ // back from it keeps the selection it worked on.
+ property bool inMenu: false
onActiveFocusChanged: {
- if (activeFocus) {
- selectAll();
+ if (pageMenu.opened) {
+ inMenu = true;
+ } else if (activeFocus) {
+ if (!inMenu) {
+ selectAll();
+ }
+ inMenu = false;
} else {
follow();
}
}
+ Keys.onPressed: event => {
+ if (pageMenu.isMenuKey(event)) {
+ pageMenu.openAtCaret();
+ event.accepted = true;
+ }
+ }
+
+ UI.TextMenu {
+ id: pageMenu
+ onFocusLeft: {
+ pageInput.inMenu = false;
+ pageInput.follow();
+ }
+ }
}
}
UI.Label {
@@ -946,6 +970,8 @@ UI.AppWindow {
Component.onCompleted: {
if (PdfDocument.locked) {
passwordDialog.ask();
+ } else if (startTool.length > 0) {
+ setTool(startTool);
} else {
focusPages();
}
diff --git a/packages/wildos-pdf/qml/PageItem.qml b/packages/wildos-pdf/qml/PageItem.qml
index 1444db3..0fbf434 100644
--- a/packages/wildos-pdf/qml/PageItem.qml
+++ b/packages/wildos-pdf/qml/PageItem.qml
@@ -284,9 +284,19 @@ Item {
editor.open = false;
input.text = "";
event.accepted = true;
+ } else if (inputMenu.isMenuKey(event)) {
+ inputMenu.openAtCaret();
+ event.accepted = true;
}
}
- onActiveFocusChanged: if (!activeFocus) editor.commit()
+ // The text menu holds focus while it is open; the text is still
+ // being typed.
+ onActiveFocusChanged: if (!activeFocus && !inputMenu.opened) editor.commit()
+
+ UI.TextMenu {
+ id: inputMenu
+ onFocusLeft: editor.commit()
+ }
}
}
@@ -347,7 +357,8 @@ Item {
if (most > 0 && text.length > most) {
remove(most, text.length);
}
- dirty = activeFocus;
+ // A paste from the text menu lands while the menu holds focus.
+ dirty = activeFocus || textBoxMenu.opened;
}
function save() {
if (dirty) {
@@ -363,9 +374,16 @@ Item {
save();
nextItemInFocusChain(true).forceActiveFocus(Qt.TabFocusReason);
event.accepted = true;
+ } else if (textBoxMenu.isMenuKey(event)) {
+ textBoxMenu.openAtCaret();
+ event.accepted = true;
}
}
- onActiveFocusChanged: if (!activeFocus) save()
+ onActiveFocusChanged: if (!activeFocus && !textBoxMenu.opened) save()
+ UI.TextMenu {
+ id: textBoxMenu
+ onFocusLeft: textBox.save()
+ }
Connections {
target: page.app
function onCommitEdits() {
diff --git a/packages/wildos-pdf/src/main.cpp b/packages/wildos-pdf/src/main.cpp
index cfaa186..8a9bc72 100644
--- a/packages/wildos-pdf/src/main.cpp
+++ b/packages/wildos-pdf/src/main.cpp
@@ -3,6 +3,8 @@
// Nothing goes online.
//
// wildos-pdf [file.pdf]
+// wildos-pdf --sign file.pdf opens with Sign chosen, for Capture's
+// Open in PDF to sign
//
// Each file opens in a PDF of its own.
@@ -95,6 +97,8 @@ int main(int argc, char *argv[])
parser.addHelpOption();
parser.addVersionOption();
parser.addPositionalArgument(QStringLiteral("file"), QStringLiteral("A PDF to open."));
+ const QCommandLineOption sign(QStringLiteral("sign"), QStringLiteral("Open with Sign chosen."));
+ parser.addOption(sign);
parser.process(app);
const QString arg = parser.positionalArguments().value(0);
const QUrl url = arg.isEmpty() ? QUrl() : QUrl::fromUserInput(arg, QDir::currentPath(), QUrl::AssumeLocalFile);
@@ -122,6 +126,9 @@ int main(int argc, char *argv[])
QQmlComponent home(&engine);
QQmlIncubator incubator(QQmlIncubator::Asynchronous);
QVariantMap initial{{QStringLiteral("openError"), openError}};
+ if (parser.isSet(sign) && openError.isEmpty() && url.isValid() && !url.isEmpty()) {
+ initial.insert(QStringLiteral("startTool"), QStringLiteral("sign"));
+ }
if (splash) {
// Built hidden behind the splash and shown as it fades.
initial.insert(QStringLiteral("visible"), false);
diff --git a/packages/wildos-portal/CMakeLists.txt b/packages/wildos-portal/CMakeLists.txt
index 4baa0fd..fb76722 100644
--- a/packages/wildos-portal/CMakeLists.txt
+++ b/packages/wildos-portal/CMakeLists.txt
@@ -33,6 +33,7 @@ qt_add_qml_module(wildos-portal
src/filechooser.cpp src/filechooser.h
src/clash.cpp src/clash.h
src/windows.cpp src/windows.h
+ src/thumbnails.cpp src/thumbnails.h
)
target_include_directories(wildos-portal PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src)
diff --git a/packages/wildos-portal/debian/changelog b/packages/wildos-portal/debian/changelog
index 223d5f1..8afdbcb 100644
--- a/packages/wildos-portal/debian/changelog
+++ b/packages/wildos-portal/debian/changelog
@@ -1,3 +1,36 @@
+wildos-portal (0.1.6) trixie; urgency=medium
+
+ * The location box in open and save dialogs has the right-click menu
+ with Cut, Copy, Paste and Select all, and renaming there stays
+ open while the menu is up.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 08:54:22 +0000
+
+wildos-portal (0.1.5) trixie; urgency=medium
+
+ * The Open dialog opens a file whose full path is typed in File name,
+ such as ~/Documents/notes.txt, instead of saying it is not in the
+ folder.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 07:55:00 +0000
+
+wildos-portal (0.1.4) trixie; urgency=medium
+
+ * The Open dialog can show Large icons with a preview of each picture,
+ as on Windows, through the switch beside New folder. Choosing a photo
+ opens in Large icons, other files in Details, and the dialog keeps the
+ view you pick for that kind of file.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 22:26:46 +0000
+
+wildos-portal (0.1.3) trixie; urgency=medium
+
+ * The Open and Save dialog is attached to the window that opened it, as
+ on Windows: it has no taskbar button of its own, stays in front of
+ that window, and the window waits until the dialog closes.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 20:41:57 +0000
+
wildos-portal (0.1.2) trixie; urgency=medium
* The Open and Save dialog starts where you last opened or saved that
diff --git a/packages/wildos-portal/debian/control b/packages/wildos-portal/debian/control
index f4e9eb5..1020338 100644
--- a/packages/wildos-portal/debian/control
+++ b/packages/wildos-portal/debian/control
@@ -23,13 +23,14 @@ Depends:
xdg-desktop-portal,
xdg-desktop-portal-kde,
kio6,
+ kio-extras,
qml6-module-qtcore,
qml6-module-qtquick,
qml6-module-qtquick-controls,
qml6-module-qtquick-layouts,
qml6-module-qtquick-templates,
qml6-module-qtquick-window,
- wildos-ui,
+ wildos-ui (>= 0.1.11),
Description: Wild OS Open and Save dialog and file clash dialog
One Open and Save dialog for every app, laid out like the one on Windows:
places on the left, a path bar, the file list with dates, types and sizes,
diff --git a/packages/wildos-portal/qml/FileChooser.qml b/packages/wildos-portal/qml/FileChooser.qml
index b3f4806..6f4e3c4 100644
--- a/packages/wildos-portal/qml/FileChooser.qml
+++ b/packages/wildos-portal/qml/FileChooser.qml
@@ -7,8 +7,8 @@ import WildOS.UI as UI
// DialogSave.dc (8.1): the one Open and Save dialog every app gets. A 920
// by 620 glass window: title bar, a 52px tool row (back, forward, up, the
-// path bar, search, New folder), places on the left, the details list,
-// then the name and type fields on a darker band and the buttons, the main
+// path bar, search, New folder, the view switch), places on the left, the
+// details list or Large icons, then the name and type fields on a darker band and the buttons, the main
// one at the right.
UI.AppWindow {
id: win
@@ -248,6 +248,36 @@ UI.AppWindow {
enabled: win.folder.writable
onClicked: win.folder.newFolder()
}
+
+ // Files' view switch: Details, or Large icons with previews.
+ Row {
+ spacing: 0
+
+ UI.IconButton {
+ implicitWidth: 32
+ implicitHeight: 32
+ enabled: !win.folder.isComputer
+ iconName: "list"
+ iconSize: 14
+ tip: "Details"
+ checked: win.chooser.viewMode === "details" || win.folder.isComputer
+ Accessible.checkable: true
+ Accessible.checked: checked
+ onClicked: win.chooser.viewMode = "details"
+ }
+ UI.IconButton {
+ implicitWidth: 32
+ implicitHeight: 32
+ enabled: !win.folder.isComputer
+ iconName: "grid"
+ iconSize: 14
+ tip: "Large icons"
+ checked: win.chooser.viewMode === "icons" && !win.folder.isComputer
+ Accessible.checkable: true
+ Accessible.checked: checked
+ onClicked: win.chooser.viewMode = "icons"
+ }
+ }
}
Rectangle {
@@ -284,6 +314,7 @@ UI.AppWindow {
Layout.topMargin: 6
Layout.bottomMargin: 6
folder: win.folder
+ mode: win.chooser.viewMode
focus: true
onActivated: row => win.activate(row)
emptyText: {
diff --git a/packages/wildos-portal/qml/FileList.qml b/packages/wildos-portal/qml/FileList.qml
index 7c4e89c..a0ccea3 100644
--- a/packages/wildos-portal/qml/FileList.qml
+++ b/packages/wildos-portal/qml/FileList.qml
@@ -10,10 +10,16 @@ import WildOS.UI as UI
// 20px icon, the name in 13px and the rest in 12px muted. Click selects
// (Ctrl and Shift add when several may be opened), double click opens a
// folder or chooses the file, and typing jumps to a name.
+//
+// Large icons, the other view, lays the same items out as Files' Large
+// icons tiles (140 by 150, a 96px icon or a preview of the picture) so
+// photos can be told apart by what is in them.
FocusScope {
id: list
required property var folder
+ property string mode: "details"
+ readonly property bool icons: mode === "icons" && !folder.isComputer
property bool showSize: true
property int renameRow: -1
property string typed: ""
@@ -25,11 +31,26 @@ FocusScope {
property string emptyActionName: ""
function startRename(row) {
- view.positionViewAtIndex(row, ListView.Contain);
+ show(row);
renameRow = row;
}
+ function show(row) {
+ if (icons) {
+ grid.positionViewAtIndex(row, GridView.Contain);
+ } else {
+ view.positionViewAtIndex(row, ListView.Contain);
+ }
+ }
+
+ function columns() {
+ return icons ? Math.max(1, Math.floor(grid.width / grid.cellWidth)) : 1;
+ }
+
function pageRows() {
+ if (icons) {
+ return Math.max(1, Math.floor(grid.height / grid.cellHeight)) * columns();
+ }
return Math.max(1, Math.floor(view.height / 36) - 1);
}
@@ -38,8 +59,12 @@ FocusScope {
const mods = event.modifiers & (Qt.ControlModifier | Qt.ShiftModifier);
const cur = f.currentIndex;
if (event.key === Qt.Key_Down) {
- f.moveCurrent(cur + 1, mods);
+ f.moveCurrent(cur < 0 ? 0 : Math.min(f.count - 1, cur + columns()), mods);
} else if (event.key === Qt.Key_Up) {
+ f.moveCurrent(Math.max(0, cur - columns()), mods);
+ } else if (event.key === Qt.Key_Right && icons) {
+ f.moveCurrent(cur + 1, mods);
+ } else if (event.key === Qt.Key_Left && icons) {
f.moveCurrent(Math.max(0, cur - 1), mods);
} else if (event.key === Qt.Key_Home) {
f.moveCurrent(0, mods);
@@ -80,23 +105,32 @@ FocusScope {
target: list.folder
function onCurrentIndexChanged() {
if (list.folder.currentIndex >= 0) {
- view.positionViewAtIndex(list.folder.currentIndex, ListView.Contain);
+ list.show(list.folder.currentIndex);
}
}
function onUrlChanged() {
list.renameRow = -1;
view.positionViewAtBeginning();
+ grid.positionViewAtBeginning();
}
function onFolderMade(row) {
list.startRename(row);
}
}
+ onIconsChanged: {
+ renameRow = -1;
+ if (folder.currentIndex >= 0) {
+ Qt.callLater(show, folder.currentIndex);
+ }
+ }
+
Item {
id: header
x: 0
width: parent.width
height: 30
+ visible: !list.icons
component HeaderCell: Item {
id: cell
@@ -163,8 +197,9 @@ FocusScope {
anchors.left: parent.left
anchors.right: parent.right
anchors.bottom: parent.bottom
+ visible: !list.icons
clip: true
- model: list.folder
+ model: list.icons ? null : list.folder
boundsBehavior: Flickable.StopAtBounds
reuseItems: true
activeFocusOnTab: false
@@ -249,7 +284,9 @@ FocusScope {
list.forceActiveFocus();
}
onAccepted: commit()
- onActiveFocusChanged: if (!activeFocus) commit()
+ // The text menu holds focus while it is open; the rename is not over.
+ onActiveFocusChanged: if (!activeFocus && !textMenuOpen) commit()
+ onTextMenuFocusLeft: commit()
Keys.onEscapePressed: {
finished = true;
list.renameRow = -1;
@@ -310,10 +347,166 @@ FocusScope {
}
}
+ GridView {
+ id: grid
+ anchors.fill: parent
+ anchors.topMargin: 6
+ visible: list.icons
+ clip: true
+ // 8px between tiles, as in Files, so a selected tile's highlight
+ // keeps clear of its neighbours.
+ cellWidth: 148
+ cellHeight: 158
+ model: list.icons ? list.folder : null
+ boundsBehavior: Flickable.StopAtBounds
+ reuseItems: true
+ activeFocusOnTab: false
+ bottomMargin: 6
+ ScrollBar.vertical: UI.ScrollBar {}
+ Accessible.role: Accessible.List
+ Accessible.name: list.folder.title
+
+ delegate: Item {
+ id: tile
+
+ required property int index
+ required property string name
+ required property string iconName
+ required property url url
+ required property bool isDir
+ required property bool selected
+ required property bool hidden
+ required property bool preview
+ required property var stamp
+
+ width: 140
+ height: 150
+ Accessible.role: Accessible.ListItem
+ Accessible.name: name
+ Accessible.selected: selected
+
+ Rectangle {
+ anchors.fill: parent
+ radius: 8
+ color: tile.selected ? UI.Style.accentSelected : tileMouse.containsMouse ? UI.Style.surfaceHover : "transparent"
+ border.width: 1
+ border.color: tile.selected ? UI.Style.accentBorderStrong
+ : list.activeFocus && list.folder.currentIndex === tile.index ? UI.Style.accentBorderStrong : "transparent"
+ }
+
+ Column {
+ anchors.centerIn: parent
+ width: parent.width - 8
+ spacing: 6
+
+ Item {
+ anchors.horizontalCenter: parent.horizontalCenter
+ width: 96
+ height: 96
+ opacity: tile.hidden ? 0.5 : 1
+
+ UI.ThemeIcon {
+ anchors.fill: parent
+ visible: thumb.status !== Image.Ready
+ name: tile.iconName
+ fallback: tile.isDir ? "folder" : "text-x-generic"
+ }
+
+ Image {
+ id: thumb
+ anchors.fill: parent
+ visible: status === Image.Ready
+ asynchronous: true
+ cache: true
+ fillMode: Image.PreserveAspectFit
+ sourceSize: Qt.size(192, 192)
+ source: tile.preview ? "image://thumb/" + tile.stamp + "/" + encodeURIComponent(tile.url.toString()) : ""
+ smooth: true
+ mipmap: true
+ }
+ }
+
+ UI.Label {
+ visible: list.renameRow !== tile.index
+ width: parent.width
+ horizontalAlignment: Text.AlignHCenter
+ wrapMode: Text.Wrap
+ maximumLineCount: 2
+ elide: Text.ElideRight
+ size: 12
+ lineHeight: 1.1
+ text: tile.name
+ opacity: tile.hidden ? 0.6 : 1
+ }
+
+ Loader {
+ width: parent.width
+ active: list.renameRow === tile.index
+ visible: active
+ sourceComponent: UI.TextField {
+ height: 28
+ implicitHeight: 28
+ text: tile.name
+ escapeClears: false
+ Component.onCompleted: {
+ forceActiveFocus();
+ selectAll();
+ }
+ property bool finished: false
+ function commit() {
+ if (finished) {
+ return;
+ }
+ finished = true;
+ list.folder.renameItem(tile.index, text);
+ list.renameRow = -1;
+ list.forceActiveFocus();
+ }
+ onAccepted: commit()
+ // The text menu holds focus while it is open; the rename is not over.
+ onActiveFocusChanged: if (!activeFocus && !textMenuOpen) commit()
+ onTextMenuFocusLeft: commit()
+ Keys.onEscapePressed: {
+ finished = true;
+ list.renameRow = -1;
+ list.forceActiveFocus();
+ }
+ }
+ }
+ }
+
+ MouseArea {
+ id: tileMouse
+ anchors.fill: parent
+ hoverEnabled: true
+ acceptedButtons: Qt.LeftButton
+ enabled: list.renameRow !== tile.index
+ onPressed: mouse => {
+ list.forceActiveFocus();
+ list.folder.select(tile.index, mouse.modifiers);
+ }
+ onDoubleClicked: list.activated(tile.index)
+ }
+ }
+
+ // Clicking between or below the tiles clears the selection.
+ MouseArea {
+ parent: grid.contentItem
+ z: -1
+ width: Math.max(grid.width, grid.contentWidth)
+ height: Math.max(grid.height, grid.contentHeight)
+ onPressed: {
+ list.forceActiveFocus();
+ list.folder.clearSelection();
+ }
+ }
+ }
+
+
ColumnLayout {
- anchors.centerIn: view
+ anchors.centerIn: list.icons ? grid : view
width: Math.min(view.width - 40, 360)
- visible: list.emptyText.length > 0 && view.count === 0
+ visible: list.emptyText.length > 0 && list.folder.count === 0
spacing: 12
UI.Label {
diff --git a/packages/wildos-portal/qml/PathBar.qml b/packages/wildos-portal/qml/PathBar.qml
index 3934784..945e985 100644
--- a/packages/wildos-portal/qml/PathBar.qml
+++ b/packages/wildos-portal/qml/PathBar.qml
@@ -137,10 +137,23 @@ Rectangle {
bar.folder.failed("Wild OS cannot find \"" + text + "\". Check the spelling and try again.");
}
}
- onActiveFocusChanged: if (!activeFocus) bar.editing = false
+ // The text menu holds focus while it is open; the location is still
+ // being typed.
+ onActiveFocusChanged: if (!activeFocus && !locationMenu.opened) bar.editing = false
Keys.onEscapePressed: {
bar.editing = false;
bar.done();
}
+ Keys.onPressed: event => {
+ if (locationMenu.isMenuKey(event)) {
+ locationMenu.openAtCaret();
+ event.accepted = true;
+ }
+ }
+
+ UI.TextMenu {
+ id: locationMenu
+ onFocusLeft: bar.editing = false
+ }
}
}
diff --git a/packages/wildos-portal/src/chooser.cpp b/packages/wildos-portal/src/chooser.cpp
index 15c88d9..b1013c8 100644
--- a/packages/wildos-portal/src/chooser.cpp
+++ b/packages/wildos-portal/src/chooser.cpp
@@ -171,6 +171,26 @@ Chooser::Chooser(const Request &request, QObject *parent)
m_purpose = m_request.mode == Folder || m_request.mode == SaveFiles ? QStringLiteral("folders") : purposeOf(m_request.filters);
m_folder->openUrl(startFolder());
m_initialName = displayName(m_request.name);
+
+ // Pictures open in Large icons so they can be told apart, everything
+ // else in Details, until the person picks a view for that kind.
+ const QSettings recent(recentFoldersFile(), QSettings::IniFormat);
+ const QString saved = recent.value(QStringLiteral("view/") + m_purpose).toString();
+ m_viewMode = saved == QLatin1String("icons") || saved == QLatin1String("details") ? saved
+ : m_purpose == QLatin1String("pictures") ? QStringLiteral("icons")
+ : QStringLiteral("details");
+}
+
+void Chooser::setViewMode(const QString &mode)
+{
+ if (mode == m_viewMode || (mode != QLatin1String("icons") && mode != QLatin1String("details"))) {
+ return;
+ }
+ m_viewMode = mode;
+ Q_EMIT viewModeChanged();
+ QDir().mkpath(QFileInfo(recentFoldersFile()).absolutePath());
+ QSettings recent(recentFoldersFile(), QSettings::IniFormat);
+ recent.setValue(QStringLiteral("view/") + m_purpose, mode);
}
QString Chooser::recentKey() const
@@ -582,6 +602,16 @@ QString Chooser::accept(const QString &typedText)
}
if (row >= 0) {
urls.append(folder->urlAt(row));
+ } else if (typed.contains(QLatin1Char('/')) && !typed.contains(QStringLiteral(":/"))) {
+ // A path typed in full opens that file, as Save does.
+ QString path = typed.startsWith(QStringLiteral("~/")) ? QDir::homePath() + typed.mid(1) : typed;
+ if (!path.startsWith(QLatin1Char('/')) && folder->url().isLocalFile()) {
+ path = QDir(folder->url().toLocalFile()).absoluteFilePath(path);
+ }
+ if (!QFileInfo(path).isFile()) {
+ return QStringLiteral("\"%1\" does not exist. Check the name, or pick the file in the list.").arg(typed);
+ }
+ urls.append(QUrl::fromLocalFile(QFileInfo(path).absoluteFilePath()));
} else {
const QUrl url = folder->childUrl(typed);
if (url.isLocalFile() && !QFileInfo::exists(url.toLocalFile())) {
diff --git a/packages/wildos-portal/src/chooser.h b/packages/wildos-portal/src/chooser.h
index ba91c59..d7d3647 100644
--- a/packages/wildos-portal/src/chooser.h
+++ b/packages/wildos-portal/src/chooser.h
@@ -31,6 +31,8 @@ class Chooser : public QObject
Q_PROPERTY(QString initialName READ initialName CONSTANT)
Q_PROPERTY(QString nameLabel READ nameLabel CONSTANT)
Q_PROPERTY(QString typeLabel READ typeLabel CONSTANT)
+ // "details" or "icons" (Large icons), remembered per kind of file.
+ Q_PROPERTY(QString viewMode READ viewMode WRITE setViewMode NOTIFY viewModeChanged)
public:
enum Mode { Open, Save, SaveFiles, Folder };
@@ -64,6 +66,8 @@ public:
QString initialName() const { return m_initialName; }
QString nameLabel() const;
QString typeLabel() const;
+ QString viewMode() const { return m_viewMode; }
+ void setViewMode(const QString &mode);
// What the name field holds once a file is picked in the list.
Q_INVOKABLE QString nameForSelection() const;
@@ -91,6 +95,7 @@ public:
Q_SIGNALS:
void currentFilterChanged();
void choicesChanged();
+ void viewModeChanged();
private:
QString suffixFor(int filter) const;
@@ -108,6 +113,7 @@ private:
QHash<QString, QString> m_chosen;
QString m_initialName;
QString m_purpose;
+ QString m_viewMode;
QList<QUrl> m_pending;
bool m_done = false;
};
diff --git a/packages/wildos-portal/src/dirmodel.cpp b/packages/wildos-portal/src/dirmodel.cpp
index 38a69d3..903e799 100644
--- a/packages/wildos-portal/src/dirmodel.cpp
+++ b/packages/wildos-portal/src/dirmodel.cpp
@@ -7,6 +7,7 @@
#include <KCoreDirLister>
#include <KIO/MkdirJob>
#include <KIO/CopyJob>
+#include <KIO/PreviewJob>
#include <KSharedConfig>
#include <QDir>
#include <QFileInfo>
@@ -17,6 +18,39 @@
namespace
{
+// Whether KIO can draw a picture of this type for Large icons, as Files
+// decides it.
+bool previewable(const QMimeType &mime)
+{
+ static const QStringList supported = KIO::PreviewJob::supportedMimeTypes();
+ static QSet<QString> exact;
+ static QStringList wildcards;
+ if (exact.isEmpty()) {
+ for (const QString &type : supported) {
+ if (type.endsWith(QStringLiteral("/*"))) {
+ wildcards.append(type.left(type.size() - 1));
+ } else {
+ exact.insert(type);
+ }
+ }
+ }
+ if (exact.contains(mime.name())) {
+ return true;
+ }
+ for (const QString &prefix : std::as_const(wildcards)) {
+ if (mime.name().startsWith(prefix)) {
+ return true;
+ }
+ }
+ const auto parents = mime.allAncestors();
+ for (const QString &parent : parents) {
+ if (exact.contains(parent)) {
+ return true;
+ }
+ }
+ return false;
+}
+
bool isUnder(const QString &path, const QString &root)
{
return path == root || path.startsWith(root.endsWith(QLatin1Char('/')) ? root : root + QLatin1Char('/'));
@@ -173,6 +207,10 @@ QVariant DirModel::data(const QModelIndex &index, int role) const
return e.selected;
case HiddenRole:
return e.hidden;
+ case PreviewRole:
+ return e.preview;
+ case StampRole:
+ return e.dateKey;
}
return {};
}
@@ -190,6 +228,8 @@ QHash<int, QByteArray> DirModel::roleNames() const
{SizeRole, "size"},
{SelectedRole, "selected"},
{HiddenRole, "hidden"},
+ {PreviewRole, "preview"},
+ {StampRole, "stamp"},
};
}
@@ -471,6 +511,7 @@ DirModel::Entry DirModel::makeEntry(const KFileItem &item) const
if (!e.isDir) {
e.sizeKey = qint64(item.size());
e.size = Format::size(e.sizeKey);
+ e.preview = item.isLocalFile() && e.sizeKey < 100LL * 1024 * 1024 && previewable(item.currentMimeType());
}
return e;
}
diff --git a/packages/wildos-portal/src/dirmodel.h b/packages/wildos-portal/src/dirmodel.h
index a21f002..0df2d56 100644
--- a/packages/wildos-portal/src/dirmodel.h
+++ b/packages/wildos-portal/src/dirmodel.h
@@ -51,6 +51,8 @@ public:
SizeRole,
SelectedRole,
HiddenRole,
+ PreviewRole,
+ StampRole,
};
Q_ENUM(Roles)
@@ -148,6 +150,7 @@ private:
qint64 sizeKey = -1;
bool isDir = false;
bool hidden = false;
+ bool preview = false;
bool selected = false;
};
diff --git a/packages/wildos-portal/src/filechooser.cpp b/packages/wildos-portal/src/filechooser.cpp
index a95cd30..0dbd7d8 100644
--- a/packages/wildos-portal/src/filechooser.cpp
+++ b/packages/wildos-portal/src/filechooser.cpp
@@ -135,7 +135,10 @@ void FileChooserPortal::start(int mode, const QDBusObjectPath &handle, const QSt
auto portalRequest = new PortalRequest(handle, chooser, chooser);
Q_UNUSED(portalRequest);
- QQuickWindow *window = Windows::instance()->open(QStringLiteral("FileChooser"), {{QStringLiteral("chooser"), QVariant::fromValue(chooser)}}, parentWindow);
+ QQuickWindow *window = Windows::instance()->open(QStringLiteral("FileChooser"),
+ {{QStringLiteral("chooser"), QVariant::fromValue(chooser)}},
+ parentWindow,
+ options.value(QStringLiteral("modal"), true).toBool());
if (!window) {
QDBusConnection::sessionBus().send(call.createErrorReply(QDBusError::Failed, QStringLiteral("The Wild OS file dialog could not open")));
chooser->deleteLater();
diff --git a/packages/wildos-portal/src/thumbnails.cpp b/packages/wildos-portal/src/thumbnails.cpp
new file mode 100644
index 0000000..842ec24
--- /dev/null
+++ b/packages/wildos-portal/src/thumbnails.cpp
@@ -0,0 +1,85 @@
+#include "thumbnails.h"
+
+#include <KFileItem>
+#include <KIO/PreviewJob>
+#include <QCoreApplication>
+#include <QPointer>
+#include <QUrl>
+
+namespace
+{
+class ThumbnailResponse : public QQuickImageResponse
+{
+public:
+ ThumbnailResponse(const QUrl &url, const QSize &size)
+ {
+ // KIO jobs belong to the main thread.
+ QMetaObject::invokeMethod(QCoreApplication::instance(), [this, url, size, guard = QPointer<ThumbnailResponse>(this)] {
+ if (!guard) {
+ return;
+ }
+ const KFileItem item(url);
+ auto job = KIO::filePreview(KFileItemList{item}, size.isValid() ? size : QSize(256, 256));
+ job->setScaleType(KIO::PreviewJob::ScaledAndCached);
+ job->setIgnoreMaximumSize(false);
+ m_job = job;
+ QObject::connect(job, &KIO::PreviewJob::gotPreview, job, [guard](const KFileItem &, const QPixmap &pixmap) {
+ if (guard) {
+ guard->m_image = pixmap.toImage();
+ }
+ });
+ QObject::connect(job, &KJob::result, job, [guard] {
+ if (guard) {
+ Q_EMIT guard->finished();
+ }
+ });
+ }, Qt::QueuedConnection);
+ }
+
+ ~ThumbnailResponse() override
+ {
+ stop();
+ }
+
+ QQuickTextureFactory *textureFactory() const override
+ {
+ return QQuickTextureFactory::textureFactoryForImage(m_image);
+ }
+
+ QString errorString() const override
+ {
+ return m_image.isNull() ? QStringLiteral("No preview") : QString();
+ }
+
+ void cancel() override
+ {
+ stop();
+ }
+
+private:
+ void stop()
+ {
+ // Responses can die on the image loader thread; the job lives on
+ // the main one.
+ if (KIO::PreviewJob *job = m_job.data()) {
+ QMetaObject::invokeMethod(job, [job = QPointer<KIO::PreviewJob>(job)] {
+ if (job) {
+ job->kill();
+ }
+ }, Qt::QueuedConnection);
+ }
+ }
+
+ QImage m_image;
+ QPointer<KIO::PreviewJob> m_job;
+};
+}
+
+QQuickImageResponse *ThumbnailProvider::requestImageResponse(const QString &id, const QSize &requestedSize)
+{
+ // The stamp changes with the file, so the image cache never serves a
+ // stale picture.
+ const QString encoded = id.section(QLatin1Char('/'), 1);
+ const QUrl url(QUrl::fromPercentEncoding(encoded.toUtf8()));
+ return new ThumbnailResponse(url, requestedSize);
+}
diff --git a/packages/wildos-portal/src/thumbnails.h b/packages/wildos-portal/src/thumbnails.h
new file mode 100644
index 0000000..cb3a348
--- /dev/null
+++ b/packages/wildos-portal/src/thumbnails.h
@@ -0,0 +1,12 @@
+#pragma once
+
+#include <QQuickAsyncImageProvider>
+
+// image://thumb/<stamp>/<url>: a KIO preview of a photo, video or PDF for
+// Large icons, made in the background the way Files makes its own; the
+// file's icon stays until it arrives.
+class ThumbnailProvider : public QQuickAsyncImageProvider
+{
+public:
+ QQuickImageResponse *requestImageResponse(const QString &id, const QSize &requestedSize) override;
+};
diff --git a/packages/wildos-portal/src/windows.cpp b/packages/wildos-portal/src/windows.cpp
index ec5ba2d..fe96708 100644
--- a/packages/wildos-portal/src/windows.cpp
+++ b/packages/wildos-portal/src/windows.cpp
@@ -1,5 +1,7 @@
#include "windows.h"
+#include "thumbnails.h"
+
#include <KWindowSystem>
#include <QCoreApplication>
#include <QGuiApplication>
@@ -24,6 +26,7 @@ Windows::Windows(QObject *parent)
: QObject(parent)
, m_engine(new QQmlApplicationEngine(this))
{
+ m_engine->addImageProvider(QStringLiteral("thumb"), new ThumbnailProvider);
m_idle.setSingleShot(true);
m_idle.setInterval(idleQuitMs);
connect(&m_idle, &QTimer::timeout, this, [this] {
@@ -34,7 +37,7 @@ Windows::Windows(QObject *parent)
scheduleQuit();
}
-QQuickWindow *Windows::open(const QString &component, const QVariantMap &properties, const QString &parentWindow)
+QQuickWindow *Windows::open(const QString &component, const QVariantMap &properties, const QString &parentWindow, bool modal)
{
QQmlComponent factory(m_engine, QStringLiteral("WildOS.Portal"), component);
QObject *object = factory.createWithInitialProperties(properties);
@@ -46,26 +49,36 @@ QQuickWindow *Windows::open(const QString &component, const QVariantMap &propert
}
hold();
connect(window, &QObject::destroyed, this, &Windows::release);
- attach(window, parentWindow);
+ // Attached to the app's window, the dialog has no taskbar button of its
+ // own and stays in front of that window. Modal when the app asks (an
+ // Open or Save dialog does by default), as on Windows: that window can't
+ // be used until the dialog closes.
+ if (attach(window, parentWindow) && modal) {
+ window->setModality(Qt::WindowModal);
+ }
window->show();
window->requestActivate();
return window;
}
-void Windows::attach(QQuickWindow *window, const QString &parentWindow)
+bool Windows::attach(QQuickWindow *window, const QString &parentWindow)
{
// The portal names the app's window "x11:<id>" or "wayland:<exported
- // handle>". Qt's portal dialog sends an X11 id even on Wayland, which
- // means nothing there, so only the matching kind is used.
+ // handle>". An X11 id means nothing on Wayland (an app on XWayland, or
+ // a Qt app before Wild OS's plasma-integration patch, sends one), so
+ // only the matching kind is used.
if (parentWindow.startsWith(QStringLiteral("x11:")) && KWindowSystem::isPlatformX11()) {
bool ok = false;
const WId id = parentWindow.mid(4).toULongLong(&ok, 16);
if (ok && id) {
KWindowSystem::setMainWindow(window, id);
+ return true;
}
} else if (parentWindow.startsWith(QStringLiteral("wayland:")) && KWindowSystem::isPlatformWayland()) {
KWindowSystem::setMainWindow(window, parentWindow.mid(8));
+ return true;
}
+ return false;
}
void Windows::hold()
diff --git a/packages/wildos-portal/src/windows.h b/packages/wildos-portal/src/windows.h
index c0fae2d..38d923c 100644
--- a/packages/wildos-portal/src/windows.h
+++ b/packages/wildos-portal/src/windows.h
@@ -18,13 +18,13 @@ class Windows : public QObject
public:
static Windows *instance();
- QQuickWindow *open(const QString &component, const QVariantMap &properties, const QString &parentWindow);
+ QQuickWindow *open(const QString &component, const QVariantMap &properties, const QString &parentWindow, bool modal = false);
void hold();
void release();
private:
explicit Windows(QObject *parent = nullptr);
- void attach(QQuickWindow *window, const QString &parentWindow);
+ bool attach(QQuickWindow *window, const QString &parentWindow);
void scheduleQuit();
QQmlEngine *m_engine;
diff --git a/packages/wildos-rdp/CMakeLists.txt b/packages/wildos-rdp/CMakeLists.txt
index 330d807..fba794c 100644
--- a/packages/wildos-rdp/CMakeLists.txt
+++ b/packages/wildos-rdp/CMakeLists.txt
@@ -37,6 +37,7 @@ qt_standard_project_setup(REQUIRES 6.8)
qt_add_executable(wildos-rdp
src/main.cpp
src/railwindow.cpp src/railwindow.h
+ src/desktopwindow.cpp src/desktopwindow.h
src/rail.cpp src/rail.h
src/loading.cpp src/loading.h
src/style.cpp src/style.h
diff --git a/packages/wildos-rdp/debian/changelog b/packages/wildos-rdp/debian/changelog
index 2847ab4..8843e7b 100644
--- a/packages/wildos-rdp/debian/changelog
+++ b/packages/wildos-rdp/debian/changelog
@@ -1,3 +1,9 @@
+wildos-rdp (0.1.16) trixie; urgency=medium
+
+ * Opens the whole Windows desktop too, so FreeRDP is no longer needed.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 13:36:51 +0000
+
wildos-rdp (0.1.15) trixie; urgency=medium
* A RemoteApp connection rides out Windows being paused: FreeRDP's TCP
diff --git a/packages/wildos-rdp/src/desktopwindow.cpp b/packages/wildos-rdp/src/desktopwindow.cpp
new file mode 100644
index 0000000..7e5e9d8
--- /dev/null
+++ b/packages/wildos-rdp/src/desktopwindow.cpp
@@ -0,0 +1,210 @@
+#include "desktopwindow.h"
+
+#include "client.h"
+#include "desktop.h"
+#include "input.h"
+
+#include <QCursor>
+#include <QGuiApplication>
+#include <QKeyEvent>
+#include <QMouseEvent>
+#include <QPainter>
+#include <QPixmap>
+#include <QScreen>
+#include <QWheelEvent>
+
+#include <algorithm>
+#include <cstring>
+
+DesktopWindow::DesktopWindow(const QString &title)
+ : m_session(new DesktopSession(this))
+{
+ setTitle(title);
+ setSurfaceType(QSurface::RasterSurface);
+ m_store = std::make_unique<QBackingStore>(this);
+
+ // Windows lays the desktop out again once the size has settled, not for
+ // every step of a drag.
+ m_resize.setSingleShot(true);
+ m_resize.setInterval(300);
+ connect(&m_resize, &QTimer::timeout, this, [this] {
+ if (m_connected) {
+ m_session->resize(physicalSize(), devicePixelRatio());
+ }
+ });
+
+ connect(m_session, &DesktopSession::certificateNeeded, this, [this](const QVariantMap &, bool changed) {
+ m_session->answerCertificate(!changed, true);
+ });
+ connect(m_session, &DesktopSession::credentialsNeeded, this, [this](const QString &, const QString &, const QString &) {
+ // The password comes with the arguments; asked for again means
+ // Windows refused it, and the agent sets a new one next time.
+ m_session->answerCredentials(false, {}, {}, {});
+ });
+ connect(m_session, &DesktopSession::connected, this, [this] {
+ m_connected = true;
+ m_session->resize(physicalSize(), devicePixelRatio());
+ });
+ connect(m_session, &DesktopSession::frameChanged, this, &DesktopWindow::damaged);
+ connect(m_session, &DesktopSession::pointerImage, this, [this](const QImage &image, const QPoint &hotspot) {
+ // Windows sends the pointer at its own pixels; the screen's scale
+ // makes it the right size here.
+ QPixmap pixmap = QPixmap::fromImage(image);
+ const qreal dpr = devicePixelRatio();
+ pixmap.setDevicePixelRatio(dpr);
+ setCursor(QCursor(pixmap, int(hotspot.x() / dpr), int(hotspot.y() / dpr)));
+ });
+ connect(m_session, &DesktopSession::pointerHidden, this, [this] { setCursor(Qt::BlankCursor); });
+ connect(m_session, &DesktopSession::pointerDefault, this, [this] { setCursor(Qt::ArrowCursor); });
+ connect(m_session, &DesktopSession::finished, this, [this](const QString &code, bool authFailed) {
+ m_connected = false;
+ if (authFailed) {
+ // Windows mode's agent reads its log for this word, and sets a
+ // new password next time.
+ qWarning("wildos-rdp: LOGON_FAILURE, Windows refused the password");
+ }
+ Q_EMIT ended(code);
+ });
+}
+
+DesktopWindow::~DesktopWindow()
+{
+ // The connection thread is joined before anything it uses goes.
+ m_session->stop();
+}
+
+bool DesktopWindow::start(const QList<QByteArray> &args, QString *error)
+{
+ if (!m_session->configure(args, error)) {
+ return false;
+ }
+ // A window a little smaller than the screen, as Remote opens one.
+ QScreen *screen = QGuiApplication::primaryScreen();
+ const QSize logical = screen ? screen->availableSize() * 0.8 : QSize(1280, 800);
+ resize(logical);
+ const double dpr = screen ? screen->devicePixelRatio() : 1.0;
+ m_session->setDisplay(logical * dpr, dpr);
+ show();
+ m_session->start();
+ return true;
+}
+
+QSize DesktopWindow::physicalSize() const
+{
+ return (QSizeF(size()) * devicePixelRatio()).toSize();
+}
+
+void DesktopWindow::damaged(const QRegion &region)
+{
+ m_session->client()->withPrimary([this, &region](const uchar *data, int stride, QSize size) {
+ if (m_image.size() != size) {
+ // A new desktop size: the whole picture again.
+ m_image = QImage(data, size.width(), size.height(), stride, QImage::Format_RGB32).copy();
+ return;
+ }
+ for (const QRect &r : region) {
+ const QRect c = r.intersected(QRect(QPoint(0, 0), size));
+ for (int y = c.top(); y <= c.bottom(); ++y) {
+ std::memcpy(m_image.scanLine(y) + qsizetype(c.left()) * 4, data + qsizetype(y) * stride + qsizetype(c.left()) * 4,
+ size_t(c.width()) * 4);
+ }
+ }
+ });
+ requestUpdate();
+}
+
+QRectF DesktopWindow::pictureRect() const
+{
+ if (m_image.isNull() || width() <= 0 || height() <= 0) {
+ return {};
+ }
+ const double s = std::min(double(width()) / m_image.width(), double(height()) / m_image.height());
+ const QSizeF shown(m_image.width() * s, m_image.height() * s);
+ return QRectF(QPointF((width() - shown.width()) / 2, (height() - shown.height()) / 2), shown);
+}
+
+QPoint DesktopWindow::toRemote(const QPointF &local) const
+{
+ const QRectF pic = pictureRect();
+ if (pic.isEmpty()) {
+ return {};
+ }
+ const double x = (local.x() - pic.x()) / pic.width() * m_image.width();
+ const double y = (local.y() - pic.y()) / pic.height() * m_image.height();
+ return QPoint(std::clamp(int(x), 0, m_image.width() - 1), std::clamp(int(y), 0, m_image.height() - 1));
+}
+
+void DesktopWindow::render()
+{
+ if (!isExposed()) {
+ return;
+ }
+ const QRect all(QPoint(0, 0), size());
+ m_store->beginPaint(all);
+ {
+ QPainter p(m_store->paintDevice());
+ p.fillRect(all, Qt::black);
+ if (!m_image.isNull()) {
+ p.setRenderHint(QPainter::SmoothPixmapTransform);
+ p.drawImage(pictureRect(), m_image);
+ }
+ }
+ m_store->endPaint();
+ m_store->flush(all);
+}
+
+bool DesktopWindow::event(QEvent *event)
+{
+ if (event->type() == QEvent::UpdateRequest) {
+ render();
+ return true;
+ }
+ return QWindow::event(event);
+}
+
+void DesktopWindow::exposeEvent(QExposeEvent *)
+{
+ render();
+}
+
+void DesktopWindow::resizeEvent(QResizeEvent *event)
+{
+ m_store->resize(event->size());
+ m_resize.start();
+ requestUpdate();
+}
+
+void DesktopWindow::mousePressEvent(QMouseEvent *event)
+{
+ rdpinput::button(m_session->client(), event->button(), true, toRemote(event->position()));
+}
+
+void DesktopWindow::mouseReleaseEvent(QMouseEvent *event)
+{
+ rdpinput::button(m_session->client(), event->button(), false, toRemote(event->position()));
+}
+
+void DesktopWindow::mouseMoveEvent(QMouseEvent *event)
+{
+ rdpinput::move(m_session->client(), toRemote(event->position()));
+}
+
+void DesktopWindow::wheelEvent(QWheelEvent *event)
+{
+ rdpinput::wheel(m_session->client(), event->angleDelta(), toRemote(event->position()), m_wheelX, m_wheelY);
+}
+
+void DesktopWindow::keyPressEvent(QKeyEvent *event)
+{
+ rdpinput::key(m_session->client(), event, true, m_keysDown);
+}
+
+void DesktopWindow::keyReleaseEvent(QKeyEvent *event)
+{
+ rdpinput::key(m_session->client(), event, false, m_keysDown);
+}
+
+void DesktopWindow::focusOutEvent(QFocusEvent *)
+{
+ rdpinput::releaseAll(m_session->client(), m_keysDown);
+}
diff --git a/packages/wildos-rdp/src/desktopwindow.h b/packages/wildos-rdp/src/desktopwindow.h
new file mode 100644
index 0000000..1b483a4
--- /dev/null
+++ b/packages/wildos-rdp/src/desktopwindow.h
@@ -0,0 +1,64 @@
+#pragma once
+
+#include <QBackingStore>
+#include <QImage>
+#include <QList>
+#include <QTimer>
+#include <QWindow>
+
+#include <memory>
+
+class DesktopSession;
+
+// The whole Windows desktop in one window, for "Open Windows desktop" in
+// Settings: the engine's desktop session drawn at the window's size, with
+// the keyboard and pointer going to Windows. Windows lays its desktop out
+// again for each new window size.
+//
+// Windows mode's own VM is trusted the way its app windows trust it: a
+// certificate seen for the first time is kept, and a changed one is refused
+// (Windows mode forgets the old one itself when Windows is set up again).
+class DesktopWindow : public QWindow
+{
+ Q_OBJECT
+
+public:
+ explicit DesktopWindow(const QString &title);
+ ~DesktopWindow() override;
+
+ // FreeRDP's arguments as xfreerdp3 takes them, the password among them.
+ bool start(const QList<QByteArray> &args, QString *error);
+
+Q_SIGNALS:
+ // The session ended; `code` is FreeRDP's reason, empty when it ended
+ // normally.
+ void ended(const QString &code);
+
+protected:
+ bool event(QEvent *event) override;
+ void exposeEvent(QExposeEvent *event) override;
+ void resizeEvent(QResizeEvent *event) override;
+ void mousePressEvent(QMouseEvent *event) override;
+ void mouseReleaseEvent(QMouseEvent *event) override;
+ void mouseMoveEvent(QMouseEvent *event) override;
+ void wheelEvent(QWheelEvent *event) override;
+ void keyPressEvent(QKeyEvent *event) override;
+ void keyReleaseEvent(QKeyEvent *event) override;
+ void focusOutEvent(QFocusEvent *event) override;
+
+private:
+ void damaged(const QRegion &region);
+ void render();
+ QRectF pictureRect() const;
+ QPoint toRemote(const QPointF &local) const;
+ QSize physicalSize() const;
+
+ DesktopSession *m_session;
+ std::unique_ptr<QBackingStore> m_store;
+ QImage m_image;
+ QTimer m_resize;
+ QList<quint32> m_keysDown;
+ int m_wheelX = 0;
+ int m_wheelY = 0;
+ bool m_connected = false;
+};
diff --git a/packages/wildos-rdp/src/main.cpp b/packages/wildos-rdp/src/main.cpp
index 20f405d..3e7e42a 100644
--- a/packages/wildos-rdp/src/main.cpp
+++ b/packages/wildos-rdp/src/main.cpp
@@ -2,14 +2,19 @@
// window of its own on the desktop, drawn at the screen's own scale.
//
// wildos-rdp [--app-id ID --title TITLE --icon ICON --reason TEXT --program EXE] /args-from:stdin
+// wildos-rdp --desktop /args-from:stdin
//
// The FreeRDP arguments are the ones xfreerdp3 takes, one per line on
// standard input with the password last, so nothing secret is ever on a
// command line. With --app-id the loading window for that app is on screen
// before they arrive: the agent starts this the moment an app is opened
// and writes them once Windows is awake.
+//
+// --desktop opens the whole Windows desktop in one window instead, for
+// Settings' "Open Windows desktop"; the arguments arrive the same way.
#include "client.h"
+#include "desktopwindow.h"
#include "rail.h"
#include "railwindow.h"
#include "screens.h"
@@ -17,6 +22,7 @@
#include "service.h"
#include <QElapsedTimer>
+#include <QFile>
#include <QGuiApplication>
#include <QScreen>
#include <QSocketNotifier>
@@ -48,6 +54,8 @@ struct Options {
bool fromStdin = false;
// Signs in and leaves the session ready, disconnected, for the next app.
bool prepareSession = false;
+ // The whole desktop in one window (desktopwindow.h).
+ bool desktop = false;
QList<QByteArray> freerdp;
};
@@ -63,6 +71,8 @@ Options parse(int argc, char **argv)
o.fromStdin = true;
} else if (a == "--prepare-session") {
o.prepareSession = true;
+ } else if (a == "--desktop") {
+ o.desktop = true;
} else {
o.freerdp.append(a);
}
@@ -85,6 +95,58 @@ double askedScale(const QList<QByteArray> &args)
}
return 0;
}
+
+// Reads the arguments (password last) from standard input, keeps the
+// window's title out of them, and runs until the window closes or the
+// session ends.
+int runDesktop(QGuiApplication &app, const Options &options)
+{
+ QList<QByteArray> args = options.freerdp;
+ QString title = QStringLiteral("Windows desktop");
+ QFile in;
+ if (options.fromStdin && in.open(stdin, QIODevice::ReadOnly)) {
+ while (!in.atEnd()) {
+ QByteArray line = in.readLine();
+ while (line.endsWith('\n') || line.endsWith('\r')) {
+ line.chop(1);
+ }
+ if (line.startsWith("/title:")) {
+ title = QString::fromUtf8(line.mid(7));
+ } else if (!line.isEmpty()) {
+ args.append(line);
+ }
+ }
+ }
+ if (args.isEmpty()) {
+ return 1;
+ }
+ QGuiApplication::setQuitOnLastWindowClosed(true);
+ int status = 0;
+ QString error;
+ {
+ DesktopWindow window(title);
+ QObject::connect(&window, &DesktopWindow::ended, &app, [&status](const QString &code) {
+ if (!code.isEmpty()) {
+ qWarning("wildos-rdp: the Windows desktop ended: %s", qPrintable(code));
+ status = 1;
+ }
+ QCoreApplication::quit();
+ });
+ const bool started = window.start(args, &error);
+ for (QByteArray &a : args) {
+ a.fill('\0');
+ }
+ if (!started) {
+ qWarning("wildos-rdp: the Windows desktop couldn't open: %s", qPrintable(error));
+ return 1;
+ }
+ const int code = app.exec();
+ if (code != 0) {
+ status = code;
+ }
+ }
+ return status;
+}
}
int main(int argc, char **argv)
@@ -98,6 +160,10 @@ int main(int argc, char **argv)
Options options = parse(argc, argv);
+ if (options.desktop) {
+ return runDesktop(app, options);
+ }
+
if (pipe2(signalPipe, O_CLOEXEC) == 0) {
std::signal(SIGTERM, onSignal);
std::signal(SIGINT, onSignal);
diff --git a/packages/wildos-recovery/app/qml/Main.qml b/packages/wildos-recovery/app/qml/Main.qml
index 2c021c6..6f6c0c3 100644
--- a/packages/wildos-recovery/app/qml/Main.qml
+++ b/packages/wildos-recovery/app/qml/Main.qml
@@ -943,6 +943,15 @@ Window {
font.family: "Albert Sans"
font.pixelSize: 14
placeholderText: "Disk password"
+ // Only what is typed: no Ctrl+V, Shift+Insert or middle click.
+ Keys.onPressed: event => {
+ if (event.matches(StandardKey.Paste) || (event.key === Qt.Key_Insert && (event.modifiers & Qt.ShiftModifier)))
+ event.accepted = true;
+ }
+ MouseArea {
+ anchors.fill: parent
+ acceptedButtons: Qt.MiddleButton
+ }
placeholderTextColor: Qt.rgba(1, 1, 1, 0.5)
background: Rectangle {
implicitHeight: 42
diff --git a/packages/wildos-recovery/debian/changelog b/packages/wildos-recovery/debian/changelog
index 80db49b..de7e961 100644
--- a/packages/wildos-recovery/debian/changelog
+++ b/packages/wildos-recovery/debian/changelog
@@ -1,3 +1,31 @@
+wildos-recovery (0.1.7) trixie; urgency=medium
+
+ * The disk password box takes only what is typed: nothing can be pasted
+ into it.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 09:45:00 +0000
+
+wildos-recovery (0.1.6) trixie; urgency=medium
+
+ * When a new kernel can't reach the desktop, the next start uses the
+ last one that could, and stays on it until a newer one arrives.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 22:52:35 +0000
+
+wildos-recovery (0.1.5) trixie; urgency=medium
+
+ * Going back to a restore point or resetting Wild OS keeps Settings >
+ System > History as it is.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 15:37:21 +0000
+
+wildos-recovery (0.1.4) trixie; urgency=medium
+
+ * The reset copy downloads a release once, not after every start-up, when
+ its files do not verify, and its copying no longer crowds out open apps.
+
+ -- Wild OS Developers <[email protected]> Thu, 12 Nov 2026 21:14:46 +0000
+
wildos-recovery (0.1.3) trixie; urgency=medium
* Going back to a restore point keeps Steam's controller support as it
diff --git a/packages/wildos-recovery/debian/postinst b/packages/wildos-recovery/debian/postinst
index 1067ac1..861d6b0 100644
--- a/packages/wildos-recovery/debian/postinst
+++ b/packages/wildos-recovery/debian/postinst
@@ -16,6 +16,11 @@ if [ "$1" = "configure" ]; then
if [ "$(findmnt -no FSTYPE /)" != btrfs ]; then
dracut --force >/dev/null 2>&1 || echo "wildos-recovery: the start-up files are updated at the next kernel update" >&2
fi
+ # The kernel running now works, so a newer one installed later gets
+ # one start to prove itself before the PC goes back to this one.
+ if [ -e /boot/grub/grubenv ] && ! grub-editenv /boot/grub/grubenv list | grep -q '^wildos_kernel_ok='; then
+ grub-editenv /boot/grub/grubenv set "wildos_kernel_ok=$(uname -r)" || true
+ fi
if [ -e /boot/grub/grub.cfg ] && command -v update-grub >/dev/null; then
update-grub >/dev/null 2>&1 || true
fi
diff --git a/packages/wildos-recovery/files/grub/15_wildos_recovery b/packages/wildos-recovery/files/grub/15_wildos_recovery
index b830d0b..6d5251d 100644
--- a/packages/wildos-recovery/files/grub/15_wildos_recovery
+++ b/packages/wildos-recovery/files/grub/15_wildos_recovery
@@ -10,6 +10,11 @@
# - "Start-up recovery" boots the reset copy kept inside the encrypted disk,
# with its own kernel and initramfs from /boot/wildos-recovery. Nothing of
# the installed system runs.
+# - A new kernel gets one start. If that start doesn't reach the desktop,
+# the PC starts "Wild OS (previous version)" (wildos-base's 10_wildos)
+# from then on, until a newer kernel arrives or the new one is picked from
+# the menu and works. wildos_kernel_ok is the last kernel that reached the
+# desktop (recovery-boot), wildos_kernel_tried the new one given its start.
# - On Btrfs, "Restore points" lists each restore point whose kernel is
# still on /boot, to start it on a layer in memory.
set -e
@@ -67,6 +72,22 @@ echo 'fi'
echo 'if [ "${wildos_reason}" = "reset-everything" ]; then'
echo ' set wildos_ram="rd.live.ram=1"'
echo 'fi'
+newest=$(for f in /boot/vmlinuz-*; do
+ if grub_file_is_not_garbage "$f"; then echo "${f#/boot/vmlinuz-}"; fi
+done | version_sort -r | head -n 2)
+if [ "$(echo "$newest" | wc -l)" = 2 ]; then
+ newest=$(echo "$newest" | sed -n 1p)
+ echo "if [ -n \"\${wildos_kernel_ok}\" ]; then"
+ echo " if [ \"\${wildos_kernel_ok}\" != \"$newest\" ]; then"
+ echo " if [ \"\${wildos_kernel_tried}\" = \"$newest\" ]; then"
+ echo " set default=\"wildos-previous-$device_id\""
+ echo " elif [ -z \"\${wildos_reason}\" ]; then"
+ echo " set wildos_kernel_tried=\"$newest\""
+ echo " save_env wildos_kernel_tried"
+ echo " fi"
+ echo " fi"
+ echo "fi"
+fi
echo 'if [ "${wildos_tries}" = "2" ]; then'
echo ' set wildos_tries='
echo ' save_env wildos_tries'
diff --git a/packages/wildos-recovery/files/recovery-boot b/packages/wildos-recovery/files/recovery-boot
index 3dbe3d6..48fe7df 100644
--- a/packages/wildos-recovery/files/recovery-boot
+++ b/packages/wildos-recovery/files/recovery-boot
@@ -4,6 +4,7 @@
# recovery-boot next [REASON] start in start-up recovery once (REASON:
# menu, reset-keep, reset-everything)
# recovery-boot good this start counts as good: clear the count
+# and note the kernel as one that works
# recovery-boot watch wait for a person's desktop, then "good";
# a clean shutdown from the sign-in screen
# counts as good too (wildos-boot-ok)
@@ -45,6 +46,7 @@ next)
;;
good)
editenv unset wildos_tries
+ editenv set "wildos_kernel_ok=$(uname -r)"
;;
watch)
mkdir -p "$SEEN"
@@ -57,6 +59,7 @@ watch)
sleep 20
if [ "$(loginctl show-session "$id" -p State --value 2>/dev/null)" = active ]; then
editenv unset wildos_tries
+ editenv set "wildos_kernel_ok=$(uname -r)"
: > "$SEEN/good"
exit 0
fi
diff --git a/packages/wildos-recovery/files/reset-copy b/packages/wildos-recovery/files/reset-copy
index c9009e8..05c961a 100644
--- a/packages/wildos-recovery/files/reset-copy
+++ b/packages/wildos-recovery/files/reset-copy
@@ -35,6 +35,9 @@ SIGNATURE = "LiveOS/reset.sha256.sig"
RELEASE = "https://dl.wildos.io/latest/"
STATE = "state.json"
LOG = "/var/log/wildos-restore-points.log"
+# The signed sum of a release whose reset files did not verify, so the same
+# 2 GB download is not tried again after every start-up.
+REJECTED = "/var/lib/wildos/reset-copy-rejected"
FILES = ["LiveOS/squashfs.img", "live/vmlinuz", "live/initrd.img"]
@@ -244,6 +247,11 @@ def update():
return 1
if state().get("iso_sha256") == want and verify(quick=True)[0]:
return 0
+ try:
+ if open(REJECTED).read().strip() == want:
+ return 0
+ except OSError:
+ pass
iso = os.path.join(work, "wildos-amd64.iso")
log("downloading the newest release for the reset copy")
fetch(RELEASE + "wildos-amd64.iso", iso)
@@ -262,6 +270,8 @@ def update():
ok, why = verify(new)
if not ok:
log(f"the release's reset files did not verify ({why}); keeping the old copy")
+ with open(REJECTED, "w") as r:
+ r.write(want + "\n")
return 1
write_state(new, verified=True, why="", release=release_name(new), iso_sha256=want,
copied=int(time.time()))
diff --git a/packages/wildos-recovery/files/restore-points b/packages/wildos-recovery/files/restore-points
index e5304ff..e39634c 100644
--- a/packages/wildos-recovery/files/restore-points
+++ b/packages/wildos-recovery/files/restore-points
@@ -71,6 +71,8 @@ NOT_SYSTEM = [
"/home", "/swapfile", "/swap", "/.snapshots", "/boot/*",
"/var/lib/wildos/restore-points", "/var/lib/wildos/reset",
"/var/log", "/var/cache", "/var/tmp",
+ # Settings > System > History: what happened stays, going back included.
+ "/var/lib/wildos/history",
# Windows mode: its disk, firmware variables, TPM and saved memory, and
# the VM's definition. Going back never rolls Windows back.
"/var/lib/wildos/winmode", "/var/lib/libvirt", "/etc/libvirt",
diff --git a/packages/wildos-recovery/files/systemd/wildos-reset-copy.service b/packages/wildos-recovery/files/systemd/wildos-reset-copy.service
index cd305fc..51293c1 100644
--- a/packages/wildos-recovery/files/systemd/wildos-reset-copy.service
+++ b/packages/wildos-recovery/files/systemd/wildos-reset-copy.service
@@ -8,4 +8,7 @@ ConditionPathExists=!/run/initramfs/live
Type=oneshot
Nice=19
IOSchedulingClass=idle
+# Copying a 2 GB release fills the page cache; past this the kernel
+# reclaims the copy's own cache instead of the apps you are using.
+MemoryHigh=768M
ExecStart=/usr/libexec/wildos/reset-copy update
diff --git a/packages/wildos-remote/debian/changelog b/packages/wildos-remote/debian/changelog
index cbf6713..a406a32 100644
--- a/packages/wildos-remote/debian/changelog
+++ b/packages/wildos-remote/debian/changelog
@@ -1,3 +1,10 @@
+wildos-remote (0.1.7) trixie; urgency=medium
+
+ * Connection details and public keys can be copied from a right-
+ click menu.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 08:54:22 +0000
+
wildos-remote (0.1.6) trixie; urgency=medium
* All my monitors lays the remote desktop out with each screen beside
diff --git a/packages/wildos-remote/debian/control b/packages/wildos-remote/debian/control
index 1620b27..6a69f70 100644
--- a/packages/wildos-remote/debian/control
+++ b/packages/wildos-remote/debian/control
@@ -25,7 +25,7 @@ Architecture: any
Depends:
${shlibs:Depends},
${misc:Depends},
- wildos-ui (>= 0.1.3),
+ wildos-ui (>= 0.1.11),
openssh-client,
libfreerdp3-3 (>= 3.32),
libfreerdp-client3-3 (>= 3.32),
diff --git a/packages/wildos-remote/qml/InfoRows.qml b/packages/wildos-remote/qml/InfoRows.qml
index eef0f40..a5899cd 100644
--- a/packages/wildos-remote/qml/InfoRows.qml
+++ b/packages/wildos-remote/qml/InfoRows.qml
@@ -82,6 +82,16 @@ Rectangle {
selectionColor: UI.Style.textSelection
font.family: "JetBrains Mono"
font.pixelSize: UI.Style.px(12)
+ Keys.onPressed: event => {
+ if (valueMenu.isMenuKey(event)) {
+ valueMenu.openAtCaret();
+ event.accepted = true;
+ }
+ }
+
+ UI.TextMenu {
+ id: valueMenu
+ }
}
}
}
diff --git a/packages/wildos-remote/qml/KeychainPage.qml b/packages/wildos-remote/qml/KeychainPage.qml
index b7d0ee6..7717901 100644
--- a/packages/wildos-remote/qml/KeychainPage.qml
+++ b/packages/wildos-remote/qml/KeychainPage.qml
@@ -326,6 +326,16 @@ Item {
selectionColor: UI.Style.textSelection
font.family: "JetBrains Mono"
font.pixelSize: UI.Style.px(12)
+ Keys.onPressed: event => {
+ if (publicMenu.isMenuKey(event)) {
+ publicMenu.openAtCaret();
+ event.accepted = true;
+ }
+ }
+
+ UI.TextMenu {
+ id: publicMenu
+ }
}
}
Row {
diff --git a/packages/wildos-report/CMakeLists.txt b/packages/wildos-report/CMakeLists.txt
index 2f241af..76e3bc0 100644
--- a/packages/wildos-report/CMakeLists.txt
+++ b/packages/wildos-report/CMakeLists.txt
@@ -5,12 +5,13 @@ set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
include(GNUInstallDirs)
-option(WILDOS_REPORT_TESTS "Build the redactor tests" OFF)
+option(WILDOS_REPORT_TESTS "Build the redactor and issue watch tests" OFF)
-find_package(Qt6 6.8 REQUIRED COMPONENTS Core Gui Widgets DBus Concurrent Qml Quick QuickControls2)
+find_package(Qt6 6.8 REQUIRED COMPONENTS Core Gui Widgets DBus Concurrent Network Qml Quick QuickControls2)
find_package(KF6DBusAddons REQUIRED)
find_package(KF6Notifications REQUIRED)
find_package(KF6Archive REQUIRED)
+find_package(KF6WindowSystem REQUIRED)
qt_standard_project_setup(REQUIRES 6.8)
@@ -32,6 +33,7 @@ qt_add_qml_module(wildos-report
src/report.cpp src/report.h
src/collector.cpp src/collector.h
src/crashnotify.cpp src/crashnotify.h
+ src/issuewatch.cpp src/issuewatch.h
src/parts.cpp src/parts.h
src/redactor.cpp src/redactor.h
src/sysinfo.cpp src/sysinfo.h
@@ -39,8 +41,8 @@ qt_add_qml_module(wildos-report
target_include_directories(wildos-report PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src)
target_link_libraries(wildos-report PRIVATE
- Qt6::Widgets Qt6::Gui Qt6::DBus Qt6::Concurrent Qt6::Qml Qt6::Quick Qt6::QuickControls2
- KF6::DBusAddons KF6::Notifications KF6::Archive
+ Qt6::Widgets Qt6::Gui Qt6::DBus Qt6::Concurrent Qt6::Network Qt6::Qml Qt6::Quick Qt6::QuickControls2
+ KF6::DBusAddons KF6::Notifications KF6::Archive KF6::WindowSystem
)
if(WILDOS_REPORT_TESTS)
@@ -50,6 +52,10 @@ if(WILDOS_REPORT_TESTS)
target_include_directories(redactor-test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src)
target_link_libraries(redactor-test PRIVATE Qt6::Core Qt6::Test)
add_test(NAME redactor COMMAND redactor-test)
+ qt_add_executable(issuewatch-test tests/issuewatch_test.cpp src/issuewatch.cpp)
+ target_include_directories(issuewatch-test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src)
+ target_link_libraries(issuewatch-test PRIVATE Qt6::Core Qt6::Test)
+ add_test(NAME issuewatch COMMAND issuewatch-test)
endif()
install(TARGETS wildos-report RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
@@ -67,10 +73,13 @@ install(FILES data/995-wildos-crash-reports.conf DESTINATION ${CMAKE_INSTALL_PRE
install(FILES data/coredump-wildos-report.conf DESTINATION ${CMAKE_INSTALL_PREFIX}/lib/systemd/system/[email protected]
RENAME wildos-report.conf)
install(FILES data/wildos-report-crash.path data/wildos-report-crash.service DESTINATION ${CMAKE_INSTALL_PREFIX}/lib/systemd/user)
-# KDE's crash reporter steps aside; see drkonqi-wildos-report.conf.
+# KDE's crash reporter steps aside; see drkonqi-wildos-report.conf. Its
+# socket is masked instead (debian/links): sockets.target upholds it, so a
+# condition that stops it made systemd try it again, and log a dozen lines,
+# whenever an app started.
install(FILES data/drkonqi-wildos-report.conf DESTINATION ${CMAKE_INSTALL_PREFIX}/lib/systemd/system/[email protected]
RENAME wildos-report.conf)
-foreach(unit drkonqi-coredump-launcher.socket drkonqi-coredump-pickup.service drkonqi-sentry-postman.path drkonqi-sentry-postman.timer
+foreach(unit drkonqi-coredump-pickup.service drkonqi-sentry-postman.path drkonqi-sentry-postman.timer
drkonqi-sentry-postman.service)
install(FILES data/drkonqi-wildos-report.conf DESTINATION ${CMAKE_INSTALL_PREFIX}/lib/systemd/user/${unit}.d RENAME wildos-report.conf)
endforeach()
diff --git a/packages/wildos-report/debian/changelog b/packages/wildos-report/debian/changelog
index b3aef2a..e97707e 100644
--- a/packages/wildos-report/debian/changelog
+++ b/packages/wildos-report/debian/changelog
@@ -1,3 +1,45 @@
+wildos-report (0.1.6) trixie; urgency=medium
+
+ * Right-clicking the title, time and description boxes gives Cut, Copy
+ and Paste.
+ * Open GitHub says what it is doing while the browser opens, then what
+ to do there: sign in, drag in the report and submit the issue. Once
+ the issue appears on GitHub the window says so, with its number, and
+ that it is safe to close. To find it, Report a problem reads GitHub's
+ public list of new issues for up to half an hour, without signing in
+ and without sending anything.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 07:54:43 +0000
+
+wildos-report (0.1.5) trixie; urgency=medium
+
+ * Report a problem can attach pictures already on the PC, such as an
+ earlier screenshot, with Choose a picture beside Take a screenshot.
+ Each is added as a fresh copy with no location, camera details or
+ file name in it, as a new screenshot is.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 22:26:50 +0000
+
+wildos-report (0.1.4) trixie; urgency=medium
+
+ * Report a problem from an event in Settings > System > History comes
+ with that event attached, and looks at the logs from when it happened.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 14:12:47 +0000
+
+wildos-report (0.1.3) trixie; urgency=medium
+
+ * Starting an app no longer fills the system log with lines about KDE's
+ crash reporter, which stays off.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 12:19:13 +0000
+
+wildos-report (0.1.2) trixie; urgency=medium
+
+ * Closing the window ends the app, so it opens again the next time.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 10:21:27 +0000
+
wildos-report (0.1.1) trixie; urgency=medium
* Crash notices: crashes are recorded again, as which program, the signal
diff --git a/packages/wildos-report/debian/control b/packages/wildos-report/debian/control
index d4c9d5a..e79a60f 100644
--- a/packages/wildos-report/debian/control
+++ b/packages/wildos-report/debian/control
@@ -11,6 +11,7 @@ Build-Depends:
libkf6dbusaddons-dev,
libkf6notifications-dev,
libkf6archive-dev,
+ libkf6windowsystem-dev,
Standards-Version: 4.7.0
Rules-Requires-Root: no
@@ -19,7 +20,7 @@ Architecture: any
Depends:
${shlibs:Depends},
${misc:Depends},
- wildos-ui (>= 0.1.3),
+ wildos-ui (>= 0.1.10),
systemd-coredump,
pkexec,
polkitd,
@@ -44,7 +45,8 @@ Description: Wild OS Report a problem
numbers, email addresses and file names are replaced with placeholders
before anything is shown, and every part can be left out. Nothing is
sent for you: open an issue on GitHub, save the report or copy the
- description.
+ description. After Open GitHub it looks for the new issue in GitHub's
+ public list of issues, without signing in, to say when it is up.
.
After an app crashes, a notice offers to report it, at most once per app
per day. systemd-coredump records which program crashed, never its
diff --git a/packages/wildos-report/debian/links b/packages/wildos-report/debian/links
new file mode 100644
index 0000000..fb84156
--- /dev/null
+++ b/packages/wildos-report/debian/links
@@ -0,0 +1 @@
+dev/null etc/systemd/user/drkonqi-coredump-launcher.socket
diff --git a/packages/wildos-report/debian/postinst b/packages/wildos-report/debian/postinst
index 10425fc..686d543 100755
--- a/packages/wildos-report/debian/postinst
+++ b/packages/wildos-report/debian/postinst
@@ -1,9 +1,14 @@
#!/bin/sh
set -e
-# Crashes reach systemd-coredump from now on, not at the next start-up.
if [ "$1" = configure ] && [ -d /run/systemd/system ]; then
+ # Crashes reach systemd-coredump from now on, not at the next start-up.
systemctl restart systemd-sysctl.service >/dev/null 2>&1 || true
+ # Signed-in accounts see the masked DrKonqi socket now rather than at
+ # their next sign-in; until then their session keeps trying to start it.
+ for user in $(loginctl list-users --no-legend 2>/dev/null | awk '{print $2}'); do
+ timeout 10 systemctl --user --machine="$user@" daemon-reload >/dev/null 2>&1 || true
+ done
fi
#DEBHELPER#
diff --git a/packages/wildos-report/qml/HandoffDialog.qml b/packages/wildos-report/qml/HandoffDialog.qml
new file mode 100644
index 0000000..154fd01
--- /dev/null
+++ b/packages/wildos-report/qml/HandoffDialog.qml
@@ -0,0 +1,157 @@
+import QtQuick
+import QtQuick.Layouts
+import QtQuick.Templates as T
+import WildOS.UI as UI
+
+// What happens after Open GitHub. The issue is finished in the browser,
+// where this app can't see; it only learns it was posted by finding it on
+// GitHub, so until then it says what to do there rather than claiming
+// anything was sent. `stage` is Report.handoff: opening, waiting, posted.
+UI.Dialog {
+ id: dialog
+
+ property string stage
+ property string zipName
+ property int issueNumber
+ property bool watching
+
+ signal showReport()
+ signal openAgain()
+ signal viewIssue()
+ signal closeWindow()
+
+ readonly property bool posted: stage === "posted"
+
+ title: stage === "opening" ? qsTr("Opening GitHub in your browser")
+ : posted ? qsTr("Issue submitted")
+ : qsTr("Finish in your browser")
+ iconName: posted ? "check" : ""
+ text: stage === "opening" ? qsTr("Saving the report to Downloads, then opening a new issue with your title and description filled in.")
+ : posted ? qsTr("Thank you. Your report is issue #%1 on GitHub. It's safe to close this window.").arg(issueNumber)
+ : qsTr("Your title and description are filled in on the new issue page. To send it:")
+ closePolicy: stage === "opening" ? T.Popup.NoAutoClose : T.Popup.CloseOnEscape
+
+ RowLayout {
+ visible: dialog.stage === "opening"
+ Layout.fillWidth: true
+ Layout.topMargin: 4
+ Layout.bottomMargin: 8
+ spacing: 10
+
+ UI.Spinner {
+ size: 18
+ }
+ UI.Label {
+ Layout.fillWidth: true
+ text: qsTr("This takes a few seconds.")
+ color: UI.Style.inkMuted
+ }
+ }
+
+ ColumnLayout {
+ visible: dialog.stage === "waiting"
+ Layout.fillWidth: true
+ spacing: 8
+
+ Repeater {
+ model: [
+ qsTr("Sign in to GitHub if it asks."),
+ qsTr("Drag %1 from your Downloads folder into the description box.").arg(dialog.zipName),
+ qsTr("Submit the issue.")
+ ]
+
+ delegate: RowLayout {
+ id: stepRow
+
+ required property string modelData
+ required property int index
+
+ Layout.fillWidth: true
+ spacing: 10
+
+ Rectangle {
+ Layout.alignment: Qt.AlignTop
+ implicitWidth: 20
+ implicitHeight: 20
+ radius: 10
+ color: UI.Style.accentAlpha(0.14, 0.10)
+
+ UI.Label {
+ anchors.centerIn: parent
+ text: stepRow.index + 1
+ size: 11.5
+ font.weight: UI.Style.weightSemiBold
+ color: UI.Style.accentText
+ }
+ }
+ UI.Label {
+ Layout.fillWidth: true
+ text: stepRow.modelData
+ wrapMode: Text.WordWrap
+ elide: Text.ElideNone
+ color: UI.Style.inkStatus
+ }
+ }
+ }
+
+ RowLayout {
+ Layout.fillWidth: true
+ Layout.topMargin: 6
+ spacing: 16
+
+ UI.LinkButton {
+ text: qsTr("Show the report in its folder")
+ size: 13
+ onClicked: dialog.showReport()
+ }
+ UI.LinkButton {
+ text: qsTr("Open the issue page again")
+ size: 13
+ onClicked: dialog.openAgain()
+ }
+ }
+
+ RowLayout {
+ Layout.fillWidth: true
+ Layout.topMargin: 8
+ spacing: 10
+
+ UI.Spinner {
+ Layout.alignment: Qt.AlignTop
+ Layout.topMargin: 1
+ visible: dialog.watching
+ size: 14
+ }
+ UI.Label {
+ Layout.fillWidth: true
+ text: dialog.watching
+ ? qsTr("This window will say when your issue is up. Closing it now is safe too: everything is in your browser and in Downloads.")
+ : qsTr("Once you've submitted it, you can close this window.")
+ size: 12.5
+ wrapMode: Text.WordWrap
+ elide: Text.ElideNone
+ color: UI.Style.inkMuted
+ }
+ }
+ }
+
+ buttons: [
+ UI.Button {
+ visible: dialog.stage === "waiting"
+ text: qsTr("Back to the report")
+ onClicked: dialog.close()
+ },
+ UI.Button {
+ visible: dialog.posted
+ text: qsTr("View issue")
+ iconName: "external"
+ onClicked: dialog.viewIssue()
+ },
+ UI.Button {
+ visible: dialog.stage !== "opening"
+ kind: "primary"
+ text: qsTr("Close window")
+ onClicked: dialog.closeWindow()
+ }
+ ]
+}
diff --git a/packages/wildos-report/qml/Main.qml b/packages/wildos-report/qml/Main.qml
index 3bc8ba6..0c2468e 100644
--- a/packages/wildos-report/qml/Main.qml
+++ b/packages/wildos-report/qml/Main.qml
@@ -207,6 +207,30 @@ UI.AppWindow {
onAccepted: Report.saveTo(selectedFile)
}
+ HandoffDialog {
+ id: handoffDialog
+ stage: Report.handoff
+ zipName: Report.handoffZip
+ issueNumber: Report.postedNumber
+ watching: Report.watching
+ onShowReport: Report.showSaved()
+ onOpenAgain: Report.reopenGitHub()
+ onViewIssue: Report.viewPosted()
+ onCloseWindow: window.close()
+ onClosed: Report.endHandoff()
+
+ Connections {
+ target: Report
+ function onHandoffChanged() {
+ if (Report.handoff.length > 0 && !handoffDialog.opened) {
+ handoffDialog.open();
+ } else if (Report.handoff.length === 0 && handoffDialog.opened) {
+ handoffDialog.close();
+ }
+ }
+ }
+ }
+
UI.Toast {
id: toast
anchors.horizontalCenter: parent.horizontalCenter
diff --git a/packages/wildos-report/qml/PageSend.qml b/packages/wildos-report/qml/PageSend.qml
index 66cd3b4..5ab2318 100644
--- a/packages/wildos-report/qml/PageSend.qml
+++ b/packages/wildos-report/qml/PageSend.qml
@@ -67,8 +67,10 @@ Item {
FieldLabel {
text: qsTr("Title")
}
- TextField {
+ UI.TextField {
id: titleField
+ // Escape would otherwise wipe the suggested title.
+ escapeClears: false
Layout.fillWidth: true
implicitHeight: 32
leftPadding: 10
diff --git a/packages/wildos-report/qml/PageWhat.qml b/packages/wildos-report/qml/PageWhat.qml
index 6a5ad18..309afa4 100644
--- a/packages/wildos-report/qml/PageWhat.qml
+++ b/packages/wildos-report/qml/PageWhat.qml
@@ -5,7 +5,8 @@ import WildOS.Report
import WildOS.UI as UI
// Step 1, What happened (ReportDescribe.dc): which part, when, what went
-// wrong, whether it happens again, and screenshots.
+// wrong, whether it happens again, and screenshots: a new one taken with
+// Capture, or pictures already on the PC.
Item {
id: page
@@ -93,8 +94,9 @@ Item {
text: qsTr("at")
color: UI.Style.inkMuted
}
- TextField {
+ UI.TextField {
id: timeField
+ escapeClears: false
implicitWidth: 72
implicitHeight: 32
text: Report.pickTime
@@ -152,7 +154,7 @@ Item {
anchors.fill: parent
ScrollBar.vertical: UI.ScrollBar {}
- TextArea {
+ UI.TextArea {
id: description
text: Report.description
onTextChanged: Report.description = text
@@ -266,16 +268,26 @@ Item {
}
Item {
- width: addShot.width
- height: Report.screenshots.length > 0 ? 58 : addShot.height
+ width: addButtons.width
+ height: Report.screenshots.length > 0 ? 58 : addButtons.height
- ActionButton {
- id: addShot
+ Row {
+ id: addButtons
anchors.verticalCenter: parent.verticalCenter
- iconName: "image-plus"
- text: Report.capturing ? qsTr("Waiting for Capture") : qsTr("Add a screenshot")
- enabled: !Report.capturing
- onClicked: Report.takeScreenshot()
+ spacing: 8
+
+ ActionButton {
+ iconName: "image-plus"
+ text: Report.capturing ? qsTr("Waiting for Capture") : qsTr("Take a screenshot")
+ enabled: !Report.capturing
+ onClicked: Report.takeScreenshot()
+ }
+ ActionButton {
+ iconName: "folder"
+ text: qsTr("Choose a picture")
+ enabled: !Report.capturing
+ onClicked: Report.chooseScreenshotFiles(page.Window.window)
+ }
}
}
}
diff --git a/packages/wildos-report/src/issuewatch.cpp b/packages/wildos-report/src/issuewatch.cpp
new file mode 100644
index 0000000..7874e76
--- /dev/null
+++ b/packages/wildos-report/src/issuewatch.cpp
@@ -0,0 +1,36 @@
+#include "issuewatch.h"
+
+#include <QJsonArray>
+#include <QJsonDocument>
+#include <QJsonObject>
+
+namespace IssueWatch
+{
+Posted find(const QByteArray &json, const QString &zipName, const QDateTime &since)
+{
+ if (zipName.isEmpty()) {
+ return {};
+ }
+ const QDateTime earliest = since.toUTC().addSecs(-120);
+ // Only ever opened in the browser, so it must be an issue page of ours.
+ static const QString prefix = QStringLiteral("https://github.com/wildorigins/wildos/issues/");
+ for (const QJsonValue &value : QJsonDocument::fromJson(json).array()) {
+ const QJsonObject issue = value.toObject();
+ // The issues list includes pull requests.
+ if (issue.contains(QLatin1String("pull_request"))) {
+ continue;
+ }
+ const QDateTime created = QDateTime::fromString(issue.value(QLatin1String("created_at")).toString(), Qt::ISODate);
+ if (!created.isValid() || created < earliest) {
+ continue;
+ }
+ const bool named = issue.value(QLatin1String("body")).toString().contains(zipName);
+ const QString url = issue.value(QLatin1String("html_url")).toString();
+ const int number = issue.value(QLatin1String("number")).toInt();
+ if (named && number > 0 && url == prefix + QString::number(number)) {
+ return {number, url};
+ }
+ }
+ return {};
+}
+}
diff --git a/packages/wildos-report/src/issuewatch.h b/packages/wildos-report/src/issuewatch.h
new file mode 100644
index 0000000..50834ad
--- /dev/null
+++ b/packages/wildos-report/src/issuewatch.h
@@ -0,0 +1,21 @@
+#pragma once
+
+#include <QDateTime>
+#include <QString>
+
+// Finding the issue someone posted after Report a problem opened GitHub for
+// them, in GitHub's list of the newest issues. Nobody signs in here, so the
+// only thing tying an issue to this report is what we put in it: the zip's
+// name, which the issue body names and the attached file is called by.
+namespace IssueWatch
+{
+struct Posted {
+ int number = 0;
+ QString url;
+};
+
+// `json` is a reply from /repos/wildorigins/wildos/issues. An issue counts
+// when its body names `zipName` and it was opened after `since`, less a
+// couple of minutes for a clock that is slightly out.
+Posted find(const QByteArray &json, const QString &zipName, const QDateTime &since);
+}
diff --git a/packages/wildos-report/src/main.cpp b/packages/wildos-report/src/main.cpp
index 6d33a61..3c08302 100644
--- a/packages/wildos-report/src/main.cpp
+++ b/packages/wildos-report/src/main.cpp
@@ -8,6 +8,10 @@
// wildos-report --part files the same
// wildos-report --crash USEC --app NAME
// after "<App> closed unexpectedly"
+// wildos-report --event FILE with an event from Settings >
+// System > History attached (a JSON
+// note in the runtime folder, deleted
+// once read)
// wildos-report --save DIR [--part X] [--since SECS] [--until SECS]
// [--boot -1] [--description TEXT]
// no window: the whole report, saved
@@ -174,6 +178,7 @@ int main(int argc, char *argv[])
parser.addOption({QStringLiteral("part"), QStringLiteral("The part of Wild OS to report a problem with."), QStringLiteral("part")});
parser.addOption({QStringLiteral("crash"), QStringLiteral("When it crashed, in microseconds since 1970."), QStringLiteral("usec")});
parser.addOption({QStringLiteral("app"), QStringLiteral("The name of the app that crashed."), QStringLiteral("name")});
+ parser.addOption({QStringLiteral("event"), QStringLiteral("An event from History to attach."), QStringLiteral("file")});
parser.addPositionalArgument(QStringLiteral("url"), QStringLiteral("wildos-report:<part>"));
parser.process(app);
@@ -191,6 +196,11 @@ int main(int argc, char *argv[])
Incubation incubation;
QQmlApplicationEngine engine;
engine.setIncubationController(&incubation);
+ // QQmlApplicationEngine only wires Qt.quit() up when it loads the window
+ // itself; this window comes through a component and an incubator. Left
+ // unwired, closing the window hid it but the app kept running, holding
+ // the D-Bus name, so every later launch went to a window nobody saw.
+ QObject::connect(&engine, &QQmlEngine::quit, &app, &QCoreApplication::quit, Qt::QueuedConnection);
QObject *splash = makeSplash(&engine);
QQmlComponent home(&engine);
diff --git a/packages/wildos-report/src/report.cpp b/packages/wildos-report/src/report.cpp
index 1f604c8..6cf2f80 100644
--- a/packages/wildos-report/src/report.cpp
+++ b/packages/wildos-report/src/report.cpp
@@ -1,11 +1,19 @@
#include "report.h"
+#include "issuewatch.h"
#include "parts.h"
#include "sysinfo.h"
+#include <KWaylandExtras>
+#include <KWindowSystem>
#include <KZip>
#include <QBuffer>
#include <QClipboard>
+#include <QColorSpace>
+#include <QDBusArgument>
+#include <QDBusConnection>
+#include <QDBusMessage>
+#include <QDBusMetaType>
#include <QDesktopServices>
#include <QDir>
#include <QEventLoop>
@@ -13,13 +21,66 @@
#include <QFileInfo>
#include <QFutureWatcher>
#include <QGuiApplication>
+#include <QImage>
+#include <QImageReader>
+#include <QJsonDocument>
+#include <QJsonObject>
#include <QLocale>
+#include <QNetworkAccessManager>
+#include <QNetworkReply>
+#include <QNetworkRequest>
+#include <QPainter>
#include <QProcess>
#include <QRegularExpression>
#include <QStandardPaths>
#include <QUrl>
#include <QtConcurrentRun>
+#include <unistd.h>
+
+struct PickerRule {
+ uint type = 0;
+ QString pattern;
+};
+struct PickerFilter {
+ QString name;
+ QList<PickerRule> rules;
+};
+Q_DECLARE_METATYPE(PickerRule)
+Q_DECLARE_METATYPE(PickerFilter)
+
+QDBusArgument &operator<<(QDBusArgument &arg, const PickerRule &rule)
+{
+ arg.beginStructure();
+ arg << rule.type << rule.pattern;
+ arg.endStructure();
+ return arg;
+}
+
+const QDBusArgument &operator>>(const QDBusArgument &arg, PickerRule &rule)
+{
+ arg.beginStructure();
+ arg >> rule.type >> rule.pattern;
+ arg.endStructure();
+ return arg;
+}
+
+QDBusArgument &operator<<(QDBusArgument &arg, const PickerFilter &filter)
+{
+ arg.beginStructure();
+ arg << filter.name << filter.rules;
+ arg.endStructure();
+ return arg;
+}
+
+const QDBusArgument &operator>>(const QDBusArgument &arg, PickerFilter &filter)
+{
+ arg.beginStructure();
+ arg >> filter.name >> filter.rules;
+ arg.endStructure();
+ return arg;
+}
+
namespace
{
const QString issuesUrl = QStringLiteral("https://github.com/wildorigins/wildos/issues");
@@ -131,7 +192,8 @@ Report::Report(QObject *parent)
const char *file;
bool included;
} sections[] = {
- {"description", "report.md", true}, {"about", "about-this-pc.txt", true}, {"crash", "crash.txt", true},
+ {"description", "report.md", true}, {"event", "history-event.txt", true}, {"about", "about-this-pc.txt", true},
+ {"crash", "crash.txt", true},
{"logs", "logs.txt", true}, {"updates", "recent-updates.txt", true}, {"fulllog", "full-system-log.txt", false},
};
for (const auto &s : sections) {
@@ -142,6 +204,8 @@ Report::Report(QObject *parent)
m_sections << section;
}
connect(&m_collector, &Collector::finished, this, &Report::collected);
+ m_watchTimer.setSingleShot(true);
+ connect(&m_watchTimer, &QTimer::timeout, this, &Report::watchOnce);
m_capturePoll.setInterval(250);
connect(&m_capturePoll, &QTimer::timeout, this, [this]() {
const bool done = QFile::exists(m_capturePath);
@@ -188,6 +252,11 @@ void Report::handle(const QStringList &arguments)
} else if (a == QLatin1String("--app") && i + 1 < arguments.size()) {
m_crashApp = arguments.at(++i);
Q_EMIT crashChanged();
+ } else if (a == QLatin1String("--event") && i + 1 < arguments.size()) {
+ const QString about = readEvent(arguments.at(++i));
+ if (part.isEmpty()) {
+ part = about;
+ }
}
}
// A report already under way keeps its answers.
@@ -197,6 +266,64 @@ void Report::handle(const QStringList &arguments)
Q_EMIT raiseRequested();
}
+QString Report::readEvent(const QString &path)
+{
+ // Only from this account's own runtime folder, where Settings leaves it
+ // and nobody else can write.
+ const QFileInfo info(path);
+ const QString runtime = QStandardPaths::writableLocation(QStandardPaths::RuntimeLocation);
+ if (runtime.isEmpty() || !info.canonicalFilePath().startsWith(QFileInfo(runtime).canonicalFilePath() + QLatin1Char('/')) || !info.isFile()
+ || info.isSymLink() || info.ownerId() != getuid() || info.size() > 256 * 1024) {
+ return {};
+ }
+ QFile file(path);
+ if (!file.open(QIODevice::ReadOnly)) {
+ return {};
+ }
+ const QJsonObject o = QJsonDocument::fromJson(file.readAll()).object();
+ file.close();
+ file.remove();
+ const QString title = o.value(QStringLiteral("title")).toString().left(200);
+ const QString text = o.value(QStringLiteral("text")).toString();
+ if (title.isEmpty() || text.isEmpty()) {
+ return {};
+ }
+ m_eventTitle = title;
+ m_eventTime = QDateTime::fromSecsSinceEpoch(o.value(QStringLiteral("when")).toInteger());
+ section(QStringLiteral("event"))->raw = QStringLiteral("# From Settings > System > History\n\n") + text;
+ m_fixedSince = {};
+ if (o.value(QStringLiteral("crash")).toBool()) {
+ m_crashTime = m_eventTime;
+ m_crashApp = o.value(QStringLiteral("app")).toString();
+ }
+ Q_EMIT crashChanged();
+ Q_EMIT whenChanged();
+ Q_EMIT itemsChanged();
+
+ // The part of Wild OS the event is about, so the logs gathered are its.
+ const QString kind = o.value(QStringLiteral("kind")).toString();
+ const QString program = o.value(QStringLiteral("program")).toString();
+ if (!program.isEmpty()) {
+ return Parts::byProgram(program).id;
+ }
+ if (kind.startsWith(QLatin1String("update")) || kind == QLatin1String("restore-point") || kind == QLatin1String("programs")) {
+ return QStringLiteral("updates");
+ }
+ if (kind.startsWith(QLatin1String("app")) || kind == QLatin1String("install-failed")) {
+ return QStringLiteral("store");
+ }
+ if (kind.startsWith(QLatin1String("drive"))) {
+ return QStringLiteral("files");
+ }
+ if (kind == QLatin1String("signin") || kind == QLatin1String("signout") || kind == QLatin1String("password")) {
+ return QStringLiteral("signin");
+ }
+ if (kind == QLatin1String("firewall")) {
+ return QStringLiteral("network");
+ }
+ return QStringLiteral("other");
+}
+
QVariantList Report::parts() const
{
return Parts::choices();
@@ -263,11 +390,13 @@ QPair<QDateTime, QDateTime> Report::window() const
}
} else {
// Ten minutes before the crash or now, so what led up to it is in.
+ // An event from History is looked at however long ago it was.
const bool recentCrash = m_crashTime.isValid() && m_crashTime.secsTo(now) < 6 * 3600;
- const QDateTime anchor = recentCrash ? m_crashTime : now;
+ const bool anchored = recentCrash || m_eventTime.isValid();
+ const QDateTime anchor = recentCrash ? m_crashTime : m_eventTime.isValid() ? m_eventTime : now;
since = anchor.addSecs(-10 * 60);
since.setTime(QTime(since.time().hour(), since.time().minute()));
- until = recentCrash ? qMin(now, anchor.addSecs(5 * 60)) : now;
+ until = anchored ? qMin(now, anchor.addSecs(5 * 60)) : now;
}
return {since, until};
}
@@ -311,9 +440,10 @@ QVariantList Report::screenshots() const
QVariantList list;
for (const QString &path : m_shots) {
const QFileInfo info(path);
+ const QString name = m_shotNames.value(path);
list.append(QVariantMap{
{QStringLiteral("url"), QUrl::fromLocalFile(path)},
- {QStringLiteral("label"), QStringLiteral("Screenshot, %1").arg(info.lastModified().toString(QStringLiteral("HH:mm")))},
+ {QStringLiteral("label"), name.isEmpty() ? QStringLiteral("Screenshot, %1").arg(info.lastModified().toString(QStringLiteral("HH:mm"))) : name},
{QStringLiteral("size"), sizeName(info.size())},
});
}
@@ -322,6 +452,11 @@ QVariantList Report::screenshots() const
QString Report::crashNote() const
{
+ if (!m_eventTitle.isEmpty()) {
+ const QString at = m_eventTime.date() == QDate::currentDate() ? m_eventTime.toString(QStringLiteral("HH:mm"))
+ : m_eventTime.toString(QStringLiteral("d MMMM, HH:mm"));
+ return QStringLiteral("From History: %1, %2. Its details are added for you.").arg(m_eventTitle, at);
+ }
if (!m_crashTime.isValid()) {
return {};
}
@@ -358,7 +493,9 @@ void Report::removeScreenshot(int index)
if (index < 0 || index >= m_shots.size()) {
return;
}
- QFile::remove(m_shots.takeAt(index));
+ const QString path = m_shots.takeAt(index);
+ m_shotNames.remove(path);
+ QFile::remove(path);
Q_EMIT screenshotsChanged();
if (m_redactSerial > 0) {
redactAll();
@@ -395,6 +532,9 @@ QString Report::describe() const
if (m_crashTime.isValid()) {
lines << QStringLiteral("Closed unexpectedly at: %1").arg(m_crashTime.toString(QStringLiteral("d MMMM yyyy, HH:mm:ss")));
}
+ if (!m_eventTitle.isEmpty()) {
+ lines << QStringLiteral("From History: %1, %2").arg(m_eventTitle, m_eventTime.toString(QStringLiteral("d MMMM yyyy, HH:mm")));
+ }
lines << QStringLiteral("When: %1 (%2 to %3)")
.arg(m_when == QLatin1String("today") ? QStringLiteral("Earlier today")
: m_when == QLatin1String("pick") ? QStringLiteral("At a time picked")
@@ -512,6 +652,9 @@ QVariantList Report::items() const
: m_shots.size() == 1 ? QStringLiteral("Your description and screenshot")
: QStringLiteral("Your description"),
shots, QStringLiteral("file-text"));
+ if (!m_eventTitle.isEmpty()) {
+ add(QStringLiteral("event"), QStringLiteral("This event from History"), m_eventTitle, QStringLiteral("history"));
+ }
const QString v = SysInfo::version();
add(QStringLiteral("about"), QStringLiteral("About this PC"),
v.isEmpty() ? QStringLiteral("Wild OS version, the PC's model, graphics and memory")
@@ -580,6 +723,9 @@ QString Report::previewTitle() const
if (m_viewing == QLatin1String("crash")) {
return QStringLiteral("Preview: crash details");
}
+ if (m_viewing == QLatin1String("event")) {
+ return QStringLiteral("Preview: the event from History");
+ }
if (m_viewing == QLatin1String("updates")) {
return QStringLiteral("Preview: recent updates");
}
@@ -740,6 +886,166 @@ QString Report::suggestedName() const
return QStringLiteral("wildos-report-%1.zip").arg(QTime::currentTime().toString(QStringLiteral("HHmm")));
}
+// The portal's own call rather than Qt's file dialog: Qt only passes the
+// folder to start in when saving, and Open should start in Screenshots.
+void Report::chooseScreenshotFiles(QWindow *window)
+{
+ if (!m_pickerRequest.isEmpty()) {
+ return;
+ }
+ m_pickerRequest = QStringLiteral("pending");
+ const auto ask = [this](const QString &parent) {
+ static const bool registered = [] {
+ qDBusRegisterMetaType<PickerRule>();
+ qDBusRegisterMetaType<QList<PickerRule>>();
+ qDBusRegisterMetaType<PickerFilter>();
+ qDBusRegisterMetaType<QList<PickerFilter>>();
+ return true;
+ }();
+ Q_UNUSED(registered)
+ static int serial = 0;
+ const QString token = QStringLiteral("wildos_report_%1").arg(++serial);
+ QString sender = QDBusConnection::sessionBus().baseService().mid(1);
+ sender.replace(QLatin1Char('.'), QLatin1Char('_'));
+ m_pickerRequest = QStringLiteral("/org/freedesktop/portal/desktop/request/%1/%2").arg(sender, token);
+ QDBusConnection::sessionBus().connect(QStringLiteral("org.freedesktop.portal.Desktop"), m_pickerRequest,
+ QStringLiteral("org.freedesktop.portal.Request"), QStringLiteral("Response"), this,
+ SLOT(pickerResponse(uint, QVariantMap)));
+
+ QList<PickerFilter> filters{{QStringLiteral("Pictures"), {}}};
+ for (const char *glob : {"*.png", "*.jpg", "*.jpeg", "*.webp", "*.gif", "*.bmp"}) {
+ filters.first().rules.append({0, QString::fromLatin1(glob)});
+ }
+ QByteArray folder = QFile::encodeName(screenshotsFolder().toLocalFile());
+ folder.append('\0');
+ const QVariantMap options{
+ {QStringLiteral("handle_token"), token},
+ {QStringLiteral("modal"), true},
+ {QStringLiteral("multiple"), true},
+ {QStringLiteral("filters"), QVariant::fromValue(filters)},
+ {QStringLiteral("current_filter"), QVariant::fromValue(filters.first())},
+ {QStringLiteral("current_folder"), folder},
+ };
+ QDBusMessage call = QDBusMessage::createMethodCall(QStringLiteral("org.freedesktop.portal.Desktop"), QStringLiteral("/org/freedesktop/portal/desktop"),
+ QStringLiteral("org.freedesktop.portal.FileChooser"), QStringLiteral("OpenFile"));
+ call << parent << QStringLiteral("Choose a picture") << options;
+ QDBusConnection::sessionBus().callWithCallback(call, this, SLOT(pickerOpened()), SLOT(pickerFailed()));
+ };
+ if (!window || !KWindowSystem::isPlatformWayland()) {
+ ask(QString());
+ return;
+ }
+ // The dialog belongs to this window (in front of it, no taskbar button
+ // of its own) through the handle the compositor gives it.
+ auto done = std::make_shared<bool>(false);
+ auto exported = std::make_shared<QMetaObject::Connection>();
+ *exported = connect(KWaylandExtras::self(), &KWaylandExtras::windowExported, this, [ask, window, done, exported](QWindow *w, const QString &handle) {
+ if (w != window || *done) {
+ return;
+ }
+ *done = true;
+ QObject::disconnect(*exported);
+ ask(QStringLiteral("wayland:") + handle);
+ });
+ QTimer::singleShot(1000, this, [ask, done, exported]() {
+ if (!*done) {
+ *done = true;
+ QObject::disconnect(*exported);
+ ask(QString());
+ }
+ });
+ KWaylandExtras::exportWindow(window);
+}
+
+void Report::pickerResponse(uint response, const QVariantMap &results)
+{
+ QDBusConnection::sessionBus().disconnect(QStringLiteral("org.freedesktop.portal.Desktop"), m_pickerRequest,
+ QStringLiteral("org.freedesktop.portal.Request"), QStringLiteral("Response"), this,
+ SLOT(pickerResponse(uint, QVariantMap)));
+ m_pickerRequest.clear();
+ if (response != 0) {
+ return;
+ }
+ QList<QUrl> files;
+ const QStringList uris = results.value(QStringLiteral("uris")).toStringList();
+ for (const QString &uri : uris) {
+ files << QUrl(uri);
+ }
+ addScreenshotFiles(files);
+}
+
+void Report::pickerOpened()
+{
+}
+
+void Report::pickerFailed()
+{
+ m_pickerRequest.clear();
+ Q_EMIT message(QStringLiteral("The Open dialog couldn't be shown"));
+}
+
+void Report::addScreenshotFiles(const QList<QUrl> &files)
+{
+ if (!m_temp.isValid()) {
+ return;
+ }
+ int added = 0;
+ QStringList unreadable;
+ for (const QUrl &file : files) {
+ const QString source = file.toLocalFile();
+ QImageReader reader(source);
+ reader.setAutoTransform(true);
+ QImage image = reader.read();
+ if (image.isNull()) {
+ unreadable << QFileInfo(source).fileName();
+ continue;
+ }
+ if (image.colorSpace().isValid() && image.colorSpace() != QColorSpace(QColorSpace::SRgb)) {
+ image.convertToColorSpace(QColorSpace(QColorSpace::SRgb));
+ }
+ // Photos from a phone run to 50 megapixels; a screen's worth is
+ // plenty to show a problem and keeps the report small.
+ if (image.width() > 3840 || image.height() > 3840) {
+ image = image.scaled(3840, 3840, Qt::KeepAspectRatio, Qt::SmoothTransformation);
+ }
+ // Drawn onto a blank picture and saved as a new PNG, the way a
+ // screenshot from Capture is added: the copy carries no location,
+ // camera or author details and no file name, only the pixels.
+ QImage clean(image.size(), image.hasAlphaChannel() ? QImage::Format_ARGB32 : QImage::Format_RGB32);
+ clean.fill(Qt::transparent);
+ {
+ QPainter painter(&clean);
+ painter.drawImage(0, 0, image);
+ }
+ const QString path = m_temp.filePath(QStringLiteral("picture-%1-%2.png").arg(QDateTime::currentMSecsSinceEpoch()).arg(added));
+ if (!clean.save(path, "PNG")) {
+ unreadable << QFileInfo(source).fileName();
+ continue;
+ }
+ m_shots << path;
+ m_shotNames.insert(path, QFileInfo(source).fileName());
+ ++added;
+ }
+ if (added > 0) {
+ Q_EMIT screenshotsChanged();
+ if (m_redactSerial > 0) {
+ redactAll();
+ }
+ }
+ if (unreadable.size() == 1) {
+ Q_EMIT message(QStringLiteral("%1 couldn't be opened as a picture").arg(unreadable.first()));
+ } else if (unreadable.size() > 1) {
+ Q_EMIT message(QStringLiteral("%1 files couldn't be opened as pictures").arg(unreadable.size()));
+ }
+}
+
+QUrl Report::screenshotsFolder() const
+{
+ const QString pictures = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation);
+ const QString screenshots = pictures + QStringLiteral("/Screenshots");
+ return QUrl::fromLocalFile(QFileInfo(screenshots).isDir() ? screenshots : pictures);
+}
+
QUrl Report::downloadsFolder() const
{
return QUrl::fromLocalFile(QStandardPaths::writableLocation(QStandardPaths::DownloadLocation));
@@ -824,6 +1130,7 @@ QString Report::issueBody(const QString &zipName, int budget) const
QStringList lines{words, QString(), QStringLiteral("| | |"), QStringLiteral("|---|---|")};
lines << QStringLiteral("| Part of Wild OS | %1 |").arg(partName());
lines << QStringLiteral("| When | %1 |").arg(m_crashTime.isValid() ? m_crashTime.toString(QStringLiteral("d MMMM yyyy, HH:mm"))
+ : m_eventTime.isValid() ? m_eventTime.toString(QStringLiteral("d MMMM yyyy, HH:mm"))
: QStringLiteral("%1 to %2").arg(since.toString(QStringLiteral("d MMMM yyyy, HH:mm")),
until.toString(QStringLiteral("HH:mm"))));
if (!repeatText().isEmpty()) {
@@ -841,31 +1148,149 @@ QString Report::issueBody(const QString &zipName, int budget) const
return lines.join(QLatin1Char('\n'));
}
-bool Report::openGitHub()
+void Report::setHandoff(const QString &state)
{
- const QString folder = QStandardPaths::writableLocation(QStandardPaths::DownloadLocation);
- QDir().mkpath(folder);
- const QString path = writeZip(uniquePath(folder), false);
- if (path.isEmpty()) {
- Q_EMIT message(QStringLiteral("The report couldn't be saved to Downloads"));
- return false;
+ m_handoff = state;
+ Q_EMIT handoffChanged();
+}
+
+void Report::openGitHub()
+{
+ if (m_handoff == QLatin1String("opening")) {
+ return;
}
- const QString title = m_title.trimmed().isEmpty() ? QStringLiteral("Problem with %1").arg(partName()) : m_title.trimmed();
- const auto encode = [](const QString &value) { return QString::fromLatin1(QUrl::toPercentEncoding(value)); };
- const QString zipName = QFileInfo(path).fileName();
- const auto address = [&](int budget) {
- return issuesUrl + QStringLiteral("/new?title=") + encode(title) + QStringLiteral("&body=") + encode(issueBody(zipName, budget));
- };
- // A long description is cut to fit, and the whole of it is in the zip.
- QString url = address(-1);
- for (int budget = int(m_description.size()); url.size() > urlBudget && budget > 0; budget = budget * 4 / 5) {
- url = address(budget);
+ endHandoff();
+ m_postedNumber = 0;
+ m_postedUrl.clear();
+ setHandoff(QStringLiteral("opening"));
+ const int serial = m_handoffSerial;
+ // Writing the zip holds up the window for a moment, so the dialog that
+ // says what is happening gets drawn first.
+ QTimer::singleShot(150, this, [this, serial]() {
+ if (serial != m_handoffSerial) {
+ return;
+ }
+ const QString folder = QStandardPaths::writableLocation(QStandardPaths::DownloadLocation);
+ QDir().mkpath(folder);
+ const QString path = writeZip(uniquePath(folder), false);
+ if (path.isEmpty()) {
+ setHandoff({});
+ Q_EMIT message(QStringLiteral("The report couldn't be saved to Downloads"));
+ return;
+ }
+ const QString title = m_title.trimmed().isEmpty() ? QStringLiteral("Problem with %1").arg(partName()) : m_title.trimmed();
+ const auto encode = [](const QString &value) { return QString::fromLatin1(QUrl::toPercentEncoding(value)); };
+ const QString zipName = QFileInfo(path).fileName();
+ const auto address = [&](int budget) {
+ return issuesUrl + QStringLiteral("/new?title=") + encode(title) + QStringLiteral("&body=") + encode(issueBody(zipName, budget));
+ };
+ // A long description is cut to fit, and the whole of it is in the zip.
+ QString url = address(-1);
+ for (int budget = int(m_description.size()); url.size() > urlBudget && budget > 0; budget = budget * 4 / 5) {
+ url = address(budget);
+ }
+ if (url.size() > urlBudget) {
+ url = address(0);
+ }
+ m_handoffUrl = url;
+ m_handoffZip = zipName;
+ m_handoffAt = QDateTime::currentDateTimeUtc();
+ if (!QDesktopServices::openUrl(QUrl::fromEncoded(url.toLatin1()))) {
+ setHandoff({});
+ Q_EMIT message(QStringLiteral("The browser couldn't be opened. The report is in Downloads."));
+ return;
+ }
+ // The browser takes a moment to appear; saying "finish in your
+ // browser" before it has would be ahead of what is on screen.
+ QTimer::singleShot(2500, this, [this, serial]() {
+ if (serial != m_handoffSerial) {
+ return;
+ }
+ m_watching = true;
+ setHandoff(QStringLiteral("waiting"));
+ watchNext(20);
+ });
+ });
+}
+
+void Report::reopenGitHub()
+{
+ if (!m_handoffUrl.isEmpty()) {
+ QDesktopServices::openUrl(QUrl::fromEncoded(m_handoffUrl.toLatin1()));
+ }
+}
+
+void Report::endHandoff()
+{
+ ++m_handoffSerial;
+ m_watchTimer.stop();
+ m_watching = false;
+ m_watchTag.clear();
+ if (m_watchReply) {
+ m_watchReply->abort();
}
- if (url.size() > urlBudget) {
- url = address(0);
+ if (!m_handoff.isEmpty()) {
+ setHandoff({});
}
- QDesktopServices::openUrl(QUrl::fromEncoded(url.toLatin1()));
- return true;
+}
+
+void Report::viewPosted()
+{
+ if (!m_postedUrl.isEmpty()) {
+ QDesktopServices::openUrl(QUrl(m_postedUrl));
+ }
+}
+
+// Without signing in, GitHub answers 60 requests an hour from one address,
+// but an answer that nothing has changed since last time (304) is free. So
+// even if new issues kept arriving, every 20 seconds for ten minutes and
+// then every minute until half an hour stays under the limit.
+void Report::watchNext(int seconds)
+{
+ if (m_handoffAt.secsTo(QDateTime::currentDateTimeUtc()) + seconds > 30 * 60) {
+ m_watching = false;
+ Q_EMIT handoffChanged();
+ return;
+ }
+ m_watchTimer.start(seconds * 1000);
+}
+
+void Report::watchOnce()
+{
+ if (!m_net) {
+ m_net = new QNetworkAccessManager(this);
+ }
+ QNetworkRequest request(QUrl(QStringLiteral("https://api.github.com/repos/wildorigins/wildos/issues?state=all&sort=created&direction=desc&per_page=30")));
+ request.setHeader(QNetworkRequest::UserAgentHeader, QByteArrayLiteral("Wild OS Report a problem"));
+ request.setRawHeader("Accept", "application/vnd.github+json");
+ request.setRawHeader("X-GitHub-Api-Version", "2022-11-28");
+ if (!m_watchTag.isEmpty()) {
+ request.setRawHeader("If-None-Match", m_watchTag);
+ }
+ request.setTransferTimeout(20000);
+ const int serial = m_handoffSerial;
+ QNetworkReply *reply = m_net->get(request);
+ m_watchReply = reply;
+ connect(reply, &QNetworkReply::finished, this, [this, serial, reply]() {
+ reply->deleteLater();
+ if (serial != m_handoffSerial) {
+ return;
+ }
+ const int status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
+ if (status == 200) {
+ m_watchTag = reply->rawHeader("ETag");
+ const IssueWatch::Posted posted = IssueWatch::find(reply->readAll(), m_handoffZip, m_handoffAt);
+ if (posted.number > 0) {
+ m_postedNumber = posted.number;
+ m_postedUrl = posted.url;
+ m_watching = false;
+ setHandoff(QStringLiteral("posted"));
+ return;
+ }
+ }
+ const bool limited = status == 403 || status == 429;
+ watchNext(limited ? 120 : m_handoffAt.secsTo(QDateTime::currentDateTimeUtc()) < 600 ? 20 : 60);
+ });
}
bool Report::saveTo(const QUrl &file)
diff --git a/packages/wildos-report/src/report.h b/packages/wildos-report/src/report.h
index f29d8e5..2b1a20e 100644
--- a/packages/wildos-report/src/report.h
+++ b/packages/wildos-report/src/report.h
@@ -6,10 +6,15 @@
#include <QAbstractListModel>
#include <QDateTime>
#include <QObject>
+#include <QPointer>
#include <QQmlEngine>
#include <QTemporaryDir>
#include <QTimer>
#include <QVariantList>
+#include <QWindow>
+
+class QNetworkAccessManager;
+class QNetworkReply;
// The lines of whatever the preview pane shows. A log line has a time and a
// source; anything else is just text.
@@ -70,13 +75,21 @@ class Report : public QObject
Q_PROPERTY(QString title READ title WRITE setTitle NOTIFY titleChanged)
Q_PROPERTY(QString savedText READ savedText NOTIFY savedChanged)
Q_PROPERTY(QString savedPath READ savedPath NOTIFY savedChanged)
+ // After Open GitHub: "opening" while the zip is written and the browser
+ // starts, "waiting" while the issue is finished there, "posted" once it
+ // shows up on GitHub, empty otherwise.
+ Q_PROPERTY(QString handoff READ handoff NOTIFY handoffChanged)
+ Q_PROPERTY(bool watching READ watching NOTIFY handoffChanged)
+ Q_PROPERTY(QString handoffZip READ handoffZip NOTIFY handoffChanged)
+ Q_PROPERTY(int postedNumber READ postedNumber NOTIFY handoffChanged)
public:
static Report *instance();
static Report *create(QQmlEngine *, QJSEngine *) { return instance(); }
// From the command line or a second launch: wildos-report:<part>,
- // --part, and --crash/--app after a crash notification.
+ // --part, --crash/--app after a crash notification, and --event FILE
+ // from History.
void handle(const QStringList &arguments);
// `--save DIR` from start-up recovery, without a window: builds the
// whole report and writes it to DIR. Returns the zip's path, or empty.
@@ -114,6 +127,10 @@ public:
void setTitle(const QString &title);
QString savedText() const { return m_savedText; }
QString savedPath() const { return m_savedPath; }
+ QString handoff() const { return m_handoff; }
+ bool watching() const { return m_watching; }
+ QString handoffZip() const { return m_handoffZip; }
+ int postedNumber() const { return m_postedNumber; }
// Step 2 opens: gather for the chosen part and time, unless that is
// what was last gathered, and remove personal details from it all.
@@ -124,8 +141,15 @@ public:
Q_INVOKABLE void removeWord(const QString &word);
Q_INVOKABLE void takeScreenshot();
Q_INVOKABLE void removeScreenshot(int index);
+ // Pictures already on the PC: the Open dialog, starting in Pictures >
+ // Screenshots, in front of `window`.
+ Q_INVOKABLE void chooseScreenshotFiles(QWindow *window);
+ void addScreenshotFiles(const QList<QUrl> &files);
Q_INVOKABLE void suggestTitle();
- Q_INVOKABLE bool openGitHub();
+ Q_INVOKABLE void openGitHub();
+ Q_INVOKABLE void reopenGitHub();
+ Q_INVOKABLE void endHandoff();
+ Q_INVOKABLE void viewPosted();
Q_INVOKABLE bool saveTo(const QUrl &file);
Q_INVOKABLE void copyDescription();
Q_INVOKABLE void copyPreview();
@@ -149,6 +173,7 @@ Q_SIGNALS:
void sizeChanged();
void titleChanged();
void savedChanged();
+ void handoffChanged();
// The window gets out of the way of Capture, and comes back after.
void hideForCapture();
void captureDone();
@@ -156,7 +181,13 @@ Q_SIGNALS:
// Another launch asked for the window.
void raiseRequested();
+private Q_SLOTS:
+ void pickerResponse(uint response, const QVariantMap &results);
+ void pickerOpened();
+ void pickerFailed();
+
private:
+ QUrl screenshotsFolder() const;
// One per process: QML gets it through create(), not a constructor.
explicit Report(QObject *parent = nullptr);
@@ -172,6 +203,9 @@ private:
QPair<QDateTime, QDateTime> window() const;
QString describe() const;
QString repeatText() const;
+ // Reads what History handed over, then deletes it; returns the part
+ // of Wild OS it is about, or empty.
+ QString readEvent(const QString &path);
void collected(const RawReport &raw);
void redactAll();
void measure();
@@ -183,6 +217,9 @@ private:
QString uniquePath(const QString &folder) const;
QString issueBody(const QString &zipName, int budget) const;
void showPreview();
+ void setHandoff(const QString &state);
+ void watchNext(int seconds);
+ void watchOnce();
QString m_part = QStringLiteral("other");
QString m_when = QStringLiteral("now");
@@ -193,6 +230,9 @@ private:
QString m_title;
bool m_titleTouched = false;
QStringList m_shots;
+ // The name a chosen picture had, shown only beside it on this page.
+ QHash<QString, QString> m_shotNames;
+ QString m_pickerRequest;
QTemporaryDir m_temp;
bool m_capturing = false;
QString m_capturePath;
@@ -204,6 +244,9 @@ private:
QDateTime m_fixedUntil;
QString m_crashApp;
QDateTime m_crashTime;
+ // An event handed over from Settings > System > History (--event).
+ QString m_eventTitle;
+ QDateTime m_eventTime;
Collector m_collector;
bool m_collecting = false;
@@ -221,4 +264,16 @@ private:
PreviewModel m_preview;
QString m_savedText;
QString m_savedPath;
+ QString m_handoff;
+ int m_handoffSerial = 0;
+ QString m_handoffUrl;
+ QString m_handoffZip;
+ QDateTime m_handoffAt;
+ QTimer m_watchTimer;
+ bool m_watching = false;
+ QNetworkAccessManager *m_net = nullptr;
+ QPointer<QNetworkReply> m_watchReply;
+ QByteArray m_watchTag;
+ int m_postedNumber = 0;
+ QString m_postedUrl;
};
diff --git a/packages/wildos-report/tests/issuewatch_test.cpp b/packages/wildos-report/tests/issuewatch_test.cpp
new file mode 100644
index 0000000..678d06b
--- /dev/null
+++ b/packages/wildos-report/tests/issuewatch_test.cpp
@@ -0,0 +1,90 @@
+// Picking this report's issue out of GitHub's list of the newest ones. The
+// replies are trimmed copies of what /repos/wildorigins/wildos/issues sends.
+
+#include "issuewatch.h"
+
+#include <QJsonDocument>
+#include <QJsonObject>
+#include <QTest>
+
+class IssueWatchTest : public QObject
+{
+ Q_OBJECT
+
+private:
+ const QDateTime opened = QDateTime::fromString(QStringLiteral("2026-11-14T10:00:00Z"), Qt::ISODate);
+ const QString zip = QStringLiteral("wildos-report-1000.zip");
+
+ static QByteArray issue(int number, const QString &created, const QString &body, bool pull = false)
+ {
+ QJsonObject object{{QStringLiteral("number"), number},
+ {QStringLiteral("html_url"),
+ QStringLiteral("https://github.com/wildorigins/wildos/%1/%2").arg(pull ? QStringLiteral("pull") : QStringLiteral("issues")).arg(number)},
+ {QStringLiteral("created_at"), created},
+ {QStringLiteral("body"), body}};
+ if (pull) {
+ object.insert(QStringLiteral("pull_request"), QJsonObject());
+ }
+ return QJsonDocument(object).toJson(QJsonDocument::Compact);
+ }
+
+ static QByteArray list(const QList<QByteArray> &issues)
+ {
+ QByteArray out = "[";
+ for (qsizetype i = 0; i < issues.size(); ++i) {
+ out += (i > 0 ? "," : "") + issues.at(i);
+ }
+ return out + "]";
+ }
+
+private Q_SLOTS:
+ void findsTheIssueThatNamesTheZip()
+ {
+ const QByteArray reply = list({issue(58, QStringLiteral("2026-11-14T10:04:10Z"), QStringLiteral("Something else")),
+ issue(57, QStringLiteral("2026-11-14T10:03:00Z"), QStringLiteral("Files froze. Drag `wildos-report-1000.zip` here."))});
+ const IssueWatch::Posted posted = IssueWatch::find(reply, zip, opened);
+ QCOMPARE(posted.number, 57);
+ QCOMPARE(posted.url, QStringLiteral("https://github.com/wildorigins/wildos/issues/57"));
+ }
+
+ void findsItByTheAttachedFile()
+ {
+ const QByteArray reply = list({issue(57, QStringLiteral("2026-11-14T10:03:00Z"),
+ QStringLiteral("[wildos-report-1000.zip](https://github.com/user-attachments/files/1/wildos-report-1000.zip)"))});
+ QCOMPARE(IssueWatch::find(reply, zip, opened).number, 57);
+ }
+
+ void ignoresAnOlderIssueWithTheSameName()
+ {
+ const QByteArray reply = list({issue(40, QStringLiteral("2026-11-13T10:03:00Z"), QStringLiteral("wildos-report-1000.zip"))});
+ QCOMPARE(IssueWatch::find(reply, zip, opened).number, 0);
+ }
+
+ void allowsAClockSlightlyAhead()
+ {
+ const QByteArray reply = list({issue(57, QStringLiteral("2026-11-14T09:59:00Z"), QStringLiteral("wildos-report-1000.zip"))});
+ QCOMPARE(IssueWatch::find(reply, zip, opened).number, 57);
+ }
+
+ void ignoresPullRequests()
+ {
+ const QByteArray reply = list({issue(59, QStringLiteral("2026-11-14T10:03:00Z"), QStringLiteral("wildos-report-1000.zip"), true)});
+ QCOMPARE(IssueWatch::find(reply, zip, opened).number, 0);
+ }
+
+ void ignoresAnotherNumberedZip()
+ {
+ const QByteArray reply = list({issue(57, QStringLiteral("2026-11-14T10:03:00Z"), QStringLiteral("wildos-report-1000-2.zip"))});
+ QCOMPARE(IssueWatch::find(reply, zip, opened).number, 0);
+ }
+
+ void survivesNonsense()
+ {
+ QCOMPARE(IssueWatch::find("{\"message\":\"API rate limit exceeded\"}", zip, opened).number, 0);
+ QCOMPARE(IssueWatch::find("not json", zip, opened).number, 0);
+ QCOMPARE(IssueWatch::find(list({}), QString(), opened).number, 0);
+ }
+};
+
+QTEST_GUILESS_MAIN(IssueWatchTest)
+#include "issuewatch_test.moc"
diff --git a/packages/wildos-settings/CMakeLists.txt b/packages/wildos-settings/CMakeLists.txt
index 20e1f12..5fadd07 100644
--- a/packages/wildos-settings/CMakeLists.txt
+++ b/packages/wildos-settings/CMakeLists.txt
@@ -8,6 +8,8 @@ include(GNUInstallDirs)
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(KF6Archive REQUIRED)
+find_package(Qt6Svg 6.8 REQUIRED)
find_package(KF6CoreAddons REQUIRED)
find_package(KF6Service REQUIRED)
find_package(KF6I18n REQUIRED)
@@ -37,6 +39,7 @@ set_source_files_properties(qml/components/Pages.qml PROPERTIES QT_QML_SINGLETON
set_source_files_properties(qml/components/Navigator.qml PROPERTIES QT_QML_SINGLETON_TYPE TRUE)
set_source_files_properties(qml/components/Format.qml PROPERTIES QT_QML_SINGLETON_TYPE TRUE)
set_source_files_properties(qml/components/Protection.qml PROPERTIES QT_QML_SINGLETON_TYPE TRUE)
+set_source_files_properties(qml/components/HistoryWords.qml PROPERTIES QT_QML_SINGLETON_TYPE TRUE)
qt_add_qml_module(wildos-settings
URI WildOS.Settings
@@ -56,6 +59,7 @@ qt_add_qml_module(wildos-settings
src/inputdevices.cpp src/inputdevices.h
src/defaultapps.cpp src/defaultapps.h
src/clock.cpp src/clock.h
+ src/securetime.cpp src/securetime.h
src/startupapps.cpp src/startupapps.h
src/keyboard.cpp src/keyboard.h
src/printers.cpp src/printers.h
@@ -81,6 +85,11 @@ qt_add_qml_module(wildos-settings
src/soundtheme.cpp src/soundtheme.h
src/accessibility.cpp src/accessibility.h
src/recovery.cpp src/recovery.h
+ src/freespace.cpp src/freespace.h
+ src/firewall.cpp src/firewall.h
+ src/advanced.cpp src/advanced.h
+ src/history.cpp src/history.h
+ src/devices.cpp src/devices.h
src/accesscore.cpp src/accesscore.h
)
@@ -114,8 +123,17 @@ install(TARGETS wildos-settings RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
install(FILES data/org.wildos.settings.desktop DESTINATION ${CMAKE_INSTALL_DATADIR}/applications)
# The helpers are looked up by these exact paths (polkit pins the update
# helper to it), so they do not follow the distribution's libexec layout.
-install(PROGRAMS data/settings-update-policy data/settings-users data/settings-locale data/settings-protection data/settings-network data/settings-cpu-threads data/settings-32bit data/settings-game-overlay data/settings-graphics-driver data/settings-brave-spelling data/settings-fingerprint DESTINATION ${CMAKE_INSTALL_PREFIX}/libexec/wildos)
+install(PROGRAMS data/settings-update-policy data/settings-users data/settings-locale data/settings-protection data/settings-firewall data/settings-firewall-off data/settings-history data/settings-devices data/settings-network data/settings-cpu-threads data/settings-32bit data/settings-game-overlay data/settings-graphics-driver data/settings-brave-spelling data/settings-fingerprint data/settings-free-space data/settings-advanced data/advanced-protection-apply DESTINATION ${CMAKE_INSTALL_PREFIX}/libexec/wildos)
install(FILES data/org.wildos.settings.policy DESTINATION ${CMAKE_INSTALL_DATADIR}/polkit-1/actions)
+# Privacy and security > Advanced protection: the hooks settings-advanced
+# runs for the choices Settings carries out itself, and the services behind
+# them. Other packages add hooks of their own to the same folder.
+install(PROGRAMS data/advanced-protection.d/usb_locked data/advanced-protection.d/radios_idle_off data/advanced-protection.d/dns
+ data/advanced-protection.d/dns_provider data/advanced-protection.d/dns_strict data/advanced-protection.d/vpn_only
+ DESTINATION ${CMAKE_INSTALL_PREFIX}/lib/wildos/advanced-protection.d)
+install(PROGRAMS data/wildos-usb-lock data/wildos-radios-idle data/wildos-advanced-session DESTINATION ${CMAKE_INSTALL_PREFIX}/libexec/wildos)
+install(FILES data/wildos-usb-lock.service data/wildos-radios-idle.service DESTINATION ${CMAKE_INSTALL_PREFIX}/lib/systemd/system)
+install(FILES data/wildos-advanced-session.service DESTINATION ${CMAKE_INSTALL_PREFIX}/lib/systemd/user)
# Opened from About > Credits. Not under /usr/share/doc, which the ISO
# leaves out.
install(FILES data/fluent/LICENSE DESTINATION ${CMAKE_INSTALL_DATADIR}/wildos-settings/licences RENAME fluent-ui-system-icons.txt)
@@ -139,16 +157,37 @@ qt_add_executable(wildos-brave-spelling src/bravespelling/main.cpp)
target_link_libraries(wildos-brave-spelling PRIVATE Qt6::Core KF6::SonnetCore)
install(TARGETS wildos-brave-spelling RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}/libexec/wildos)
install(FILES data/org.wildos.brave-spelling.desktop DESTINATION ${CMAKE_INSTALL_SYSCONFDIR}/xdg/autostart)
+# Turns a Windows pointer, pointer pack or picture into the "Your own"
+# pointer theme, and copies it to the sign-in screen for greeter-access. A
+# process of its own, so an untrusted file can never take Settings down.
+qt_add_executable(pointer-import src/pointerimport/main.cpp src/pointerimport/wincursor.cpp src/pointerimport/xcursor.cpp src/pointerimport/cursor.h)
+target_link_libraries(pointer-import PRIVATE Qt6::Gui Qt6::Svg KF6::Archive)
+install(TARGETS pointer-import RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}/libexec/wildos)
# 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)
+# System > History's records: brought up to date every hour and whenever
+# the page opens (settings-history).
+install(FILES data/wildos-history.socket data/[email protected] data/wildos-history.service data/wildos-history.timer
+ DESTINATION ${CMAKE_INSTALL_PREFIX}/lib/systemd/system)
+# Free up space's Tidy up automatically, switched on per person from
+# Settings with systemctl --user.
+install(FILES data/wildos-free-space.service data/wildos-free-space.timer
+ DESTINATION ${CMAKE_INSTALL_PREFIX}/lib/systemd/user)
+# System > Devices: the kernel's firmware complaints and the drives' own
+# health checks, which only root can read (settings-devices).
+install(FILES data/wildos-devices.socket data/[email protected]
+ DESTINATION ${CMAKE_INSTALL_PREFIX}/lib/systemd/system)
+install(FILES data/fprintd-wildos-history.conf DESTINATION ${CMAKE_INSTALL_PREFIX}/lib/systemd/system/fprintd.service.d
+ RENAME wildos-history.conf)
-# 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)
+# The root half of Advanced network settings and the firewall: encrypted DNS
+# for each new network, the VPN kill switch, loading the firewall again as
+# networks change and keeping the list of what it blocked. 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/networkd/blocked.cpp src/networkd/blocked.h 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)
diff --git a/packages/wildos-settings/data/advanced-protection-apply b/packages/wildos-settings/data/advanced-protection-apply
new file mode 100644
index 0000000..cbd7b88
--- /dev/null
+++ b/packages/wildos-settings/data/advanced-protection-apply
@@ -0,0 +1,37 @@
+#!/bin/sh
+# Puts one Advanced protection choice into effect: runs its hook,
+# /usr/lib/wildos/advanced-protection.d/KEY, as root with the value now in
+# the store as $1. Each part of Wild OS that carries out a choice installs
+# its own hook, so a key with no hook installed has nothing to do as root
+# (what it changes is read where it is used, or applied in each session by
+# a service that watches the store).
+
+set -eu
+
+HOOKS=/usr/lib/wildos/advanced-protection.d
+HELPER=/usr/libexec/wildos/settings-advanced
+
+value_of() {
+ "$HELPER" get | sed -n "s/^$1=//p"
+}
+
+run_hook() {
+ hook=$HOOKS/$1
+ [ -x "$hook" ] || return 0
+ value=$(value_of "$1")
+ [ -n "$value" ] || return 0
+ if ! "$hook" "$value"; then
+ echo "advanced-protection-apply: the $1 hook failed" >&2
+ return 1
+ fi
+}
+
+[ $# -eq 1 ] || { echo "usage: advanced-protection-apply KEY" >&2; exit 2; }
+case "$1" in
+ *[!a-z_]* | '')
+ exit 2
+ ;;
+ *)
+ run_hook "$1"
+ ;;
+esac
diff --git a/packages/wildos-settings/data/advanced-protection.d/dns b/packages/wildos-settings/data/advanced-protection.d/dns
new file mode 100644
index 0000000..98e709d
--- /dev/null
+++ b/packages/wildos-settings/data/advanced-protection.d/dns
@@ -0,0 +1,11 @@
+#!/bin/sh
+# Advanced protection's Encrypted DNS. wildos-network reads dns, dns_strict
+# and dns_provider from the store as it changes and moves each network
+# over; this only makes sure it is running to see it.
+set -eu
+
+case "${1:-}" in
+ on | off | quad9 | mullvad | cloudflare) ;;
+ *) exit 2 ;;
+esac
+systemctl start wildos-network.service >/dev/null 2>&1 || true
diff --git a/packages/wildos-settings/data/advanced-protection.d/dns_provider b/packages/wildos-settings/data/advanced-protection.d/dns_provider
new file mode 100644
index 0000000..98e709d
--- /dev/null
+++ b/packages/wildos-settings/data/advanced-protection.d/dns_provider
@@ -0,0 +1,11 @@
+#!/bin/sh
+# Advanced protection's Encrypted DNS. wildos-network reads dns, dns_strict
+# and dns_provider from the store as it changes and moves each network
+# over; this only makes sure it is running to see it.
+set -eu
+
+case "${1:-}" in
+ on | off | quad9 | mullvad | cloudflare) ;;
+ *) exit 2 ;;
+esac
+systemctl start wildos-network.service >/dev/null 2>&1 || true
diff --git a/packages/wildos-settings/data/advanced-protection.d/dns_strict b/packages/wildos-settings/data/advanced-protection.d/dns_strict
new file mode 100644
index 0000000..98e709d
--- /dev/null
+++ b/packages/wildos-settings/data/advanced-protection.d/dns_strict
@@ -0,0 +1,11 @@
+#!/bin/sh
+# Advanced protection's Encrypted DNS. wildos-network reads dns, dns_strict
+# and dns_provider from the store as it changes and moves each network
+# over; this only makes sure it is running to see it.
+set -eu
+
+case "${1:-}" in
+ on | off | quad9 | mullvad | cloudflare) ;;
+ *) exit 2 ;;
+esac
+systemctl start wildos-network.service >/dev/null 2>&1 || true
diff --git a/packages/wildos-settings/data/advanced-protection.d/radios_idle_off b/packages/wildos-settings/data/advanced-protection.d/radios_idle_off
new file mode 100644
index 0000000..1360fd5
--- /dev/null
+++ b/packages/wildos-settings/data/advanced-protection.d/radios_idle_off
@@ -0,0 +1,10 @@
+#!/bin/sh
+# Advanced protection's "Wi-Fi and Bluetooth switch themselves off":
+# wildos-radios-idle runs only while it is on.
+set -eu
+
+case "${1:-}" in
+ on) systemctl enable --now wildos-radios-idle.service ;;
+ off) systemctl disable --now wildos-radios-idle.service ;;
+ *) exit 2 ;;
+esac
diff --git a/packages/wildos-settings/data/advanced-protection.d/usb_locked b/packages/wildos-settings/data/advanced-protection.d/usb_locked
new file mode 100644
index 0000000..62bc9a9
--- /dev/null
+++ b/packages/wildos-settings/data/advanced-protection.d/usb_locked
@@ -0,0 +1,22 @@
+#!/bin/sh
+# Advanced protection's "Ignore new USB devices while locked" is USBGuard,
+# the same switch as Block new USB devices on Privacy and security. On,
+# new devices wait to be allowed, and while the session is locked
+# wildos-usb-lock holds back even the kinds that normally work at once.
+# Off, USBGuard stops and USB devices work as soon as they are plugged in
+# (usb-release lets go of any it was holding back).
+set -eu
+
+# usbguard-dbus needs usbguard and is enabled on its own, so left enabled
+# it would start USBGuard again at the next start-up.
+case "${1:-}" in
+ on)
+ systemctl enable --now usbguard.service usbguard-dbus.service
+ ;;
+ off)
+ systemctl disable --now usbguard-dbus.service usbguard.service
+ ;;
+ *)
+ exit 2
+ ;;
+esac
diff --git a/packages/wildos-settings/data/advanced-protection.d/vpn_only b/packages/wildos-settings/data/advanced-protection.d/vpn_only
new file mode 100644
index 0000000..3fb426b
--- /dev/null
+++ b/packages/wildos-settings/data/advanced-protection.d/vpn_only
@@ -0,0 +1,21 @@
+#!/bin/sh
+# Advanced protection's "Block everything unless the VPN is on": the VPN
+# kill switch of Advanced network settings, one switch shown in both
+# places. wildos-network watches the flag and does the blocking.
+set -eu
+
+FLAG=/etc/wildos/vpn-kill-switch
+
+case "${1:-}" in
+ on)
+ mkdir -p "$(dirname "$FLAG")"
+ echo "# Written by Wild OS Settings: the VPN kill switch is on." > "$FLAG"
+ ;;
+ off)
+ rm -f "$FLAG"
+ ;;
+ *)
+ exit 2
+ ;;
+esac
+systemctl start wildos-network.service >/dev/null 2>&1 || true
diff --git a/packages/wildos-settings/data/fprintd-wildos-history.conf b/packages/wildos-settings/data/fprintd-wildos-history.conf
new file mode 100644
index 0000000..85b7983
--- /dev/null
+++ b/packages/wildos-settings/data/fprintd-wildos-history.conf
@@ -0,0 +1,6 @@
+# Settings > System > History: fprintd says whether a finger matched only
+# in its debug messages. This turns on fprintd's own domain, not libfprint's
+# far chattier ones, so a sign-in or unlock with a finger, and a finger that
+# wasn't recognised, can be told apart from a password.
+[Service]
+Environment=G_MESSAGES_DEBUG=fprintd
diff --git a/packages/wildos-settings/data/org.wildos.Network.conf b/packages/wildos-settings/data/org.wildos.Network.conf
index 81b31fe..2a9ea0b 100644
--- a/packages/wildos-settings/data/org.wildos.Network.conf
+++ b/packages/wildos-settings/data/org.wildos.Network.conf
@@ -2,13 +2,17 @@
"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. -->
+ NetworkManager, ask which programs wait for connections (Listening,
+ what ss shows root) and empty the firewall's list of what it blocked
+ (ClearBlocked). 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.wildos.Network" send_member="Listening"/>
+ <allow send_destination="org.wildos.Network" send_interface="org.wildos.Network" send_member="ClearBlocked"/>
<allow send_destination="org.wildos.Network" send_interface="org.freedesktop.DBus.Introspectable"/>
</policy>
</busconfig>
diff --git a/packages/wildos-settings/data/org.wildos.settings.policy b/packages/wildos-settings/data/org.wildos.settings.policy
index 178123d..23871e1 100644
--- a/packages/wildos-settings/data/org.wildos.settings.policy
+++ b/packages/wildos-settings/data/org.wildos.settings.policy
@@ -6,9 +6,11 @@
/usr/libexec/wildos, which takes only its own fixed requests:
settings-update-policy (Updates), settings-users and
settings-fingerprint (Accounts),
- settings-locale (Time and language), settings-protection (Privacy
- and security), settings-network (the VPN kill switch) and
- settings-brave-spelling (Typing). settings-cpu-threads and
+ settings-locale (Time and language), settings-protection,
+ settings-firewall and settings-firewall-off (Privacy and security),
+ settings-advanced (Advanced protection), settings-network (the VPN
+ kill switch), settings-brave-spelling (Typing)
+ and settings-free-space (Storage). settings-cpu-threads and
settings-32bit change start-up options. -->
<policyconfig>
<vendor>Wild OS</vendor>
@@ -38,6 +40,30 @@
<annotate key="org.freedesktop.policykit.exec.path">/usr/libexec/wildos/settings-protection</annotate>
</action>
+ <action id="org.wildos.settings.firewall">
+ <description>Change the firewall</description>
+ <message>Change what other computers can reach on this PC?</message>
+ <icon_name>security-high</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-firewall</annotate>
+ </action>
+
+ <action id="org.wildos.settings.firewall-off">
+ <description>Turn the firewall off</description>
+ <message>Turn the firewall off? Other computers will be able to reach any app on this PC that waits for connections.</message>
+ <icon_name>security-low</icon_name>
+ <defaults>
+ <allow_any>no</allow_any>
+ <allow_inactive>no</allow_inactive>
+ <allow_active>auth_admin</allow_active>
+ </defaults>
+ <annotate key="org.freedesktop.policykit.exec.path">/usr/libexec/wildos/settings-firewall-off</annotate>
+ </action>
+
<action id="org.wildos.settings.cpu-threads">
<description>Turn hyper-threading on or off</description>
<message>Change whether this computer uses hyper-threading?</message>
@@ -86,6 +112,18 @@
<annotate key="org.freedesktop.policykit.exec.path">/usr/libexec/wildos/settings-fingerprint</annotate>
</action>
+ <action id="org.wildos.settings.advanced">
+ <description>Change Advanced protection</description>
+ <message>Change Wild OS's advanced protection?</message>
+ <icon_name>security-high</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-advanced</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>
@@ -98,6 +136,68 @@
<annotate key="org.freedesktop.policykit.exec.path">/usr/libexec/wildos/settings-network</annotate>
</action>
+ <!-- No password: Free up space measuring what it could give back. It
+ only reads, and answers with sizes and the paths it measured.
+ pkexec picks this action only for "measure"; nothing else
+ settings-free-space does runs under it. -->
+ <action id="org.wildos.settings.free-space.measure">
+ <description>Measure what Free up space could remove</description>
+ <message>Measure what Wild OS can clear to free up space?</message>
+ <icon_name>drive-harddisk</icon_name>
+ <defaults>
+ <allow_any>no</allow_any>
+ <allow_inactive>no</allow_inactive>
+ <allow_active>yes</allow_active>
+ </defaults>
+ <annotate key="org.freedesktop.policykit.exec.path">/usr/libexec/wildos/settings-free-space</annotate>
+ <annotate key="org.freedesktop.policykit.exec.argv1">measure</annotate>
+ </action>
+
+ <!-- Clearing what was measured: old restore points, update files, old
+ kernels, removed packages' settings and Windows mode's TRIM. -->
+ <action id="org.wildos.settings.free-space.clean">
+ <description>Free up space</description>
+ <message>Free up space by removing what Wild OS no longer needs?</message>
+ <icon_name>drive-harddisk</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-free-space</annotate>
+ <annotate key="org.freedesktop.policykit.exec.argv1">clean</annotate>
+ </action>
+
+ <!-- Choosing what Tidy up automatically may clear takes the password. -->
+ <action id="org.wildos.settings.free-space.set-auto">
+ <description>Change what Free up space clears by itself</description>
+ <message>Let Wild OS free up space by itself when the disk is nearly full?</message>
+ <icon_name>drive-harddisk</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-free-space</annotate>
+ <annotate key="org.freedesktop.policykit.exec.argv1">set-auto</annotate>
+ </action>
+
+ <!-- No password: Tidy up automatically itself. It takes no request; it
+ does nothing unless less than 10% of the disk is free, and clears
+ only what set-auto stored behind the password. -->
+ <action id="org.wildos.settings.free-space.auto">
+ <description>Free up space when the disk is nearly full</description>
+ <message>Free up space now that the disk is nearly full?</message>
+ <icon_name>drive-harddisk</icon_name>
+ <defaults>
+ <allow_any>no</allow_any>
+ <allow_inactive>no</allow_inactive>
+ <allow_active>yes</allow_active>
+ </defaults>
+ <annotate key="org.freedesktop.policykit.exec.path">/usr/libexec/wildos/settings-free-space</annotate>
+ <annotate key="org.freedesktop.policykit.exec.argv1">auto-system</annotate>
+ </action>
+
<!-- No password: it only sets which languages Brave checks spelling in,
from a fixed list, in one file of its own. -->
<action id="org.wildos.settings.brave-spelling">
diff --git a/packages/wildos-settings/data/settings-32bit b/packages/wildos-settings/data/settings-32bit
index 1c1edaf..c36470e 100644
--- a/packages/wildos-settings/data/settings-32bit
+++ b/packages/wildos-settings/data/settings-32bit
@@ -36,6 +36,7 @@ LEVEL_FILE=/etc/wildos/protection-level
RULES_SRC=/usr/share/wildos/steam-devices
RULES_DST=/etc/udev/rules.d
RULES="60-steam-input.rules 60-steam-vr.rules"
+NTSYNC=/etc/modules-load.d/wildos-ntsync.conf
# Controllers plugged in now pick up the change straight away. uinput is
# loaded here because udev only sees it once the module is in; at start-up
@@ -50,6 +51,16 @@ devices() {
rm -f "$RULES_DST/$rule"
fi
done
+ # ntsync (Linux 6.14 and later) does Windows' locking in the kernel,
+ # which Proton uses for smoother frame times in games. Loaded from the
+ # next start-up on and now; left loaded on turning off, as a game may
+ # still have it open. Kernels without it skip it quietly.
+ if [ -e "$CHOICE" ]; then
+ echo ntsync > "$NTSYNC"
+ modprobe -q ntsync 2>/dev/null || true
+ else
+ rm -f "$NTSYNC"
+ fi
if [ -e "$CHOICE" ]; then
modprobe -q uinput 2>/dev/null || true
elif [ -c /dev/uinput ]; then
@@ -85,13 +96,20 @@ EOF
# Written by Wild OS Settings: Steam and 32-bit apps are on, so they get the
# 32-bit vDSO back.
abi.vsyscall32 = 1
+# Some games use split locks, which newer Intel processors otherwise punish
+# with a delay that shows as stutter. The delay only
+# guards against one program slowing others down, not against reading them.
+# The dash skips it on processors without split lock detection.
+-kernel.split_lock_mitigate = 0
EOF
+ sysctl -q -w kernel.split_lock_mitigate=0 2>/dev/null || true
devices
;;
off)
[ -e "$CHOICE" ] || [ -e "$DROPIN" ] || [ -e "$SYSCTL" ] || exit 0
rm -f "$CHOICE" "$DROPIN" "$SYSCTL"
sysctl -q -w abi.vsyscall32=0 2>/dev/null || true
+ sysctl -q -w kernel.split_lock_mitigate=1 2>/dev/null || true
devices
;;
devices)
diff --git a/packages/wildos-settings/data/settings-advanced b/packages/wildos-settings/data/settings-advanced
new file mode 100644
index 0000000..e859469
--- /dev/null
+++ b/packages/wildos-settings/data/settings-advanced
@@ -0,0 +1,219 @@
+#!/bin/sh
+# The store behind Settings > Privacy and security > Advanced protection.
+# Runs as root through pkexec (org.wildos.settings.policy, action
+# org.wildos.settings.advanced), and from settings-protection when the
+# protection level changes. Takes only the requests below.
+#
+# set KEY VALUE The person's own choice. KEY goes on the chosen list,
+# so no protection level changes it again.
+# reset Every key back to what the protection level in use
+# gives it (the board defaults at Standard), and the
+# chosen list emptied.
+# level LEVEL standard, strict or maximum: every key nobody chose by
+# hand takes that level's value.
+# get Every key and its value now, one KEY=VALUE per line.
+# Needs no privileges: the store is world-readable.
+#
+# /etc/wildos/advanced-protection holds KEY=VALUE lines; a missing key
+# means its default. /etc/wildos/advanced-protection.chosen lists the keys
+# set by hand. After a change, advanced-protection-apply runs each changed
+# key's hook in /usr/lib/wildos/advanced-protection.d.
+
+set -eu
+
+STORE=/etc/wildos/advanced-protection
+CHOSEN=/etc/wildos/advanced-protection.chosen
+LEVEL_FILE=/etc/wildos/protection-level
+APPLY=/usr/libexec/wildos/advanced-protection-apply
+LOCK=/run/wildos/advanced-protection.lock
+
+KEYS="usb_locked quiet_lock fingerprint_hours restart_locked_hours restart_locked_force radios_idle_off dns dns_strict dns_provider vpn_only clipboard_forget presenting scrub_files usb_encrypt guest safebox panic_key"
+
+# What each value may be.
+allowed() {
+ case "$1" in
+ fingerprint_hours) echo "0 4 8 12 24 48 72" ;;
+ restart_locked_hours) echo "0 4 8 12 18 24 48" ;;
+ dns_provider) echo "quad9 mullvad cloudflare" ;;
+ *) echo "on off" ;;
+ esac
+}
+
+# The board defaults (Standard), then what Strict and Maximum tighten. A
+# level only ever switches something on or shortens a time; the VPN switch
+# needs a VPN set up, the guest session and panic key change how the PC is
+# used and closing open apps anyway can lose work, so no level touches
+# those. dns_strict has no row of its own: Maximum makes the Encrypted DNS
+# switch's encryption strict, unless the person switched it off.
+level_value() {
+ level=$1
+ key=$2
+ case "$level:$key" in
+ maximum:fingerprint_hours) echo 12; return ;;
+ strict:fingerprint_hours) echo 24; return ;;
+ maximum:restart_locked_hours | strict:restart_locked_hours) echo 18; return ;;
+ maximum:radios_idle_off) echo on; return ;;
+ maximum:dns_strict) echo on; return ;;
+ esac
+ case "$key" in
+ usb_locked | quiet_lock | dns | clipboard_forget | presenting | scrub_files | usb_encrypt | safebox) echo on ;;
+ fingerprint_hours) echo 0 ;;
+ restart_locked_hours) echo 0 ;;
+ dns_provider) echo quad9 ;;
+ *) echo off ;;
+ esac
+}
+
+saved_level() {
+ level=$(cat "$LEVEL_FILE" 2>/dev/null || true)
+ case "$level" in strict | maximum) echo "$level" ;; *) echo standard ;; esac
+}
+
+known_key() {
+ for k in $KEYS; do
+ [ "$k" = "$1" ] && return 0
+ done
+ return 1
+}
+
+valid_value() {
+ for v in $(allowed "$1"); do
+ [ "$v" = "$2" ] && return 0
+ done
+ return 1
+}
+
+stored() {
+ sed -n "s/^$1=//p" "$STORE" 2>/dev/null | tail -n 1
+}
+
+# The value in effect: the stored one if it is still a valid choice, else
+# the board default, as every reader of the store takes it.
+current() {
+ value=$(stored "$1")
+ if [ -n "$value" ] && valid_value "$1" "$value"; then
+ echo "$value"
+ else
+ level_value standard "$1"
+ fi
+}
+
+is_chosen() {
+ grep -qx "$1" "$CHOSEN" 2>/dev/null
+}
+
+# Values for every key, with the given key replaced, written in one go so
+# a reader never sees half a file.
+write_store() {
+ mkdir -p "$(dirname "$STORE")"
+ tmp=$(mktemp "$STORE.XXXXXX")
+ {
+ echo "# Settings > Privacy and security > Advanced protection. Written by"
+ echo "# /usr/libexec/wildos/settings-advanced; change it from Settings."
+ for k in $KEYS; do
+ v=$(eval "printf '%s' \"\${new_$k:-}\"")
+ [ -n "$v" ] || v=$(current "$k")
+ echo "$k=$v"
+ done
+ } > "$tmp"
+ chmod 644 "$tmp"
+ mv -f "$tmp" "$STORE"
+}
+
+write_chosen() {
+ tmp=$(mktemp "$CHOSEN.XXXXXX")
+ cat > "$tmp"
+ chmod 644 "$tmp"
+ mv -f "$tmp" "$CHOSEN"
+}
+
+# Hooks run after the store is written, one key at a time, so each sees
+# the new value; a hook that fails leaves the others to run.
+apply_keys() {
+ for k in "$@"; do
+ "$APPLY" "$k" || true
+ done
+}
+
+# Moves every key that differs from the target values (target_<key>) to
+# them and runs the hooks of those that changed, or of every key with
+# "all", which also puts back what was changed outside the store.
+move_to_targets() {
+ changed=""
+ every=${1:-}
+ for k in $KEYS; do
+ want=$(eval "printf '%s' \"\${target_$k:-}\"")
+ [ -n "$want" ] || continue
+ if [ "$(current "$k")" != "$want" ] || [ "$(stored "$k")" != "$want" ]; then
+ eval "new_$k=\$want"
+ [ "$(current "$k")" = "$want" ] || changed="$changed $k"
+ fi
+ done
+ [ "$every" = all ] && changed=$KEYS
+ write_store
+ # shellcheck disable=SC2086
+ apply_keys $changed
+}
+
+run() {
+ case "${1:-}" in
+ get)
+ for k in $KEYS; do
+ echo "$k=$(current "$k")"
+ done
+ ;;
+ set)
+ [ $# -eq 3 ] || usage
+ known_key "$2" || usage
+ valid_value "$2" "$3" || usage
+ eval "new_$2=\$3"
+ write_store
+ {
+ grep -vx "$2" "$CHOSEN" 2>/dev/null || true
+ echo "$2"
+ } | grep -E '^[a-z_]+$' | sort -u | write_chosen
+ # Run even when nothing changed: setting a key is also how
+ # its hook is asked to put things right again.
+ apply_keys "$2"
+ ;;
+ reset)
+ [ $# -eq 1 ] || usage
+ level=$(saved_level)
+ for k in $KEYS; do
+ eval "target_$k=\$(level_value \"\$level\" \"\$k\")"
+ done
+ : | write_chosen
+ move_to_targets all
+ ;;
+ level)
+ [ $# -eq 2 ] || usage
+ case "$2" in standard | strict | maximum) ;; *) usage ;; esac
+ for k in $KEYS; do
+ is_chosen "$k" && continue
+ eval "target_$k=\$(level_value \"\$2\" \"\$k\")"
+ done
+ move_to_targets
+ ;;
+ *)
+ usage
+ ;;
+ esac
+}
+
+usage() {
+ echo "usage: settings-advanced set KEY VALUE | reset | level standard|strict|maximum | get" >&2
+ exit 2
+}
+
+if [ "${1:-}" = get ]; then
+ run "$@"
+ exit 0
+fi
+
+[ "$(id -u)" -eq 0 ] || { echo "settings-advanced: needs root" >&2; exit 1; }
+
+# Settings and settings-protection can both write at once.
+mkdir -p "$(dirname "$LOCK")"
+exec 9> "$LOCK"
+flock 9
+run "$@"
diff --git a/packages/wildos-settings/data/settings-cpu-threads b/packages/wildos-settings/data/settings-cpu-threads
index e109fd9..2afe6b9 100644
--- a/packages/wildos-settings/data/settings-cpu-threads
+++ b/packages/wildos-settings/data/settings-cpu-threads
@@ -1,54 +1,68 @@
#!/bin/sh
-# Turns hyper-threading on or off from the next start-up: "Use every processor
-# thread" in Settings > System > Power and battery, also offered by Windows
-# mode setup. Runs as root through pkexec (org.wildos.settings.cpu-threads),
-# and from settings-protection, which turns it off at Strict and Maximum.
+# Processor thread and flaw protection choices, applied from the next
+# start-up by /etc/default/grub.d/40_wildos.cfg (wildos-base). Runs as root
+# through pkexec (org.wildos.settings.cpu-threads).
#
-# Wild OS ships with it off. Kicksecure's boot options (nosmt=force, ",nosmt"
-# on several CPU flaw mitigations, and l1tf=full,force) keep the second thread
-# of every core offline, so a program can't read what another one leaves in a
-# core they share. Turning it on keeps every mitigation and only lets those
-# threads run: ",nosmt" and "nosmt=force" go, and l1tf drops to "flush", which
-# still clears the cache each time a virtual machine runs. The kernel decides
-# this at boot, so it takes a restart.
+# on | off "Use every processor thread" in Settings > System > Power
+# and battery, also offered by Windows mode setup. Until it
+# is touched, the kernel runs every thread except on
+# processors it lists as unsafe for sharing a core.
+# protect on|off "Extra processor protection" in Settings > Privacy and
+# security: Kicksecure's full set of processor flaw
+# protections, forced on whether or not the processor
+# needs them, with the second thread of every core off.
#
-# on | off save the choice and rebuild the boot menu
+# Strict and Maximum protection always get the full set; 40_wildos.cfg
+# reads the level itself.
set -eu
-CHOICE=/etc/wildos/cpu-threads
-DROPIN=/etc/default/grub.d/41_wildos_cpu_threads.cfg
+THREADS=/etc/wildos/cpu-threads
+PROTECT=/etc/wildos/cpu-protection
LEVEL_FILE=/etc/wildos/protection-level
-case "${1:-}" in
-on)
- # Strict and Maximum keep every CPU flaw protection on; Settings greys the
- # switch out there, and this refuses in case anything else asks.
+strict_level() {
case "$(cat "$LEVEL_FILE" 2>/dev/null || true)" in
- strict | maximum)
- echo "Strict and Maximum protection keep hyper-threading off." >&2
- exit 3
- ;;
+ strict | maximum) return 0 ;;
esac
+ return 1
+}
+
+case "${1:-}:${2:-}" in
+on:)
+ # Settings greys the switch out at Strict, Maximum and with extra
+ # protection on; this refuses in case anything else asks.
+ if strict_level || [ "$(cat "$PROTECT" 2>/dev/null || true)" = extra ]; then
+ echo "Extra processor protection keeps hyper-threading off." >&2
+ exit 3
+ fi
mkdir -p /etc/wildos
- echo on > "$CHOICE"
- # Sorts after 40_cpu_mitigations.cfg, so it edits what that file added.
- cat > "$DROPIN" <<'EOF'
-# Written by Wild OS Settings: hyper-threading is on. Every CPU flaw mitigation
-# stays; only the options that keep the second thread of each core offline go.
-GRUB_CMDLINE_LINUX="$(printf '%s' "$GRUB_CMDLINE_LINUX" | sed -e 's/ nosmt=force//g' -e 's/,nosmt//g' -e 's/l1tf=full,force/l1tf=flush/g')"
-EOF
+ echo on > "$THREADS"
;;
-off)
- [ -e "$CHOICE" ] || [ -e "$DROPIN" ] || exit 0
- rm -f "$CHOICE" "$DROPIN"
+off:)
+ mkdir -p /etc/wildos
+ echo off > "$THREADS"
+ ;;
+protect:on)
+ mkdir -p /etc/wildos
+ echo extra > "$PROTECT"
+ ;;
+protect:off)
+ if strict_level; then
+ echo "Strict and Maximum protection keep extra processor protection on." >&2
+ exit 3
+ fi
+ rm -f "$PROTECT"
;;
*)
- echo "usage: $0 on|off" >&2
+ echo "usage: $0 on|off|protect on|protect off" >&2
exit 2
;;
esac
+# The old drop-in from before 40_wildos.cfg read the choice itself.
+rm -f /etc/default/grub.d/41_wildos_cpu_threads.cfg
+
if command -v update-grub >/dev/null 2>&1; then
update-grub >/dev/null 2>&1
else
diff --git a/packages/wildos-settings/data/settings-devices b/packages/wildos-settings/data/settings-devices
new file mode 100644
index 0000000..34af904
--- /dev/null
+++ b/packages/wildos-settings/data/settings-devices
@@ -0,0 +1,234 @@
+#!/usr/bin/python3 -I
+"""The two things Settings > System > Devices can't read as you.
+
+Runs as root, once for each connection to wildos-devices.socket, and takes
+no requests: it writes one JSON object and exits.
+
+ firmware kernel lines from this start-up saying a device's firmware
+ could not be loaded, with the device each is about. Drivers
+ often try several versions and settle on one they find, so
+ a line here alone doesn't mean anything is broken; Settings
+ only calls a device short of firmware when it also isn't
+ working.
+ disks each internal drive's own health check, from smartctl:
+ passed or failed, and the few figures that explain it. No
+ serial numbers.
+ unbound each PCI device and USB interface with no driver: the kernel
+ modules that would drive it (modprobe -R) and whether one is
+ switched off, by security-misc on purpose or blacklisted by
+ someone, with the file that does it.
+
+Only reads. The kernel log, the drives' health logs and the kernel's module
+list (/usr/lib/modules is root's alone on Wild OS) all need root, which is
+why Settings doesn't do this itself.
+"""
+
+import fnmatch
+import glob
+import json
+import os
+import re
+import subprocess
+import sys
+
+FIRMWARE_WORDS = re.compile(r"firmware", re.I)
+FAILED_WORDS = re.compile(r"fail|not found|no suitable|missing|unable|error|couldn't|could not|cannot", re.I)
+# "iwlwifi 0000:00:14.3: Direct firmware load for iwlwifi-so-a0-gf-a0-89.ucode failed with error -2"
+FILE_IN_LINE = re.compile(r"(?:load(?:ing)?(?: firmware)?|firmware:? failed to load|request(?:ing)? firmware)\s+(?:for\s+)?[\"']?([\w./+-]+\.(?:bin|ucode|fw|sbin|ri|pnvm|ddc|tlv|hcd|dat|img|zst|xz))", re.I)
+PREFIX = re.compile(r"^(\S+) (\S+): ")
+
+
+def run(args, timeout=10):
+ try:
+ out = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, timeout=timeout)
+ return out.stdout.decode("utf-8", "replace")
+ except (OSError, subprocess.TimeoutExpired):
+ return ""
+
+
+def firmware():
+ found = []
+ seen = set()
+ text = run(["journalctl", "-k", "-b", "-o", "json", "--no-pager", "-q"], timeout=20)
+ for line in text.splitlines():
+ try:
+ entry = json.loads(line)
+ except ValueError:
+ continue
+ message = entry.get("MESSAGE")
+ if not isinstance(message, str) or not FIRMWARE_WORDS.search(message) or not FAILED_WORDS.search(message):
+ continue
+ # The device the line is about: journald's own field when the
+ # driver logged through dev_err(), else the "driver address:"
+ # prefix most drivers print.
+ device = entry.get("_KERNEL_DEVICE", "")
+ if device.startswith("+"):
+ device = device[1:]
+ else:
+ device = ""
+ driver = ""
+ prefix = PREFIX.match(message)
+ if prefix:
+ driver = prefix.group(1)
+ if not device and re.match(r"^[0-9a-f]{4}:[0-9a-f]{2}:[0-9a-f]{2}\.[0-7]$", prefix.group(2)):
+ device = "pci:" + prefix.group(2)
+ elif not device and re.match(r"^\d+-[\d.]+(:\d+\.\d+)?$", prefix.group(2)):
+ device = "usb:" + prefix.group(2)
+ name = FILE_IN_LINE.search(message)
+ key = (device, message)
+ if key in seen:
+ continue
+ seen.add(key)
+ found.append({"device": device, "driver": driver, "file": name.group(1) if name else "", "message": message[:300]})
+ return found[-50:]
+
+
+def internal_disks():
+ disks = []
+ for path in sorted(glob.glob("/sys/block/*")):
+ name = os.path.basename(path)
+ if re.match(r"^(loop|ram|zram|dm-|md|sr|fd|nbd)", name):
+ continue
+ try:
+ with open(os.path.join(path, "removable")) as f:
+ if f.read().strip() == "1":
+ continue
+ except OSError:
+ continue
+ # USB drives are someone's stick or backup disk, not the PC's own.
+ if "/usb" in os.path.realpath(os.path.join(path, "device")):
+ continue
+ disks.append(name)
+ return disks
+
+
+def number(value):
+ return value if isinstance(value, (int, float)) and not isinstance(value, bool) else None
+
+
+def health(name):
+ out = run(["smartctl", "-j", "-H", "-A", "/dev/" + name])
+ try:
+ data = json.loads(out)
+ except ValueError:
+ return {"reported": False}
+ status = data.get("smart_status")
+ if not isinstance(status, dict) or "passed" not in status:
+ return {"reported": False}
+ result = {"reported": True, "passed": bool(status.get("passed"))}
+ temperature = data.get("temperature", {})
+ if isinstance(temperature, dict) and number(temperature.get("current")) is not None:
+ result["temperature"] = temperature["current"]
+ hours = data.get("power_on_time", {})
+ if isinstance(hours, dict) and number(hours.get("hours")) is not None:
+ result["hours"] = hours["hours"]
+ nvme = data.get("nvme_smart_health_information_log")
+ if isinstance(nvme, dict):
+ for key, field in (("percentUsed", "percentage_used"), ("spare", "available_spare"),
+ ("spareThreshold", "available_spare_threshold"), ("mediaErrors", "media_errors"),
+ ("criticalWarning", "critical_warning")):
+ if number(nvme.get(field)) is not None:
+ result[key] = nvme[field]
+ table = data.get("ata_smart_attributes", {}).get("table", [])
+ for attribute in table if isinstance(table, list) else []:
+ raw = attribute.get("raw", {}).get("value") if isinstance(attribute.get("raw"), dict) else None
+ if number(raw) is None:
+ continue
+ if attribute.get("id") == 5:
+ result["reallocated"] = raw
+ elif attribute.get("id") == 197:
+ result["pending"] = raw
+ elif attribute.get("id") == 198:
+ result["uncorrectable"] = raw
+ return result
+
+
+def module_rules():
+ files = {}
+ for folder in ("/usr/lib/modprobe.d", "/lib/modprobe.d", "/run/modprobe.d", "/etc/modprobe.d"):
+ for path in glob.glob(os.path.join(folder, "*.conf")):
+ files[os.path.basename(path)] = path
+ security, blacklisted = {}, {}
+ for path in files.values():
+ try:
+ with open(path, encoding="utf-8", errors="replace") as f:
+ lines = f.read().splitlines()
+ except OSError:
+ continue
+ for line in lines:
+ words = line.split()
+ if len(words) < 2:
+ continue
+ module = words[1].replace("-", "_")
+ if words[0] == "blacklist":
+ (security if "security-misc" in os.path.basename(path) else blacklisted)[module] = path
+ elif words[0] == "install" and len(words) >= 3:
+ if "security-misc" in words[2]:
+ security[module] = path
+ elif words[2].endswith("/false") or words[2].endswith("/true"):
+ blacklisted[module] = path
+ return security, blacklisted
+
+
+def builtin_aliases():
+ # Drivers built into the kernel aren't in modules.alias, so modprobe -R
+ # doesn't name them; their aliases are in modules.builtin.modinfo.
+ aliases = []
+ try:
+ with open("/lib/modules/%s/modules.builtin.modinfo" % os.uname().release, "rb") as f:
+ items = f.read().split(b"\0")
+ except OSError:
+ return aliases
+ for item in items:
+ text = item.decode("utf-8", "replace")
+ if ".alias=" in text:
+ module, pattern = text.split(".alias=", 1)
+ aliases.append((module.replace("-", "_"), pattern))
+ return aliases
+
+
+def unbound():
+ security, blacklisted = module_rules()
+ builtin = None
+ out = {}
+ for path in glob.glob("/sys/bus/pci/devices/*") + glob.glob("/sys/bus/usb/devices/*:*"):
+ if os.path.exists(os.path.join(path, "driver")):
+ continue
+ try:
+ with open(os.path.join(path, "modalias")) as f:
+ alias = f.read().strip()
+ except OSError:
+ continue
+ # Bridges and other plumbing inside the PC; Settings doesn't list them.
+ if alias.startswith("pci:") and re.search(r"bc06sc", alias):
+ continue
+ modules = []
+ for line in run(["modprobe", "-R", alias], timeout=5).splitlines():
+ name = line.strip().replace("-", "_")
+ if name and name not in modules:
+ modules.append(name)
+ if not modules:
+ if builtin is None:
+ builtin = builtin_aliases()
+ for module, pattern in builtin:
+ if module not in modules and fnmatch.fnmatchcase(alias, pattern):
+ modules.append(module)
+ entry = {"modules": modules}
+ for name in modules:
+ if name in blacklisted:
+ entry["blacklisted"] = name
+ entry["file"] = blacklisted[name]
+ elif name in security:
+ entry["security"] = name
+ out[os.path.realpath(path)] = entry
+ return out
+
+
+def main():
+ answer = {"firmware": firmware(), "disks": {name: health(name) for name in internal_disks()}, "unbound": unbound()}
+ sys.stdout.write(json.dumps(answer) + "\n")
+ sys.stdout.flush()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/packages/wildos-settings/data/settings-firewall b/packages/wildos-settings/data/settings-firewall
new file mode 100644
index 0000000..dbea9eb
--- /dev/null
+++ b/packages/wildos-settings/data/settings-firewall
@@ -0,0 +1,623 @@
+#!/usr/bin/python3 -I
+"""Wild OS's firewall, for Settings > Privacy and security > Firewall.
+
+Runs as root: through pkexec (org.wildos.settings.policy) for the choices
+made in Settings, from settings-protection when the protection level
+changes or the computer starts, and from wildos-network whenever the
+networks this computer is on change. Takes only the requests below.
+
+ apply load the rules for what is set now
+ enabled on|off the firewall itself
+ trust UUID home|public how much a network is trusted
+ discovery on|off finding printers, screens and speakers
+ service files|remote|ssh on|off
+ install and start the server, or stop it
+ allow NAME PORT PROTO SCOPE ADDRESS DURATION
+ let other computers reach a port:
+ PROTO tcp|udp|both, SCOPE network|device|
+ anyone (ADDRESS is the device's, or -),
+ DURATION forever|restart|hour
+ rule ID on|off switch a rule you added
+ remove ID remove it
+
+Everything is one nftables table, wildos_protection, built afresh from the
+saved choices (/etc/wildos/firewall.json) each time, so the rules can never
+drift from what Settings shows. Incoming connections are refused unless
+they answer something this computer asked for, or a row in Settings lets
+them in. A public network gets none of those rows, and a network nobody has
+called Home yet gets only network discovery, as before there were rows: a
+server switched on at home must never open on the next cafe's Wi-Fi. Windows mode's bridge is
+always let through: Windows mode's own table (wildos_win) limits it, and a
+drop here would be final whatever that table allows. Nothing outgoing is
+limited.
+
+Files in /etc/wildos/firewall.d/*.rules add rule lines of their own to the
+input chain on every network (dev access lets one PC's SSH in that way).
+"""
+
+import fcntl
+import ipaddress
+import json
+import os
+import re
+import secrets
+import subprocess
+import sys
+import time
+
+CONFIG = "/etc/wildos/firewall.json"
+SESSION = "/run/wildos/firewall-session.json"
+STATE = "/run/wildos/firewall-state.json"
+EXTRA_DIR = "/etc/wildos/firewall.d"
+LEVEL_FILE = "/etc/wildos/protection-level"
+LOCK = "/run/wildos/firewall.lock"
+# security-status runs without root and cannot list the rules, so this is
+# written once nft has taken them.
+MARK = "/run/wildos/firewall"
+TABLE = "wildos_protection"
+# wildos-network listens on this netlink log group for "What the firewall
+# blocked".
+LOG_GROUP = 47
+
+# Each server is installed the first time it is switched on, so no port is
+# ever opened for nothing.
+SERVICES = {
+ "ssh": {
+ "packages": ["openssh-server"],
+ "units": ["ssh.service"],
+ "ports": [("tcp", 22)],
+ "binary": "/usr/sbin/sshd",
+ },
+ # Samba for the shares Files makes (a folder's Properties > Sharing), and
+ # wsdd2 so Windows PCs see this one under Network.
+ "files": {
+ "packages": ["samba", "wsdd2"],
+ "units": ["smbd.service", "wsdd2.service"],
+ "ports": [("tcp", 445), ("tcp", 5357), ("udp", 3702)],
+ "binary": "/usr/sbin/smbd",
+ },
+ # KDE's RDP server runs in the person's own session (Settings starts its
+ # user service), showing their desktop.
+ "remote": {
+ "packages": ["krdp"],
+ "units": [],
+ "ports": [("tcp", 3389)],
+ "binary": "/usr/bin/krdpserver",
+ },
+}
+
+# mDNS, as Wild OS has always let in: how printers, Chromecasts and AirPlay
+# speakers are found and announce themselves. SSDP and WS-Discovery replies
+# come back to a temporary port that no rule here can open, and Windows PCs
+# find this one through File sharing's own wsdd2 port.
+DISCOVERY = (5353,)
+
+DEFAULT = {"enabled": True, "networks": {}, "discovery": True,
+ "services": {"files": False, "remote": False, "ssh": False}, "rules": []}
+
+UUID_RE = re.compile(r"^[0-9a-fA-F-]{8,64}$")
+IFACE_RE = re.compile(r"^[A-Za-z0-9_.:@-]{1,15}$")
+ID_RE = re.compile(r"^[0-9a-f]{8}$")
+
+
+def history(what, **data):
+ """Each change, for Settings > System > History, which reads it back
+ from the journal. Who asked comes from pkexec."""
+ data["what"] = what
+ try:
+ data["by"] = int(os.environ.get("PKEXEC_UID", "0"))
+ except ValueError:
+ data["by"] = 0
+ try:
+ import syslog
+ syslog.openlog("settings-firewall")
+ syslog.syslog(syslog.LOG_INFO, "HISTORY " + json.dumps(data, sort_keys=True))
+ except OSError:
+ pass
+
+
+def network_name(uuid):
+ p = run(["nmcli", "-g", "connection.id", "connection", "show", uuid])
+ return p.stdout.strip() if p and p.returncode == 0 else ""
+
+
+def fail(message, code=1):
+ print(message, file=sys.stderr)
+ sys.exit(code)
+
+
+def read_json(path, default):
+ try:
+ with open(path, encoding="utf-8") as f:
+ data = json.load(f)
+ return data if isinstance(data, type(default)) else default
+ except (OSError, ValueError):
+ return default
+
+
+def write_json(path, data):
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ tmp = path + ".new"
+ with open(tmp, "w", encoding="utf-8") as f:
+ json.dump(data, f, indent=1, sort_keys=True)
+ f.write("\n")
+ os.chmod(tmp, 0o644)
+ os.replace(tmp, path)
+
+
+def load_config():
+ cfg = read_json(CONFIG, {})
+ out = json.loads(json.dumps(DEFAULT))
+ out["enabled"] = cfg.get("enabled", True) is not False
+ out["discovery"] = cfg.get("discovery", True) is not False
+ nets = cfg.get("networks", {})
+ if isinstance(nets, dict):
+ out["networks"] = {k: v for k, v in nets.items() if UUID_RE.match(k) and v in ("home", "public")}
+ services = cfg.get("services", {})
+ if isinstance(services, dict):
+ for name in SERVICES:
+ out["services"][name] = services.get(name) is True
+ out["rules"] = [r for r in cfg.get("rules", []) if valid_rule(r)]
+ return out
+
+
+def load_session():
+ return [r for r in read_json(SESSION, {}).get("rules", []) if valid_rule(r)]
+
+
+def valid_rule(r):
+ if not isinstance(r, dict):
+ return False
+ try:
+ if not ID_RE.match(r["id"]) or not 0 < int(r["port"]) < 65536:
+ return False
+ if r["proto"] not in ("tcp", "udp", "both") or r["scope"] not in ("network", "device", "anyone"):
+ return False
+ if r["scope"] == "device":
+ ipaddress.ip_address(r["address"])
+ return isinstance(r.get("name", ""), str)
+ except (KeyError, TypeError, ValueError):
+ return False
+
+
+def saved_level():
+ try:
+ with open(LEVEL_FILE, encoding="utf-8") as f:
+ level = f.read().strip()
+ except OSError:
+ level = ""
+ return level if level in ("strict", "maximum") else "standard"
+
+
+def run(args, check=False, capture=True):
+ env = dict(os.environ, LC_ALL="C")
+ try:
+ p = subprocess.run(args, capture_output=capture, text=True, env=env, timeout=60)
+ except (OSError, subprocess.TimeoutExpired) as e:
+ if check:
+ fail(str(e))
+ return None
+ if check and p.returncode != 0:
+ fail((p.stderr or p.stdout or "").strip() or "%s failed" % args[0])
+ return p
+
+
+def nmcli_fields(line):
+ # nmcli -t escapes ':' and '\' in values with a backslash.
+ fields, cur, esc = [], "", False
+ for ch in line:
+ if esc:
+ cur += ch
+ esc = False
+ elif ch == "\\":
+ esc = True
+ elif ch == ":":
+ fields.append(cur)
+ cur = ""
+ else:
+ cur += ch
+ fields.append(cur)
+ return fields
+
+
+def active_networks():
+ """The Wi-Fi, Ethernet and other links NetworkManager has up, each with
+ the address ranges of the network it is on and its routers. VPN tunnels
+ are left out: nobody on the far side of one is "on this network"."""
+ # At start-up the firewall goes up before NetworkManager (or even D-Bus)
+ # runs, and nmcli would wait for them; wildos-network applies the rules
+ # again once a network is up.
+ nm = subprocess.run(["systemctl", "is-active", "--quiet", "NetworkManager.service"], capture_output=True)
+ if nm.returncode != 0 or not os.path.exists("/run/dbus/system_bus_socket"):
+ return []
+ p = run(["nmcli", "-t", "-f", "UUID,NAME,TYPE,DEVICE,STATE", "connection", "show", "--active"])
+ if p is None or p.returncode != 0:
+ return []
+ skip = {"loopback", "vpn", "wireguard", "bridge", "tun", "dummy", "veth"}
+ nets = []
+ for line in p.stdout.splitlines():
+ f = nmcli_fields(line)
+ if len(f) < 5 or f[2] in skip or not f[3] or f[4] != "activated":
+ continue
+ uuid, name, kind, dev = f[0], f[1], f[2], f[3]
+ if not UUID_RE.match(uuid) or not IFACE_RE.match(dev) or dev.startswith(("virbr", "wildos-win", "tun", "tap", "docker")):
+ continue
+ v4, v6 = [], []
+ a = run(["ip", "-j", "addr", "show", "dev", dev])
+ try:
+ info = json.loads(a.stdout) if a and a.returncode == 0 else []
+ except ValueError:
+ info = []
+ for iface in info:
+ for addr in iface.get("addr_info", []):
+ try:
+ net = ipaddress.ip_interface("%s/%s" % (addr["local"], addr["prefixlen"])).network
+ except (KeyError, ValueError):
+ continue
+ if net.version == 4:
+ v4.append(str(net))
+ elif net.is_link_local:
+ v6.append("fe80::/10")
+ elif net.subnet_of(ipaddress.ip_network("fc00::/7")):
+ v6.append(str(net))
+ gateways = []
+ for fam in ("-4", "-6"):
+ r = run(["ip", fam, "-j", "route", "show", "default", "dev", dev])
+ try:
+ for route in json.loads(r.stdout) if r and r.returncode == 0 else []:
+ if route.get("gateway"):
+ gateways.append(route["gateway"])
+ except ValueError:
+ pass
+ # A hotspot (NetworkManager's "shared" method) hands out addresses
+ # and answers name lookups itself, through dnsmasq.
+ m = run(["nmcli", "-g", "ipv4.method", "connection", "show", uuid])
+ shared = m is not None and m.returncode == 0 and m.stdout.strip() == "shared"
+ nets.append({"uuid": uuid, "name": name, "type": kind, "device": dev, "shared": shared,
+ "v4": collapse(v4), "v6": collapse(v6), "gateways": gateways})
+ return nets
+
+
+def collapse(cidrs):
+ # nft refuses overlapping ranges in one set.
+ return [str(n) for n in ipaddress.collapse_addresses(ipaddress.ip_network(c) for c in set(cidrs))]
+
+
+def extra_lines():
+ lines = []
+ try:
+ names = sorted(n for n in os.listdir(EXTRA_DIR) if n.endswith(".rules"))
+ except OSError:
+ return lines
+ for name in names:
+ try:
+ with open(os.path.join(EXTRA_DIR, name), encoding="utf-8") as f:
+ for line in f:
+ line = line.split("#", 1)[0].strip()
+ if line and not any(c in line for c in "{};"):
+ lines.append(line)
+ except OSError:
+ pass
+ return lines
+
+
+def l4(proto, port):
+ if proto == "both":
+ return "meta l4proto { tcp, udp } th dport %d" % port
+ return "%s dport %d" % (proto, port)
+
+
+def accept_lines(dev, net, proto, port, scope, address=None):
+ """The rules that let one port in on one interface, from the devices
+ the scope names."""
+ match = l4(proto, int(port))
+ lead = 'iifname "%s" ' % dev
+ if scope == "anyone":
+ return [lead + match + " accept"]
+ if scope == "device":
+ a = ipaddress.ip_address(address)
+ return [lead + ("ip" if a.version == 4 else "ip6") + " saddr " + str(a) + " " + match + " accept"]
+ out = []
+ if net["v4"]:
+ out.append(lead + "ip saddr { %s } %s accept" % (", ".join(net["v4"]), match))
+ if net["v6"]:
+ out.append(lead + "ip6 saddr { %s } %s accept" % (", ".join(net["v6"]), match))
+ return out
+
+
+def ruleset(cfg, level, nets, session, extras):
+ body = [
+ "ct state established,related accept",
+ "ct state invalid drop",
+ "iif lo accept",
+ 'iifname { "virbr-wildos", "wildos-win*" } accept',
+ "meta l4proto ipv6-icmp accept",
+ "icmp type { echo-reply, destination-unreachable, time-exceeded, parameter-problem } accept",
+ "udp sport 67 udp dport 68 accept",
+ "udp sport 547 udp dport 546 accept",
+ ]
+ body += extras
+ now = time.time()
+ for net in nets:
+ dev = net["device"]
+ # The devices on this PC's own hotspot get their addresses and name
+ # lookups from it, whatever else that network is allowed.
+ if net.get("shared"):
+ body.append('iifname "%s" udp dport { 53, 67 } accept' % dev)
+ body.append('iifname "%s" tcp dport 53 accept' % dev)
+ trust = cfg["networks"].get(net["uuid"])
+ if trust == "public":
+ continue
+ if cfg["discovery"] and level != "maximum":
+ body.append('iifname "%s" udp dport { %s } accept' % (dev, ", ".join(str(p) for p in DISCOVERY)))
+ if trust != "home":
+ continue
+ for name, svc in SERVICES.items():
+ if cfg["services"][name] and os.path.exists(svc["binary"]):
+ for proto, port in svc["ports"]:
+ body += accept_lines(dev, net, proto, port, "network")
+ for r in cfg["rules"] + session:
+ if r.get("on", True) is False or (r.get("until") or 0) and r["until"] <= now:
+ continue
+ body += accept_lines(dev, net, r["proto"], r["port"], r["scope"], r.get("address"))
+ # Only new connections sent to this computer itself are logged, not
+ # what every device broadcasts to the whole network, and never more
+ # than a few a minute.
+ body.append("meta pkttype host ct state new meta l4proto { tcp, udp } "
+ 'limit rate 12/minute burst 20 packets log prefix "wildos-blocked" group %d' % LOG_GROUP)
+ return ("table inet {t}\ndelete table inet {t}\ntable inet {t} {{\n"
+ " chain input {{\n"
+ " type filter hook input priority filter; policy drop;\n"
+ "{body}"
+ " }}\n}}\n").format(t=TABLE, body="".join(" %s\n" % line for line in body))
+
+
+def nft_load(text):
+ p = subprocess.run(["nft", "-f", "-"], input=text, capture_output=True, text=True)
+ return p.returncode == 0, p.stderr.strip()
+
+
+def apply():
+ cfg = load_config()
+ level = saved_level()
+ now = time.time()
+
+ # Rules that ran out are gone for good.
+ keep = [r for r in cfg["rules"] if not (r.get("until") or 0) or r["until"] > now]
+ if len(keep) != len(cfg["rules"]):
+ cfg["rules"] = keep
+ write_json(CONFIG, cfg)
+
+ nets = active_networks() if cfg["enabled"] else []
+ session = load_session()
+ try:
+ os.remove(MARK)
+ except OSError:
+ pass
+
+ if not cfg["enabled"]:
+ subprocess.run(["nft", "delete", "table", "inet", TABLE], capture_output=True)
+ loaded = True
+ elif subprocess.run(["sh", "-c", "command -v nft"], capture_output=True).returncode != 0:
+ loaded = False
+ else:
+ extras = extra_lines()
+ loaded, err = nft_load(ruleset(cfg, level, nets, session, extras))
+ if not loaded and extras:
+ # A broken line in firewall.d must never leave the computer open.
+ print("firewall.d ignored: " + err, file=sys.stderr)
+ loaded, err = nft_load(ruleset(cfg, level, nets, session, []))
+ if not loaded:
+ print(err, file=sys.stderr)
+ else:
+ os.makedirs(os.path.dirname(MARK), exist_ok=True)
+ with open(MARK, "w", encoding="utf-8") as f:
+ f.write(level + "\n")
+ os.chmod(MARK, 0o644)
+
+ expiries = [r["until"] for r in cfg["rules"] if (r.get("until") or 0) > now]
+ write_json(STATE, {
+ "applied": int(now),
+ "enabled": cfg["enabled"],
+ "loaded": bool(loaded and cfg["enabled"]),
+ "level": level,
+ "next_expiry": min(expiries) if expiries else 0,
+ "networks": [dict(n, trust=cfg["networks"].get(n["uuid"], "")) for n in nets],
+ })
+ return loaded
+
+
+def session_user():
+ uid = os.environ.get("PKEXEC_UID", "")
+ if not uid.isdigit():
+ return None
+ try:
+ import pwd
+ return pwd.getpwuid(int(uid)).pw_name
+ except (KeyError, ImportError):
+ return None
+
+
+def apt_install(packages):
+ """Installs with apt, reporting progress as "progress N" lines, and the
+ reason in plain words if it cannot."""
+ env = dict(os.environ, LC_ALL="C", DEBIAN_FRONTEND="noninteractive")
+ lists = "/var/lib/apt/lists"
+ has_lists = any(n.endswith("_Packages") for n in os.listdir(lists)) if os.path.isdir(lists) else False
+
+ def update():
+ print("step Getting the list of packages", flush=True)
+ subprocess.run(["apt-get", "update", "-q"], env=env, capture_output=True)
+
+ if not has_lists:
+ update()
+ for attempt in (1, 2):
+ print("step Downloading", flush=True)
+ p = subprocess.Popen(["apt-get", "install", "-y", "-q", "--no-install-recommends",
+ "-o", "APT::Status-Fd=1",
+ "-o", "Dpkg::Options::=--force-confdef", "-o", "Dpkg::Options::=--force-confold"]
+ + packages, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
+ errors = []
+ installing = False
+ for line in p.stdout:
+ line = line.strip()
+ if line.startswith(("E:", "Err:")):
+ errors.append(line)
+ continue
+ parts = line.split(":", 3)
+ if len(parts) >= 3 and parts[0] in ("dlstatus", "pmstatus"):
+ try:
+ pct = float(parts[2])
+ except ValueError:
+ continue
+ # Downloading is the first half of the bar, installing the second.
+ if parts[0] == "pmstatus" and not installing:
+ installing = True
+ print("step Installing", flush=True)
+ print("progress %d" % int(pct / 2 + (50 if parts[0] == "pmstatus" else 0)), flush=True)
+ if p.wait() == 0:
+ return
+ if attempt == 1 and any("Unable to locate" in e or "404" in e or "Failed to fetch" in e for e in errors):
+ update()
+ continue
+ reason = errors[-1].split(":", 1)[1].strip() if errors else "apt-get could not install " + " ".join(packages)
+ if "Could not resolve" in reason or "Failed to fetch" in reason or "Temporary failure" in reason:
+ fail("It could not be downloaded. Check that this computer is online and try again.")
+ if "Could not get lock" in reason:
+ fail("Another install or update is running. Try again when it has finished.")
+ fail(reason)
+
+
+def systemctl(*args):
+ p = run(["systemctl"] + list(args))
+ return p is not None and p.returncode == 0
+
+
+def set_service(name, on):
+ svc = SERVICES[name]
+ cfg = load_config()
+ if on:
+ if not os.path.exists(svc["binary"]):
+ apt_install(svc["packages"])
+ if not os.path.exists(svc["binary"]):
+ fail("It was installed but its server is missing. Nothing was changed.")
+ if name == "files":
+ user = session_user()
+ # Files shares folders through Samba's user shares, which need
+ # this group; it applies from the next sign-in.
+ if user:
+ run(["gpasswd", "-a", user, "sambashare"])
+ for unit in svc["units"]:
+ if not systemctl("enable", "--now", unit):
+ p = run(["systemctl", "status", "--no-pager", "-n", "3", unit])
+ fail("%s did not start. %s" % (unit, (p.stdout.strip().splitlines() or [""])[-1] if p else ""))
+ cfg["services"][name] = True
+ write_json(CONFIG, cfg)
+ apply()
+ else:
+ cfg["services"][name] = False
+ write_json(CONFIG, cfg)
+ apply()
+ for unit in svc["units"]:
+ systemctl("disable", "--now", unit)
+
+
+def parse_allow(args):
+ if len(args) != 6:
+ fail("usage: settings-firewall allow NAME PORT PROTO SCOPE ADDRESS DURATION", 2)
+ name, port, proto, scope, address, duration = args
+ name = " ".join(name.split())[:60]
+ if not name or not name.isprintable():
+ fail("The name can't be used.", 2)
+ if not port.isdigit() or not 0 < int(port) < 65536:
+ fail("A port is a number from 1 to 65535.", 2)
+ if proto not in ("tcp", "udp", "both") or scope not in ("network", "device", "anyone"):
+ fail("usage: settings-firewall allow NAME PORT tcp|udp|both network|device|anyone ADDRESS forever|restart|hour", 2)
+ if duration not in ("forever", "restart", "hour"):
+ fail("usage: settings-firewall allow ... forever|restart|hour", 2)
+ rule = {"id": secrets.token_hex(4), "name": name, "port": int(port), "proto": proto, "scope": scope,
+ "on": True, "added": int(time.time())}
+ if scope == "device":
+ try:
+ a = ipaddress.ip_address(address)
+ except ValueError:
+ fail("That isn't an address. It looks like 192.168.1.24.", 2)
+ if a.is_loopback or a.is_multicast or a.is_unspecified:
+ fail("That address can't be another device.", 2)
+ rule["address"] = str(a)
+ if duration == "hour":
+ rule["until"] = int(time.time()) + 3600
+ return rule, duration == "restart"
+
+
+def main():
+ args = sys.argv[1:]
+ if not args:
+ fail(__doc__.strip(), 2)
+ os.makedirs("/run/wildos", exist_ok=True)
+ lock = open(LOCK, "w")
+ fcntl.flock(lock, fcntl.LOCK_EX)
+
+ cmd = args[0]
+ if cmd in ("apply", "boot") and len(args) == 1:
+ sys.exit(0 if apply() else 1)
+ if cmd == "enabled" and len(args) == 2 and args[1] in ("on", "off"):
+ cfg = load_config()
+ cfg["enabled"] = args[1] == "on"
+ write_json(CONFIG, cfg)
+ history("firewall", on=cfg["enabled"])
+ sys.exit(0 if apply() else 1)
+ if cmd == "trust" and len(args) == 3 and UUID_RE.match(args[1]) and args[2] in ("home", "public"):
+ cfg = load_config()
+ cfg["networks"][args[1]] = args[2]
+ write_json(CONFIG, cfg)
+ history("trust", trust=args[2], network=network_name(args[1]))
+ sys.exit(0 if apply() else 1)
+ if cmd == "discovery" and len(args) == 2 and args[1] in ("on", "off"):
+ cfg = load_config()
+ cfg["discovery"] = args[1] == "on"
+ write_json(CONFIG, cfg)
+ history("discovery", on=cfg["discovery"])
+ sys.exit(0 if apply() else 1)
+ if cmd == "service" and len(args) == 3 and args[1] in SERVICES and args[2] in ("on", "off"):
+ set_service(args[1], args[2] == "on")
+ history("service", service=args[1], on=args[2] == "on")
+ sys.exit(0)
+ if cmd == "allow":
+ rule, session_only = parse_allow(args[1:])
+ if session_only:
+ data = {"rules": load_session() + [rule]}
+ write_json(SESSION, data)
+ else:
+ cfg = load_config()
+ cfg["rules"].append(rule)
+ write_json(CONFIG, cfg)
+ history("allow", name=rule.get("name", ""), port=rule["port"], proto=rule["proto"], scope=rule["scope"],
+ address=rule.get("address", ""), until=rule.get("until"), session=session_only)
+ sys.exit(0 if apply() else 1)
+ if cmd in ("rule", "remove") and len(args) == (3 if cmd == "rule" else 2) and ID_RE.match(args[1]):
+ if cmd == "rule" and args[2] not in ("on", "off"):
+ fail("usage: settings-firewall rule ID on|off", 2)
+ cfg = load_config()
+ session = load_session()
+ found = None
+ for rules in (cfg["rules"], session):
+ for r in list(rules):
+ if r["id"] == args[1]:
+ found = r
+ if cmd == "remove":
+ rules.remove(r)
+ else:
+ r["on"] = args[2] == "on"
+ if not found:
+ fail("That rule has already gone.")
+ write_json(CONFIG, cfg)
+ write_json(SESSION, {"rules": session})
+ history("rule", name=found.get("name", ""), port=found["port"], proto=found["proto"],
+ change="removed" if cmd == "remove" else args[2])
+ sys.exit(0 if apply() else 1)
+ fail(__doc__.strip(), 2)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/packages/wildos-settings/data/settings-firewall-off b/packages/wildos-settings/data/settings-firewall-off
new file mode 100644
index 0000000..2edcebc
--- /dev/null
+++ b/packages/wildos-settings/data/settings-firewall-off
@@ -0,0 +1,5 @@
+#!/bin/sh
+# Turns the firewall off. A path of its own so polkit can ask for the
+# password every time (org.wildos.settings.firewall-off), where every other
+# firewall change keeps the answer for a few minutes.
+exec /usr/libexec/wildos/settings-firewall enabled off
diff --git a/packages/wildos-settings/data/settings-free-space b/packages/wildos-settings/data/settings-free-space
new file mode 100644
index 0000000..df47f0a
--- /dev/null
+++ b/packages/wildos-settings/data/settings-free-space
@@ -0,0 +1,1368 @@
+#!/usr/bin/python3 -I
+"""Settings > System > Storage > Free up space: measures what can be
+cleared, and clears it.
+
+Half of it is the person's own files and half is the system's, so there
+are two halves:
+
+ As the person, never as root (nothing in a home folder is ever touched
+ with root's rights):
+ measure-home the Recycle Bins on internal drives, app
+ caches, leftovers of removed apps in the
+ home folder, large files in Downloads
+ run ITEM... [--download PATH]...
+ clear the ticked items; the system ones go
+ through pkexec (clean), then the home ones
+ run --auto Tidy up automatically: only when less than 10%
+ of the disk is free, only the items ticked
+ when it was turned on, never Downloads; says
+ what it removed in a notification
+
+ As root, through pkexec, each request under its own polkit action:
+ measure (no password) old restore points, update
+ files, leftovers of removed packages,
+ Windows mode's disk
+ measure open-files (no password) which files under the asking
+ person's cache folders their programs have
+ open, so App caches leaves them
+ clean ITEM... (admin password) clear those of them
+ auto-system (no password) the same for Tidy up
+ automatically: does nothing unless less than
+ 10% of the disk is free, and clears only what
+ set-auto stored for the person asking
+ set-auto [ITEM...] (admin password) store which system items
+ Tidy up automatically may clear for the
+ person asking; none turns it off
+
+ITEMs are the page's: bin, restorePoints, updates, caches, leftovers,
+winmode, downloads. Clearing never takes a list of paths from the caller
+(Review's downloads are only checked against the list measured here): it
+measures again and removes exactly what measuring would show.
+
+Sizes are what the disk would really get back, not file lengths: blocks
+in use, each hard-linked file counted once, and on Btrfs only what no
+other snapshot shares. What was cleared is noted in the journal as
+"FREED {json}", which Settings > System > History shows.
+"""
+
+import fcntl
+import glob
+import json
+import os
+import pwd
+import re
+import shutil
+import sqlite3
+import stat
+import subprocess
+import sys
+import syslog
+import time
+import urllib.parse
+
+DAY = 24 * 3600
+
+# Restore points: the newest this many always stay.
+KEEP_POINTS = 3
+RP_TOOL = "/usr/libexec/wildos/restore-points"
+BTRFS_STORE = "/.snapshots"
+EXT4_STORE = "/var/lib/wildos/restore-points"
+# A go-back's undo point is how the person gets back again; restore-points
+# itself protects it for an hour (UNDO_GRACE), so this does too.
+UNDO_GRACE = 60 * 60
+
+APT_ARCHIVES = "/var/cache/apt/archives"
+PACKAGEKIT_CACHE = "/var/cache/PackageKit"
+
+WINMODE_CONFIG = "/etc/wildos/winmode.json"
+WINMODE_DISK = "/var/lib/wildos/winmode/windows.qcow2"
+WINMODE_DOMAIN = "wildos-windows"
+# Windows' own retrim can take a while on a large, long-unused disk.
+TRIM_TIMEOUT = 900
+
+HELPER = "/usr/libexec/wildos/settings-free-space"
+SYSTEM_CONFIG = "/etc/wildos/free-space.json"
+ROOT_LOCK = "/run/lock/wildos-free-space.lock"
+# Tidy up automatically starts below this share of the disk free.
+LOW_SPACE = 0.10
+
+PAGE_ITEMS = ("bin", "restorePoints", "updates", "caches", "leftovers", "winmode", "downloads")
+SYSTEM_ITEMS = ("restorePoints", "updates", "leftovers", "winmode")
+HOME_ITEMS = ("bin", "caches", "leftovers", "downloads")
+# Downloads are only ever cleared from Review, never automatically.
+AUTO_ITEMS = ("bin", "restorePoints", "updates", "caches", "leftovers", "winmode")
+LABELS = {"bin": "Recycle Bin", "restorePoints": "old restore points", "updates": "update files",
+ "caches": "app caches", "leftovers": "leftovers from removed apps",
+ "winmode": "unused space inside Windows mode", "downloads": "large files in Downloads"}
+
+DOWNLOADS_MIN = 100 * 1024 * 1024
+DOWNLOADS_DAYS = 90
+
+# Wild OS's own apps (Recommends of wildos-desktop, so each can be
+# uninstalled) and what each keeps in the home folder, from where their
+# code puts it. Only an app's own settings, index and state: what people
+# make with them lives in Notes, Recordings, Music, Videos, Pictures and
+# Documents, which are never on this list. Only folders whose package is
+# no longer installed count. The shared wildosrc (clock and theme choices)
+# belongs to the whole desktop and is never on it either. Write and Tables
+# keep their documents' settings in LibreOffice's profile, which belongs to
+# LibreOffice, so that stays out.
+WILDOS_APP_FOLDERS = {
+ "wildos-mail": [".config/wildos-mail", ".local/share/wildos-mail", ".cache/wildos-mail"],
+ "wildos-music": [".config/wildos/music.conf", ".local/share/wildos-music"],
+ "wildos-notes": [".config/wildos/notes.conf", ".local/share/wildos-notes"],
+ "wildos-videos": [".config/wildos/videos.conf", ".local/share/wildos-videos", ".cache/wildos-videos"],
+ "wildos-voice": [".config/wildos/voice.conf", ".local/share/wildos-voice"],
+ "wildos-archive": [".config/wildos/archive.conf", ".cache/wildos/archive"],
+ "wildos-backup": [".config/wildos/backup.conf", ".local/state/wildos-backup", ".cache/wildos-backup",
+ ".config/systemd/user/wildos-backup.timer.d"],
+ "wildos-pdf": [".config/wildos-pdf.conf", ".local/share/wildos-pdf", ".cache/wildos-pdf"],
+ "wildos-remote": [".config/wildos-remote", ".local/share/wildos-remote", ".cache/wildos-remote"],
+ "wildos-capture": [".config/wildosscreenshotrc"],
+ "wildos-terminal": [".config/wildosterminalrc"],
+ "wildos-office": [".local/share/wildos-office"],
+}
+
+# Caches that look like caches but a running session needs whole: KDE's
+# list of installed apps and their file types. Deleting it mid-session
+# leaves Start and Open with empty until it is rebuilt.
+CACHE_KEEP = [re.compile(r"^ksycoca6"), re.compile(r"^ksycoca5")]
+
+
+# ---------------------------------------------------------------- sizes
+
+def used(st):
+ return st.st_blocks * 512
+
+
+class Walker:
+ """Disk use of trees, each inode counted once across every call, so
+ hard-linked restore points and Flatpak deployments are not counted
+ twice. Never follows symbolic links or crosses into other
+ filesystems."""
+
+ def __init__(self):
+ self.seen = set()
+
+ def size(self, path, files=None):
+ total = 0
+ try:
+ top = os.lstat(path)
+ except OSError:
+ return 0
+ stack = [(path, top)]
+ dev = top.st_dev
+ while stack:
+ p, st = stack.pop()
+ key = (st.st_dev, st.st_ino)
+ if key in self.seen:
+ continue
+ self.seen.add(key)
+ total += used(st)
+ if stat.S_ISDIR(st.st_mode):
+ try:
+ with os.scandir(p) as it:
+ for e in it:
+ try:
+ cst = e.stat(follow_symlinks=False)
+ except OSError:
+ continue
+ if cst.st_dev != dev:
+ continue
+ stack.append((e.path, cst))
+ except OSError:
+ pass
+ elif files is not None and stat.S_ISREG(st.st_mode):
+ files.append(p)
+ return total
+
+
+def tree_size(path):
+ return Walker().size(path)
+
+
+def content_size(w, path):
+ """What clearing a folder's contents gives back: the folder itself
+ stays, so its own block is not counted."""
+ try:
+ if not stat.S_ISDIR(os.lstat(path).st_mode):
+ return w.size(path)
+ with os.scandir(path) as it:
+ return sum(w.size(e.path) for e in it)
+ except OSError:
+ return 0
+
+
+def run(args, timeout=60, ok=(0,)):
+ try:
+ r = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, timeout=timeout,
+ env={"PATH": "/usr/sbin:/usr/bin:/sbin:/bin", "LC_ALL": "C.UTF-8"})
+ except (OSError, subprocess.TimeoutExpired):
+ return None
+ if r.returncode not in ok:
+ return None
+ return r.stdout.decode("utf-8", "replace")
+
+
+def item(targets, kept=None, **extra):
+ d = {"bytes": sum(t.get("bytes", 0) for t in targets), "count": len(targets),
+ "targets": targets, "kept": kept or []}
+ d.update(extra)
+ return d
+
+
+# ---------------------------------------------------------------- packages
+
+def installed_packages():
+ """{"name:arch": (version, status)} and {"name": [arch...]}."""
+ out = run(["dpkg-query", "-W", "-f", "${Package}\t${Architecture}\t${Version}\t${db:Status-Abbrev}\n"]) or ""
+ pkgs = {}
+ for line in out.splitlines():
+ f = line.split("\t")
+ if len(f) == 4:
+ pkgs[f[0] + ":" + f[1]] = (f[2], f[3].strip())
+ return pkgs
+
+
+def present(entry):
+ """Installed in any state short of removed: dpkg's "i" plus unpacked,
+ half-configured and waiting on triggers, which an interrupted update
+ leaves behind."""
+ return bool(entry) and len(entry[1]) > 1 and entry[1][1] in "iUFWt"
+
+
+def is_installed(pkgs, name):
+ return any(k.split(":")[0] == name and present(v) for k, v in pkgs.items())
+
+
+def version_le(a, b):
+ return subprocess.run(["dpkg", "--compare-versions", a, "le", b],
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0
+
+
+# ---------------------------------------------------------------- restore points
+
+def restore_points():
+ btrfs = os.path.exists(os.path.join(BTRFS_STORE, "index.json"))
+ store = BTRFS_STORE if btrfs else EXT4_STORE
+ if not os.path.isdir(store):
+ return item([], available=False)
+ pts = []
+ for n in os.listdir(store):
+ if not n.isdigit():
+ continue
+ data = os.path.join(store, n, "snapshot" if btrfs else "tree")
+ try:
+ with open(os.path.join(store, n, "info.json")) as f:
+ info = json.load(f)
+ except (OSError, ValueError):
+ continue
+ if os.path.exists(data):
+ pts.append(info)
+ # The same order restore-points keeps them in: oldest first.
+ pts.sort(key=lambda p: (p.get("time", 0), p["id"]))
+ pending = None
+ try:
+ with open(os.path.join(store, "pending")) as f:
+ pending = json.load(f).get("id")
+ except (OSError, ValueError):
+ pass
+
+ newest = pts[-KEEP_POINTS:]
+ kept, victims = [], []
+ for p in pts:
+ if p in newest:
+ kept.append((p, "one of the newest %d" % KEEP_POINTS))
+ elif p["id"] == pending:
+ kept.append((p, "going back to it is waiting for a restart"))
+ elif p.get("kind") == "undo" and time.time() - p.get("time", 0) < UNDO_GRACE:
+ kept.append((p, "it undoes a go-back made less than an hour ago"))
+ else:
+ victims.append(p)
+
+ def describe(p, path, size, why=None):
+ d = {"id": p["id"], "path": path, "label": p.get("label", ""), "time": p.get("time", 0),
+ "kind": p.get("kind", ""), "kernels": p.get("kernels") or [], "bytes": size}
+ if why:
+ d["why"] = why
+ return d
+
+ targets = []
+ if btrfs:
+ # btrfs filesystem du: "Exclusive" is what deleting that one
+ # snapshot frees. Data shared only among the points being deleted
+ # isn't in anyone's Exclusive, so the total may come out a little
+ # low, never high.
+ paths = [os.path.join(store, str(p["id"]), "snapshot") for p in victims]
+ excl = {}
+ out = run(["btrfs", "filesystem", "du", "-s", "--raw"] + paths, timeout=600) if paths else ""
+ for line in (out or "").splitlines()[1:]:
+ f = line.split(None, 3)
+ if len(f) == 4 and f[0].isdigit():
+ excl[f[3]] = int(f[1])
+ w = Walker()
+ for p, _ in kept:
+ w.size(os.path.join(store, str(p["id"]), "boot"))
+ for p in victims:
+ pdir = os.path.join(store, str(p["id"]))
+ size = excl.get(os.path.join(pdir, "snapshot"), 0) + w.size(os.path.join(pdir, "boot"))
+ targets.append(describe(p, pdir, size))
+ else:
+ # The points are rsync copies hard-linked to each other: what the
+ # kept points also hold is not freed, so they are walked first.
+ w = Walker()
+ for p, _ in kept:
+ w.size(os.path.join(store, str(p["id"])))
+ for p in victims:
+ pdir = os.path.join(store, str(p["id"]))
+ targets.append(describe(p, pdir, w.size(pdir)))
+ return item(targets, [describe(p, os.path.join(store, str(p["id"])), 0, why) for p, why in kept],
+ available=True, backend="btrfs" if btrfs else "ext4", how=RP_TOOL + " delete ID")
+
+
+# ---------------------------------------------------------------- update files
+
+def deb_fields(name):
+ """name_version_arch.deb, version with ":" written as %3a."""
+ base = os.path.basename(name)[:-4]
+ parts = base.split("_")
+ if len(parts) != 3:
+ return None
+ return parts[0], urllib.parse.unquote(parts[1]), parts[2]
+
+
+def apt_debs(pkgs):
+ targets, kept = [], []
+ for path in sorted(glob.glob(os.path.join(APT_ARCHIVES, "*.deb"))):
+ f = deb_fields(path)
+ try:
+ size = used(os.lstat(path))
+ except OSError:
+ continue
+ if not f:
+ kept.append({"path": path, "bytes": size, "why": "not a name apt gives its downloads"})
+ continue
+ name, version, arch = f
+ have = pkgs.get(name + ":" + arch)
+ if not have or not present(have):
+ # Not installed: a new package an update still has to install.
+ kept.append({"path": path, "bytes": size, "why": "not installed yet"})
+ elif version_le(version, have[0]):
+ targets.append({"path": path, "bytes": size,
+ "why": "installed" if version == have[0] else "older than the installed " + have[0]})
+ else:
+ kept.append({"path": path, "bytes": size, "why": "a newer version waiting to be installed"})
+ partial = os.path.join(APT_ARCHIVES, "partial")
+ if os.path.isdir(partial):
+ kept.append({"path": partial, "bytes": tree_size(partial), "why": "downloads apt may still be finishing"})
+ return targets, kept
+
+
+def packagekit_cache(pkgs):
+ """PackageKit's apt backend downloads into apt's own archives; anything
+ of its own that is a .deb follows the same rule, the rest (its
+ metadata) is kept."""
+ targets, kept = [], []
+ if not os.path.isdir(PACKAGEKIT_CACHE):
+ return targets, kept
+ for root, dirs, files in os.walk(PACKAGEKIT_CACHE):
+ for n in files:
+ path = os.path.join(root, n)
+ try:
+ size = used(os.lstat(path))
+ except OSError:
+ continue
+ f = deb_fields(path) if n.endswith(".deb") else None
+ have = f and pkgs.get(f[0] + ":" + f[2])
+ if f and have and present(have) and version_le(f[1], have[0]):
+ targets.append({"path": path, "bytes": size, "why": "installed"})
+ else:
+ kept.append({"path": path, "bytes": size, "why": "PackageKit's own lists, not a download" if not f
+ else "not installed yet"})
+ return targets, kept
+
+
+def flatpak_refs(installation):
+ """flatpak's own idea of unused runtimes in one installation (the list
+ `flatpak uninstall --unused` would offer, which leaves out pinned and
+ explicitly installed runtimes), read through libflatpak so nothing is
+ asked or removed."""
+ try:
+ import gi
+ gi.require_version("Flatpak", "1.0")
+ from gi.repository import Flatpak
+ except (ImportError, ValueError):
+ return None, []
+ try:
+ inst = Flatpak.Installation.new_system(None) if installation == "system" else Flatpak.Installation.new_user(None)
+ unused = inst.list_unused_refs(None, None)
+ apps = inst.list_installed_refs_by_kind(Flatpak.RefKind.APP, None)
+ except Exception:
+ return None, []
+ return [(r.format_ref(), r.get_deploy_dir(), r.get_installed_size()) for r in unused], \
+ [(a.get_name(), a.get_deploy_dir()) for a in apps]
+
+
+def runtimes_used_by(deploy_dirs):
+ """Runtime and SDK refs named in installed apps' metadata."""
+ used_refs = set()
+ for d in deploy_dirs:
+ try:
+ with open(os.path.join(d, "metadata"), encoding="utf-8", errors="replace") as f:
+ text = f.read()
+ except OSError:
+ continue
+ for m in re.finditer(r"^(?:runtime|sdk)=(\S+)", text, re.M):
+ used_refs.add("runtime/" + m.group(1))
+ return used_refs
+
+
+def home_flatpak_apps():
+ """Deploy dirs of every person's own Flatpak apps, read as root but only
+ their small metadata files, so the system's unused list never takes a
+ runtime someone's own app runs on."""
+ dirs = []
+ for p in pwd.getpwall():
+ if 1000 <= p.pw_uid < 60000:
+ dirs += glob.glob(os.path.join(p.pw_dir, ".local/share/flatpak/app/*/*/*/active"))
+ return dirs
+
+
+def flatpak_unused(installation, extra_used=()):
+ unused, apps = flatpak_refs(installation)
+ if unused is None:
+ return [], [{"path": "flatpak (" + installation + ")", "bytes": 0, "why": "libflatpak could not be read"}]
+ needed = runtimes_used_by([a[1] for a in apps] + list(extra_used))
+ targets, kept = [], []
+ w = Walker()
+ for ref, deploy, size in unused:
+ base = "/".join(ref.split("/")[:4])
+ entry = {"path": deploy or ref, "ref": ref}
+ if base in needed:
+ entry.update(bytes=size, why="an installed app still names it")
+ kept.append(entry)
+ continue
+ # The deploy folder's files are hard links into flatpak's store,
+ # which `flatpak uninstall` prunes, so its disk use is what comes
+ # back.
+ entry.update(bytes=w.size(deploy) if deploy else size, why="no installed app uses it")
+ targets.append(entry)
+ return targets, kept
+
+
+def old_kernels(pkgs, points_kernels, btrfs):
+ """Only the kernels apt itself would autoremove: Debian's
+ apt-auto-removal keeps the running one, the newest and the one before
+ it. Never the running kernel, whatever apt says."""
+ running = os.uname().release
+ out = run(["apt-get", "-s", "-o", "Debug::NoLocking=1", "autoremove"], timeout=120) or ""
+ names = []
+ for line in out.splitlines():
+ m = re.match(r"^Remv (\S+)", line)
+ if m and re.match(r"^linux-(image|modules|headers|kbuild)-", m.group(1)):
+ names.append(m.group(1))
+ targets, kept = [], []
+ for name in names:
+ version = re.sub(r"^linux-(image|modules|headers|kbuild)-(unsigned-)?", "", name)
+ size_kib = run(["dpkg-query", "-W", "-f", "${Installed-Size}", name]) or "0"
+ size = int(size_kib.strip() or 0) * 1024
+ entry = {"path": "package " + name, "package": name, "bytes": size}
+ if running.startswith(version) or version.startswith(running):
+ entry["why"] = "the kernel running now"
+ kept.append(entry)
+ elif btrfs and version in points_kernels:
+ # On Btrfs a restore point that still has this kernel keeps
+ # its files, so removing the package frees nothing until that
+ # point goes too.
+ entry.update(bytes=0, why="a restore point being kept still holds it, so nothing would come back")
+ targets.append(entry)
+ else:
+ entry["why"] = "apt marks it as no longer needed"
+ targets.append(entry)
+ for k, v in pkgs.items():
+ n = k.split(":")[0]
+ if re.match(r"^linux-image-\d", n) and present(v) and n not in names:
+ kept.append({"path": "package " + n, "package": n, "bytes": 0,
+ "why": "the kernel running now" if running in n else "apt keeps it (newest or the one before)"})
+ return targets, kept
+
+
+def update_files(pkgs, rp):
+ parts = {}
+ t, k = apt_debs(pkgs)
+ parts["apt"] = item(t, k, how="rm each file")
+ t, k = packagekit_cache(pkgs)
+ parts["packagekit"] = item(t, k, how="rm each file")
+ t, k = flatpak_unused("system", home_flatpak_apps())
+ parts["flatpak"] = item(t, k, how="flatpak uninstall --system --noninteractive REF")
+ kept_kernels = set()
+ for p in rp.get("kept", []):
+ kept_kernels.update(p.get("kernels") or [])
+ t, k = old_kernels(pkgs, kept_kernels, rp.get("backend") == "btrfs")
+ parts["kernels"] = item(t, k, how="dpkg --remove PACKAGES")
+ return {"bytes": sum(p["bytes"] for p in parts.values()), "count": sum(p["count"] for p in parts.values()),
+ "parts": parts}
+
+
+# ---------------------------------------------------------------- leftovers (system)
+
+def removed_package_configs(pkgs):
+ """Packages removed but not purged (dpkg's "rc"): their configuration
+ files are all that is left of them."""
+ targets = []
+ for k, v in sorted(pkgs.items()):
+ if not v[1].startswith("rc"):
+ continue
+ name = k.split(":")[0]
+ out = run(["dpkg-query", "-W", "-f", "${Conffiles}\n", k]) or ""
+ files, size = [], 0
+ for line in out.splitlines():
+ f = line.split()
+ if f and f[0].startswith("/"):
+ try:
+ st = os.lstat(f[0])
+ except OSError:
+ continue
+ files.append(f[0])
+ size += used(st)
+ targets.append({"path": "package " + name, "package": name, "files": files, "bytes": size})
+ return item(targets, how="dpkg --purge PACKAGES")
+
+
+# ---------------------------------------------------------------- Windows mode
+
+def winmode():
+ cfg = {}
+ try:
+ with open(WINMODE_CONFIG) as f:
+ cfg = json.load(f)
+ except (OSError, ValueError):
+ pass
+ domain = cfg.get("domain") or WINMODE_DOMAIN
+ try:
+ st = os.stat(WINMODE_DISK)
+ except OSError:
+ return item([], available=False)
+ allocated = used(st)
+ state = (run(["virsh", "-c", "qemu:///system", "domstate", domain], timeout=15) or "").strip()
+ saved = (run(["virsh", "-c", "qemu:///system", "dominfo", domain], timeout=15) or "")
+ managed_save = bool(re.search(r"^Managed save:\s+yes", saved, re.M))
+ guest_used = None
+ if state == "running":
+ # The guest agent knows how full Windows' own drives are.
+ out = run(["virsh", "-c", "qemu:///system", "qemu-agent-command", domain,
+ '{"execute":"guest-get-fsinfo"}', "--timeout", "10"], timeout=20)
+ try:
+ fs = json.loads(out or "{}").get("return") or []
+ sizes = [f.get("used-bytes") for f in fs if isinstance(f.get("used-bytes"), int)]
+ if sizes:
+ guest_used = sum(sizes)
+ except ValueError:
+ pass
+ d = {"path": WINMODE_DISK, "allocated": allocated, "apparent": st.st_size, "state": state or "unknown",
+ "managed_save": managed_save, "guest_used": guest_used}
+ if guest_used is None:
+ # Without Windows running nothing can read inside its disk short of
+ # opening NTFS here, which this never does.
+ d["bytes"] = 0
+ d["why"] = "Windows' own free space is only known while Windows mode is on"
+ return item([], [d], available=True, known=False, state=d["state"], managed_save=managed_save,
+ allocated=allocated)
+ d["bytes"] = max(0, allocated - guest_used)
+ return item([d], available=True, known=True, state=d["state"], managed_save=managed_save, allocated=allocated,
+ guest_used=guest_used)
+
+
+def measure_system():
+ pkgs = installed_packages()
+ rp = restore_points()
+ out = {
+ "restorePoints": rp,
+ "updates": update_files(pkgs, rp),
+ "leftoversSystem": removed_package_configs(pkgs),
+ "winmode": winmode(),
+ }
+ return out
+
+
+# ---------------------------------------------------------------- home
+
+def home():
+ return os.path.expanduser("~")
+
+
+def xdg(name, default):
+ path = os.path.join(home(), ".config/user-dirs.dirs")
+ try:
+ with open(path, encoding="utf-8") as f:
+ for line in f:
+ m = re.match(r'^XDG_%s_DIR="(.*)"' % name, line.strip())
+ if m:
+ return m.group(1).replace("$HOME", home())
+ except OSError:
+ pass
+ return os.path.join(home(), default)
+
+
+def removable_devices():
+ """Device paths on drives that can be unplugged (USB sticks, SD cards),
+ with everything on them: partitions, and encrypted volumes inside
+ those."""
+ out = run(["lsblk", "-J", "-o", "PATH,RM,HOTPLUG"], timeout=15)
+ found = set()
+
+ def walk(nodes, inherited):
+ for n in nodes or []:
+ gone = inherited or n.get("rm") in (True, "1") or n.get("hotplug") in (True, "1")
+ if gone and n.get("path"):
+ found.add(n["path"])
+ walk(n.get("children"), gone)
+ try:
+ walk(json.loads(out or "{}").get("blockdevices"), False)
+ except ValueError:
+ pass
+ return found
+
+
+def mounted_filesystems():
+ """(mount point, source device) for every mounted block device."""
+ mounts = []
+ try:
+ with open("/proc/self/mountinfo", encoding="utf-8", errors="replace") as f:
+ for line in f:
+ left, _, right = line.partition(" - ")
+ fields, extra = left.split(), right.split()
+ if len(fields) >= 5 and len(extra) >= 2 and extra[1].startswith("/dev/"):
+ point = fields[4].replace(r"\040", " ")
+ mounts.append((point, extra[1]))
+ except OSError:
+ pass
+ return mounts
+
+
+def trash_bins():
+ """Every Recycle Bin of this person: the one in the home folder, and the
+ .Trash-UID and .Trash/UID folders the file manager makes at the top of
+ other drives. Bins on removable drives are only reported, never
+ cleared: the drive may be someone else's, or gone by the time the
+ clearing starts."""
+ uid = os.getuid()
+ bins, removable_bins = [], []
+ home_bin = os.path.join(home(), ".local/share/Trash")
+ if os.path.isdir(home_bin):
+ bins.append(home_bin)
+ try:
+ home_dev = os.stat(home()).st_dev
+ except OSError:
+ home_dev = None
+ removable = removable_devices()
+ seen = set()
+ for point, source in mounted_filesystems():
+ try:
+ st = os.stat(point)
+ except OSError:
+ continue
+ # Files on the home folder's own drive always go to the home bin.
+ if st.st_dev == home_dev or st.st_dev in seen:
+ continue
+ seen.add(st.st_dev)
+ for cand in (os.path.join(point, ".Trash-%d" % uid), os.path.join(point, ".Trash", str(uid))):
+ if os.path.isdir(cand) and not os.path.islink(cand) and os.stat(cand).st_uid == uid:
+ (removable_bins if source in removable else bins).append(cand)
+ return bins, removable_bins
+
+
+def recycle_bin():
+ bins, removable_bins = trash_bins()
+ w = Walker()
+ targets, kept, count = [], [], 0
+ for b in bins:
+ files = len(glob.glob(os.path.join(b, "info", "*.trashinfo")))
+ count += files
+ size = sum(content_size(w, os.path.join(b, sub)) for sub in ("files", "info", "expunged"))
+ targets.append({"path": b, "bytes": size, "files": files,
+ "clears": [os.path.join(b, sub) + "/*" for sub in ("files", "info", "expunged")]
+ + [os.path.join(b, "directorysizes")]})
+ for b in removable_bins:
+ kept.append({"path": b, "bytes": tree_size(b), "why": "on a removable drive"})
+ return item(targets, kept, files=count, how="the contents of files, info and expunged in each bin")
+
+
+def app_caches(busy=None):
+ targets, kept = [], []
+ cache = os.path.join(home(), ".cache")
+ w = Walker()
+ # Files open apps are using stay, so they are counted first and so
+ # never as space that comes back.
+ if busy is None:
+ busy = open_files() or set()
+ for p in sorted(busy):
+ kept.append({"path": p, "bytes": w.size(p), "why": "an open app is using it"})
+ try:
+ entries = sorted(os.listdir(cache))
+ except OSError:
+ entries = []
+ for n in entries:
+ p = os.path.join(cache, n)
+ if any(r.match(n) for r in CACHE_KEEP):
+ kept.append({"path": p, "bytes": tree_size(p), "why": "KDE's list of installed apps, which the session needs"})
+ continue
+ targets.append({"path": p, "bytes": content_size(w, p)})
+ for p in sorted(glob.glob(os.path.join(home(), ".var/app/*/cache"))):
+ if os.path.islink(p):
+ continue
+ targets.append({"path": p, "bytes": content_size(w, p)})
+ thumbs = os.path.join(cache, "thumbnails")
+ return item(targets, kept, thumbnails=tree_size(thumbs) if os.path.isdir(thumbs) else 0,
+ how="the contents of each folder; files an open app is using are left")
+
+
+def flatpak_ids():
+ ids = set()
+ for scope in ("--user", "--system"):
+ out = run(["flatpak", "list", scope, "--app", "--columns=application"], timeout=30)
+ if out is None:
+ return None
+ ids.update(line.strip() for line in out.splitlines() if line.strip())
+ return ids
+
+
+# plasma-browser-integration puts its native messaging host into the
+# Flatpak folder of every browser it knows, installed or not.
+BROWSER_INTEGRATION = {"org.kde.plasma.browser_integration.json", "plasma-browser-integration-host"}
+
+
+def only_browser_integration(path):
+ found = False
+ for root, dirs, files in os.walk(path):
+ for n in files:
+ if n not in BROWSER_INTEGRATION:
+ return False
+ found = True
+ return found
+
+
+def leftovers_home():
+ targets, kept = [], []
+ ids = flatpak_ids()
+ w = Walker()
+ for p in sorted(glob.glob(os.path.join(home(), ".var/app/*"))):
+ app = os.path.basename(p)
+ if os.path.islink(p) or not os.path.isdir(p):
+ continue
+ if ids is None:
+ kept.append({"path": p, "bytes": 0, "why": "could not list installed Flatpak apps"})
+ elif app in ids:
+ continue
+ elif only_browser_integration(p):
+ kept.append({"path": p, "bytes": w.size(p),
+ "why": "KDE's browser integration writes it again at every sign-in"})
+ else:
+ targets.append({"path": p, "app": app, "kind": "flatpak", "bytes": w.size(p)})
+ pkgs = installed_packages()
+ for pkg, rels in sorted(WILDOS_APP_FOLDERS.items()):
+ if is_installed(pkgs, pkg):
+ continue
+ for rel in rels:
+ p = os.path.join(home(), rel)
+ if os.path.lexists(p) and not os.path.islink(p):
+ targets.append({"path": p, "app": pkg, "kind": "wildos", "bytes": w.size(p)})
+ apps = sorted({t["app"] for t in targets})
+ return item(targets, kept, apps=apps)
+
+
+def kactivities_last_used():
+ """When KDE's activity history last saw each file opened, if it is on."""
+ db = os.path.join(home(), ".local/share/kactivitymanagerd/resources/database")
+ seen = {}
+ if not os.path.exists(db):
+ return seen
+ try:
+ con = sqlite3.connect("file:" + urllib.parse.quote(db) + "?mode=ro", uri=True, timeout=2)
+ for res, last in con.execute("SELECT targettedResource, MAX(lastUpdate) FROM ResourceScoreCache GROUP BY targettedResource"):
+ if res and last:
+ seen[res if res.startswith("/") else urllib.parse.unquote(res.replace("file://", ""))] = float(last)
+ con.close()
+ except sqlite3.Error:
+ pass
+ return seen
+
+
+def xbel_last_used():
+ path = os.path.join(home(), ".local/share/recently-used.xbel")
+ seen = {}
+ try:
+ with open(path, encoding="utf-8", errors="replace") as f:
+ text = f.read()
+ except OSError:
+ return seen
+ for m in re.finditer(r'<bookmark href="file://([^"]+)"[^>]*?(?:visited="([^"]+)")?[^>]*?(?:modified="([^"]+)")?', text):
+ p = urllib.parse.unquote(m.group(1))
+ for stamp in (m.group(2), m.group(3)):
+ if stamp:
+ try:
+ t = time.mktime(time.strptime(stamp[:19], "%Y-%m-%dT%H:%M:%S"))
+ except ValueError:
+ continue
+ seen[p] = max(seen.get(p, 0), t)
+ return seen
+
+
+def large_downloads():
+ folder = xdg("DOWNLOAD", "Downloads")
+ if os.path.realpath(folder) == os.path.realpath(home()):
+ # Downloads pointed at the home folder itself: too wide to judge.
+ return item([], [{"path": folder, "bytes": 0, "why": "Downloads is the home folder"}], folder=folder)
+ opened = kactivities_last_used()
+ for p, t in xbel_last_used().items():
+ opened[p] = max(opened.get(p, 0), t)
+ cutoff = time.time() - DOWNLOADS_DAYS * DAY
+ targets = []
+ for root, dirs, files in os.walk(folder):
+ for n in files:
+ p = os.path.join(root, n)
+ try:
+ st = os.lstat(p)
+ except OSError:
+ continue
+ if not stat.S_ISREG(st.st_mode) or st.st_size < DOWNLOADS_MIN:
+ continue
+ # Wild OS mounts its disk with noatime, so the file's access
+ # time says nothing. Last opened is the later of when it was
+ # last written (downloaded) and when Wild OS's recent files
+ # last saw it opened.
+ last = max(st.st_mtime, opened.get(p, 0))
+ if last < cutoff:
+ targets.append({"path": p, "name": n, "bytes": used(st), "size": st.st_size, "last": last})
+ targets.sort(key=lambda t: -t["bytes"])
+ return item(targets, folder=folder, how="only the files ticked in Review")
+
+
+def measure_home():
+ return {
+ "bin": recycle_bin(),
+ "caches": app_caches(),
+ "leftoversHome": leftovers_home(),
+ "downloads": large_downloads(),
+ }
+
+
+# ---------------------------------------------------------------- clearing
+
+def disk_free():
+ st = os.statvfs("/")
+ return st.f_bavail * st.f_frsize, st.f_blocks * st.f_frsize
+
+
+def low_on_space():
+ free, total = disk_free()
+ return total > 0 and free / total < LOW_SPACE
+
+
+def hold_lock(path):
+ """One clearing at a time: a second one stops instead of waiting."""
+ fd = os.open(path, os.O_WRONLY | os.O_CREAT, 0o600)
+ try:
+ fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ except OSError:
+ os.close(fd)
+ return None
+ return fd
+
+
+def result(removed=None, skipped=None, freed=0, error=None):
+ r = {"freed": freed, "removed": removed or [], "skipped": skipped or []}
+ if error:
+ r["error"] = error
+ return r
+
+
+def remove_path(path):
+ """Removes a file, link or folder without ever following a link out of
+ it; True when it is gone."""
+ try:
+ st = os.lstat(path)
+ except FileNotFoundError:
+ return True
+ except OSError:
+ return False
+ try:
+ if stat.S_ISDIR(st.st_mode):
+ shutil.rmtree(path)
+ else:
+ os.unlink(path)
+ except OSError:
+ return False
+ return not os.path.lexists(path)
+
+
+def apt_busy():
+ """apt or an update holds its locks, so its downloads may be in use."""
+ for lock in ("/var/lib/dpkg/lock-frontend", "/var/cache/apt/archives/lock"):
+ if not os.path.exists(lock):
+ continue
+ fd = hold_lock(lock)
+ if fd is None:
+ return True
+ os.close(fd)
+ return False
+
+
+def clean_restore_points():
+ rp = restore_points()
+ removed, skipped, freed = [], [], 0
+ for t in rp["targets"]:
+ if run([RP_TOOL, "delete", str(t["id"])], timeout=1800) is not None:
+ removed.append(t["path"])
+ freed += t["bytes"]
+ else:
+ skipped.append({"path": t["path"], "why": "restore-points could not delete it"})
+ return result(removed, skipped, freed)
+
+
+def clean_updates():
+ m = update_files(installed_packages(), restore_points())["parts"]
+ removed, skipped, freed = [], [], 0
+ files = m["apt"]["targets"] + m["packagekit"]["targets"]
+ if files and apt_busy():
+ skipped += [{"path": t["path"], "why": "an update is running"} for t in files]
+ elif files:
+ lock = hold_lock("/var/cache/apt/archives/lock")
+ for t in files:
+ if os.path.isfile(t["path"]) and not os.path.islink(t["path"]) and remove_path(t["path"]):
+ removed.append(t["path"])
+ freed += t["bytes"]
+ if lock is not None:
+ os.close(lock)
+ for t in m["flatpak"]["targets"]:
+ if run(["flatpak", "uninstall", "--system", "--noninteractive", "-y", t["ref"]], timeout=600) is not None:
+ removed.append(t["ref"])
+ freed += t["bytes"]
+ else:
+ skipped.append({"path": t["ref"], "why": "flatpak could not remove it"})
+ # dpkg itself, not apt: apt would take a new restore point first and use
+ # more space than the kernel gives back. Kernels a kept restore point
+ # still holds give nothing back, so they stay.
+ kernels = [t for t in m["kernels"]["targets"] if t["bytes"] > 0]
+ if kernels:
+ names = [t["package"] for t in kernels]
+ if run(["dpkg", "--remove"] + names, timeout=1800) is not None:
+ removed += ["package " + n for n in names]
+ freed += sum(t["bytes"] for t in kernels)
+ else:
+ skipped += [{"path": "package " + n, "why": "dpkg could not remove it"} for n in names]
+ return result(removed, skipped, freed)
+
+
+def clean_leftovers_system():
+ m = removed_package_configs(installed_packages())
+ names = [t["package"] for t in m["targets"]]
+ if not names:
+ return result()
+ if run(["dpkg", "--purge"] + names, timeout=600) is None:
+ return result(skipped=[{"path": "package " + n, "why": "dpkg could not purge it"} for n in names])
+ return result(["package " + n for n in names], freed=m["bytes"])
+
+
+def winmode_domain():
+ try:
+ with open(WINMODE_CONFIG) as f:
+ return json.load(f).get("domain") or WINMODE_DOMAIN
+ except (OSError, ValueError, AttributeError):
+ return WINMODE_DOMAIN
+
+
+def agent(domain, command, timeout):
+ out = run(["virsh", "-c", "qemu:///system", "qemu-agent-command", domain, json.dumps(command),
+ "--timeout", str(timeout)], timeout=timeout + 30)
+ try:
+ return json.loads(out) if out else None
+ except ValueError:
+ return None
+
+
+def clean_winmode():
+ """Windows TRIMs its own free space and the disk's discard='unmap' hands
+ what it frees back to the disk file. Only while Windows mode is on:
+ the disk file itself is never rewritten here."""
+ m = winmode()
+ if not m.get("available"):
+ return result()
+ if m.get("state") != "running":
+ return result(skipped=[{"path": WINMODE_DISK, "why": "Windows mode isn't on"}])
+ domain = winmode_domain()
+ before = m["allocated"]
+ # guest-fstrim is the agent's own retrim (defrag /L on each volume).
+ done = agent(domain, {"execute": "guest-fstrim"}, TRIM_TIMEOUT)
+ if done is None:
+ # An agent without guest-fstrim: run Windows' retrim directly.
+ started = agent(domain, {"execute": "guest-exec", "arguments": {
+ "path": "C:\\Windows\\System32\\defrag.exe", "arg": ["C:", "/L"], "capture-output": True}}, 30)
+ pid = (started or {}).get("return", {}).get("pid")
+ if pid is None:
+ return result(skipped=[{"path": WINMODE_DISK, "why": "Windows' guest agent did not answer"}])
+ deadline = time.time() + TRIM_TIMEOUT
+ while time.time() < deadline:
+ time.sleep(5)
+ st = agent(domain, {"execute": "guest-exec-status", "arguments": {"pid": pid}}, 30)
+ if st is None or st.get("return", {}).get("exited"):
+ break
+ try:
+ after = used(os.stat(WINMODE_DISK))
+ except OSError:
+ after = before
+ return result([WINMODE_DISK], freed=max(0, before - after))
+
+
+SYSTEM_CLEANERS = {"restorePoints": clean_restore_points, "updates": clean_updates,
+ "leftovers": clean_leftovers_system, "winmode": clean_winmode}
+
+
+def clean_system(items):
+ fd = hold_lock(ROOT_LOCK)
+ if fd is None:
+ return {"error": "busy"}
+ out = {}
+ for it in SYSTEM_ITEMS:
+ if it in items:
+ try:
+ out[it] = SYSTEM_CLEANERS[it]()
+ except Exception as e: # one item failing must not stop the rest
+ out[it] = result(error=str(e))
+ os.close(fd)
+ return out
+
+
+def system_config():
+ try:
+ with open(SYSTEM_CONFIG) as f:
+ cfg = json.load(f)
+ return cfg if isinstance(cfg, dict) else {}
+ except (OSError, ValueError):
+ return {}
+
+
+def asker():
+ try:
+ return int(os.environ.get("PKEXEC_UID", ""))
+ except ValueError:
+ return None
+
+
+# ---------------------------------------------------------------- clearing (home)
+
+def open_cache_files(uid):
+ """As root: the files under one person's cache folders that their
+ running programs have open or mapped. Wild OS's hardened kernel keeps
+ people from reading even their own processes' open files, so the
+ person's half asks for this through the measure action. Only paths
+ inside that person's caches are handed back."""
+ try:
+ pw = pwd.getpwuid(uid)
+ except (KeyError, TypeError):
+ return []
+ roots = (os.path.join(pw.pw_dir, ".cache") + "/", os.path.join(pw.pw_dir, ".var/app") + "/")
+ found = set()
+
+ def keep(path):
+ path = path.rstrip("\n")
+ if path.endswith(" (deleted)"):
+ return
+ if path.startswith(roots):
+ found.add(path)
+ for pid in os.listdir("/proc"):
+ if not pid.isdigit():
+ continue
+ base = "/proc/" + pid
+ try:
+ if os.stat(base).st_uid != uid:
+ continue
+ for fd in os.listdir(base + "/fd"):
+ try:
+ keep(os.readlink(base + "/fd/" + fd))
+ except OSError:
+ pass
+ with open(base + "/maps", encoding="utf-8", errors="replace") as f:
+ for line in f:
+ parts = line.split(None, 5)
+ if len(parts) == 6:
+ keep(parts[5])
+ except OSError:
+ continue
+ return sorted(found)
+
+
+def open_files():
+ """The person's open cache files, from the root half; None when it
+ could not say."""
+ try:
+ r = subprocess.run(["pkexec", HELPER, "measure", "open-files"], stdout=subprocess.PIPE,
+ stderr=subprocess.DEVNULL, timeout=60)
+ if r.returncode == 0:
+ return set(json.loads(r.stdout).get("open", []))
+ except (OSError, ValueError, subprocess.TimeoutExpired):
+ pass
+ return None
+
+
+def recently_changed(top, within=3600):
+ """Without the list of open files, whatever changed in the last hour is
+ taken to be in use."""
+ found, cutoff = set(), time.time() - within
+ for root, dirs, files in os.walk(top):
+ for n in files:
+ p = os.path.join(root, n)
+ try:
+ if os.lstat(p).st_mtime > cutoff:
+ found.add(p)
+ except OSError:
+ pass
+ return found
+
+
+def empty_tree(top, busy):
+ """Removes everything under top except files in busy, bottom up, with
+ the folders that are left empty; top itself stays. A top that is a
+ file is removed unless busy. Returns what was kept for being open."""
+ kept = []
+ try:
+ st = os.lstat(top)
+ except OSError:
+ return kept
+ if not stat.S_ISDIR(st.st_mode):
+ if top in busy:
+ kept.append(top)
+ else:
+ remove_path(top)
+ return kept
+ for root, dirs, files in os.walk(top, topdown=False):
+ for n in files:
+ p = os.path.join(root, n)
+ if p in busy:
+ kept.append(p)
+ continue
+ try:
+ os.unlink(p)
+ except OSError:
+ pass
+ for n in dirs:
+ p = os.path.join(root, n)
+ try:
+ if os.path.islink(p):
+ os.unlink(p)
+ else:
+ os.rmdir(p)
+ except OSError:
+ pass
+ return kept
+
+
+def clean_bin():
+ m = recycle_bin()
+ removed, freed = [], 0
+ for t in m["targets"]:
+ for sub in ("files", "info", "expunged"):
+ empty_tree(os.path.join(t["path"], sub), set())
+ # KIO's cache of folder sizes in the bin, which it rebuilds.
+ remove_path(os.path.join(t["path"], "directorysizes"))
+ removed.append(t["path"])
+ freed += t["bytes"]
+ return result(removed, freed=freed)
+
+
+def clean_caches():
+ busy = open_files()
+ m = app_caches(busy if busy is not None else set())
+ removed, skipped, freed = [], [], 0
+ for t in m["targets"]:
+ kept = empty_tree(t["path"], busy if busy is not None else recently_changed(t["path"]))
+ left = content_size(Walker(), t["path"]) if kept else 0
+ freed += max(0, t["bytes"] - left)
+ removed.append(t["path"])
+ skipped += [{"path": k, "why": "an open app is using it"} for k in kept]
+ return result(removed, skipped, freed)
+
+
+def clean_leftovers_home():
+ m = leftovers_home()
+ removed, skipped, freed = [], [], 0
+ for t in m["targets"]:
+ if remove_path(t["path"]):
+ removed.append(t["path"])
+ freed += t["bytes"]
+ else:
+ skipped.append({"path": t["path"], "why": "could not be removed"})
+ return result(removed, skipped, freed)
+
+
+def clean_downloads(chosen):
+ allowed = {t["path"]: t for t in large_downloads()["targets"]}
+ removed, skipped, freed = [], [], 0
+ for p in chosen:
+ t = allowed.get(p)
+ if t is None:
+ skipped.append({"path": p, "why": "not a large file left unopened for 90 days"})
+ elif remove_path(p):
+ removed.append(p)
+ freed += t["bytes"]
+ return result(removed, skipped, freed)
+
+
+# ---------------------------------------------------------------- the person's run
+
+def size_text(n):
+ # Units of 1024 labelled GB, the way Settings and Files show sizes.
+ for unit, scale in (("TB", 1024 ** 4), ("GB", 1024 ** 3), ("MB", 1024 ** 2)):
+ if n >= scale:
+ v = n / scale
+ return ("%.0f %s" if unit == "MB" or (unit == "GB" and v >= 100) else "%.1f %s") % (v, unit)
+ return "%d KB" % max(1, n // 1024)
+
+
+def word_list(words):
+ return words[0] if len(words) == 1 else ", ".join(words[:-1]) + " and " + words[-1]
+
+
+def prefs_path():
+ return os.path.join(home(), ".config/wildos/free-space.json")
+
+
+def read_prefs():
+ try:
+ with open(prefs_path()) as f:
+ p = json.load(f)
+ return p if isinstance(p, dict) else {}
+ except (OSError, ValueError):
+ return {}
+
+
+def notify(title, body):
+ try:
+ subprocess.run(["notify-send", "--app-name=Wild OS", "--icon=drive-harddisk", title, body],
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=30)
+ except (OSError, subprocess.TimeoutExpired):
+ pass
+
+
+def person_run(items, downloads, auto):
+ runtime = os.environ.get("XDG_RUNTIME_DIR") or "/tmp"
+ fd = hold_lock(os.path.join(runtime, "wildos-free-space.lock"))
+ if fd is None:
+ return {"error": "busy"}
+ if auto:
+ prefs = read_prefs()
+ if not prefs.get("auto"):
+ return {"auto": "off"}
+ if not low_on_space():
+ return {"auto": "enough space"}
+ items = [i for i in prefs.get("items", []) if i in AUTO_ITEMS]
+ downloads = []
+ before, _ = disk_free()
+ out = {}
+ system = [i for i in SYSTEM_ITEMS if i in items]
+ if system:
+ args = ["pkexec", HELPER] + (["auto-system"] if auto else ["clean"] + system)
+ r = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
+ if r.returncode in (126, 127):
+ # No password given: nothing at all is cleared.
+ return {"cancelled": True}
+ try:
+ got = json.loads(r.stdout or b"{}")
+ out.update({k: v for k, v in got.items() if k in SYSTEM_ITEMS and isinstance(v, dict)})
+ except ValueError:
+ pass
+ if "bin" in items:
+ out["bin"] = clean_bin()
+ if "caches" in items:
+ out["caches"] = clean_caches()
+ if "leftovers" in items:
+ home_part = clean_leftovers_home()
+ sys_part = out.get("leftovers") or result()
+ out["leftovers"] = result(sys_part["removed"] + home_part["removed"],
+ sys_part["skipped"] + home_part["skipped"],
+ sys_part["freed"] + home_part["freed"])
+ if "downloads" in items and downloads:
+ out["downloads"] = clean_downloads(downloads)
+ after, _ = disk_free()
+ freed = {k: v["freed"] for k, v in out.items() if v.get("freed")}
+ summary = {"auto": auto, "bytes": max(0, after - before), "items": freed}
+ if freed:
+ # History reads this back (settings-history, kind space-freed).
+ syslog.openlog("settings-free-space")
+ syslog.syslog(syslog.LOG_INFO, "FREED " + json.dumps(summary, sort_keys=True))
+ if auto:
+ names = [LABELS[k] for k in PAGE_ITEMS if k in freed]
+ names[0] = names[0][0].upper() + names[0][1:]
+ notify("Space was freed up automatically",
+ "The disk was nearly full, so Wild OS cleared %s: %s."
+ % (size_text(sum(freed.values())), word_list(names)))
+ os.close(fd)
+ return {"items": out, "freed": summary["bytes"], "auto": auto}
+
+
+def set_auto(items):
+ uid = asker()
+ if uid is None:
+ return None
+ cfg = system_config()
+ if items:
+ cfg[str(uid)] = items
+ else:
+ cfg.pop(str(uid), None)
+ os.makedirs(os.path.dirname(SYSTEM_CONFIG), exist_ok=True)
+ tmp = SYSTEM_CONFIG + ".new"
+ with open(tmp, "w") as f:
+ json.dump(cfg, f, indent=1, sort_keys=True)
+ f.write("\n")
+ os.chmod(tmp, 0o644)
+ os.replace(tmp, SYSTEM_CONFIG)
+ return {"items": items}
+
+
+def main(argv):
+ cmd = argv[0] if argv else ""
+ args = argv[1:]
+ root = os.geteuid() == 0
+ if cmd in ("measure", "clean", "auto-system", "set-auto") and not root:
+ print(cmd + " needs root (pkexec)", file=sys.stderr)
+ return 2
+ if cmd in ("measure-home", "run") and root:
+ # As the person, so nothing in a home folder is ever touched with
+ # root's rights.
+ print(cmd + " runs as the person, not root", file=sys.stderr)
+ return 2
+ res = None
+ if cmd == "measure" and not args:
+ res = measure_system()
+ elif cmd == "measure" and args == ["open-files"]:
+ res = {"open": open_cache_files(asker())}
+ elif cmd == "measure-home":
+ res = measure_home()
+ elif cmd == "clean" and all(a in SYSTEM_ITEMS for a in args):
+ res = clean_system(args)
+ elif cmd == "auto-system" and not args:
+ items = [i for i in system_config().get(str(asker()), []) if i in SYSTEM_ITEMS and i in AUTO_ITEMS]
+ res = clean_system(items) if items and low_on_space() else {}
+ elif cmd == "set-auto" and all(a in SYSTEM_ITEMS and a in AUTO_ITEMS for a in args):
+ res = set_auto(args)
+ elif cmd == "run":
+ downloads, items, i = [], [], 0
+ while i < len(args):
+ if args[i] == "--download" and i + 1 < len(args):
+ downloads.append(args[i + 1])
+ i += 2
+ continue
+ if args[i] in PAGE_ITEMS:
+ items.append(args[i])
+ i += 1
+ res = person_run(items, downloads, "--auto" in args)
+ if res is None:
+ print(__doc__, file=sys.stderr)
+ return 2
+ json.dump(res, sys.stdout)
+ sys.stdout.write("\n")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv[1:]))
diff --git a/packages/wildos-settings/data/settings-history b/packages/wildos-settings/data/settings-history
new file mode 100644
index 0000000..1796d7b
--- /dev/null
+++ b/packages/wildos-settings/data/settings-history
@@ -0,0 +1,1678 @@
+#!/usr/bin/python3 -I
+"""What happened on this PC, for Settings > System > History.
+
+Runs as root, from wildos-history.timer every hour and from
+wildos-history.socket whenever Settings opens the page, and takes no
+requests: it only reads. It picks out the events a person would care about
+from the system journal, apt's history, the restore points' index and the
+firewall's list of blocked connections, and keeps them as plain records:
+
+ /var/lib/wildos/history/system.jsonl what anyone on this PC may see
+ /var/lib/wildos/history/user-UID.jsonl one account's own, readable
+ by that account only
+
+Each line is one event: {id, t, kind, data, tech}, tech being the few
+source lines it was made from. Settings writes the words. Events older
+than 30 days are deleted on every run, and nothing is sent anywhere.
+
+ settings-history collect bring the records up to date
+ settings-history serve the same for one connection on standard
+ input ([email protected]), answering
+ "ok" or "error <why>"
+ settings-history lid-closed note what decides the lid's action as it
+ closes (wildos-network runs it then)
+ settings-history lid-opened note the lid opening (the same)
+ settings-history forget firewall
+ the firewall's Clear the list: drop
+ History's copies of what it blocked
+"""
+
+import fcntl
+import glob
+import hashlib
+import json
+import os
+import pwd
+import re
+import subprocess
+import sys
+import time
+
+DIR = "/var/lib/wildos/history"
+STATE = os.path.join(DIR, "state.json")
+LOCK = "/run/wildos-history.lock"
+KEEP = 30 * 24 * 3600
+# Repeats of the same thing this close together are one event.
+MERGE = 10 * 60
+
+APT_LOGS = ["/var/log/apt/history.log.1", "/var/log/apt/history.log"]
+FIREWALL_LOG = "/var/lib/wildos/firewall/blocked.log"
+RESTORE_INDEXES = ["/.snapshots/index.json", "/var/lib/wildos/restore-points/index.json"]
+
+RESTORE_LOGS = ["/var/log/wildos-restore-points.log.1", "/var/log/wildos-restore-points.log"]
+# What wildos-network writes when the lid closes: why nothing may happen
+# next, which the journal never says (lid-closed below).
+LID_SNAPSHOTS = os.path.join(DIR, "lid-snapshots.json")
+# The lid closed and nothing followed within this long: it stayed on.
+LID_WAIT = 90
+# The label restore-points gives the point Reset Wild OS makes first.
+RESET_LABEL = "Before resetting Wild OS"
+
+COREDUMP = "fc2e22bc6ee647b6b90729ab34a250b1"
+SESSION_START = "8d45620c1a4348dbb17410da57c60c66"
+SESSION_STOP = "3354939424b4456d9802ca8333ed424a"
+FLATPAK = "c7b39b1e006b464599465e105b361485"
+SLEEP_START = "6bbd95ee977941e497c48be27c254128"
+SLEEP_STOP = "8811e6df2a8e40f58a94cea26f8ebf14"
+# logind: "The system will reboot now!" with ACTION and OPERATOR, then
+# "System is rebooting." with SHUTDOWN.
+LOGIND_ASKED = "9e7066279dc8403da79ce4b1a69064b2"
+LOGIND_SHUTDOWN = "98268866d1d54a499c4e98921d93bc40"
+STARTUP_FINISHED = "b07a249cd024414a82dd00cd181378ff"
+JOURNAL_STOPPED = "d93fb3c9c24d451a97cea615ce59c00b"
+# PID 1 starting and finishing a unit, for the disk password's wait.
+UNIT_STARTING = "7d4958e842da4a758f6c1cdc7b36dcc5"
+UNIT_STARTED = "39f53479d3a045ac8e11786248231fbf"
+
+# Settings' root helpers name each change to the firewall and the
+# protection level in the journal, as "HISTORY {json}".
+CHANGE_HELPERS = ("settings-firewall", "settings-protection")
+# Free up space notes what it cleared, as "FREED {json}", from the
+# person's own run of settings-free-space.
+FREE_SPACE = "settings-free-space"
+# The camera and microphone lights note each use, as "USE {json}", from the
+# person's own session (wildos-branding's camera-mic).
+CAMERA_MIC = "wildos-camera-mic"
+
+# Where a password is typed, by PAM service.
+PAM_PLACES = {"sddm": "signin", "sddm-autologin": "signin", "login": "signin", "kde": "lock",
+ "kscreenlocker": "lock", "polkit-1": "admin", "sudo": "admin", "su": "admin", "sshd": "ssh"}
+
+JOURNAL_FIELDS = ("__REALTIME_TIMESTAMP", "MESSAGE", "MESSAGE_ID", "SYSLOG_IDENTIFIER", "_COMM", "_TRANSPORT", "_UID", "_PID", "_BOOT_ID",
+ "COREDUMP_EXE", "COREDUMP_COMM", "COREDUMP_SIGNAL", "COREDUMP_SIGNAL_NAME", "COREDUMP_UID",
+ "COREDUMP_UNIT", "COREDUMP_USER_UNIT", "COREDUMP_PID", "COREDUMP_CGROUP",
+ "SESSION_ID", "USER_ID", "LEADER", "OPERATION", "REF", "REMOTE",
+ "SLEEP", "SHUTDOWN", "ACTION", "OPERATOR", "_SYSTEMD_UNIT", "_AUDIT_TYPE_NAME", "GLIB_DOMAIN")
+
+
+def now():
+ return time.time()
+
+
+def event_id(*parts):
+ return hashlib.sha1("\x1f".join(str(p) for p in parts).encode("utf-8", "replace")).hexdigest()[:16]
+
+
+def read_json(path, default):
+ try:
+ with open(path, encoding="utf-8") as f:
+ data = json.load(f)
+ return data if isinstance(data, type(default)) else default
+ except (OSError, ValueError):
+ return default
+
+
+def write_file(path, text, mode=0o644, gid=0):
+ tmp = path + ".new"
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, mode)
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
+ f.write(text)
+ os.fchown(f.fileno(), 0, gid)
+ os.fchmod(f.fileno(), mode)
+ os.replace(tmp, path)
+
+
+def is_person(uid):
+ return isinstance(uid, int) and 1000 <= uid < 60000
+
+
+def user_of(name):
+ try:
+ return pwd.getpwnam(name)
+ except (KeyError, TypeError):
+ return None
+
+
+def uid_of(name):
+ p = user_of(name)
+ return p.pw_uid if p else None
+
+
+def name_of(uid):
+ try:
+ return pwd.getpwuid(uid).pw_name
+ except (KeyError, TypeError):
+ return ""
+
+
+def real_name(name):
+ p = user_of(name)
+ gecos = (p.pw_gecos.split(",")[0].strip() if p else "")
+ return gecos or name
+
+
+class Store:
+ """The records, loaded whole: they are a month of events at most."""
+
+ def __init__(self):
+ self.events = {}
+ self.changed = set()
+
+ def path(self, uid):
+ return os.path.join(DIR, "system.jsonl" if uid is None else "user-%d.jsonl" % uid)
+
+ def load(self):
+ for path in glob.glob(os.path.join(DIR, "*.jsonl")):
+ # The file an event is in says whose it is, so it stays there
+ # and ages out of there.
+ m = re.match(r"user-(\d+)\.jsonl$", os.path.basename(path))
+ uid = int(m.group(1)) if m else None
+ if uid is None and os.path.basename(path) != "system.jsonl":
+ continue
+ try:
+ with open(path, encoding="utf-8") as f:
+ for line in f:
+ try:
+ e = json.loads(line)
+ except ValueError:
+ continue
+ if not isinstance(e, dict) or not isinstance(e.get("id"), str) or not isinstance(e.get("t"), (int, float)):
+ continue
+ e.pop("uid", None)
+ if uid is not None:
+ e["uid"] = uid
+ self.events[e["id"]] = e
+ except OSError:
+ pass
+
+ def has(self, eid):
+ return eid in self.events
+
+ def get(self, eid):
+ return self.events.get(eid)
+
+ def add(self, kind, t, data, tech, uid=None, eid=None):
+ eid = eid or event_id(kind, t, json.dumps(data, sort_keys=True))
+ if eid in self.events or t < now() - KEEP:
+ return self.events.get(eid)
+ e = {"id": eid, "t": round(t, 3), "kind": kind, "data": data, "tech": tech[-12:]}
+ if uid is not None:
+ e["uid"] = uid
+ self.events[eid] = e
+ self.changed.add(uid)
+ return e
+
+ def remove(self, eid):
+ e = self.events.pop(eid, None)
+ if e:
+ self.changed.add(e.get("uid"))
+
+ def touch(self, e):
+ self.changed.add(e.get("uid"))
+
+ def latest(self, kind, match, within=MERGE, at=None):
+ """The newest event of this kind that match() accepts and whose last
+ moment is within `within` seconds of `at`."""
+ best = None
+ for e in self.events.values():
+ if e["kind"] != kind or not match(e):
+ continue
+ last = e["data"].get("last", e["t"])
+ if at is not None and not (0 <= at - last <= within):
+ continue
+ if best is None or e["t"] > best["t"]:
+ best = e
+ return best
+
+ def prune(self):
+ oldest = now() - KEEP
+ for eid, e in list(self.events.items()):
+ if e.get("t", 0) < oldest:
+ del self.events[eid]
+ self.changed.add(e.get("uid"))
+
+ def save(self):
+ os.makedirs(DIR, mode=0o755, exist_ok=True)
+ os.chmod(DIR, 0o755)
+ by_uid = {}
+ for e in self.events.values():
+ by_uid.setdefault(e.get("uid"), []).append(e)
+ # Every file that exists is written again when it lost events, so a
+ # file whose events all aged out goes too.
+ for path in glob.glob(os.path.join(DIR, "user-*.jsonl")):
+ m = re.match(r"user-(\d+)\.jsonl$", os.path.basename(path))
+ if m and int(m.group(1)) not in by_uid:
+ self.changed.add(int(m.group(1)))
+ for uid in self.changed:
+ events = sorted(by_uid.get(uid, []), key=lambda e: e["t"])
+ path = self.path(uid)
+ if uid is not None and not events:
+ try:
+ os.unlink(path)
+ except OSError:
+ pass
+ continue
+ text = "".join(json.dumps(e, sort_keys=True, ensure_ascii=False) + "\n" for e in events)
+ if uid is None:
+ write_file(path, text, 0o644)
+ else:
+ try:
+ gid = pwd.getpwuid(uid).pw_gid
+ except KeyError:
+ # The account is gone, and its history with it.
+ try:
+ os.unlink(path)
+ except OSError:
+ pass
+ continue
+ write_file(path, text, 0o640, gid)
+
+
+def tech_line(t, source, text):
+ return [round(t, 3), source[:40], text[:300]]
+
+
+# ------------------------------------------------------------ app names
+
+def desktop_dirs(uid=None):
+ dirs = ["/usr/share/applications", "/usr/local/share/applications",
+ "/var/lib/flatpak/exports/share/applications"]
+ if uid is not None:
+ try:
+ home = pwd.getpwuid(uid).pw_dir
+ dirs += [os.path.join(home, ".local/share/applications"),
+ os.path.join(home, ".local/share/flatpak/exports/share/applications")]
+ except KeyError:
+ pass
+ return dirs
+
+
+def read_desktop(path):
+ name, program, hidden, entry = "", "", False, False
+ try:
+ with open(path, encoding="utf-8", errors="replace") as f:
+ for line in f:
+ line = line.rstrip("\n")
+ if line.startswith("["):
+ entry = line.strip() == "[Desktop Entry]"
+ elif entry and line.startswith("Name="):
+ name = line[5:].strip()
+ elif entry and line.startswith("Exec="):
+ program = os.path.basename(line[5:].strip().split(" ")[0])
+ elif entry and line.strip() == "NoDisplay=true":
+ hidden = True
+ except OSError:
+ pass
+ return name, program, hidden
+
+
+def app_for_program(program, comm, uid=None):
+ """The name people know a program by, from its Start menu entry."""
+ if program == "plasmashell" or comm == "plasmashell":
+ return "The desktop"
+ if program == "kwin_wayland":
+ return "The window manager"
+ for d in desktop_dirs(uid):
+ for path in sorted(glob.glob(os.path.join(d, "*.desktop"))):
+ name, exe, hidden = read_desktop(path)
+ if name and exe and not hidden and exe in (program, comm):
+ return name
+ return ""
+
+
+def app_for_flatpak(appid, uid=None):
+ for d in desktop_dirs(uid):
+ name, _, _ = read_desktop(os.path.join(d, appid + ".desktop"))
+ if name:
+ return name
+ return catalogue_name(appid, uid)
+
+
+def catalogue_name(appid, uid=None):
+ """An app's name from the catalogue Flatpak keeps of each remote, for
+ an app removed before History looked at it."""
+ roots = ["/var/lib/flatpak/appstream"]
+ if uid is not None:
+ try:
+ roots.append(os.path.join(pwd.getpwuid(uid).pw_dir, ".local/share/flatpak/appstream"))
+ except KeyError:
+ pass
+ needle = "<id>%s</id>" % appid
+ for root in roots:
+ for path in glob.glob(os.path.join(root, "*", "*", "active", "appstream.xml")):
+ try:
+ with open(path, encoding="utf-8", errors="replace") as f:
+ text = f.read()
+ except OSError:
+ continue
+ at = text.find(needle)
+ if at < 0:
+ continue
+ m = re.search(r"<name>([^<]{1,80})</name>", text[at:at + 20000])
+ if m:
+ return m.group(1).strip().replace("&amp;", "&")
+ return ""
+
+
+def app_for_package(package):
+ """A package's own Start menu entry, while it is installed."""
+ try:
+ out = subprocess.run(["dpkg-query", "-L", package], capture_output=True, text=True, timeout=10).stdout
+ except (OSError, subprocess.TimeoutExpired):
+ return ""
+ for path in out.splitlines():
+ if path.startswith("/usr/share/applications/") and path.endswith(".desktop"):
+ name, _, hidden = read_desktop(path)
+ if name and not hidden:
+ return name
+ return ""
+
+
+def flatpak_cgroup_app(cgroup):
+ m = re.search(r"app-flatpak-([A-Za-z0-9_.-]+?)-\d+\.scope", cgroup or "")
+ return m.group(1) if m else ""
+
+
+# ------------------------------------------------------------ the journal
+
+def journal_entries(state):
+ """New entries since the last run, or the last 30 days the first time."""
+ args = ["journalctl", "--no-pager", "-q", "-o", "json", "--output-fields=" + ",".join(JOURNAL_FIELDS)]
+ cursor = state.get("cursor")
+ if cursor:
+ args.append("--after-cursor=" + cursor)
+ else:
+ args.append("--since=@%d" % int(now() - KEEP))
+ args += ["MESSAGE_ID=" + COREDUMP, "MESSAGE_ID=" + SESSION_START, "MESSAGE_ID=" + SESSION_STOP,
+ "MESSAGE_ID=" + FLATPAK, "MESSAGE_ID=" + SLEEP_START, "MESSAGE_ID=" + SLEEP_STOP,
+ "+", "_COMM=udisksd", "+", "_TRANSPORT=kernel", "+", "_COMM=systemd-logind", "+", "_COMM=fprintd", "+", "_COMM=ksmserver",
+ "+", "_AUDIT_TYPE_NAME=USER_AUTH", "+", "_SYSTEMD_UNIT=wildos-winmoded.service", "+",
+ "SYSLOG_IDENTIFIER=sddm-helper", "SYSLOG_IDENTIFIER=kscreenlocker_greet",
+ "SYSLOG_IDENTIFIER=polkit-agent-helper-1", "SYSLOG_IDENTIFIER=sshd", "SYSLOG_IDENTIFIER=sshd-session",
+ "SYSLOG_IDENTIFIER=sudo", "SYSLOG_IDENTIFIER=login", "SYSLOG_IDENTIFIER=su"]
+ args += [x for name in CHANGE_HELPERS + (FREE_SPACE, CAMERA_MIC) for x in ("+", "SYSLOG_IDENTIFIER=" + name)]
+ env = dict(os.environ, LC_ALL="C.UTF-8", SYSTEMD_COLORS="0")
+ p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env)
+ for line in p.stdout:
+ try:
+ e = json.loads(line)
+ except ValueError:
+ continue
+ msg = e.get("MESSAGE")
+ # journalctl gives a message that isn't valid UTF-8 as a list of bytes.
+ if isinstance(msg, list):
+ e["MESSAGE"] = bytes(b for b in msg if isinstance(b, int) and 0 <= b < 256).decode("utf-8", "replace")
+ elif not isinstance(msg, str):
+ e["MESSAGE"] = ""
+ yield e
+ # Moved on entry by entry, so a run cut short never counts a wrong
+ # password or a blocked connection twice.
+ if e.get("__CURSOR"):
+ state["cursor"] = e["__CURSOR"]
+ err = p.stderr.read().decode("utf-8", "replace").strip()
+ code = p.wait()
+ if code != 0:
+ raise RuntimeError(err or "journalctl stopped with %d" % code)
+
+
+def num(value):
+ try:
+ return int(value)
+ except (TypeError, ValueError):
+ return None
+
+
+class Journal:
+ def __init__(self, store, state):
+ self.store = store
+ self.state = state
+ # Sessions this collector reported a sign-in for: id -> {user, uid}.
+ self.sessions = state.setdefault("sessions", {})
+ # Disks the kernel called removable: name -> time it said so.
+ self.removable = state.setdefault("removable", {})
+ # PAM sessions opened, by the process that opened them, which logind
+ # then names as the session's leader: pid -> (time, service, who
+ # said so, where from).
+ self.opened = {}
+ # Lid closes not yet followed by sleep or a shutdown: [{t, boot}].
+ self.lids = state.setdefault("lids", [])
+ # The latest lid, power key and logind request, for why the PC
+ # slept or shut down.
+ self.recent = state.setdefault("recent", {})
+ # The sleep event still waiting for its wake-up.
+ self.sleeping = state.get("sleeping")
+ # fprintd's last verify: who it was for, and when a finger matched,
+ # so the sign-in or unlock it led to says so.
+ self.fp = state.setdefault("fp", {})
+ # Lid switches wildos-network noted, not yet fed in: on some laptops
+ # logind never logs the lid while KDE holds it.
+ done = state.get("lid_switch_done", now() - KEEP)
+ self.switches = sorted(x for x in lid_switches(done + 0.001, now()) if x[0] > done)
+
+ def run(self):
+ for e in journal_entries(self.state):
+ t = (num(e.get("__REALTIME_TIMESTAMP")) or 0) / 1e6
+ if t < now() - KEEP:
+ continue
+ mid = e.get("MESSAGE_ID", "")
+ comm = e.get("_COMM", "")
+ while self.switches and self.switches[0][0] <= t:
+ self.lid_switch(*self.switches.pop(0), e.get("_BOOT_ID", ""))
+ # Within one start-up the monotonic clock never jumps, as the
+ # wall clock does when the time is set.
+ self.boot = e.get("_BOOT_ID", "")
+ self.mono = (num(e.get("__MONOTONIC_TIMESTAMP")) or 0) / 1e6
+ try:
+ if mid == COREDUMP:
+ self.crash(t, e)
+ elif mid == SESSION_START:
+ self.session_start(t, e)
+ elif mid == SESSION_STOP:
+ self.session_stop(t, e)
+ elif mid == FLATPAK:
+ self.flatpak(t, e)
+ elif mid in (SLEEP_START, SLEEP_STOP):
+ self.sleep(t, e, mid == SLEEP_START)
+ elif comm == "systemd-logind":
+ self.logind(t, e)
+ elif comm == "fprintd":
+ self.fprint(t, e)
+ elif comm == "ksmserver":
+ # KDE began signing out to shut down or restart.
+ if "is shutting down" in e["MESSAGE"]:
+ for lid in self.lids:
+ if 0 <= t - lid["t"] <= LID_WAIT:
+ lid.setdefault("ksm", t)
+ elif e.get("_AUDIT_TYPE_NAME") == "USER_AUTH":
+ self.audit_auth(t, e)
+ elif e.get("_SYSTEMD_UNIT") == "wildos-winmoded.service":
+ self.winmode(t, e)
+ elif e.get("SYSLOG_IDENTIFIER") in CHANGE_HELPERS:
+ self.change(t, e)
+ elif e.get("SYSLOG_IDENTIFIER") == FREE_SPACE:
+ self.freed(t, e)
+ elif e.get("SYSLOG_IDENTIFIER") == CAMERA_MIC:
+ self.device_use(t, e)
+ elif comm == "udisksd":
+ self.udisks(t, e)
+ elif e.get("_TRANSPORT") == "kernel":
+ self.kernel(t, e)
+ else:
+ self.pam(t, e)
+ except (KeyError, ValueError, TypeError, AttributeError):
+ # One odd entry never stops the rest.
+ continue
+ for switch in self.switches:
+ self.lid_switch(*switch, "")
+ self.settle_lids()
+ self.state["sleeping"] = self.sleeping
+ # Removable disks are only looked up for a few days, and a session
+ # whose end was never logged (a power cut) is forgotten with its
+ # sign-in.
+ for name, at in list(self.removable.items()):
+ if at < now() - 7 * 24 * 3600:
+ del self.removable[name]
+ for sid, s in list(self.sessions.items()):
+ if s.get("t", 0) < now() - KEEP:
+ del self.sessions[sid]
+
+ def crash(self, t, e):
+ uid = num(e.get("COREDUMP_UID"))
+ exe = e.get("COREDUMP_EXE", "")
+ comm = e.get("COREDUMP_COMM", "")
+ program = os.path.basename(exe) or comm
+ signal = e.get("COREDUMP_SIGNAL_NAME", "") or ("signal %s" % e.get("COREDUMP_SIGNAL", "?"))
+ pid = e.get("COREDUMP_PID", "")
+ tech = [tech_line(t, program or comm or "program", "stopped, signal %s (%s)" % (e.get("COREDUMP_SIGNAL", "?"), signal))]
+ if exe:
+ tech.append(tech_line(t, "program", "%s, process %s" % (exe, pid)))
+ unit = e.get("COREDUMP_USER_UNIT") or e.get("COREDUMP_UNIT") or ""
+ # An app's own unit name is a long random string that says nothing;
+ # a service's names the service.
+ if unit and not is_person(uid):
+ tech.append(tech_line(t, "unit", unit))
+ tech.append(tech_line(t, "coredump", "recorded, no memory kept, not sent"))
+ eid = event_id("crash", e.get("COREDUMP_PID"), t)
+ if is_person(uid):
+ app = app_for_flatpak(flatpak_cgroup_app(e.get("COREDUMP_CGROUP")), uid) if "app-flatpak-" in (e.get("COREDUMP_CGROUP") or "") else ""
+ app = app or app_for_program(program, comm, uid)
+ self.store.add("crash", t, {"app": app, "program": program, "signal": signal}, tech, uid, eid)
+ else:
+ self.store.add("service-crash", t, {"program": program, "unit": unit, "signal": signal}, tech, None, eid)
+
+ def pam(self, t, e):
+ msg = e["MESSAGE"]
+ ident = e.get("SYSLOG_IDENTIFIER", "")
+ pid = e.get("_PID", "")
+ m = re.match(r"pam_unix\(([\w.-]+):session\): session opened for user ([\w.-]+)", msg)
+ if m:
+ earlier = self.opened.get(pid)
+ self.opened[pid] = (t, m.group(1), ident, earlier[3] if earlier else "", {"b": self.boot, "m": self.mono})
+ return
+ m = re.match(r"Accepted \S+ for ([\w.-]+) from (\S+)", msg)
+ if m and ident.startswith("sshd"):
+ self.opened[pid] = (t, "sshd", ident, m.group(2), {"b": self.boot, "m": self.mono})
+ return
+ place, user, source = "", "", ""
+ m = re.match(r"pam_unix\(([\w.-]+):auth\): authentication failure;.*?\buser=([\w.-]+)", msg)
+ if m:
+ place, user = PAM_PLACES.get(m.group(1), "admin"), m.group(2)
+ # sshd says it again in its own words, with where from.
+ if place == "ssh":
+ return
+ m = m or re.match(r"Failed password for (?:invalid user )?([\w.-]+) from (\S+)", msg)
+ if m and not place:
+ place, user, source = "ssh", m.group(1), m.group(2)
+ if not place or not user:
+ return
+ # A finger unlocks the lock screen while its password half gives up
+ # in the same second, logging a failure nobody typed.
+ if place == "lock" and self.fp.get("user") == user and 0 <= self.since(self.fp.get("last")) <= 3:
+ return
+ uid = uid_of(user)
+ owner = uid if is_person(uid) else None
+ tech = tech_line(t, ident or "pam", msg)
+ e2 = self.store.latest("password", lambda x: x["data"].get("user") == user and x["data"].get("place") == place, at=t)
+ if e2 is not None:
+ e2["data"]["count"] = e2["data"].get("count", 1) + 1
+ e2["data"]["last"] = round(t, 3)
+ e2["tech"] = (e2["tech"] + [tech])[-12:]
+ self.store.touch(e2)
+ return
+ data = {"user": user, "name": real_name(user), "place": place, "count": 1, "last": round(t, 3)}
+ if source:
+ data["from"] = source
+ self.store.add("password", t, data, [tech], owner)
+
+ def session_start(self, t, e):
+ user = e.get("USER_ID", "")
+ sid = e.get("SESSION_ID", "")
+ uid = uid_of(user)
+ # Only sessions someone signed in to: the sign-in screen's own and
+ # each account's background service manager (opened through
+ # "systemd-user", whose PAM lines aren't read) are left out.
+ opened = self.opened.pop(e.get("LEADER", ""), None)
+ if not is_person(uid) or not sid or not opened or not 0 <= self.since(opened[4]) <= 60:
+ return
+ service = opened[1]
+ if service == "systemd-user":
+ return
+ how = "screen" if service.startswith("sddm") else "ssh" if service == "sshd" else "console" if service == "login" else "other"
+ data = {"user": user, "name": real_name(user), "how": how}
+ if how == "ssh" and opened[3]:
+ data["from"] = opened[3]
+ tech = [tech_line(opened[0], opened[2] or "pam", "session opened through %s" % service),
+ tech_line(t, "systemd-logind", e.get("MESSAGE", ""))]
+ # A finger that matched for this account just before.
+ match = self.take_match(user, t, 30) if how == "screen" else None
+ if match:
+ data["finger"] = True
+ tech.insert(0, tech_line(match["t"], "fprintd", "verify-match for %s" % user))
+ added = self.store.add("signin", t, data, tech, uid, event_id("signin", sid, t))
+ if added is not None:
+ self.sessions[self.session_key(e)] = {"user": user, "uid": uid, "t": t}
+
+ @staticmethod
+ def session_key(e):
+ # logind numbers sessions afresh at each start-up.
+ return "%s:%s" % (e.get("_BOOT_ID", ""), e.get("SESSION_ID", ""))
+
+ def session_stop(self, t, e):
+ sid = e.get("SESSION_ID", "")
+ s = self.sessions.pop(self.session_key(e), None)
+ if not s:
+ return
+ tech = [tech_line(t, "systemd-logind", e.get("MESSAGE", ""))]
+ self.store.add("signout", t, {"user": s["user"], "name": real_name(s["user"]), "since": s.get("t")}, tech, s["uid"],
+ event_id("signout", sid, t))
+
+ # ------------------------------------------------ fingerprints
+
+ def fprint(self, t, e):
+ """fprintd's own debug lines (its drop-in turns on just its domain):
+ whose prints it loaded, and each verify's result."""
+ msg = e["MESSAGE"]
+ m = re.search(r"discover_prints\(\) for user '([\w.-]+)'", msg)
+ if m:
+ self.fp["user"] = m.group(1)
+ return
+ user = self.fp.get("user", "")
+ if not user or "verify_cb: result" not in msg:
+ return
+ uid = uid_of(user)
+ owner = uid if is_person(uid) else None
+ if "verify-match" in msg:
+ self.fp["last"] = {"b": self.boot, "m": self.mono}
+ claimed = self.fp.get("claimed") or {}
+ used = claimed.get("user") == user and abs(self.since(claimed)) <= 30
+ self.fp.setdefault("matches", []).append({"t": t, "b": self.boot, "m": self.mono, "user": user, "used": used})
+ elif "verify-no-match" in msg:
+ tech = tech_line(t, "fprintd", "verify-no-match for %s" % user)
+ e2 = self.store.latest("finger-unknown", lambda x: x["data"].get("user") == user, at=t)
+ if e2 is not None:
+ e2["data"]["count"] = e2["data"].get("count", 1) + 1
+ e2["data"]["last"] = round(t, 3)
+ e2["tech"] = (e2["tech"] + [tech])[-12:]
+ self.store.touch(e2)
+ else:
+ self.store.add("finger-unknown", t, {"user": user, "name": real_name(user), "count": 1, "last": round(t, 3)},
+ [tech], owner, event_id("finger-unknown", user, t))
+
+ def since(self, rec):
+ """Seconds from rec (a {b, m} stamp) to the entry at hand."""
+ if not rec or rec.get("b") != self.boot:
+ return 1e9
+ return self.mono - rec.get("m", 0)
+
+ def take_match(self, user, t, within):
+ """The latest unused finger match for the account, if recent."""
+ for m in reversed(self.fp.get("matches", [])):
+ if m["user"] == user and (not m.get("used") or m.pop("signin", False)) and 0 <= self.since(m) <= within:
+ m["used"] = True
+ return m
+ return None
+
+ def audit_auth(self, t, e):
+ """PAM's own record of each sign-in screen, sudo and administrator
+ prompt check: which modules let the person in."""
+ msg = e["MESSAGE"]
+ if "res=success" not in msg:
+ return
+ grantors = re.search(r"grantors=(\S+)", msg)
+ acct = re.search(r'acct="([^"]+)"', msg)
+ exe = re.search(r'exe="([^"]+)"', msg)
+ # pam_fprintd for the sign-in screen and administrator prompts;
+ # sudo in a terminal takes the finger through pam_wildos_fingerprint.
+ if not grantors or not re.search(r"pam_fprintd|pam_wildos_fingerprint", grantors.group(1)) or not acct:
+ return
+ user = acct.group(1)
+ program = os.path.basename(exe.group(1)) if exe else ""
+ if program.startswith("sddm"):
+ # The sign-in event that follows says so (session_start); a
+ # sign-in that never got as far as a session is not an unlock.
+ for m in self.fp.get("matches", []):
+ if m["user"] == user and abs(self.since(m)) <= 30 and not m.get("used"):
+ m["used"] = True
+ m["signin"] = True
+ return
+ # The prompt and its PAM helper can each ask the reader, so every
+ # match around this approval belongs to it, not to the lock screen.
+ for m in self.fp.get("matches", []):
+ if m["user"] == user and abs(self.since(m)) <= 30:
+ m["used"] = True
+ self.fp["claimed"] = {"user": user, "b": self.boot, "m": self.mono}
+ uid = uid_of(user)
+ tech = [tech_line(t, program or "pam", "approved by %s for %s" % (grantors.group(1), user))]
+ e2 = self.store.latest("admin-finger", lambda x: x["data"].get("user") == user, at=t)
+ if e2 is not None:
+ e2["data"]["count"] = e2["data"].get("count", 1) + 1
+ e2["data"]["last"] = round(t, 3)
+ e2["tech"] = (e2["tech"] + tech)[-12:]
+ self.store.touch(e2)
+ return
+ self.store.add("admin-finger", t, {"user": user, "name": real_name(user), "by": "sudo" if program == "sudo" else "app",
+ "count": 1, "last": round(t, 3)},
+ tech, uid if is_person(uid) else None, event_id("admin-finger", user, t))
+
+ def settle_fingers(self):
+ """A finger match nothing else claimed within half a minute was the
+ lock screen's: kscreenlocker can't write PAM's audit record."""
+ keep = []
+ for m in self.fp.get("matches", []):
+ if m.get("used"):
+ continue
+ if now() - m["t"] < 30:
+ keep.append(m)
+ continue
+ uid = uid_of(m["user"])
+ self.store.add("unlock", m["t"], {"user": m["user"], "name": real_name(m["user"]), "finger": True},
+ [tech_line(m["t"], "fprintd", "verify-match for %s" % m["user"]),
+ tech_line(m["t"], "kscreenlocker", "unlocked")],
+ uid if is_person(uid) else None, event_id("unlock", m["user"], m["t"]))
+ self.fp["matches"] = keep[-20:]
+
+ # ------------------------------------------------ lid, power and sleep
+
+ def logind(self, t, e):
+ msg = e["MESSAGE"]
+ mid = e.get("MESSAGE_ID", "")
+ boot = e.get("_BOOT_ID", "")
+ if msg == "Lid closed.":
+ self.lid_switch(t, True, boot)
+ elif msg == "Lid opened.":
+ self.lid_switch(t, False, boot)
+ elif msg.startswith("Power key pressed"):
+ self.recent["power"] = t
+ elif mid == LOGIND_ASKED:
+ self.recent["ask"] = {"t": t, "action": e.get("ACTION", ""), "operator": e.get("OPERATOR", "")}
+ elif mid == LOGIND_SHUTDOWN:
+ self.lid_acted(t, "shutdown")
+
+ def lid_switch(self, t, closed, boot):
+ """The lid closed or opened, from logind or from UPower through
+ wildos-network; the two seeing the same switch, within a second or
+ so of each other, count once."""
+ if closed:
+ if abs(t - (self.recent.get("lid") or 0)) <= 5:
+ return
+ self.lids.append({"t": t, "boot": boot})
+ self.recent["lid"] = t
+ else:
+ if abs(t - (self.recent.get("lid_open") or 0)) <= 5:
+ return
+ self.recent["lid_open"] = t
+ for lid in self.lids:
+ lid.setdefault("opened", t)
+ self.state["lid_switch_done"] = max(self.state.get("lid_switch_done", 0), t)
+
+ def lid_acted(self, t, what):
+ """Sleep or a shutdown followed a closed lid: it did what it should."""
+ for lid in list(self.lids):
+ if 0 <= t - lid["t"] <= LID_WAIT:
+ self.lids.remove(lid)
+
+ def why(self, t, action):
+ """What started a sleep or a shutdown at t: the lid, the power
+ button, a person's request (the Start menu, or being left idle) or
+ the system."""
+ r = self.recent
+ lid = r.get("lid") or 0
+ closed = lid > (r.get("lid_open") or 0)
+ ask = r.get("ask") or {}
+ asked = 0 <= t - ask.get("t", 0) <= 120
+ if closed and 0 <= t - lid <= LID_WAIT:
+ return "lid"
+ if 0 <= t - (r.get("power") or 0) <= LID_WAIT:
+ return "power"
+ if asked:
+ return "person" if is_person(uid_of(ask.get("operator", ""))) else "system"
+ # logind acts on a closed lid by itself once nobody's desktop is
+ # in the way, which can be long after it closed (at sign-out).
+ if closed:
+ return "lid"
+ return ""
+
+ def sleep(self, t, e, start):
+ kind = e.get("SLEEP", "") or "suspend"
+ boot = e.get("_BOOT_ID", "")
+ if start:
+ reason = self.why(t, "sleep")
+ self.lid_acted(t, "sleep")
+ ask = self.recent.get("ask") or {}
+ data = {"kind": kind, "reason": reason}
+ if reason == "person":
+ data["user"] = real_name(ask.get("operator", ""))
+ added = self.store.add("sleep", t, data, [tech_line(t, "systemd-sleep", e["MESSAGE"])], None,
+ event_id("sleep", boot, t))
+ self.sleeping = added["id"] if added else None
+ return
+ ev = self.store.get(self.sleeping) if self.sleeping else None
+ self.sleeping = None
+ if ev is None:
+ return
+ ev["data"]["woke"] = round(t, 3)
+ ev["data"]["slept"] = round(t - ev["t"])
+ ev["tech"] = (ev["tech"] + [tech_line(t, "systemd-sleep", e["MESSAGE"])])[-12:]
+ self.store.touch(ev)
+
+ def settle_lids(self):
+ snapshots = read_json(LID_SNAPSHOTS, [])
+ keep = []
+ for lid in self.lids:
+ if now() - lid["t"] < LID_WAIT:
+ keep.append(lid)
+ continue
+ # logind and UPower both saw this one, in different runs.
+ if any(e["kind"] == "lid-on" and abs(e["t"] - lid["t"]) <= 5 for e in self.store.events.values()):
+ continue
+ snap = next((s for s in snapshots if abs(s.get("t", 0) - lid["t"]) <= 20 and s.get("event", "close") == "close"), {})
+ data = lid_reason(snap)
+ # KDE started the shutdown, and it never finished: an app held
+ # it up, usually by asking about unsaved work.
+ if lid.get("ksm") and data.get("reason") == "not-done":
+ data["reason"] = "held-up"
+ if lid.get("opened"):
+ data["opened"] = round(lid["opened"], 3)
+ tech = [tech_line(lid["t"], "systemd-logind", "Lid closed.")]
+ for line in snap.get("lines", []):
+ tech.append(tech_line(lid["t"], "lid", line))
+ if lid.get("ksm"):
+ tech.append(tech_line(lid["ksm"], "ksmserver", "shutting down (signing out first)"))
+ if lid.get("opened"):
+ tech.append(tech_line(lid["opened"], "systemd-logind", "Lid opened."))
+ self.store.add("lid-on", lid["t"], data, tech, None, event_id("lid-on", lid.get("boot"), lid["t"]))
+ self.lids[:] = keep
+ self.settle_fingers()
+
+ # ------------------------------------------------ Windows mode, settings
+
+ def winmode(self, t, e):
+ m = re.match(r"(start|resume|restart) failed: (.*)", e["MESSAGE"])
+ if m:
+ self.store.add("winmode-failed", t, {"action": m.group(1)},
+ [tech_line(t, "winmoded", e["MESSAGE"])], None, event_id("winmode", t, m.group(1)))
+
+ def change(self, t, e):
+ msg = e["MESSAGE"]
+ if not msg.startswith("HISTORY "):
+ return
+ data = json.loads(msg[8:])
+ if not isinstance(data, dict) or not isinstance(data.get("what"), str):
+ return
+ by = num(data.pop("by", None))
+ if is_person(by):
+ data["user"] = real_name(name_of(by))
+ self.store.add("setting", t, data, [tech_line(t, e.get("SYSLOG_IDENTIFIER", ""), msg[8:])], None,
+ event_id("setting", t, msg))
+
+ def freed(self, t, e):
+ msg = e["MESSAGE"]
+ if not msg.startswith("FREED "):
+ return
+ data = json.loads(msg[6:])
+ items = data.get("items") if isinstance(data, dict) else None
+ if not isinstance(items, dict):
+ return
+ # Whose space was freed is the journal's own record of who wrote
+ # the line, never what the line says.
+ uid = num(e.get("_UID"))
+ if not is_person(uid):
+ return
+ clean = {"auto": data.get("auto") is True, "bytes": max(0, num(data.get("bytes")) or 0),
+ "items": {k: num(v) or 0 for k, v in items.items() if isinstance(k, str)}}
+ self.store.add("space-freed", t, clean, [tech_line(t, FREE_SPACE, msg[6:])], uid,
+ event_id("space-freed", t, msg))
+
+ def device_use(self, t, e):
+ """One app's use of the camera or microphone: noted as it starts,
+ and its end filled in as it ends."""
+ msg = e["MESSAGE"]
+ if not msg.startswith("USE "):
+ return
+ data = json.loads(msg[4:])
+ if not isinstance(data, dict) or data.get("device") not in ("camera", "microphone"):
+ return
+ # Whose it is is the journal's own record of who wrote the line;
+ # an account can only ever add to its own history.
+ uid = num(e.get("_UID"))
+ if not is_person(uid):
+ return
+ key = str(data.get("key", ""))[:32]
+ start = data.get("start")
+ if not key or not isinstance(start, (int, float)):
+ return
+ end = data.get("end")
+ eid = event_id("device-use", uid, key)
+ tech = [tech_line(t, CAMERA_MIC, msg[4:])]
+ existing = self.store.get(eid)
+ if existing is None:
+ self.store.add("device-use", float(start), {"device": data["device"], "app": str(data.get("app", ""))[:80],
+ "id": str(data.get("id", ""))[:120], "how": str(data.get("how", ""))[:16],
+ "end": round(end, 3) if isinstance(end, (int, float)) else None},
+ tech, uid, eid)
+ elif isinstance(end, (int, float)):
+ existing["data"]["end"] = round(end, 3)
+ existing["tech"] = (existing["tech"] + tech)[-12:]
+ self.store.touch(existing)
+
+ def flatpak(self, t, e):
+ op = e.get("OPERATION", "")
+ ref = e.get("REF", "")
+ parts = ref.split("/")
+ if len(parts) < 2 or parts[0] != "app":
+ return
+ appid = parts[1]
+ uid = num(e.get("_UID"))
+ owner = uid if is_person(uid) else None
+ tech = [tech_line(t, "flatpak", e.get("MESSAGE", "") or "%s %s" % (op, ref))]
+ if e.get("REMOTE"):
+ tech.append(tech_line(t, "remote", e["REMOTE"]))
+ if op == "deploy install":
+ name = app_for_flatpak(appid, uid) or self.known_name(appid)
+ self.store.add("app-installed", t, {"app": name, "id": appid, "via": "flatpak", "remote": e.get("REMOTE", "")},
+ tech, owner, event_id("flatpak", t, op, ref))
+ elif op == "uninstall":
+ self.store.add("app-removed", t, {"app": self.known_name(appid), "id": appid, "via": "flatpak"},
+ tech, owner, event_id("flatpak", t, op, ref))
+ elif op == "deploy update":
+ name = app_for_flatpak(appid, uid) or self.known_name(appid)
+ e2 = self.store.latest("apps-updated", lambda x: x.get("uid") == owner, at=t)
+ if e2 is not None:
+ if appid not in e2["data"]["ids"]:
+ e2["data"]["ids"].append(appid)
+ e2["data"]["apps"].append(name)
+ e2["data"]["last"] = round(t, 3)
+ e2["tech"] = (e2["tech"] + tech)[-12:]
+ self.store.touch(e2)
+ else:
+ self.store.add("apps-updated", t, {"apps": [name], "ids": [appid], "last": round(t, 3)}, tech, owner,
+ event_id("flatpak-update", t, ref))
+
+ def known_name(self, appid):
+ """The name an app had when it was installed, once it is gone."""
+ for e in sorted(self.store.events.values(), key=lambda x: -x["t"]):
+ if e["data"].get("id") == appid and e["data"].get("app"):
+ return e["data"]["app"]
+ return ""
+
+ def kernel(self, t, e):
+ msg = e["MESSAGE"]
+ m = re.search(r"\[(sd[a-z]+)\] Attached SCSI removable disk", msg)
+ if m:
+ self.removable[m.group(1)] = t
+ return
+ m = re.match(r"Out of memory: Killed process (\d+) \(([^)]*)\).*?UID:(\d+)", msg)
+ if m:
+ uid = int(m.group(3))
+ comm = m.group(2)
+ owner = uid if is_person(uid) else None
+ app = app_for_program(comm, comm, uid) if owner is not None else ""
+ self.store.add("oom", t, {"app": app, "program": comm}, [tech_line(t, "kernel", msg)], owner,
+ event_id("oom", m.group(1), t))
+ return
+ m = (re.search(r"I/O error, dev ([\w-]+), sector", msg) or re.search(r"Buffer I/O error on dev ([\w-]+)", msg)
+ or re.search(r"(?:EXT4-fs|BTRFS) (?:error|critical|warning).*?\(device (\w[\w-]*)\)", msg))
+ if m:
+ self.disk_error(t, m.group(1), msg)
+
+ def disk_error(self, t, device, msg):
+ """Errors reading or writing a disk, one event per disk per hour:
+ a failing disk logs hundreds."""
+ tech = tech_line(t, "kernel", msg)
+ e2 = self.store.latest("disk-error", lambda x: x["data"].get("device") == device, within=3600, at=t)
+ if e2 is not None:
+ e2["data"]["count"] = e2["data"].get("count", 1) + 1
+ e2["data"]["last"] = round(t, 3)
+ if len(e2["tech"]) < 12:
+ e2["tech"].append(tech)
+ self.store.touch(e2)
+ return
+ self.store.add("disk-error", t, {"device": device, "disk": disk_kind(device, self.removable), "count": 1, "last": round(t, 3)},
+ [tech], None, event_id("disk-error", device, t))
+
+ def drive_kind(self, device):
+ base = re.sub(r"\d+$", "", os.path.basename(device))
+ if base in self.removable:
+ return "usb"
+ try:
+ if "/usb" in os.path.realpath("/sys/class/block/" + base):
+ return "usb"
+ except OSError:
+ pass
+ return "drive"
+
+ def udisks(self, t, e):
+ msg = e["MESSAGE"]
+ m = re.match(r"Mounted (/dev/\S+) at (.+?) on behalf of uid (\d+)", msg)
+ if m:
+ device, mount, uid = m.group(1), m.group(2), int(m.group(3))
+ if not mount.startswith("/media/"):
+ return
+ kind = self.drive_kind(device)
+ self.store.add("drive-in", t, {"label": os.path.basename(mount), "kind": kind},
+ [tech_line(t, "udisksd", msg)], uid if is_person(uid) else None, event_id("mount", device, t))
+ return
+ m = re.match(r"Cleaning up mount point (.+?) \(device (\S+) (?:no longer exists|is not mounted)", msg)
+ if m:
+ mount = m.group(1)
+ # Right after start-up this is udisks tidying up after a PC
+ # that went off with the drive mounted; not a drive pulled out.
+ if "no longer exists" not in msg or (num(e.get("__MONOTONIC_TIMESTAMP")) or 0) < 120e6:
+ return
+ parts = mount.split("/")
+ uid = uid_of(parts[2]) if len(parts) > 3 and parts[1] == "media" else None
+ # The mount line named the device; the clean-up only its number.
+ label = os.path.basename(mount)
+ mounted = self.store.latest("drive-in", lambda x: x["data"].get("label") == label, within=30 * 24 * 3600, at=t)
+ kind = mounted["data"].get("kind", "drive") if mounted else "drive"
+ self.store.add("drive-yanked", t, {"label": label, "kind": kind}, [tech_line(t, "udisksd", msg)],
+ uid if is_person(uid) else None, event_id("yank", mount, t))
+
+
+# ------------------------------------------------------------ disks
+
+def run_out(args, timeout=10):
+ try:
+ return subprocess.run(args, capture_output=True, text=True, timeout=timeout,
+ env=dict(os.environ, LC_ALL="C.UTF-8")).stdout
+ except (OSError, subprocess.TimeoutExpired):
+ return ""
+
+
+def disk_kind(device, removable):
+ """system (the disk Wild OS runs from), usb or other, for the words."""
+ base = os.path.basename(device)
+ # A device-mapper device (the encrypted system, LVM) or a partition:
+ # the disks under it.
+ under = run_out(["lsblk", "-nrso", "NAME,TYPE", "/dev/" + base]).split()
+ disks = [n for n, kind in zip(under[::2], under[1::2]) if kind == "disk"] or [re.sub(r"p?\d+$", "", base)]
+ root = run_out(["findmnt", "-nvo", "SOURCE", "/"]).strip()
+ root_disks = []
+ if root:
+ tree = run_out(["lsblk", "-nrso", "NAME,TYPE", root]).split()
+ root_disks = [n for n, kind in zip(tree[::2], tree[1::2]) if kind == "disk"]
+ if any(d in root_disks for d in disks):
+ return "system"
+ if any(d in removable for d in disks):
+ return "usb"
+ for d in disks:
+ try:
+ if "/usb" in os.path.realpath("/sys/class/block/" + d):
+ return "usb"
+ except OSError:
+ pass
+ return "other"
+
+
+# ------------------------------------------------------------ the lid
+
+POWERDEVIL_ACTIONS = {0: "nothing", 1: "sleep", 2: "hibernate", 8: "shutdown", 16: "ask", 32: "lock", 64: "screen-off",
+ 128: "screen-off"}
+
+
+def ini_value(path, group, key):
+ """One key of a KDE config file, or None."""
+ section = None
+ try:
+ with open(path, encoding="utf-8", errors="replace") as f:
+ for line in f:
+ line = line.strip()
+ if line.startswith("["):
+ section = line
+ elif section == group and line.startswith(key + "="):
+ return line.split("=", 1)[1].strip()
+ except OSError:
+ pass
+ return None
+
+
+def bus_property(name, path, iface, prop):
+ out = run_out(["busctl", "--json=short", "get-property", name, path, iface, prop])
+ try:
+ return json.loads(out).get("data")
+ except ValueError:
+ return None
+
+
+def lid_snapshot():
+ """Everything that decides what closing the lid does, as it is right
+ now: whose desktop is on screen, battery or mains, what Power and
+ battery > More power settings says, other screens, and inhibitor locks.
+ Nothing here goes in the journal by itself."""
+ snap = {"t": round(now(), 3), "event": "close"}
+ seat = bus_property("org.freedesktop.login1", "/org/freedesktop/login1/seat/seat0", "org.freedesktop.login1.Seat", "ActiveSession")
+ user = ""
+ if isinstance(seat, list) and seat and seat[0]:
+ user = (bus_property("org.freedesktop.login1", seat[1], "org.freedesktop.login1.Session", "Name") or "")
+ p = user_of(user) if user else None
+ snap["user"] = user if p and is_person(p.pw_uid) else ""
+ snap["battery"] = bool(bus_property("org.freedesktop.UPower", "/org/freedesktop/UPower", "org.freedesktop.UPower", "OnBattery"))
+ profile = "Battery" if snap["battery"] else "AC"
+ if snap["user"]:
+ rc = os.path.join(p.pw_dir, ".config/powerdevilrc")
+ group = "[%s][SuspendAndShutdown]" % profile
+ action = num(ini_value(rc, group, "LidAction"))
+ can_sleep = (run_out(["busctl", "call", "org.freedesktop.login1", "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager", "CanSuspend"]).strip() == 's "yes"')
+ snap["action"] = POWERDEVIL_ACTIONS.get(action if action is not None else (1 if can_sleep else 64), "other")
+ snap["with_screen"] = (ini_value(rc, group, "InhibitLidActionWhenExternalMonitorPresent") or "true") == "false"
+ snap["profile"] = profile
+ # Screens other than a laptop's own panel.
+ screens = 0
+ for status in glob.glob("/sys/class/drm/card*-*/status"):
+ name = os.path.basename(os.path.dirname(status)).split("-", 1)[1]
+ try:
+ with open(status) as f:
+ connected = f.read().strip() == "connected"
+ except OSError:
+ connected = False
+ if connected and not re.match(r"(eDP|LVDS|DSI)", name):
+ screens += 1
+ snap["screens"] = screens
+ for prop in ("HandleLidSwitch", "HandleLidSwitchExternalPower", "HandleLidSwitchDocked", "Docked"):
+ snap[prop] = bus_property("org.freedesktop.login1", "/org/freedesktop/login1", "org.freedesktop.login1.Manager", prop)
+ blocks = []
+ out = run_out(["busctl", "--json=short", "call", "org.freedesktop.login1", "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager", "ListInhibitors"])
+ try:
+ rows = json.loads(out).get("data", [[]])[0]
+ except (ValueError, IndexError, AttributeError):
+ rows = []
+ for what, who, why, mode, uid, pid in rows:
+ if mode != "block" or not re.search(r"handle-lid-switch|sleep|shutdown", what):
+ continue
+ # KDE's own lock is how KDE takes over the lid; not a reason.
+ if who == "PowerDevil":
+ snap["kde"] = True
+ continue
+ try:
+ with open("/proc/%d/comm" % pid) as f:
+ comm = f.read().strip()
+ except OSError:
+ comm = ""
+ blocks.append({"who": who, "why": why, "what": what, "comm": comm, "uid": uid})
+ snap["blocks"] = blocks
+ lines = ["%s, %s power, %d other screen%s" % (("desktop of " + snap["user"]) if snap["user"] else "sign-in screen",
+ "battery" if snap["battery"] else "mains", screens, "" if screens == 1 else "s")]
+ if snap.get("action"):
+ lines.append("More power settings: %s; even with another screen: %s" % (snap["action"], "yes" if snap.get("with_screen") else "no"))
+ for b in blocks:
+ lines.append("inhibitor %s (%s): %s, %s" % (b["who"], b["comm"], b["what"], b["why"]))
+ snap["lines"] = lines
+ return snap
+
+
+def lid_closed():
+ """Run by wildos-network as the lid closes."""
+ os.makedirs(DIR, mode=0o755, exist_ok=True)
+ snap = lid_snapshot()
+ lock = open(LID_SNAPSHOTS + ".lock", "w")
+ fcntl.flock(lock, fcntl.LOCK_EX)
+ snaps = [s for s in read_json(LID_SNAPSHOTS, []) if isinstance(s, dict) and s.get("t", 0) > now() - KEEP]
+ snaps.append(snap)
+ write_file(LID_SNAPSHOTS, json.dumps(snaps[-100:]), 0o600)
+
+
+def lid_opened():
+ """Run by wildos-network as the lid opens."""
+ os.makedirs(DIR, mode=0o755, exist_ok=True)
+ lock = open(LID_SNAPSHOTS + ".lock", "w")
+ fcntl.flock(lock, fcntl.LOCK_EX)
+ snaps = [s for s in read_json(LID_SNAPSHOTS, []) if isinstance(s, dict) and s.get("t", 0) > now() - KEEP]
+ snaps.append({"t": round(now(), 3), "event": "open"})
+ write_file(LID_SNAPSHOTS, json.dumps(snaps[-100:]), 0o600)
+
+
+def lid_switches(since, until):
+ """Lid closes and opens wildos-network saw through UPower, which reads
+ the switch itself: [(t, closed)]."""
+ out = []
+ for snap in read_json(LID_SNAPSHOTS, []):
+ if isinstance(snap, dict) and since <= snap.get("t", 0) <= until:
+ out.append((snap["t"], snap.get("event", "close") == "close"))
+ return out
+
+
+def lid_reason(snap):
+ """Why closing the lid did nothing, from what was true as it closed."""
+ if not snap:
+ return {"reason": "unknown"}
+ apps = [b for b in snap.get("blocks", []) if not b["who"] in ("ModemManager", "NetworkManager", "UPower")]
+ if apps:
+ return {"reason": "app", "apps": sorted({b["who"] for b in apps}), "profile": snap.get("profile")}
+ if snap.get("user") and snap.get("kde"):
+ action = snap.get("action", "")
+ if action in ("nothing", "lock", "screen-off", "ask"):
+ return {"reason": "setting", "action": action, "profile": snap.get("profile")}
+ if snap.get("screens", 0) > 0 and not snap.get("with_screen"):
+ return {"reason": "screen", "action": action, "screens": snap["screens"], "profile": snap.get("profile")}
+ return {"reason": "not-done", "action": action, "profile": snap.get("profile")}
+ handle = snap.get("HandleLidSwitchExternalPower") if not snap.get("battery") else snap.get("HandleLidSwitch")
+ if snap.get("Docked") and snap.get("HandleLidSwitchDocked") == "ignore":
+ return {"reason": "screen", "profile": snap.get("profile")}
+ if handle == "ignore":
+ return {"reason": "signin-setting", "profile": snap.get("profile")}
+ return {"reason": "unknown", "profile": snap.get("profile")}
+
+
+# ------------------------------------------------------------ start-up and shutdown
+
+def journal_json(args):
+ out = run_out(["journalctl", "--no-pager", "-q", "-o", "json"] + args, timeout=60)
+ entries = []
+ for line in out.splitlines():
+ try:
+ e = json.loads(line)
+ except ValueError:
+ continue
+ if isinstance(e.get("MESSAGE"), list):
+ e["MESSAGE"] = bytes(b for b in e["MESSAGE"] if isinstance(b, int) and 0 <= b < 256).decode("utf-8", "replace")
+ elif not isinstance(e.get("MESSAGE"), str):
+ e["MESSAGE"] = ""
+ e["t"] = (num(e.get("__REALTIME_TIMESTAMP")) or 0) / 1e6
+ entries.append(e)
+ return entries
+
+
+ENDING_RULES = 2
+
+
+def collect_boots(store, state):
+ """Each start-up (how long it took), and how each one ended: shut down
+ or restarted (by what), or not properly at all."""
+ out = run_out(["journalctl", "--list-boots", "--no-pager", "-o", "json"], timeout=30)
+ try:
+ boots = json.loads(out)
+ except ValueError:
+ raise RuntimeError("journalctl --list-boots: " + out[:200])
+ boots = [b for b in boots if isinstance(b, dict) and b.get("boot_id")]
+ boots.sort(key=lambda b: b.get("first_entry", 0))
+ done = state.setdefault("boots", {})
+ current = boots[-1]["boot_id"] if boots else ""
+ previous = None
+ for b in boots:
+ bid = b["boot_id"]
+ first = b.get("first_entry", 0) / 1e6
+ last = b.get("last_entry", 0) / 1e6
+ mark = done.setdefault(bid, {})
+ if last < now() - KEEP:
+ previous = b
+ continue
+ if not mark.get("start"):
+ startup(store, bid, first, previous)
+ mark["start"] = True
+ # A start-up's end is judged again when the rules change: version 2
+ # stopped calling a shutdown whose journal was cut short "not shut
+ # down properly".
+ if bid != current and mark.get("end") != ENDING_RULES:
+ store.remove(event_id("unclean", bid))
+ store.remove(event_id("ending", bid))
+ ending(store, bid, last)
+ mark["end"] = ENDING_RULES
+ previous = b
+ # Boots older than the history kept are forgotten.
+ alive = {b["boot_id"] for b in boots if b.get("last_entry", 0) / 1e6 >= now() - KEEP}
+ for bid in list(done):
+ if bid not in alive:
+ del done[bid]
+
+
+def startup(store, bid, first, previous):
+ entries = journal_json(["-b", bid, "_PID=1", "--until=@%d" % int(first + 900)])
+ finished = next((e for e in entries if e.get("MESSAGE_ID") == STARTUP_FINISHED), None)
+ # The time the disk password screen sat waiting is not start-up time.
+ # Measured on the monotonic clock: the wall clock can jump before the
+ # time is set.
+ wait = 0.0
+ starting = {}
+ for e in entries:
+ msg = e["MESSAGE"]
+ if "systemd-cryptsetup@" not in msg:
+ continue
+ mono = (num(e.get("__MONOTONIC_TIMESTAMP")) or 0) / 1e6
+ if msg.startswith("Starting systemd-cryptsetup@"):
+ starting[msg.split(" ")[1]] = mono
+ elif msg.startswith("Finished systemd-cryptsetup@"):
+ begun = starting.pop(msg.split(" ")[1], None)
+ if begun is not None:
+ wait += max(0.0, mono - begun)
+ t = finished["t"] if finished else first
+ data = {}
+ tech = [tech_line(first, "kernel", "start-up began")]
+ if finished:
+ total = sum((num(finished.get(k)) or 0) for k in ("FIRMWARE_USEC", "LOADER_USEC", "KERNEL_USEC", "INITRD_USEC", "USERSPACE_USEC")) / 1e6
+ data["seconds"] = round(max(0.0, total - wait))
+ if wait >= 1:
+ data["waited"] = round(wait)
+ tech.append(tech_line(t, "systemd", finished["MESSAGE"]))
+ if wait >= 1:
+ tech.append(tech_line(t, "systemd", "of which %.0f s waiting for the disk password" % wait))
+ store.add("startup", t, data, tech, None, event_id("startup", bid))
+
+
+def ending(store, bid, last):
+ """How a start-up that is over ended."""
+ tail = journal_json(["-b", bid, "-n", "1"])
+ clean = bool(tail) and tail[-1].get("MESSAGE_ID") == JOURNAL_STOPPED
+ since = "--since=@%d" % int(last - 1800)
+ lines = journal_json(["-b", bid, since, "_COMM=systemd-logind", "+", "_COMM=unattended-upgr", "+", "_COMM=upowerd",
+ "+", "SYSLOG_IDENTIFIER=systemd-sleep"])
+ lid = power = battery = updates = None
+ lid_open = None
+ ask = shut = None
+ asleep = None
+ for e in lines:
+ msg = e["MESSAGE"]
+ if msg == "Lid closed.":
+ lid = e["t"]
+ elif msg == "Lid opened.":
+ lid_open = e["t"]
+ elif msg.startswith("Power key pressed"):
+ power = e["t"]
+ elif e.get("MESSAGE_ID") == LOGIND_ASKED:
+ ask = e
+ elif e.get("MESSAGE_ID") == LOGIND_SHUTDOWN:
+ shut = e
+ elif e.get("_COMM") == "upowerd" and "critical" in msg.lower():
+ battery = e["t"]
+ elif e.get("_COMM") == "unattended-upgr" and "reboot" in msg.lower():
+ updates = e["t"]
+ elif e.get("SYSLOG_IDENTIFIER") == "systemd-sleep":
+ if msg.startswith("Performing sleep operation"):
+ asleep = e["t"]
+ elif msg.startswith("System returned from sleep"):
+ asleep = None
+ for when, closed in lid_switches(last - 1800, last + 1):
+ if closed and (lid is None or when > lid):
+ lid = when
+ elif not closed and (lid_open is None or when > lid_open):
+ lid_open = when
+ lid_down = lid if lid and not (lid_open and lid_open > lid) else None
+ # The journal can stop before it writes "Journal stopped": on some PCs
+ # the last lines are the file systems being unmounted. A shutdown that
+ # logind started and that ends within two minutes was a shutdown, not
+ # a power cut or a hang.
+ if not clean and shut and 0 <= last - shut["t"] <= 120:
+ clean = True
+ if not clean:
+ data = {"last": round(last, 3)}
+ if lid_down:
+ data["lid"] = round(lid_down, 3)
+ if asleep:
+ data["asleep"] = round(asleep, 3)
+ # Programs' own last words; the kernel's audit records say nothing
+ # a person can use.
+ tech = [tech_line(e["t"], e.get("SYSLOG_IDENTIFIER") or e.get("_COMM") or "journal", e["MESSAGE"])
+ for e in journal_json(["-b", bid, "-n", "4", "_TRANSPORT=journal", "_TRANSPORT=syslog", "_TRANSPORT=stdout"])]
+ tech.append(tech_line(last, "journal", "nothing more was recorded; there was no shutdown"))
+ # Shown at the next start, when it came to light.
+ store.add("unclean", last, data, tech, None, event_id("unclean", bid))
+ return
+ t = shut["t"] if shut else last
+ kind = "restart" if ((shut or {}).get("SHUTDOWN") == "reboot" or (ask or {}).get("ACTION") == "reboot") else "shutdown"
+ if lid_down and 0 <= t - lid_down <= 300:
+ cause = "lid"
+ elif power and 0 <= t - power <= 120:
+ cause = "power"
+ elif battery and 0 <= t - battery <= 300:
+ cause = "battery"
+ elif updates and 0 <= t - updates <= 1800:
+ cause = "updates"
+ elif ask and is_person(uid_of(ask.get("OPERATOR", ""))):
+ cause = "person"
+ elif ask or shut:
+ cause = "system"
+ else:
+ cause = ""
+ data = {"cause": cause}
+ if cause == "person":
+ data["user"] = real_name(ask.get("OPERATOR", ""))
+ tech = []
+ for e in (ask, shut):
+ if e:
+ tech.append(tech_line(e["t"], "systemd-logind", e["MESSAGE"] + (" (asked by %s)" % e["OPERATOR"] if e.get("OPERATOR") else "")))
+ tech.append(tech_line(last, "systemd-journald", "Journal stopped"))
+ store.add(kind, t, data, tech, None, event_id("ending", bid))
+
+
+# ------------------------------------------------------------ apt
+
+def apt_entries():
+ entries = []
+ for path in APT_LOGS:
+ try:
+ with open(path, encoding="utf-8", errors="replace") as f:
+ text = f.read()
+ except OSError:
+ continue
+ for block in re.split(r"\n\s*\n", text):
+ fields = {}
+ for line in block.strip().splitlines():
+ key, sep, value = line.partition(": ")
+ if sep:
+ fields[key.strip()] = value.strip()
+ if "Start-Date" in fields:
+ entries.append(fields)
+ return entries
+
+
+def apt_time(value):
+ try:
+ return time.mktime(time.strptime(re.sub(r"\s+", " ", value), "%Y-%m-%d %H:%M:%S"))
+ except (TypeError, ValueError):
+ return None
+
+
+def apt_packages(value):
+ # "name:arch (old, new), other:arch (version, automatic)"
+ out = []
+ for m in re.finditer(r"([^\s,(]+?)(?::[a-z0-9]+)? \(([^)]*)\)", value or ""):
+ out.append((m.group(1), "automatic" in m.group(2)))
+ return out
+
+
+def collect_apt(store):
+ restore = [e for e in store.events.values() if e["kind"] == "restore-point"]
+ for f in apt_entries():
+ t = apt_time(f.get("Start-Date"))
+ if t is None or t < now() - KEEP:
+ continue
+ eid = event_id("apt", f.get("Start-Date"), f.get("Commandline", ""))
+ if store.has(eid):
+ continue
+ end = apt_time(f.get("End-Date"))
+ if end is None and t > now() - 3600:
+ # Still going: picked up when it ends.
+ continue
+ cmd = f.get("Commandline", "")
+ installed = [p for p, auto in apt_packages(f.get("Install"))]
+ chosen = [p for p, auto in apt_packages(f.get("Install")) if not auto]
+ upgraded = [p for p, _ in apt_packages(f.get("Upgrade"))] + [p for p, _ in apt_packages(f.get("Downgrade"))]
+ removed = [p for p, _ in apt_packages(f.get("Remove"))] + [p for p, _ in apt_packages(f.get("Purge"))]
+ error = f.get("Error", "")
+ by = f.get("Requested-By", "")
+ tech = [tech_line(t, "apt", "started: " + (cmd or "an update"))]
+ if by:
+ tech.append(tech_line(t, "apt", "asked for by " + by))
+ for label, items in (("installed", installed), ("updated", upgraded), ("removed", removed)):
+ if items:
+ tech.append(tech_line(t, "apt", "%s %d: %s" % (label, len(items), ", ".join(items[:12]) + (" and more" if len(items) > 12 else ""))))
+ if error:
+ tech.append(tech_line(end or t, "apt", "error: " + error))
+ if end:
+ tech.append(tech_line(end, "apt", "finished"))
+ role = re.search(r"role='?([\w-]+)", cmd)
+ role = role.group(1) if role else ""
+ auto = "unattended-upgrade" in cmd
+ is_update = auto or role in ("update-packages", "upgrade-system") or re.search(r"\b(upgrade|full-upgrade|dist-upgrade)\b", cmd) is not None
+ # apt's hook makes the point once apt has started, so it can be
+ # stamped a little after Start-Date.
+ saved = any(r["data"].get("kind") != "manual" and -10 * 60 <= t - r["t"] <= 15 * 60 for r in restore)
+ if is_update:
+ count = len(upgraded) + len(chosen)
+ if error:
+ store.add("update-failed", t, {"count": count, "auto": auto}, tech, None, eid)
+ elif count or installed or removed:
+ store.add("updates", t, {"count": count or len(installed), "auto": auto, "restore": saved,
+ "packages": (upgraded + chosen)[:50]}, tech, None, eid)
+ elif role in ("install-packages", "install-files") and chosen:
+ names = [app_for_package(p) for p in chosen]
+ app = next((n for n in names if n), "")
+ if error:
+ store.add("install-failed", t, {"app": app, "packages": chosen[:20]}, tech, None, eid)
+ else:
+ store.add("app-installed", t, {"app": app, "id": chosen[0], "packages": chosen[:20], "via": "deb"}, tech, None, eid)
+ elif role == "remove-packages" and removed:
+ app = next((x["data"].get("app") for x in sorted(store.events.values(), key=lambda x: -x["t"])
+ if x["kind"] == "app-installed" and x["data"].get("id") in removed and x["data"].get("app")), "")
+ store.add("app-removed", t, {"app": app, "id": removed[0], "packages": removed[:20], "via": "deb"}, tech, None, eid)
+ elif installed or removed or upgraded:
+ if error:
+ store.add("install-failed", t, {"app": "", "packages": (chosen or removed)[:20]}, tech, None, eid)
+ else:
+ store.add("programs", t, {"installed": len(chosen), "removed": len(removed), "updated": len(upgraded),
+ "packages": (chosen + removed)[:20]}, tech, None, eid)
+
+
+# ------------------------------------------------------------ restore points
+
+def collect_restore(store):
+ for path in RESTORE_INDEXES:
+ index = read_json(path, {})
+ for p in index.get("points", []) if isinstance(index.get("points"), list) else []:
+ if not isinstance(p, dict):
+ continue
+ t = p.get("time")
+ if isinstance(t, str):
+ try:
+ t = time.mktime(time.strptime(t[:19], "%Y-%m-%dT%H:%M:%S"))
+ except ValueError:
+ t = None
+ if not isinstance(t, (int, float)):
+ continue
+ tech = [tech_line(t, "restore-points", "made restore point %s (%s)" % (p.get("id"), p.get("kind", "")))]
+ if p.get("label"):
+ tech.append(tech_line(t, "restore-points", "label: %s" % p["label"]))
+ store.add("restore-point", t, {"label": p.get("label") or "", "summary": p.get("summary") or "",
+ "kind": p.get("kind") or "", "point": p.get("id")}, tech, None,
+ event_id("restore", path, p.get("id"), t))
+ # Reset Wild OS makes this point first, from start-up recovery.
+ if p.get("label") == RESET_LABEL:
+ store.add("reset", t, {"point": p.get("id")}, tech, None, event_id("reset", path, p.get("id"), t))
+ labels = {}
+ for path in RESTORE_INDEXES:
+ for p in read_json(path, {}).get("points", []) or []:
+ if isinstance(p, dict):
+ labels[str(p.get("id"))] = p.get("label") or ""
+ # restore-points' own log says when the PC went back.
+ for path in RESTORE_LOGS:
+ try:
+ with open(path, encoding="utf-8", errors="replace") as f:
+ lines = f.read().splitlines()
+ except OSError:
+ continue
+ for line in lines:
+ m = re.match(r"(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d) (start-up recovery went back|went back|going back) to restore point (\d+)", line)
+ if not m:
+ continue
+ t = time.mktime(time.strptime(m.group(1), "%Y-%m-%d %H:%M:%S"))
+ how = {"going back": "staged", "went back": "done", "start-up recovery went back": "recovery"}[m.group(2)]
+ store.add("went-back", t, {"how": how, "point": m.group(3), "label": labels.get(m.group(3), "")},
+ [tech_line(t, "restore-points", line[20:])], None, event_id("went-back", line))
+
+
+# ------------------------------------------------------------ firewall
+
+def collect_firewall(store, state):
+ done = state.get("firewall", 0)
+ newest = done
+ # The open event per sender, so a burst of thousands stays quick.
+ open_events = {}
+ try:
+ f = open(FIREWALL_LOG, encoding="utf-8", errors="replace")
+ except OSError:
+ return
+ with f:
+ for line in f:
+ try:
+ b = json.loads(line)
+ t = float(b["t"])
+ except (ValueError, KeyError, TypeError):
+ continue
+ if t <= done or t < now() - KEEP:
+ continue
+ newest = max(newest, t)
+ source = str(b.get("src", ""))
+ port = num(b.get("port")) or 0
+ proto = str(b.get("proto", "tcp"))
+ tech = tech_line(t, "firewall", "turned away %s port %d from %s" % (proto, port, source))
+ if source not in open_events:
+ open_events[source] = store.latest("firewall", lambda x: x["data"].get("source") == source,
+ within=KEEP, at=t)
+ e = open_events[source]
+ if e is not None and not 0 <= t - e["data"].get("last", e["t"]) <= MERGE:
+ e = None
+ if e is not None:
+ d = e["data"]
+ d["count"] = d.get("count", 1) + 1
+ d["last"] = round(t, 3)
+ key = "%s/%d" % (proto, port)
+ if key not in d["ports"]:
+ d["ports"].append(key)
+ e["tech"] = (e["tech"] + [tech])[-12:]
+ store.touch(e)
+ continue
+ open_events[source] = store.add("firewall", t, {"source": source, "kind": b.get("kind", "other"), "device": b.get("device", ""),
+ "port": port, "proto": proto, "ports": ["%s/%d" % (proto, port)], "count": 1,
+ "last": round(t, 3)}, [tech], None, event_id("firewall", source, t))
+ state["firewall"] = newest
+
+
+# ------------------------------------------------------------ the run
+
+def collect():
+ os.makedirs(DIR, mode=0o755, exist_ok=True)
+ lock = open(LOCK, "w")
+ fcntl.flock(lock, fcntl.LOCK_EX)
+ state = read_json(STATE, {})
+ store = Store()
+ store.load()
+ store.prune()
+ # Settings shows the name of what failed, in words; the error itself
+ # goes to the system log.
+ problems = []
+ for name, step in (("the restore points", lambda: collect_restore(store)),
+ ("the system log", lambda: Journal(store, state).run()),
+ ("the record of start-ups", lambda: collect_boots(store, state)),
+ ("the list of updates", lambda: collect_apt(store)),
+ ("the firewall's list", lambda: collect_firewall(store, state))):
+ try:
+ step()
+ except (OSError, RuntimeError, ValueError, KeyError, TypeError) as e:
+ problems.append(name)
+ print("%s: %s" % (name, str(e).splitlines()[0] if str(e) else e.__class__.__name__), file=sys.stderr)
+ store.save()
+ write_file(STATE, json.dumps(state, sort_keys=True), 0o600)
+ # Settings tells people when the record could not be brought up to date.
+ status = {"t": round(now(), 3), "ok": not problems, "problems": problems}
+ write_file(os.path.join(DIR, "status.json"), json.dumps(status), 0o644)
+ return problems
+
+
+def forget_firewall():
+ """The firewall's Clear the list: History's copies go too, so clearing
+ means cleared. Blocks from before now are never read again."""
+ os.makedirs(DIR, mode=0o755, exist_ok=True)
+ lock = open(LOCK, "w")
+ fcntl.flock(lock, fcntl.LOCK_EX)
+ state = read_json(STATE, {})
+ store = Store()
+ store.load()
+ for eid, e in list(store.events.items()):
+ if e["kind"] == "firewall":
+ del store.events[eid]
+ store.changed.add(e.get("uid"))
+ state["firewall"] = now()
+ store.save()
+ write_file(STATE, json.dumps(state, sort_keys=True), 0o600)
+
+
+def main():
+ what = sys.argv[1] if len(sys.argv) > 1 else ""
+ if what == "collect":
+ problems = collect()
+ for p in problems:
+ print(p, file=sys.stderr)
+ sys.exit(1 if problems else 0)
+ if what == "lid-closed":
+ lid_closed()
+ return
+ if what == "lid-opened":
+ lid_opened()
+ return
+ if what == "forget" and sys.argv[2:] == ["firewall"]:
+ forget_firewall()
+ return
+ if what == "serve":
+ try:
+ # Settings asks each time History is opened; a run that has
+ # only just finished is answer enough.
+ status = read_json(os.path.join(DIR, "status.json"), {})
+ fresh = status.get("ok") and 0 <= now() - status.get("t", 0) < 5
+ problems = [] if fresh else collect()
+ reply = "ok\n" if not problems else "error %s\n" % "; ".join(problems)[:500]
+ except Exception as e: # noqa: BLE001 - the caller must always get an answer
+ print(str(e), file=sys.stderr)
+ reply = "error the list couldn't be brought up to date\n"
+ try:
+ sys.stdout.write(reply)
+ sys.stdout.flush()
+ except OSError:
+ pass
+ return
+ print(__doc__.strip(), file=sys.stderr)
+ sys.exit(2)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/packages/wildos-settings/data/settings-network b/packages/wildos-settings/data/settings-network
index c64f9f4..b9093b7 100644
--- a/packages/wildos-settings/data/settings-network
+++ b/packages/wildos-settings/data/settings-network
@@ -1,31 +1,24 @@
#!/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.
+# (org.wildos.settings.policy) and takes only the requests below.
#
# 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.
+#
+# The same switch is Advanced protection's "Block everything unless the VPN
+# is on", so the choice goes into its store and its vpn_only hook writes
+# /etc/wildos/vpn-kill-switch, which the wildos-network service watches.
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"
+ "kill-switch on" | "kill-switch off")
+ exec /usr/libexec/wildos/settings-advanced set vpn_only "$2"
;;
*)
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/settings-protection b/packages/wildos-settings/data/settings-protection
index 028cc95..2ca8de7 100644
--- a/packages/wildos-settings/data/settings-protection
+++ b/packages/wildos-settings/data/settings-protection
@@ -12,7 +12,9 @@
# maximum Strict, plus the firewall blocks network discovery (finding
# printers and screens), Bluetooth is off and the camera's
# driver is blocked.
-# boot Loads the firewall for the saved level (the service's job).
+# Strict and Maximum also switch on some of Advanced
+# protection's options (settings-advanced level).
+# boot Loads the firewall for the saved level (the service's job).
#
# The screen lock times that go with each level belong to the person, not
# the system, so Settings sets those itself.
@@ -23,48 +25,19 @@ LEVEL_FILE=/etc/wildos/protection-level
USBGUARD_CONF=/etc/usbguard/usbguard-daemon.conf
USBGUARD_RULES=/etc/usbguard/rules.d/50-wildos-protection.conf
CAMERA_BLOCK=/etc/modprobe.d/60-wildos-protection-camera.conf
-TABLE=wildos_protection
-# Written once nft has taken the rules, so security-status (which runs
-# without root and cannot list them) can say the firewall is up.
-FIREWALL_MARK=/run/wildos/firewall
+FIREWALL=/usr/libexec/wildos/settings-firewall
saved_level() {
level=$(cat "$LEVEL_FILE" 2>/dev/null || true)
case "$level" in strict | maximum) echo "$level" ;; *) echo standard ;; esac
}
-# Incoming connections are refused unless they answer something this
-# computer asked for. The Windows mode bridge (virbr-wildos) stays open:
-# Windows gets its address and DNS from this computer through it, and
-# Windows mode's own table (wildos_win) already limits what may come in
-# there. A drop here would be final whatever that table allows. mDNS stays
-# open at Standard and Strict, which is how printers and screens on the
-# network are found. Nothing outgoing is limited at any level.
+# The firewall's rules come from settings-firewall, which builds them from
+# the level saved here and the choices on Settings > Privacy and security >
+# Firewall. Maximum keeps network discovery off whatever is chosen there.
firewall() {
- rm -f "$FIREWALL_MARK"
- nft delete table inet "$TABLE" 2>/dev/null || true
- command -v nft >/dev/null || return 0
- discovery='udp dport 5353 accept'
- [ "$1" = maximum ] && discovery=''
- nft -f - <<EOF
-table inet $TABLE {
- chain input {
- type filter hook input priority filter; policy drop;
- ct state established,related accept
- ct state invalid drop
- iif lo accept
- iifname { "virbr-wildos", "wildos-win*" } accept
- meta l4proto ipv6-icmp accept
- icmp type { echo-reply, destination-unreachable, time-exceeded, parameter-problem } accept
- udp sport 67 udp dport 68 accept
- udp sport 547 udp dport 546 accept
- $discovery
- }
-}
-EOF
- mkdir -p "$(dirname "$FIREWALL_MARK")"
- echo "$1" > "$FIREWALL_MARK"
- chmod 644 "$FIREWALL_MARK"
+ [ -x "$FIREWALL" ] || return 0
+ "$FIREWALL" apply || true
}
# Every device attached when Strict is chosen is allowed first, so nothing
@@ -116,24 +89,32 @@ case "${1:-}" in
standard | strict | maximum)
previous=$(saved_level)
mkdir -p "$(dirname "$LEVEL_FILE")"
- firewall "$1"
+ if [ "$1" = standard ]; then
+ rm -f "$LEVEL_FILE"
+ else
+ echo "$1" > "$LEVEL_FILE"
+ fi
+ firewall
+ # For Settings > System > History.
+ if [ "$previous" != "$1" ] && command -v logger >/dev/null 2>&1; then
+ logger -t settings-protection "HISTORY {\"what\": \"level\", \"level\": \"$1\", \"from\": \"$previous\", \"by\": ${PKEXEC_UID:-0}}" || true
+ fi
usb "$1"
bluetooth "$1" "$previous"
camera "$1"
- # Strict and Maximum keep every CPU flaw protection on and the kernel's
- # 32-bit layer out, so hyper-threading and 32-bit apps go off from the
- # next start-up. Standard leaves the person's choices.
- if [ "$1" != standard ] && [ -x /usr/libexec/wildos/settings-cpu-threads ]; then
- /usr/libexec/wildos/settings-cpu-threads off || true
+ # Advanced protection: the level switches some of its options on
+ # (settings-advanced has which), never one the person set by hand.
+ if [ -x /usr/libexec/wildos/settings-advanced ]; then
+ /usr/libexec/wildos/settings-advanced level "$1" || true
fi
+ # Strict and Maximum keep the kernel's 32-bit layer out, so 32-bit
+ # apps go off from the next start-up. Every processor flaw
+ # protection and the thread choice need nothing here: 40_wildos.cfg
+ # reads the level, so going back to Standard brings back the
+ # person's own choices.
if [ "$1" != standard ] && [ -x /usr/libexec/wildos/settings-32bit ]; then
/usr/libexec/wildos/settings-32bit off || true
fi
- if [ "$1" = standard ]; then
- rm -f "$LEVEL_FILE"
- else
- echo "$1" > "$LEVEL_FILE"
- fi
# Standard relaxes a few of Kicksecure's start-up options for speed
# (/etc/default/grub.d/40_wildos.cfg reads the saved level), so
# crossing between Standard and the stricter levels rebuilds the
@@ -147,7 +128,7 @@ case "${1:-}" in
esac
;;
boot)
- firewall "$(saved_level)"
+ firewall
;;
*)
echo "usage: settings-protection standard|strict|maximum|boot" >&2
diff --git a/packages/wildos-settings/data/wildos-advanced-session b/packages/wildos-settings/data/wildos-advanced-session
new file mode 100644
index 0000000..c26597d
--- /dev/null
+++ b/packages/wildos-settings/data/wildos-advanced-session
@@ -0,0 +1,202 @@
+#!/usr/bin/python3 -I
+"""The parts of Advanced protection that belong to each person's session.
+
+Presenting mode (presenting in /etc/wildos/advanced-protection) is the
+notification server's own "do not disturb while sharing or mirroring the
+screen", which Settings > System > Notifications also switches. When the
+store's value changes (from Advanced protection, a protection level or
+Reset to defaults), each session is moved to it; a change made since on
+the Notifications page stays until the store changes again.
+
+Restart when left locked (restart_locked_hours, 0 for off): once the screen
+has been locked for the whole of that time, the PC restarts, so the disk is
+fully encrypted again and only the disk password opens it. It goes through
+Plasma's own restart, which asks every app to close first. By default an
+app holding work it hasn't saved keeps the restart from happening and it
+is tried again an hour later. With restart_locked_force on, the person's
+choice, whatever is still open two minutes after that is closed by
+restarting through logind, with the inhibitors this session's own apps
+hold overridden (logind lets a person's restart pass their own apps'
+inhibitors; one held by the system, such as an update being installed,
+still holds it, and it is tried again an hour later). Never while the PC
+runs on its battery below 20 per cent. The time counts from the lock, and
+includes time asleep.
+"""
+
+import os
+import subprocess
+import sys
+import time
+
+from gi.repository import Gio, GLib
+
+STORE_DIR = "/etc/wildos"
+STORE = os.path.join(STORE_DIR, "advanced-protection")
+STATE_DIR = os.path.join(os.environ.get("XDG_STATE_HOME") or os.path.expanduser("~/.local/state"), "wildos")
+APPLIED = os.path.join(STATE_DIR, "advanced-presenting")
+
+CHECK = 60
+RETRY = 3600
+# How long Plasma's restart gets to close every app before a forced one.
+GRACE = 120
+LOW_BATTERY = 20
+
+UPOWER = "org.freedesktop.UPower"
+
+
+def log(*args):
+ print(*args, flush=True)
+
+
+def store():
+ values = {"presenting": "on", "restart_locked_hours": "0", "restart_locked_force": "off"}
+ try:
+ with open(STORE) as f:
+ for line in f:
+ key, sep, value = line.strip().partition("=")
+ if sep and key in values:
+ values[key] = value
+ except OSError:
+ pass
+ return values
+
+
+def since_start():
+ """Seconds since start-up, counting sleep, which the clock can't move."""
+ return time.clock_gettime(time.CLOCK_BOOTTIME)
+
+
+class Session:
+ def __init__(self):
+ self.session = Gio.bus_get_sync(Gio.BusType.SESSION, None)
+ self.system = Gio.bus_get_sync(Gio.BusType.SYSTEM, None)
+ self.values = store()
+ self.locked_since = None
+ self.next_try = 0
+
+ self.monitor = Gio.File.new_for_path(STORE_DIR).monitor_directory(Gio.FileMonitorFlags.WATCH_MOVES, None)
+ self.monitor.connect("changed", self._store_changed)
+ self.presenting()
+
+ self.session.signal_subscribe("org.freedesktop.ScreenSaver", "org.freedesktop.ScreenSaver", "ActiveChanged",
+ "/ScreenSaver", None, Gio.DBusSignalFlags.NONE, self._lock_changed, None)
+ self._locked(self._screen_locked())
+ GLib.timeout_add_seconds(CHECK, self._tick)
+
+ def _store_changed(self, monitor, file, other, event):
+ names = {f.get_basename() for f in (file, other) if f is not None}
+ if "advanced-protection" in names:
+ self.values = store()
+ self.presenting()
+
+ def presenting(self):
+ want = self.values["presenting"]
+ if want not in ("on", "off"):
+ return
+ try:
+ with open(APPLIED) as f:
+ if f.read().strip() == want:
+ return
+ first = False
+ except OSError:
+ first = True
+ # The first time, whatever the person already chose on the
+ # Notifications page stays: only later changes to the store move it.
+ if not first:
+ value = "true" if want == "on" else "false"
+ for key in ("WhenScreenSharing", "WhenScreensMirrored"):
+ try:
+ subprocess.run(["kwriteconfig6", "--file", "plasmanotifyrc", "--group", "DoNotDisturb", "--key", key,
+ "--type", "bool", "--notify", value], check=True, timeout=10)
+ except (OSError, subprocess.SubprocessError) as e:
+ log("could not set presenting mode:", e)
+ return
+ log("presenting mode", want)
+ os.makedirs(STATE_DIR, exist_ok=True)
+ with open(APPLIED + ".new", "w") as f:
+ f.write(want + "\n")
+ os.replace(APPLIED + ".new", APPLIED)
+
+ def _screen_locked(self):
+ try:
+ reply = self.session.call_sync("org.freedesktop.ScreenSaver", "/ScreenSaver", "org.freedesktop.ScreenSaver",
+ "GetActive", None, GLib.VariantType("(b)"), Gio.DBusCallFlags.NONE, 3000, None)
+ return reply.unpack()[0]
+ except GLib.Error:
+ return False
+
+ def _lock_changed(self, conn, sender, path, iface, signal, params, data):
+ self._locked(params.unpack()[0])
+
+ def _locked(self, locked):
+ if locked and self.locked_since is None:
+ self.locked_since = since_start()
+ self.next_try = 0
+ elif not locked:
+ self.locked_since = None
+
+ def _battery_low(self):
+ try:
+ on_battery = self.system.call_sync(UPOWER, "/org/freedesktop/UPower", "org.freedesktop.DBus.Properties", "Get",
+ GLib.Variant("(ss)", (UPOWER, "OnBattery")), GLib.VariantType("(v)"),
+ Gio.DBusCallFlags.NONE, 3000, None).unpack()[0]
+ if not on_battery:
+ return False
+ percent = self.system.call_sync(UPOWER, "/org/freedesktop/UPower/devices/DisplayDevice",
+ "org.freedesktop.DBus.Properties", "Get",
+ GLib.Variant("(ss)", (UPOWER + ".Device", "Percentage")), GLib.VariantType("(v)"),
+ Gio.DBusCallFlags.NONE, 3000, None).unpack()[0]
+ return percent < LOW_BATTERY
+ except GLib.Error:
+ return False
+
+ def _tick(self):
+ try:
+ hours = int(self.values["restart_locked_hours"])
+ except ValueError:
+ hours = 0
+ if hours <= 0 or self.locked_since is None:
+ return True
+ now = since_start()
+ if now - self.locked_since < hours * 3600 or now < self.next_try:
+ return True
+ if self._battery_low():
+ return True
+ # Still locked right now, not just as last heard.
+ if not self._screen_locked():
+ self.locked_since = None
+ return True
+ self.next_try = now + RETRY
+ log("locked for %d hours: restarting, once every app has closed" % hours)
+ self.session.call("org.kde.Shutdown", "/Shutdown", "org.kde.Shutdown", "logoutAndReboot", None, None,
+ Gio.DBusCallFlags.NONE, -1, None, None, None)
+ if self.values["restart_locked_force"] == "on":
+ GLib.timeout_add_seconds(GRACE, self._force)
+ return True
+
+ def _force(self):
+ """Still here after the grace period: Plasma's restart was held up
+ by an app, or refused."""
+ if self.values["restart_locked_force"] != "on" or self.locked_since is None:
+ return False
+ if self._battery_low() or not self._screen_locked():
+ return False
+ log("an app kept the restart from happening: restarting anyway")
+ try:
+ subprocess.run(["systemctl", "reboot", "--check-inhibitors=no"], check=True, timeout=30)
+ except (OSError, subprocess.SubprocessError) as e:
+ log("could not restart:", e)
+ return False
+
+
+def main():
+ if len(sys.argv) > 1:
+ print("usage: wildos-advanced-session", file=sys.stderr)
+ return 2
+ Session()
+ GLib.MainLoop().run()
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/packages/wildos-settings/data/wildos-advanced-session.service b/packages/wildos-settings/data/wildos-advanced-session.service
new file mode 100644
index 0000000..76af1b3
--- /dev/null
+++ b/packages/wildos-settings/data/wildos-advanced-session.service
@@ -0,0 +1,15 @@
+[Unit]
+Description=Advanced protection in this session: presenting mode and restart when left locked
+Documentation=file:///usr/libexec/wildos/wildos-advanced-session
+PartOf=graphical-session.target
+After=graphical-session.target
+# The sign-in screen's account has no session of its own to look after.
+ConditionUser=!@system
+
+[Service]
+ExecStart=/usr/libexec/wildos/wildos-advanced-session
+Restart=on-failure
+RestartSec=5
+
+[Install]
+WantedBy=graphical-session.target
diff --git a/packages/wildos-settings/data/wildos-devices.socket b/packages/wildos-settings/data/wildos-devices.socket
new file mode 100644
index 0000000..51c890d
--- /dev/null
+++ b/packages/wildos-settings/data/wildos-devices.socket
@@ -0,0 +1,13 @@
+[Unit]
+Description=Settings > System > Devices: firmware and drive health
+
+[Socket]
+# Anyone signed in may ask. The answer holds which devices lacked firmware
+# at start-up and each internal drive's health, nothing personal.
+ListenStream=/run/wildos-devices.sock
+SocketMode=0666
+Accept=yes
+MaxConnections=4
+
+[Install]
+WantedBy=sockets.target
diff --git a/packages/wildos-settings/data/[email protected] b/packages/wildos-settings/data/[email protected]
new file mode 100644
index 0000000..bf3876a
--- /dev/null
+++ b/packages/wildos-settings/data/[email protected]
@@ -0,0 +1,14 @@
+[Unit]
+Description=Settings > System > Devices: firmware and drive health
+Documentation=file:///usr/libexec/wildos/settings-devices
+
+[Service]
+Type=oneshot
+ExecStart=/usr/libexec/wildos/settings-devices
+StandardInput=socket
+StandardOutput=socket
+StandardError=journal
+Nice=10
+ProtectHome=yes
+PrivateNetwork=yes
+NoNewPrivileges=yes
diff --git a/packages/wildos-settings/data/wildos-free-space.service b/packages/wildos-settings/data/wildos-free-space.service
new file mode 100644
index 0000000..bfbbc29
--- /dev/null
+++ b/packages/wildos-settings/data/wildos-free-space.service
@@ -0,0 +1,9 @@
+[Unit]
+Description=Free up space when the disk is nearly full
+Documentation=file:///usr/libexec/wildos/settings-free-space
+
+[Service]
+Type=oneshot
+ExecStart=/usr/libexec/wildos/settings-free-space run --auto
+Nice=10
+IOSchedulingClass=idle
diff --git a/packages/wildos-settings/data/wildos-free-space.timer b/packages/wildos-settings/data/wildos-free-space.timer
new file mode 100644
index 0000000..67dc827
--- /dev/null
+++ b/packages/wildos-settings/data/wildos-free-space.timer
@@ -0,0 +1,12 @@
+[Unit]
+Description=Check now and then whether the disk is nearly full
+
+# Turned on and off per person from Settings > System > Storage > Free up
+# space (Tidy up automatically). Each run only looks at free space unless
+# less than 10% of the disk is free.
+[Timer]
+OnStartupSec=10min
+OnUnitActiveSec=30min
+
+[Install]
+WantedBy=timers.target
diff --git a/packages/wildos-settings/data/wildos-history.service b/packages/wildos-settings/data/wildos-history.service
new file mode 100644
index 0000000..6cb4728
--- /dev/null
+++ b/packages/wildos-settings/data/wildos-history.service
@@ -0,0 +1,9 @@
+[Unit]
+Description=Keep Settings > System > History up to date
+Documentation=file:///usr/libexec/wildos/settings-history
+
+[Service]
+Type=oneshot
+ExecStart=/usr/libexec/wildos/settings-history collect
+Nice=10
+IOSchedulingClass=idle
diff --git a/packages/wildos-settings/data/wildos-history.socket b/packages/wildos-settings/data/wildos-history.socket
new file mode 100644
index 0000000..b352b5d
--- /dev/null
+++ b/packages/wildos-settings/data/wildos-history.socket
@@ -0,0 +1,13 @@
+[Unit]
+Description=Bring Settings > System > History up to date when it opens
+
+[Socket]
+# Anyone signed in may ask; the answer is only "ok", and the records stay
+# where each account can read its own.
+ListenStream=/run/wildos-history.sock
+SocketMode=0666
+Accept=yes
+MaxConnections=4
+
+[Install]
+WantedBy=sockets.target
diff --git a/packages/wildos-settings/data/wildos-history.timer b/packages/wildos-settings/data/wildos-history.timer
new file mode 100644
index 0000000..c0942d6
--- /dev/null
+++ b/packages/wildos-settings/data/wildos-history.timer
@@ -0,0 +1,12 @@
+[Unit]
+Description=Keep Settings > System > History up to date
+
+[Timer]
+# Often enough that nothing ages out of the system log or the firewall's
+# own week-long list before History has a copy, even if Settings is never
+# opened.
+OnBootSec=5min
+OnUnitActiveSec=1h
+
+[Install]
+WantedBy=timers.target
diff --git a/packages/wildos-settings/data/[email protected] b/packages/wildos-settings/data/[email protected]
new file mode 100644
index 0000000..db5c462
--- /dev/null
+++ b/packages/wildos-settings/data/[email protected]
@@ -0,0 +1,12 @@
+[Unit]
+Description=Bring Settings > System > History up to date
+Documentation=file:///usr/libexec/wildos/settings-history
+
+[Service]
+Type=oneshot
+ExecStart=/usr/libexec/wildos/settings-history serve
+StandardInput=socket
+StandardOutput=socket
+StandardError=journal
+Nice=10
+IOSchedulingClass=idle
diff --git a/packages/wildos-settings/data/wildos-radios-idle b/packages/wildos-settings/data/wildos-radios-idle
new file mode 100644
index 0000000..ddfcafd
--- /dev/null
+++ b/packages/wildos-settings/data/wildos-radios-idle
@@ -0,0 +1,127 @@
+#!/usr/bin/python3 -I
+"""Advanced protection's "Wi-Fi and Bluetooth switch themselves off".
+
+Wi-Fi that has been on for 30 minutes without being connected to a network
+is switched off (NetworkManager's WirelessEnabled), and so is Bluetooth
+that has been on for 30 minutes with no device connected (BlueZ's Powered,
+adapter by adapter). Each is timed on its own. A radio switched on again,
+by hand or by anything else, gets a fresh 30 minutes, and so does
+everything after the PC wakes from sleep: the time asleep doesn't count,
+and a network needs a moment to join after waking.
+
+Runs only while radios_idle_off is on (its hook enables this service).
+"""
+
+import sys
+import time
+
+from gi.repository import Gio, GLib
+
+IDLE = 30 * 60
+CHECK = 30
+
+NM = ("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager", "org.freedesktop.NetworkManager")
+NM_DEVICE = "org.freedesktop.NetworkManager.Device"
+NM_WIFI = 2
+NM_ACTIVATED = 100
+BLUEZ = "org.bluez"
+LOGIN1 = ("org.freedesktop.login1", "/org/freedesktop/login1", "org.freedesktop.login1.Manager")
+
+
+def log(*args):
+ print(*args, flush=True)
+
+
+class Radios:
+ def __init__(self):
+ self.bus = Gio.bus_get_sync(Gio.BusType.SYSTEM, None)
+ # When each radio was last seen on and connected, or switched on.
+ self.wifi_since = None
+ self.adapters = {}
+ self.bus.signal_subscribe(LOGIN1[0], LOGIN1[2], "PrepareForSleep", LOGIN1[1], None,
+ Gio.DBusSignalFlags.NONE, self._sleep, None)
+ GLib.timeout_add_seconds(CHECK, self._tick)
+ self._tick()
+
+ def _call(self, name, path, iface, method, args, reply_type):
+ try:
+ return self.bus.call_sync(name, path, iface, method, args,
+ GLib.VariantType(reply_type) if reply_type else None,
+ Gio.DBusCallFlags.NONE, 5000, None)
+ except GLib.Error:
+ return None
+
+ def _prop(self, name, path, iface, prop):
+ reply = self._call(name, path, "org.freedesktop.DBus.Properties", "Get",
+ GLib.Variant("(ss)", (iface, prop)), "(v)")
+ return reply.unpack()[0] if reply else None
+
+ def _set(self, name, path, iface, prop, value):
+ return self._call(name, path, "org.freedesktop.DBus.Properties", "Set",
+ GLib.Variant("(ssv)", (iface, prop, value)), None) is not None
+
+ def _sleep(self, conn, sender, path, iface, signal, params, data):
+ if not params.unpack()[0]:
+ now = time.monotonic()
+ if self.wifi_since is not None:
+ self.wifi_since = now
+ self.adapters = {a: now for a in self.adapters}
+
+ def _wifi(self, now):
+ if not self._prop(NM[0], NM[1], NM[2], "WirelessEnabled"):
+ self.wifi_since = None
+ return
+ connected = False
+ for path in self._prop(NM[0], NM[1], NM[2], "Devices") or []:
+ if self._prop(NM[0], path, NM_DEVICE, "DeviceType") == NM_WIFI \
+ and self._prop(NM[0], path, NM_DEVICE, "State") == NM_ACTIVATED:
+ connected = True
+ if connected or self.wifi_since is None:
+ self.wifi_since = now
+ elif now - self.wifi_since >= IDLE:
+ if self._set(NM[0], NM[1], NM[2], "WirelessEnabled", GLib.Variant("b", False)):
+ log("Wi-Fi switched off: not connected for 30 minutes")
+ self.wifi_since = None
+
+ def _bluetooth(self, now):
+ reply = self._call(BLUEZ, "/", "org.freedesktop.DBus.ObjectManager", "GetManagedObjects", None,
+ "(a{oa{sa{sv}}})")
+ objects = reply.unpack()[0] if reply else {}
+ powered = {}
+ busy = set()
+ for path, ifaces in objects.items():
+ adapter = ifaces.get("org.bluez.Adapter1")
+ if adapter is not None and adapter.get("Powered"):
+ powered[path] = True
+ device = ifaces.get("org.bluez.Device1")
+ if device is not None and device.get("Connected") and device.get("Adapter"):
+ busy.add(device["Adapter"])
+ for path in list(self.adapters):
+ if path not in powered:
+ del self.adapters[path]
+ for path in powered:
+ if path in busy or path not in self.adapters:
+ self.adapters[path] = now
+ elif now - self.adapters[path] >= IDLE:
+ if self._set(BLUEZ, path, "org.bluez.Adapter1", "Powered", GLib.Variant("b", False)):
+ log("Bluetooth switched off on %s: nothing connected for 30 minutes" % path)
+ del self.adapters[path]
+
+ def _tick(self):
+ now = time.monotonic()
+ self._wifi(now)
+ self._bluetooth(now)
+ return True
+
+
+def main():
+ if len(sys.argv) > 1:
+ print("usage: wildos-radios-idle", file=sys.stderr)
+ return 2
+ Radios()
+ GLib.MainLoop().run()
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/packages/wildos-settings/data/wildos-radios-idle.service b/packages/wildos-settings/data/wildos-radios-idle.service
new file mode 100644
index 0000000..3bcba96
--- /dev/null
+++ b/packages/wildos-settings/data/wildos-radios-idle.service
@@ -0,0 +1,12 @@
+[Unit]
+Description=Switch Wi-Fi and Bluetooth off when nothing has been connected for 30 minutes
+Documentation=file:///usr/libexec/wildos/wildos-radios-idle
+After=NetworkManager.service bluetooth.service dbus.service
+
+[Service]
+ExecStart=/usr/libexec/wildos/wildos-radios-idle
+Restart=on-failure
+RestartSec=5
+
+[Install]
+WantedBy=multi-user.target
diff --git a/packages/wildos-settings/data/wildos-usb-lock b/packages/wildos-settings/data/wildos-usb-lock
new file mode 100644
index 0000000..9c09b24
--- /dev/null
+++ b/packages/wildos-settings/data/wildos-usb-lock
@@ -0,0 +1,229 @@
+#!/usr/bin/python3 -I
+"""Advanced protection's "Ignore new USB devices while locked".
+
+With USB protection on (USBGuard), memory sticks, keyboards, mice, webcams
+and audio devices normally work as soon as they are plugged in, and
+anything else waits to be allowed from the shield on the taskbar. While the
+screen of the signed-in person is locked, this holds back every device
+plugged in, of any kind: USBGuard's InsertedDevicePolicy goes to block for
+as long as the lock lasts.
+
+Devices already connected keep working throughout. One that drops off and
+comes back by itself while the PC is locked (a keyboard's receiver waking
+up with the PC, a hub resetting) is let back in when it matches a device
+that was there when the screen locked: same id, serial number, name and
+port.
+
+At sign-in the policy goes back to what it was, and each device that
+arrived during the lock is reconnected on its port, so USBGuard decides on
+it as if it had just been plugged in: a memory stick then works, and
+anything else waits to be allowed, with the taskbar asking about it now
+that someone is there (security-notify waits for the unlock).
+
+Does nothing while usb_locked is off in /etc/wildos/advanced-protection
+or USBGuard is not running.
+"""
+
+import os
+import re
+import subprocess
+import sys
+
+from gi.repository import Gio, GLib
+
+STORE = "/etc/wildos/advanced-protection"
+USBGUARD_CONF = "/etc/usbguard/usbguard-daemon.conf"
+LOGIN1 = "org.freedesktop.login1"
+POLL = 2
+
+# "12: block id 046d:c52b serial "..." name "..." hash ... via-port "1-2" ..."
+DEVICE = re.compile(r'^(\d+): (allow|block|reject) (.*)$')
+
+
+def log(*args):
+ print(*args, flush=True)
+
+
+def store_on():
+ value = "on"
+ try:
+ with open(STORE) as f:
+ for line in f:
+ if line.startswith("usb_locked="):
+ value = line.split("=", 1)[1].strip()
+ except OSError:
+ pass
+ return value != "off"
+
+
+def usbguard(*args):
+ try:
+ out = subprocess.run(["usbguard", *args], capture_output=True, text=True, timeout=15)
+ except (OSError, subprocess.TimeoutExpired) as e:
+ log("usbguard", " ".join(args), "failed:", e)
+ return None
+ if out.returncode != 0:
+ return None
+ return out.stdout
+
+
+def field(rule, name):
+ m = re.search(r'\b%s "((?:[^"\\]|\\.)*)"' % name, rule) or re.search(r'\b%s (\S+)' % name, rule)
+ return m.group(1) if m else ""
+
+
+def identity(rule):
+ return (field(rule, "id"), field(rule, "serial"), field(rule, "name"), field(rule, "via-port"))
+
+
+def devices():
+ out = usbguard("list-devices")
+ if out is None:
+ return None
+ found = []
+ for line in out.splitlines():
+ m = DEVICE.match(line.strip())
+ if m:
+ found.append((m.group(1), m.group(2), m.group(3)))
+ return found
+
+
+def configured_policy():
+ try:
+ with open(USBGUARD_CONF) as f:
+ for line in f:
+ if line.startswith("InsertedDevicePolicy="):
+ return line.split("=", 1)[1].strip() or "apply-policy"
+ except OSError:
+ pass
+ return "apply-policy"
+
+
+def reconnect(port):
+ """Disconnects and reconnects the device on PORT without touching it,
+ so the kernel announces it again and USBGuard decides afresh."""
+ if not re.fullmatch(r"\d+-\d+(\.\d+)*", port):
+ return
+ # The port's own folder: the device's goes away once it is disconnected.
+ switch = os.path.realpath("/sys/bus/usb/devices/%s/port" % port) + "/disable"
+ try:
+ with open(switch, "w") as f:
+ f.write("1")
+ GLib.timeout_add(500, lambda: (write_quietly(switch, "0"), False)[1])
+ except OSError as e:
+ log("could not reconnect", port, e)
+
+
+def write_quietly(path, text):
+ try:
+ with open(path, "w") as f:
+ f.write(text)
+ except OSError as e:
+ log("could not write", path, e)
+
+
+class Watcher:
+ def __init__(self):
+ self.bus = Gio.bus_get_sync(Gio.BusType.SYSTEM, None)
+ self.locked = False
+ self.known = set()
+ self.arrived = set()
+ self.restore = None
+ self.timer = 0
+ self.bus.signal_subscribe(LOGIN1, "org.freedesktop.DBus.Properties", "PropertiesChanged", None, None,
+ Gio.DBusSignalFlags.NONE, self._changed, None)
+ self._check()
+
+ def _changed(self, conn, sender, path, iface, signal, params, data):
+ name, changed, _ = params.unpack()
+ if "LockedHint" in changed or "ActiveSession" in changed or "Active" in changed:
+ self._check()
+
+ def _get(self, path, iface, prop):
+ try:
+ reply = self.bus.call_sync(LOGIN1, path, "org.freedesktop.DBus.Properties", "Get",
+ GLib.Variant("(ss)", (iface, prop)), GLib.VariantType("(v)"),
+ Gio.DBusCallFlags.NONE, 3000, None)
+ return reply.unpack()[0]
+ except GLib.Error:
+ return None
+
+ def _screen_locked(self):
+ """The person at seat0 has their screen locked. The sign-in screen
+ is not a lock: someone may need a keyboard to sign in."""
+ active = self._get("/org/freedesktop/login1/seat/seat0", "org.freedesktop.login1.Seat", "ActiveSession")
+ if not active or not active[1] or active[1] == "/":
+ return False
+ session = active[1]
+ if self._get(session, "org.freedesktop.login1.Session", "Class") != "user":
+ return False
+ return bool(self._get(session, "org.freedesktop.login1.Session", "LockedHint"))
+
+ def _check(self):
+ locked = self._screen_locked() and store_on()
+ if locked and not self.locked:
+ self._lock()
+ elif not locked and self.locked:
+ self._unlock()
+
+ def _lock(self):
+ present = devices()
+ if present is None:
+ return
+ self.known = {identity(rule) for num, target, rule in present if target == "allow"}
+ self.arrived = set()
+ current = (usbguard("get-parameter", "InsertedDevicePolicy") or "").strip()
+ self.restore = current if current and current != "block" else configured_policy()
+ if usbguard("set-parameter", "InsertedDevicePolicy", "block") is None:
+ log("USBGuard did not take the lock policy")
+ return
+ self.locked = True
+ # USBGuard says nothing over IPC that would wake this, so the
+ # devices are looked at every couple of seconds, only while locked.
+ self.timer = GLib.timeout_add_seconds(POLL, self._tick)
+ log("screen locked: new USB devices are held back")
+
+ def _unlock(self):
+ self.locked = False
+ if self.timer:
+ GLib.source_remove(self.timer)
+ self.timer = 0
+ usbguard("set-parameter", "InsertedDevicePolicy", self.restore or configured_policy())
+ log("signed in again: USB devices follow the usual policy")
+ for num, target, rule in devices() or []:
+ port = field(rule, "via-port")
+ if target != "allow" and port in self.arrived:
+ reconnect(port)
+ self.arrived = set()
+
+ def _tick(self):
+ for num, target, rule in devices() or []:
+ if target == "allow":
+ continue
+ if identity(rule) in self.known:
+ usbguard("allow-device", num)
+ else:
+ self.arrived.add(field(rule, "via-port"))
+ return True
+
+
+def main():
+ if len(sys.argv) > 1:
+ print("usage: wildos-usb-lock", file=sys.stderr)
+ return 2
+ watcher = Watcher()
+ loop = GLib.MainLoop()
+
+ def stop(*_):
+ if watcher.locked:
+ watcher._unlock()
+ loop.quit()
+ return False
+
+ GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, 15, stop)
+ loop.run()
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/packages/wildos-settings/data/wildos-usb-lock.service b/packages/wildos-settings/data/wildos-usb-lock.service
new file mode 100644
index 0000000..96f807c
--- /dev/null
+++ b/packages/wildos-settings/data/wildos-usb-lock.service
@@ -0,0 +1,12 @@
+[Unit]
+Description=Hold back new USB devices while the screen is locked
+Documentation=file:///usr/libexec/wildos/wildos-usb-lock
+After=usbguard.service dbus.service systemd-logind.service
+
+[Service]
+ExecStart=/usr/libexec/wildos/wildos-usb-lock
+Restart=on-failure
+RestartSec=2
+
+[Install]
+WantedBy=multi-user.target
diff --git a/packages/wildos-settings/debian/changelog b/packages/wildos-settings/debian/changelog
index 0afaaca..7f7d73b 100644
--- a/packages/wildos-settings/debian/changelog
+++ b/packages/wildos-settings/debian/changelog
@@ -1,3 +1,285 @@
+wildos-settings (0.1.55) trixie; urgency=medium
+
+ * The fingerprint keeps working after a restart again: asking for the
+ password after a restart or every so many hours is off unless you
+ switch it on in Advanced protection (Strict and Maximum switch it on).
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 16:00:00 +0000
+
+wildos-settings (0.1.54) trixie; urgency=medium
+
+ * Privacy and security > Advanced protection: extra protection for
+ people who want it, in one page. Ignore new USB devices while
+ locked, the fingerprint needing your password after a restart and
+ every so many hours, restart when left locked, Wi-Fi and Bluetooth
+ switching themselves off, encrypted DNS with a choice of Quad9,
+ Mullvad or Cloudflare, block
+ everything unless the VPN is on, the clipboard forgetting passwords,
+ presenting mode and password-locked USB sticks, with Reset to
+ defaults.
+ * Strict protection also asks for the password after 24 hours of
+ fingerprint sign-in and restarts a PC left locked for 18 hours.
+ Maximum asks for it after 12 hours, and also switches Wi-Fi and
+ Bluetooth off when unused and encrypts DNS on every network.
+ Anything you set on Advanced protection stays as you set it.
+ * Block new USB devices and the VPN kill switch are the same switches
+ as their rows on Advanced protection.
+ * Encrypted DNS can be switched off on Advanced protection, which puts
+ each network back on its own DNS, unencrypted. Switching it back on
+ gives every network the encryption it had before.
+ * Restart when left locked can close open apps anyway after the time is
+ up, for when an app with unsaved work would otherwise keep the PC from
+ restarting. Unsaved work in those apps is lost. Waiting for apps to
+ close stays the default.
+ * History lists each time an app used the camera or microphone, with when
+ it started and stopped. This week on the taskbar's camera and
+ microphone light opens History showing just those.
+ * Accounts leaves out the Guest account while Guest session is on, so
+ it can't be made an administrator or deleted by hand.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 14:56:10 +0000
+
+wildos-settings (0.1.53) trixie; urgency=medium
+
+ * Add a keyboard finds layouts by country, language and key order too:
+ Belgium, Dutch or AZERTY find Belgian, not only its own name.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 12:20:00 +0000
+
+wildos-settings (0.1.52) trixie; urgency=medium
+
+ * Password boxes for other accounts and Wi-Fi take only what is typed:
+ nothing can be pasted into them.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 10:30:00 +0000
+
+wildos-settings (0.1.51) trixie; urgency=medium
+
+ * Password boxes in Sign-in options and fingerprint setup take only what
+ is typed: nothing can be pasted into them.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 09:45:00 +0000
+
+wildos-settings (0.1.50) trixie; urgency=medium
+
+ * The password box in fingerprint setup has the right-click menu
+ with Paste and Select all, and the technical detail of a History
+ event can be selected and copied from one. Pasting a colour into
+ the underglow box from its menu is no longer undone.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 08:54:22 +0000
+
+wildos-settings (0.1.49) trixie; urgency=medium
+
+ * Windows mode: Use a licence on my Microsoft account, with the steps
+ for Microsoft's activation troubleshooter.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 08:39:52 +0000
+
+wildos-settings (0.1.48) trixie; urgency=medium
+
+ * Updates waits for the clock when it is hours behind at start-up (seen
+ on a PC whose hardware clock kept local time for Windows): every update
+ then looks signed in the future, sqv's "Not live until". The check
+ waits for sdwdate to set the clock through Tor, up to 15 minutes, says
+ so while it waits, and checks again as soon as it has. If the clock is
+ still wrong, the page says how far behind it is at least and offers
+ Date and time.
+ * Date and time shows that the clock is set automatically through Tor
+ while sdwdate runs, instead of "No time service is installed".
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 08:33:55 +0000
+
+wildos-settings (0.1.47) trixie; urgency=medium
+
+ * Steam and 32-bit apps: games run through Proton use the kernel's
+ Windows-style locking (ntsync) for smoother frame times.
+ * Recovery: Open Backup opens Backup again.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 22:47:33 +0000
+
+wildos-settings (0.1.46) trixie; urgency=medium
+
+ * Storage > Free up space: clears the Recycle Bins on internal drives,
+ old restore points (the newest three stay), update files already
+ installed, unused Flatpak runtimes, old kernels and app caches, and on
+ request leftovers of removed apps, unused space inside Windows mode
+ (Windows TRIMs it while it is on) and large old downloads chosen in
+ Review. Each item shows its real size; files open apps are using stay.
+ * Tidy up automatically clears the ticked items when less than 10% of the
+ disk is free, says what it removed, and History shows it.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 19:54:39 +0000
+
+wildos-settings (0.1.45) trixie; urgency=medium
+
+ * Settings > Updates and the Updates icon on the taskbar share one check
+ and always show the same state, including a failed check's reason.
+ * A signature dated after the clock (sdwdate set it back after start-up)
+ is retried quietly even when PackageKit calls it a signing error.
+ * With no connection at all, after the first minutes since start-up, the
+ check says "not connected" at once instead of waiting minutes on Tor.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 19:23:03 +0000
+
+wildos-settings (0.1.44) trixie; urgency=medium
+
+ * Turning the firewall off asks for the password every time
+ (settings-firewall-off, its own polkit action with auth_admin), and the
+ security tiles update as soon as the switch changes.
+ * What the firewall blocked offers Allow for every device on this
+ network, as the design shows, not only where an app is listening.
+ * Network discovery lets in mDNS (5353) only, as before the Firewall
+ page; SSDP and WS-Discovery are no longer opened.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 19:01:35 +0000
+
+wildos-settings (0.1.43) trixie; urgency=medium
+
+ * Personalisation > Taskbar has an End task switch, off by default, that
+ adds End task to an app's right-click menu on the taskbar. Searching
+ for "end task", "kill" or "force close" finds it.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 18:44:54 +0000
+
+wildos-settings (0.1.42) trixie; urgency=medium
+
+ * Settings > Accessibility > Pointer has a fifth choice, Your own: use a
+ Windows pointer (.cur, or an animated .ani), a Windows pointer pack (a
+ .zip or its install.inf, with every role it covers: help, busy, text,
+ resize, link and the rest), or a PNG or SVG picture with the spot it
+ points from. Roles the file doesn't cover stay white, the size slider
+ works with it, and X11 apps use it too. A file that isn't a pointer is
+ refused without changing anything.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 18:17:04 +0000
+
+wildos-settings (0.1.41) trixie; urgency=medium
+
+ * Updates no longer says it could not check right after start-up. A
+ check that fails while the connection, Tor or the clock is still
+ settling (the clock can be set back a minute or two at start-up, which
+ makes a fresh release look signed in the future) tries again by itself
+ for about three minutes. When it still fails, the page says why: no
+ internet, Wild OS's update server, Debian's updates through Tor,
+ another install still running or a signature problem, with Try again
+ and a link to copy the technical details.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 18:00:15 +0000
+
+wildos-settings (0.1.40) trixie; urgency=medium
+
+ * Printers and scanners looks for printers and scanners as soon as it
+ opens and offers each one it finds with a single Add. Printers that
+ need no driver, and network scanners, work straight away. Each printer
+ in the list says whether it is the default, whether it also scans and,
+ where the printer reports it, how much ink or toner is left. New help
+ for adding a printer by its address, a printer with only a Windows
+ driver, printing a test page and scanning with Capture.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 16:50:00 +0000
+
+wildos-settings (0.1.39) trixie; urgency=medium
+
+ * History no longer says the PC didn't shut down properly after a normal
+ shutdown or restart whose last log lines were cut short. Start-ups
+ already listed that way are checked again.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 18:00:00 +0000
+
+wildos-settings (0.1.38) trixie; urgency=medium
+
+ * History also says when the PC started and how long it took, when it
+ shut down, restarted or slept and why, when it didn't shut down
+ properly, and when the lid was closed but it stayed on, with the
+ reason. It shows sign-ins and unlocks with a fingerprint, fingerprints
+ that weren't recognised, disk errors, Windows mode failing to start,
+ going back to a restore point, Reset, and changes to the firewall and
+ the protection level.
+ * Clear the list in What the firewall blocked clears History's copies
+ too.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 16:07:27 +0000
+
+wildos-settings (0.1.37) trixie; urgency=medium
+
+ * Firewall: a network you join counts as Home only once you choose Home
+ for it. Until then only network discovery gets in, so file sharing,
+ Remote Desktop, SSH and ports you allowed at home never open on a cafe
+ or hotel Wi-Fi.
+ * Firewall: devices joining this PC's hotspot get an address again.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 16:45:00 +0000
+
+wildos-settings (0.1.36) trixie; urgency=medium
+
+ * Privacy and security has Extra processor protection, off by default:
+ every processor flaw protection forced on and one thread per core.
+ Strict and Maximum include it.
+ * Use every processor thread is on by default where the processor is
+ safe for it.
+ * Steam and 32-bit apps also stops newer Intel processors slowing down
+ games that use split locks.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 16:30:00 +0000
+
+wildos-settings (0.1.35) trixie; urgency=medium
+
+ * System > Devices: every device in this PC by its plain name, with what
+ it really is, the driver running it and where it is connected. Devices
+ with no driver, on a stand-in driver, short of firmware or not set up
+ come first, each with the button that fixes it. The internal drive
+ shows its own health check. Check again looks once more.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 15:04:10 +0000
+
+wildos-settings (0.1.34) trixie; urgency=medium
+
+ * System > History: what happened on this PC in plain words, newest
+ first: apps that closed unexpectedly, sign-ins, wrong passwords, USB
+ drives, updates, restore points, apps installed and removed, Backup and
+ what the firewall blocked. Details says what happened, what Wild OS did
+ and what you can do, and can send it with Report a problem. Kept on
+ this PC for 30 days; nothing is sent anywhere.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 14:12:47 +0000
+
+wildos-settings (0.1.33) trixie; urgency=medium
+
+ * Installed apps uninstalls Wild OS's own apps and Windows apps
+ installed through Windows mode.
+ * Settings can't be removed, even from a terminal.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 13:36:51 +0000
+
+wildos-settings (0.1.32) trixie; urgency=medium
+
+ * Privacy and security > Firewall: switch the firewall off and on, mark a
+ network Home or Public, turn network discovery, file sharing, Remote
+ Desktop and SSH on or off, allow an app or port for this network, one
+ device or anyone, and see what the firewall blocked.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 09:49:55 +0000
+
+wildos-settings (0.1.31) trixie; urgency=medium
+
+ * Uninstall says Recycle Bin, as Files and the desktop do.
+
+ -- Wild OS Developers <[email protected]> Thu, 12 Nov 2026 22:02:34 +0000
+
+wildos-settings (0.1.30) trixie; urgency=medium
+
+ * Installed apps can uninstall apps that installed themselves in the home
+ folder, such as AppImages and apps with their own install script.
+
+ -- Wild OS Developers <[email protected]> Thu, 12 Nov 2026 21:30:51 +0000
+
+wildos-settings (0.1.29) trixie; urgency=medium
+
+ * Settings no longer crashes as it closes.
+
+ -- Wild OS Developers <[email protected]> Thu, 12 Nov 2026 21:07:25 +0000
+
wildos-settings (0.1.28) trixie; urgency=medium
* Steam and 32-bit apps also turns on Steam's controller support: game
diff --git a/packages/wildos-settings/debian/control b/packages/wildos-settings/debian/control
index ccaf6e7..3b0f34a 100644
--- a/packages/wildos-settings/debian/control
+++ b/packages/wildos-settings/debian/control
@@ -9,6 +9,8 @@ Build-Depends:
qt6-declarative-dev,
libkf6kcmutils-dev,
libkf6config-dev,
+ libkf6archive-dev,
+ qt6-svg-dev,
libkf6coreaddons-dev,
libkf6service-dev,
libkf6i18n-dev,
@@ -31,10 +33,21 @@ Rules-Requires-Root: no
Package: wildos-settings
Architecture: any
+# Where apps are uninstalled and everything else is set: apt refuses to
+# remove it, even from a terminal, unless told --allow-remove-essential.
+Protected: yes
Depends:
${shlibs:Depends},
${misc:Depends},
+# 40_wildos.cfg reads the processor choices settings-cpu-threads writes.
+ wildos-base (>= 0.1.3),
nftables,
+ iproute2,
+ python3,
+# Free up space asks libflatpak itself which runtimes are unused
+# (settings-free-space), the same list flatpak uninstall --unused offers.
+ python3-gi,
+ gir1.2-flatpak-1.0,
network-manager,
network-manager-openvpn,
systemd-resolved,
@@ -59,7 +72,7 @@ Depends:
libkscreen-bin,
wildos-branding,
steam-devices,
- wildos-ui (>= 0.1.3),
+ wildos-ui (>= 0.1.12),
kio6,
packagekit,
pkexec,
@@ -118,3 +131,8 @@ Description: Wild OS Settings
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.
+ .
+ The firewall is one nftables table that settings-firewall builds from the
+ protection level and the choices on the Firewall page, loaded again by
+ wildos-network as networks come and go. File sharing, Remote Desktop and
+ SSH install Samba, KRdp or OpenSSH the first time they are switched on.
diff --git a/packages/wildos-settings/debian/links b/packages/wildos-settings/debian/links
index 00ab94f..c4859dc 100644
--- a/packages/wildos-settings/debian/links
+++ b/packages/wildos-settings/debian/links
@@ -1,2 +1,3 @@
usr/libexec/wildos/kde-settings-redirect usr/bin/systemsettings
usr/libexec/wildos/kde-settings-redirect usr/bin/kcmshell6
+usr/lib/systemd/user/wildos-advanced-session.service usr/lib/systemd/user/graphical-session.target.wants/wildos-advanced-session.service
diff --git a/packages/wildos-settings/debian/postinst b/packages/wildos-settings/debian/postinst
index 136b527..01598f6 100644
--- a/packages/wildos-settings/debian/postinst
+++ b/packages/wildos-settings/debian/postinst
@@ -26,6 +26,16 @@ if [ "$1" = "configure" ]; then
# Steam's controller rules follow the 32-bit choice, including on PCs
# that turned it on before the rules came with it.
/usr/libexec/wildos/settings-32bit devices || true
+ # PCs that turned Steam and 32-bit apps on before games got the split
+ # lock setting with it.
+ SYSCTL32=/etc/sysctl.d/991-wildos-32bit.conf
+ if [ -e /etc/wildos/32bit ] && [ -f "$SYSCTL32" ] && ! grep -q split_lock_mitigate "$SYSCTL32"; then
+ printf '%s\n' '# Some games use split locks, which newer Intel processors otherwise punish' \
+ '# with a delay that shows as stutter. The delay only guards against one' \
+ '# program slowing others down, not against reading them.' \
+ '-kernel.split_lock_mitigate = 0' >> "$SYSCTL32"
+ sysctl -q -w kernel.split_lock_mitigate=0 2>/dev/null || true
+ fi
fi
#DEBHELPER#
diff --git a/packages/wildos-settings/debian/rules b/packages/wildos-settings/debian/rules
index 7e1501c..22f7cfc 100644
--- a/packages/wildos-settings/debian/rules
+++ b/packages/wildos-settings/debian/rules
@@ -11,3 +11,12 @@ override_dh_auto_configure:
# every account on install.
override_dh_installsystemduser:
dh_installsystemduser --no-enable
+
+# Wi-Fi and Bluetooth switching themselves off is off until chosen in
+# Advanced protection, whose hook enables the service; every other system
+# unit is on from install.
+override_dh_installsystemd:
+ dh_installsystemd --no-enable --no-start wildos-radios-idle.service
+ dh_installsystemd wildos-protection.service wildos-network.service wildos-usb-lock.service \
+ wildos-history.socket [email protected] wildos-history.service wildos-history.timer \
+ wildos-devices.socket [email protected]
diff --git a/packages/wildos-settings/qml/Main.qml b/packages/wildos-settings/qml/Main.qml
index ee08e06..2d910a7 100644
--- a/packages/wildos-settings/qml/Main.qml
+++ b/packages/wildos-settings/qml/Main.qml
@@ -50,6 +50,18 @@ UI.AppWindow {
if (id === "update-install") {
Navigator.request = "install";
}
+ // The camera and microphone lights' This week: History, showing
+ // only their uses in the last seven days.
+ if (id === "history-camera") {
+ Navigator.request = "camera-mic";
+ id = "history";
+ }
+ // Start's Uninstall for an app that installed itself in the home
+ // folder: Installed apps opens with the app's dialog.
+ if (id.startsWith("uninstall:")) {
+ Navigator.request = id;
+ id = "installedapps";
+ }
id = Pages.resolve(id);
let p = Pages.page(id);
if (!p || !Pages.exists(id)) {
diff --git a/packages/wildos-settings/qml/components/DeviceDetailDialog.qml b/packages/wildos-settings/qml/components/DeviceDetailDialog.qml
new file mode 100644
index 0000000..012baff
--- /dev/null
+++ b/packages/wildos-settings/qml/components/DeviceDetailDialog.qml
@@ -0,0 +1,124 @@
+import QtQuick
+import QtQuick.Layouts
+import WildOS.UI as UI
+
+// One device of System > Devices: what is wrong in plain words when it
+// needs you, then what it really is, the driver running it and where it is
+// connected, and any figures of its own (a drive's health, a battery's).
+// The fix button is the same as on its row.
+RecoveryDialog {
+ id: dialog
+
+ property var row: ({})
+ readonly property bool needsYou: row.state === "attention"
+ readonly property var facts: {
+ const out = [];
+ const add = (label, value) => {
+ if (value) {
+ out.push({ label: label, value: value });
+ }
+ };
+ add("Model", row.model);
+ add("Made by", row.maker);
+ add("Driver", row.driver ? row.driver : row.kind === "printer" ? "" : "None");
+ add("Connected", row.connection);
+ for (const e of (row.extra || [])) {
+ add(e.label, e.value);
+ }
+ add("Hardware ID", row.hardwareId);
+ return out;
+ }
+
+ signal act(var row)
+
+ function openFor(r) {
+ row = r;
+ open();
+ }
+
+ title: row.name || ""
+ iconName: row.icon || "chip"
+ dialogWidth: 560
+
+ RowLayout {
+ Layout.fillWidth: true
+ spacing: 8
+
+ PathIcon {
+ Layout.alignment: Qt.AlignTop
+ Layout.topMargin: 2
+ name: dialog.needsYou ? "triangle-alert" : dialog.row.state === "off" ? "power-round" : "status-ok"
+ size: 15
+ strokeWidth: 2.2
+ color: dialog.needsYou ? (UI.Style.dark ? "#ffc46a" : UI.Style.warning)
+ : dialog.row.state === "off" ? UI.Style.inkMuted
+ : (UI.Style.dark ? "#5fd38d" : "#1d7a4c")
+ }
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: dialog.needsYou ? dialog.row.problem : (dialog.row.state === "off" ? "" : "Working. ") + dialog.row.line + "."
+ size: 13.5
+ wrapMode: Text.Wrap
+ elide: Text.ElideNone
+ }
+ }
+
+ GridLayout {
+ Layout.fillWidth: true
+ Layout.topMargin: 6
+ columns: 2
+ columnSpacing: 18
+ rowSpacing: 8
+
+ Repeater {
+ model: dialog.facts
+
+ UI.Label {
+ required property var modelData
+ required property int index
+ Layout.row: index
+ Layout.column: 0
+ Layout.alignment: Qt.AlignTop
+ text: modelData.label
+ size: 13
+ color: UI.Style.inkMuted
+ }
+ }
+
+ Repeater {
+ model: dialog.facts
+
+ UI.Label {
+ required property var modelData
+ required property int index
+ Layout.row: index
+ Layout.column: 1
+ Layout.fillWidth: true
+ text: modelData.value
+ size: 13
+ wrapMode: Text.Wrap
+ elide: Text.ElideNone
+ }
+ }
+ }
+
+ buttons: [
+ UI.Button {
+ visible: dialog.needsYou && (dialog.row.action || "") !== ""
+ implicitHeight: 32
+ text: dialog.row.actionLabel || ""
+ onClicked: {
+ const r = dialog.row;
+ dialog.close();
+ dialog.act(r);
+ }
+ },
+ UI.Button {
+ implicitHeight: 32
+ kind: "primary"
+ text: "Close"
+ onClicked: dialog.close()
+ }
+ ]
+}
diff --git a/packages/wildos-settings/qml/components/DeviceList.qml b/packages/wildos-settings/qml/components/DeviceList.qml
new file mode 100644
index 0000000..5e4cbc5
--- /dev/null
+++ b/packages/wildos-settings/qml/components/DeviceList.qml
@@ -0,0 +1,130 @@
+import QtQuick
+import QtQuick.Layouts
+import QtQuick.Templates as T
+import WildOS.UI as UI
+
+// One card of System > Devices (SettingsDevices.dc): a row per device with
+// its plain name and one line, the button that fixes it when it needs you,
+// and its state at the right. Rows are Devices' maps.
+Rectangle {
+ id: card
+
+ property var model: []
+ // The board's status colours, as History and Firewall use them.
+ readonly property color amber: UI.Style.dark ? "#ffc46a" : UI.Style.warning
+ readonly property color green: UI.Style.dark ? "#5fd38d" : "#1d7a4c"
+
+ signal opened(var row)
+ signal acted(var row)
+
+ implicitHeight: rowsColumn.implicitHeight
+ radius: 12
+ color: UI.Style.tone(0.05)
+ border.width: 1
+ border.color: UI.Style.tone(0.07)
+ clip: true
+
+ Column {
+ id: rowsColumn
+ width: parent.width
+
+ Repeater {
+ model: card.model
+
+ T.AbstractButton {
+ id: deviceRow
+ required property var modelData
+ required property int index
+ readonly property bool needsYou: modelData.state === "attention"
+ readonly property bool off: modelData.state === "off"
+ width: rowsColumn.width
+ height: 50
+ hoverEnabled: true
+ focusPolicy: Qt.StrongFocus
+ Accessible.role: Accessible.Button
+ Accessible.name: modelData.name + ". " + (needsYou ? modelData.problem : modelData.line)
+ Accessible.description: "Details"
+ onClicked: card.opened(modelData)
+
+ background: Rectangle {
+ color: deviceRow.hovered ? UI.Style.tone(0.03) : "transparent"
+ radius: 12
+
+ Rectangle {
+ visible: deviceRow.index > 0
+ anchors.left: parent.left
+ anchors.right: parent.right
+ height: 1
+ color: UI.Style.tone(0.07)
+ }
+
+ UI.FocusRing {
+ visible: deviceRow.visualFocus
+ targetRadius: 12
+ }
+ }
+
+ contentItem: RowLayout {
+ spacing: 14
+
+ PathIcon {
+ Layout.leftMargin: 18
+ name: deviceRow.modelData.icon
+ size: 19
+ strokeWidth: 1.8
+ color: UI.Style.iconInk
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 1
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: deviceRow.modelData.name
+ size: 13.5
+ }
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: deviceRow.needsYou ? deviceRow.modelData.problem : deviceRow.modelData.line
+ size: 12
+ color: UI.Style.inkMuted
+ }
+ }
+
+ UI.Button {
+ visible: deviceRow.needsYou && deviceRow.modelData.action !== ""
+ implicitHeight: 32
+ text: deviceRow.modelData.actionLabel
+ Accessible.name: deviceRow.modelData.actionLabel + ": " + deviceRow.modelData.name
+ onClicked: card.acted(deviceRow.modelData)
+ }
+
+ Item {
+ visible: deviceRow.needsYou && deviceRow.modelData.action !== ""
+ Layout.preferredWidth: 12
+ }
+
+ RowLayout {
+ Layout.rightMargin: 18
+ spacing: 6
+
+ PathIcon {
+ name: deviceRow.needsYou ? "triangle-alert" : deviceRow.off ? "power-round" : "status-ok"
+ size: 14
+ strokeWidth: 2.2
+ color: deviceRow.needsYou ? card.amber : deviceRow.off ? UI.Style.inkMuted : card.green
+ }
+
+ UI.Label {
+ text: deviceRow.needsYou || deviceRow.off ? deviceRow.modelData.badge : "Working"
+ size: 12.5
+ color: deviceRow.needsYou ? card.amber : UI.Style.inkMuted
+ }
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/packages/wildos-settings/qml/components/FingerprintSetup.qml b/packages/wildos-settings/qml/components/FingerprintSetup.qml
index 1d3b7a8..fe79e3a 100644
--- a/packages/wildos-settings/qml/components/FingerprintSetup.qml
+++ b/packages/wildos-settings/qml/components/FingerprintSetup.qml
@@ -386,6 +386,7 @@ T.Popup {
anchors.rightMargin: 12
verticalAlignment: TextInput.AlignVCenter
echoMode: TextInput.Password
+ UI.NoPaste {}
passwordCharacter: "•"
color: UI.Style.ink
selectionColor: UI.Style.textSelection
@@ -399,6 +400,16 @@ T.Popup {
Accessible.passwordEdit: true
onTextChanged: dialog.error = ""
onAccepted: dialog.submit()
+ Keys.onPressed: event => {
+ if (passwordMenu.isMenuKey(event)) {
+ passwordMenu.openAtCaret();
+ event.accepted = true;
+ }
+ }
+
+ UI.TextMenu {
+ id: passwordMenu
+ }
}
}
diff --git a/packages/wildos-settings/qml/components/FirewallActivityDialog.qml b/packages/wildos-settings/qml/components/FirewallActivityDialog.qml
new file mode 100644
index 0000000..1a73781
--- /dev/null
+++ b/packages/wildos-settings/qml/components/FirewallActivityDialog.qml
@@ -0,0 +1,264 @@
+import QtQuick
+import QtQuick.Layouts
+import WildOS.Settings
+import WildOS.UI as UI
+
+// What the firewall blocked (FirewallActivity.dc): the latest connections
+// it turned away, today or over the week it keeps them, each with when,
+// who sent it as far as the network says (your router, another PC on this
+// network, the internet) and what it was for. Allow is offered for a
+// sender on a network nearby, never the internet or the router; it opens
+// Allow an app or port for that device and port.
+RecoveryDialog {
+ id: dialog
+
+ property string range: "today"
+ property date now: new Date()
+ readonly property int shownMax: 5
+ readonly property var entries: Firewall.blocked.filter(b => range === "week" || b.when.toDateString() === now.toDateString())
+ readonly property var shown: entries.slice(0, shownMax)
+
+ signal allowRequested(var entry)
+
+ function who(kind) {
+ return kind === "router" ? "Your router"
+ : kind === "local" ? "Another PC on this network"
+ : kind === "internet" ? "The internet"
+ : "Another local network";
+ }
+
+ function countLine() {
+ const n = entries.length;
+ const when = range === "week" ? "in 7 days" : "today";
+ if (n === 0) {
+ return "";
+ }
+ return n > shownMax ? n + " " + when + " · showing the latest " + shownMax : n + " " + when;
+ }
+
+ title: "What the firewall blocked"
+ iconName: "shield-round-check"
+ dialogWidth: 680
+
+ onOpened: {
+ now = new Date();
+ range = "today";
+ Firewall.refreshListening();
+ }
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: "Each of these tried to connect to this PC and was turned away. Allow one only if you recognise it and meant it to connect."
+ size: 13
+ lineHeightMode: Text.FixedHeight
+ lineHeight: 19.5
+ color: UI.Style.inkMuted
+ wrapMode: Text.Wrap
+ elide: Text.ElideNone
+ }
+
+ RowLayout {
+ Layout.fillWidth: true
+ spacing: 12
+
+ Segmented {
+ options: [{ value: "today", text: "Today" }, { value: "week", text: "7 days" }]
+ value: dialog.range
+ onPicked: v => dialog.range = v
+ }
+
+ Item {
+ Layout.fillWidth: true
+ }
+
+ UI.Label {
+ text: dialog.countLine()
+ size: 12.5
+ color: UI.Style.inkMuted
+ }
+ }
+
+ Rectangle {
+ Layout.fillWidth: true
+ implicitHeight: list.implicitHeight
+ radius: 10
+ color: UI.Style.tone(0.04)
+ border.width: 1
+ border.color: UI.Style.tone(0.07)
+ clip: true
+
+ Column {
+ id: list
+ width: parent.width
+
+ Repeater {
+ model: dialog.shown
+
+ Item {
+ id: entryRow
+ required property var modelData
+ required property int index
+ readonly property string service: Firewall.serviceName(modelData.port, modelData.proto)
+ readonly property bool canAllow: modelData.kind === "local" || modelData.kind === "other"
+ width: list.width
+ height: 52
+
+ Rectangle {
+ visible: entryRow.index > 0
+ anchors.left: parent.left
+ anchors.right: parent.right
+ height: 1
+ color: UI.Style.tone(0.07)
+ }
+
+ RowLayout {
+ anchors.fill: parent
+ anchors.leftMargin: 14
+ anchors.rightMargin: 14
+ spacing: 14
+
+ UI.Label {
+ // The board's 40px fits a 24-hour clock; "10:42 PM" needs more.
+ Layout.preferredWidth: Format.twelveHour() ? 62 : 40
+ text: dialog.range === "week" && entryRow.modelData.when.toDateString() !== dialog.now.toDateString()
+ ? Format.shortDate(entryRow.modelData.when).slice(0, 5) : Format.time(entryRow.modelData.when)
+ size: 12.5
+ color: UI.Style.inkMuted
+ font.features: ({ "tnum": 1 })
+ }
+
+ PathIcon {
+ name: entryRow.modelData.kind === "router" ? "router"
+ : entryRow.modelData.kind === "internet" ? "globe-round" : "monitor-round"
+ size: 18
+ strokeWidth: 1.8
+ color: UI.Style.ink
+ }
+
+ ColumnLayout {
+ Layout.preferredWidth: 210
+ Layout.fillWidth: false
+ spacing: 1
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: dialog.who(entryRow.modelData.kind)
+ size: 13
+ elide: Text.ElideRight
+ }
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: entryRow.modelData.source
+ size: 12
+ color: UI.Style.inkMuted
+ font.features: ({ "tnum": 1 })
+ elide: Text.ElideMiddle
+ }
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 1
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: entryRow.service.length > 0 ? entryRow.service : (entryRow.modelData.proto === "udp" ? "UDP port " : "Port ") + entryRow.modelData.port
+ size: 13
+ elide: Text.ElideRight
+ }
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: entryRow.service.length > 0 ? (entryRow.modelData.proto === "udp" ? "UDP port " : "Port ") + entryRow.modelData.port : "Nothing on this PC is known to use it"
+ size: 12
+ color: UI.Style.inkMuted
+ elide: Text.ElideRight
+ }
+ }
+
+ Item {
+ Layout.preferredWidth: 76
+ Layout.fillHeight: true
+
+ UI.Button {
+ anchors.right: parent.right
+ anchors.verticalCenter: parent.verticalCenter
+ visible: entryRow.canAllow
+ implicitHeight: 32
+ text: "Allow"
+ enabled: Firewall.enabled && !Firewall.busy
+ Accessible.name: "Allow " + dialog.who(entryRow.modelData.kind).toLowerCase() + " on port " + entryRow.modelData.port
+ onClicked: {
+ const entry = entryRow.modelData;
+ dialog.close();
+ dialog.allowRequested(entry);
+ }
+ }
+
+ UI.Label {
+ anchors.right: parent.right
+ anchors.verticalCenter: parent.verticalCenter
+ visible: !entryRow.canAllow
+ text: "Blocked"
+ size: 12.5
+ color: UI.Style.inkSubtle
+ }
+ }
+ }
+ }
+ }
+
+ Item {
+ visible: dialog.shown.length === 0
+ width: list.width
+ height: 52
+
+ UI.Label {
+ anchors.left: parent.left
+ anchors.leftMargin: 14
+ anchors.verticalCenter: parent.verticalCenter
+ text: dialog.range === "week" ? "Nothing has tried to connect in the last 7 days." : "Nothing has tried to connect today."
+ size: 13
+ color: UI.Style.inkMuted
+ }
+ }
+ }
+ }
+
+ RowLayout {
+ Layout.fillWidth: true
+ spacing: 10
+
+ PathIcon {
+ name: "lock-round"
+ size: 14
+ strokeWidth: 2
+ color: UI.Style.inkSubtle
+ }
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: "Kept on this PC for 7 days, then deleted. Nothing is sent anywhere."
+ size: 12.5
+ color: UI.Style.inkMuted
+ wrapMode: Text.Wrap
+ elide: Text.ElideNone
+ }
+ }
+
+ buttons: [
+ UI.Button {
+ implicitHeight: 32
+ text: "Clear the list"
+ enabled: Firewall.blocked.length > 0
+ onClicked: Firewall.clearBlocked()
+ },
+ UI.Button {
+ implicitHeight: 32
+ kind: "primary"
+ text: "Close"
+ onClicked: dialog.close()
+ }
+ ]
+}
diff --git a/packages/wildos-settings/qml/components/FirewallAllowDialog.qml b/packages/wildos-settings/qml/components/FirewallAllowDialog.qml
new file mode 100644
index 0000000..c0f68c3
--- /dev/null
+++ b/packages/wildos-settings/qml/components/FirewallAllowDialog.qml
@@ -0,0 +1,315 @@
+import QtQuick
+import QtQuick.Layouts
+import WildOS.Settings
+import WildOS.UI as UI
+
+// Allow an app or port (FirewallAllow.dc). An app is one of the programs
+// waiting for connections right now that the firewall turns away (asked of
+// wildos-network, which can name them all); a port is any number. Who can
+// connect is the devices on this network, one device, or anyone; for how
+// long is until it is turned off, until the next restart or for an hour.
+// Allowed rules never apply on a public network (settings-firewall).
+RecoveryDialog {
+ id: dialog
+
+ property string networkName
+ property string what: "app"
+ property int appIndex: 0
+ property string portText
+ property string scope: "network"
+ property string address
+ property string duration: "forever"
+ property string error
+ // Opened from "What the firewall blocked": {port, proto, source, kind}.
+ property var preset: null
+
+ readonly property var apps: Firewall.listening
+ readonly property var app: what === "app" && apps.length > 0 ? apps[Math.min(appIndex, apps.length - 1)] : null
+ readonly property int port: what === "app" ? (app ? app.port : 0) : (/^\d{1,5}$/.test(portText.trim()) ? parseInt(portText.trim()) : 0)
+ readonly property string addressProblem: scope === "device" ? Firewall.checkAddress(address) : ""
+ readonly property bool ready: port > 0 && port < 65536 && addressProblem.length === 0
+
+ function openFor(entry) {
+ preset = entry || null;
+ what = "app";
+ appIndex = 0;
+ portText = "";
+ scope = "network";
+ address = "";
+ duration = "forever";
+ error = "";
+ if (preset) {
+ // The device that knocked, when it is on a network nearby; the
+ // internet as a whole is never offered from here.
+ if (preset.kind === "local" || preset.kind === "other") {
+ scope = "device";
+ address = preset.source;
+ }
+ what = "port";
+ portText = String(preset.port);
+ }
+ Firewall.refreshListening();
+ open();
+ }
+
+ function pickPreset() {
+ if (!preset) {
+ return;
+ }
+ const i = apps.findIndex(a => a.port === preset.port && a.proto === preset.proto);
+ if (i >= 0) {
+ what = "app";
+ appIndex = i;
+ }
+ }
+
+ function submit() {
+ if (!ready || Firewall.busy) {
+ return;
+ }
+ error = "";
+ const known = Firewall.serviceName(port, app ? app.proto : "tcp");
+ const name = app ? app.name : known.length > 0 ? known : "Port " + port;
+ Firewall.allow(name, port, app ? app.proto : "both", scope, scope === "device" ? address : "", duration);
+ }
+
+ title: "Allow an app or port"
+ iconName: "shield-round-check"
+ dialogWidth: 560
+
+ Connections {
+ target: Firewall
+ function onListeningChanged() {
+ dialog.pickPreset();
+ }
+ function onDone(what) {
+ if (what === "allow" && dialog.opened) {
+ dialog.close();
+ }
+ }
+ function onFailed(message) {
+ if (dialog.opened) {
+ dialog.error = message;
+ }
+ }
+ }
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: dialog.what === "app"
+ ? "Apps listed here are running now and waiting for other devices to connect. Until you allow one, the firewall turns those connections away."
+ : "Other devices can connect to whatever on this PC waits on the port you give. Allow only a port an app you trust uses."
+ size: 13
+ lineHeightMode: Text.FixedHeight
+ lineHeight: 19.5
+ color: UI.Style.inkMuted
+ wrapMode: Text.Wrap
+ elide: Text.ElideNone
+ }
+
+ RowLayout {
+ Layout.fillWidth: true
+ spacing: 12
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: "WHAT TO ALLOW"
+ size: 12.5
+ font.weight: UI.Style.weightBold
+ font.letterSpacing: 0.25
+ color: UI.Style.inkSubtle
+ }
+
+ Segmented {
+ options: [{ value: "app", text: "An app" }, { value: "port", text: "A port number" }]
+ value: dialog.what
+ onPicked: v => dialog.what = v
+ }
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ visible: dialog.what === "app"
+ spacing: 6
+
+ Repeater {
+ model: dialog.apps
+
+ FirewallChoice {
+ required property var modelData
+ required property int index
+ Layout.fillWidth: true
+ title: modelData.name
+ description: "Waiting for connections on " + (modelData.proto === "udp" ? "UDP port " : "port ") + modelData.port
+ checked: dialog.appIndex === index
+ onClicked: dialog.appIndex = index
+ }
+ }
+
+ UI.Label {
+ Layout.fillWidth: true
+ visible: dialog.apps.length === 0
+ text: "No apps are waiting for connections right now. Start the app first, or choose A port number."
+ size: 12.5
+ color: UI.Style.inkMuted
+ wrapMode: Text.Wrap
+ elide: Text.ElideNone
+ }
+ }
+
+ RowLayout {
+ Layout.fillWidth: true
+ visible: dialog.what === "port"
+ spacing: 12
+
+ UI.TextField {
+ id: portField
+ Layout.preferredWidth: 160
+ placeholderText: "Port, such as 8096"
+ inputMethodHints: Qt.ImhDigitsOnly
+ validator: IntValidator { bottom: 1; top: 65535 }
+ text: dialog.portText
+ onTextEdited: dialog.portText = text
+ onAccepted: dialog.submit()
+ Accessible.name: "Port number"
+ }
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: {
+ const known = dialog.port > 0 ? Firewall.serviceName(dialog.port, "tcp") : "";
+ return known.length > 0 ? "Usually " + known + ". TCP and UDP." : dialog.port > 0 ? "TCP and UDP." : "";
+ }
+ size: 12
+ color: UI.Style.inkMuted
+ elide: Text.ElideRight
+ }
+ }
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: "WHO CAN CONNECT"
+ size: 12.5
+ font.weight: UI.Style.weightBold
+ font.letterSpacing: 0.25
+ color: UI.Style.inkSubtle
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 6
+
+ FirewallChoice {
+ Layout.fillWidth: true
+ title: "Devices on this network"
+ description: dialog.networkName.length > 0 ? "Phones, TVs and PCs on " + dialog.networkName + ". Recommended." : "Phones, TVs and PCs on the network you're on. Recommended."
+ checked: dialog.scope === "network"
+ onClicked: dialog.scope = "network"
+ }
+
+ FirewallChoice {
+ id: deviceChoice
+ Layout.fillWidth: true
+ title: "One device only"
+ description: dialog.scope === "device" && dialog.address.length > 0 && dialog.addressProblem.length > 0
+ ? dialog.addressProblem : "Give its address, such as 192.168.1.24."
+ checked: dialog.scope === "device"
+ showBelow: checked
+ onClicked: {
+ dialog.scope = "device";
+ addressField.forceActiveFocus();
+ }
+
+ below: UI.TextField {
+ id: addressField
+ Layout.preferredWidth: 220
+ placeholderText: "192.168.1.24"
+ text: dialog.address
+ error: dialog.address.length > 0 && dialog.addressProblem.length > 0
+ onTextEdited: dialog.address = text.trim()
+ onAccepted: dialog.submit()
+ Accessible.name: "The device's address"
+ }
+ }
+
+ FirewallChoice {
+ Layout.fillWidth: true
+ title: "Anyone, including the internet"
+ description: "Only works if your router is set up to pass it on."
+ checked: dialog.scope === "anyone"
+ onClicked: dialog.scope = "anyone"
+
+ PathIcon {
+ name: "triangle-alert"
+ size: 16
+ strokeWidth: 2
+ color: "#ffc46a"
+ }
+ }
+ }
+
+ RowLayout {
+ Layout.fillWidth: true
+ spacing: 12
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: "FOR HOW LONG"
+ size: 12.5
+ font.weight: UI.Style.weightBold
+ font.letterSpacing: 0.25
+ color: UI.Style.inkSubtle
+ }
+
+ UI.ComboBox {
+ id: durationBox
+ Layout.preferredWidth: 220
+ implicitHeight: 32
+ Accessible.name: "For how long"
+ model: [
+ { value: "forever", text: "Until I turn it off" },
+ { value: "restart", text: "Until I restart" },
+ { value: "hour", text: "For one hour" }
+ ]
+ currentIndex: model.findIndex(o => o.value === dialog.duration)
+ onActivated: dialog.duration = currentValue
+ }
+ }
+
+ RowLayout {
+ Layout.fillWidth: true
+ spacing: 10
+
+ PathIcon {
+ name: "lock-round"
+ size: 14
+ strokeWidth: 2
+ color: UI.Style.inkSubtle
+ }
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: dialog.error.length > 0 ? dialog.error : "Never applies on a public network. You will be asked for your password."
+ size: 12.5
+ color: dialog.error.length > 0 ? UI.Style.warning : UI.Style.inkMuted
+ wrapMode: Text.Wrap
+ elide: Text.ElideNone
+ }
+ }
+
+ buttons: [
+ UI.Button {
+ implicitHeight: 32
+ text: "Cancel"
+ onClicked: dialog.close()
+ },
+ UI.Button {
+ implicitHeight: 32
+ kind: "primary"
+ text: Firewall.busy && Firewall.busyWhat === "allow" ? "Allowing" : "Allow"
+ busy: Firewall.busy && Firewall.busyWhat === "allow"
+ enabled: dialog.ready && !Firewall.busy
+ onClicked: dialog.submit()
+ }
+ ]
+}
diff --git a/packages/wildos-settings/qml/components/FirewallChoice.qml b/packages/wildos-settings/qml/components/FirewallChoice.qml
new file mode 100644
index 0000000..a1ab6ca
--- /dev/null
+++ b/packages/wildos-settings/qml/components/FirewallChoice.qml
@@ -0,0 +1,109 @@
+import QtQuick
+import QtQuick.Layouts
+import QtQuick.Templates as T
+import WildOS.UI as UI
+
+// One choice of a set in the firewall's dialog (FirewallAllow.dc): a 46px
+// row with an 18px radio, a 13px title over a 12px muted line, and an
+// optional mark at the right. Chosen, it takes the accent edge on a 0.10
+// accent wash; otherwise a 0.04 fill with a 0.07 edge. Radius 8.
+T.AbstractButton {
+ id: control
+
+ property string title
+ property string description
+ default property alias trailing: trailingRow.data
+ property alias below: belowColumn.data
+ property bool showBelow: false
+
+ // The dialog binds `checked` and sets its own choice on click.
+ checkable: false
+ hoverEnabled: true
+ focusPolicy: Qt.StrongFocus
+ implicitWidth: 300
+ implicitHeight: Math.max(46, body.implicitHeight + topPadding + bottomPadding)
+ topPadding: 6
+ bottomPadding: 6
+ leftPadding: 14
+ rightPadding: 14
+ Accessible.role: Accessible.RadioButton
+ Accessible.name: title
+ Accessible.description: description
+
+ background: Rectangle {
+ radius: 8
+ color: control.checked ? Qt.rgba(UI.Style.accent.r, UI.Style.accent.g, UI.Style.accent.b, 0.10)
+ : control.hovered && control.enabled ? UI.Style.tone(0.07) : UI.Style.tone(0.04)
+ border.width: 1
+ border.color: control.checked ? UI.Style.accent : UI.Style.tone(0.07)
+
+ UI.FocusRing {
+ visible: control.visualFocus
+ targetRadius: 8
+ }
+ }
+
+ contentItem: ColumnLayout {
+ id: body
+ spacing: 8
+
+ RowLayout {
+ Layout.fillWidth: true
+ spacing: 12
+
+ Rectangle {
+ Layout.preferredWidth: 18
+ Layout.preferredHeight: 18
+ radius: 9
+ color: control.checked ? UI.Style.accent : "transparent"
+ border.width: control.checked ? 0 : 1.5
+ border.color: UI.Style.toggleOffBorder
+
+ Rectangle {
+ visible: control.checked
+ anchors.centerIn: parent
+ width: 7
+ height: 7
+ radius: 3.5
+ color: UI.Style.textOnAccent
+ }
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 1
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: control.title
+ size: 13
+ }
+
+ UI.Label {
+ Layout.fillWidth: true
+ visible: control.description.length > 0
+ text: control.description
+ size: 12
+ color: UI.Style.inkMuted
+ wrapMode: Text.Wrap
+ elide: Text.ElideNone
+ }
+ }
+
+ Row {
+ id: trailingRow
+ visible: children.length > 0
+ Layout.alignment: Qt.AlignVCenter
+ spacing: 8
+ }
+ }
+
+ ColumnLayout {
+ id: belowColumn
+ Layout.fillWidth: true
+ Layout.leftMargin: 30
+ Layout.bottomMargin: 4
+ visible: control.showBelow
+ }
+ }
+}
diff --git a/packages/wildos-settings/qml/components/HistoryDetailDialog.qml b/packages/wildos-settings/qml/components/HistoryDetailDialog.qml
new file mode 100644
index 0000000..0603147
--- /dev/null
+++ b/packages/wildos-settings/qml/components/HistoryDetailDialog.qml
@@ -0,0 +1,166 @@
+import QtQuick
+import QtQuick.Layouts
+import WildOS.Settings
+import WildOS.UI as UI
+
+// One event of System > History (HistoryDetail.dc): what happened, what
+// Wild OS did and what you can do, in plain words, then the lines it was
+// made from, which Copy puts on the clipboard. Report a problem opens
+// wildos-report with the event attached.
+RecoveryDialog {
+ id: dialog
+
+ property var event: null
+ readonly property var words: event ? HistoryWords.describe(event, History.events) : ({})
+ property bool copied: false
+
+ signal failed(string message)
+
+ function openFor(e) {
+ event = e;
+ copied = false;
+ open();
+ }
+
+ title: words.title || ""
+ iconName: words.icon || "info"
+ dialogWidth: 600
+
+ Repeater {
+ model: [
+ { heading: "What happened", text: dialog.words.happened || "" },
+ { heading: "What Wild OS did", text: dialog.words.did || "" },
+ { heading: "What you can do", text: dialog.words.todo || "" }
+ ]
+
+ ColumnLayout {
+ id: part
+ required property var modelData
+ Layout.fillWidth: true
+ spacing: 4
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: part.modelData.heading.toUpperCase()
+ size: 12.5
+ font.weight: UI.Style.weightBold
+ font.letterSpacing: 0.25
+ color: UI.Style.inkSubtle
+ }
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: part.modelData.text
+ size: 13.5
+ lineHeightMode: Text.ProportionalHeight
+ lineHeight: 1.5
+ wrapMode: Text.Wrap
+ elide: Text.ElideNone
+ }
+ }
+ }
+
+ RowLayout {
+ Layout.fillWidth: true
+ spacing: 8
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: "TECHNICAL DETAIL"
+ size: 12.5
+ font.weight: UI.Style.weightBold
+ font.letterSpacing: 0.25
+ color: UI.Style.inkSubtle
+ }
+
+ UI.LinkButton {
+ text: dialog.copied ? "Copied" : "Copy"
+ Accessible.name: "Copy the technical detail"
+ onClicked: {
+ clipboard.text = dialog.event ? HistoryWords.fullText(dialog.event, History.events) : "";
+ clipboard.selectAll();
+ clipboard.copy();
+ dialog.copied = true;
+ copiedTimer.restart();
+ }
+ }
+ }
+
+ Rectangle {
+ Layout.fillWidth: true
+ implicitHeight: techText.implicitHeight + 24
+ radius: 8
+ color: UI.Style.dark ? Qt.rgba(0, 0, 0, 0.28) : Qt.rgba(0, 0, 0, 0.04)
+ border.width: 1
+ border.color: UI.Style.tone(0.07)
+ clip: true
+
+ // Selectable, so part of it can be copied as well as all of it.
+ // TextEdit has no line height of its own; the board's 1.45 comes
+ // from the rich text instead.
+ TextEdit {
+ id: techText
+ anchors.left: parent.left
+ anchors.right: parent.right
+ anchors.top: parent.top
+ anchors.leftMargin: 14
+ anchors.rightMargin: 14
+ anchors.topMargin: 12
+ readonly property string plain: dialog.event ? HistoryWords.techText(dialog.event) : ""
+ text: "<div style=\"line-height: 145%; white-space: pre-wrap\">"
+ + plain.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;") + "</div>"
+ textFormat: TextEdit.RichText
+ readOnly: true
+ selectByMouse: true
+ font.family: "monospace"
+ font.pixelSize: UI.Style.px(11.5)
+ color: UI.Style.inkMuted
+ selectionColor: UI.Style.textSelection
+ selectedTextColor: UI.Style.ink
+ wrapMode: TextEdit.WrapAnywhere
+ Keys.onPressed: event => {
+ if (techMenu.isMenuKey(event)) {
+ techMenu.openAtCaret();
+ event.accepted = true;
+ }
+ }
+
+ UI.TextMenu {
+ id: techMenu
+ }
+ }
+ }
+
+ TextEdit {
+ id: clipboard
+ visible: false
+ }
+
+ Timer {
+ id: copiedTimer
+ interval: 2000
+ onTriggered: dialog.copied = false
+ }
+
+ buttons: [
+ UI.Button {
+ implicitHeight: 32
+ text: "Report a problem"
+ onClicked: {
+ const e = dialog.event;
+ const sent = History.report({ id: e.id, kind: e.kind, when: e.when, data: e.data, title: dialog.words.title },
+ HistoryWords.fullText(e, History.events));
+ dialog.close();
+ if (!sent) {
+ dialog.failed("Report a problem isn't installed, or this event couldn't be handed to it.");
+ }
+ }
+ },
+ UI.Button {
+ implicitHeight: 32
+ kind: "primary"
+ text: "Close"
+ onClicked: dialog.close()
+ }
+ ]
+}
diff --git a/packages/wildos-settings/qml/components/HistoryWords.qml b/packages/wildos-settings/qml/components/HistoryWords.qml
new file mode 100644
index 0000000..ac7442f
--- /dev/null
+++ b/packages/wildos-settings/qml/components/HistoryWords.qml
@@ -0,0 +1,624 @@
+pragma Singleton
+
+import QtQuick
+import WildOS.Settings
+import WildOS.UI as UI
+
+// The words for History (SettingsHistory.dc, HistoryDetail.dc): for each
+// kind of event settings-history records, a title, one line for the list,
+// and the three parts of Details (what happened, what Wild OS did, what you
+// can do). One place, so the list, Details and Save as a file always say
+// the same thing. Every sentence is checked against what Wild OS really
+// does; anything it can't know (which file was being copied) isn't said.
+QtObject {
+ id: words
+
+ // The board's status colours; on light, the Style's own deeper ones.
+ readonly property color amber: UI.Style.dark ? "#ffc46a" : UI.Style.warning
+ readonly property color green: UI.Style.dark ? "#5fd38d" : "#1d7a4c"
+ readonly property color red: UI.Style.dark ? "#ff8f8f" : UI.Style.danger
+ readonly property color blue: UI.Style.accent
+ readonly property color plain: UI.Style.ink
+
+ function at(date) {
+ return Format.time(date);
+ }
+
+ function dayAndTime(date) {
+ const day = Format.day(date);
+ return (day === "today" || day === "yesterday" ? day : "on " + day) + " at " + Format.time(date);
+ }
+
+ function quoted(text) {
+ return "“" + text + "”";
+ }
+
+ function countText(n, one, many) {
+ return n === 1 ? one : n + " " + many;
+ }
+
+ function listNames(names) {
+ const list = names.filter(n => n && n.length > 0);
+ if (list.length === 0) {
+ return "";
+ }
+ if (list.length === 1) {
+ return list[0];
+ }
+ if (list.length === 2) {
+ return list[0] + " and " + list[1];
+ }
+ return list[0] + ", " + list[1] + " and " + Format.plural(list.length - 2, "more", "more");
+ }
+
+ // How many times the same program stopped in the 30 days kept.
+ function repeats(e, all) {
+ const program = e.data.program || "";
+ return all.filter(x => (x.kind === "crash" || x.kind === "service-crash") && (x.data.program || "") === program).length;
+ }
+
+ function repeatSentence(e, all) {
+ const n = repeats(e, all);
+ return n <= 1 ? "This is the first time in the last 30 days." : "It has happened " + n + " times in the last 30 days.";
+ }
+
+ function duration(fromSecs, to) {
+ const minutes = Math.max(0, Math.round((to.getTime() / 1000 - fromSecs) / 60));
+ if (minutes < 1) {
+ return "less than a minute";
+ }
+ if (minutes < 60) {
+ return Format.plural(minutes, "minute", "minutes");
+ }
+ const hours = Math.floor(minutes / 60);
+ const rest = minutes % 60;
+ return Format.plural(hours, "hour", "hours") + (rest > 0 ? " " + Format.plural(rest, "minute", "minutes") : "");
+ }
+
+ function firewallWho(kind) {
+ return kind === "router" ? "your router"
+ : kind === "local" ? "another PC on this network"
+ : kind === "internet" ? "the internet"
+ : "another network";
+ }
+
+ function portName(port, proto) {
+ const service = Firewall.serviceName(port, proto);
+ return service.length > 0 ? service : (proto === "udp" ? "UDP port " : "Port ") + port;
+ }
+
+ function passwordPlace(place) {
+ return place === "signin" ? "at the sign-in screen"
+ : place === "lock" ? "to unlock the screen"
+ : place === "ssh" ? "over SSH"
+ : "when an app asked for the admin password";
+ }
+
+ // {title, detail, icon, tone, problem, group, happened, did, todo}.
+ // group is what the filters pick from: security, updates, apps or
+ // other.
+ function describe(e, all) {
+ const d = e.data || {};
+ const when = e.when;
+ switch (e.kind) {
+ case "crash": {
+ const app = d.app && d.app.length > 0 ? d.app : "";
+ return {
+ title: app.length > 0 ? app + " closed unexpectedly" : "A program closed unexpectedly",
+ detail: app.length > 0 ? "It stopped suddenly. Open it again to carry on." : "It was called " + d.program + ".",
+ icon: "triangle-alert", tone: amber, problem: true, group: "apps",
+ happened: (app.length > 0 ? app : d.program) + " stopped suddenly at " + at(when) + ". " + repeatSentence(e, all),
+ did: "Recorded which program stopped, how and when. Nothing from its memory was kept, and nothing was sent anywhere.",
+ todo: "Nothing, unless it keeps happening. If it does, send a report so it can be fixed."
+ };
+ }
+ case "service-crash":
+ return {
+ title: "A part of Wild OS stopped unexpectedly",
+ detail: d.program + ", which runs in the background.",
+ icon: "triangle-alert", tone: amber, problem: true, group: "other",
+ happened: d.program + " stopped suddenly at " + at(when) + ". It runs in the background, so you may not have seen anything happen. " + repeatSentence(e, all),
+ did: "Recorded which program stopped, how and when. Nothing from its memory was kept, and nothing was sent anywhere.",
+ todo: "If something stopped working at that time, restart the PC. If it keeps happening, send a report so it can be fixed."
+ };
+ case "oom": {
+ const name = d.app && d.app.length > 0 ? d.app : d.program;
+ return {
+ title: name + " was closed to free up memory",
+ detail: "This PC ran out of memory.",
+ icon: "triangle-alert", tone: amber, problem: true, group: "apps",
+ happened: "This PC ran out of memory at " + at(when) + ", so " + name + " was closed to keep everything else running.",
+ did: "Closed " + name + " so the rest of the PC could carry on.",
+ todo: "Close apps and browser tabs you aren't using. If it keeps happening, this PC may need more memory for what you do."
+ };
+ }
+ case "drive-in": {
+ const what = d.kind === "usb" ? "A USB drive" : "A drive";
+ return {
+ title: what + " was connected",
+ detail: "It's called " + quoted(d.label) + ".",
+ icon: "security-key", tone: plain, problem: false, group: "security",
+ happened: what + " called " + quoted(d.label) + " was plugged in at " + at(when) + " and made ready to use.",
+ did: "Made it ready to use, so its files show in Files.",
+ todo: "Nothing, if it's yours. If you don't know where a drive came from, don't open files on it."
+ };
+ }
+ case "drive-yanked": {
+ const what = d.kind === "usb" ? "A USB drive" : "A drive";
+ return {
+ title: what + " was removed while it was in use",
+ detail: "Anything being copied to " + quoted(d.label) + " may not have finished.",
+ icon: "security-key", tone: red, problem: true, group: "other",
+ happened: quoted(d.label) + " was unplugged at " + at(when) + " while it was still in use, before it was ejected.",
+ did: "Tidied up after it, so it can be plugged in again.",
+ todo: "Plug it back in and check that the files you last copied to it open. Next time, choose Eject in Files before you unplug it."
+ };
+ }
+ case "signin": {
+ const where = d.how === "ssh" ? "from another computer, over SSH" + (d.from ? " from " + d.from : "")
+ : d.how === "console" ? "at a text console"
+ : d.how === "screen" ? "at the sign-in screen" : "";
+ return {
+ title: d.name + " signed in",
+ detail: d.finger ? "With a fingerprint." : d.how === "ssh" ? "From another computer, over SSH." : d.how === "console" ? "At a text console." : d.how === "screen" ? "At the sign-in screen." : "To this PC.",
+ icon: "log-in", tone: d.how === "ssh" ? blue : plain, problem: false, group: "security",
+ happened: d.name + " signed in" + (where.length > 0 ? " " + where : "") + (d.finger ? ", with a fingerprint," : "") + " at " + at(when) + ".",
+ did: d.how === "ssh" ? "Let them in once the password or key was right."
+ : d.finger ? "Started their desktop once the fingerprint matched one saved for them." : "Started their desktop once the password was right.",
+ todo: d.how === "ssh" ? "Nothing, if it was you. If it wasn't, change your password in Accounts, and turn SSH off in Privacy and security > Firewall."
+ : "Nothing, if it was you. If it wasn't, change your password in Accounts > Sign-in options."
+ };
+ }
+ case "signout":
+ return {
+ title: d.name + " signed out",
+ detail: d.since ? "After " + duration(d.since, when) + "." : "Their session ended.",
+ icon: "log-out", tone: plain, problem: false, group: "security",
+ happened: d.name + "'s session ended at " + at(when) + ", by signing out, restarting or shutting down.",
+ did: "Closed their apps and desktop.",
+ todo: "Nothing."
+ };
+ case "password": {
+ const n = d.count || 1;
+ const lastAt = new Date((d.last || 0) * 1000);
+ const span = n > 1 && Format.isValid(lastAt) && Format.time(lastAt) !== at(when) ? " between " + at(when) + " and " + Format.time(lastAt) : " at " + at(when);
+ const ssh = d.place === "ssh";
+ return {
+ title: ssh ? (n === 1 ? "Someone tried to sign in over SSH" : "Someone tried to sign in over SSH " + n + " times")
+ : d.place === "admin" ? (n === 1 ? "A wrong admin password was typed" : n + " wrong admin passwords were typed")
+ : (n === 1 ? "A wrong password was typed " : n + " wrong passwords were typed ") + passwordPlace(d.place),
+ detail: ssh ? "As " + quoted(d.user) + (d.from ? ", from " + d.from : "") + ". It was turned away."
+ : "For " + d.name + ". " + (n === 1 ? "It was" : "Each was") + " turned away.",
+ icon: "lock-round", tone: n >= 3 ? amber : plain, problem: false, group: "security",
+ happened: ssh ? countText(n, "A wrong password was", "wrong passwords were") + " given over SSH for " + quoted(d.user) + (d.from ? ", from " + d.from : "") + span + "."
+ : countText(n, "A wrong password was", "wrong passwords were") + " typed for " + d.name + " " + passwordPlace(d.place) + span + ".",
+ did: n === 1 ? "Turned it away." : "Turned each one away.",
+ todo: ssh ? "If you don't use SSH, turn it off in Privacy and security > Firewall. If you do, make sure every account has a strong password."
+ : "Nothing, if it was you mistyping. If it wasn't you, change your password in Accounts > Sign-in options."
+ };
+ }
+ case "firewall": {
+ const who = firewallWho(d.kind);
+ // The log's device is the network interface it came in on; people
+ // know the sender by its address.
+ const from = d.source;
+ const many = (d.ports || []).length > 1;
+ const n = d.count || 1;
+ const what = many ? n + " tries on " + d.ports.length + " ports" : portName(d.port, d.proto) + (n > 1 ? ", " + n + " times" : "");
+ return {
+ title: (n > 1 ? "Connections from " : "A connection from ") + who + (n > 1 ? " were blocked" : " was blocked"),
+ detail: what + ", from " + from + ".",
+ icon: "shield-round", tone: blue, problem: false, group: "security",
+ happened: who.charAt(0).toUpperCase() + who.slice(1) + " (" + d.source + ") tried to connect to this PC"
+ + (many ? " " + n + " times, on " + d.ports.length + " different ports," : " for " + portName(d.port, d.proto) + (n > 1 ? ", " + n + " times," : ""))
+ + (n > 1 ? " starting at " : " at ") + at(when) + ".",
+ did: "Turned " + (n > 1 ? "every try" : "it") + " away at the firewall. Nothing on this PC was reached.",
+ todo: "Nothing. If you were expecting it, allow it in Privacy and security > Firewall."
+ };
+ }
+ case "updates": {
+ const n = d.count || 0;
+ return {
+ title: d.auto ? "Security updates installed" : "Updates installed",
+ detail: Format.plural(n, "update", "updates") + (d.auto ? ", installed automatically." : ".") + (d.restore ? " A restore point was saved first." : ""),
+ icon: "refresh-cw", tone: green, problem: false, group: "updates",
+ happened: Format.plural(n, "update was", "updates were") + " installed" + (d.auto ? " automatically, in the background" : "") + " at " + at(when) + ".",
+ did: d.restore ? "Saved a restore point first, then installed them." : "Installed them.",
+ todo: d.restore ? "Nothing. If something stopped working since, you can go back in System > Recovery." : "Nothing."
+ };
+ }
+ case "update-failed":
+ return {
+ title: "Updates didn't finish",
+ detail: "Installing them stopped with an error.",
+ icon: "triangle-alert", tone: amber, problem: true, group: "updates",
+ happened: "Installing updates stopped partway at " + at(when) + ", with the error below.",
+ did: d.auto ? "Stopped, and will try again with the next automatic update." : "Stopped, and kept the error below.",
+ todo: "Open Updates and choose Check for updates to try again. If it fails again, send a report."
+ };
+ case "install-failed":
+ return {
+ title: (d.app && d.app.length > 0 ? d.app : "An app") + " couldn't be installed",
+ detail: "Installing it stopped with an error.",
+ icon: "triangle-alert", tone: amber, problem: true, group: "apps",
+ happened: "Installing " + (d.app && d.app.length > 0 ? d.app : (d.packages || []).join(", ")) + " stopped partway at " + at(when) + ", with the error below.",
+ did: "Stopped, and kept the error below.",
+ todo: "Try again from the Store. If it fails again, send a report."
+ };
+ case "restore-point": {
+ // The label is what Recovery lists the point under.
+ const what = d.label && d.label.length > 0 ? d.label
+ : d.kind === "manual" ? "Made by you"
+ : d.kind === "driver" ? "Before a driver was installed"
+ : d.kind === "update" ? "Before updates" : "";
+ const covers = d.summary && d.summary.length > 0 ? " It covers " + d.summary.charAt(0).toLowerCase() + d.summary.slice(1).replace(/\.$/, "") + "." : "";
+ return {
+ title: "A restore point was saved",
+ detail: what.length > 0 ? what.replace(/\.$/, "") + "." : "Wild OS can go back to it.",
+ icon: "history", tone: green, problem: false, group: "updates",
+ happened: "A copy of Wild OS's own files was saved at " + at(when) + ", so this PC can go back to how it was then." + covers,
+ did: "Kept it with the other restore points. Your own files aren't part of it and stay as they are.",
+ todo: "Nothing. To go back to it, open System > Recovery."
+ };
+ }
+ case "app-installed": {
+ const name = d.app && d.app.length > 0 ? d.app : d.id;
+ return {
+ title: name + " was installed",
+ detail: d.via === "flatpak" ? (d.remote === "flathub" ? "From Flathub, through the Store." : "From the Store.") : "From the Store.",
+ icon: "status-ok", tone: green, problem: false, group: "apps",
+ happened: name + " was installed at " + at(when) + ".",
+ did: "Installed it and added it to Start.",
+ todo: "Nothing. To remove it, open Apps > Installed apps."
+ };
+ }
+ case "app-removed": {
+ const name = d.app && d.app.length > 0 ? d.app : d.id;
+ return {
+ title: name + " was removed",
+ detail: "It's no longer on this PC.",
+ icon: "trash-round", tone: plain, problem: false, group: "apps",
+ happened: name + " was removed at " + at(when) + ".",
+ did: "Removed it from this PC and from Start.",
+ todo: "Nothing. To get it back, find it in the Store."
+ };
+ }
+ case "space-freed": {
+ // Free up space (settings-free-space), by hand or by Tidy up
+ // automatically when less than 10% of the disk was free.
+ const order = ["bin", "restorePoints", "updates", "caches", "leftovers", "winmode", "downloads"];
+ const labels = { bin: "the Recycle Bin", restorePoints: "old restore points", updates: "update files",
+ caches: "app caches", leftovers: "leftovers from removed apps",
+ winmode: "unused space inside Windows mode", downloads: "large files in Downloads" };
+ const items = d.items || {};
+ const parts = order.filter(k => items[k] > 0).map(k => labels[k]);
+ // Every item named: there are seven at most.
+ const what = parts.length <= 1 ? (parts[0] || "nothing")
+ : parts.slice(0, -1).join(", ") + " and " + parts[parts.length - 1];
+ const total = Object.keys(items).reduce((sum, k) => sum + (items[k] || 0), 0);
+ const size = System.formatBytes(total);
+ return {
+ title: d.auto ? "Space was freed up automatically" : "Space was freed up",
+ detail: size + " from " + what + ".",
+ icon: "hard-drive", tone: green, problem: false, group: "other",
+ happened: d.auto ? "Less than 10% of the disk was free at " + at(when) + ", so Wild OS cleared the items ticked in Free up space."
+ : "You freed up space at " + at(when) + ".",
+ did: "Cleared " + what + ", " + size + " in all. Your documents, pictures and settings were not touched"
+ + (items.leftovers > 0 ? ", apart from the settings of apps you had removed." : "."),
+ todo: d.auto ? "Nothing. To change what is cleared, or to turn this off, go to System > Storage > Free up space."
+ : "Nothing."
+ };
+ }
+ case "apps-updated": {
+ const names = d.apps || [];
+ return {
+ title: names.length === 1 ? (names[0] || "An app") + " was updated" : "Apps updated",
+ detail: names.length === 1 ? "To its newest version." : listNames(names) + ".",
+ icon: "refresh-cw", tone: green, problem: false, group: "updates",
+ happened: (names.length === 1 ? (names[0] || "An app") + " was" : listNames(names) + " were") + " updated at " + at(when) + ".",
+ did: "Updated " + (names.length === 1 ? "it" : "them") + " to the newest version.",
+ todo: "Nothing."
+ };
+ }
+ case "programs": {
+ const parts = [];
+ if (d.installed > 0) {
+ parts.push(Format.plural(d.installed, "program", "programs") + " installed");
+ }
+ if (d.removed > 0) {
+ parts.push(Format.plural(d.removed, "program", "programs") + " removed");
+ }
+ if (d.updated > 0) {
+ parts.push(Format.plural(d.updated, "program", "programs") + " updated");
+ }
+ const line = parts.join(", ");
+ return {
+ title: "Programs were changed",
+ detail: line.charAt(0).toUpperCase() + line.slice(1) + ", by an administrator.",
+ icon: "app-window", tone: plain, problem: false, group: "apps",
+ happened: line.charAt(0).toUpperCase() + line.slice(1) + " at " + at(when) + ", with apt, by someone with the admin password.",
+ did: "Made the changes asked for.",
+ todo: "Nothing, if it was you or someone you trust with the admin password."
+ };
+ }
+ case "backup": {
+ const drive = d.drive && d.drive.length > 0 ? d.drive : "the backup drive";
+ if (d.result === "failed") {
+ return {
+ title: "Backup didn't finish",
+ detail: d.reason && d.reason.length > 0 ? d.reason : "It stopped with an error.",
+ icon: "hard-drive", tone: amber, problem: true, group: "other",
+ happened: "A backup to " + drive + " stopped at " + at(when) + " before it finished.",
+ did: "Kept your earlier backups as they were.",
+ todo: "Open Backup to see what it needs, then choose Back up now."
+ };
+ }
+ if (d.result === "stopped") {
+ return {
+ title: "Backup was stopped",
+ detail: "It stopped before it finished.",
+ icon: "hard-drive", tone: plain, problem: false, group: "other",
+ happened: "A backup to " + drive + " was stopped at " + at(when) + " before it finished.",
+ did: "Kept your earlier backups as they were.",
+ todo: "Choose Back up now in Backup when it suits you."
+ };
+ }
+ return {
+ title: "Backup finished",
+ detail: d.files > 0 ? Format.plural(d.files, "file", "files") + " copied to " + drive + "." : "Nothing had changed since the last one.",
+ icon: "hard-drive", tone: green, problem: false, group: "other",
+ happened: "Your files were backed up to " + drive + " at " + at(when) + "." + (d.warning && d.warning.length > 0 ? " " + d.warning : ""),
+ did: d.files > 0 ? "Copied " + Format.plural(d.files, "new or changed file", "new or changed files") + " and kept the earlier versions." : "Checked every file. None had changed.",
+ todo: "Nothing."
+ };
+ }
+ case "startup":
+ return {
+ title: "This PC started",
+ detail: d.seconds !== undefined ? "Started in " + Format.plural(d.seconds, "second", "seconds") + "." : "Started.",
+ icon: "power-round", tone: plain, problem: false, group: "other",
+ happened: "This PC started" + (d.seconds !== undefined ? " in " + Format.plural(d.seconds, "second", "seconds") : "")
+ + (d.waited ? ", not counting the " + Format.plural(d.waited, "second", "seconds") + " the disk password screen waited for you" : "")
+ + ". It was ready at " + at(when) + ".",
+ did: "Unlocked the disk with your password and started Wild OS.",
+ todo: "Nothing."
+ };
+ case "shutdown":
+ case "restart": {
+ const restart = e.kind === "restart";
+ const by = d.cause === "lid" ? "when the lid was closed"
+ : d.cause === "power" ? "with the power button"
+ : d.cause === "battery" ? "because the battery was nearly flat"
+ : d.cause === "updates" ? "to finish installing updates"
+ : d.cause === "person" ? "by " + (d.user || "someone signed in")
+ : d.cause === "system" ? "by Wild OS or an administrator" : "";
+ return {
+ title: restart ? "This PC restarted" : "This PC was shut down",
+ detail: by.length > 0 ? by.charAt(0).toUpperCase() + by.slice(1) + "." : (restart ? "It restarted properly." : "It shut down properly."),
+ icon: "power-round", tone: plain, problem: false, group: "other",
+ happened: (restart ? "This PC restarted" : "This PC shut down") + (by.length > 0 ? " " + by : "") + " at " + at(when) + ", and went through a normal shutdown.",
+ did: "Closed the apps that were open and finished writing everything to the disk before " + (restart ? "restarting." : "switching off."),
+ todo: "Nothing."
+ };
+ }
+ case "unclean": {
+ const last = new Date((d.last || 0) * 1000);
+ const lid = d.lid ? new Date(d.lid * 1000) : null;
+ return {
+ title: "This PC didn't shut down properly",
+ detail: d.asleep ? "It was asleep when it stopped" + (lid ? ", with the lid closed." : ".")
+ : lid ? "The lid was closed at " + Format.time(lid) + " and it stayed on until it stopped."
+ : "It lost power or stopped responding.",
+ icon: "triangle-alert", tone: amber, problem: true, group: "other",
+ happened: "The last thing Wild OS recorded was " + dayAndTime(last) + ". After that it stopped without shutting down"
+ + (d.asleep ? ", while it was asleep" : lid ? ", with the lid closed since " + dayAndTime(lid) : "")
+ + ": the battery ran out, the power was cut, the power button was held down or it stopped responding.",
+ did: "Started normally the next time. Anything open and not saved then may have lost its latest changes.",
+ todo: d.asleep ? "A PC that is asleep still uses a little battery, and stops like this when it runs out. To have it switch off instead, set what closing the lid does to Shut down in Settings > System > Power and battery > More power settings."
+ : lid ? "Closing the lid didn't shut it down or put it to sleep. Check what closing the lid does in Settings > System > Power and battery > More power settings, and look for \"The lid was closed but the PC stayed on\" here."
+ : "If you didn't switch it off yourself and it keeps happening, send a report so it can be looked at."
+ };
+ }
+ case "sleep": {
+ const hib = d.kind === "hibernate";
+ const why = d.reason === "lid" ? "when the lid was closed"
+ : d.reason === "power" ? "with the power button"
+ : d.reason === "person" ? "when " + (d.user || "someone") + " chose Sleep or left it idle"
+ : d.reason === "system" ? "when Wild OS asked it to" : "";
+ const woke = d.woke ? new Date(d.woke * 1000) : null;
+ return {
+ title: hib ? "This PC hibernated" : "This PC went to sleep",
+ detail: woke ? "Woke up at " + Format.time(woke) + ", after " + duration(0, new Date(d.slept * 1000)) + "." : "It didn't wake up from this.",
+ icon: "moon", tone: plain, problem: false, group: "other",
+ happened: (hib ? "This PC hibernated" : "This PC went to sleep") + (why.length > 0 ? " " + why : "") + " at " + at(when) + "."
+ + (woke ? " It woke up " + dayAndTime(woke) + "." : " There is no record of it waking up: it ran out of battery or was switched off while asleep."),
+ did: hib ? "Saved everything open to the disk and switched off." : "Kept everything open in memory and used as little power as it could.",
+ todo: "Nothing."
+ };
+ }
+ case "lid-on": {
+ const apps = (d.apps || []).join(" and ");
+ const actionWords = { "nothing": "do nothing", "lock": "lock the screen", "screen-off": "turn off the screen", "ask": "ask what to do",
+ "shutdown": "shut down", "sleep": "go to sleep", "hibernate": "hibernate" };
+ const where = d.profile === "Battery" ? " on battery" : d.profile === "AC" ? " when plugged in" : "";
+ const page = "Settings > System > Power and battery > More power settings";
+ const opened = d.opened ? new Date(d.opened * 1000) : null;
+ const reason = d.reason === "app" ? "Kept on by " + apps + "."
+ : d.reason === "setting" ? "Closing the lid is set to " + actionWords[d.action] + where + "."
+ : d.reason === "screen" ? "Another screen was connected."
+ : d.reason === "held-up" ? "It started to shut down, but an app held it up."
+ : d.reason === "not-done" ? "It was set to " + (actionWords[d.action] || "act") + ", but didn't."
+ : d.reason === "signin-setting" ? "At the sign-in screen, closing the lid is set to do nothing."
+ : "Nothing recorded why.";
+ return {
+ title: "The lid was closed but the PC stayed on",
+ detail: reason,
+ icon: "computer", tone: amber, problem: true, group: "other",
+ happened: "The lid was closed at " + at(when) + " and nothing happened in the minute after: the PC didn't shut down or go to sleep. "
+ + (d.reason === "app" ? apps + " asked Wild OS not to, while it worked."
+ : d.reason === "setting" ? "That is what closing the lid is set to do" + where + "."
+ : d.reason === "screen" ? "Another screen was connected, and closing the lid is set to do nothing then."
+ : d.reason === "held-up" ? "Closing the lid is set to shut down, and it started to: Wild OS began signing out. An open app held it up, usually by asking whether to save your work, and nobody could answer with the lid closed. Once an app has asked, the shutdown is called off, so the PC stays on until it is shut down another way."
+ : d.reason === "not-done" && d.action === "shutdown" ? "It was set to shut down, but the shutdown didn't happen. An app with unsaved work can stop it."
+ : d.reason === "not-done" ? "It was set to " + (actionWords[d.action] || "act") + ", but that didn't happen."
+ : d.reason === "signin-setting" ? "Nobody was signed in, and at the sign-in screen closing the lid is set to do nothing."
+ : "")
+ + (opened ? " The lid was opened again " + dayAndTime(opened) + "." : ""),
+ did: "Kept running. A PC left on like this in a bag keeps using its battery and can get warm.",
+ todo: d.reason === "app" ? "Close " + apps + ", or let it finish, before you close the lid."
+ : d.reason === "screen" ? "To make the lid act anyway, turn on Do this even when another screen is connected in " + page + "."
+ : d.reason === "held-up" || d.reason === "not-done" && d.action === "shutdown" ? "Save your work and close apps before you close the lid, or set the lid to Sleep in " + page + ", which keeps everything as it is."
+ : "To change what closing the lid does, open " + page + "."
+ };
+ }
+ case "finger-unknown": {
+ const n = d.count || 1;
+ return {
+ title: n === 1 ? "A fingerprint wasn't recognised" : n + " fingerprints weren't recognised",
+ detail: "For " + d.name + ". " + (n === 1 ? "It was" : "Each was") + " turned away.",
+ icon: "fingerprint", tone: n >= 3 ? amber : plain, problem: false, group: "security",
+ happened: (n === 1 ? "A finger that didn't match any saved for " : n + " fingers that didn't match any saved for ") + d.name
+ + " " + (n === 1 ? "was" : "were") + " put on the reader at " + at(when) + ".",
+ did: n === 1 ? "Didn't let it in." : "Didn't let any of them in.",
+ todo: "Nothing, if it was you. If your finger often isn't recognised, add it again in Accounts > Sign-in options."
+ };
+ }
+ case "unlock":
+ return {
+ title: d.name + " unlocked the PC",
+ detail: "With a fingerprint.",
+ icon: "fingerprint", tone: plain, problem: false, group: "security",
+ happened: d.name + " unlocked the lock screen with a fingerprint at " + at(when) + ".",
+ did: "Unlocked once the fingerprint matched one saved for them.",
+ todo: "Nothing, if it was you. If it wasn't, remove the saved fingerprints in Accounts > Sign-in options."
+ };
+ case "admin-finger": {
+ const n = d.count || 1;
+ return {
+ title: n === 1 ? "An admin task was approved with a fingerprint" : n + " admin tasks were approved with a fingerprint",
+ detail: "By " + d.name + (d.by === "sudo" ? ", in Terminal." : "."),
+ icon: "fingerprint", tone: blue, problem: false, group: "security",
+ happened: d.name + " approved " + (n === 1 ? "a task that needs" : n + " tasks that need") + " the admin password with a fingerprint" + (d.by === "sudo" ? ", in Terminal," : "") + " at " + at(when) + ".",
+ did: "Let " + (n === 1 ? "it" : "them") + " go ahead once the fingerprint matched.",
+ todo: "Nothing, if it was you. To use the password instead, turn fingerprints off for admin tasks in Accounts > Sign-in options."
+ };
+ }
+ case "disk-error": {
+ const n = d.count || 1;
+ const what = d.disk === "system" ? "The system disk" : d.disk === "usb" ? "A USB drive" : "A disk";
+ return {
+ title: what + " had trouble reading or writing",
+ detail: Format.plural(n, "error", "errors") + ", on " + d.device + ".",
+ icon: "hard-drive", tone: red, problem: true, group: "other",
+ happened: what + " (" + d.device + ") couldn't read or write some of its data at " + at(when) + (n > 1 ? ", " + n + " times within the hour" : "") + ".",
+ did: "Reported the error to the program that was reading or writing. The data it was after may be damaged.",
+ todo: d.disk === "usb" ? "Copy what you need off it and use another drive. Choose Eject in Files before you unplug it."
+ : d.disk === "system" ? "Back up your files now with Backup. If it happens again, the disk may be failing."
+ : "Copy what you need off it. If it happens again, the disk may be failing."
+ };
+ }
+ case "winmode-failed": {
+ const resume = d.action === "resume";
+ return {
+ title: resume ? "Windows mode couldn't resume" : "Windows mode couldn't start",
+ detail: "Windows apps couldn't open.",
+ icon: "windowsapps", tone: amber, problem: true, group: "apps",
+ happened: (resume ? "Windows mode was asked to carry on where it left off" : "Windows mode was asked to start Windows") + " at " + at(when) + ", and it couldn't.",
+ did: "Left Windows as it was and said so on screen.",
+ todo: "Try again from Windows mode on the taskbar. If it keeps happening, restart the PC or send a report."
+ };
+ }
+ // From the camera and microphone lights on the taskbar: amber and
+ // green, as the lights are.
+ case "device-use": {
+ const camera = d.device === "camera";
+ const thing = camera ? "the camera" : "the microphone";
+ const app = d.app && d.app.length > 0 ? d.app : "An app";
+ const ended = typeof d.end === "number" ? new Date(d.end * 1000) : null;
+ const span = ended ? "From " + at(when) + " to " + at(ended) + ", " + duration(when.getTime() / 1000, ended) + "."
+ : "From " + at(when) + ".";
+ return {
+ title: app + " used " + thing,
+ detail: span,
+ icon: camera ? "camera" : "mic", tone: camera ? green : amber, problem: false, group: "security",
+ happened: app + " started using " + thing + " at " + at(when)
+ + (ended ? " and stopped at " + at(ended) + ", after " + duration(when.getTime() / 1000, ended) + "." : "."),
+ did: "Showed the " + (camera ? "camera" : "microphone") + " light on the taskbar while it was in use, and noted which app and when, nothing more.",
+ todo: "Nothing, if you expected it. If not, click the light on the taskbar while it is on: Stop cuts the app off, and the switch there turns " + thing + " off for every app."
+ };
+ }
+ case "setting": {
+ const service ={ files: "File sharing", remote: "Remote Desktop", ssh: "SSH" };
+ const levels = { standard: "Standard", strict: "Strict", maximum: "Maximum" };
+ const port = (d.proto === "udp" ? "UDP port " : "Port ") + d.port;
+ const title = d.what === "firewall" ? (d.on ? "The firewall was turned on" : "The firewall was turned off")
+ : d.what === "trust" ? (d.network || "A network") + " was set to " + (d.trust === "public" ? "Public" : "Home")
+ : d.what === "discovery" ? "Network discovery was turned " + (d.on ? "on" : "off")
+ : d.what === "service" ? (service[d.service] || d.service) + " was turned " + (d.on ? "on" : "off")
+ : d.what === "allow" ? (d.name || port) + " was allowed through the firewall"
+ : d.what === "rule" ? (d.name || port) + (d.change === "removed" ? " was removed from the firewall" : " was turned " + d.change + " in the firewall")
+ : d.what === "level" ? "Protection was set to " + (levels[d.level] || d.level)
+ : "A security setting was changed";
+ const weaker = (d.what === "firewall" && !d.on) || (d.what === "service" && d.on) || d.what === "allow"
+ || (d.what === "level" && d.level === "standard");
+ return {
+ title: title,
+ detail: (d.what === "allow" ? port + ", " + (d.scope === "anyone" ? "from anyone. " : d.scope === "device" ? "from " + d.address + " only. " : "from this network. ") : "")
+ + (d.user ? "By " + d.user + "." : "By Wild OS."),
+ icon: "shield-round", tone: weaker ? amber : blue, problem: false, group: "security",
+ happened: title + " at " + at(when) + (d.what === "level" && d.from ? ", from " + (levels[d.from] || d.from) : "") + (d.user ? ", by " + d.user : "") + ".",
+ did: d.what === "level" ? "Changed the firewall, USB and other protections to match." : "Loaded the firewall's rules again to match.",
+ todo: "Nothing, if it was you. To change it back, open Settings > Privacy and security" + (d.what === "level" ? "." : " > Firewall.")
+ };
+ }
+ case "went-back": {
+ const staged = d.how === "staged";
+ return {
+ title: staged ? "Going back to an earlier version was set up" : "This PC went back to an earlier version",
+ detail: staged ? "It happens when the PC restarts." : (d.label ? d.label.replace(/\.$/, "") + "." : "To restore point " + d.point + ".")
+ + (d.how === "recovery" ? " From start-up recovery." : ""),
+ icon: "history", tone: green, problem: false, group: "updates",
+ happened: staged ? "Going back to restore point " + d.point + (d.label ? " (" + d.label + ")" : "") + " was set up at " + at(when) + ", to happen at the next start-up."
+ : "Wild OS's own files went back to restore point " + d.point + (d.label ? " (" + d.label + ")" : "") + " at " + at(when) + (d.how === "recovery" ? ", from start-up recovery" : "") + ".",
+ did: staged ? "Saved a restore point of the version you're on first, so this can be undone." : "Put back the system files and apps of that restore point. Your own files, Wi-Fi and accounts stayed as they were.",
+ todo: staged ? "Restart when you're ready." : "To undo it, go back to \"Before going back to an earlier version\" in System > Recovery."
+ };
+ }
+ case "reset":
+ return {
+ title: "Wild OS was reset",
+ detail: "Keeping your files. A restore point was saved first.",
+ icon: "rotate-ccw", tone: green, problem: false, group: "updates",
+ happened: "Reset Wild OS started at " + at(when) + ", from start-up recovery, keeping your files.",
+ did: "Saved a restore point, then put Wild OS's own files back to the copy kept on this PC. Your files and accounts were kept.",
+ todo: "Reinstall any apps you miss from the Store. If something is wrong, go back to \"Before resetting Wild OS\" in System > Recovery."
+ };
+ }
+ return {
+ title: "Something happened", detail: "", icon: "info", tone: plain, problem: false, group: "other",
+ happened: "", did: "", todo: "Nothing."
+ };
+ }
+
+ // The board's three columns: when, which program, what it said. In a
+ // file or a report "Today" would go stale, so those get dates.
+ function techText(e, dated) {
+ const lines = e.tech || [];
+ const width = Math.min(16, Math.max(4, ...lines.map(l => l.source.length))) + 3;
+ return lines.map(l => {
+ const day = Format.day(l.when);
+ const name = dated ? Format.shortDate(l.when) : day === "today" ? "Today" : day === "yesterday" ? "Yesterday" : Format.shortDate(l.when);
+ return name + " " + Qt.formatTime(l.when, "HH:mm:ss") + " " + (l.source + " ".repeat(width)).slice(0, width) + l.text;
+ }).join("\n");
+ }
+
+ // The whole event as text, for Copy, Save as a file and the report.
+ function fullText(e, all) {
+ const w = describe(e, all);
+ return w.title + "\n" + Format.longDate(e.when) + ", " + Qt.formatTime(e.when, "HH:mm:ss") + "\n\n"
+ + "What happened\n" + w.happened + "\n\n"
+ + "What Wild OS did\n" + w.did + "\n\n"
+ + "What you can do\n" + w.todo + "\n\n"
+ + "Technical detail\n" + techText(e, true) + "\n";
+ }
+}
diff --git a/packages/wildos-settings/qml/components/Pages.qml b/packages/wildos-settings/qml/components/Pages.qml
index 360e696..ad20d99 100644
--- a/packages/wildos-settings/qml/components/Pages.qml
+++ b/packages/wildos-settings/qml/components/Pages.qml
@@ -25,7 +25,7 @@ QtObject {
keywords: "start overview recommended welcome control panel all settings" },
"system": { title: "System", icon: "system", component: "CategoryPage",
- children: ["display", "sound", "notifications", "power", "storage", "multitasking", "recovery", "about"],
+ children: ["display", "sound", "notifications", "power", "storage", "hardware", "multitasking", "recovery", "history", "about"],
keywords: "system computer pc" },
"display": { title: "Display", parent: "system", icon: "display", component: "DisplayPage", fallback: "kcm_kscreen",
description: "Monitors, brightness, resolution and scale",
@@ -48,9 +48,19 @@ QtObject {
"storage": { title: "Storage", parent: "system", icon: "storage", component: "StoragePage",
description: "Disk space and the Recycle Bin",
keywords: "disk disks space drive drives free space free up space full bin trash recycle recycle bin empty hard drive hard disk ssd clean up cleanup disk cleanup storage sense volumes partitions usage" },
+ "freespace": { title: "Free up space", parent: "storage", icon: "storage", component: "FreeSpacePage",
+ description: "Clear what Wild OS and your apps no longer need",
+ keywords: "free up space clean up cleanup disk cleanup storage sense disk full low disk space cache caches app caches temporary files temp files thumbnails recycle bin trash old restore points update files downloaded updates apt cache old kernels flatpak unused runtimes leftovers removed apps windows mode disk compact shrink large files downloads tidy up automatically" },
"recovery": { title: "Recovery", parent: "system", icon: "restore", component: "RecoveryPage",
description: "Restore points, reset and start-up options",
keywords: "recovery restore restore point restore points system restore go back roll back rollback undo update earlier version previous version snapshot snapshots reset reset this pc factory reset reinstall fresh start start-up options startup options advanced startup safe mode repair boot shift restart backup" },
+ "history": { title: "History", parent: "system", icon: "clock", component: "HistoryPage",
+ description: "What happened on this PC, in plain words",
+ keywords: "history event viewer events event log log logs reliability monitor reliability history what happened crash crashes crashed closed unexpectedly app crash problems errors error warnings sign in sign-ins signed in logon login failed password wrong password usb drive removed firewall blocked updates installed update history restore point backup installed apps removed apps audit security log journal" },
+ // Device Manager. Its id isn't "devices", which is Bluetooth and devices.
+ "hardware": { title: "Devices", parent: "system", icon: "chip", component: "DevicesPage",
+ description: "Every device in this PC, its driver and what needs you",
+ keywords: "device manager devices hardware drivers driver missing driver no driver unknown device yellow exclamation firmware missing firmware not working graphics card video card gpu wifi wi-fi adapter network adapter ethernet bluetooth sound card audio speakers microphone webcam camera fingerprint reader keyboard touchpad mouse touchscreen pen tablet game controller battery health drive health disk health smart ssd hard drive nvme storage printer scanner usb device pci model check again rescan scan for hardware changes" },
"multitasking": { title: "Multitasking", parent: "system", icon: "multitasking", component: "MultitaskingPage",
description: "Snap windows, desktops and Alt+Tab",
keywords: "snap layouts snap assist snap windows window snapping suggest fill alt tab task switcher windows side by side split screen taskbar all desktops open windows screen corners hot corners corner actions mouse corner hold key modifier quick note keep awake caffeine do not disturb turn screen off app grid title bar double click maximise minimise task view" },
@@ -139,8 +149,8 @@ QtObject {
description: "Lock screen picture and screen lock",
keywords: "lock screen picture wallpaper background login screen sign in screen" },
"taskbar": { title: "Taskbar", parent: "personalisation", icon: "taskbar", component: "TaskbarPage",
- description: "Hiding the taskbar, Windows mode status",
- keywords: "taskbar panel auto hide autohide hide taskbar clock seconds full date battery percentage show desktop peek windows mode status virtual machine" },
+ description: "Hiding the taskbar, End task, Windows mode status",
+ keywords: "taskbar panel auto hide autohide hide taskbar clock seconds full date battery percentage show desktop peek end task kill force close force quit not responding frozen hung windows mode status virtual machine" },
"fonts": { title: "Fonts", parent: "personalisation", icon: "font", component: "FontsPage",
description: "Install and remove fonts",
keywords: "font fonts typeface install font remove font ttf otf typography" },
@@ -204,7 +214,7 @@ QtObject {
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 protection level encryption firewall secure boot sandbox usb block usb usage data telemetry diagnostics windows security steam 32-bit 32 bit ia32 i386 games old apps compatibility controller controllers gamepad joystick steam input remote play performance overlay fps frame rate frametime mangohud" },
+ keywords: "security privacy protection protection level encryption firewall secure boot sandbox usb block usb usage data telemetry diagnostics windows security steam 32-bit 32 bit ia32 i386 games old apps compatibility controller controllers gamepad joystick steam input remote play performance overlay fps frame rate frametime mangohud processor cpu extra processor protection spectre meltdown mitigations hyperthreading smt threads" },
"apppermissions": { title: "App permissions", parent: "privacy", icon: "sandbox", component: "AppPermissionsPage", fallback: "kcm_flatpak",
description: "What apps from the Store can reach",
keywords: "permissions sandbox app access store apps flatpak" },
@@ -226,6 +236,17 @@ QtObject {
"apppermissionsadvanced": { title: "Everything an app can reach", parent: "apppermissions", icon: "sandbox", component: "AppPermissionsAdvancedPage",
description: "Every sandbox permission, app by app",
keywords: "flatpak permissions dbus d-bus environment variables devices sockets filesystem override reset advanced" },
+ "firewall": { title: "Firewall", parent: "privacy", icon: "firewall", component: "FirewallPage",
+ description: "What other computers can reach on this PC",
+ keywords: "firewall network protection public network private network home network trusted network allow app allow port open port port forwarding blocked connections incoming connections network discovery file sharing smb samba remote desktop rdp ssh server windows defender firewall" },
+ "advancedprotection": { title: "Advanced protection", parent: "privacy", icon: "shield", component: "AdvancedProtectionPage",
+ description: "Extra protection for people who want it",
+ keywords: "advanced protection extra protection hardening locked lock screen usb usb devices while locked quiet lock screen notifications on lock screen hide notification content fingerprint password after restart fingerprint timeout restart when locked auto restart reboot encrypted disk wi-fi bluetooth switch off automatically radios idle encrypted dns dns over tls dot quad9 mullvad cloudflare vpn only kill switch block internet without vpn camera light microphone light clipboard passwords clear clipboard presenting mode screen sharing do not disturb remove personal details metadata exif location password-locked usb sticks encrypt usb drive guest session guest account safe box sandbox panic key panic button reset to defaults" },
+ // KDE's Remote Desktop module, for the accounts other PCs sign in
+ // with once Remote Desktop is on (Firewall).
+ "remotedesktop": { title: "Remote Desktop sign-in", parent: "firewall", icon: "display", kcm: "kcm_krdpserver",
+ description: "Who can sign in to this PC from another one",
+ keywords: "remote desktop rdp krdp sign in username password certificate" },
"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 auto lock timeout password sign in wake waking sleep" },
diff --git a/packages/wildos-settings/qml/components/PathIcon.qml b/packages/wildos-settings/qml/components/PathIcon.qml
index 367f7c6..70a7dea 100644
--- a/packages/wildos-settings/qml/components/PathIcon.qml
+++ b/packages/wildos-settings/qml/components/PathIcon.qml
@@ -41,7 +41,51 @@ Item {
"folder-check": "M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2ZM9 13l2 2 4-4",
"trash-round": "M3 6h18M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2M10 11v6M14 11v6",
"x-mark": "M18 6 6 18M6 6l12 12",
- "plus-thin": "M5 12h14M12 5v14"
+ "plus-thin": "M5 12h14M12 5v14",
+ // Privacy and security > Firewall and its dialogs
+ // (SettingsFirewall.dc, FirewallAllow.dc, FirewallActivity.dc).
+ "shield-round-alert": "M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1zM12 8v4M12 16h.01",
+ "wifi-round": "M12 20h.01M2 8.82a15 15 0 0 1 20 0M5 12.859a10 10 0 0 1 14 0M8.5 16.429a5 5 0 0 1 7 0",
+ "ethernet": "M3 7h18a1 1 0 0 1 1 1v9a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V8a1 1 0 0 1 1-1ZM7 14v-3M11 14v-3M15 14v-3M19 14v-3",
+ "printer-round": "M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2M6 9V3a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v6M7 14h10a1 1 0 0 1 1 1v6a1 1 0 0 1-1 1H7a1 1 0 0 1-1-1v-6a1 1 0 0 1 1-1Z",
+ "folder-round": "M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",
+ "monitor-round": "M4 3h16a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2ZM8 21h8M12 17v4",
+ "terminal-round": "M4 17l6-6-6-6M12 19h8",
+ "server": "M4 2h16a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2ZM4 14h16a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-4a2 2 0 0 1 2-2ZM6 6h.01M6 18h.01",
+ "router": "M4 14h16a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-4a2 2 0 0 1 2-2ZM6.01 18H6M10.01 18H10M15 10v4M17.84 7.17a4 4 0 0 0-5.66 0M20.66 4.34a8 8 0 0 0-11.31 0",
+ "globe-round": "M2 12a10 10 0 1 0 20 0a10 10 0 1 0 -20 0ZM12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20M2 12h20",
+ "triangle-alert": "M21.73 18l-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3M12 9v4M12 17h.01",
+ // System > History (SettingsHistory.dc): updates, and signing out.
+ "refresh-cw": "M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8M21 3v5h-5M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16M8 16H3v5",
+ "log-out": "M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4M16 17l5-5-5-5M21 12H9",
+ // System > Devices (SettingsDevices.dc): sound and camera rows.
+ "volume-round": "M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298zM16 9a5 5 0 0 1 0 6M19.364 18.364a9 9 0 0 0 0-12.728",
+ "camera-round": "M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3zM9 13a3 3 0 1 0 6 0a3 3 0 1 0 -6 0Z",
+ // Printers and scanners (SettingsPrinters.dc): scanners, the
+ // test page and the search row.
+ "scan-line": "M3 7V5a2 2 0 0 1 2-2h2M17 3h2a2 2 0 0 1 2 2v2M21 17v2a2 2 0 0 1-2 2h-2M7 21H5a2 2 0 0 1-2-2v-2M7 12h10",
+ "file-text": "M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7ZM14 2v4a2 2 0 0 0 2 2h4M10 9H8M16 13H8M16 17H8",
+ "search-round": "M3 11a8 8 0 1 0 16 0a8 8 0 1 0 -16 0ZM21 21l-4.3-4.3",
+ // Storage > Free up space (SettingsFreeSpace.dc).
+ "download-round": "M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 10l5 5 5-5M12 15V3",
+ "layers": "m12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83ZM22 17.65l-9.17 4.16a2 2 0 0 1-1.66 0L2 17.65M22 12.65l-9.17 4.16a2 2 0 0 1-1.66 0L2 12.65",
+ "package": "M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73zM12 22V12M3.3 7l7.703 4.734a2 2 0 0 0 1.994 0L20.7 7M7.5 4.27l9 5.15",
+ "info-round": "M2 12a10 10 0 1 0 20 0a10 10 0 1 0 -20 0ZM12 16v-4M12 8h.01",
+ // Privacy and security > Advanced protection (AdvancedProtection.dc,
+ // AdvancedProtection2.dc).
+ "usb-round": "M9 7a1 1 0 1 0 2 0a1 1 0 1 0 -2 0ZM3 20a1 1 0 1 0 2 0a1 1 0 1 0 -2 0ZM4.7 19.3 19 5M21 3l-3 1 2 2ZM9.26 7.68 5 12l2 5M10 14l5 2 3.5-3.5M18 12l1-1 1 1-1 1Z",
+ "eye-off-round": "M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49M14.084 14.158a3 3 0 0 1-4.242-4.242M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143M2 2l20 20",
+ "wifi-off-round": "M12 20h.01M8.5 16.429a5 5 0 0 1 7 0M5 12.859a10 10 0 0 1 5.17-2.69M19 12.859a10 10 0 0 0-2.007-1.523M2 8.82a15 15 0 0 1 4.177-2.643M22 8.82a15 15 0 0 0-11.288-3.764M2 2l20 20",
+ "globe-lock": "M15.686 15A14.5 14.5 0 0 1 12 22a14.5 14.5 0 0 1 0-20 10 10 0 1 0 9.542 13M2 12h8.5M20 6V4a2 2 0 1 0-4 0v2M15 6h6a1 1 0 0 1 1 1v3a1 1 0 0 1 -1 1h-6a1 1 0 0 1 -1 -1v-3a1 1 0 0 1 1 -1Z",
+ "shield-off": "M2 2l20 20M5 5a1 1 0 0 0-1 1v7c0 5 3.5 7.5 7.67 8.94a1 1 0 0 0 .67.01c2.35-.82 4.48-1.97 5.9-3.71M9.309 3.652A12.252 12.252 0 0 0 11.24 2.28a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1v7a9.784 9.784 0 0 1-.08 1.264",
+ "video-round": "M16 13l5.223 3.482a.5.5 0 0 0 .777-.416V7.87a.5.5 0 0 0-.752-.432L16 10.5M4 6h10a2 2 0 0 1 2 2v8a2 2 0 0 1 -2 2h-10a2 2 0 0 1 -2 -2v-8a2 2 0 0 1 2 -2Z",
+ "clipboard-x": "M9 2h6a1 1 0 0 1 1 1v2a1 1 0 0 1 -1 1h-6a1 1 0 0 1 -1 -1v-2a1 1 0 0 1 1 -1ZM16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2M15 11l-6 6M9 11l6 6",
+ "presentation": "M2 3h20M21 3v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V3M7 21l5-5 5 5",
+ "image-off": "M2 2L22 22M10.41 10.41a2 2 0 1 1-2.83-2.83M13.5 13.5L6 21M18 12L21 15M3.59 3.59A1.99 1.99 0 0 0 3 5v14a2 2 0 0 0 2 2h14c.55 0 1.052-.22 1.41-.59M21 15V5a2 2 0 0 0-2-2H9",
+ "user-round": "M7 8a5 5 0 1 0 10 0a5 5 0 1 0 -10 0ZM20 21a8 8 0 0 0-16 0",
+ "box": "M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16ZM3.3 7l8.7 5 8.7-5M12 22V12",
+ "siren": "M7 18v-6a5 5 0 1 1 10 0v6M5 21a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-1a2 2 0 0 0-2-2H7a2 2 0 0 0-2 2zM21 12h1M18.5 4.5 18 5M2 12h1M12 2v1M4.929 4.929l.707.707M12 12v6",
+ "flame": "M8.5 14.5A2.5 2.5 0 0 0 11 12c0-1.38-.5-2-1-3-1.072-2.143-.224-4.054 2-6 .5 2.5 2 4.9 4 6.5 2 1.6 3 3.5 3 5.5a7 7 0 1 1-14 0c0-1.153.433-2.294 1-3a2.5 2.5 0 0 0 2.5 2.5z",
})
readonly property bool own: paths[name] !== undefined
diff --git a/packages/wildos-settings/qml/components/Protection.qml b/packages/wildos-settings/qml/components/Protection.qml
index 6bafa0d..ed9a565 100644
--- a/packages/wildos-settings/qml/components/Protection.qml
+++ b/packages/wildos-settings/qml/components/Protection.qml
@@ -9,6 +9,29 @@ import WildOS.Settings
// needing a look, not as fine.
QtObject {
readonly property var status: System.security
+
+ // The firewall's switch changes what the tiles say at once, not at the
+ // next check.
+ property Connections firewallSwitch: Connections {
+ target: Firewall
+ function onDone(what) {
+ if (what === "enabled") {
+ System.refreshSecurity();
+ }
+ }
+ }
+
+ // USB protection is Advanced protection's usb_locked; a failed or
+ // cancelled change refreshes too, so the switches go back to the truth.
+ property Connections advancedSwitch: Connections {
+ target: Advanced
+ function onBusyChanged() {
+ if (!Advanced.busy) {
+ System.refreshSecurity();
+ }
+ }
+ }
+
readonly property bool live: status.live === "yes"
function count(key) {
diff --git a/packages/wildos-settings/qml/components/SecurityCard.qml b/packages/wildos-settings/qml/components/SecurityCard.qml
index ad93d0f..3d55e04 100644
--- a/packages/wildos-settings/qml/components/SecurityCard.qml
+++ b/packages/wildos-settings/qml/components/SecurityCard.qml
@@ -119,7 +119,8 @@ HomeCard {
title: modelData.title
value: card.rowValue(modelData)
valueColor: rowTone === "warn" ? UI.Style.warning : UI.Style.inkMuted
- onClicked: protectionDialog.show(modelData)
+ // The firewall has a page of its own to change it on.
+ onClicked: modelData.key === "firewall" && Firewall.available ? Navigator.open("firewall") : protectionDialog.show(modelData)
}
}
diff --git a/packages/wildos-settings/qml/components/Segmented.qml b/packages/wildos-settings/qml/components/Segmented.qml
new file mode 100644
index 0000000..9e3bc18
--- /dev/null
+++ b/packages/wildos-settings/qml/components/Segmented.qml
@@ -0,0 +1,72 @@
+import QtQuick
+import QtQuick.Templates as T
+import WildOS.UI as UI
+
+// A small segmented control, as the firewall boards draw it
+// (SettingsFirewall.dc, FirewallAllow.dc, FirewallActivity.dc): a 0.05
+// well with a 0.10 edge and 2px inside it, 26px segments with 12px either
+// side, the chosen one on a 0.12 fill in semibold, the others muted.
+Rectangle {
+ id: control
+
+ // [{ value, text }]
+ property var options: []
+ property var value
+ signal picked(var value)
+
+ implicitWidth: row.implicitWidth + 6
+ implicitHeight: 32
+ radius: 7
+ color: UI.Style.tone(0.05)
+ border.width: 1
+ border.color: UI.Style.tone(0.10)
+ opacity: enabled ? 1 : 0.5
+
+ Row {
+ id: row
+ anchors.centerIn: parent
+
+ Repeater {
+ model: control.options
+
+ T.AbstractButton {
+ id: segment
+ required property var modelData
+ readonly property bool chosen: control.value === modelData.value
+
+ implicitWidth: label.implicitWidth + 24
+ implicitHeight: 26
+ hoverEnabled: true
+ focusPolicy: Qt.StrongFocus
+ Accessible.role: Accessible.RadioButton
+ Accessible.name: modelData.text
+ Accessible.checked: chosen
+ onClicked: {
+ if (!chosen) {
+ control.picked(modelData.value);
+ }
+ }
+
+ background: Rectangle {
+ radius: 5
+ color: segment.chosen ? UI.Style.tone(0.12) : segment.hovered && segment.enabled ? UI.Style.tone(0.06) : "transparent"
+
+ UI.FocusRing {
+ visible: segment.visualFocus
+ targetRadius: 5
+ }
+ }
+
+ contentItem: UI.Label {
+ id: label
+ text: segment.modelData.text
+ size: 12.5
+ horizontalAlignment: Text.AlignHCenter
+ verticalAlignment: Text.AlignVCenter
+ font.weight: segment.chosen ? UI.Style.weightSemiBold : UI.Style.weightRegular
+ color: segment.chosen ? UI.Style.ink : UI.Style.inkMuted
+ }
+ }
+ }
+ }
+}
diff --git a/packages/wildos-settings/qml/pages/AccessibilityPage.qml b/packages/wildos-settings/qml/pages/AccessibilityPage.qml
index e5345b9..6950376 100644
--- a/packages/wildos-settings/qml/pages/AccessibilityPage.qml
+++ b/packages/wildos-settings/qml/pages/AccessibilityPage.qml
@@ -1,4 +1,6 @@
import QtQuick
+import QtCore
+import QtQuick.Dialogs
import QtQuick.Layouts
import QtQuick.Templates as T
import WildOS.Settings
@@ -154,6 +156,38 @@ PageScroll {
onClicked: Accessibility.setPointerColour(modelData.id)
}
}
+
+ // A pointer of your own, as Windows lets you
+ // browse for one: a plus until there is one,
+ // then its picture.
+ UI.Swatch {
+ colour: UI.Style.surfaceSunken
+ name: "Your own"
+ selected: Accessibility.pointerColour === "custom"
+ enabled: !Accessibility.pointerBusy
+ onClicked: Accessibility.customPointer ? ownPointerDialog.open() : pointerFile.open()
+
+ contentItem: Item {
+ Image {
+ anchors.centerIn: parent
+ width: 16
+ height: 16
+ visible: Accessibility.customPointer
+ source: Accessibility.customPointerPreview
+ sourceSize: Qt.size(32, 32)
+ fillMode: Image.PreserveAspectFit
+ cache: false
+ }
+
+ UI.Icon {
+ anchors.centerIn: parent
+ visible: !Accessibility.customPointer
+ name: "plus"
+ size: 12
+ color: UI.Style.iconMuted
+ }
+ }
+ }
}
}
}
@@ -425,4 +459,168 @@ PageScroll {
}
}
}
+
+ FileDialog {
+ id: pointerFile
+ title: "Choose a pointer"
+ nameFilters: ["Pointers and pictures (*.cur *.ani *.zip *.inf *.png *.svg)", "Windows pointers (*.cur *.ani)",
+ "Windows pointer packs (*.zip *.inf)", "Pictures (*.png *.svg)"]
+ currentFolder: StandardPaths.writableLocation(StandardPaths.DownloadLocation)
+ onAccepted: {
+ if (/\.(png|svg)$/i.test(selectedFile.toString())) {
+ hotspotDialog.choose(selectedFile);
+ } else {
+ Accessibility.addPointer(selectedFile);
+ }
+ }
+ }
+
+ UI.Dialog {
+ id: ownPointerDialog
+ title: "Your own pointer"
+ text: (Accessibility.customPointerSource.length > 0 ? "Made from " + Accessibility.customPointerSource + ". " : "")
+ + (Accessibility.pointerColour === "custom"
+ ? "Choose another file to replace it, or remove it to go back to the white pointer."
+ : "Use it again, choose another file to replace it, or remove it.")
+
+ Image {
+ Layout.preferredWidth: 48
+ Layout.preferredHeight: 48
+ source: Accessibility.customPointerPreview
+ sourceSize: Qt.size(96, 96)
+ fillMode: Image.PreserveAspectFit
+ cache: false
+ }
+
+ buttons: [
+ UI.Button {
+ text: "Use it"
+ kind: "primary"
+ visible: Accessibility.pointerColour !== "custom"
+ onClicked: {
+ ownPointerDialog.close();
+ Accessibility.setPointerColour("custom");
+ }
+ },
+ UI.Button {
+ text: "Choose another file"
+ onClicked: {
+ ownPointerDialog.close();
+ pointerFile.open();
+ }
+ },
+ UI.Button {
+ text: "Remove"
+ onClicked: {
+ ownPointerDialog.close();
+ Accessibility.removeCustomPointer();
+ }
+ },
+ UI.Button {
+ text: "Cancel"
+ onClicked: ownPointerDialog.close()
+ }
+ ]
+ }
+
+ // A picture has no hotspot of its own: it points from the top-left
+ // corner unless you click somewhere else on it.
+ UI.Dialog {
+ id: hotspotDialog
+
+ property url file
+ property real hotX: 0
+ property real hotY: 0
+
+ function choose(url) {
+ file = url;
+ hotX = 0;
+ hotY = 0;
+ open();
+ }
+
+ title: "Where does it point?"
+ text: "Click the spot on the picture that does the clicking."
+
+ Item {
+ Layout.alignment: Qt.AlignHCenter
+ Layout.preferredWidth: 160
+ Layout.preferredHeight: 160
+
+ Rectangle {
+ anchors.fill: parent
+ radius: 8
+ color: UI.Style.surfaceSunken
+ }
+
+ Image {
+ anchors.centerIn: parent
+ width: 136
+ height: 136
+ source: hotspotDialog.file
+ sourceSize: Qt.size(272, 272)
+ fillMode: Image.PreserveAspectFit
+ cache: false
+
+ MouseArea {
+ x: (parent.width - parent.paintedWidth) / 2
+ y: (parent.height - parent.paintedHeight) / 2
+ width: parent.paintedWidth
+ height: parent.paintedHeight
+ cursorShape: Qt.CrossCursor
+ onClicked: mouse => {
+ hotspotDialog.hotX = Math.max(0, Math.min(1, mouse.x / width));
+ hotspotDialog.hotY = Math.max(0, Math.min(1, mouse.y / height));
+ }
+
+ Rectangle {
+ x: hotspotDialog.hotX * parent.width - width / 2
+ y: hotspotDialog.hotY * parent.height - height / 2
+ width: 12
+ height: 12
+ radius: 6
+ color: "transparent"
+ border.width: 2
+ border.color: UI.Style.accent
+ }
+ }
+ }
+ }
+
+ buttons: [
+ UI.Button {
+ text: "Use it"
+ kind: "primary"
+ onClicked: {
+ hotspotDialog.close();
+ Accessibility.addPointer(hotspotDialog.file, hotspotDialog.hotX, hotspotDialog.hotY);
+ }
+ },
+ UI.Button {
+ text: "Cancel"
+ onClicked: hotspotDialog.close()
+ }
+ ]
+ }
+
+ UI.Dialog {
+ id: pointerError
+ title: "Couldn't use that file"
+ buttons: [
+ UI.Button {
+ text: "OK"
+ kind: "primary"
+ onClicked: pointerError.close()
+ }
+ ]
+ }
+
+ Connections {
+ target: Accessibility
+
+ function onPointerFailed(message) {
+ pointerError.text = message;
+ pointerError.open();
+ }
+ }
}
diff --git a/packages/wildos-settings/qml/pages/AdvancedProtectionPage.qml b/packages/wildos-settings/qml/pages/AdvancedProtectionPage.qml
new file mode 100644
index 0000000..bc135c4
--- /dev/null
+++ b/packages/wildos-settings/qml/pages/AdvancedProtectionPage.qml
@@ -0,0 +1,600 @@
+import QtQuick
+import QtQuick.Layouts
+import org.kde.notificationmanager as NotificationManager
+import WildOS.Settings
+import WildOS.UI as UI
+
+// Privacy and security > Advanced protection (AdvancedProtection.dc,
+// AdvancedProtection2.dc): extra protection, none of it needed every day.
+// Every choice is kept by the root helper settings-advanced in one store
+// (Advanced), and the part of Wild OS that carries it out reads it or runs
+// a hook when it changes. A row whose part isn't installed is left out, so
+// no switch here does nothing.
+//
+// Three rows are the same switch as one elsewhere and show that switch's
+// own state: USB is Block new USB devices (USBGuard), the VPN row is the
+// kill switch in Advanced network settings, and presenting mode is the
+// Notifications page's do not disturb while sharing the screen. Strict and
+// Maximum protection switch some of these on (settings-advanced level),
+// never one the person set here.
+PageScroll {
+ id: page
+
+ readonly property var values: Advanced.values
+ readonly property var installed: Advanced.installed
+ readonly property bool ready: Advanced.available && !Advanced.busy
+
+ readonly property bool usbShown: Protection.status.devices !== undefined
+ readonly property bool usbOn: Protection.status.devices === "on"
+ readonly property bool hasVpn: NetworkSettings.vpns.length > 0
+ readonly property bool presentingOn: notifications.inhibitNotificationsWhenScreenSharing && notifications.inhibitNotificationsWhenScreensMirrored
+
+ // Each row shown, and whether it is on; the lights are always on.
+ readonly property var rows: [
+ { shown: page.usbShown, on: page.usbOn },
+ { shown: page.installed.quiet_lock === true, on: page.values.quiet_lock === "on" },
+ { shown: true, on: page.values.fingerprint_hours > 0 },
+ { shown: true, on: page.values.restart_locked_hours > 0 },
+ { shown: true, on: page.values.radios_idle_off === "on" },
+ { shown: true, on: page.values.dns !== "off" },
+ { shown: true, on: NetworkSettings.killSwitch },
+ { shown: true, on: true },
+ { shown: true, on: page.values.clipboard_forget === "on" },
+ { shown: true, on: page.presentingOn },
+ { shown: page.installed.scrub_files === true, on: page.values.scrub_files === "on" },
+ { shown: true, on: page.values.usb_encrypt === "on" },
+ { shown: page.installed.guest === true, on: page.values.guest === "on" },
+ { shown: page.installed.safebox === true, on: page.values.safebox === "on" },
+ { shown: page.installed.panic_key === true, on: page.values.panic_key === "on" }
+ ]
+ readonly property int shownCount: rows.filter(r => r.shown).length
+ readonly property int onCount: rows.filter(r => r.shown && r.on).length
+
+ NotificationManager.Settings {
+ id: notifications
+ live: true
+ }
+
+ Notice {
+ id: notice
+ Layout.fillWidth: true
+ }
+
+ Connections {
+ target: Advanced
+ function onFailed(key, message) {
+ notice.show("Nothing was changed", message, true);
+ }
+ function onDone(key) {
+ notice.hide();
+ }
+ }
+
+ // A row with a switch, and a drop-down before it when it has one.
+ component OptionRow: UI.SettingRow {
+ id: optionRow
+
+ property string glyph
+ property bool on
+ property bool switchEnabled: page.ready
+ property bool locked: false
+ property string lockedReason
+ // What goes before the switch: a drop-down, or the panic key.
+ property alias extra: extraRow.data
+ signal switched(bool on)
+
+ width: parent ? parent.width : implicitWidth
+ minHeight: 54
+ leading: PathIcon {
+ anchors.verticalCenter: parent.verticalCenter
+ name: optionRow.glyph
+ size: 19
+ strokeWidth: 1.8
+ color: UI.Style.ink
+ }
+
+ Row {
+ id: extraRow
+ anchors.verticalCenter: parent.verticalCenter
+ spacing: 10
+ visible: children.length > 0
+ }
+
+ UI.Toggle {
+ id: toggle
+ anchors.verticalCenter: parent.verticalCenter
+ checked: optionRow.on
+ enabled: optionRow.switchEnabled
+ locked: optionRow.locked
+ lockedReason: optionRow.lockedReason
+ Accessible.name: optionRow.title
+ onToggled: optionRow.switched(checked)
+
+ // A cancelled password leaves the choice as it was, so the
+ // switch goes back to it.
+ Connections {
+ target: Advanced
+ function onChanged() {
+ toggle.checked = Qt.binding(() => optionRow.on);
+ }
+ }
+ Connections {
+ target: NetworkSettings
+ function onKillSwitchChanged() {
+ toggle.checked = Qt.binding(() => optionRow.on);
+ }
+ }
+ }
+ }
+
+ // A note in place of a switch ("Always on").
+ component NoteRow: UI.SettingRow {
+ id: noteRow
+
+ property string glyph
+ property string note
+
+ width: parent ? parent.width : implicitWidth
+ minHeight: 54
+ leading: PathIcon {
+ anchors.verticalCenter: parent.verticalCenter
+ name: noteRow.glyph
+ size: 19
+ strokeWidth: 1.8
+ color: UI.Style.ink
+ }
+
+ UI.Label {
+ anchors.verticalCenter: parent.verticalCenter
+ text: noteRow.note
+ size: 12.5
+ color: UI.Style.inkSubtle
+ }
+ }
+
+ component Heading: RowLayout {
+ property alias text: title.text
+ property alias trailing: trailingItems.data
+
+ Layout.fillWidth: true
+ Layout.topMargin: 4
+ Layout.bottomMargin: -4
+ spacing: 12
+
+ SectionTitle {
+ id: title
+ Layout.fillWidth: true
+ }
+
+ Row {
+ id: trailingItems
+ }
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 16
+
+ // How much is switched on.
+ Rectangle {
+ Layout.fillWidth: true
+ implicitHeight: heroRow.implicitHeight + 28
+ radius: 12
+ color: UI.Style.tone(0.05)
+ border.width: 1
+ border.color: UI.Style.tone(0.07)
+
+ RowLayout {
+ id: heroRow
+ anchors.left: parent.left
+ anchors.right: parent.right
+ anchors.verticalCenter: parent.verticalCenter
+ anchors.leftMargin: 18
+ anchors.rightMargin: 18
+ spacing: 18
+
+ Rectangle {
+ Layout.preferredWidth: 46
+ Layout.preferredHeight: 46
+ radius: 23
+ color: Qt.rgba(95 / 255, 211 / 255, 141 / 255, 0.16)
+
+ PathIcon {
+ anchors.centerIn: parent
+ name: "shield-round-check"
+ size: 24
+ strokeWidth: 2.1
+ color: "#5fd38d"
+ }
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 3
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: page.onCount + " of " + page.shownCount + " switched on"
+ size: 16.5
+ font.weight: UI.Style.weightSemiBold
+ wrapMode: Text.Wrap
+ }
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: "Extra protection for people who want it. None of it is needed for everyday use."
+ size: 13
+ color: UI.Style.inkMuted
+ wrapMode: Text.Wrap
+ }
+ }
+
+ UI.Button {
+ implicitHeight: 32
+ text: "Reset to defaults"
+ enabled: page.ready
+ busy: Advanced.busyKey === "reset"
+ onClicked: resetDialog.open()
+ }
+ }
+ }
+
+ Heading {
+ text: "When this PC is locked"
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ // The same switch as Block new USB devices: USBGuard, plus
+ // holding back every new device while locked
+ // (wildos-usb-lock).
+ OptionRow {
+ visible: page.usbShown
+ glyph: "usb-round"
+ title: "Ignore new USB devices while locked"
+ description: "A stick or cable plugged into a locked PC does nothing until you sign in."
+ on: page.usbOn
+ onSwitched: on => Advanced.set("usb_locked", on)
+ }
+
+ OptionRow {
+ visible: page.installed.quiet_lock === true
+ glyph: "eye-off-round"
+ title: "Quiet lock screen"
+ description: "Notifications show that something arrived, never what it says."
+ on: page.values.quiet_lock === "on"
+ onSwitched: on => Advanced.set("quiet_lock", on)
+ }
+
+ // fingerprint-turn and pam_wildos_fingerprint read it.
+ OptionRow {
+ id: fingerprintRow
+ glyph: "fingerprint"
+ title: "Fingerprint needs your password sometimes"
+ description: "Always after a restart, and again after this long."
+ on: page.values.fingerprint_hours > 0
+ onSwitched: on => Advanced.set("fingerprint_hours", on ? fingerprintBox.currentValue : 0)
+
+ extra: UI.ComboBox {
+ id: fingerprintBox
+ width: 120
+ enabled: page.ready
+ Accessible.name: "How long the fingerprint works before the password is needed"
+ model: [
+ { value: 4, text: "4 hours" },
+ { value: 8, text: "8 hours" },
+ { value: 12, text: "12 hours" },
+ { value: 24, text: "24 hours" },
+ { value: 48, text: "48 hours" },
+ { value: 72, text: "72 hours" }
+ ]
+ readonly property int stored: page.values.fingerprint_hours > 0 ? page.values.fingerprint_hours : 48
+ currentIndex: Math.max(0, model.findIndex(o => o.value === stored))
+ onActivated: Advanced.set("fingerprint_hours", currentValue)
+ }
+ }
+
+ // wildos-advanced-session, in the person's session.
+ OptionRow {
+ glyph: "power-round"
+ title: "Restart when left locked"
+ description: "Puts the disk back to fully encrypted."
+ on: page.values.restart_locked_hours > 0
+ onSwitched: on => Advanced.set("restart_locked_hours", on ? restartBox.currentValue : 0)
+
+ extra: [
+ UI.ComboBox {
+ id: restartBox
+ width: 150
+ enabled: page.ready
+ Accessible.name: "Restart after"
+ model: [
+ { value: 4, text: "After 4 hours" },
+ { value: 8, text: "After 8 hours" },
+ { value: 12, text: "After 12 hours" },
+ { value: 18, text: "After 18 hours" },
+ { value: 24, text: "After 24 hours" },
+ { value: 48, text: "After 48 hours" }
+ ]
+ readonly property int stored: page.values.restart_locked_hours > 0 ? page.values.restart_locked_hours : 18
+ currentIndex: Math.max(0, model.findIndex(o => o.value === stored))
+ onActivated: Advanced.set("restart_locked_hours", currentValue)
+ },
+ // What happens when an app is still open with work
+ // in it: the list says it in full, the box in short.
+ UI.ComboBox {
+ width: 160
+ visible: page.values.restart_locked_hours > 0
+ enabled: page.ready
+ Accessible.name: "When apps are still open"
+ model: [
+ { value: "off", text: "Wait for open apps to close", short: "Wait for apps" },
+ { value: "on", text: "Close open apps anyway (unsaved work may be lost)", short: "Close apps anyway" }
+ ]
+ currentIndex: page.values.restart_locked_force === "on" ? 1 : 0
+ displayText: model[currentIndex].short
+ onActivated: Advanced.set("restart_locked_force", currentValue)
+ }
+ ]
+ }
+ }
+ }
+
+ Heading {
+ text: "Network"
+ trailing: UI.LinkButton {
+ text: "Firewall"
+ visible: Firewall.available
+ onClicked: Navigator.open("firewall")
+ }
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ // wildos-radios-idle, which the hook starts and stops.
+ OptionRow {
+ glyph: "wifi-off-round"
+ title: "Wi-Fi and Bluetooth switch themselves off"
+ description: "When nothing has been connected for 30 minutes."
+ on: page.values.radios_idle_off === "on"
+ onSwitched: on => Advanced.set("radios_idle_off", on)
+ }
+
+ // wildos-network. On is encrypted wherever the network
+ // allows it, and on every network or not at all under
+ // Maximum protection (dns_strict); off leaves each network
+ // on its own servers, unencrypted.
+ OptionRow {
+ glyph: "globe-lock"
+ title: "Encrypted DNS"
+ description: "Your internet provider cannot see which sites you look up."
+ on: page.values.dns !== "off"
+ onSwitched: on => Advanced.set("dns", on)
+
+ extra: UI.ComboBox {
+ width: 120
+ enabled: page.ready
+ Accessible.name: "Encrypted DNS provider"
+ model: [
+ { value: "quad9", text: "Quad9" },
+ { value: "mullvad", text: "Mullvad" },
+ { value: "cloudflare", text: "Cloudflare" }
+ ]
+ currentIndex: Math.max(0, model.findIndex(o => o.value === page.values.dns_provider))
+ onActivated: Advanced.set("dns_provider", currentValue)
+ }
+ }
+
+ // The kill switch of Advanced network settings itself.
+ OptionRow {
+ glyph: "shield-off"
+ title: "Block everything unless the VPN is on"
+ description: NetworkSettings.killSwitchState === "blocking" ? "The VPN dropped, so the internet is blocked until it connects again or you turn this off."
+ : NetworkSettings.killSwitchState === "mullvad" ? "The Mullvad app's own kill switch is guarding its connection."
+ : "Nothing leaks if the VPN drops. Needs a VPN set up first."
+ descriptionColor: NetworkSettings.killSwitchState === "blocking" ? UI.Style.warning : UI.Style.inkMuted
+ on: NetworkSettings.killSwitch
+ switchEnabled: NetworkSettings.busy.length === 0 && (page.hasVpn || NetworkSettings.killSwitch)
+ locked: !page.hasVpn && !NetworkSettings.killSwitch
+ lockedReason: "Add a VPN in Advanced network settings first"
+ onSwitched: on => NetworkSettings.setKillSwitch(on)
+ }
+ }
+ }
+
+ Heading {
+ text: "Your data"
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ NoteRow {
+ glyph: "video-round"
+ title: "Camera and microphone lights"
+ description: "An icon in the taskbar whenever either is in use, and which app is using it."
+ note: "Always on"
+ }
+
+ // The clipboard panel (wildos-clipboard) wipes it.
+ OptionRow {
+ glyph: "clipboard-x"
+ title: "Clipboard forgets passwords"
+ description: "Anything copied from a password box is wiped after 60 seconds."
+ on: page.values.clipboard_forget === "on"
+ onSwitched: on => Advanced.set("clipboard_forget", on)
+ }
+
+ // The Notifications page's switch, which is the person's
+ // own: set here at once, and through the store for the
+ // protection levels and every other session
+ // (wildos-advanced-session).
+ OptionRow {
+ glyph: "presentation"
+ title: "Presenting mode"
+ description: "Holds notifications back while you share or record the screen."
+ on: page.presentingOn
+ onSwitched: on => {
+ notifications.inhibitNotificationsWhenScreenSharing = on;
+ notifications.inhibitNotificationsWhenScreensMirrored = on;
+ notifications.save();
+ Advanced.set("presenting", on);
+ }
+ }
+
+ OptionRow {
+ visible: page.installed.scrub_files === true
+ glyph: "image-off"
+ title: "Remove personal details from files"
+ description: "Location, device and author names. Right-click a file in Files to use it."
+ on: page.values.scrub_files === "on"
+ onSwitched: on => Advanced.set("scrub_files", on)
+
+ // Files keeps which details go (wildos-files).
+ extra: UI.LinkButton {
+ anchors.verticalCenter: parent.verticalCenter
+ text: "Choose what is removed"
+ enabled: page.values.scrub_files === "on"
+ onClicked: UI.System.run("wildos-files", ["--remove-details-choices"])
+ }
+ }
+
+ // Files' format window offers encryption only while it is on.
+ OptionRow {
+ glyph: "lock-round"
+ title: "Password-locked USB sticks"
+ description: "Tick \"Encrypt this drive\" when you format a drive."
+ on: page.values.usb_encrypt === "on"
+ onSwitched: on => Advanced.set("usb_encrypt", on)
+ }
+ }
+ }
+
+ Heading {
+ visible: lendingCard.visible
+ text: "Lending and testing"
+ }
+
+ UI.Card {
+ id: lendingCard
+ Layout.fillWidth: true
+ visible: page.installed.guest === true || page.installed.safebox === true
+
+ Column {
+ width: parent.width
+
+ OptionRow {
+ visible: page.installed.guest === true
+ glyph: "user-round"
+ title: "Guest session"
+ description: "Lend this PC. A clean desktop, wiped when they sign out."
+ on: page.values.guest === "on"
+ onSwitched: on => Advanced.set("guest", on)
+ }
+
+ OptionRow {
+ visible: page.installed.safebox === true
+ glyph: "box"
+ title: "Safe box"
+ description: "Open an unknown program or attachment sealed off from your files and the network."
+ on: page.values.safebox === "on"
+ onSwitched: on => Advanced.set("safebox", on)
+ }
+ }
+ }
+
+ // The duress password (DuressSetup.dc) comes later; its row waits
+ // for it rather than offer a Set up that does nothing.
+ Heading {
+ visible: emergencyCard.visible
+ text: "Emergencies"
+ }
+
+ UI.Card {
+ id: emergencyCard
+ Layout.fillWidth: true
+ visible: page.installed.panic_key === true
+
+ Column {
+ width: parent.width
+
+ OptionRow {
+ glyph: "siren"
+ title: "Panic key"
+ description: "Locks the screen, clears the clipboard and cuts the network in one press."
+ on: page.values.panic_key === "on"
+ onSwitched: on => Advanced.set("panic_key", on)
+
+ extra: Rectangle {
+ width: 150
+ height: 32
+ radius: 6
+ color: UI.Style.tone(0.05)
+ border.width: 1
+ border.color: UI.Style.tone(0.10)
+
+ UI.Label {
+ anchors.left: parent.left
+ anchors.leftMargin: 10
+ anchors.verticalCenter: parent.verticalCenter
+ text: "Ctrl + Alt + End"
+ size: 13
+ }
+ }
+ }
+ }
+ }
+
+ RowLayout {
+ Layout.fillWidth: true
+ spacing: 10
+
+ PathIcon {
+ name: "info-round"
+ size: 14
+ strokeWidth: 2
+ color: UI.Style.inkSubtle
+ }
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: "Strict and Maximum protection switch some of these on for you. Anything you change here stays as you set it."
+ size: 12.5
+ color: UI.Style.inkMuted
+ wrapMode: Text.Wrap
+ }
+ }
+ }
+
+ UI.Dialog {
+ id: resetDialog
+ title: "Reset advanced protection?"
+ text: "Everything on this page goes back to how Wild OS comes, and what you changed here is forgotten. Strict and Maximum protection switch their options on again."
+ buttons: [
+ UI.Button {
+ text: "Reset"
+ kind: "primary"
+ onClicked: {
+ resetDialog.close();
+ notice.hide();
+ Advanced.reset();
+ }
+ },
+ UI.Button {
+ text: "Cancel"
+ onClicked: resetDialog.close()
+ }
+ ]
+ }
+}
diff --git a/packages/wildos-settings/qml/pages/DateTimePage.qml b/packages/wildos-settings/qml/pages/DateTimePage.qml
index 55a038e..bc92a63 100644
--- a/packages/wildos-settings/qml/pages/DateTimePage.qml
+++ b/packages/wildos-settings/qml/pages/DateTimePage.qml
@@ -24,7 +24,7 @@ PageScroll {
target: Clock
function onFailed(reason) {
page.error = reason;
- autoToggle.checked = Qt.binding(() => Clock.automatic);
+ autoToggle.checked = Qt.binding(() => Clock.automatic || Clock.secureTime);
}
function onChanged() {
page.error = "";
@@ -60,7 +60,8 @@ PageScroll {
UI.Label {
Layout.fillWidth: true
- text: Clock.automatic ? (Clock.synchronised ? "Set automatically from the internet" : "Set automatically when the computer is online")
+ text: Clock.secureTime ? (Clock.secureTimeSet ? "Set automatically through Tor" : "Being set through Tor, which can take a few minutes after start-up")
+ : Clock.automatic ? (Clock.synchronised ? "Set automatically from the internet" : "Set automatically when the computer is online")
: "Set by hand"
color: UI.Style.inkMuted
}
@@ -86,15 +87,18 @@ PageScroll {
UI.SettingRow {
iconName: "clock"
title: "Set time automatically"
- description: Clock.canAutomatic ? "Keeps the clock right using a time server on the internet"
+ // sdwdate asks onion sites through Tor, so none of them sees
+ // this computer's address, and no time server is asked.
+ description: Clock.secureTime ? "Wild OS keeps the clock right by asking several sites through Tor, so none of them sees your address"
+ : Clock.canAutomatic ? "Keeps the clock right using a time server on the internet"
: "No time service is installed, so the clock is set by hand"
- enabled: Clock.canAutomatic
- status: Clock.automatic ? "On" : "Off"
+ enabled: Clock.canAutomatic && !Clock.secureTime
+ status: Clock.automatic || Clock.secureTime ? "On" : "Off"
UI.Toggle {
id: autoToggle
anchors.verticalCenter: parent.verticalCenter
- checked: Clock.automatic
+ checked: Clock.automatic || Clock.secureTime
Accessible.name: "Set time automatically"
onToggled: Clock.setAutomatic(checked)
}
diff --git a/packages/wildos-settings/qml/pages/DevicesPage.qml b/packages/wildos-settings/qml/pages/DevicesPage.qml
new file mode 100644
index 0000000..f5fa3df
--- /dev/null
+++ b/packages/wildos-settings/qml/pages/DevicesPage.qml
@@ -0,0 +1,252 @@
+import QtQuick
+import QtQuick.Layouts
+import WildOS.Settings
+import WildOS.UI as UI
+
+// System > Devices (SettingsDevices.dc), Wild OS's Device Manager. What
+// needs you comes first, each with the one button that fixes it, then
+// everything that works. Devices finds the hardware; printers come from
+// Printers (the queues, and those on the network not set up yet) and the
+// fingerprint reader's state from Fingerprint. A device opens
+// DeviceDetailDialog.
+PageScroll {
+ id: page
+
+ property bool showAll: false
+ property bool searchHandedOver: false
+ readonly property int shortList: 7
+
+ readonly property var usbQueues: Printers.printers.filter(p => /^(usb|ipp:\/\/localhost|ipps?:\/\/\[?::1)/.test(p.uri || ""))
+
+ function printerRows() {
+ const rows = [];
+ for (const p of Printers.printers) {
+ rows.push({ key: "queue:" + p.name, kind: "printer", name: p.info || p.name, icon: "printer-round",
+ line: p.status || "Ready", state: "ok", badge: "", problem: "", action: "", actionLabel: "",
+ model: p.model || "", maker: "", driver: "CUPS", hardwareId: "",
+ connection: /^usb:/.test(p.uri || "") ? "USB" : /^(ipp:\/\/localhost|ipps?:\/\/\[?::1)/.test(p.uri || "") ? "USB, through ipp-usb" : "Your network",
+ extra: p.location ? [{ label: "Location", value: p.location }] : [] });
+ }
+ // A search that started before the queues were read lists a printer
+ // already set up as found; its queue says otherwise.
+ const queued = Printers.printers.map(p => p.uri).concat(Printers.printers.map(p => p.info), Printers.printers.map(p => p.name));
+ for (const f of Printers.found.filter(f => !queued.includes(f.uri) && !queued.includes(f.name))) {
+ rows.push({ key: "found:" + f.uri, kind: "printer", name: f.name, icon: "printer-round",
+ line: "", state: "attention", badge: "Not set up", problem: "Found on your network, but not set up yet.",
+ action: "printers", actionLabel: "Set up", model: f.model || "", maker: "", driver: "", hardwareId: "",
+ connection: "Your network", extra: f.location ? [{ label: "Location", value: f.location }] : [] });
+ }
+ return rows;
+ }
+
+ // Devices' list with what QML knows better: the fingerprints saved,
+ // whether a USB printer has a queue, and the printers.
+ readonly property var rows: {
+ const out = [];
+ for (const d of Devices.devices) {
+ const row = Object.assign({}, d);
+ if (row.kind === "fingerprint" && row.state === "ok") {
+ const n = Fingerprint.fingers.length;
+ row.line = Fingerprint.windowsKey ? "Holds a key from Windows Hello" : n === 0 ? "No fingers saved yet" : Format.plural(n, "finger", "fingers") + " saved";
+ }
+ if (row.kind === "printer" && row.state === "ok") {
+ if (page.usbQueues.length === 0) {
+ row.state = "attention";
+ row.badge = "Not set up";
+ row.problem = "Plugged in, but not set up yet.";
+ row.action = "printers";
+ row.actionLabel = "Set up";
+ } else {
+ // Its queue's row says the rest.
+ continue;
+ }
+ }
+ out.push(row);
+ }
+ const printers = page.printerRows();
+ const at = out.findIndex(r => ["scanner", "smartcard", "phone", "usbdrive", "card", "hdmisound", "cardreader", "usb", "usbctl", "storagectl", "firewire"].includes(r.kind));
+ out.splice(at < 0 ? out.length : at, 0, ...printers);
+ return out;
+ }
+ readonly property var attention: rows.filter(r => r.state === "attention")
+ readonly property var working: rows.filter(r => r.state !== "attention")
+ readonly property var shownWorking: showAll ? working : working.slice(0, shortList)
+
+ function act(row) {
+ if (row.action === "printers") {
+ // Printers and scanners carries on with the search started here.
+ page.searchHandedOver = true;
+ Navigator.request = "printers-add";
+ Navigator.open("printers");
+ } else if (row.action === "graphicsdriver" || row.action === "update") {
+ Navigator.open(row.action);
+ } else if (row.action === "backup") {
+ if (!Devices.openBackup()) {
+ notice.show("Backup isn't installed", "Install it from the Store to copy your files to another drive.", true);
+ }
+ } else if (row.action === "restart") {
+ Updates.restart();
+ } else if (row.action === "allow") {
+ Devices.allow(row.port);
+ } else if (row.action === "report") {
+ if (!Devices.openReport()) {
+ notice.show("Report a problem isn't installed", "Install it from the Store to send a report.", true);
+ }
+ }
+ }
+
+ function checkAgain() {
+ Devices.scan();
+ Printers.reload();
+ Printers.search();
+ Fingerprint.reload();
+ }
+
+ Component.onCompleted: {
+ if (Devices.ready) {
+ Devices.scan();
+ }
+ Printers.search();
+ }
+ Component.onDestruction: {
+ if (!page.searchHandedOver) {
+ Printers.stopSearch();
+ }
+ }
+
+ Notice {
+ id: notice
+ Layout.fillWidth: true
+ }
+
+ Connections {
+ target: Devices
+ function onFailed(message) {
+ notice.show("The device wasn't allowed", message, true);
+ }
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 14
+
+ // The summary: how many devices need you, or that none do.
+ Rectangle {
+ id: hero
+ readonly property bool worry: page.attention.length > 0
+ Layout.fillWidth: true
+ implicitHeight: heroRow.implicitHeight + 28
+ radius: 12
+ color: UI.Style.tone(0.05)
+ border.width: 1
+ border.color: UI.Style.tone(0.07)
+
+ RowLayout {
+ id: heroRow
+ anchors.left: parent.left
+ anchors.right: parent.right
+ anchors.verticalCenter: parent.verticalCenter
+ anchors.leftMargin: 18
+ anchors.rightMargin: 18
+ spacing: 18
+
+ Rectangle {
+ Layout.preferredWidth: 46
+ Layout.preferredHeight: 46
+ radius: 23
+ color: Qt.rgba(heroIcon.color.r, heroIcon.color.g, heroIcon.color.b, 0.16)
+
+ PathIcon {
+ id: heroIcon
+ anchors.centerIn: parent
+ name: hero.worry ? "triangle-alert" : "status-ok"
+ size: 24
+ strokeWidth: 2.1
+ color: hero.worry ? (UI.Style.dark ? "#ffc46a" : UI.Style.warning) : (UI.Style.dark ? "#5fd38d" : "#1d7a4c")
+ }
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 3
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: !Devices.ready ? "Looking at the devices in this PC"
+ : hero.worry ? Format.plural(page.attention.length, "device needs", "devices need") + " you"
+ : "Every device is working"
+ size: 16.5
+ font.weight: UI.Style.weightBold
+ wrapMode: Text.Wrap
+ }
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: !Devices.ready ? "This takes a moment."
+ : (hero.worry ? "Everything else in this PC is working." : "Nothing in this PC needs you.")
+ + " Select a device to see its details and driver."
+ size: 13
+ color: UI.Style.inkMuted
+ wrapMode: Text.Wrap
+ }
+ }
+
+ UI.Button {
+ implicitHeight: 32
+ iconName: "refresh"
+ text: "Check again"
+ busy: Devices.scanning
+ enabled: !Devices.scanning
+ onClicked: page.checkAgain()
+ }
+ }
+ }
+
+ SectionTitle {
+ Layout.topMargin: 4
+ Layout.bottomMargin: -4
+ Layout.fillWidth: true
+ visible: page.attention.length > 0
+ text: "Needs attention"
+ }
+
+ DeviceList {
+ Layout.fillWidth: true
+ visible: page.attention.length > 0
+ model: page.attention
+ onOpened: row => details.openFor(row)
+ onActed: row => page.act(row)
+ }
+
+ RowLayout {
+ Layout.topMargin: 4
+ Layout.bottomMargin: -4
+ Layout.fillWidth: true
+ visible: page.working.length > 0
+
+ SectionTitle {
+ Layout.fillWidth: true
+ text: "Working"
+ }
+
+ UI.LinkButton {
+ visible: page.working.length > page.shortList
+ text: page.showAll ? "Show fewer" : "Show all " + page.working.length
+ onClicked: page.showAll = !page.showAll
+ }
+ }
+
+ DeviceList {
+ Layout.fillWidth: true
+ visible: page.working.length > 0
+ model: page.shownWorking
+ onOpened: row => details.openFor(row)
+ onActed: row => page.act(row)
+ }
+ }
+
+ DeviceDetailDialog {
+ id: details
+ onAct: row => page.act(row)
+ }
+}
diff --git a/packages/wildos-settings/qml/pages/FirewallPage.qml b/packages/wildos-settings/qml/pages/FirewallPage.qml
new file mode 100644
index 0000000..7ee9d00
--- /dev/null
+++ b/packages/wildos-settings/qml/pages/FirewallPage.qml
@@ -0,0 +1,425 @@
+import QtQuick
+import QtQuick.Layouts
+import WildOS.Settings
+import WildOS.UI as UI
+
+// Privacy and security > Firewall (SettingsFirewall.dc): the firewall
+// itself, how much the network in use is trusted, and one card of what
+// other computers can reach, with what the firewall turned away today at
+// its foot. Everything here goes through Firewall and its one root helper,
+// settings-firewall. A public network gets none of the rows, Maximum
+// protection keeps discovery off, and Windows mode is always let through,
+// so the switches say so rather than claim otherwise.
+PageScroll {
+ id: page
+
+ readonly property var net: NetworkSettings.current
+ readonly property bool connected: (net.uuid || "").length > 0
+ readonly property bool isPublic: connected && Firewall.publicNetworks[net.uuid] === true
+ readonly property bool isHome: connected && Firewall.homeNetworks[net.uuid] === true
+ // Joined but never called Home or Public: discovery works as it always
+ // did, and nothing else is let in until Home is chosen.
+ readonly property bool undecided: connected && !isPublic && !isHome
+ readonly property bool maximum: System.protectionLevel === "maximum"
+ readonly property bool on: Firewall.enabled
+ // The rows can let anything in: the firewall is on and this network is
+ // trusted.
+ readonly property bool live: on && !isPublic && !undecided
+ readonly property string publicReason: "Off while you're on a public network"
+ readonly property string lockReason: undecided ? "Off until you choose Home for this network" : publicReason
+
+ // "Today" moves on at midnight without anything new coming in.
+ property date now: new Date()
+ readonly property var today: Firewall.blocked.filter(b => b.when.toDateString() === page.now.toDateString())
+
+ function whoPhrase(kind) {
+ return kind === "router" ? "your router"
+ : kind === "local" ? "another PC on this network"
+ : kind === "internet" ? "the internet"
+ : "another local network";
+ }
+
+ function blockedLine() {
+ const n = page.today.length;
+ if (n === 0) {
+ return "Nothing has been turned away today.";
+ }
+ const latest = page.today[0];
+ return "Turned away today: " + Format.plural(n, "connection", "connections") + ". "
+ + (n === 1 ? "It was" : "The latest was") + " at " + Format.time(latest.when) + ", from " + page.whoPhrase(latest.kind) + ".";
+ }
+
+ readonly property var serviceNames: ({ files: "file sharing", remote: "Remote Desktop", ssh: "the SSH server" })
+
+ function serviceText(name, normal, whenOn) {
+ if (Firewall.busyWhat === name) {
+ const s = Firewall.services[name] || {};
+ if (Firewall.step === "Downloading" || Firewall.step === "Installing") {
+ return Firewall.step + " " + page.serviceNames[name] + (Firewall.progress >= 0 ? ", " + Firewall.progress + "%" : "");
+ }
+ if (Firewall.step.length > 0) {
+ return Firewall.step;
+ }
+ return s.on ? "Turning it off…" : "Turning it on…";
+ }
+ const s = Firewall.services[name] || {};
+ if (page.live && name === "remote" && s.on && s.running === false) {
+ return "Nobody can sign in yet. Add an account under Who can sign in.";
+ }
+ return page.live && s.on && whenOn ? whenOn : normal;
+ }
+
+ function scopeText(rule) {
+ if (rule.scope === "anyone") {
+ return "Anyone, including the internet";
+ }
+ if (rule.scope === "device") {
+ return rule.address + " only";
+ }
+ return "Devices on this network only";
+ }
+
+ function ruleText(rule) {
+ const port = (rule.proto === "udp" ? "UDP port " : "Port ") + rule.port;
+ const when = rule.session ? "Until you restart"
+ : Format.isValid(rule.until) ? "Until " + Format.time(rule.until)
+ : "Added by you";
+ return port + " · " + page.scopeText(rule) + " · " + when;
+ }
+
+ // Coming back from Who can sign in may have started Remote Desktop.
+ Component.onCompleted: Firewall.refresh()
+
+ Notice {
+ id: notice
+ Layout.fillWidth: true
+ }
+
+ Connections {
+ target: Firewall
+ function onFailed(message) {
+ notice.show("Nothing was changed", message, true);
+ }
+ function onDone(what) {
+ notice.hide();
+ }
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 16
+
+ // The firewall itself.
+ Rectangle {
+ id: hero
+ readonly property bool good: Firewall.enabled && Firewall.loaded
+ Layout.fillWidth: true
+ implicitHeight: heroRow.implicitHeight + 32
+ radius: 12
+ color: UI.Style.tone(0.05)
+ border.width: 1
+ border.color: UI.Style.tone(0.07)
+
+ RowLayout {
+ id: heroRow
+ anchors.left: parent.left
+ anchors.right: parent.right
+ anchors.verticalCenter: parent.verticalCenter
+ anchors.leftMargin: 18
+ anchors.rightMargin: 18
+ spacing: 18
+
+ Rectangle {
+ Layout.preferredWidth: 52
+ Layout.preferredHeight: 52
+ radius: 26
+ color: hero.good ? Qt.rgba(95 / 255, 211 / 255, 141 / 255, 0.16) : UI.Style.warningSoft
+
+ PathIcon {
+ anchors.centerIn: parent
+ name: hero.good ? "shield-round-check" : "shield-round-alert"
+ size: 26
+ strokeWidth: 2.2
+ color: hero.good ? "#5fd38d" : UI.Style.warning
+ }
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 3
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: !Firewall.enabled ? "The firewall is off"
+ : !Firewall.loaded ? "The firewall didn't load"
+ : "The firewall is on"
+ size: 17
+ font.weight: UI.Style.weightBold
+ wrapMode: Text.Wrap
+ }
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: !Firewall.enabled ? "Other computers can reach any app on this PC that waits for connections. Windows mode is still kept to itself."
+ : !Firewall.loaded ? "Other computers can reach any app on this PC that waits for connections. Turn the firewall off and on again to load it."
+ : "Nothing can connect to this PC unless you allow it below. Your own apps go online as normal."
+ size: 13
+ color: UI.Style.inkMuted
+ wrapMode: Text.Wrap
+ }
+ }
+
+ UI.Toggle {
+ checked: Firewall.enabled
+ enabled: Firewall.available && !Firewall.busy
+ Accessible.name: "Firewall"
+ onToggled: Firewall.setEnabled(checked)
+ }
+ }
+ }
+
+ // The network in use, and how far it is trusted.
+ UI.Card {
+ Layout.fillWidth: true
+
+ UI.SettingRow {
+ width: parent.width
+ minHeight: 60
+ enabled: page.on
+ leading: PathIcon {
+ anchors.verticalCenter: parent.verticalCenter
+ name: page.net.wifi === false ? "ethernet" : "wifi-round"
+ size: 20
+ strokeWidth: 1.8
+ color: UI.Style.ink
+ }
+ title: page.connected ? page.net.name : "Not connected"
+ description: !page.connected ? "Choose Home or Public for each network when you join it."
+ : page.isPublic ? "A public network. Everything below is switched off until you leave."
+ : page.undecided ? "Is this a network you trust? Choose Home to let in what you switch on below, or Public to keep it all out."
+ : "A network you trust. On a public network, everything below is switched off until you leave."
+
+ Segmented {
+ anchors.verticalCenter: parent.verticalCenter
+ visible: page.connected
+ enabled: page.on && !Firewall.busy
+ options: [{ value: "home", text: "Home" }, { value: "public", text: "Public" }]
+ value: page.isPublic ? "public" : page.isHome ? "home" : ""
+ onPicked: v => Firewall.setPublic(page.net.uuid, v === "public")
+ }
+ }
+ }
+
+ RowLayout {
+ Layout.fillWidth: true
+ Layout.topMargin: 4
+ Layout.bottomMargin: -4
+ spacing: 12
+
+ SectionTitle {
+ Layout.fillWidth: true
+ text: "What other computers can reach"
+ }
+
+ UI.Button {
+ implicitHeight: 32
+ iconName: "plus"
+ text: "Allow an app or port"
+ enabled: page.on && Firewall.available && !Firewall.busy
+ onClicked: allowDialog.openFor(null)
+ }
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ UI.SettingRow {
+ minHeight: 60
+ leading: PathIcon {
+ anchors.verticalCenter: parent.verticalCenter
+ name: "printer-round"
+ size: 20
+ strokeWidth: 1.8
+ color: UI.Style.ink
+ }
+ enabled: page.on
+ title: "Network discovery"
+ description: page.maximum ? "Off at Maximum protection, which keeps this PC hidden on the network."
+ : "Find printers, screens and speakers nearby, and let them find this PC."
+
+ UI.Toggle {
+ anchors.verticalCenter: parent.verticalCenter
+ checked: page.on && !page.isPublic && Firewall.discovery && !page.maximum
+ enabled: page.on && !Firewall.busy
+ locked: page.on && (page.isPublic || page.maximum)
+ lockedReason: page.maximum ? "Maximum protection keeps this off" : page.publicReason
+ Accessible.name: "Network discovery"
+ onToggled: Firewall.setDiscovery(checked)
+ }
+ }
+
+ Repeater {
+ model: [
+ { key: "files", icon: "folder-round", title: "File sharing", text: "Share folders with other PCs on this network.",
+ on: "Share a folder from its Properties in Files, under Sharing." },
+ { key: "remote", icon: "monitor-round", title: "Remote Desktop", text: "Let another PC see and control this one.",
+ on: "Let another PC see and control this one, signing in with an account you add under Who can sign in." },
+ { key: "ssh", icon: "terminal-round", title: "SSH", text: "Terminal access from another computer.",
+ on: "Terminal access from another computer, signing in with an account on this PC." }
+ ]
+
+ UI.SettingRow {
+ id: serviceRow
+ required property var modelData
+ readonly property var svc: Firewall.services[modelData.key] || ({})
+ width: parent.width
+ minHeight: 60
+ leading: PathIcon {
+ anchors.verticalCenter: parent.verticalCenter
+ name: serviceRow.modelData.icon
+ size: 20
+ strokeWidth: 1.8
+ color: UI.Style.ink
+ }
+ enabled: page.on
+ title: modelData.title
+ description: page.serviceText(modelData.key, modelData.text, modelData.on)
+
+ UI.LinkButton {
+ anchors.verticalCenter: parent.verticalCenter
+ visible: serviceRow.modelData.key === "remote" && serviceRow.svc.on === true && Firewall.busyWhat !== "remote"
+ text: "Who can sign in"
+ enabled: page.on
+ onClicked: Navigator.open("remotedesktop")
+ }
+
+ UI.Toggle {
+ anchors.verticalCenter: parent.verticalCenter
+ checked: page.live && serviceRow.svc.on === true
+ enabled: page.on && !Firewall.busy
+ locked: page.on && (page.isPublic || page.undecided)
+ lockedReason: page.lockReason
+ Accessible.name: serviceRow.modelData.title
+ onToggled: Firewall.setService(serviceRow.modelData.key, checked)
+ }
+ }
+ }
+
+ Repeater {
+ model: Firewall.rules
+
+ UI.SettingRow {
+ id: ruleRow
+ required property var modelData
+ width: parent.width
+ minHeight: 60
+ leading: PathIcon {
+ anchors.verticalCenter: parent.verticalCenter
+ name: "server"
+ size: 20
+ strokeWidth: 1.8
+ color: UI.Style.ink
+ }
+ enabled: page.on
+ title: modelData.name
+ description: page.ruleText(modelData)
+
+ UI.LinkButton {
+ anchors.verticalCenter: parent.verticalCenter
+ text: "Remove"
+ enabled: page.on && !Firewall.busy
+ Accessible.name: "Remove " + ruleRow.modelData.name
+ onClicked: Firewall.removeRule(ruleRow.modelData.id)
+ }
+
+ UI.Toggle {
+ anchors.verticalCenter: parent.verticalCenter
+ checked: page.live && ruleRow.modelData.on
+ enabled: page.on && !Firewall.busy
+ locked: page.on && (page.isPublic || page.undecided)
+ lockedReason: page.lockReason
+ Accessible.name: ruleRow.modelData.name
+ onToggled: Firewall.setRuleOn(ruleRow.modelData.id, checked)
+ }
+ }
+ }
+
+ // Windows mode's virtual PC reaches this one through its own
+ // bridge, which its own firewall (wildos_win) limits.
+ UI.SettingRow {
+ visible: WindowsMode.installed
+ minHeight: 60
+ leading: PathIcon {
+ anchors.verticalCenter: parent.verticalCenter
+ name: "lock-round"
+ size: 20
+ strokeWidth: 1.8
+ color: UI.Style.ink
+ }
+ title: "Windows mode"
+ description: "Talks to this PC only and never to your network. Managed by Wild OS."
+
+ UI.Label {
+ anchors.verticalCenter: parent.verticalCenter
+ text: "Always on"
+ size: 12.5
+ color: UI.Style.inkMuted
+ }
+ }
+
+ Item {
+ width: parent.width
+ height: 44
+
+ Rectangle {
+ anchors.left: parent.left
+ anchors.right: parent.right
+ height: 1
+ color: UI.Style.borderSubtle
+ }
+
+ RowLayout {
+ anchors.fill: parent
+ anchors.leftMargin: 18
+ anchors.rightMargin: 18
+ spacing: 18
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: page.blockedLine()
+ size: 12.5
+ color: UI.Style.inkMuted
+ elide: Text.ElideRight
+ }
+
+ UI.LinkButton {
+ visible: Firewall.blocked.length > 0
+ text: "See what was blocked"
+ onClicked: activityDialog.open()
+ }
+ }
+ }
+ }
+ }
+ }
+
+ Timer {
+ interval: 60000
+ running: page.visible
+ repeat: true
+ onTriggered: page.now = new Date()
+ }
+
+ FirewallAllowDialog {
+ id: allowDialog
+ networkName: page.connected ? page.net.name : ""
+ }
+
+ FirewallActivityDialog {
+ id: activityDialog
+ onAllowRequested: entry => allowDialog.openFor(entry)
+ }
+}
diff --git a/packages/wildos-settings/qml/pages/FreeSpacePage.qml b/packages/wildos-settings/qml/pages/FreeSpacePage.qml
new file mode 100644
index 0000000..2626929
--- /dev/null
+++ b/packages/wildos-settings/qml/pages/FreeSpacePage.qml
@@ -0,0 +1,419 @@
+import QtQuick
+import QtQuick.Layouts
+import WildOS.Settings
+import WildOS.UI as UI
+
+// System > Storage > Free up space (SettingsFreeSpace.dc): what Wild OS can
+// clear, each with its real size from settings-free-space. The four items
+// that cost nothing are ticked to begin with; the three with a consequence
+// are not, and large downloads are only ever cleared from the list in
+// Review. The ticks are kept, because Tidy up automatically clears them.
+PageScroll {
+ id: page
+
+ readonly property var sys: FreeSpace.system
+ readonly property var home: FreeSpace.home
+ readonly property bool measured: !FreeSpace.measuring && Object.keys(page.home).length > 0
+
+ readonly property var defaultTicks: ["bin", "restorePoints", "updates", "caches"]
+ property var ticked: page.ticksFrom(FreeSpace.hasSavedItems ? FreeSpace.savedItems : page.defaultTicks)
+ // Paths of the large downloads ticked in Review.
+ property var chosenDownloads: []
+
+ function part(map, key) {
+ return map && map[key] ? map[key] : { bytes: 0, count: 0, targets: [], kept: [] };
+ }
+
+ readonly property var bin: part(home, "bin")
+ readonly property var points: part(sys, "restorePoints")
+ readonly property var updates: part(sys, "updates")
+ readonly property var caches: part(home, "caches")
+ readonly property var leftoversSystem: part(sys, "leftoversSystem")
+ readonly property var leftoversHome: part(home, "leftoversHome")
+ readonly property var winmode: part(sys, "winmode")
+ readonly property var downloads: part(home, "downloads")
+
+ readonly property int leftoverApps: leftoversSystem.count + (leftoversHome.apps ? leftoversHome.apps.length : 0)
+ readonly property real chosenDownloadBytes: downloads.targets.filter(t => chosenDownloads.indexOf(t.path) >= 0)
+ .reduce((sum, t) => sum + t.bytes, 0)
+
+ readonly property var sizes: ({
+ bin: bin.bytes,
+ restorePoints: points.bytes,
+ updates: updates.bytes,
+ caches: caches.bytes,
+ leftovers: leftoversSystem.bytes + leftoversHome.bytes,
+ winmode: winmode.known ? winmode.bytes : 0,
+ downloads: chosenDownloadBytes
+ })
+ readonly property real total: Object.keys(sizes).reduce((sum, k) => sum + (ticked[k] ? sizes[k] : 0), 0)
+
+ readonly property var rows: [
+ { key: "bin", icon: "trash-round", title: "Recycle Bin", shown: true, bytes: sizes.bin,
+ description: bin.files > 0 ? Format.plural(bin.files, "file", "files") + " you have already deleted." : "The Recycle Bin is empty." },
+ // The system half can fail (no polkit agent, say): then its rows
+ // say nothing they could not check.
+ { key: "restorePoints", icon: "history", title: "Old restore points", shown: points.available !== false, bytes: sizes.restorePoints,
+ unknown: FreeSpace.systemFailed,
+ description: FreeSpace.systemFailed ? "Keeps the newest 3 and removes the older ones."
+ : points.count > 0 ? "Keeps the newest 3 and removes " + points.count + " older " + (points.count === 1 ? "one." : "ones.")
+ : "Keeps the newest 3. There are no older ones." },
+ { key: "updates", icon: "download-round", title: "Update files already installed", shown: true, bytes: sizes.updates,
+ unknown: FreeSpace.systemFailed,
+ description: "Downloads that are no longer needed." },
+ { key: "caches", icon: "layers", title: "App caches", shown: true, bytes: sizes.caches,
+ description: "Temporary files that apps rebuild when they need them." },
+ { key: "leftovers", icon: "package", title: "Leftovers from removed apps", shown: true, bytes: sizes.leftovers,
+ description: leftoverApps > 0 ? "Settings kept for " + Format.plural(leftoverApps, "app", "apps") + " you removed. Clearing them means a reinstall starts fresh."
+ : "Nothing is left from apps you removed." },
+ // Only where Windows mode is set up.
+ { key: "winmode", icon: "app-window", title: "Unused space inside Windows mode", shown: winmode.available === true,
+ bytes: sizes.winmode, unknown: winmode.known !== true,
+ // Windows trims its own free space, so it has to be running; a
+ // tick here is kept for Tidy up automatically to do it then.
+ description: winmode.known === true ? "Shrinks the Windows disk file. Windows mode needs to stay on while it runs."
+ : "Shrinks the Windows disk file. This can only be done while Windows mode is on." },
+ { key: "downloads", icon: "folder-round", title: "Large files in Downloads", shown: true,
+ bytes: ticked.downloads ? chosenDownloadBytes : downloads.bytes,
+ description: downloads.count > 0 ? Format.plural(downloads.count, "file", "files") + " over 100 MB that you have not opened for 90 days."
+ : "No files over 100 MB that you have left unopened for 90 days." }
+ ]
+
+ function ticksFrom(list) {
+ const t = { downloads: false };
+ for (const k of ["bin", "restorePoints", "updates", "caches", "leftovers", "winmode"]) {
+ t[k] = list.indexOf(k) >= 0;
+ }
+ return t;
+ }
+
+ // Downloads are never kept: Review chooses them each time.
+ function keptTicks(t) {
+ return Object.keys(t).filter(k => k !== "downloads" && t[k]);
+ }
+
+ function tick(key, on) {
+ const t = Object.assign({}, ticked);
+ t[key] = on;
+ ticked = t;
+ if (key !== "downloads") {
+ FreeSpace.saveItems(keptTicks(t));
+ }
+ }
+
+ readonly property var tickedItems: rows.filter(r => r.shown && ticked[r.key] && (r.key !== "downloads" || chosenDownloads.length > 0))
+ readonly property string clearList: {
+ const names = { bin: "the Recycle Bin", restorePoints: "old restore points", updates: "update files",
+ caches: "app caches", leftovers: "leftovers from removed apps", winmode: "unused space inside Windows mode",
+ downloads: Format.plural(chosenDownloads.length, "file", "files") + " from Downloads" };
+ const list = tickedItems.map(r => names[r.key]);
+ return list.length <= 1 ? (list[0] || "") : list.slice(0, -1).join(", ") + " and " + list[list.length - 1];
+ }
+
+ Component.onCompleted: FreeSpace.measure()
+
+ Connections {
+ target: FreeSpace
+ function onCleaned(result) {
+ if (result.cancelled) {
+ return;
+ }
+ page.chosenDownloads = [];
+ page.tick("downloads", false);
+ const items = result.items || {};
+ const freed = Object.keys(items).reduce((sum, k) => sum + (items[k].freed || 0), 0);
+ const skipped = Object.keys(items).reduce((all, k) => all.concat(items[k].skipped || []), []);
+ const notes = [];
+ if (skipped.some(s => s.why === "an update is running")) {
+ notes.push("Update files were left because an update is running.");
+ }
+ if (skipped.some(s => s.why === "an open app is using it")) {
+ notes.push("Files that open apps are using were left.");
+ }
+ if (skipped.some(s => s.why === "Windows mode isn't on")) {
+ notes.push("Windows mode was off, so its disk was not shrunk.");
+ }
+ if (freed > 0) {
+ notice.show(System.formatBytes(freed) + " was freed up", notes.join(" "), false);
+ } else {
+ notice.show("Nothing was freed up", notes.length > 0 ? notes.join(" ") : "There was nothing left to clear.", notes.length > 0);
+ }
+ }
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 14
+
+ Notice {
+ id: notice
+ Layout.fillWidth: true
+ }
+
+ // The hero: the total of the ticked items, and the one button.
+ Rectangle {
+ Layout.fillWidth: true
+ implicitHeight: heroRow.implicitHeight + 28
+ radius: 12
+ color: UI.Style.dark ? Qt.rgba(1, 1, 1, 0.05) : Qt.rgba(0, 0, 0, 0.035)
+ border.width: 1
+ border.color: UI.Style.dark ? Qt.rgba(1, 1, 1, 0.07) : Qt.rgba(0, 0, 0, 0.07)
+
+ RowLayout {
+ id: heroRow
+ anchors.left: parent.left
+ anchors.right: parent.right
+ anchors.verticalCenter: parent.verticalCenter
+ anchors.leftMargin: 18
+ anchors.rightMargin: 18
+ spacing: 18
+
+ Rectangle {
+ Layout.preferredWidth: 46
+ Layout.preferredHeight: 46
+ radius: 23
+ color: Qt.rgba(95 / 255, 211 / 255, 141 / 255, 0.16)
+
+ PathIcon {
+ anchors.centerIn: parent
+ name: "hard-drive"
+ size: 24
+ strokeWidth: 2.1
+ color: HistoryWords.green
+ }
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 3
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: !page.measured ? "Measuring what can be freed"
+ : page.total > 0 ? System.formatBytes(page.total) + " can be freed safely"
+ : page.tickedItems.length > 0 ? "There is nothing to free up" : "Tick what you want cleared"
+ size: 16.5
+ font.weight: UI.Style.weightSemiBold
+ wrapMode: Text.Wrap
+ }
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: "This disk is " + System.formatBytes(FreeSpace.diskTotal) + " with " + System.formatBytes(FreeSpace.diskFree)
+ + " free. Nothing here touches your documents, pictures or settings."
+ size: 13
+ color: UI.Style.inkMuted
+ wrapMode: Text.Wrap
+ }
+ }
+
+ UI.Button {
+ kind: "primary"
+ text: FreeSpace.cleaning ? "Freeing up space"
+ : page.measured && page.total > 0 ? "Free up " + System.formatBytes(page.total) : "Free up space"
+ busy: FreeSpace.measuring || FreeSpace.cleaning
+ enabled: page.measured && !FreeSpace.cleaning && page.total > 0
+ onClicked: confirmDialog.open()
+ }
+ }
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ Repeater {
+ model: page.rows
+
+ UI.SettingRow {
+ id: row
+ required property var modelData
+ readonly property bool on: page.ticked[modelData.key] === true
+ readonly property bool isDownloads: modelData.key === "downloads"
+ width: parent.width
+ visible: modelData.shown
+ title: modelData.title
+ description: modelData.description
+
+ leading: [
+ UI.CheckBox {
+ anchors.verticalCenter: parent.verticalCenter
+ checked: row.on
+ enabled: page.measured
+ Accessible.name: row.title
+ onToggled: {
+ const want = checked;
+ // The page's ticks decide, so a Review
+ // closed without choosing leaves the box
+ // clear.
+ checked = Qt.binding(() => row.on);
+ if (!row.isDownloads) {
+ page.tick(row.modelData.key, want);
+ } else if (want) {
+ // Never ticked without Review: only
+ // what is ticked there counts.
+ reviewDialog.open();
+ } else {
+ page.chosenDownloads = [];
+ page.tick("downloads", false);
+ }
+ }
+ },
+ PathIcon {
+ anchors.verticalCenter: parent.verticalCenter
+ name: row.modelData.icon
+ size: 19
+ }
+ ]
+
+ UI.LinkButton {
+ anchors.verticalCenter: parent.verticalCenter
+ visible: row.isDownloads && page.downloads.count > 0
+ text: "Review"
+ onClicked: reviewDialog.open()
+ }
+
+ UI.Label {
+ anchors.verticalCenter: parent.verticalCenter
+ width: 70
+ horizontalAlignment: Text.AlignRight
+ text: !page.measured ? "" : row.modelData.unknown ? "Unknown" : System.formatBytes(row.modelData.bytes)
+ size: 13.5
+ font.features: ({ "tnum": 1 })
+ color: row.on ? UI.Style.ink : UI.Style.inkMuted
+ }
+ }
+ }
+ }
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ UI.SettingRow {
+ width: parent.width
+ title: "Tidy up automatically"
+ description: "When less than 10% of the disk is free, clear the ticked items. You are told what was removed."
+ leading: PathIcon {
+ anchors.verticalCenter: parent.verticalCenter
+ name: "refresh-cw"
+ size: 20
+ }
+
+ UI.Toggle {
+ anchors.verticalCenter: parent.verticalCenter
+ checked: FreeSpace.autoOn
+ onToggled: {
+ const want = checked;
+ // Follows FreeSpace, so a password that was not
+ // given leaves it as it was.
+ checked = Qt.binding(() => FreeSpace.autoOn);
+ FreeSpace.setAuto(want, page.keptTicks(page.ticked));
+ }
+ }
+ }
+ }
+
+ RowLayout {
+ Layout.fillWidth: true
+ spacing: 10
+
+ PathIcon {
+ name: "info-round"
+ size: 14
+ color: UI.Style.inkSubtle
+ }
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: "There is no registry to clean and nothing to defragment on Wild OS. This page is only about getting space back."
+ size: 12.5
+ color: UI.Style.inkMuted
+ wrapMode: Text.Wrap
+ }
+ }
+ }
+
+ UI.Dialog {
+ id: confirmDialog
+ title: "Free up " + System.formatBytes(page.total) + "?"
+ text: "This removes " + page.clearList + " for good. Your documents, pictures and settings are not touched"
+ + (page.ticked.leftovers ? ", apart from the settings of apps you removed." : ".")
+ buttons: [
+ UI.Button {
+ text: "Free up " + System.formatBytes(page.total)
+ kind: "primary"
+ onClicked: {
+ confirmDialog.close();
+ FreeSpace.clean(page.tickedItems.map(r => r.key), page.ticked.downloads ? page.chosenDownloads : []);
+ }
+ },
+ UI.Button {
+ text: "Cancel"
+ onClicked: confirmDialog.close()
+ }
+ ]
+ }
+
+ UI.Dialog {
+ id: reviewDialog
+
+ property var picks: []
+
+ size: "large"
+ title: "Large files in Downloads"
+ text: "Files over 100 MB in Downloads that you have not opened for 90 days. Tick the ones to remove. Nothing else in Downloads is touched."
+ onOpened: picks = page.chosenDownloads.slice()
+
+ Column {
+ Layout.fillWidth: true
+
+ Repeater {
+ model: page.downloads.targets
+
+ UI.SettingRow {
+ id: fileRow
+ required property var modelData
+ width: parent.width
+ title: modelData.name
+ description: "Not opened since " + Format.day(new Date(modelData.last * 1000))
+ leading: UI.CheckBox {
+ anchors.verticalCenter: parent.verticalCenter
+ checked: reviewDialog.picks.indexOf(fileRow.modelData.path) >= 0
+ onToggled: {
+ const p = reviewDialog.picks.filter(x => x !== fileRow.modelData.path);
+ if (checked) {
+ p.push(fileRow.modelData.path);
+ }
+ reviewDialog.picks = p;
+ }
+ }
+
+ UI.Label {
+ anchors.verticalCenter: parent.verticalCenter
+ text: System.formatBytes(fileRow.modelData.bytes)
+ color: UI.Style.inkMuted
+ }
+ }
+ }
+ }
+
+ buttons: [
+ UI.Button {
+ text: "Done"
+ kind: "primary"
+ onClicked: {
+ page.chosenDownloads = reviewDialog.picks;
+ page.tick("downloads", reviewDialog.picks.length > 0);
+ reviewDialog.close();
+ }
+ },
+ UI.Button {
+ text: "Cancel"
+ onClicked: reviewDialog.close()
+ }
+ ]
+ }
+}
diff --git a/packages/wildos-settings/qml/pages/HistoryPage.qml b/packages/wildos-settings/qml/pages/HistoryPage.qml
new file mode 100644
index 0000000..ed5759e
--- /dev/null
+++ b/packages/wildos-settings/qml/pages/HistoryPage.qml
@@ -0,0 +1,452 @@
+import QtQuick
+import QtQuick.Layouts
+import QtQuick.Dialogs
+import QtQuick.Templates as T
+import WildOS.Settings
+import WildOS.UI as UI
+
+// System > History (SettingsHistory.dc): what happened on this PC, in plain
+// words, newest first and grouped by day. The records are settings-history's
+// (History), the words HistoryWords'. Details opens HistoryDetailDialog
+// (HistoryDetail.dc). Kept 30 days; nothing is sent anywhere.
+PageScroll {
+ id: page
+
+ property string filter: "all"
+ property string period: "week"
+ property int limit: 120
+ property date now: new Date()
+
+ readonly property var periodStart: period === "today" ? new Date(now.getFullYear(), now.getMonth(), now.getDate())
+ : new Date(now.getTime() - (period === "week" ? 7 : 30) * 86400000)
+ readonly property string periodWords: period === "today" ? "today" : period === "week" ? "this week" : "in the last 30 days"
+ readonly property string periodSpan: period === "today" ? "today" : period === "week" ? "in the last 7 days" : "in the last 30 days"
+
+ // Every event in the period, with its words.
+ readonly property var inPeriod: History.events.filter(e => e.when >= periodStart).map(e => ({ event: e, words: HistoryWords.describe(e, History.events) }))
+ readonly property int problems: inPeriod.filter(x => x.words.problem).length
+ // "camera" is the camera and microphone lights' This week link, not one
+ // of the filters on the page.
+ readonly property var shown: unreadable ? [] : inPeriod.filter(x => filter === "all" ? true : filter === "problems" ? x.words.problem
+ : filter === "camera" ? x.event.kind === "device-use" : x.words.group === filter)
+ readonly property bool unreadable: History.problem === "unreadable"
+
+ // [{ label, rows: [{event, words}] }], newest day first.
+ readonly property var days: {
+ const out = [];
+ const list = shown.slice(0, limit);
+ for (let i = 0; i < list.length; ++i) {
+ const day = Format.day(list[i].event.when);
+ const label = day === "today" ? "Today" : day === "yesterday" ? "Yesterday" : day;
+ if (out.length === 0 || out[out.length - 1].label !== label) {
+ out.push({ label: label, rows: [] });
+ }
+ out[out.length - 1].rows.push(list[i]);
+ }
+ return out;
+ }
+
+ function emptyText() {
+ if (page.filter === "problems") {
+ return "No problems " + page.periodSpan + ".";
+ }
+ if (page.filter === "security") {
+ return "Nothing to do with security " + page.periodSpan + ".";
+ }
+ if (page.filter === "updates") {
+ return "No updates or restore points " + page.periodSpan + ".";
+ }
+ if (page.filter === "camera") {
+ return "No app used the camera or microphone " + page.periodSpan + ".";
+ }
+ if (page.filter === "apps") {
+ return "No apps installed, removed or closed unexpectedly " + page.periodSpan + ".";
+ }
+ return "Nothing has happened on this PC " + page.periodSpan + ".";
+ }
+
+ function filterName() {
+ return ({ all: "Everything", problems: "Problems", security: "Security", updates: "Updates", apps: "Apps", camera: "Camera and microphone" })[page.filter];
+ }
+
+ function exportText() {
+ const head = "Wild OS history: " + filterName() + ", " + page.periodSpan + "\n"
+ + "Saved " + Format.longDate(new Date()) + " at " + Format.time(new Date()) + " from Settings > System > History\n";
+ const body = page.shown.map(x => HistoryWords.fullText(x.event, History.events)).join("\n----------------------------------------\n\n");
+ return head + "\n" + (body.length > 0 ? body : emptyText() + "\n");
+ }
+
+ // wildos-settings --page history-camera, from the lights' This week.
+ function takeRequest() {
+ if (Navigator.request === "camera-mic") {
+ Navigator.request = "";
+ page.filter = "camera";
+ page.period = "week";
+ page.limit = 120;
+ }
+ }
+
+ Connections {
+ target: Navigator
+ function onRequestChanged() {
+ page.takeRequest();
+ }
+ }
+
+ Component.onCompleted: {
+ takeRequest();
+ History.refresh();
+ }
+
+ Notice {
+ id: notice
+ Layout.fillWidth: true
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 14
+
+ // The summary: problems in the period, or that all went well.
+ Rectangle {
+ id: hero
+ readonly property bool worry: page.unreadable || page.problems > 0
+ Layout.fillWidth: true
+ implicitHeight: heroRow.implicitHeight + 28
+ radius: 12
+ color: UI.Style.tone(0.05)
+ border.width: 1
+ border.color: UI.Style.tone(0.07)
+
+ RowLayout {
+ id: heroRow
+ anchors.left: parent.left
+ anchors.right: parent.right
+ anchors.verticalCenter: parent.verticalCenter
+ anchors.leftMargin: 18
+ anchors.rightMargin: 18
+ spacing: 18
+
+ Rectangle {
+ Layout.preferredWidth: 46
+ Layout.preferredHeight: 46
+ radius: 23
+ color: Qt.rgba(heroIcon.color.r, heroIcon.color.g, heroIcon.color.b, 0.16)
+
+ PathIcon {
+ id: heroIcon
+ anchors.centerIn: parent
+ name: hero.worry ? "triangle-alert" : "status-ok"
+ size: 24
+ strokeWidth: 2.1
+ color: hero.worry ? HistoryWords.amber : HistoryWords.green
+ }
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 3
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: page.unreadable ? "History can't be shown"
+ : page.problems > 0 ? Format.plural(page.problems, "thing", "things") + " worth a look " + page.periodWords
+ : "Nothing needs a look " + page.periodWords
+ size: 16.5
+ font.weight: UI.Style.weightBold
+ wrapMode: Text.Wrap
+ }
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: page.unreadable ? History.problemDetail + " Restarting the PC usually fixes this."
+ : page.problems > 0 ? "Everything else went as it should. Choose Problems to see only those."
+ : "Everything went as it should."
+ size: 13
+ color: UI.Style.inkMuted
+ wrapMode: Text.Wrap
+ }
+ }
+
+ UI.Button {
+ implicitHeight: 32
+ text: "Report a problem"
+ onClicked: {
+ if (!History.openReport()) {
+ notice.show("Report a problem isn't installed", "Install it from the Store to send a report.", true);
+ }
+ }
+ }
+ }
+ }
+
+ RowLayout {
+ Layout.fillWidth: true
+ spacing: 12
+
+ Segmented {
+ enabled: !page.unreadable
+ options: [{ value: "all", text: "Everything" }, { value: "problems", text: "Problems" }, { value: "security", text: "Security" },
+ { value: "updates", text: "Updates" }, { value: "apps", text: "Apps" }]
+ value: page.filter
+ onPicked: v => {
+ page.filter = v;
+ page.limit = 120;
+ }
+ }
+
+ Item {
+ Layout.fillWidth: true
+ }
+
+ UI.ComboBox {
+ Layout.preferredWidth: 150
+ enabled: !page.unreadable
+ Accessible.name: "Period"
+ model: [{ value: "today", text: "Today" }, { value: "week", text: "Last 7 days" }, { value: "month", text: "Last 30 days" }]
+ currentIndex: model.findIndex(o => o.value === page.period)
+ onActivated: index => {
+ page.period = model[index].value;
+ page.limit = 120;
+ }
+ }
+ }
+
+ // The latest events could not be gathered, but older ones are here.
+ RowLayout {
+ Layout.fillWidth: true
+ visible: History.problem === "stale"
+ spacing: 8
+
+ PathIcon {
+ name: "triangle-alert"
+ size: 14
+ strokeWidth: 2
+ color: HistoryWords.amber
+ }
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: "Some of the latest events may be missing. " + History.problemDetail
+ size: 12.5
+ color: UI.Style.inkMuted
+ wrapMode: Text.Wrap
+ elide: Text.ElideNone
+ }
+ }
+
+ Repeater {
+ model: page.days
+
+ ColumnLayout {
+ id: dayBlock
+ required property var modelData
+ Layout.fillWidth: true
+ spacing: 14
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: dayBlock.modelData.label.toUpperCase()
+ size: 12.5
+ font.weight: UI.Style.weightBold
+ font.letterSpacing: 0.25
+ color: UI.Style.inkSubtle
+ Accessible.role: Accessible.Heading
+ }
+
+ Rectangle {
+ Layout.fillWidth: true
+ implicitHeight: rowsColumn.implicitHeight
+ radius: 12
+ color: UI.Style.tone(0.05)
+ border.width: 1
+ border.color: UI.Style.tone(0.07)
+ clip: true
+
+ Column {
+ id: rowsColumn
+ width: parent.width
+
+ Repeater {
+ model: dayBlock.modelData.rows
+
+ T.AbstractButton {
+ id: eventRow
+ required property var modelData
+ required property int index
+ width: rowsColumn.width
+ height: 54
+ hoverEnabled: true
+ focusPolicy: Qt.StrongFocus
+ Accessible.role: Accessible.Button
+ Accessible.name: modelData.words.title + ". " + modelData.words.detail
+ Accessible.description: "Details"
+ onClicked: details.openFor(modelData.event)
+
+ background: Rectangle {
+ color: eventRow.hovered ? UI.Style.tone(0.03) : "transparent"
+ radius: 12
+
+ Rectangle {
+ visible: eventRow.index > 0
+ anchors.left: parent.left
+ anchors.right: parent.right
+ height: 1
+ color: UI.Style.tone(0.07)
+ }
+
+ UI.FocusRing {
+ visible: eventRow.visualFocus
+ targetRadius: 12
+ }
+ }
+
+ contentItem: RowLayout {
+ spacing: 14
+
+ Item {
+ Layout.leftMargin: 18
+ // The board's 38px fits a 24-hour clock; "10:42 PM" needs more.
+ Layout.preferredWidth: Format.twelveHour() ? 60 : 38
+ Layout.fillHeight: true
+
+ UI.Label {
+ anchors.verticalCenter: parent.verticalCenter
+ text: Format.time(eventRow.modelData.event.when)
+ size: 12.5
+ color: UI.Style.inkMuted
+ font.features: ({ "tnum": 1 })
+ }
+ }
+
+ PathIcon {
+ name: eventRow.modelData.words.icon
+ size: 19
+ strokeWidth: 1.9
+ color: eventRow.modelData.words.tone
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 2
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: eventRow.modelData.words.title
+ size: 13.5
+ font.weight: UI.Style.weightMedium
+ }
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: eventRow.modelData.words.detail
+ size: 12.5
+ color: UI.Style.inkMuted
+ }
+ }
+
+ UI.LinkButton {
+ Layout.rightMargin: 18
+ text: "Details"
+ Accessible.name: "Details of " + eventRow.modelData.words.title
+ onClicked: details.openFor(eventRow.modelData.event)
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // Nothing in the period, or nothing for the filter chosen.
+ Rectangle {
+ Layout.fillWidth: true
+ visible: page.shown.length === 0 && !page.unreadable
+ implicitHeight: 54
+ radius: 12
+ color: UI.Style.tone(0.05)
+ border.width: 1
+ border.color: UI.Style.tone(0.07)
+
+ UI.Label {
+ anchors.left: parent.left
+ anchors.right: parent.right
+ anchors.leftMargin: 18
+ anchors.rightMargin: 18
+ anchors.verticalCenter: parent.verticalCenter
+ text: History.loading && History.events.length === 0 ? "Looking at what happened…" : page.emptyText()
+ size: 13
+ color: UI.Style.inkMuted
+ }
+ }
+
+ UI.LinkButton {
+ visible: page.shown.length > page.limit
+ text: "Show " + Math.min(120, page.shown.length - page.limit) + " more"
+ onClicked: page.limit += 120
+ }
+
+ RowLayout {
+ Layout.fillWidth: true
+ spacing: 8
+
+ PathIcon {
+ name: "lock-round"
+ size: 14
+ strokeWidth: 2
+ color: UI.Style.inkMuted
+ }
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: "Kept on this PC for 30 days, then deleted. Nothing is sent anywhere."
+ size: 12.5
+ color: UI.Style.inkMuted
+ wrapMode: Text.Wrap
+ elide: Text.ElideNone
+ }
+
+ UI.LinkButton {
+ text: "Save as a file"
+ visible: !page.unreadable
+ onClicked: {
+ saveDialog.selectedFile = History.defaultSaveFile();
+ saveDialog.open();
+ }
+ }
+ }
+ }
+
+ Timer {
+ interval: 60000
+ running: page.visible
+ repeat: true
+ onTriggered: {
+ page.now = new Date();
+ History.refresh();
+ }
+ }
+
+ HistoryDetailDialog {
+ id: details
+ onFailed: message => notice.show("Report a problem couldn't open", message, true)
+ }
+
+ FileDialog {
+ id: saveDialog
+ title: "Save history as a file"
+ fileMode: FileDialog.SaveFile
+ defaultSuffix: "txt"
+ nameFilters: ["Text files (*.txt)"]
+ onAccepted: {
+ if (History.saveTo(selectedFile, page.exportText())) {
+ const parts = decodeURIComponent(selectedFile.toString()).split("/");
+ notice.show("History saved", Format.plural(page.shown.length, "event was", "events were") + " saved as " + parts[parts.length - 1]
+ + ", in " + parts[parts.length - 2] + ".", false);
+ } else {
+ notice.show("History wasn't saved", "That folder can't be written to. Choose another one.", true);
+ }
+ }
+ }
+}
diff --git a/packages/wildos-settings/qml/pages/InstalledAppsPage.qml b/packages/wildos-settings/qml/pages/InstalledAppsPage.qml
index a45f104..3648c02 100644
--- a/packages/wildos-settings/qml/pages/InstalledAppsPage.qml
+++ b/packages/wildos-settings/qml/pages/InstalledAppsPage.qml
@@ -5,19 +5,67 @@ import WildOS.UI as UI
// Installed apps: everything that shows in Start, with Uninstall for the
// apps that can safely go. Store apps are removed with flatpak, others with
-// PackageKit, which asks for the administrator password.
+// PackageKit, which asks for the administrator password. Apps that installed
+// themselves into the home folder (their own install script, an AppImage)
+// belong to no package: their files go to the Trash, listed first. Windows
+// mode's apps are uninstalled inside Windows: a Store app at once, any
+// other program by its own uninstaller, which opens in a window.
PageScroll {
id: page
property string message
property bool messageIsError: false
+ // Start's Uninstall for an app it can't remove itself (Wild OS's own,
+ // one in the home folder or in Windows mode) opens this page with
+ // Navigator.request "uninstall:<launcher id>".
+ function takeRequest() {
+ if (!Navigator.request.startsWith("uninstall:")) {
+ return;
+ }
+ const id = Navigator.request.substring(10).replace(/.desktop$/, "");
+ Navigator.request = "";
+ const name = apps.nameOf(id);
+ if (name.length === 0) {
+ return;
+ }
+ if (apps.canUninstall(id)) {
+ page.ask(id, name);
+ } else {
+ page.messageIsError = true;
+ page.message = name + " is part of Wild OS, so it can't be uninstalled.";
+ }
+ }
+
+ function ask(id, name) {
+ confirm.appId = id;
+ confirm.appName = name;
+ confirm.files = apps.homeFiles(id);
+ confirm.data = apps.homeData(id);
+ confirm.windows = apps.isWindowsApp(id);
+ confirm.withData = false;
+ confirm.open();
+ }
+
+ Component.onCompleted: takeRequest()
+
+ Connections {
+ target: Navigator
+ function onRequestChanged() {
+ page.takeRequest();
+ }
+ }
+
AppsModel {
id: apps
onUninstalled: name => {
page.messageIsError = false;
page.message = name + " was uninstalled.";
}
+ onUninstallOpened: name => {
+ page.messageIsError = false;
+ page.message = name + "'s uninstaller is open in Windows. Finish there, and " + name + " leaves this list once it's done.";
+ }
onUninstallFailed: (name, reason) => {
page.messageIsError = true;
page.message = name + " was not uninstalled. " + (reason.length > 0 ? reason : "Try again from the Store.");
@@ -74,18 +122,14 @@ PageScroll {
required property bool canUninstall
themeIcon: appIcon.length > 0 ? appIcon : "application-x-executable"
title: name
- description: source === "store" ? "From the Store" : canUninstall ? "Installed app" : "Part of Wild OS"
+ description: source === "store" ? "From the Store" : source === "home" ? "Installed in your home folder" : source === "windows" ? "Runs in Windows mode" : canUninstall ? "Installed app" : "Part of Wild OS"
UI.Button {
anchors.verticalCenter: parent.verticalCenter
visible: app.canUninstall
text: apps.busyId === app.appId ? "Uninstalling" : "Uninstall"
enabled: apps.busyId.length === 0
- onClicked: {
- confirm.appId = app.appId;
- confirm.appName = app.name;
- confirm.open();
- }
+ onClicked: page.ask(app.appId, app.name)
}
}
}
@@ -97,9 +141,34 @@ PageScroll {
property string appId
property string appName
+ property var files: []
+ property var data: []
+ property bool withData: false
+ property bool windows: false
+ readonly property bool home: files.length > 0
title: "Uninstall " + appName + "?"
- text: appName + " will be removed from this computer. Your own files are not touched."
+ text: windows
+ ? "Windows uninstalls " + appName + ". If it has an uninstaller of its own, that opens in a window to finish. If it came as part of a bigger program, like Word in Microsoft 365, the whole program goes. Files you saved in your folders stay."
+ : home
+ ? appName + " installed itself in your home folder. These go to the Recycle Bin, so you can put them back:"
+ : appName + " will be removed from this computer. Your own files are not touched."
+
+ UI.Label {
+ Layout.fillWidth: true
+ visible: confirm.home
+ text: confirm.files.concat(confirm.withData ? confirm.data : []).join("\n")
+ color: UI.Style.inkMuted
+ size: 12
+ wrapMode: Text.WrapAnywhere
+ }
+
+ UI.CheckBox {
+ visible: confirm.home && confirm.data.length > 0
+ text: "Also remove its settings and data"
+ checked: confirm.withData
+ onToggled: confirm.withData = checked
+ }
buttons: [
UI.Button {
text: "Uninstall"
@@ -107,7 +176,7 @@ PageScroll {
onClicked: {
confirm.close();
page.message = "";
- apps.uninstall(confirm.appId);
+ apps.uninstall(confirm.appId, confirm.withData);
}
},
UI.Button {
diff --git a/packages/wildos-settings/qml/pages/KeyboardPage.qml b/packages/wildos-settings/qml/pages/KeyboardPage.qml
index f0068d6..6b3f337 100644
--- a/packages/wildos-settings/qml/pages/KeyboardPage.qml
+++ b/packages/wildos-settings/qml/pages/KeyboardPage.qml
@@ -275,7 +275,7 @@ PageScroll {
const query = filter.text.trim().toLowerCase();
const taken = page.layouts.map(l => l.layout + "|" + l.variant);
return all.filter(l => !taken.includes(l.layout + "|" + l.variant)
- && (query.length === 0 || l.name.toLowerCase().includes(query)));
+ && (query.length === 0 || l.name.toLowerCase().includes(query) || (l.keywords || "").includes(query)));
}
title: "Add a keyboard"
@@ -292,7 +292,7 @@ PageScroll {
UI.SearchField {
id: filter
Layout.fillWidth: true
- placeholderText: "Search layouts, for example French"
+ placeholderText: "Search by country, language or layout, for example Belgium"
onTextChanged: addDialog.chosen = -1
onDownPressed: {
addDialog.chosen = Math.max(0, addDialog.chosen);
diff --git a/packages/wildos-settings/qml/pages/NetworkAdvancedPage.qml b/packages/wildos-settings/qml/pages/NetworkAdvancedPage.qml
index ba4987b..3fbaf1a 100644
--- a/packages/wildos-settings/qml/pages/NetworkAdvancedPage.qml
+++ b/packages/wildos-settings/qml/pages/NetworkAdvancedPage.qml
@@ -794,6 +794,7 @@ PageScroll {
Layout.fillWidth: true
visible: addVpnDialog.typing
revealable: true
+ UI.NoPaste {}
}
FieldLabel {
diff --git a/packages/wildos-settings/qml/pages/NetworkPage.qml b/packages/wildos-settings/qml/pages/NetworkPage.qml
index 6da7609..2bde8cd 100644
--- a/packages/wildos-settings/qml/pages/NetworkPage.qml
+++ b/packages/wildos-settings/qml/pages/NetworkPage.qml
@@ -171,6 +171,7 @@ PageScroll {
Layout.fillWidth: true
placeholderText: "Network password"
revealable: true
+ UI.NoPaste {}
onAccepted: connectButton.clicked()
Keys.onEscapePressed: page.expanded = ""
}
diff --git a/packages/wildos-settings/qml/pages/OtherUsersPage.qml b/packages/wildos-settings/qml/pages/OtherUsersPage.qml
index 2bdcc02..fa86b7f 100644
--- a/packages/wildos-settings/qml/pages/OtherUsersPage.qml
+++ b/packages/wildos-settings/qml/pages/OtherUsersPage.qml
@@ -221,6 +221,7 @@ PageScroll {
Layout.fillWidth: true
placeholderText: "Password"
revealable: true
+ UI.NoPaste {}
error: text.length > 0 && text.length < 8
onAccepted: confirmField.forceActiveFocus()
}
@@ -236,6 +237,7 @@ PageScroll {
Layout.fillWidth: true
placeholderText: "Confirm the password"
revealable: true
+ UI.NoPaste {}
error: text.length > 0 && text !== passwordField.text
onAccepted: createButton.clicked()
}
diff --git a/packages/wildos-settings/qml/pages/PowerPage.qml b/packages/wildos-settings/qml/pages/PowerPage.qml
index e9a20e8..6426865 100644
--- a/packages/wildos-settings/qml/pages/PowerPage.qml
+++ b/packages/wildos-settings/qml/pages/PowerPage.qml
@@ -134,7 +134,7 @@ PageScroll {
id: threadsCard
Layout.fillWidth: true
visible: Processor.threadsAvailable
- readonly property bool pending: Processor.everyThread !== Processor.everyThreadActive
+ readonly property bool pending: Processor.threadsPending
Column {
width: parent.width
@@ -143,10 +143,11 @@ PageScroll {
iconName: "chip"
title: "Use every processor thread"
description: Processor.everyThreadLocked
- ? "Off at Strict and Maximum protection, which keep every CPU flaw protection on."
+ ? (threadsCard.pending ? "Restart to finish turning it off. " : "")
+ + "Off while extra processor protection is on, in Privacy and security."
: threadsCard.pending
? "Restart to finish turning it " + (Processor.everyThread ? "on." : "off.")
- : "Faster heavy apps, one less CPU-flaw protection for the whole PC. Needs a restart."
+ : "Faster heavy apps. Off keeps the second thread of each core idle, a little safer. Needs a restart."
UI.Toggle {
id: threadsToggle
@@ -154,14 +155,14 @@ PageScroll {
checked: Processor.everyThread && !Processor.everyThreadLocked
enabled: !Processor.busy && !Processor.everyThreadLocked
locked: Processor.everyThreadLocked
- lockedReason: "Strict and Maximum protection keep this off"
+ lockedReason: "Extra processor protection keeps this off"
Accessible.name: "Use every processor thread"
onToggled: Processor.setEveryThread(checked)
}
}
UI.SettingRow {
- visible: threadsCard.pending && !Processor.everyThreadLocked
+ visible: threadsCard.pending
title: "Restart to apply"
description: "Open apps are asked to save first."
diff --git a/packages/wildos-settings/qml/pages/PrintersAdvancedPage.qml b/packages/wildos-settings/qml/pages/PrintersAdvancedPage.qml
index 5ef15c5..149dbe3 100644
--- a/packages/wildos-settings/qml/pages/PrintersAdvancedPage.qml
+++ b/packages/wildos-settings/qml/pages/PrintersAdvancedPage.qml
@@ -51,6 +51,16 @@ PageScroll {
onSelectedChanged: prefs = selected.length > 0 ? Printers.preferences(selected) : ({})
+ // Printers and scanners' "It only has a Windows driver" opens this page
+ // with Navigator.request "printers-driver", straight into choosing a
+ // driver.
+ Component.onCompleted: {
+ if (Navigator.request === "printers-driver") {
+ Navigator.request = "";
+ startAdding();
+ }
+ }
+
Timer {
interval: 4000
running: Printers.available && page.visible
diff --git a/packages/wildos-settings/qml/pages/PrintersPage.qml b/packages/wildos-settings/qml/pages/PrintersPage.qml
index c945fd1..530a87b 100644
--- a/packages/wildos-settings/qml/pages/PrintersPage.qml
+++ b/packages/wildos-settings/qml/pages/PrintersPage.qml
@@ -3,12 +3,15 @@ import QtQuick.Layouts
import WildOS.Settings
import WildOS.UI as UI
-// Printers and scanners, after Windows 11: "Add a printer or scanner"
-// searches the network and lists what it finds, each with Add device, with
-// a way in by address for a printer that does not announce itself; below,
-// the printers already added. Opening one shows its own page (Set as
-// default, Print a test page, Remove), which stacks in the breadcrumb the
-// way Windows does.
+// Printers and scanners (SettingsPrinters.dc, board 6.23). Opening the page
+// looks for printers and scanners on the network; each one not added yet is
+// offered at the top with one Add, which for a driverless printer (IPP
+// Everywhere, AirPrint, Mopria) or an eSCL or WSD scanner is all it takes.
+// Below, the printers and scanners already added, each with its state,
+// whether it is the default, whether it also scans and its ink where the
+// printer reports it; then the four ways out when something isn't working.
+// Manage opens a printer's or scanner's own page, which stacks in the
+// breadcrumb the way Windows does.
PageScroll {
id: page
@@ -21,27 +24,93 @@ PageScroll {
}
return null;
}
- property bool adding: false
+ // A scanner's row, kept whole: USB ones come from Devices and have no
+ // name of their own in Printers.
+ property var scanner: null
property string addingUri
- readonly property int depth: selected.length > 0 ? 2 : 1
- readonly property var subTitles: printer ? [printer.info] : []
+ readonly property int depth: selected.length > 0 || scanner !== null ? 2 : 1
+ readonly property var subTitles: printer ? [printer.info] : scanner ? [scanner.title] : []
+
+ readonly property bool online: NetworkSettings.current.uuid !== undefined
+
+ // Printers found on the network that are not set up. A search that
+ // started before the queues were read can list one already added; its
+ // queue says otherwise.
+ readonly property var offers: {
+ const queued = Printers.printers.map(p => p.uri).concat(Printers.printers.map(p => p.info), Printers.printers.map(p => p.name));
+ const out = Printers.found.filter(f => !queued.includes(f.uri) && !queued.includes(f.name))
+ .map(f => ({ kind: "printer", name: f.name, uri: f.uri, scans: f.scans }));
+ for (const s of Printers.foundScanners) {
+ out.push({ kind: "scanner", name: s.name, uri: "", scans: true });
+ }
+ return out;
+ }
+
+ readonly property var usbScanners: Devices.devices.filter(d => d.kind === "scanner")
+
+ readonly property var rows: {
+ const out = [];
+ // The default first, as the board lists it, then by name.
+ const printers = Printers.printers.slice().sort((a, b) => (b.isDefault - a.isDefault) || a.info.localeCompare(b.info));
+ for (const p of printers) {
+ out.push({ kind: "printer", key: p.name, title: p.info, line: statusOf(p), problem: p.problem });
+ }
+ for (const s of Printers.scanners) {
+ out.push({ kind: "scanner", key: "net:" + s.name, title: s.name, url: s.url, network: true,
+ line: s.seen ? "Ready · On your network" : Printers.scannersLooked ? "Not found on your network" : "On your network",
+ problem: !s.seen && Printers.scannersLooked });
+ }
+ for (const d of usbScanners) {
+ out.push({ kind: "scanner", key: "usb:" + d.name, title: d.name, url: "", network: false, model: d.model || "",
+ line: "Ready · Connected by USB", problem: false });
+ }
+ return out;
+ }
+
+ // The printer "Print a test page" uses: the default, or the only one.
+ readonly property var testPrinter: {
+ const list = Printers.printers;
+ return list.find(p => p.isDefault) || (list.length > 0 ? list[0] : null);
+ }
function back() {
- if (selected.length > 0) {
+ if (depth > 1) {
selected = "";
+ scanner = null;
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" : "");
+ return [p.status, p.isDefault ? "Default" : "", p.scans ? "Prints and scans" : "", p.ink,
+ p.jobs > 0 ? Format.plural(p.jobs, "document", "documents") + " waiting" : ""]
+ .filter(t => t && t.length > 0).join(" · ");
+ }
+
+ function offerText(o) {
+ return (o.kind === "scanner" ? "Scans." : o.scans ? "Prints and scans." : "Prints.")
+ + " It works straight away, with no driver to install.";
+ }
+
+ function openCapture() {
+ if (!Printers.openCapture()) {
+ notice.show("Capture didn't open", "Capture isn't installed on this computer.", true);
+ }
}
Component.onDestruction: Printers.stopSearch()
+ // The page looks as soon as it opens. System > Devices' "Set up" opens
+ // it with Navigator.request "printers-add", which this look answers.
+ Component.onCompleted: {
+ if (Navigator.request === "printers-add") {
+ Navigator.request = "";
+ }
+ Printers.search();
+ }
+
// Printers change state on their own (paper runs out, a job finishes).
Timer {
interval: 4000
@@ -54,9 +123,10 @@ PageScroll {
target: Printers
function onDone(title, message) {
notice.show(title, message, false);
- if (title === "Printer added") {
- page.adding = false;
- }
+ }
+ // A printer removed here, or anywhere else, leaves its page once the
+ // list read after the change no longer has it.
+ function onChanged() {
if (page.selected.length > 0 && page.printer === null) {
page.selected = "";
}
@@ -66,6 +136,16 @@ PageScroll {
}
}
+ // Joining a network is when its printers can be found.
+ Connections {
+ target: NetworkSettings
+ function onCurrentChanged() {
+ if (page.online && !Printers.searching) {
+ Printers.search();
+ }
+ }
+ }
+
Notice {
id: notice
}
@@ -80,119 +160,218 @@ PageScroll {
ColumnLayout {
Layout.fillWidth: true
- visible: page.selected.length === 0 && Printers.available
+ visible: page.depth === 1 && Printers.available
spacing: Metrics.sectionGap
- UI.Card {
+ // Several found at once read as one list, closer than sections.
+ ColumnLayout {
Layout.fillWidth: true
+ visible: page.offers.length > 0
+ spacing: 10
- Column {
- width: parent.width
-
- UI.SettingRow {
- iconName: "printer"
- iconTile: true
- minHeight: 68
- title: "Add a printer or scanner"
- description: Printers.searching ? "Looking for printers on your network" : ""
+ Repeater {
+ model: page.offers
- UI.Spinner {
- anchors.verticalCenter: parent.verticalCenter
- visible: Printers.searching
- }
+ OfferCard {
+ id: offer
+ required property var modelData
+ iconName: modelData.kind === "scanner" ? "scan-line" : "printer-round"
+ title: "Found on your network: " + modelData.name
+ description: page.offerText(modelData)
UI.Button {
anchors.verticalCenter: parent.verticalCenter
- text: Printers.searching ? "Stop" : page.adding ? "Search again" : "Add device"
- kind: page.adding ? "secondary" : "primary"
- enabled: Printers.busy !== "add"
+ text: "Add"
+ kind: "primary"
+ busy: Printers.busy === "add" && page.addingUri === offer.modelData.uri && offer.modelData.kind === "printer"
+ enabled: Printers.busy.length === 0
onClicked: {
- if (Printers.searching) {
- Printers.stopSearch();
+ if (offer.modelData.kind === "scanner") {
+ Printers.addScanner(offer.modelData.name);
} else {
- page.adding = true;
- Printers.search();
+ page.addingUri = offer.modelData.uri;
+ Printers.add(offer.modelData.uri, offer.modelData.name);
}
}
}
}
+ }
+ }
- Repeater {
- model: page.adding ? Printers.found : []
+ // Nothing to offer: still looking, nothing there, or no network to
+ // look on. With printers already added, finding nothing new needs
+ // no card of its own, as on the board.
+ OfferCard {
+ id: idle
+ visible: page.offers.length === 0 && (page.rows.length === 0 || !page.online)
+ readonly property bool looking: Printers.searching || Printers.findingScanners
+ iconName: !page.online && !looking ? "wifi-round" : looking ? "search-round" : "printer-round"
+ title: !page.online && !looking ? "Not connected to a network"
+ : looking ? "Looking for printers and scanners"
+ : "No new printers or scanners found"
+ description: !page.online && !looking ? "Printers and scanners on a network show up here once this computer joins it."
+ : looking ? "On the network this computer is joined to."
+ : "Check it's switched on and joined to the same network as this computer."
+
+ UI.Spinner {
+ anchors.verticalCenter: parent.verticalCenter
+ visible: idle.looking
+ }
- UI.SettingRow {
- id: foundRow
- required property var modelData
- iconName: "printer"
- title: modelData.name
- description: [modelData.model, modelData.location].filter(t => t && t.length > 0 && t !== modelData.name).join(", ")
+ UI.Button {
+ anchors.verticalCenter: parent.verticalCenter
+ visible: !idle.looking
+ text: page.online ? "Search again" : "Network settings"
+ onClicked: page.online ? Printers.search() : Navigator.open("network")
+ }
+ }
- UI.Button {
- anchors.verticalCenter: parent.verticalCenter
- text: "Add device"
- busy: Printers.busy === "add" && page.addingUri === foundRow.modelData.uri
- enabled: Printers.busy.length === 0
- onClicked: {
- page.addingUri = foundRow.modelData.uri;
- Printers.add(foundRow.modelData.uri, foundRow.modelData.name);
- }
- }
- }
- }
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 10
- UI.SettingRow {
- visible: page.adding && !Printers.searching && Printers.found.length === 0
- title: "No new printers found"
- description: "Check the printer is on and joined to the same network as this computer."
- }
+ SectionTitle {
+ text: "Your printers and scanners"
+ }
- UI.SettingRow {
- visible: page.adding
- title: "The printer that I want isn't listed"
- description: "Add it by its network name or IP address"
+ UI.Card {
+ Layout.fillWidth: true
+ visible: page.rows.length > 0
- UI.Button {
- anchors.verticalCenter: parent.verticalCenter
- text: "Add manually"
- enabled: Printers.busy.length === 0
- onClicked: addressDialog.open()
+ Column {
+ width: parent.width
+
+ Repeater {
+ model: page.rows
+
+ UI.SettingRow {
+ id: row
+ required property var modelData
+ title: modelData.title
+ description: modelData.line
+ descriptionColor: modelData.problem ? UI.Style.warning : UI.Style.inkMuted
+ interactive: true
+ minHeight: 60
+ Accessible.name: modelData.title + ", " + modelData.line
+ onClicked: manage()
+
+ function manage() {
+ if (modelData.kind === "printer") {
+ page.selected = modelData.key;
+ } else {
+ page.scanner = modelData;
+ }
+ }
+
+ leading: PathIcon {
+ name: row.modelData.kind === "scanner" ? "scan-line" : "printer-round"
+ size: 20
+ strokeWidth: 1.8
+ }
+
+ UI.LinkButton {
+ anchors.verticalCenter: parent.verticalCenter
+ text: "Manage"
+ Accessible.name: "Manage " + row.modelData.title
+ onClicked: row.manage()
+ }
+ }
}
}
}
+
+ UI.Label {
+ Layout.fillWidth: true
+ visible: page.rows.length === 0
+ text: "No printers or scanners yet. Most made since 2014 work without a driver and show up above when they're switched on."
+ color: UI.Style.inkMuted
+ wrapMode: Text.Wrap
+ elide: Text.ElideNone
+ }
}
- UI.Card {
+ ColumnLayout {
Layout.fillWidth: true
- visible: Printers.printers.length > 0
+ spacing: 10
- Column {
- width: parent.width
+ SectionTitle {
+ text: "If something is not working"
+ }
- Repeater {
- model: Printers.printers
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
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
+ title: "My printer is not in the list"
+ description: "Add it by its network address, or plug it in with a USB cable."
+ minHeight: 60
+ leading: PathIcon { name: "search-round"; size: 20; strokeWidth: 1.8 }
+
+ UI.Button {
+ anchors.verticalCenter: parent.verticalCenter
+ text: "Add by address"
+ enabled: Printers.busy.length === 0
+ onClicked: addressDialog.open()
+ }
+ }
+
+ // Printing through Windows mode (board 6.24) waits on a
+ // test with real hardware. Until then this leads to the
+ // drivers Wild OS has, where a model from the same
+ // series often prints.
+ UI.SettingRow {
+ title: "It only has a Windows driver"
+ description: "Try a driver for the same maker or series. Plain printing works on many models."
+ minHeight: 60
+ visible: Pages.exists("printersadvanced")
+ leading: PathIcon { name: "app-window"; size: 20; strokeWidth: 1.8 }
+
+ UI.Button {
+ anchors.verticalCenter: parent.verticalCenter
+ text: "Set up"
+ onClicked: {
+ Navigator.request = "printers-driver";
+ Navigator.open("printersadvanced");
+ }
+ }
+ }
+
+ UI.SettingRow {
+ title: "Print a test page"
+ description: page.testPrinter === null ? "Add a printer first."
+ : Printers.printers.length > 1 ? "Prints on " + page.testPrinter.info + ". Check it's lined up and has ink."
+ : "Check the printer is lined up and has ink."
+ minHeight: 60
+ leading: PathIcon { name: "file-text"; size: 20; strokeWidth: 1.8 }
+
+ UI.Button {
+ anchors.verticalCenter: parent.verticalCenter
+ text: "Print"
+ busy: page.testPrinter !== null && Printers.busy === page.testPrinter.name
+ enabled: Printers.busy.length === 0 && page.testPrinter !== null && !page.testPrinter.paused
+ onClicked: Printers.printTestPage(page.testPrinter.name)
+ }
+ }
+
+ UI.SettingRow {
+ title: "Scan something"
+ description: "Opens Capture on its Scan tab."
+ minHeight: 60
+ leading: PathIcon { name: "scan-line"; size: 20; strokeWidth: 1.8 }
+
+ UI.Button {
+ anchors.verticalCenter: parent.verticalCenter
+ text: "Open Capture"
+ onClicked: page.openCapture()
+ }
}
}
}
}
- UI.Label {
- Layout.fillWidth: true
- visible: Printers.printers.length === 0
- text: "No printers yet. Printers that work over the network without a driver, which is most made since 2014, can be added above."
- color: UI.Style.inkMuted
- wrapMode: Text.Wrap
- elide: Text.ElideNone
- }
-
ColumnLayout {
Layout.fillWidth: true
visible: Pages.exists("printersadvanced")
@@ -225,47 +404,11 @@ PageScroll {
visible: page.printer !== null
spacing: Metrics.sectionGap
- UI.Card {
- Layout.fillWidth: true
- implicitHeight: 96
-
- RowLayout {
- anchors.fill: parent
- anchors.leftMargin: 24
- anchors.rightMargin: 24
- spacing: 18
-
- Rectangle {
- Layout.preferredWidth: 56
- Layout.preferredHeight: 56
- radius: UI.Style.radiusMd
- color: UI.Style.surfaceTile
-
- UI.Icon {
- anchors.centerIn: parent
- name: "printer"
- size: 28
- }
- }
-
- ColumnLayout {
- Layout.fillWidth: true
- spacing: 2
-
- UI.Label {
- Layout.fillWidth: true
- text: page.printer ? page.printer.info : ""
- size: 18
- font.weight: UI.Style.weightSemiBold
- }
-
- UI.Label {
- Layout.fillWidth: true
- text: page.printer ? page.statusOf(page.printer) : ""
- color: page.printer && page.printer.problem ? UI.Style.warning : UI.Style.inkMuted
- }
- }
- }
+ DeviceHeader {
+ iconName: "printer-round"
+ title: page.printer ? page.printer.info : ""
+ line: page.printer ? page.statusOf(page.printer) : ""
+ problem: page.printer !== null && page.printer.problem
}
UI.Card {
@@ -310,6 +453,19 @@ PageScroll {
}
}
+ UI.SettingRow {
+ visible: page.printer !== null && page.printer.scans
+ title: "Scan something"
+ description: "Opens Capture on its Scan tab"
+ leading: PathIcon { name: "scan-line"; size: 20; strokeWidth: 1.8 }
+
+ UI.Button {
+ anchors.verticalCenter: parent.verticalCenter
+ text: "Open Capture"
+ onClicked: page.openCapture()
+ }
+ }
+
UI.SettingRow {
visible: page.printer !== null && page.printer.jobs > 0
iconName: "list"
@@ -354,39 +510,224 @@ PageScroll {
}
}
- ColumnLayout {
+ AboutCard {
+ heading: "About this printer"
+ facts: page.printer ? [
+ ["Ink and toner", page.printer.inkDetail],
+ ["Model", page.printer.model],
+ ["Location", page.printer.location],
+ ["Address", page.printer.uri],
+ ["Name apps use", page.printer.name]
+ ] : []
+ }
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ visible: page.scanner !== null
+ spacing: Metrics.sectionGap
+
+ DeviceHeader {
+ iconName: "scan-line"
+ title: page.scanner ? page.scanner.title : ""
+ line: page.scanner ? page.scanner.line : ""
+ problem: page.scanner !== null && page.scanner.problem
+ }
+
+ UI.Card {
Layout.fillWidth: true
- spacing: 10
- SectionTitle {
- text: "About this printer"
+ Column {
+ width: parent.width
+
+ UI.SettingRow {
+ title: "Scan something"
+ description: "Opens Capture on its Scan tab"
+ leading: PathIcon { name: "scan-line"; size: 20; strokeWidth: 1.8 }
+
+ UI.Button {
+ anchors.verticalCenter: parent.verticalCenter
+ text: "Open Capture"
+ onClicked: page.openCapture()
+ }
+ }
+
+ UI.SettingRow {
+ visible: page.scanner !== null && page.scanner.network
+ iconName: "delete"
+ title: "Remove this scanner"
+ description: "It leaves this list. Capture can still find it on the network."
+
+ UI.Button {
+ anchors.verticalCenter: parent.verticalCenter
+ text: "Remove"
+ danger: true
+ onClicked: {
+ Printers.removeScanner(page.scanner.title);
+ page.scanner = null;
+ }
+ }
+ }
}
+ }
- UI.Card {
+ AboutCard {
+ heading: "About this scanner"
+ facts: page.scanner ? [
+ ["Connected by", page.scanner.network ? "Your network" : "USB"],
+ ["Model", page.scanner.model || ""],
+ ["Address", page.scanner.url || ""]
+ ] : []
+ }
+ }
+
+ // The tinted circle and two lines of the board's "Found on your
+ // network" card, in the list cards' own surface.
+ component OfferCard: UI.Card {
+ id: offerCard
+
+ property string iconName
+ property string title
+ property string description
+ default property alias actions: actionRow.data
+
+ Layout.fillWidth: true
+ topPadding: 14
+ bottomPadding: 14
+ leftPadding: 18
+ rightPadding: 18
+
+ RowLayout {
+ width: parent.width
+ spacing: 18
+
+ Rectangle {
+ Layout.preferredWidth: 46
+ Layout.preferredHeight: 46
+ radius: 23
+ color: Qt.rgba(UI.Style.accent.r, UI.Style.accent.g, UI.Style.accent.b, UI.Style.dark ? 0.16 : 0.12)
+
+ PathIcon {
+ anchors.centerIn: parent
+ name: offerCard.iconName
+ size: 24
+ strokeWidth: 2.1
+ color: UI.Style.accent
+ }
+ }
+
+ ColumnLayout {
Layout.fillWidth: true
+ spacing: 3
- Column {
- width: parent.width
+ UI.Label {
+ Layout.fillWidth: true
+ text: offerCard.title
+ size: 16.5
+ font.weight: UI.Style.weightSemiBold
+ }
- Repeater {
- model: page.printer ? [
- ["Model", page.printer.model],
- ["Location", page.printer.location],
- ["Address", page.printer.uri],
- ["Name apps use", page.printer.name]
- ].filter(r => r[1] && r[1].length > 0) : []
+ UI.Label {
+ Layout.fillWidth: true
+ text: offerCard.description
+ color: UI.Style.inkMuted
+ wrapMode: Text.Wrap
+ elide: Text.ElideNone
+ }
+ }
- UI.SettingRow {
- required property var modelData
- title: modelData[0]
+ Row {
+ id: actionRow
+ Layout.alignment: Qt.AlignVCenter
+ spacing: 8
+ }
+ }
+ }
- UI.Label {
- anchors.verticalCenter: parent.verticalCenter
- width: Math.min(implicitWidth, 420)
- text: modelData[1]
- color: UI.Style.inkMuted
- elide: Text.ElideMiddle
- }
+ component DeviceHeader: UI.Card {
+ id: header
+
+ property string iconName
+ property string title
+ property string line
+ property bool problem: false
+
+ Layout.fillWidth: true
+ implicitHeight: 96
+
+ RowLayout {
+ anchors.fill: parent
+ anchors.leftMargin: 24
+ anchors.rightMargin: 24
+ spacing: 18
+
+ Rectangle {
+ Layout.preferredWidth: 56
+ Layout.preferredHeight: 56
+ radius: UI.Style.radiusMd
+ color: UI.Style.surfaceTile
+
+ PathIcon {
+ anchors.centerIn: parent
+ name: header.iconName
+ size: 28
+ }
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 2
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: header.title
+ size: 18
+ font.weight: UI.Style.weightSemiBold
+ }
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: header.line
+ color: header.problem ? UI.Style.warning : UI.Style.inkMuted
+ wrapMode: Text.Wrap
+ elide: Text.ElideNone
+ }
+ }
+ }
+ }
+
+ component AboutCard: ColumnLayout {
+ id: about
+
+ property string heading
+ property var facts: []
+
+ Layout.fillWidth: true
+ spacing: 10
+
+ SectionTitle {
+ text: about.heading
+ }
+
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ Repeater {
+ model: about.facts.filter(r => r[1] && r[1].length > 0)
+
+ UI.SettingRow {
+ required property var modelData
+ title: modelData[0]
+
+ UI.Label {
+ anchors.verticalCenter: parent.verticalCenter
+ width: Math.min(implicitWidth, 420)
+ text: modelData[1]
+ color: UI.Style.inkMuted
+ elide: Text.ElideMiddle
}
}
}
diff --git a/packages/wildos-settings/qml/pages/PrivacyPage.qml b/packages/wildos-settings/qml/pages/PrivacyPage.qml
index b2be8ce..3820050 100644
--- a/packages/wildos-settings/qml/pages/PrivacyPage.qml
+++ b/packages/wildos-settings/qml/pages/PrivacyPage.qml
@@ -21,6 +21,19 @@ PageScroll {
return Format.plural(n, "app", "apps") + " can use your " + what;
}
+ Connections {
+ target: Advanced
+ function onFailed(key, message) {
+ if (key === "usb_locked") {
+ page.usbError = "USB protection could not be changed.";
+ }
+ }
+ // A cancelled password leaves it as it was.
+ function onChanged() {
+ usbToggle.checked = Qt.binding(() => Protection.status.devices === "on");
+ }
+ }
+
Connections {
target: System
function onUsbProtectionFailed(reason) {
@@ -121,6 +134,20 @@ PageScroll {
color: UI.Style.inkMuted
wrapMode: Text.Wrap
}
+
+ UI.Card {
+ Layout.fillWidth: true
+ visible: Advanced.available
+
+ UI.SettingRow {
+ width: parent.width
+ iconName: "shield"
+ title: "Advanced protection"
+ description: "Extra protection for people who want it"
+ chevron: true
+ onClicked: Navigator.open("advancedprotection")
+ }
+ }
}
ColumnLayout {
@@ -238,10 +265,80 @@ PageScroll {
checked: Protection.status.devices === "on"
enabled: !(System.securityChecking)
Accessible.name: "Block new USB devices"
- onToggled: System.setUsbProtection(checked)
+ // One switch with Advanced protection's "Ignore new USB
+ // devices while locked", kept in its store.
+ onToggled: {
+ page.usbError = "";
+ if (Advanced.available) {
+ Advanced.set("usb_locked", checked);
+ } else {
+ System.setUsbProtection(checked);
+ }
+ }
+ }
+ }
+
+ // Kicksecure's full set of processor flaw protections, forced on
+ // whatever the processor, with every core's second thread off.
+ // Off by default for speed; Strict and Maximum keep it on
+ // (settings-cpu-threads protect, read by 40_wildos.cfg).
+ UI.SettingRow {
+ id: cpuRow
+ readonly property bool pending: Processor.extraProtectionPending
+ minHeight: 64
+ title: "Extra processor protection"
+ description: Processor.extraProtectionLocked
+ ? "On at Strict and Maximum protection."
+ : cpuRow.pending
+ ? "Restart to finish turning it " + (Processor.extraProtection ? "on." : "off.")
+ : Processor.extraProtection
+ ? "On. Every processor flaw protection is forced on and each core runs one thread, so heavy apps and Windows mode are slower."
+ : "Off for speed: Linux picks protections to suit your processor. On forces every one, even for flaws your processor doesn't have, and turns off the second thread of each core. Needs a restart."
+ status: Processor.extraProtection ? "On" : "Off"
+
+ UI.Toggle {
+ id: cpuToggle
+ anchors.verticalCenter: parent.verticalCenter
+ checked: Processor.extraProtection
+ enabled: !Processor.busy && !Processor.extraProtectionLocked
+ locked: Processor.extraProtectionLocked
+ lockedReason: "Strict and Maximum protection keep this on"
+ Accessible.name: "Extra processor protection"
+ onToggled: {
+ cpuError.text = "";
+ Processor.setExtraProtection(checked);
+ }
+ }
+ }
+
+ UI.SettingRow {
+ visible: cpuRow.pending
+ title: "Restart to apply"
+ description: "Open apps are asked to save first."
+
+ UI.Button {
+ anchors.verticalCenter: parent.verticalCenter
+ text: "Restart now"
+ onClicked: Updates.restart()
}
}
}
+
+ Connections {
+ target: Processor
+ // A cancelled password leaves the choice as it was, so the switch goes back to it.
+ function onChanged() { cpuToggle.checked = Processor.extraProtection }
+ function onFailed(message) { cpuError.text = message }
+ }
+ }
+
+ UI.Label {
+ id: cpuError
+ visible: text.length > 0
+ Layout.fillWidth: true
+ wrapMode: Text.WordWrap
+ size: 13
+ color: UI.Style.warning
}
// The kernel's 32-bit layer, which Steam and older games need. A boot
diff --git a/packages/wildos-settings/qml/pages/SignInPage.qml b/packages/wildos-settings/qml/pages/SignInPage.qml
index ed71f57..e7c7c31 100644
--- a/packages/wildos-settings/qml/pages/SignInPage.qml
+++ b/packages/wildos-settings/qml/pages/SignInPage.qml
@@ -464,6 +464,7 @@ PageScroll {
UI.TextField {
id: walletPasswordField
+ UI.NoPaste {}
Layout.fillWidth: true
placeholderText: "Your account password"
revealable: true
@@ -473,6 +474,7 @@ PageScroll {
UI.TextField {
id: walletOtherField
+ UI.NoPaste {}
Layout.fillWidth: true
visible: walletDialog.needsOther
placeholderText: "The password your saved passwords use"
@@ -533,6 +535,7 @@ PageScroll {
UI.TextField {
id: autoPasswordField
+ UI.NoPaste {}
Layout.fillWidth: true
placeholderText: "Your password"
revealable: true
@@ -607,6 +610,7 @@ PageScroll {
UI.TextField {
id: currentField
+ UI.NoPaste {}
Layout.fillWidth: true
placeholderText: "Current password"
revealable: true
@@ -616,6 +620,7 @@ PageScroll {
UI.TextField {
id: newField
+ UI.NoPaste {}
Layout.fillWidth: true
Layout.topMargin: 6
placeholderText: "New password"
@@ -634,6 +639,7 @@ PageScroll {
UI.TextField {
id: confirmField
+ UI.NoPaste {}
Layout.fillWidth: true
placeholderText: "Confirm the new password"
revealable: true
diff --git a/packages/wildos-settings/qml/pages/SoundPage.qml b/packages/wildos-settings/qml/pages/SoundPage.qml
index 3247b67..ee023fe 100644
--- a/packages/wildos-settings/qml/pages/SoundPage.qml
+++ b/packages/wildos-settings/qml/pages/SoundPage.qml
@@ -257,7 +257,7 @@ PageScroll {
// 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
+ // runs as wildos-rdp (wildos-winmode rdp.py), so they are one stream and
// one row.
function isWindows(stream) {
const p = props(stream);
diff --git a/packages/wildos-settings/qml/pages/StoragePage.qml b/packages/wildos-settings/qml/pages/StoragePage.qml
index df7e20f..0b40ae8 100644
--- a/packages/wildos-settings/qml/pages/StoragePage.qml
+++ b/packages/wildos-settings/qml/pages/StoragePage.qml
@@ -4,25 +4,11 @@ import QtQuick.Layouts
import WildOS.Settings
import WildOS.UI as UI
-// Storage: how full each disk is and what the Recycle Bin is holding on to, with
-// the Recycle Bin emptied for real through ktrash6.
+// Storage: how full each disk is, and the way into Free up space.
PageScroll {
id: page
property var volumes: System.volumes()
- property real bin: System.binSize()
-
- function refresh() {
- volumes = System.volumes();
- bin = System.binSize();
- }
-
- Connections {
- target: System
- function onBinEmptied() {
- page.refresh();
- }
- }
Repeater {
model: page.volumes
@@ -101,20 +87,14 @@ PageScroll {
Column {
width: parent.width
+ // Everything Wild OS can clear (SettingsFreeSpace.dc), the
+ // Recycle Bin included, on a page of its own.
UI.SettingRow {
- id: binRow
iconName: "trash"
- title: "Recycle Bin"
- description: page.bin > 0
- ? System.formatBytes(page.bin) + " in files you deleted. Emptying the Recycle Bin removes them for good."
- : "The Recycle Bin is empty."
-
- UI.Button {
- anchors.verticalCenter: parent.verticalCenter
- visible: page.bin > 0
- text: "Empty Recycle Bin"
- onClicked: emptyDialog.open()
- }
+ title: "Clean up"
+ description: "Recycle Bin, old restore points, update files, app caches and more"
+ chevron: true
+ onClicked: Navigator.open("freespace")
}
UI.SettingRow {
@@ -138,24 +118,4 @@ PageScroll {
}
}
}
-
- UI.Dialog {
- id: emptyDialog
- title: "Empty the Recycle Bin?"
- text: System.formatBytes(page.bin) + " of deleted files will be removed for good. You cannot get them back."
- buttons: [
- UI.Button {
- text: "Empty Recycle Bin"
- kind: "primary"
- onClicked: {
- emptyDialog.close();
- System.emptyBin();
- }
- },
- UI.Button {
- text: "Keep files"
- onClicked: emptyDialog.close()
- }
- ]
- }
}
diff --git a/packages/wildos-settings/qml/pages/TaskbarPage.qml b/packages/wildos-settings/qml/pages/TaskbarPage.qml
index 1a98404..d088c1b 100644
--- a/packages/wildos-settings/qml/pages/TaskbarPage.qml
+++ b/packages/wildos-settings/qml/pages/TaskbarPage.qml
@@ -17,8 +17,8 @@ PageScroll {
{ mode: 2, title: "Hide it when a window covers it", description: "It stays visible until a window needs the space" }
]
- // Clock and battery choices live in wildosrc [Taskbar]; the taskbar
- // watches the file and follows straight away.
+ // Clock, battery and End task choices live in wildosrc [Taskbar]; the
+ // taskbar watches the file and follows straight away.
property int revision: 0
function taskbarOption(key) {
revision;
@@ -109,6 +109,29 @@ PageScroll {
}
}
+ // Off by default, as on Windows 11: Close window lets an app ask
+ // about unsaved work, End task does not.
+ UI.Card {
+ Layout.fillWidth: true
+
+ Column {
+ width: parent.width
+
+ UI.SettingRow {
+ title: "End task"
+ description: "Adds End task to an app's right-click menu on the taskbar, to close an app that isn't responding. Anything unsaved in it is lost."
+ status: page.taskbarOption("EndTask") ? "On" : "Off"
+
+ UI.Toggle {
+ anchors.verticalCenter: parent.verticalCenter
+ checked: page.taskbarOption("EndTask")
+ Accessible.name: "End task"
+ onToggled: page.setTaskbarOption("EndTask", checked)
+ }
+ }
+ }
+ }
+
SectionTitle {
text: "Taskbar items"
}
diff --git a/packages/wildos-settings/qml/pages/ThemesPage.qml b/packages/wildos-settings/qml/pages/ThemesPage.qml
index 85c456c..1f0fe47 100644
--- a/packages/wildos-settings/qml/pages/ThemesPage.qml
+++ b/packages/wildos-settings/qml/pages/ThemesPage.qml
@@ -254,11 +254,15 @@ PageScroll {
readonly property bool complete: /^#[0-9a-f]{6}$/.test(normalised)
error: activeFocus && text.length > 0 && !complete
onAccepted: save()
+ // Saving puts the stored colour back in the box, which would
+ // undo a paste from the text menu; the menu holds focus while
+ // it is up.
onActiveFocusChanged: {
- if (!activeFocus) {
+ if (!activeFocus && !textMenuOpen) {
save();
}
}
+ onTextMenuFocusLeft: save()
function save(): void {
if (complete) {
Themes.setUnderglowCustom(normalised);
diff --git a/packages/wildos-settings/qml/pages/UpdatePage.qml b/packages/wildos-settings/qml/pages/UpdatePage.qml
index 6a1e3f2..bc68a56 100644
--- a/packages/wildos-settings/qml/pages/UpdatePage.qml
+++ b/packages/wildos-settings/qml/pages/UpdatePage.qml
@@ -227,13 +227,16 @@ PageScroll {
: Format.plural(Updates.updates.length, "update is", "updates are") + " ready to install";
case "installed": return Updates.restartNeeded ? "Restart to finish updating" : "Updates installed";
case "uptodate": return unchecked ? "Not checked for updates yet" : "You're up to date";
- case "error": return Updates.updates.length > 0 ? "The updates were not installed" : "Wild OS could not check for updates";
+ case "error": return Updates.updates.length > 0 && !Updates.checkFailed ? "The updates were not installed" : "Wild OS could not check for updates";
default: return Updates.available ? "Updates" : "Updates are not available";
}
}
description: {
switch (Updates.state) {
case "checking":
+ if (Updates.clockWaiting)
+ return (Updates.clockBehind.length > 0 ? "The clock on this computer is at least " + Updates.clockBehind + " behind. " : "")
+ + "Wild OS is setting it through Tor, which can take a few minutes after start-up, and checks again as soon as it has.";
return Updates.waiting ? "Waiting for another install to finish first, such as the automatic security updates."
: "This can take a minute on a slow connection.";
case "installing":
@@ -277,9 +280,39 @@ PageScroll {
UI.Button {
visible: Updates.state !== "available" && Updates.state !== "installing"
enabled: Updates.available && !page.busy
- text: Updates.state === "checking" ? "Checking" : "Check now"
+ text: Updates.state === "checking" ? (Updates.clockWaiting ? "Waiting for the clock" : "Checking")
+ : Updates.state === "error" && Updates.checkFailed ? "Try again" : "Check now"
onClicked: Updates.check()
}
+
+ UI.Button {
+ visible: Updates.state === "error" && Updates.clockProblem && Pages.exists("datetime")
+ text: "Date and time"
+ onClicked: Navigator.open("datetime")
+ }
+ }
+
+ // PackageKit's error and apt's lines, for anyone helping to fix a check
+ // that failed; the card above says why in plain words.
+ UI.LinkButton {
+ id: copyDetails
+ property bool copied: false
+ Layout.leftMargin: -4
+ Layout.topMargin: -8
+ visible: Updates.state === "error" && Updates.errorDetails.length > 0
+ text: copied ? "Technical details copied" : "Copy technical details"
+ onVisibleChanged: copied = false
+ onClicked: {
+ detailsClipboard.text = Updates.errorDetails;
+ detailsClipboard.selectAll();
+ detailsClipboard.copy();
+ copied = true;
+ }
+ }
+
+ TextEdit {
+ id: detailsClipboard
+ visible: false
}
UI.ProgressBar {
diff --git a/packages/wildos-settings/qml/pages/WindowsModePage.qml b/packages/wildos-settings/qml/pages/WindowsModePage.qml
index 2ae183a..660795b 100644
--- a/packages/wildos-settings/qml/pages/WindowsModePage.qml
+++ b/packages/wildos-settings/qml/pages/WindowsModePage.qml
@@ -14,6 +14,9 @@ PageScroll {
readonly property var status: WindowsMode.status
readonly property var licence: status.licence || ({})
readonly property var options: status.options || ({})
+ // Activating with a licence on a Microsoft account, from the agent:
+ // state is starting, open, ending or "".
+ readonly property var activation: status.activation || ({ state: "" })
readonly property bool ready: WindowsMode.state === "ready"
readonly property string vm: status.vm || ""
property string message
@@ -133,7 +136,9 @@ PageScroll {
if (page.licence.source === "none") {
return edition + ", not activated";
}
- const how = page.licence.source === "key" ? "your product key ending " + (page.licence.keyEnd || "") : "this PC's built-in licence";
+ const how = page.licence.source === "key" ? "your product key ending " + (page.licence.keyEnd || "")
+ : page.licence.source === "account" ? "the licence on your Microsoft account"
+ : "this PC's built-in licence";
return edition + (page.licence.activated === true ? ", activated with " : ", to be activated with ") + how;
}
@@ -150,6 +155,21 @@ PageScroll {
}
}
+ UI.ListRow {
+ minHeight: 54
+ visible: page.licence.activated !== true || page.activation.state !== ""
+ title: "Use a licence on my Microsoft account"
+ description: page.activation.state !== ""
+ ? "Under way in the Activate Windows window."
+ : "For Windows 11 Pro activated on another PC with your Microsoft account. Microsoft may let you move it here."
+
+ UI.Button {
+ anchors.verticalCenter: parent.verticalCenter
+ text: page.activation.state !== "" ? "Show steps" : "Start"
+ onClicked: accountDialog.open()
+ }
+ }
+
UI.ListRow {
minHeight: 54
title: "When no Windows app is open"
@@ -201,7 +221,7 @@ PageScroll {
visible: Processor.threadsAvailable
title: "Use every processor thread"
description: Processor.everyThreadLocked
- ? "Off at Strict and Maximum protection."
+ ? "Off while extra processor protection is on."
: "Faster Windows apps and games. Set in Power and battery."
status: Processor.everyThread && !Processor.everyThreadLocked ? "On" : "Off"
@@ -584,6 +604,185 @@ PageScroll {
]
}
+ // Activating with a Microsoft account (wildos-winmode, activation.py):
+ // what happens before it starts, the steps while the Activate Windows
+ // window is open, and how it went. The agent keeps the state, so closing
+ // Settings part way and coming back shows the steps again.
+ UI.Dialog {
+ id: accountDialog
+ size: "large"
+ title: "Use a licence on my Microsoft account"
+ closePolicy: phase === "intro" || phase === "result" ? T.Popup.CloseOnEscape : T.Popup.NoAutoClose
+
+ // Set once Start is pressed, so the result shows instead of the
+ // introduction when the activation ends.
+ property bool started
+ property string problem
+ property string secret
+ readonly property string phase: page.activation.state === "starting" ? "starting"
+ : page.activation.state === "open" ? "open"
+ : page.activation.state === "ending" ? "ending"
+ : started && page.activation.result ? "result" : "intro"
+ readonly property var outcome: page.activation.result || ({})
+
+ text: {
+ switch (phase) {
+ case "starting":
+ return "Starting Windows and adding the account for activating. This can take a minute or two, and Windows takes a moment more to sign in to a new account the first time.";
+ case "open":
+ return "The Activate Windows window is signed in to an account made just for this. In it:";
+ case "ending":
+ return "Signing out of the account for activating and removing it.";
+ case "result":
+ if (outcome.already) {
+ return "Windows is already activated, so there's nothing to move.";
+ }
+ if (outcome.activated) {
+ return "Windows is activated. The activation belongs to Windows mode's virtual PC, so it stays now the account for activating is removed."
+ + (outcome.message ? " " + outcome.message : "");
+ }
+ return "Windows isn't activated. "
+ + (outcome.message ? outcome.message : "The account for activating is removed.")
+ + " You can try again, add a product key, or activate by phone: open the Windows desktop from Troubleshooting and run slui 4.";
+ default:
+ return "Windows mode adds a second Windows account just for this and opens the Windows desktop signed in to it, where you sign in to your Microsoft account and use Microsoft's activation troubleshooter. Afterwards Windows mode removes the account. Your own Windows account isn't changed, and Windows apps you have open leave the screen until it's done.";
+ }
+ }
+
+ onOpened: {
+ problem = "";
+ started = page.activation.state !== "";
+ secret = phase === "open" ? WindowsMode.activationPassword() : "";
+ }
+ onClosed: secret = ""
+ onPhaseChanged: secret = phase === "open" ? WindowsMode.activationPassword() : ""
+
+ Connections {
+ target: WindowsMode
+ function onAccountActivationDone(answer) {
+ accountDialog.problem = answer;
+ }
+ }
+
+ UI.Label {
+ Layout.fillWidth: true
+ visible: accountDialog.phase === "intro"
+ text: "The activation belongs to this virtual PC, so it stays after the account is removed. Microsoft only moves some licences: one that came from a free upgrade of a PC's original Windows often won't move to different hardware. If yours doesn't, a product key or activating by phone are the other ways."
+ size: 14
+ color: UI.Style.inkStatus
+ lineHeight: 1.55
+ wrapMode: Text.Wrap
+ elide: Text.ElideNone
+ }
+
+ Repeater {
+ model: accountDialog.phase === "open" ? [
+ "1. Open Settings, then Accounts, then Your info, and choose Sign in with a Microsoft account instead. When Windows asks for this account's current password, paste this one:",
+ "2. Then in Settings, open System, then Activation. Choose Troubleshoot, and when it has finished, I recently changed hardware on this device.",
+ "3. Pick this device from the list and choose Activate. If Windows asks you to set up a PIN, it goes with the account."
+ ] : []
+
+ ColumnLayout {
+ required property string modelData
+ required property int index
+ Layout.fillWidth: true
+ spacing: 8
+
+ UI.Label {
+ Layout.fillWidth: true
+ text: modelData
+ size: 14
+ lineHeight: 1.4
+ wrapMode: Text.Wrap
+ elide: Text.ElideNone
+ }
+
+ RowLayout {
+ Layout.fillWidth: true
+ visible: index === 0 && accountDialog.secret.length > 0
+ spacing: 8
+
+ UI.TextField {
+ Layout.fillWidth: true
+ text: accountDialog.secret
+ readOnly: true
+ selectByMouse: true
+ font.family: "monospace"
+ Accessible.name: "Password of the account for activating"
+ }
+
+ UI.Button {
+ text: "Copy"
+ onClicked: WindowsMode.copySecret(accountDialog.secret)
+ }
+ }
+ }
+ }
+
+ UI.Label {
+ Layout.fillWidth: true
+ visible: accountDialog.phase === "open"
+ text: "Windows mode checks every few seconds and finishes by itself once Windows says it's activated. Done or Cancel removes the account straight away."
+ size: 13
+ color: UI.Style.inkMuted
+ wrapMode: Text.Wrap
+ elide: Text.ElideNone
+ }
+
+ UI.Label {
+ Layout.fillWidth: true
+ visible: text.length > 0 && accountDialog.phase !== "result"
+ text: accountDialog.problem
+ size: 13
+ color: UI.Style.warning
+ wrapMode: Text.Wrap
+ elide: Text.ElideNone
+ Accessible.role: Accessible.AlertMessage
+ }
+
+ buttons: [
+ UI.Button {
+ visible: accountDialog.phase === "intro"
+ text: "Cancel"
+ onClicked: accountDialog.close()
+ },
+ UI.Button {
+ visible: accountDialog.phase === "intro"
+ kind: "primary"
+ text: "Open the Windows desktop"
+ onClicked: {
+ accountDialog.problem = "";
+ accountDialog.started = true;
+ WindowsMode.activateWithAccount();
+ }
+ },
+ UI.Button {
+ visible: accountDialog.phase === "open"
+ text: "Cancel"
+ onClicked: WindowsMode.endAccountActivation()
+ },
+ UI.Button {
+ visible: accountDialog.phase === "open"
+ kind: "primary"
+ text: "Done"
+ onClicked: WindowsMode.endAccountActivation()
+ },
+ UI.Button {
+ visible: accountDialog.phase === "starting" || accountDialog.phase === "ending"
+ kind: "primary"
+ text: accountDialog.phase === "starting" ? "Starting" : "Removing the account"
+ busy: true
+ enabled: false
+ },
+ UI.Button {
+ visible: accountDialog.phase === "result"
+ kind: "primary"
+ text: "Close"
+ onClicked: accountDialog.close()
+ }
+ ]
+ }
+
UI.Dialog {
id: foldersDialog
title: "Folders Windows apps can see"
diff --git a/packages/wildos-settings/src/accesscore.cpp b/packages/wildos-settings/src/accesscore.cpp
index cf6a452..755d443 100644
--- a/packages/wildos-settings/src/accesscore.cpp
+++ b/packages/wildos-settings/src/accesscore.cpp
@@ -194,6 +194,9 @@ const PointerColour pointerList[] = {
{"seaglass", "Sea glass", "#7fd6c8", "WildOS-SeaGlass"},
};
+const QString customId = QStringLiteral("custom");
+const QString customTheme = QStringLiteral("WildOS-Custom");
+
// wildos-shell's effects, by their KWin plugin ids.
const QString outlineEffect = QStringLiteral("wildos_outline");
const QString blurEffect = QStringLiteral("wildos_blurinactive");
@@ -588,9 +591,22 @@ QVariantList pointerColours()
return list;
}
+QString customPointerTheme()
+{
+ return customTheme;
+}
+
+QString customPointerDir()
+{
+ return QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QStringLiteral("/icons/") + customTheme;
+}
+
QString pointerColour()
{
const QString theme = cursorTheme();
+ if (theme == customTheme) {
+ return customId;
+ }
for (const PointerColour &p : pointerList) {
if (theme == QLatin1String(p.theme)) {
return QString::fromLatin1(p.id);
@@ -619,6 +635,9 @@ void setPointer(const QString &colourId, int size)
theme = QString::fromLatin1(p.theme);
}
}
+ if (colourId == customId && QFileInfo::exists(customPointerDir() + QStringLiteral("/index.theme"))) {
+ theme = customTheme;
+ }
KSharedConfigPtr input = fresh(QStringLiteral("kcminputrc"));
KConfigGroup mouse = input->group(QStringLiteral("Mouse"));
if (!theme.isEmpty()) {
diff --git a/packages/wildos-settings/src/accesscore.h b/packages/wildos-settings/src/accesscore.h
index 1c7f0a7..ff72367 100644
--- a/packages/wildos-settings/src/accesscore.h
+++ b/packages/wildos-settings/src/accesscore.h
@@ -69,7 +69,12 @@ void setOnScreenKeyboard(bool on, QObject *context, const std::function<void()>
// The pointer colours Settings offers, as { id, name, colour, theme }.
QVariantList pointerColours();
+// "custom" while the pointer is the account's own (customPointerTheme).
QString pointerColour();
+// The account's own pointer, made by pointer-import from a Windows pointer
+// or a picture, in ~/.local/share/icons/WildOS-Custom.
+QString customPointerTheme();
+QString customPointerDir();
int pointerSize();
QList<int> pointerSizes();
void setPointer(const QString &colourId, int size);
diff --git a/packages/wildos-settings/src/accessibility.cpp b/packages/wildos-settings/src/accessibility.cpp
index d506a71..fc4a689 100644
--- a/packages/wildos-settings/src/accessibility.cpp
+++ b/packages/wildos-settings/src/accessibility.cpp
@@ -2,11 +2,17 @@
#include "accesscore.h"
+#include <KConfig>
+#include <KConfigGroup>
#include <KSharedConfig>
#include <QDBusConnection>
+#include <QDir>
#include <QFile>
+#include <QFileInfo>
+#include <QProcess>
#include <QStandardPaths>
+#include <QTimer>
Accessibility::Accessibility(QObject *parent)
: QObject(parent)
@@ -31,6 +37,7 @@ Accessibility::Accessibility(QObject *parent)
QStringLiteral("enabledChanged"), this, SLOT(refresh()));
m_monoAudio = AccessCore::monoAudio();
+ readCustomPointer();
refresh();
refreshMagnifier();
}
@@ -96,6 +103,108 @@ void Accessibility::setPointerSize(int size)
Q_EMIT changed();
}
+void Accessibility::readCustomPointer()
+{
+ const QString dir = AccessCore::customPointerDir();
+ m_customPointer = QFileInfo::exists(dir + QStringLiteral("/index.theme"));
+ m_customPreview.clear();
+ m_customSource.clear();
+ if (m_customPointer) {
+ const KConfig index(dir + QStringLiteral("/index.theme"), KConfig::SimpleConfig);
+ const KConfigGroup group = index.group(QStringLiteral("Wild OS"));
+ m_customSource = group.readEntry("Source", QString());
+ // The stamp changes with every new pointer, so the swatch's picture
+ // is read again rather than taken from the image cache.
+ m_customPreview = QUrl::fromLocalFile(dir + QStringLiteral("/preview.png"));
+ m_customPreview.setFragment(group.readEntry("Stamp", QString()));
+ }
+ Q_EMIT customPointerChanged();
+}
+
+QString Accessibility::x11Link()
+{
+ return QDir::homePath() + QStringLiteral("/.icons/") + AccessCore::customPointerTheme();
+}
+
+// X11 apps load pointers through libXcursor, whose Debian build looks in
+// ~/.icons and /usr/share/icons but not ~/.local/share/icons, where KWin,
+// GTK and Qt on Wayland find the theme. A link puts it where both look.
+void Accessibility::linkForX11()
+{
+ const QFileInfo link(x11Link());
+ if (link.exists() || link.isSymLink()) {
+ return;
+ }
+ QDir().mkpath(link.path());
+ QFile::link(AccessCore::customPointerDir(), link.filePath());
+}
+
+void Accessibility::addPointer(const QUrl &file, qreal hotX, qreal hotY)
+{
+ if (m_pointerBusy || !file.isLocalFile()) {
+ return;
+ }
+ const QString dir = AccessCore::customPointerDir();
+ QDir().mkpath(QFileInfo(dir).path());
+ m_pointerBusy = true;
+ Q_EMIT customPointerChanged();
+
+ // A separate process reads the file, so a damaged or hostile one can at
+ // worst end that process, never Settings.
+ auto *process = new QProcess(this);
+ process->setProcessChannelMode(QProcess::ForwardedErrorChannel);
+ auto *timeout = new QTimer(process);
+ timeout->setSingleShot(true);
+ connect(timeout, &QTimer::timeout, process, &QProcess::kill);
+ connect(process, &QProcess::finished, this, [this, process](int code, QProcess::ExitStatus status) {
+ process->deleteLater();
+ m_pointerBusy = false;
+ readCustomPointer();
+ if (status == QProcess::NormalExit && code == 0) {
+ linkForX11();
+ if (m_pointerColour == QLatin1String("custom")) {
+ // KWin only reloads the pointer when its theme's name
+ // changes, so it goes through white to pick up the new one.
+ AccessCore::setPointer(QStringLiteral("white"), m_pointerSize);
+ QTimer::singleShot(400, this, [this] {
+ AccessCore::setPointer(QStringLiteral("custom"), m_pointerSize);
+ refresh();
+ });
+ } else {
+ setPointerColour(QStringLiteral("custom"));
+ }
+ } else if (status == QProcess::NormalExit && code == 1) {
+ Q_EMIT pointerFailed(QStringLiteral("Wild OS couldn't save the pointer. Check there's space left on the disk."));
+ } else {
+ Q_EMIT pointerFailed(QStringLiteral("That file isn't a pointer Wild OS can use."));
+ }
+ });
+ connect(process, &QProcess::errorOccurred, this, [this, process](QProcess::ProcessError error) {
+ if (error == QProcess::FailedToStart) {
+ process->deleteLater();
+ m_pointerBusy = false;
+ Q_EMIT customPointerChanged();
+ Q_EMIT pointerFailed(QStringLiteral("That file isn't a pointer Wild OS can use."));
+ }
+ });
+ process->start(QStringLiteral("/usr/libexec/wildos/pointer-import"),
+ {QStringLiteral("convert"), file.toLocalFile(), dir, QString::number(qBound(0.0, hotX, 1.0)), QString::number(qBound(0.0, hotY, 1.0))});
+ timeout->start(90000);
+}
+
+void Accessibility::removeCustomPointer()
+{
+ if (m_pointerColour == QLatin1String("custom")) {
+ setPointerColour(QStringLiteral("white"));
+ }
+ QDir(AccessCore::customPointerDir()).removeRecursively();
+ const QFileInfo link(x11Link());
+ if (link.isSymLink()) {
+ QFile::remove(link.filePath());
+ }
+ readCustomPointer();
+}
+
void Accessibility::setMagnifier(bool on)
{
AccessCore::setMagnifier(on);
diff --git a/packages/wildos-settings/src/accessibility.h b/packages/wildos-settings/src/accessibility.h
index d175221..1383d4f 100644
--- a/packages/wildos-settings/src/accessibility.h
+++ b/packages/wildos-settings/src/accessibility.h
@@ -4,6 +4,7 @@
#include <QObject>
#include <QQmlEngine>
+#include <QUrl>
#include <QVariantList>
// Settings > Accessibility. The values and how they are applied live in
@@ -21,6 +22,12 @@ class Accessibility : public QObject
Q_PROPERTY(QList<int> pointerSizes READ pointerSizes CONSTANT)
Q_PROPERTY(QString pointerColour READ pointerColour NOTIFY changed)
Q_PROPERTY(int pointerSize READ pointerSize NOTIFY changed)
+ // The account's own pointer: whether there is one, its picture for the
+ // swatch, the file it was made from, and whether one is being made.
+ Q_PROPERTY(bool customPointer READ customPointer NOTIFY customPointerChanged)
+ Q_PROPERTY(QUrl customPointerPreview READ customPointerPreview NOTIFY customPointerChanged)
+ Q_PROPERTY(QString customPointerSource READ customPointerSource NOTIFY customPointerChanged)
+ Q_PROPERTY(bool pointerBusy READ pointerBusy NOTIFY customPointerChanged)
Q_PROPERTY(bool magnifier READ magnifier NOTIFY magnifierChanged)
Q_PROPERTY(bool screenReaderInstalled READ screenReaderInstalled CONSTANT)
Q_PROPERTY(bool screenReader READ screenReader NOTIFY changed)
@@ -54,6 +61,10 @@ public:
QList<int> pointerSizes() const;
QString pointerColour() const { return m_pointerColour; }
int pointerSize() const { return m_pointerSize; }
+ bool customPointer() const { return m_customPointer; }
+ QUrl customPointerPreview() const { return m_customPreview; }
+ QString customPointerSource() const { return m_customSource; }
+ bool pointerBusy() const { return m_pointerBusy; }
bool magnifier() const { return m_magnifier; }
bool screenReaderInstalled() const { return m_screenReaderInstalled; }
bool screenReader() const { return m_screenReader; }
@@ -81,6 +92,11 @@ public:
Q_INVOKABLE void setPointerColour(const QString &id);
Q_INVOKABLE void setPointerSize(int size);
+ // Makes the account's own pointer from a .cur, .ani, a pointer pack
+ // (.zip or its install.inf) or a .png or .svg picture, whose hotspot is
+ // given as a fraction of its width and height, and switches to it.
+ Q_INVOKABLE void addPointer(const QUrl &file, qreal hotX = 0, qreal hotY = 0);
+ Q_INVOKABLE void removeCustomPointer();
Q_INVOKABLE void setMagnifier(bool on);
Q_INVOKABLE void setScreenReader(bool on);
Q_INVOKABLE void setHighContrast(bool on);
@@ -108,13 +124,22 @@ public Q_SLOTS:
Q_SIGNALS:
void changed();
void magnifierChanged();
+ void customPointerChanged();
+ void pointerFailed(const QString &message);
private:
void watch(const QString &file);
+ void readCustomPointer();
+ static QString x11Link();
+ static void linkForX11();
QVariantList m_pointerColours;
QString m_pointerColour;
int m_pointerSize = 24;
+ bool m_customPointer = false;
+ QUrl m_customPreview;
+ QString m_customSource;
+ bool m_pointerBusy = false;
bool m_magnifier = false;
bool m_screenReaderInstalled = false;
bool m_screenReader = false;
diff --git a/packages/wildos-settings/src/advanced.cpp b/packages/wildos-settings/src/advanced.cpp
new file mode 100644
index 0000000..e480a33
--- /dev/null
+++ b/packages/wildos-settings/src/advanced.cpp
@@ -0,0 +1,138 @@
+#include "advanced.h"
+
+#include <QDir>
+#include <QFile>
+#include <QFileInfo>
+#include <QProcess>
+
+namespace
+{
+const QString helper = QStringLiteral("/usr/libexec/wildos/settings-advanced");
+const QString storeDir = QStringLiteral("/etc/wildos");
+const QString storeFile = QStringLiteral("/etc/wildos/advanced-protection");
+const QString chosenFile = QStringLiteral("/etc/wildos/advanced-protection.chosen");
+const QString hookDir = QStringLiteral("/usr/lib/wildos/advanced-protection.d");
+
+// The board defaults, which a missing key stands for (settings-advanced
+// keeps the same list).
+const QList<QPair<QString, QString>> defaults{
+ {QStringLiteral("usb_locked"), QStringLiteral("on")},
+ {QStringLiteral("quiet_lock"), QStringLiteral("on")},
+ {QStringLiteral("fingerprint_hours"), QStringLiteral("0")},
+ {QStringLiteral("restart_locked_hours"), QStringLiteral("0")},
+ {QStringLiteral("restart_locked_force"), QStringLiteral("off")},
+ {QStringLiteral("radios_idle_off"), QStringLiteral("off")},
+ {QStringLiteral("dns"), QStringLiteral("on")},
+ {QStringLiteral("dns_strict"), QStringLiteral("off")},
+ {QStringLiteral("dns_provider"), QStringLiteral("quad9")},
+ {QStringLiteral("vpn_only"), QStringLiteral("off")},
+ {QStringLiteral("clipboard_forget"), QStringLiteral("on")},
+ {QStringLiteral("presenting"), QStringLiteral("on")},
+ {QStringLiteral("scrub_files"), QStringLiteral("on")},
+ {QStringLiteral("usb_encrypt"), QStringLiteral("on")},
+ {QStringLiteral("guest"), QStringLiteral("off")},
+ {QStringLiteral("safebox"), QStringLiteral("on")},
+ {QStringLiteral("panic_key"), QStringLiteral("off")},
+};
+
+QStringList readLines(const QString &path)
+{
+ QFile file(path);
+ if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
+ return {};
+ }
+ return QString::fromUtf8(file.readAll()).split(QLatin1Char('\n'), Qt::SkipEmptyParts);
+}
+}
+
+Advanced::Advanced(QObject *parent)
+ : QObject(parent)
+{
+ // The helper writes the store, then the chosen list.
+ m_settle.setSingleShot(true);
+ m_settle.setInterval(150);
+ connect(&m_settle, &QTimer::timeout, this, &Advanced::refresh);
+ connect(&m_watcher, &QFileSystemWatcher::directoryChanged, &m_settle, qOverload<>(&QTimer::start));
+ refresh();
+}
+
+bool Advanced::available() const
+{
+ return QFileInfo(helper).isExecutable();
+}
+
+void Advanced::refresh()
+{
+ QHash<QString, QString> stored;
+ for (const QString &line : readLines(storeFile)) {
+ const qsizetype equals = line.indexOf(QLatin1Char('='));
+ if (equals > 0 && !line.startsWith(QLatin1Char('#'))) {
+ stored.insert(line.left(equals).trimmed(), line.mid(equals + 1).trimmed());
+ }
+ }
+ QVariantMap values;
+ QVariantMap installed;
+ for (const auto &[key, fallback] : defaults) {
+ const QString value = stored.value(key, fallback);
+ bool number = false;
+ const int hours = value.toInt(&number);
+ values.insert(key, key.endsWith(QLatin1String("_hours")) ? QVariant(number ? hours : fallback.toInt()) : QVariant(value));
+ installed.insert(key, QFileInfo(hookDir + QLatin1Char('/') + key).isExecutable());
+ }
+ QStringList chosen;
+ for (const QString &line : readLines(chosenFile)) {
+ chosen.append(line.trimmed());
+ }
+
+ for (const QString &dir : {storeDir, hookDir}) {
+ if (QFileInfo::exists(dir) && !m_watcher.directories().contains(dir)) {
+ m_watcher.addPath(dir);
+ }
+ }
+ if (values != m_values || chosen != m_chosen || installed != m_installed) {
+ m_values = values;
+ m_chosen = chosen;
+ m_installed = installed;
+ Q_EMIT changed();
+ }
+}
+
+void Advanced::run(const QStringList &args, const QString &key)
+{
+ if (m_process) {
+ return;
+ }
+ m_busyKey = key;
+ m_process = new QProcess(this);
+ m_process->setProcessChannelMode(QProcess::MergedChannels);
+ connect(m_process, &QProcess::finished, this, [this, key](int code, QProcess::ExitStatus status) {
+ m_process->deleteLater();
+ m_process = nullptr;
+ m_busyKey.clear();
+ Q_EMIT busyChanged();
+ refresh();
+ if (status == QProcess::NormalExit && code == 0) {
+ Q_EMIT done(key);
+ } else if (status != QProcess::NormalExit || (code != 126 && code != 127)) {
+ // 126 and 127: the password prompt was dismissed, which needs no
+ // message. The switch goes back to the store's value.
+ Q_EMIT failed(key, QStringLiteral("Something went wrong. Nothing was changed."));
+ }
+ // A switch flipped by hand has lost its binding; changed() puts
+ // every row back to what the store says.
+ Q_EMIT changed();
+ });
+ Q_EMIT busyChanged();
+ m_process->start(QStringLiteral("pkexec"), QStringList{helper} + args);
+}
+
+void Advanced::set(const QString &key, const QVariant &value)
+{
+ QString text = value.typeId() == QMetaType::Bool ? (value.toBool() ? QStringLiteral("on") : QStringLiteral("off")) : value.toString();
+ run({QStringLiteral("set"), key, text}, key);
+}
+
+void Advanced::reset()
+{
+ run({QStringLiteral("reset")}, QStringLiteral("reset"));
+}
diff --git a/packages/wildos-settings/src/advanced.h b/packages/wildos-settings/src/advanced.h
new file mode 100644
index 0000000..a383016
--- /dev/null
+++ b/packages/wildos-settings/src/advanced.h
@@ -0,0 +1,70 @@
+#pragma once
+
+#include <QFileSystemWatcher>
+#include <QObject>
+#include <QQmlEngine>
+#include <QStringList>
+#include <QTimer>
+#include <QVariantMap>
+
+class QProcess;
+
+// Settings > Privacy and security > Advanced protection. Reads the store the
+// root helper settings-advanced keeps (/etc/wildos/advanced-protection,
+// world-readable, a missing key meaning its default) and the list of keys
+// set by hand; asks for every change through the helper, behind the admin
+// password. Each change runs that key's hook in
+// /usr/lib/wildos/advanced-protection.d, and a hook being installed is how
+// the page knows the part of Wild OS that carries a choice out is there.
+class Advanced : public QObject
+{
+ Q_OBJECT
+ QML_ELEMENT
+ QML_SINGLETON
+
+ Q_PROPERTY(bool available READ available CONSTANT)
+ // Every key, with its value now: "on"/"off", hours as a number, or
+ // dns_provider "quad9", "mullvad", "cloudflare".
+ Q_PROPERTY(QVariantMap values READ values NOTIFY changed)
+ // Keys set by hand, which no protection level changes.
+ Q_PROPERTY(QStringList chosen READ chosen NOTIFY changed)
+ // Key to true where its hook is installed.
+ Q_PROPERTY(QVariantMap installed READ installed NOTIFY changed)
+ Q_PROPERTY(bool busy READ busy NOTIFY busyChanged)
+ // The key being changed, or "reset".
+ Q_PROPERTY(QString busyKey READ busyKey NOTIFY busyChanged)
+
+public:
+ explicit Advanced(QObject *parent = nullptr);
+
+ bool available() const;
+ QVariantMap values() const { return m_values; }
+ QStringList chosen() const { return m_chosen; }
+ QVariantMap installed() const { return m_installed; }
+ bool busy() const { return m_process != nullptr; }
+ QString busyKey() const { return m_busyKey; }
+
+ Q_INVOKABLE void refresh();
+ Q_INVOKABLE void set(const QString &key, const QVariant &value);
+ // Back to the defaults, forgetting what was set by hand.
+ Q_INVOKABLE void reset();
+
+Q_SIGNALS:
+ void changed();
+ void busyChanged();
+ // A change did not happen; the reason, in words.
+ void failed(const QString &key, const QString &message);
+ // A change went through.
+ void done(const QString &key);
+
+private:
+ void run(const QStringList &args, const QString &key);
+
+ QFileSystemWatcher m_watcher;
+ QTimer m_settle;
+ QProcess *m_process = nullptr;
+ QString m_busyKey;
+ QVariantMap m_values;
+ QStringList m_chosen;
+ QVariantMap m_installed;
+};
diff --git a/packages/wildos-settings/src/appsmodel.cpp b/packages/wildos-settings/src/appsmodel.cpp
index cfa50d2..b777a31 100644
--- a/packages/wildos-settings/src/appsmodel.cpp
+++ b/packages/wildos-settings/src/appsmodel.cpp
@@ -2,21 +2,123 @@
#include <KApplicationTrader>
#include <KService>
+#include <KShell>
#include <PackageKit/Daemon>
#include <QCollator>
+#include <algorithm>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QProcess>
#include <QRegularExpression>
+#include <QStandardPaths>
+#include <QDirIterator>
+#include <QDBusConnection>
+#include <QDBusMessage>
+#include <QDBusPendingCallWatcher>
+#include <QDBusPendingReply>
+#include <QJsonDocument>
+#include <QJsonObject>
using PackageKit::Daemon;
using PackageKit::Transaction;
namespace
{
+QString homePath()
+{
+ static const QString home = QDir(QDir::homePath()).canonicalPath();
+ return home;
+}
+
+bool insideHome(const QString &path)
+{
+ return !path.isEmpty() && path.startsWith(homePath() + QLatin1Char('/'));
+}
+
+// Folders that hold many apps' files. One of them is never removed whole,
+// only the app's own folder or file inside it.
+QStringList sharedRoots()
+{
+ const QString h = homePath();
+ return {h,
+ h + QStringLiteral("/.local"),
+ h + QStringLiteral("/.local/bin"),
+ h + QStringLiteral("/.local/share"),
+ h + QStringLiteral("/.local/state"),
+ h + QStringLiteral("/.local/lib"),
+ h + QStringLiteral("/.local/opt"),
+ h + QStringLiteral("/.config"),
+ h + QStringLiteral("/.cache"),
+ h + QStringLiteral("/opt"),
+ h + QStringLiteral("/Applications"),
+ h + QStringLiteral("/bin")};
+}
+
+// Names under ~/.local/share and ~/.config that belong to the desktop or to
+// many apps, never to the one being removed.
+const QStringList sharedNames = {QStringLiteral("applications"), QStringLiteral("icons"), QStringLiteral("pixmaps"), QStringLiteral("flatpak"),
+ QStringLiteral("Trash"), QStringLiteral("fonts"), QStringLiteral("mime"), QStringLiteral("themes"),
+ QStringLiteral("kservices6"), QStringLiteral("plasma"), QStringLiteral("dbus-1"), QStringLiteral("systemd"),
+ QStringLiteral("autostart"), QStringLiteral("wildos"), QStringLiteral("kde"), QStringLiteral("gtk-3.0"),
+ QStringLiteral("gtk-4.0"), QStringLiteral("recently-used.xbel"), QStringLiteral("user-places.xbel")};
+
+// The program a launcher starts, past "env" and its VAR=value settings.
+QString launcherProgram(const QString &exec)
+{
+ const QStringList words = KShell::splitArgs(exec);
+ int i = 0;
+ if (i < words.size() && QFileInfo(words.at(i)).fileName() == QLatin1String("env")) {
+ ++i;
+ while (i < words.size() && (words.at(i).contains(QLatin1Char('=')) || words.at(i).startsWith(QLatin1Char('-')))) {
+ ++i;
+ }
+ }
+ if (i >= words.size()) {
+ return {};
+ }
+ const QString program = words.at(i);
+ return program.contains(QLatin1Char('/')) ? program : QStandardPaths::findExecutable(program);
+}
+
+// The app's own folder or file directly inside one of the shared folders,
+// for a path somewhere within it.
+QString ownTopLevel(const QString &path)
+{
+ const QStringList roots = {homePath() + QStringLiteral("/.local/share"), homePath() + QStringLiteral("/.local/opt"),
+ homePath() + QStringLiteral("/.local/lib"), homePath() + QStringLiteral("/opt"),
+ homePath() + QStringLiteral("/Applications"), homePath() + QStringLiteral("/.local/bin"),
+ homePath() + QStringLiteral("/bin")};
+ for (const QString &root : roots) {
+ if (path.startsWith(root + QLatin1Char('/'))) {
+ const QString first = path.mid(root.size() + 1).section(QLatin1Char('/'), 0, 0);
+ if (first.isEmpty() || sharedNames.contains(first)) {
+ return {};
+ }
+ return root + QLatin1Char('/') + first;
+ }
+ }
+ return {};
+}
+
+void addPath(QStringList &list, const QString &path)
+{
+ if (!insideHome(path) || sharedRoots().contains(path) || list.contains(path)) {
+ return;
+ }
+ const QFileInfo info(path);
+ if (info.exists() || info.isSymLink()) {
+ list << path;
+ }
+}
+
+QString displayPath(const QString &path)
+{
+ return QStringLiteral("~") + path.mid(homePath().size());
+}
+
// Packages that make up the desktop itself. Removing any of them would take
// Wild OS apart, whatever the dependency tree allows.
const QStringList coreMetapackages = {QStringLiteral("wildos-desktop"), QStringLiteral("wildos-base"), QStringLiteral("wildos-branding")};
@@ -59,12 +161,24 @@ AppsModel::AppsModel(QObject *parent)
// so installs failed with "needs the administrator password" and no
// prompt ever appeared.
PackageKit::Daemon::global()->setHints(QStringList{QStringLiteral("interactive=true")});
+ m_reloadSoon.setSingleShot(true);
+ m_reloadSoon.setInterval(1500);
+ connect(&m_reloadSoon, &QTimer::timeout, this, &AppsModel::reload);
+ const QString launchers = homePath() + QStringLiteral("/.local/share/applications");
+ if (QFileInfo::exists(launchers)) {
+ m_launchers.addPath(launchers);
+ }
+ connect(&m_launchers, &QFileSystemWatcher::directoryChanged, &m_reloadSoon, qOverload<>(&QTimer::start));
reload();
}
QHash<QString, QString> AppsModel::desktopOwners() const
{
QHash<QString, QString> owners;
+ // A Wild OS package that ships a launcher whole under a stock app's id
+ // (Write is libreoffice-writer.desktop) owns that app, not the stock
+ // package whose launcher it stands in for.
+ QHash<QString, QString> shipped;
QDir info(QStringLiteral("/var/lib/dpkg/info"));
const auto lists = info.entryList({QStringLiteral("*.list")}, QDir::Files);
for (const QString &list : lists) {
@@ -77,9 +191,12 @@ QHash<QString, QString> AppsModel::desktopOwners() const
const QByteArray line = file.readLine().trimmed();
if (line.startsWith("/usr/share/applications/") && line.endsWith(".desktop")) {
owners.insert(QFileInfo(QString::fromUtf8(line)).fileName(), package);
+ } else if (line.startsWith("/usr/share/wildos/launchers/") && line.endsWith(".desktop")) {
+ shipped.insert(QFileInfo(QString::fromUtf8(line)).fileName(), package);
}
}
}
+ owners.insert(shipped);
return owners;
}
@@ -111,7 +228,8 @@ void AppsModel::reload()
});
for (const KService::Ptr &service : services) {
const QString id = service->desktopEntryName();
- if (seen.contains(id) || service->name().isEmpty()) {
+ // Just uninstalled: the launcher is gone before the menu cache knows.
+ if (seen.contains(id) || service->name().isEmpty() || !QFileInfo::exists(service->entryPath())) {
continue;
}
seen.insert(id);
@@ -122,7 +240,22 @@ void AppsModel::reload()
app.flatpak = service->property<QString>(QStringLiteral("X-Flatpak"));
app.userFlatpak = service->entryPath().contains(QLatin1String("/.local/share/flatpak/"));
app.package = owners.value(QFileInfo(service->entryPath()).fileName());
- app.protectedApp = app.flatpak.isEmpty() && (app.package.isEmpty() || core.contains(app.package) || app.package.startsWith(QLatin1String("wildos-")));
+ // Wild OS's own apps are only recommended by the desktop, so they
+ // can go; what the desktop depends on cannot.
+ app.protectedApp = app.flatpak.isEmpty() && (app.package.isEmpty() || core.contains(app.package));
+ // A launcher in the home folder for a program in the home folder,
+ // put there by the app's own installer. Windows mode writes its
+ // apps' launchers there too.
+ const QString entry = QFileInfo(service->entryPath()).canonicalFilePath();
+ if (id.startsWith(QLatin1String("wildos-winmode-")) && service->property<QString>(QStringLiteral("X-WildOS-Engine")) == QLatin1String("windows-mode")) {
+ app.windowsApp = true;
+ app.protectedApp = false;
+ } else if (app.flatpak.isEmpty() && app.package.isEmpty() && !id.startsWith(QLatin1String("wildos-"))
+ && entry.startsWith(homePath() + QStringLiteral("/.local/share/applications/"))) {
+ findHomeFiles(app, entry, service->exec(), service->icon());
+ app.homeApp = !app.files.isEmpty();
+ app.protectedApp = !app.homeApp;
+ }
apps << app;
}
@@ -132,10 +265,154 @@ void AppsModel::reload()
return collator.compare(a.name, b.name) < 0;
});
+ // Two launchers can share a folder or a maker's prefix (an app suite).
+ // A file more than one of them would take stays, so removing one never
+ // breaks the other; only each launcher's own files go with it.
+ QHash<QString, int> claims;
+ for (const App &app : std::as_const(apps)) {
+ for (const QString &path : app.files) {
+ claims[path] += 1;
+ }
+ }
+ for (App &app : apps) {
+ app.files.erase(std::remove_if(app.files.begin(), app.files.end(),
+ [&claims](const QString &path) {
+ return claims.value(path) > 1;
+ }),
+ app.files.end());
+ }
+
m_all = apps;
applyFilter();
}
+void AppsModel::findHomeFiles(App &app, const QString &entryPath, const QString &exec, const QString &icon)
+{
+ const QString program = launcherProgram(exec);
+ const QString target = QFileInfo(program).canonicalFilePath();
+ if (!insideHome(target)) {
+ return;
+ }
+ // A program outside the folders apps install into (a build in someone's
+ // projects folder) stays; only its launcher goes.
+ // The app's own folder holds the program (or is it, for an AppImage or a
+ // single file in ~/.local/bin), so the program is not listed twice.
+ QStringList files;
+ files << entryPath;
+ const QString folder = ownTopLevel(target);
+ addPath(files, folder);
+ // The program as the launcher names it, often a link in ~/.local/bin.
+ addPath(files, ownTopLevel(QFileInfo(program).absoluteFilePath()));
+
+ // Names the app's files go by: the launcher's, the program's and its
+ // folder's, and the maker's prefix ("herdr" for herdr-app) for the other
+ // programs an installer drops beside it.
+ QSet<QString> names = {QFileInfo(entryPath).completeBaseName(), QFileInfo(program).fileName(), QFileInfo(target).fileName()};
+ if (!folder.isEmpty()) {
+ names.insert(QFileInfo(folder).fileName());
+ }
+ const QString prefix = QFileInfo(entryPath).completeBaseName().section(QRegularExpression(QStringLiteral("[-_.]")), 0, 0);
+ for (const QString &bin : {homePath() + QStringLiteral("/.local/bin"), homePath() + QStringLiteral("/bin")}) {
+ const auto entries = QDir(bin).entryInfoList(QDir::Files | QDir::System | QDir::NoDotAndDotDot);
+ for (const QFileInfo &info : entries) {
+ const QString name = info.fileName();
+ const bool samePrefix = prefix.size() >= 4 && (name == prefix || name.startsWith(prefix + QLatin1Char('-')));
+ const QString points = info.isSymLink() ? info.canonicalFilePath() : QString();
+ const bool intoFolder = !folder.isEmpty() && points.startsWith(folder + QLatin1Char('/'));
+ if (samePrefix || intoFolder) {
+ addPath(files, info.absoluteFilePath());
+ names.insert(name);
+ }
+ }
+ }
+
+ if (QFileInfo(icon).isAbsolute()) {
+ addPath(files, QFileInfo(icon).canonicalFilePath());
+ } else if (!icon.isEmpty()) {
+ for (const QString &dir : {homePath() + QStringLiteral("/.local/share/icons"), homePath() + QStringLiteral("/.local/share/pixmaps")}) {
+ QDirIterator it(dir, {icon + QStringLiteral(".svg"), icon + QStringLiteral(".svgz"), icon + QStringLiteral(".png"), icon + QStringLiteral(".xpm")},
+ QDir::Files, QDirIterator::Subdirectories);
+ while (it.hasNext()) {
+ addPath(files, it.next());
+ }
+ }
+ }
+
+ // Settings and data in the usual places under the same names, offered
+ // separately: someone reinstalling may want to keep them.
+ QStringList data;
+ for (const QString &name : std::as_const(names)) {
+ if (name.isEmpty() || sharedNames.contains(name)) {
+ continue;
+ }
+ for (const QString &base : {QStringLiteral("/.config/"), QStringLiteral("/.local/share/"), QStringLiteral("/.local/state/"), QStringLiteral("/.cache/")}) {
+ const QString path = homePath() + base + name;
+ if (!files.contains(path)) {
+ addPath(data, path);
+ }
+ }
+ }
+ data.sort();
+ app.files = files;
+ app.data = data;
+}
+
+QString AppsModel::nameOf(const QString &id) const
+{
+ for (const App &app : m_all) {
+ if (app.id == id || app.id + QStringLiteral(".desktop") == id) {
+ return app.name;
+ }
+ }
+ return {};
+}
+
+bool AppsModel::canUninstall(const QString &id) const
+{
+ for (const App &app : m_all) {
+ if (app.id == id || app.id + QStringLiteral(".desktop") == id) {
+ return !app.protectedApp;
+ }
+ }
+ return false;
+}
+
+bool AppsModel::isWindowsApp(const QString &id) const
+{
+ for (const App &app : m_all) {
+ if (app.id == id || app.id + QStringLiteral(".desktop") == id) {
+ return app.windowsApp;
+ }
+ }
+ return false;
+}
+
+QStringList AppsModel::homeFiles(const QString &id) const
+{
+ QStringList shown;
+ for (const App &app : m_all) {
+ if (app.id == id && app.homeApp) {
+ for (const QString &path : app.files) {
+ shown << displayPath(path);
+ }
+ }
+ }
+ return shown;
+}
+
+QStringList AppsModel::homeData(const QString &id) const
+{
+ QStringList shown;
+ for (const App &app : m_all) {
+ if (app.id == id && app.homeApp) {
+ for (const QString &path : app.data) {
+ shown << displayPath(path);
+ }
+ }
+ }
+ return shown;
+}
+
void AppsModel::setFilter(const QString &filter)
{
if (filter == m_filter) {
@@ -179,7 +456,7 @@ QVariant AppsModel::data(const QModelIndex &index, int role) const
case IdRole:
return app.id;
case SourceRole:
- return app.flatpak.isEmpty() ? QStringLiteral("system") : QStringLiteral("store");
+ return app.windowsApp ? QStringLiteral("windows") : app.homeApp ? QStringLiteral("home") : app.flatpak.isEmpty() ? QStringLiteral("system") : QStringLiteral("store");
case PackageRole:
return app.flatpak.isEmpty() ? app.package : app.flatpak;
case CanUninstallRole:
@@ -200,7 +477,7 @@ QHash<int, QByteArray> AppsModel::roleNames() const
};
}
-void AppsModel::uninstall(const QString &id)
+void AppsModel::uninstall(const QString &id, bool withData)
{
if (!m_busyId.isEmpty()) {
return;
@@ -215,6 +492,35 @@ void AppsModel::uninstall(const QString &id)
m_busyId = id;
Q_EMIT busyChanged();
+ if (app.windowsApp) {
+ uninstallWindowsApp(app);
+ return;
+ }
+
+ // Everything goes to the Trash, so a file that was not the app's after
+ // all can be put back. Each path is checked again: it must still be
+ // inside the home folder and not one of the shared folders.
+ if (app.homeApp) {
+ QStringList paths = app.files;
+ if (withData) {
+ paths << app.data;
+ }
+ QStringList stuck;
+ for (const QString &path : std::as_const(paths)) {
+ const QFileInfo info(path);
+ if (!insideHome(path) || sharedRoots().contains(path) || (!info.exists() && !info.isSymLink())) {
+ continue;
+ }
+ // A link holds nothing to put back, and once its target is in the
+ // Trash it points nowhere and cannot be moved there itself.
+ if (info.isSymLink() ? !QFile::remove(path) : !QFile::moveToTrash(path)) {
+ stuck << displayPath(path);
+ }
+ }
+ finishUninstall(app, stuck.isEmpty(), stuck.isEmpty() ? QString() : QStringLiteral("These could not be moved to the Recycle Bin: ") + stuck.join(QStringLiteral(", ")));
+ return;
+ }
+
if (!app.flatpak.isEmpty()) {
auto process = new QProcess(this);
connect(process, &QProcess::finished, this, [this, process, app](int code, QProcess::ExitStatus) {
@@ -252,6 +558,33 @@ void AppsModel::uninstall(const QString &id)
});
}
+// Windows mode may have to start Windows first, so the call is given as
+// long as a cold start and Windows finding the uninstaller take.
+void AppsModel::uninstallWindowsApp(const App &app)
+{
+ QDBusMessage call = QDBusMessage::createMethodCall(QStringLiteral("org.wildos.WindowsMode1"), QStringLiteral("/org/wildos/WindowsMode1"),
+ QStringLiteral("org.wildos.WindowsMode1"), QStringLiteral("UninstallApp"));
+ call << app.id.mid(QStringLiteral("wildos-winmode-").size());
+ auto *watcher = new QDBusPendingCallWatcher(QDBusConnection::sessionBus().asyncCall(call, 600000), this);
+ connect(watcher, &QDBusPendingCallWatcher::finished, this, [this, watcher, app] {
+ watcher->deleteLater();
+ const QDBusPendingReply<QString> reply = *watcher;
+ if (reply.isError()) {
+ finishUninstall(app, false, QStringLiteral("Windows mode didn't answer. Restart the PC, then try again."));
+ return;
+ }
+ const QJsonObject answer = QJsonDocument::fromJson(reply.value().toUtf8()).object();
+ const QString state = answer.value(QStringLiteral("state")).toString();
+ if (state == QLatin1String("opened")) {
+ m_busyId.clear();
+ Q_EMIT busyChanged();
+ Q_EMIT uninstallOpened(app.name);
+ return;
+ }
+ finishUninstall(app, state == QLatin1String("removed"), answer.value(QStringLiteral("message")).toString());
+ });
+}
+
void AppsModel::finishUninstall(const App &app, bool ok, const QString &reason)
{
m_busyId.clear();
diff --git a/packages/wildos-settings/src/appsmodel.h b/packages/wildos-settings/src/appsmodel.h
index df85f33..254ddbb 100644
--- a/packages/wildos-settings/src/appsmodel.h
+++ b/packages/wildos-settings/src/appsmodel.h
@@ -1,12 +1,15 @@
#pragma once
#include <QAbstractListModel>
+#include <QFileSystemWatcher>
+#include <QTimer>
#include <QQmlEngine>
#include <QSet>
// The apps someone can see in Start, with where each came from and whether
-// removing it is safe. Wild OS's own apps are protected, the same way
-// Windows does not offer to uninstall Settings.
+// removing it is safe. What the desktop depends on (Settings, the Store,
+// Files) is protected, the same way Windows does not offer to uninstall
+// Settings.
class AppsModel : public QAbstractListModel
{
Q_OBJECT
@@ -37,7 +40,16 @@ public:
QString busyId() const { return m_busyId; }
Q_INVOKABLE void reload();
- Q_INVOKABLE void uninstall(const QString &id);
+ // withData also takes the app's settings and data, for apps in the home
+ // folder; packages and Store apps leave them anyway.
+ Q_INVOKABLE void uninstall(const QString &id, bool withData = false);
+ // What Uninstall would move to the Trash for an app in the home folder,
+ // as ~/ paths, so the dialog can show it before anything goes.
+ Q_INVOKABLE QStringList homeFiles(const QString &id) const;
+ Q_INVOKABLE QStringList homeData(const QString &id) const;
+ Q_INVOKABLE QString nameOf(const QString &id) const;
+ Q_INVOKABLE bool isWindowsApp(const QString &id) const;
+ Q_INVOKABLE bool canUninstall(const QString &id) const;
Q_SIGNALS:
void filterChanged();
@@ -45,6 +57,9 @@ Q_SIGNALS:
void busyChanged();
void uninstalled(const QString &name);
void uninstallFailed(const QString &name, const QString &reason);
+ // A Windows app's own uninstaller is open in its window; the app leaves
+ // the list once that finishes.
+ void uninstallOpened(const QString &name);
private:
struct App {
@@ -55,10 +70,21 @@ private:
bool userFlatpak = false;
QString package;
bool protectedApp = false;
+ // Installed by its own script or as an AppImage into the home
+ // folder, so it belongs to no package: its files are moved to the
+ // Trash instead.
+ bool homeApp = false;
+ // Runs in Windows mode: Windows itself uninstalls it.
+ bool windowsApp = false;
+ QStringList files;
+ QStringList data;
};
+ static void findHomeFiles(App &app, const QString &entryPath, const QString &exec, const QString &icon);
+
void applyFilter();
void finishUninstall(const App &app, bool ok, const QString &reason);
+ void uninstallWindowsApp(const App &app);
QHash<QString, QString> desktopOwners() const;
QSet<QString> protectedPackages() const;
@@ -66,4 +92,7 @@ private:
QList<App> m_shown;
QString m_filter;
QString m_busyId;
+ // Windows mode writes and removes its apps' launchers there.
+ QFileSystemWatcher m_launchers;
+ QTimer m_reloadSoon;
};
diff --git a/packages/wildos-settings/src/clock.cpp b/packages/wildos-settings/src/clock.cpp
index 6468d7b..6a8b68a 100644
--- a/packages/wildos-settings/src/clock.cpp
+++ b/packages/wildos-settings/src/clock.cpp
@@ -6,8 +6,11 @@
#include <QDBusPendingCallWatcher>
#include <QDBusPendingReply>
#include <QDBusVariant>
+#include <QFileSystemWatcher>
#include <QTimeZone>
+#include "securetime.h"
+
#include <algorithm>
namespace
@@ -29,6 +32,13 @@ QString offsetText(int seconds)
Clock::Clock(QObject *parent)
: QObject(parent)
{
+ readSecureTime();
+ // sdwdate's marker for having set the clock appears in this folder, so
+ // the page changes from "being set" to "set" as it happens.
+ auto watch = new QFileSystemWatcher({QStringLiteral("/run/sdwdate")}, this);
+ connect(watch, &QFileSystemWatcher::directoryChanged, this, [this] {
+ readSecureTime();
+ });
QDBusConnection bus = QDBusConnection::systemBus();
auto names = bus.interface();
// timedated starts on demand, so it counts as there when it can start.
@@ -42,6 +52,17 @@ Clock::Clock(QObject *parent)
read();
}
+void Clock::readSecureTime()
+{
+ const bool running = SecureTime::running();
+ const bool set = SecureTime::setThisBoot();
+ if (running != m_secureTime || set != m_secureTimeSet) {
+ m_secureTime = running;
+ m_secureTimeSet = set;
+ Q_EMIT changed();
+ }
+}
+
void Clock::read()
{
auto message = QDBusMessage::createMethodCall(service, path, QStringLiteral("org.freedesktop.DBus.Properties"), QStringLiteral("GetAll"));
diff --git a/packages/wildos-settings/src/clock.h b/packages/wildos-settings/src/clock.h
index 2dc7f87..36dcbdb 100644
--- a/packages/wildos-settings/src/clock.h
+++ b/packages/wildos-settings/src/clock.h
@@ -19,6 +19,11 @@ class Clock : public QObject
Q_PROPERTY(bool automatic READ automatic NOTIFY changed)
Q_PROPERTY(bool canAutomatic READ canAutomatic NOTIFY changed)
Q_PROPERTY(bool synchronised READ synchronised NOTIFY changed)
+ // sdwdate sets the clock through Tor; timedated does not know it, so
+ // automatic says off while it runs.
+ Q_PROPERTY(bool secureTime READ secureTime NOTIFY changed)
+ // sdwdate has set the clock since this start-up.
+ Q_PROPERTY(bool secureTimeSet READ secureTimeSet NOTIFY changed)
public:
explicit Clock(QObject *parent = nullptr);
@@ -28,6 +33,8 @@ public:
bool automatic() const { return m_automatic; }
bool canAutomatic() const { return m_canAutomatic; }
bool synchronised() const { return m_synchronised; }
+ bool secureTime() const { return m_secureTime; }
+ bool secureTimeSet() const { return m_secureTimeSet; }
// Every zone as { value: "Europe/London", text: "(UTC+00:00) London, Europe" },
// in order of offset as Windows lists them.
@@ -46,6 +53,7 @@ private Q_SLOTS:
private:
void read();
+ void readSecureTime();
void call(const QString &method, const QVariantList &arguments);
bool m_available = false;
@@ -53,4 +61,6 @@ private:
bool m_automatic = false;
bool m_canAutomatic = false;
bool m_synchronised = false;
+ bool m_secureTime = false;
+ bool m_secureTimeSet = false;
};
diff --git a/packages/wildos-settings/src/devices.cpp b/packages/wildos-settings/src/devices.cpp
new file mode 100644
index 0000000..7629975
--- /dev/null
+++ b/packages/wildos-settings/src/devices.cpp
@@ -0,0 +1,1380 @@
+#include "devices.h"
+
+#include <QCoreApplication>
+#include <QDBusArgument>
+#include <QDBusConnection>
+#include <QDBusMessage>
+#include <QDBusMetaType>
+#include <QDBusObjectPath>
+#include <QDBusVariant>
+#include <QDir>
+#include <QElapsedTimer>
+#include <QFile>
+#include <QFileInfo>
+#include <QHash>
+#include <QJsonArray>
+#include <QJsonDocument>
+#include <QJsonObject>
+#include <QLocalSocket>
+#include <QLocale>
+#include <QPointer>
+#include <QProcess>
+#include <QRegularExpression>
+#include <QSet>
+#include <QStandardPaths>
+#include <QThread>
+#include <QTimer>
+
+#include <libudev.h>
+#include <sys/stat.h>
+#include <sys/statvfs.h>
+#include <sys/sysmacros.h>
+
+#include <algorithm>
+#include <functional>
+
+using ManagedObjects = QMap<QDBusObjectPath, QMap<QString, QVariantMap>>;
+Q_DECLARE_METATYPE(ManagedObjects)
+
+namespace
+{
+const QString socketPath = QStringLiteral("/run/wildos-devices.sock");
+// What the shield's "Allow once" runs for a device USB protection blocked.
+const QString allowHelper = QStringLiteral("/usr/libexec/wildos/usb-devices");
+
+// The order the page lists devices in: what people look for first.
+const QStringList kindOrder = {
+ QStringLiteral("graphics"), QStringLiteral("wifi"), QStringLiteral("ethernet"), QStringLiteral("bluetooth"),
+ QStringLiteral("sound"), QStringLiteral("camera"), QStringLiteral("fingerprint"), QStringLiteral("storage"),
+ QStringLiteral("touchpad"), QStringLiteral("keyboard"), QStringLiteral("keyboardmouse"), QStringLiteral("mouse"),
+ QStringLiteral("touchscreen"), QStringLiteral("pen"), QStringLiteral("controller"), QStringLiteral("battery"),
+ QStringLiteral("printer"), QStringLiteral("scanner"), QStringLiteral("smartcard"), QStringLiteral("usbdrive"),
+ QStringLiteral("card"), QStringLiteral("hdmisound"), QStringLiteral("cardreader"), QStringLiteral("usb"),
+ QStringLiteral("usbctl"), QStringLiteral("storagectl"), QStringLiteral("firewire"),
+};
+
+struct Dev {
+ QString key;
+ QString kind;
+ QString name;
+ QString icon;
+ QString line;
+ QString state = QStringLiteral("ok");
+ QString badge;
+ QString problem;
+ QString action;
+ QString actionLabel;
+ QString model;
+ QString maker;
+ QString driver;
+ QString connection;
+ QString hardwareId;
+ QVariantList extra;
+ // How it is attached: "pci", "usb", "builtin" (serio, i2c, platform),
+ // "bluetooth".
+ QString bus;
+ QString vendorId;
+ QString productId;
+ // The device, or the USB interface, that wants a driver and has none.
+ QString unboundPath;
+ bool virtualHardware = false;
+ // Ahead of others of its kind: the drive Wild OS runs from.
+ bool first = false;
+ bool builtIn = false;
+ // Interfaces of a USB device that should have a driver and have none.
+ bool unboundInterface = false;
+ // Its job's output (a network adapter, a sound card...) is missing.
+ bool functionMissing = false;
+ // Every bound driver name, for a USB device with several interfaces.
+ QStringList drivers;
+ QString netInterface;
+ QString wireless;
+ QString hci;
+ QString blockName;
+ QString port;
+
+ QVariantMap toMap() const
+ {
+ return {
+ {QStringLiteral("key"), key}, {QStringLiteral("kind"), kind},
+ {QStringLiteral("name"), name}, {QStringLiteral("icon"), icon},
+ {QStringLiteral("line"), line}, {QStringLiteral("state"), state},
+ {QStringLiteral("badge"), badge}, {QStringLiteral("problem"), problem},
+ {QStringLiteral("action"), action}, {QStringLiteral("actionLabel"), actionLabel},
+ {QStringLiteral("model"), model}, {QStringLiteral("maker"), maker},
+ {QStringLiteral("driver"), driver}, {QStringLiteral("connection"), connection},
+ {QStringLiteral("hardwareId"), hardwareId}, {QStringLiteral("extra"), extra},
+ {QStringLiteral("port"), port},
+ };
+ }
+};
+
+QString text(const QString &path)
+{
+ QFile file(path);
+ return file.open(QIODevice::ReadOnly) ? QString::fromUtf8(file.readAll()).trimmed() : QString();
+}
+
+QString real(const QString &path)
+{
+ return QFileInfo(path).canonicalFilePath();
+}
+
+QString linkName(const QString &path)
+{
+ const QFileInfo info(path);
+ return info.exists() ? QFileInfo(info.symLinkTarget()).fileName() : QString();
+}
+
+bool under(const QString &path, const QString &ancestor)
+{
+ return !ancestor.isEmpty() && (path == ancestor || path.startsWith(ancestor + QLatin1Char('/')));
+}
+
+// The USB device a sysfs path belongs to (the folder with idVendor), for
+// interfaces, HID devices, network adapters and disks below it.
+QString usbDeviceOf(QString path)
+{
+ while (path.size() > 1 && path.contains(QLatin1String("/usb"))) {
+ if (QFile::exists(path + QStringLiteral("/idVendor")) && !QFileInfo(path).fileName().startsWith(QLatin1String("usb"))) {
+ return path;
+ }
+ path = path.section(QLatin1Char('/'), 0, -2);
+ }
+ return {};
+}
+
+QString pciAddressIn(const QString &path)
+{
+ static const QRegularExpression address(QStringLiteral("^[0-9a-f]{4}:[0-9a-f]{2}:[0-9a-f]{2}\\.[0-7]$"));
+ const QStringList parts = path.split(QLatin1Char('/'));
+ for (int i = parts.size() - 1; i >= 0; --i) {
+ if (address.match(parts.at(i)).hasMatch()) {
+ return parts.at(i);
+ }
+ }
+ return {};
+}
+
+// "Intel Corporation" -> "Intel", "Advanced Micro Devices, Inc. [AMD/ATI]"
+// -> "AMD", "Realtek Semiconductor Co., Ltd." -> "Realtek".
+QString shortMaker(QString maker)
+{
+ static const QRegularExpression bracket(QStringLiteral("\\[([^\\]/]+)"));
+ const QRegularExpressionMatch m = bracket.match(maker);
+ if (m.hasMatch()) {
+ return m.captured(1).trimmed();
+ }
+ static const QRegularExpression suffix(QStringLiteral(
+ "[,.]?\\s+(Corporation|Corp\\.?|Inc\\.?|Incorporated|Co\\.?,?|Ltd\\.?|Limited|GmbH|AG|S\\.A\\.|Semiconductor|Technology|Technologies|"
+ "Electronics|International|Microelectronics|Systems)\\s*$"),
+ QRegularExpression::CaseInsensitiveOption);
+ QString before;
+ while (before != maker) {
+ before = maker;
+ maker.remove(suffix);
+ maker = maker.trimmed();
+ }
+ return maker;
+}
+
+// "Alder Lake-P GT2 [Iris Xe Graphics]" -> "Iris Xe Graphics".
+QString shortModel(const QString &model)
+{
+ static const QRegularExpression bracket(QStringLiteral("\\[([^\\]]+)\\]\\s*$"));
+ const QRegularExpressionMatch m = bracket.match(model);
+ return m.hasMatch() ? m.captured(1).trimmed() : model.trimmed();
+}
+
+// Units of 1024 labelled GB, as System::formatBytes shows them, so a drive
+// reads the same here as in Storage and Files.
+QString sizeText(double bytes)
+{
+ const QLocale locale = QLocale::system();
+ const double gb = 1024.0 * 1024 * 1024;
+ const double tb = gb * 1024;
+ if (bytes >= tb) {
+ return QStringLiteral("%1 TB").arg(locale.toString(bytes / tb, 'f', 2));
+ }
+ return QStringLiteral("%1 GB").arg(locale.toString(bytes / gb, 'f', bytes >= 100 * gb ? 0 : 1));
+}
+
+bool isVirtualVendor(const QString &vendor)
+{
+ static const QSet<QString> vendors = {QStringLiteral("1af4"), QStringLiteral("1b36"), QStringLiteral("1234"), QStringLiteral("15ad"),
+ QStringLiteral("80ee"), QStringLiteral("0627"), QStringLiteral("46f4"), QStringLiteral("0e0f")};
+ return vendors.contains(vendor);
+}
+
+// Interface classes from a USB device's raw descriptors. A device USB
+// protection has blocked has no interfaces in sysfs yet, but the kernel has
+// read these already.
+QSet<QString> descriptorClasses(const QString &path)
+{
+ QSet<QString> classes;
+ QFile file(path + QStringLiteral("/descriptors"));
+ if (!file.open(QIODevice::ReadOnly)) {
+ return classes;
+ }
+ const QByteArray b = file.read(65536);
+ for (int i = 0; i + 1 < b.size() && quint8(b.at(i)) >= 2; i += quint8(b.at(i))) {
+ if (quint8(b.at(i + 1)) == 4 && i + 5 < b.size()) {
+ QString cls = QStringLiteral("%1").arg(quint8(b.at(i + 5)), 2, 16, QLatin1Char('0'));
+ classes.insert(cls == QLatin1String("0a") ? QStringLiteral("02") : cls);
+ }
+ }
+ return classes;
+}
+
+// Names a USB device gives itself can hold anything; keep what a product
+// name needs.
+QString cleanName(QString name)
+{
+ static const QRegularExpression unwanted(QStringLiteral("[^\\p{L}\\p{N} ._,()+/&'-]"));
+ name.remove(unwanted);
+ return name.simplified().left(60);
+}
+
+struct Udev {
+ struct udev *handle = udev_new();
+ struct udev_hwdb *hwdb = handle ? udev_hwdb_new(handle) : nullptr;
+ ~Udev()
+ {
+ if (hwdb) {
+ udev_hwdb_unref(hwdb);
+ }
+ if (handle) {
+ udev_unref(handle);
+ }
+ }
+ // udev's database entry loses the hwdb names when a driver is unbound,
+ // so they are looked up again by the device's modalias when missing.
+ QHash<QString, QString> withNames(const QString &syspath) const
+ {
+ QHash<QString, QString> out = properties(syspath);
+ if (out.contains(QStringLiteral("ID_MODEL_FROM_DATABASE")) || !hwdb) {
+ return out;
+ }
+ const QByteArray alias = text(syspath + QStringLiteral("/modalias")).toUtf8();
+ if (alias.isEmpty()) {
+ return out;
+ }
+ for (struct udev_list_entry *e = udev_hwdb_get_properties_list_entry(hwdb, alias.constData(), 0); e; e = udev_list_entry_get_next(e)) {
+ const QString key = QString::fromUtf8(udev_list_entry_get_name(e));
+ if (!out.contains(key)) {
+ out.insert(key, QString::fromUtf8(udev_list_entry_get_value(e)));
+ }
+ }
+ return out;
+ }
+ QHash<QString, QString> properties(const QString &syspath) const
+ {
+ QHash<QString, QString> out;
+ if (!handle) {
+ return out;
+ }
+ struct udev_device *device = udev_device_new_from_syspath(handle, syspath.toUtf8().constData());
+ if (!device) {
+ return out;
+ }
+ for (struct udev_list_entry *e = udev_device_get_properties_list_entry(device); e; e = udev_list_entry_get_next(e)) {
+ out.insert(QString::fromUtf8(udev_list_entry_get_name(e)), QString::fromUtf8(udev_list_entry_get_value(e)));
+ }
+ udev_device_unref(device);
+ return out;
+ }
+};
+
+QVariant dbusProperty(const QString &service, const QString &path, const QString &interface, const QString &name)
+{
+ QDBusMessage call = QDBusMessage::createMethodCall(service, path, QStringLiteral("org.freedesktop.DBus.Properties"), QStringLiteral("Get"));
+ call << interface << name;
+ const QDBusMessage reply = QDBusConnection::systemBus().call(call, QDBus::Block, 2000);
+ if (reply.type() != QDBusMessage::ReplyMessage || reply.arguments().isEmpty()) {
+ return {};
+ }
+ return reply.arguments().constFirst().value<QDBusVariant>().variant();
+}
+
+// What NetworkManager says about one network adapter, in a few words.
+QString networkLine(const QString &interface, bool wifi, bool cable)
+{
+ const QString nm = QStringLiteral("org.freedesktop.NetworkManager");
+ QDBusMessage call = QDBusMessage::createMethodCall(nm, QStringLiteral("/org/freedesktop/NetworkManager"), nm, QStringLiteral("GetDeviceByIpIface"));
+ call << interface;
+ const QDBusMessage reply = QDBusConnection::systemBus().call(call, QDBus::Block, 2000);
+ if (reply.type() != QDBusMessage::ReplyMessage || reply.arguments().isEmpty()) {
+ return {};
+ }
+ const QString device = reply.arguments().constFirst().value<QDBusObjectPath>().path();
+ const QString active = dbusProperty(nm, device, nm + QStringLiteral(".Device"), QStringLiteral("ActiveConnection")).value<QDBusObjectPath>().path();
+ if (active.isEmpty() || active == QLatin1String("/")) {
+ if (wifi && !dbusProperty(nm, QStringLiteral("/org/freedesktop/NetworkManager"), nm, QStringLiteral("WirelessEnabled")).toBool()) {
+ return QStringLiteral("Turned off");
+ }
+ if (!wifi && !cable) {
+ return QStringLiteral("No cable plugged in");
+ }
+ return QStringLiteral("Not connected");
+ }
+ const QString id = dbusProperty(nm, active, nm + QStringLiteral(".Connection.Active"), QStringLiteral("Id")).toString();
+ const uint state = dbusProperty(nm, active, nm + QStringLiteral(".Connection.Active"), QStringLiteral("State")).toUInt();
+ if (!wifi) {
+ return state == 2 ? QStringLiteral("Connected") : QStringLiteral("Connecting");
+ }
+ return (state == 2 ? QStringLiteral("Connected to %1") : QStringLiteral("Connecting to %1")).arg(id);
+}
+
+// BlueZ's adapters: hciN -> {powered, paired}.
+QHash<QString, QPair<bool, int>> bluetoothAdapters()
+{
+ QHash<QString, QPair<bool, int>> out;
+ QDBusMessage call = QDBusMessage::createMethodCall(QStringLiteral("org.bluez"), QStringLiteral("/"), QStringLiteral("org.freedesktop.DBus.ObjectManager"),
+ QStringLiteral("GetManagedObjects"));
+ const QDBusMessage reply = QDBusConnection::systemBus().call(call, QDBus::Block, 2000);
+ if (reply.type() != QDBusMessage::ReplyMessage || reply.arguments().isEmpty()) {
+ return out;
+ }
+ const ManagedObjects objects = qdbus_cast<ManagedObjects>(reply.arguments().constFirst());
+ for (auto it = objects.cbegin(); it != objects.cend(); ++it) {
+ const QString path = it.key().path();
+ if (it.value().contains(QStringLiteral("org.bluez.Adapter1"))) {
+ out[path.section(QLatin1Char('/'), -1)].first = it.value().value(QStringLiteral("org.bluez.Adapter1")).value(QStringLiteral("Powered")).toBool();
+ }
+ }
+ for (auto it = objects.cbegin(); it != objects.cend(); ++it) {
+ const QVariantMap device = it.value().value(QStringLiteral("org.bluez.Device1"));
+ if (!device.isEmpty() && device.value(QStringLiteral("Paired")).toBool()) {
+ out[it.key().path().section(QLatin1Char('/'), 3, 3)].second += 1;
+ }
+ }
+ return out;
+}
+
+// settings-devices' answer: kernel firmware failures and drive health.
+QJsonObject askRoot(bool *answered)
+{
+ QLocalSocket socket;
+ socket.connectToServer(socketPath);
+ *answered = false;
+ if (!socket.waitForConnected(2000)) {
+ return {};
+ }
+ QByteArray data;
+ QElapsedTimer timer;
+ timer.start();
+ while (timer.elapsed() < 20000) {
+ if (socket.bytesAvailable() || socket.waitForReadyRead(500)) {
+ data += socket.readAll();
+ if (data.endsWith('\n')) {
+ break;
+ }
+ } else if (socket.state() != QLocalSocket::ConnectedState) {
+ break;
+ }
+ }
+ const QJsonDocument doc = QJsonDocument::fromJson(data);
+ *answered = doc.isObject();
+ return doc.object();
+}
+
+// Space used on each disk by what is mounted from it, through LUKS and LVM.
+QHash<QString, QPair<double, double>> spaceByDisk(QSet<QString> *systemDisks)
+{
+ QHash<QString, QPair<double, double>> out;
+ QFile mounts(QStringLiteral("/proc/self/mountinfo"));
+ if (!mounts.open(QIODevice::ReadOnly | QIODevice::Text)) {
+ return out;
+ }
+ QSet<dev_t> seen;
+ const std::function<QStringList(const QString &)> disksOf = [&disksOf](const QString &name) -> QStringList {
+ const QString path = real(QStringLiteral("/sys/class/block/") + name);
+ if (path.isEmpty()) {
+ return {};
+ }
+ if (QFile::exists(path + QStringLiteral("/partition"))) {
+ return {QFileInfo(path.section(QLatin1Char('/'), 0, -2)).fileName()};
+ }
+ const QStringList slaves = QDir(path + QStringLiteral("/slaves")).entryList(QDir::Dirs | QDir::NoDotAndDotDot);
+ if (slaves.isEmpty()) {
+ return {name};
+ }
+ QStringList all;
+ for (const QString &slave : slaves) {
+ all << disksOf(slave);
+ }
+ return all;
+ };
+ // procfs files have no size, so QFile::atEnd() is true before reading.
+ const QStringList lines = QString::fromUtf8(mounts.readAll()).split(QLatin1Char('\n'), Qt::SkipEmptyParts);
+ for (const QString &line : lines) {
+ const QStringList halves = line.split(QStringLiteral(" - "));
+ if (halves.size() < 2) {
+ continue;
+ }
+ const QStringList left = halves.at(0).split(QLatin1Char(' '));
+ const QStringList right = halves.at(1).split(QLatin1Char(' '));
+ if (left.size() < 5 || right.size() < 2 || !right.at(1).startsWith(QLatin1String("/dev/"))) {
+ continue;
+ }
+ struct stat st;
+ if (::stat(right.at(1).toUtf8().constData(), &st) != 0 || !S_ISBLK(st.st_mode) || seen.contains(st.st_rdev)) {
+ continue;
+ }
+ seen.insert(st.st_rdev);
+ const QString mountPoint = QString(left.at(4)).replace(QStringLiteral("\\040"), QStringLiteral(" "));
+ struct statvfs vfs;
+ if (::statvfs(mountPoint.toUtf8().constData(), &vfs) != 0 || vfs.f_blocks == 0) {
+ continue;
+ }
+ const double total = double(vfs.f_blocks) * vfs.f_frsize;
+ const double used = total - double(vfs.f_bfree) * vfs.f_frsize;
+ const QString name = linkName(QStringLiteral("/sys/dev/block/%1:%2").arg(major(st.st_rdev)).arg(minor(st.st_rdev)));
+ for (const QString &disk : disksOf(name)) {
+ if (mountPoint == QLatin1String("/")) {
+ systemDisks->insert(disk);
+ }
+ out[disk].first += used;
+ out[disk].second += total;
+ }
+ }
+ return out;
+}
+
+struct LibfprintReaders {
+ QSet<QString> supported;
+ QSet<QString> unsupported;
+};
+
+// libfprint's hwdb lists the readers it drives, then under an "unsupported"
+// comment the ones it knows of but can't (as Fingerprint reads it).
+LibfprintReaders libfprintReaders()
+{
+ LibfprintReaders readers;
+ QFile hwdb(QStringLiteral("/usr/lib/udev/hwdb.d/60-autosuspend-libfprint-2.hwdb"));
+ if (!hwdb.open(QIODevice::ReadOnly | QIODevice::Text)) {
+ return readers;
+ }
+ bool unsupportedSection = false;
+ while (!hwdb.atEnd()) {
+ const QString line = QString::fromLatin1(hwdb.readLine()).trimmed();
+ if (line.startsWith(QLatin1Char('#'))) {
+ unsupportedSection = unsupportedSection || line.contains(QLatin1String("unsupported"), Qt::CaseInsensitive);
+ } else if (line.startsWith(QLatin1String("usb:v")) && line.size() >= 14) {
+ const QString id = (line.mid(5, 4) + QLatin1Char(':') + line.mid(10, 4)).toLower();
+ (unsupportedSection ? readers.unsupported : readers.supported).insert(id);
+ }
+ }
+ return readers;
+}
+
+QString usbConnection(const QString &path)
+{
+ const QString port = QFileInfo(path).fileName();
+ return text(path + QStringLiteral("/removable")) == QLatin1String("fixed") ? QStringLiteral("Built in, on USB port %1").arg(port)
+ : QStringLiteral("USB port %1").arg(port);
+}
+
+QString pciConnection(const QString &address)
+{
+ return QStringLiteral("Inside this PC, in PCI slot %1").arg(address);
+}
+
+// NVIDIA cards Debian's nvidia-driver drives: Maxwell (GeForce GTX 900,
+// device IDs from 0x1340) up to Ada (RTX 40). Older ones need legacy
+// drivers Debian no longer ships and RTX 50 cards (0x2b00 on) need a newer
+// driver, so the open driver is the best those can have here.
+bool nvidiaSupported(const QString &product)
+{
+ bool ok = false;
+ const uint id = product.toUInt(&ok, 16);
+ return ok && id >= 0x1340 && id < 0x2b00;
+}
+
+QVariantList scanAll(const QJsonObject &root, bool rootAnswered)
+{
+ Udev udev;
+ const LibfprintReaders fprint = libfprintReaders();
+ QList<Dev> list;
+ const auto find = [&list](const QString &key) -> Dev * {
+ for (Dev &d : list) {
+ if (d.key == key) {
+ return &d;
+ }
+ }
+ return nullptr;
+ };
+
+ // What each kind of device produces when its driver works, by the real
+ // path of the device it belongs to.
+ QStringList drmCards;
+ for (const QString &card : QDir(QStringLiteral("/sys/class/drm")).entryList({QStringLiteral("card*")}, QDir::Dirs | QDir::System)) {
+ if (!card.contains(QLatin1Char('-'))) {
+ drmCards << real(QStringLiteral("/sys/class/drm/%1/device").arg(card));
+ }
+ }
+ QStringList soundCards;
+ for (const QString &card : QDir(QStringLiteral("/sys/class/sound")).entryList({QStringLiteral("card*")}, QDir::Dirs | QDir::System)) {
+ soundCards << real(QStringLiteral("/sys/class/sound/%1/device").arg(card));
+ }
+ QStringList videoDevices;
+ for (const QString &node : QDir(QStringLiteral("/sys/class/video4linux")).entryList(QDir::Dirs | QDir::System | QDir::NoDotAndDotDot)) {
+ videoDevices << real(QStringLiteral("/sys/class/video4linux/%1/device").arg(node));
+ }
+ QStringList netDevices;
+ for (const QString &net : QDir(QStringLiteral("/sys/class/net")).entryList(QDir::Dirs | QDir::System | QDir::NoDotAndDotDot)) {
+ netDevices << real(QStringLiteral("/sys/class/net/%1/device").arg(net));
+ }
+ QStringList hciDevices;
+ for (const QString &hci : QDir(QStringLiteral("/sys/class/bluetooth")).entryList({QStringLiteral("hci*")}, QDir::Dirs | QDir::System)) {
+ if (!hci.contains(QLatin1Char(':'))) {
+ hciDevices << real(QStringLiteral("/sys/class/bluetooth/%1/device").arg(hci));
+ }
+ }
+ QStringList blockDevices;
+ for (const QString &block : QDir(QStringLiteral("/sys/block")).entryList(QDir::Dirs | QDir::System | QDir::NoDotAndDotDot)) {
+ blockDevices << real(QStringLiteral("/sys/block/") + block);
+ }
+ const auto anyUnder = [](const QStringList &paths, const QString &ancestor) {
+ return std::any_of(paths.cbegin(), paths.cend(), [&ancestor](const QString &p) {
+ return under(p, ancestor);
+ });
+ };
+
+ // PCI: the parts inside the PC.
+ for (const QString &address : QDir(QStringLiteral("/sys/bus/pci/devices")).entryList(QDir::Dirs | QDir::System | QDir::NoDotAndDotDot)) {
+ const QString path = real(QStringLiteral("/sys/bus/pci/devices/") + address);
+ bool ok = false;
+ const uint cls = text(path + QStringLiteral("/class")).toUInt(&ok, 16);
+ if (!ok) {
+ continue;
+ }
+ const uint base = cls >> 16;
+ const uint sub = (cls >> 8) & 0xff;
+ const uint progIf = cls & 0xff;
+ const auto props = udev.withNames(path);
+ const QString vendor = text(path + QStringLiteral("/vendor")).mid(2);
+ const QString product = text(path + QStringLiteral("/device")).mid(2);
+ const QString dbModel = props.value(QStringLiteral("ID_MODEL_FROM_DATABASE"));
+
+ QString kind;
+ if (base == 0x03) {
+ kind = QStringLiteral("graphics");
+ } else if (base == 0x02) {
+ kind = sub == 0x80 ? QStringLiteral("wifi") : QStringLiteral("ethernet");
+ } else if (base == 0x0d) {
+ kind = sub == 0x11 ? QStringLiteral("bluetooth") : QStringLiteral("wifi");
+ } else if (base == 0x04 && (sub == 0x01 || sub == 0x03)) {
+ const bool onGraphics = (vendor == QLatin1String("10de") || vendor == QLatin1String("1002")) && !address.endsWith(QLatin1String(".0"));
+ kind = onGraphics ? QStringLiteral("hdmisound") : QStringLiteral("sound");
+ } else if (base == 0x04 && dbModel.contains(QRegularExpression(QStringLiteral("IPU|Imaging|Camera"), QRegularExpression::CaseInsensitiveOption))) {
+ kind = QStringLiteral("camera");
+ } else if (base == 0x01) {
+ kind = QStringLiteral("storagectl");
+ } else if (base == 0x0c && sub == 0x03) {
+ kind = QStringLiteral("usbctl");
+ } else if (base == 0x0c && sub == 0x00) {
+ kind = QStringLiteral("firewire");
+ } else if ((base == 0x08 && sub == 0x05) || (base == 0xff && dbModel.contains(QLatin1String("Card Reader"), Qt::CaseInsensitive))) {
+ kind = QStringLiteral("cardreader");
+ } else {
+ continue;
+ }
+ Dev d;
+ d.key = path;
+ d.kind = kind;
+ d.bus = QStringLiteral("pci");
+ d.vendorId = vendor;
+ d.productId = product;
+ d.unboundPath = path;
+ d.maker = shortMaker(props.value(QStringLiteral("ID_VENDOR_FROM_DATABASE")));
+ d.model = dbModel.isEmpty() ? props.value(QStringLiteral("ID_PCI_SUBCLASS_FROM_DATABASE")) : shortModel(dbModel);
+ d.hardwareId = QStringLiteral("PCI %1:%2").arg(vendor, product);
+ d.connection = pciConnection(address);
+ d.virtualHardware = isVirtualVendor(vendor);
+ d.builtIn = true;
+ d.driver = linkName(path + QStringLiteral("/driver"));
+ // virtio devices: virtio-pci only carries the bus; the driver that
+ // does the work sits on the virtioN device below it.
+ if (d.driver == QLatin1String("virtio-pci")) {
+ for (const QString &child : QDir(path).entryList({QStringLiteral("virtio*")}, QDir::Dirs)) {
+ const QString inner = linkName(path + QLatin1Char('/') + child + QStringLiteral("/driver"));
+ if (!inner.isEmpty()) {
+ d.driver = inner;
+ }
+ }
+ }
+ if (kind == QLatin1String("storagectl")) {
+ // An NVMe drive or a virtual disk is its own controller: the
+ // drive's row covers it, unless it has no driver.
+ if ((sub == 0x08 || d.virtualHardware) && !d.driver.isEmpty()) {
+ continue;
+ }
+ }
+ if (kind == QLatin1String("usbctl") && progIf == 0x40) {
+ d.name = QStringLiteral("USB4 controller");
+ }
+ list << d;
+ }
+
+ // USB: what is plugged in, and what is built in over USB (cameras,
+ // fingerprint readers, Bluetooth).
+ for (const QString &entry : QDir(QStringLiteral("/sys/bus/usb/devices")).entryList(QDir::Dirs | QDir::System | QDir::NoDotAndDotDot)) {
+ if (entry.contains(QLatin1Char(':')) || entry.startsWith(QLatin1String("usb"))) {
+ continue;
+ }
+ const QString path = real(QStringLiteral("/sys/bus/usb/devices/") + entry);
+ if (text(path + QStringLiteral("/bDeviceClass")) == QLatin1String("09")) {
+ continue;
+ }
+ const auto props = udev.withNames(path);
+ Dev d;
+ d.key = path;
+ d.bus = QStringLiteral("usb");
+ d.vendorId = text(path + QStringLiteral("/idVendor"));
+ d.productId = text(path + QStringLiteral("/idProduct"));
+ d.hardwareId = QStringLiteral("USB %1:%2").arg(d.vendorId, d.productId);
+ d.virtualHardware = isVirtualVendor(d.vendorId);
+ d.connection = usbConnection(path);
+ d.builtIn = text(path + QStringLiteral("/removable")) == QLatin1String("fixed");
+ const QString manufacturer = cleanName(text(path + QStringLiteral("/manufacturer")));
+ const QString productName = cleanName(text(path + QStringLiteral("/product")));
+ d.maker = shortMaker(props.value(QStringLiteral("ID_VENDOR_FROM_DATABASE"), manufacturer));
+ if (d.maker.isEmpty()) {
+ d.maker = manufacturer;
+ }
+ d.model = props.value(QStringLiteral("ID_MODEL_FROM_DATABASE"), productName);
+ if (d.model.isEmpty()) {
+ d.model = productName;
+ }
+ d.model = shortModel(d.model);
+
+ // By interface class: whether any interface of it has a driver. A
+ // device with several audio or video interfaces needs only one of
+ // them claimed, and CDC data goes with its control interface.
+ QSet<QString> classes;
+ QHash<QString, bool> classBound;
+ QHash<QString, QString> unboundByClass;
+ for (const QString &iface : QDir(path).entryList({entry + QStringLiteral(":*")}, QDir::Dirs)) {
+ const QString ipath = path + QLatin1Char('/') + iface;
+ QString cls = text(ipath + QStringLiteral("/bInterfaceClass"));
+ if (cls == QLatin1String("0a")) {
+ cls = QStringLiteral("02");
+ }
+ classes.insert(cls);
+ const QString driver = linkName(ipath + QStringLiteral("/driver"));
+ classBound[cls] = classBound.value(cls) || !driver.isEmpty();
+ if (!driver.isEmpty() && !d.drivers.contains(driver)) {
+ d.drivers << driver;
+ }
+ if (driver.isEmpty() && !unboundByClass.contains(cls)) {
+ unboundByClass.insert(cls, real(ipath));
+ }
+ }
+ const bool blocked = text(path + QStringLiteral("/authorized")) == QLatin1String("0");
+ if (blocked) {
+ classes = descriptorClasses(path);
+ d.port = entry;
+ d.state = QStringLiteral("attention");
+ d.problem = QStringLiteral("Blocked by USB protection until you allow it.");
+ d.badge = QStringLiteral("Blocked");
+ d.action = QStringLiteral("allow");
+ d.actionLabel = QStringLiteral("Allow");
+ }
+ QString unboundIface;
+ for (const QString &cls : {QStringLiteral("01"), QStringLiteral("02"), QStringLiteral("03"), QStringLiteral("05"), QStringLiteral("07"),
+ QStringLiteral("08"), QStringLiteral("0e"), QStringLiteral("0f"), QStringLiteral("10"), QStringLiteral("e0")}) {
+ if (!blocked && classes.contains(cls) && !classBound.value(cls)) {
+ d.unboundInterface = true;
+ unboundIface = unboundByClass.value(cls);
+ break;
+ }
+ }
+ if (unboundIface.isEmpty()) {
+ for (auto it = unboundByClass.cbegin(); it != unboundByClass.cend(); ++it) {
+ if (!classBound.value(it.key())) {
+ unboundIface = it.value();
+ break;
+ }
+ }
+ }
+ d.driver = d.drivers.join(QStringLiteral(", "));
+ d.unboundPath = unboundIface.isEmpty() ? path : unboundIface;
+ const QString id = d.vendorId + QLatin1Char(':') + d.productId;
+
+ if (fprint.supported.contains(id) || fprint.unsupported.contains(id)) {
+ d.kind = QStringLiteral("fingerprint");
+ // libfprint drives it from user space; no kernel driver to want.
+ d.unboundInterface = false;
+ d.driver = QStringLiteral("libfprint");
+ if (fprint.unsupported.contains(id)) {
+ d.state = QStringLiteral("attention");
+ d.problem = QStringLiteral("Wild OS has no driver for this reader yet.");
+ d.badge = QStringLiteral("Needs a driver");
+ d.action = QStringLiteral("report");
+ d.actionLabel = QStringLiteral("Report it");
+ d.driver.clear();
+ }
+ } else if (classes.contains(QStringLiteral("0e"))) {
+ d.kind = QStringLiteral("camera");
+ } else if (classes.contains(QStringLiteral("07"))) {
+ d.kind = QStringLiteral("printer");
+ } else if (classes.contains(QStringLiteral("e0"))) {
+ d.kind = QStringLiteral("bluetooth");
+ } else if (classes.contains(QStringLiteral("01"))) {
+ d.kind = QStringLiteral("sound");
+ } else if (props.value(QStringLiteral("libsane_matched")) == QLatin1String("yes")) {
+ d.kind = QStringLiteral("scanner");
+ d.driver = QStringLiteral("SANE");
+ d.unboundInterface = false;
+ } else if (classes.contains(QStringLiteral("0b"))) {
+ d.kind = QStringLiteral("smartcard");
+ d.driver = d.driver.isEmpty() ? QStringLiteral("pcscd") : d.driver;
+ } else if (classes.contains(QStringLiteral("08"))) {
+ d.kind = QStringLiteral("usbdrive");
+ } else if (classes == QSet<QString>{QStringLiteral("03")}) {
+ d.kind = QStringLiteral("hid");
+ } else if (props.value(QStringLiteral("ID_MTP_DEVICE")) == QLatin1String("1") || classes.contains(QStringLiteral("06"))) {
+ d.kind = QStringLiteral("phone");
+ d.unboundInterface = false;
+ } else {
+ d.kind = QStringLiteral("usb");
+ }
+ list << d;
+ }
+
+ // Network adapters: Wi-Fi or Ethernet, and the interface name for
+ // NetworkManager.
+ for (const QString &net : QDir(QStringLiteral("/sys/class/net")).entryList(QDir::Dirs | QDir::System | QDir::NoDotAndDotDot)) {
+ QString device = real(QStringLiteral("/sys/class/net/%1/device").arg(net));
+ if (device.isEmpty()) {
+ continue;
+ }
+ const QString usb = usbDeviceOf(device);
+ if (!usb.isEmpty()) {
+ device = usb;
+ } else if (QFileInfo(device).fileName().startsWith(QLatin1String("virtio"))) {
+ device = device.section(QLatin1Char('/'), 0, -2);
+ }
+ Dev *d = find(device);
+ if (!d) {
+ continue;
+ }
+ const bool wifi = QFile::exists(QStringLiteral("/sys/class/net/%1/wireless").arg(net)) || QFile::exists(QStringLiteral("/sys/class/net/%1/phy80211").arg(net));
+ d->kind = wifi ? QStringLiteral("wifi") : QStringLiteral("ethernet");
+ d->netInterface = net;
+ }
+
+ // Drives.
+ QSet<QString> systemDisks;
+ const QHash<QString, QPair<double, double>> space = spaceByDisk(&systemDisks);
+ const QJsonObject health = root.value(QStringLiteral("disks")).toObject();
+ for (const QString &block : QDir(QStringLiteral("/sys/block")).entryList(QDir::Dirs | QDir::System | QDir::NoDotAndDotDot)) {
+ static const QRegularExpression skip(QStringLiteral("^(loop|ram|zram|dm-|md|sr|fd|nbd)"));
+ if (skip.match(block).hasMatch()) {
+ continue;
+ }
+ const QString path = real(QStringLiteral("/sys/block/") + block);
+ const double bytes = text(path + QStringLiteral("/size")).toDouble() * 512;
+ if (bytes <= 0) {
+ continue;
+ }
+ const QString usb = usbDeviceOf(path);
+ if (!usb.isEmpty()) {
+ Dev *d = find(usb);
+ if (d) {
+ d->kind = QStringLiteral("usbdrive");
+ d->blockName = block;
+ d->line = QStringLiteral("Plugged in, %1").arg(sizeText(bytes));
+ }
+ continue;
+ }
+ Dev d;
+ d.key = path;
+ d.blockName = block;
+ d.builtIn = true;
+ const QString pciAddress = pciAddressIn(path);
+ const QString pciPath = pciAddress.isEmpty() ? QString() : real(QStringLiteral("/sys/bus/pci/devices/") + pciAddress);
+ const auto pciProps = pciPath.isEmpty() ? QHash<QString, QString>() : udev.properties(pciPath);
+ d.virtualHardware = isVirtualVendor(text(pciPath + QStringLiteral("/vendor")).mid(2));
+ const bool removable = text(path + QStringLiteral("/removable")) == QLatin1String("1");
+ const bool solid = text(path + QStringLiteral("/queue/rotational")) == QLatin1String("0") || block.startsWith(QLatin1String("nvme"));
+ static const QRegularExpression ata(QStringLiteral("/ata(\\d+)/"));
+ const QRegularExpressionMatch port = ata.match(path);
+ d.model = cleanName(text(path + QStringLiteral("/device/model")));
+ if (d.model.isEmpty()) {
+ d.model = shortModel(pciProps.value(QStringLiteral("ID_MODEL_FROM_DATABASE")));
+ }
+ // A SATA drive's vendor field says only "ATA" and its controller is
+ // someone else's, so its maker is left to the model name.
+ d.maker = text(path + QStringLiteral("/device/vendor"));
+ if (d.maker == QLatin1String("ATA")) {
+ d.maker.clear();
+ } else if (d.maker.isEmpty() && !port.hasMatch()) {
+ d.maker = shortMaker(pciProps.value(QStringLiteral("ID_VENDOR_FROM_DATABASE")));
+ }
+ d.driver = linkName(path + QStringLiteral("/device/driver"));
+ if (d.driver.isEmpty() && block.startsWith(QLatin1String("nvme"))) {
+ d.driver = QStringLiteral("nvme");
+ }
+ if (d.driver.isEmpty() || d.driver == QLatin1String("sd")) {
+ d.driver = d.driver.isEmpty() ? linkName(pciPath + QStringLiteral("/driver")) : QStringLiteral("sd (%1)").arg(linkName(pciPath + QStringLiteral("/driver")));
+ }
+ d.connection =port.hasMatch() ? QStringLiteral("Inside this PC, on SATA port %1").arg(port.captured(1))
+ : !pciAddress.isEmpty() ? pciConnection(pciAddress)
+ : QStringLiteral("Built in");
+ d.hardwareId = pciPath.isEmpty() ? QString() : QStringLiteral("PCI %1:%2").arg(text(pciPath + QStringLiteral("/vendor")).mid(2), text(pciPath + QStringLiteral("/device")).mid(2));
+ if (removable || block.startsWith(QLatin1String("mmcblk"))) {
+ d.kind = QStringLiteral("card");
+ d.name = QStringLiteral("Memory card, %1").arg(sizeText(bytes));
+ d.line = QStringLiteral("In the card reader");
+ list << d;
+ continue;
+ }
+ d.kind = QStringLiteral("storage");
+ d.first = systemDisks.contains(block);
+ d.name = (d.virtualHardware ? QStringLiteral("Virtual drive, %1") : solid ? QStringLiteral("Internal SSD, %1") : QStringLiteral("Internal hard drive, %1")).arg(sizeText(bytes));
+ d.extra << QVariantMap{{QStringLiteral("label"), QStringLiteral("Size")}, {QStringLiteral("value"), sizeText(bytes)}};
+
+ QString used;
+ if (space.contains(block) && space.value(block).second > 0) {
+ const auto s = space.value(block);
+ used = QStringLiteral("%1% used").arg(qRound(100 * s.first / s.second));
+ d.extra << QVariantMap{{QStringLiteral("label"), QStringLiteral("Space used")},
+ {QStringLiteral("value"), QStringLiteral("%1% (%2 of %3)").arg(qRound(100 * s.first / s.second)).arg(sizeText(s.first), sizeText(s.second))}};
+ }
+ const QJsonObject h = health.value(block).toObject();
+ QString healthWords;
+ if (!rootAnswered) {
+ healthWords = QStringLiteral("Couldn't be checked just now.");
+ d.line = used.isEmpty() ? QStringLiteral("Built in") : used.left(1).toUpper() + used.mid(1);
+ } else if (!h.value(QStringLiteral("reported")).toBool()) {
+ healthWords = d.virtualHardware ? QStringLiteral("A virtual drive doesn't report its health.") : QStringLiteral("This drive doesn't report its health.");
+ d.line = used.isEmpty() ? QStringLiteral("Built in") : used.left(1).toUpper() + used.mid(1);
+ } else {
+ const bool passed = h.value(QStringLiteral("passed")).toBool();
+ const int warning = h.value(QStringLiteral("criticalWarning")).toInt();
+ const int wear = h.value(QStringLiteral("percentUsed")).toInt(-1);
+ if (!passed || warning != 0) {
+ healthWords = QStringLiteral("Failing. Its own health check says it may stop working.");
+ d.state = QStringLiteral("attention");
+ d.problem = QStringLiteral("Its health check says it's failing. Back up your files now.");
+ d.badge = QStringLiteral("Failing");
+ d.action = QStringLiteral("backup");
+ d.actionLabel = QStringLiteral("Back up now");
+ } else if (wear >= 100) {
+ healthWords = QStringLiteral("Worn out. It has used all of its rated life.");
+ d.state = QStringLiteral("attention");
+ d.problem = QStringLiteral("It has used all of its rated life. Back up your files now.");
+ d.badge = QStringLiteral("Wearing out");
+ d.action = QStringLiteral("backup");
+ d.actionLabel = QStringLiteral("Back up now");
+ } else {
+ healthWords = QStringLiteral("Healthy. Its own health check passed.");
+ }
+ d.line = QStringLiteral("Healthy") + (used.isEmpty() ? QString() : QStringLiteral(". ") + used);
+ if (wear >= 0) {
+ d.extra << QVariantMap{{QStringLiteral("label"), QStringLiteral("Wear")}, {QStringLiteral("value"), QStringLiteral("%1% of its rated life used").arg(wear)}};
+ }
+ if (h.contains(QStringLiteral("temperature"))) {
+ d.extra << QVariantMap{{QStringLiteral("label"), QStringLiteral("Temperature")}, {QStringLiteral("value"), QStringLiteral("%1 °C").arg(h.value(QStringLiteral("temperature")).toInt())}};
+ }
+ if (h.value(QStringLiteral("hours")).toInteger() > 0) {
+ d.extra << QVariantMap{{QStringLiteral("label"), QStringLiteral("Switched on for")},
+ {QStringLiteral("value"), QStringLiteral("%1 hours in all").arg(QLocale(QLocale::English).toString(h.value(QStringLiteral("hours")).toInteger()))}};
+ }
+ const qint64 bad = h.value(QStringLiteral("reallocated")).toInteger() + h.value(QStringLiteral("pending")).toInteger();
+ if (bad > 0) {
+ d.extra << QVariantMap{{QStringLiteral("label"), QStringLiteral("Damaged areas")},
+ {QStringLiteral("value"), QStringLiteral("%1, set aside so nothing is stored there").arg(bad)}};
+ }
+ }
+ d.extra.insert(0, QVariantMap{{QStringLiteral("label"), QStringLiteral("Health")}, {QStringLiteral("value"), healthWords}});
+ list << d;
+ }
+
+ // Keyboards, mice, touchpads, touchscreens, pens and game controllers,
+ // one row per physical device however many input nodes it has.
+ struct Input {
+ QString key;
+ QString source;
+ QString bus;
+ QString name;
+ QString driver;
+ int bits = 0;
+ };
+ enum { Keyboard = 1, Mouse = 2, Touchpad = 4, Touchscreen = 8, Pen = 16, Joystick = 32 };
+ QList<Input> inputs;
+ static const QRegularExpression notKeyboard(
+ QStringLiteral("Video Bus|Power Button|Sleep Button|Lid Switch|HID events|WMI|hotkeys|Consumer Control|System Control|Wireless Radio|Speaker|Headphone|Mic|HDMI|Jack"),
+ QRegularExpression::CaseInsensitiveOption);
+ for (const QString &node : QDir(QStringLiteral("/sys/class/input")).entryList({QStringLiteral("input*")}, QDir::Dirs | QDir::System)) {
+ const QString path = real(QStringLiteral("/sys/class/input/") + node);
+ const auto props = udev.properties(path);
+ const QString name = text(path + QStringLiteral("/name"));
+ const QString idBus = props.value(QStringLiteral("ID_BUS"));
+ if (path.contains(QLatin1String("/virtual/")) && idBus != QLatin1String("bluetooth")) {
+ continue;
+ }
+ int bits = 0;
+ if (props.value(QStringLiteral("ID_INPUT_KEYBOARD")) == QLatin1String("1") && !notKeyboard.match(name).hasMatch()) {
+ bits |= Keyboard;
+ }
+ if (props.value(QStringLiteral("ID_INPUT_MOUSE")) == QLatin1String("1")) {
+ bits |= Mouse;
+ }
+ if (props.value(QStringLiteral("ID_INPUT_TOUCHPAD")) == QLatin1String("1")) {
+ bits |= Touchpad;
+ }
+ if (props.value(QStringLiteral("ID_INPUT_TOUCHSCREEN")) == QLatin1String("1")) {
+ bits |= Touchscreen;
+ }
+ if (props.value(QStringLiteral("ID_INPUT_TABLET")) == QLatin1String("1") && !(bits & Mouse)) {
+ bits |= Pen;
+ }
+ if (props.value(QStringLiteral("ID_INPUT_JOYSTICK")) == QLatin1String("1")) {
+ bits |= Joystick;
+ }
+ if (bits == 0) {
+ continue;
+ }
+ Input in;
+ in.name = cleanName(name);
+ in.bits = bits;
+ const QString parent = path.section(QLatin1Char('/'), 0, -2);
+ in.driver = linkName(parent + QStringLiteral("/driver"));
+ if (idBus == QLatin1String("bluetooth")) {
+ in.key = QStringLiteral("bluetooth:") + text(path + QStringLiteral("/uniq"));
+ in.bus = QStringLiteral("bluetooth");
+ } else if (const QString usb = usbDeviceOf(path); !usb.isEmpty()) {
+ in.key = usb;
+ in.bus = QStringLiteral("usb");
+ } else {
+ static const QRegularExpression physical(QStringLiteral("^(.*/(serio\\d+|i2c-[^/]*:[^/]*|[^/]*:[^/]*\\.\\d+))(/|$)"));
+ const QRegularExpressionMatch m = physical.match(parent);
+ in.key = m.hasMatch() ? m.captured(1) : parent;
+ in.bus = QStringLiteral("builtin");
+ }
+ in.source = path;
+ bool merged = false;
+ for (Input &existing : inputs) {
+ if (existing.key == in.key) {
+ existing.bits |= in.bits;
+ if (existing.driver.isEmpty()) {
+ existing.driver = in.driver;
+ }
+ merged = true;
+ }
+ }
+ if (!merged) {
+ inputs << in;
+ }
+ }
+ for (const Input &in : std::as_const(inputs)) {
+ Dev *existing = find(in.key);
+ Dev d = existing ? *existing : Dev();
+ d.key = in.key;
+ d.bus = in.bus;
+ if (in.bits & Touchpad) {
+ d.kind = QStringLiteral("touchpad");
+ } else if (in.bits & Touchscreen) {
+ d.kind = QStringLiteral("touchscreen");
+ } else if (in.bits & Pen) {
+ d.kind = QStringLiteral("pen");
+ } else if (in.bits & Joystick) {
+ d.kind = QStringLiteral("controller");
+ } else if ((in.bits & Keyboard) && (in.bits & Mouse)) {
+ d.kind = QStringLiteral("keyboardmouse");
+ } else if (in.bits & Keyboard) {
+ d.kind = QStringLiteral("keyboard");
+ } else {
+ d.kind = QStringLiteral("mouse");
+ }
+ if (in.bus == QLatin1String("bluetooth")) {
+ d.connection = QStringLiteral("Bluetooth");
+ d.model = in.name;
+ d.driver = in.driver;
+ } else if (in.bus == QLatin1String("builtin")) {
+ d.connection = QStringLiteral("Built in");
+ d.builtIn = true;
+ d.model = in.name;
+ d.driver = in.driver;
+ } else if (d.driver.isEmpty()) {
+ d.driver = in.driver;
+ }
+ if (existing) {
+ *existing = d;
+ } else {
+ list << d;
+ }
+ }
+
+ // Batteries in the PC (not a mouse's: those say scope Device).
+ for (const QString &supply : QDir(QStringLiteral("/sys/class/power_supply")).entryList(QDir::Dirs | QDir::System | QDir::NoDotAndDotDot)) {
+ const QString path = real(QStringLiteral("/sys/class/power_supply/") + supply);
+ if (text(path + QStringLiteral("/type")) != QLatin1String("Battery") || text(path + QStringLiteral("/scope")) == QLatin1String("Device")) {
+ continue;
+ }
+ Dev d;
+ d.key = path;
+ d.kind = QStringLiteral("battery");
+ d.builtIn = true;
+ d.connection = QStringLiteral("Built in");
+ d.maker = text(path + QStringLiteral("/manufacturer"));
+ d.model = text(path + QStringLiteral("/model_name"));
+ d.driver = linkName(path + QStringLiteral("/device/driver"));
+ double full = text(path + QStringLiteral("/energy_full")).toDouble();
+ double design = text(path + QStringLiteral("/energy_full_design")).toDouble();
+ if (design <= 0) {
+ full = text(path + QStringLiteral("/charge_full")).toDouble();
+ design = text(path + QStringLiteral("/charge_full_design")).toDouble();
+ }
+ if (design > 0 && full > 0) {
+ const int percent = qMin(100, qRound(100 * full / design));
+ d.line = QStringLiteral("Holds %1% of its charge when new").arg(percent);
+ d.extra << QVariantMap{{QStringLiteral("label"), QStringLiteral("Health")}, {QStringLiteral("value"), d.line}};
+ } else {
+ d.line = QStringLiteral("Built in");
+ }
+ list << d;
+ }
+
+ // Kernel lines about firmware that failed to load, by the device each
+ // is about.
+ QList<QPair<QString, QString>> firmware;
+ for (const QJsonValue &v : root.value(QStringLiteral("firmware")).toArray()) {
+ const QJsonObject o = v.toObject();
+ const QString device = o.value(QStringLiteral("device")).toString();
+ const int colon = device.indexOf(QLatin1Char(':'));
+ if (colon <= 0) {
+ continue;
+ }
+ const QString path = real(QStringLiteral("/sys/bus/%1/devices/%2").arg(device.left(colon), device.mid(colon + 1)));
+ if (!path.isEmpty()) {
+ firmware << qMakePair(path, o.value(QStringLiteral("file")).toString());
+ }
+ }
+ const QJsonObject unbound = root.value(QStringLiteral("unbound")).toObject();
+ const QHash<QString, QPair<bool, int>> adapters = bluetoothAdapters();
+ QList<QPair<QString, QString>> rfkills;
+ for (const QString &r : QDir(QStringLiteral("/sys/class/rfkill")).entryList(QDir::Dirs | QDir::System | QDir::NoDotAndDotDot)) {
+ const QString path = real(QStringLiteral("/sys/class/rfkill/") + r);
+ const QString how = text(path + QStringLiteral("/hard")) == QLatin1String("1") ? QStringLiteral("hard")
+ : text(path + QStringLiteral("/soft")) == QLatin1String("1") ? QStringLiteral("soft")
+ : QString();
+ rfkills << qMakePair(path, how);
+ }
+
+ // Names, status lines and whatever needs attention.
+ QVariantList out;
+ QList<Dev> done;
+ for (Dev d : std::as_const(list)) {
+ if (d.kind == QLatin1String("hid") && !d.unboundInterface && d.state != QLatin1String("attention")) {
+ continue;
+ }
+ if (d.kind == QLatin1String("hid")) {
+ d.kind = QStringLiteral("usb");
+ }
+ if (d.kind == QLatin1String("usbdrive") && d.blockName.isEmpty() && !d.unboundInterface) {
+ // Mass storage with no disk yet (an empty card reader).
+ d.kind = QStringLiteral("cardreader");
+ }
+
+ const QString rfkill = [&]() {
+ for (const auto &r : std::as_const(rfkills)) {
+ if (under(r.first, d.key) && !r.second.isEmpty()) {
+ return r.second;
+ }
+ }
+ return QString();
+ }();
+ const bool bound = !d.driver.isEmpty();
+
+ // Plain names and icons.
+ static const QHash<QString, QPair<QString, QString>> plain = {
+ {QStringLiteral("graphics"), {QStringLiteral("Graphics"), QStringLiteral("monitor-round")}},
+ {QStringLiteral("wifi"), {QStringLiteral("Wi-Fi"), QStringLiteral("wifi-round")}},
+ {QStringLiteral("ethernet"), {QStringLiteral("Ethernet"), QStringLiteral("ethernet")}},
+ {QStringLiteral("bluetooth"), {QStringLiteral("Bluetooth"), QStringLiteral("bluetooth")}},
+ {QStringLiteral("sound"), {QStringLiteral("Speakers and microphone"), QStringLiteral("volume-round")}},
+ {QStringLiteral("hdmisound"), {QStringLiteral("Sound over HDMI"), QStringLiteral("volume-round")}},
+ {QStringLiteral("camera"), {QStringLiteral("Camera"), QStringLiteral("camera-round")}},
+ {QStringLiteral("fingerprint"), {QStringLiteral("Fingerprint reader"), QStringLiteral("fingerprint")}},
+ {QStringLiteral("storage"), {QStringLiteral("Storage"), QStringLiteral("hard-drive")}},
+ {QStringLiteral("touchpad"), {QStringLiteral("Touchpad"), QStringLiteral("touchpad")}},
+ {QStringLiteral("keyboard"), {QStringLiteral("Keyboard"), QStringLiteral("keyboard")}},
+ {QStringLiteral("keyboardmouse"), {QStringLiteral("Keyboard and mouse"), QStringLiteral("keyboard")}},
+ {QStringLiteral("mouse"), {QStringLiteral("Mouse"), QStringLiteral("mouse")}},
+ {QStringLiteral("touchscreen"), {QStringLiteral("Touchscreen"), QStringLiteral("display")}},
+ {QStringLiteral("pen"), {QStringLiteral("Pen and tablet"), QStringLiteral("pencil")}},
+ {QStringLiteral("controller"), {QStringLiteral("Game controller"), QStringLiteral("games")}},
+ {QStringLiteral("battery"), {QStringLiteral("Battery"), QStringLiteral("battery")}},
+ {QStringLiteral("printer"), {QStringLiteral("Printer"), QStringLiteral("printer-round")}},
+ {QStringLiteral("scanner"), {QStringLiteral("Scanner"), QStringLiteral("printer-round")}},
+ {QStringLiteral("smartcard"), {QStringLiteral("Smart card reader"), QStringLiteral("security-key")}},
+ {QStringLiteral("phone"), {QStringLiteral("Phone or camera"), QStringLiteral("phone")}},
+ {QStringLiteral("usbdrive"), {QStringLiteral("USB drive"), QStringLiteral("usb")}},
+ {QStringLiteral("card"), {QStringLiteral("Memory card"), QStringLiteral("usb")}},
+ {QStringLiteral("cardreader"), {QStringLiteral("Memory card reader"), QStringLiteral("usb")}},
+ {QStringLiteral("usb"), {QStringLiteral("USB device"), QStringLiteral("usb")}},
+ {QStringLiteral("usbctl"), {QStringLiteral("USB controller"), QStringLiteral("usb")}},
+ {QStringLiteral("storagectl"), {QStringLiteral("Storage controller"), QStringLiteral("chip")}},
+ {QStringLiteral("firewire"), {QStringLiteral("FireWire port"), QStringLiteral("plug")}},
+ };
+ if (d.name.isEmpty()) {
+ d.name = plain.value(d.kind).first;
+ if (d.kind == QLatin1String("graphics")) {
+ if (d.virtualHardware) {
+ d.name = QStringLiteral("Virtual graphics");
+ } else if (d.vendorId == QLatin1String("10de")) {
+ d.name = QStringLiteral("NVIDIA graphics card");
+ } else if (d.vendorId == QLatin1String("1002")) {
+ d.name = QStringLiteral("AMD graphics");
+ } else if (d.vendorId == QLatin1String("8086")) {
+ d.name = QStringLiteral("Intel graphics");
+ }
+ } else if (d.kind == QLatin1String("sound") && d.bus == QLatin1String("usb")) {
+ d.name = QStringLiteral("USB audio");
+ } else if (d.kind == QLatin1String("camera") && d.bus == QLatin1String("usb") && !d.builtIn) {
+ d.name = QStringLiteral("Webcam");
+ } else if (d.kind == QLatin1String("wifi") && d.bus == QLatin1String("usb")) {
+ d.name = QStringLiteral("Wi-Fi adapter");
+ } else if (d.kind == QLatin1String("ethernet") && d.bus == QLatin1String("usb")) {
+ d.name = QStringLiteral("Ethernet adapter");
+ }
+ }
+ d.icon = plain.value(d.kind).second;
+ if (d.icon.isEmpty()) {
+ d.icon = QStringLiteral("chip");
+ }
+
+ // The usual line, before any problem replaces it.
+ if (d.line.isEmpty()) {
+ if (d.kind == QLatin1String("wifi") || d.kind == QLatin1String("ethernet")) {
+ if (rfkill == QLatin1String("hard")) {
+ d.line = QStringLiteral("Turned off with a switch or key");
+ } else if (rfkill == QLatin1String("soft")) {
+ d.line = QStringLiteral("Turned off");
+ } else if (!d.netInterface.isEmpty()) {
+ d.line = networkLine(d.netInterface, d.kind == QLatin1String("wifi"),
+ text(QStringLiteral("/sys/class/net/%1/carrier").arg(d.netInterface)) == QLatin1String("1"));
+ }
+ } else if (d.kind == QLatin1String("bluetooth")) {
+ QString hci;
+ for (const QString &h : QDir(QStringLiteral("/sys/class/bluetooth")).entryList({QStringLiteral("hci*")}, QDir::Dirs | QDir::System)) {
+ if (!h.contains(QLatin1Char(':')) && under(real(QStringLiteral("/sys/class/bluetooth/%1/device").arg(h)), d.key)) {
+ hci = h;
+ }
+ }
+ if (rfkill == QLatin1String("hard")) {
+ d.line = QStringLiteral("Turned off with a switch or key");
+ } else if (rfkill == QLatin1String("soft") || (adapters.contains(hci) && !adapters.value(hci).first)) {
+ d.line = QStringLiteral("Turned off");
+ } else if (adapters.contains(hci)) {
+ const int paired = adapters.value(hci).second;
+ d.line = paired == 0 ? QStringLiteral("No devices paired yet")
+ : paired == 1 ? QStringLiteral("1 device paired")
+ : QStringLiteral("%1 devices paired").arg(paired);
+ }
+ } else if (d.kind == QLatin1String("graphics") && d.driver == QLatin1String("nvidia")) {
+ d.line = QStringLiteral("Using NVIDIA's driver");
+ } else if (d.kind == QLatin1String("graphics") && d.driver == QLatin1String("nouveau")) {
+ d.line = QStringLiteral("Using the open driver");
+ } else if (d.kind == QLatin1String("usb")) {
+ d.line = d.model.isEmpty() ? QStringLiteral("Plugged in") : d.model;
+ }
+ if (d.line.isEmpty()) {
+ d.line = d.bus == QLatin1String("bluetooth") ? QStringLiteral("Connected over Bluetooth")
+ : d.builtIn ? QStringLiteral("Built in")
+ : QStringLiteral("Plugged in over USB");
+ }
+ }
+
+ // Is it doing its job?
+ if (bound) {
+ if (d.kind == QLatin1String("graphics") && d.bus == QLatin1String("pci")) {
+ d.functionMissing = !anyUnder(drmCards, d.key);
+ } else if ((d.kind == QLatin1String("wifi") || d.kind == QLatin1String("ethernet")) && d.netInterface.isEmpty()) {
+ d.functionMissing = !anyUnder(netDevices, d.key);
+ } else if (d.kind == QLatin1String("bluetooth")) {
+ d.functionMissing = !anyUnder(hciDevices, d.key);
+ } else if (d.kind == QLatin1String("sound") || d.kind == QLatin1String("hdmisound")) {
+ d.functionMissing = !anyUnder(soundCards, d.key);
+ } else if (d.kind == QLatin1String("camera")) {
+ d.functionMissing = !anyUnder(videoDevices, d.key);
+ } else if (d.kind == QLatin1String("storagectl")) {
+ d.functionMissing = false;
+ }
+ }
+ QStringList firmwareFiles;
+ for (const auto &f : std::as_const(firmware)) {
+ if (under(f.first, d.key) && !f.second.isEmpty() && !firmwareFiles.contains(f.second)) {
+ firmwareFiles << f.second;
+ }
+ }
+ const bool wantsDriver = !bound && (d.bus == QLatin1String("pci") || d.unboundInterface || d.kind == QLatin1String("usb"));
+
+ if (d.state == QLatin1String("attention")) {
+ // Already decided: an unsupported fingerprint reader, a failing drive.
+ } else if (d.kind == QLatin1String("graphics") && d.vendorId == QLatin1String("10de") && d.driver != QLatin1String("nvidia")
+ && QFile::exists(QStringLiteral("/var/lib/dpkg/info/nvidia-driver.list"))) {
+ d.state = QStringLiteral("attention");
+ d.problem = QStringLiteral("NVIDIA's driver is installed and starts after a restart.");
+ d.badge = QStringLiteral("Restart needed");
+ d.action = QStringLiteral("restart");
+ d.actionLabel = QStringLiteral("Restart now");
+ } else if (d.kind == QLatin1String("graphics") && d.vendorId == QLatin1String("10de") && d.driver != QLatin1String("nvidia")
+ && nvidiaSupported(d.productId) && firmwareFiles.isEmpty()) {
+ d.state = QStringLiteral("attention");
+ d.problem = bound && !d.functionMissing ? QStringLiteral("Running on the basic driver, so games and video will be slow.")
+ : QStringLiteral("Running without a driver, so games and video will be slow.");
+ d.badge = QStringLiteral("Needs a driver");
+ d.action = QStringLiteral("graphicsdriver");
+ d.actionLabel = QStringLiteral("Install the driver");
+ } else if ((wantsDriver || d.functionMissing) && !firmwareFiles.isEmpty()) {
+ d.state = QStringLiteral("attention");
+ d.problem = QStringLiteral("Can't start because its firmware is missing.");
+ d.badge = QStringLiteral("Missing firmware");
+ d.action = QStringLiteral("update");
+ d.actionLabel = QStringLiteral("Check for updates");
+ d.extra << QVariantMap{{QStringLiteral("label"), QStringLiteral("Firmware it asked for")}, {QStringLiteral("value"), firmwareFiles.join(QStringLiteral(", "))}};
+ } else if (wantsDriver) {
+ // settings-devices resolves the driver (the kernel's module list
+ // is root's on Wild OS) and says whether something switched it off.
+ const QJsonObject why = unbound.value(d.unboundPath).toObject();
+ const bool known = unbound.contains(d.unboundPath);
+ QStringList modules;
+ for (const QJsonValue &m : why.value(QStringLiteral("modules")).toArray()) {
+ modules << m.toString();
+ }
+ const QString security = why.value(QStringLiteral("security")).toString();
+ const QString blacklist = why.value(QStringLiteral("blacklisted")).toString();
+ if (!security.isEmpty() && blacklist.isEmpty()) {
+ d.state = QStringLiteral("off");
+ d.line = QStringLiteral("Switched off for security");
+ d.badge = QStringLiteral("Off");
+ d.extra << QVariantMap{{QStringLiteral("label"), QStringLiteral("Why it's off")},
+ {QStringLiteral("value"), QStringLiteral("Wild OS keeps its driver, %1, switched off: it is rarely needed and has been used to attack PCs.").arg(security)}};
+ } else if (d.kind == QLatin1String("usb") && modules.isEmpty() && !d.unboundInterface) {
+ // A device apps talk to directly, with no kernel driver to want.
+ } else {
+ d.state = QStringLiteral("attention");
+ d.badge = QStringLiteral("Needs a driver");
+ d.action = QStringLiteral("report");
+ d.actionLabel = QStringLiteral("Report it");
+ if (!blacklist.isEmpty()) {
+ d.problem = QStringLiteral("Its driver is switched off on this PC.");
+ d.extra << QVariantMap{{QStringLiteral("label"), QStringLiteral("Why it's off")},
+ {QStringLiteral("value"), QStringLiteral("Its driver, %1, is blocked in %2.").arg(blacklist, why.value(QStringLiteral("file")).toString())}};
+ } else if (!modules.isEmpty()) {
+ d.problem = QStringLiteral("Its driver didn't start.");
+ d.extra << QVariantMap{{QStringLiteral("label"), QStringLiteral("Driver that should run it")}, {QStringLiteral("value"), modules.join(QStringLiteral(", "))}};
+ } else if (!known) {
+ d.problem = d.kind == QLatin1String("graphics") ? QStringLiteral("No driver is running it, so the screen runs on a basic stand-in.")
+ : QStringLiteral("No driver is running it.");
+ } else if (d.kind == QLatin1String("graphics")) {
+ d.problem = QStringLiteral("Wild OS has no driver for it, so the screen runs on a basic stand-in.");
+ } else {
+ d.problem = QStringLiteral("Wild OS has no driver for it yet.");
+ }
+ }
+ } else if (d.functionMissing) {
+ d.state = QStringLiteral("attention");
+ d.problem = QStringLiteral("Its driver started, but it isn't working.");
+ d.badge = QStringLiteral("Not working");
+ d.action = QStringLiteral("report");
+ d.actionLabel = QStringLiteral("Report it");
+ }
+ done << d;
+ }
+
+ std::stable_sort(done.begin(), done.end(), [](const Dev &a, const Dev &b) {
+ const int ia = kindOrder.indexOf(a.kind);
+ const int ib = kindOrder.indexOf(b.kind);
+ if (ia != ib) {
+ return (ia < 0 ? 999 : ia) < (ib < 0 ? 999 : ib);
+ }
+ return a.first && !b.first;
+ });
+ for (const Dev &d : std::as_const(done)) {
+ out << d.toMap();
+ }
+ return out;
+}
+}
+
+Devices::Devices(QObject *parent)
+ : QObject(parent)
+{
+ qDBusRegisterMetaType<ManagedObjects>();
+ scan();
+}
+
+void Devices::scan()
+{
+ if (m_scanning) {
+ m_again = true;
+ return;
+ }
+ m_scanning = true;
+ Q_EMIT scanningChanged();
+ QPointer<Devices> self(this);
+ QThread *thread = QThread::create([self] {
+ bool answered = false;
+ const QJsonObject root = askRoot(&answered);
+ const QVariantList found = scanAll(root, answered);
+ QMetaObject::invokeMethod(qApp, [self, found, answered] {
+ if (!self) {
+ return;
+ }
+ self->m_devices = found;
+ self->m_ready = true;
+ self->m_healthUnknown = !answered;
+ self->m_scanning = false;
+ Q_EMIT self->devicesChanged();
+ Q_EMIT self->scanningChanged();
+ if (self->m_again) {
+ self->m_again = false;
+ self->scan();
+ }
+ });
+ });
+ connect(thread, &QThread::finished, thread, &QObject::deleteLater);
+ thread->start();
+}
+
+void Devices::allow(const QString &port)
+{
+ static const QRegularExpression valid(QStringLiteral("^\\d+-\\d+(\\.\\d+)*$"));
+ if (!valid.match(port).hasMatch() || !QFile::exists(allowHelper)) {
+ Q_EMIT failed(QStringLiteral("This device couldn't be allowed. Unplug it and try again."));
+ return;
+ }
+ auto *process = new QProcess(this);
+ connect(process, &QProcess::finished, this, [this, process] {
+ process->deleteLater();
+ const QString result = QString::fromUtf8(process->readAllStandardOutput()).trimmed();
+ if (result == QLatin1String("denied")) {
+ Q_EMIT failed(QStringLiteral("Only an administrator can allow USB devices."));
+ } else if (result != QLatin1String("allowed") && result != QLatin1String("cancelled")) {
+ Q_EMIT failed(QStringLiteral("This device couldn't be allowed. Unplug it and try again."));
+ }
+ // Its drivers take a moment to bind once it is let in.
+ QTimer::singleShot(1500, this, &Devices::scan);
+ });
+ process->start(allowHelper, {QStringLiteral("allow"), port});
+}
+
+bool Devices::openBackup() const
+{
+ // Started by name: Exec in org.wildos.backup.desktop, and gtk-launch
+ // isn't in the image.
+ const QString program = QStandardPaths::findExecutable(QStringLiteral("wildos-backup"));
+ return !program.isEmpty() && QProcess::startDetached(program, {});
+}
+
+bool Devices::openReport() const
+{
+ const QString program = QStandardPaths::findExecutable(QStringLiteral("wildos-report"));
+ return !program.isEmpty() && QProcess::startDetached(program, {});
+}
diff --git a/packages/wildos-settings/src/devices.h b/packages/wildos-settings/src/devices.h
new file mode 100644
index 0000000..06dbb1f
--- /dev/null
+++ b/packages/wildos-settings/src/devices.h
@@ -0,0 +1,64 @@
+#pragma once
+
+#include <QObject>
+#include <QQmlEngine>
+#include <QVariantList>
+
+// Settings > System > Devices, Wild OS's Device Manager. Every device a
+// person would recognise (graphics, Wi-Fi, sound, camera, drives, keyboard
+// and so on), each with a plain name, what it is really called, the driver
+// running it and where it is connected, read from sysfs, udev's hardware
+// database and the services that own each kind (NetworkManager, BlueZ).
+//
+// A device needs attention when it has no driver, runs on a stand-in
+// driver where a proper one exists, can't start for lack of firmware, or
+// its drive health check fails. The kernel's log and the drives' health
+// logs are root's, so settings-devices reads those through
+// wildos-devices.socket. Printers and fingerprints come from the Printers
+// and Fingerprint objects in QML, which already watch them.
+class Devices : public QObject
+{
+ Q_OBJECT
+ QML_ELEMENT
+ QML_SINGLETON
+
+ // One map per device, in the order the page lists them:
+ // key, kind, name, icon, line (one line of status), state ("ok",
+ // "attention" or "off"), badge, problem, action ("graphicsdriver",
+ // "update", "report", "backup", "restart", "printers", "allow" or
+ // empty), actionLabel, port (a blocked USB device's),
+ // model, maker, driver, connection, hardwareId, extra ([{label, value}])
+ Q_PROPERTY(QVariantList devices READ devices NOTIFY devicesChanged)
+ Q_PROPERTY(bool scanning READ scanning NOTIFY scanningChanged)
+ // False until the first look has finished.
+ Q_PROPERTY(bool ready READ ready NOTIFY devicesChanged)
+ // Drive health could not be read (settings-devices didn't answer).
+ Q_PROPERTY(bool healthUnknown READ healthUnknown NOTIFY devicesChanged)
+
+public:
+ explicit Devices(QObject *parent = nullptr);
+
+ QVariantList devices() const { return m_devices; }
+ bool scanning() const { return m_scanning; }
+ bool ready() const { return m_ready; }
+ bool healthUnknown() const { return m_healthUnknown; }
+
+ Q_INVOKABLE void scan();
+ // Lets a device USB protection blocked work until it is unplugged, as
+ // the shield's "Allow once" does.
+ Q_INVOKABLE void allow(const QString &port);
+ Q_INVOKABLE bool openReport() const;
+ Q_INVOKABLE bool openBackup() const;
+
+Q_SIGNALS:
+ void devicesChanged();
+ void scanningChanged();
+ void failed(const QString &message);
+
+private:
+ QVariantList m_devices;
+ bool m_scanning = false;
+ bool m_ready = false;
+ bool m_healthUnknown = false;
+ bool m_again = false;
+};
diff --git a/packages/wildos-settings/src/firewall.cpp b/packages/wildos-settings/src/firewall.cpp
new file mode 100644
index 0000000..d9e8f39
--- /dev/null
+++ b/packages/wildos-settings/src/firewall.cpp
@@ -0,0 +1,436 @@
+#include "firewall.h"
+
+#include <KService>
+
+#include <QDBusConnection>
+#include <QDBusMessage>
+#include <QDBusPendingCallWatcher>
+#include <QDBusPendingReply>
+#include <QDateTime>
+#include <QDir>
+#include <QFile>
+#include <QFileInfo>
+#include <QHostAddress>
+#include <QJsonArray>
+#include <QJsonDocument>
+#include <QJsonObject>
+#include <QProcess>
+
+namespace
+{
+const QString helper = QStringLiteral("/usr/libexec/wildos/settings-firewall");
+// Switching the firewall off asks for the password every time.
+const QString offHelper = QStringLiteral("/usr/libexec/wildos/settings-firewall-off");
+const QString configFile = QStringLiteral("/etc/wildos/firewall.json");
+const QString sessionFile = QStringLiteral("/run/wildos/firewall-session.json");
+const QString markFile = QStringLiteral("/run/wildos/firewall");
+const QString logDir = QStringLiteral("/var/lib/wildos/firewall");
+const QString logFile = QStringLiteral("/var/lib/wildos/firewall/blocked.log");
+const QString krdpUnit = QStringLiteral("app-org.kde.krdpserver.service");
+
+// The servers Settings can switch on, as settings-firewall knows them.
+struct Server {
+ const char *name;
+ const char *binary;
+};
+constexpr Server servers[] = {{"ssh", "/usr/sbin/sshd"}, {"files", "/usr/sbin/smbd"}, {"remote", "/usr/bin/krdpserver"}};
+
+// Ports the rows on the page stand for, so the list of apps to allow does
+// not offer them again.
+const QList<QPair<QString, int>> rowPorts{{QStringLiteral("tcp"), 22}, {QStringLiteral("tcp"), 445}, {QStringLiteral("tcp"), 139},
+ {QStringLiteral("tcp"), 3389}, {QStringLiteral("tcp"), 5357}, {QStringLiteral("udp"), 3702},
+ {QStringLiteral("udp"), 1900}, {QStringLiteral("udp"), 5353}, {QStringLiteral("udp"), 137},
+ {QStringLiteral("udp"), 138}};
+
+QJsonObject readObject(const QString &path)
+{
+ QFile file(path);
+ if (!file.open(QIODevice::ReadOnly)) {
+ return {};
+ }
+ return QJsonDocument::fromJson(file.readAll()).object();
+}
+
+QVariantMap ruleMap(const QJsonObject &r, bool session)
+{
+ const qint64 until = r.value(QStringLiteral("until")).toInteger();
+ return {{QStringLiteral("id"), r.value(QStringLiteral("id")).toString()},
+ {QStringLiteral("name"), r.value(QStringLiteral("name")).toString()},
+ {QStringLiteral("port"), r.value(QStringLiteral("port")).toInt()},
+ {QStringLiteral("proto"), r.value(QStringLiteral("proto")).toString()},
+ {QStringLiteral("scope"), r.value(QStringLiteral("scope")).toString()},
+ {QStringLiteral("address"), r.value(QStringLiteral("address")).toString()},
+ {QStringLiteral("until"), until > 0 ? QDateTime::fromSecsSinceEpoch(until) : QDateTime()},
+ {QStringLiteral("on"), r.value(QStringLiteral("on")).toBool(true)},
+ {QStringLiteral("session"), session}};
+}
+
+QString prettyProcess(const QString &process)
+{
+ static const QHash<QString, QString> known{{QStringLiteral("jellyfin"), QStringLiteral("Jellyfin")},
+ {QStringLiteral("syncthing"), QStringLiteral("Syncthing")},
+ {QStringLiteral("kdeconnectd"), QStringLiteral("KDE Connect")},
+ {QStringLiteral("plexmediaserver"), QStringLiteral("Plex Media Server")},
+ {QStringLiteral("java"), QStringLiteral("A Java program")},
+ {QStringLiteral("python3"), QStringLiteral("A Python program")},
+ {QStringLiteral("node"), QStringLiteral("A Node.js program")}};
+ if (known.contains(process)) {
+ return known.value(process);
+ }
+ if (process.isEmpty()) {
+ return QStringLiteral("A system program");
+ }
+ return process.at(0).toUpper() + process.mid(1);
+}
+}
+
+Firewall::Firewall(QObject *parent)
+ : QObject(parent)
+{
+ // Writes come in bursts (the config, then the state), so a change is
+ // read once they settle.
+ m_settle.setSingleShot(true);
+ m_settle.setInterval(150);
+ connect(&m_settle, &QTimer::timeout, this, &Firewall::refresh);
+ connect(&m_watcher, &QFileSystemWatcher::fileChanged, &m_settle, qOverload<>(&QTimer::start));
+ connect(&m_watcher, &QFileSystemWatcher::directoryChanged, &m_settle, qOverload<>(&QTimer::start));
+ refresh();
+}
+
+bool Firewall::available() const
+{
+ return QFileInfo::exists(helper);
+}
+
+void Firewall::watch()
+{
+ const QStringList dirs{QStringLiteral("/etc/wildos"), QStringLiteral("/run/wildos"), logDir};
+ for (const QString &dir : dirs) {
+ if (QFileInfo::exists(dir) && !m_watcher.directories().contains(dir)) {
+ m_watcher.addPath(dir);
+ }
+ }
+ // Appends to the list do not change its folder.
+ if (QFileInfo::exists(logFile) && !m_watcher.files().contains(logFile)) {
+ m_watcher.addPath(logFile);
+ }
+ if (!QFileInfo::exists(logDir) && QFileInfo::exists(QStringLiteral("/var/lib/wildos")) && !m_watcher.directories().contains(QStringLiteral("/var/lib/wildos"))) {
+ m_watcher.addPath(QStringLiteral("/var/lib/wildos"));
+ }
+}
+
+void Firewall::refresh()
+{
+ const QJsonObject cfg = readObject(configFile);
+ m_enabled = cfg.value(QStringLiteral("enabled")).toBool(true);
+ m_discovery = cfg.value(QStringLiteral("discovery")).toBool(true);
+ m_loaded = QFileInfo::exists(markFile);
+
+ m_public.clear();
+ m_home.clear();
+ const QJsonObject nets = cfg.value(QStringLiteral("networks")).toObject();
+ for (auto it = nets.begin(); it != nets.end(); ++it) {
+ if (it.value().toString() == QLatin1String("public")) {
+ m_public.insert(it.key(), true);
+ } else if (it.value().toString() == QLatin1String("home")) {
+ m_home.insert(it.key(), true);
+ }
+ }
+
+ m_services.clear();
+ const QJsonObject chosen = cfg.value(QStringLiteral("services")).toObject();
+ for (const Server &s : servers) {
+ const QString name = QString::fromLatin1(s.name);
+ const bool installed = QFileInfo::exists(QString::fromLatin1(s.binary));
+ QVariantMap state{{QStringLiteral("on"), installed && chosen.value(name).toBool()}, {QStringLiteral("installed"), installed}};
+ if (name == QLatin1String("remote") && state.value(QStringLiteral("on")).toBool()) {
+ state.insert(QStringLiteral("running"),
+ QProcess::execute(QStringLiteral("systemctl"), {QStringLiteral("--user"), QStringLiteral("is-active"), QStringLiteral("--quiet"), krdpUnit}) == 0);
+ }
+ m_services.insert(name, state);
+ }
+
+ m_rules.clear();
+ const qint64 now = QDateTime::currentSecsSinceEpoch();
+ for (const QJsonValue &v : cfg.value(QStringLiteral("rules")).toArray()) {
+ const QJsonObject r = v.toObject();
+ // An hour that has run out, before the service has tidied it away.
+ const qint64 until = r.value(QStringLiteral("until")).toInteger();
+ if (until > 0 && until <= now) {
+ continue;
+ }
+ m_rules.append(ruleMap(r, false));
+ }
+ for (const QJsonValue &v : readObject(sessionFile).value(QStringLiteral("rules")).toArray()) {
+ m_rules.append(ruleMap(v.toObject(), true));
+ }
+
+ readBlocked();
+ watch();
+ Q_EMIT changed();
+}
+
+void Firewall::readBlocked()
+{
+ QVariantList list;
+ QFile file(logFile);
+ if (file.open(QIODevice::ReadOnly)) {
+ const qint64 oldest = QDateTime::currentSecsSinceEpoch() - 7 * 24 * 3600;
+ while (!file.atEnd()) {
+ const QJsonObject o = QJsonDocument::fromJson(file.readLine()).object();
+ const qint64 t = o.value(QStringLiteral("t")).toInteger();
+ if (t < oldest) {
+ continue;
+ }
+ list.prepend(QVariantMap{{QStringLiteral("when"), QDateTime::fromSecsSinceEpoch(t)},
+ {QStringLiteral("source"), o.value(QStringLiteral("src")).toString()},
+ {QStringLiteral("proto"), o.value(QStringLiteral("proto")).toString()},
+ {QStringLiteral("port"), o.value(QStringLiteral("port")).toInt()},
+ {QStringLiteral("kind"), o.value(QStringLiteral("kind")).toString()}});
+ }
+ }
+ std::stable_sort(list.begin(), list.end(), [](const QVariant &a, const QVariant &b) {
+ return a.toMap().value(QStringLiteral("when")).toDateTime() > b.toMap().value(QStringLiteral("when")).toDateTime();
+ });
+ if (list != m_blocked) {
+ m_blocked = list;
+ Q_EMIT blockedChanged();
+ }
+}
+
+void Firewall::refreshListening()
+{
+ QDBusMessage call = QDBusMessage::createMethodCall(QStringLiteral("org.wildos.Network"), QStringLiteral("/org/wildos/Network"),
+ QStringLiteral("org.wildos.Network"), QStringLiteral("Listening"));
+ auto *watcher = new QDBusPendingCallWatcher(QDBusConnection::systemBus().asyncCall(call, 15000), this);
+ connect(watcher, &QDBusPendingCallWatcher::finished, this, [this](QDBusPendingCallWatcher *w) {
+ w->deleteLater();
+ const QDBusPendingReply<QString> reply = *w;
+ QVariantList list;
+ if (!reply.isError()) {
+ for (const QJsonValue &v : QJsonDocument::fromJson(reply.value().toUtf8()).array()) {
+ const QJsonObject o = v.toObject();
+ const int port = o.value(QStringLiteral("port")).toInt();
+ const QString proto = o.value(QStringLiteral("proto")).toString();
+ if (allowed(port, proto) || rowPorts.contains(qMakePair(proto, port))) {
+ continue;
+ }
+ QString name;
+ const QString app = o.value(QStringLiteral("app")).toString();
+ if (!app.isEmpty()) {
+ KService::Ptr service = KService::serviceByDesktopName(app);
+ if (!service) {
+ service = KService::serviceByStorageId(app + QStringLiteral(".desktop"));
+ }
+ if (service && !service->name().isEmpty()) {
+ name = service->name();
+ }
+ }
+ if (name.isEmpty()) {
+ name = prettyProcess(o.value(QStringLiteral("process")).toString());
+ }
+ list.append(QVariantMap{{QStringLiteral("name"), name}, {QStringLiteral("port"), port}, {QStringLiteral("proto"), proto}});
+ }
+ }
+ std::sort(list.begin(), list.end(), [](const QVariant &a, const QVariant &b) {
+ return a.toMap().value(QStringLiteral("port")).toInt() < b.toMap().value(QStringLiteral("port")).toInt();
+ });
+ m_listening = list;
+ Q_EMIT listeningChanged();
+ });
+}
+
+bool Firewall::allowed(int port, const QString &proto) const
+{
+ for (const QVariant &v : m_rules) {
+ const QVariantMap r = v.toMap();
+ const QString p = r.value(QStringLiteral("proto")).toString();
+ if (r.value(QStringLiteral("port")).toInt() == port && (p == proto || p == QLatin1String("both")) && r.value(QStringLiteral("on")).toBool()) {
+ return true;
+ }
+ }
+ return false;
+}
+
+QString Firewall::serviceName(int port, const QString &proto) const
+{
+ const bool udp = proto == QLatin1String("udp");
+ switch (port) {
+ case 21:
+ return udp ? QString() : QStringLiteral("File transfer (FTP)");
+ case 22:
+ return udp ? QString() : QStringLiteral("SSH");
+ case 23:
+ return udp ? QString() : QStringLiteral("Telnet");
+ case 25:
+ return udp ? QString() : QStringLiteral("Mail server");
+ case 53:
+ return QStringLiteral("Name lookups (DNS)");
+ case 80:
+ case 443:
+ case 8080:
+ return QStringLiteral("Web server");
+ case 137:
+ case 138:
+ case 139:
+ case 445:
+ return QStringLiteral("File sharing");
+ case 548:
+ return udp ? QString() : QStringLiteral("File sharing (Mac)");
+ case 631:
+ return QStringLiteral("Printing");
+ case 1194:
+ return QStringLiteral("OpenVPN");
+ case 1900:
+ case 3702:
+ case 5353:
+ case 5357:
+ return QStringLiteral("Device discovery");
+ case 3389:
+ return QStringLiteral("Remote Desktop");
+ case 5900:
+ return udp ? QString() : QStringLiteral("Screen sharing (VNC)");
+ case 8096:
+ return QStringLiteral("Media server");
+ case 22000:
+ return QStringLiteral("File sync");
+ case 25565:
+ return QStringLiteral("Game server");
+ case 51820:
+ return udp ? QStringLiteral("WireGuard") : QString();
+ default:
+ return port >= 1714 && port <= 1764 ? QStringLiteral("KDE Connect") : QString();
+ }
+}
+
+QString Firewall::checkAddress(const QString &address) const
+{
+ const QString text = address.trimmed();
+ if (text.isEmpty()) {
+ return QStringLiteral("Give the device's address.");
+ }
+ const QHostAddress a(text);
+ if (a.isNull()) {
+ return QStringLiteral("That isn't an address. It looks like 192.168.1.24.");
+ }
+ if (a.isLoopback() || a.isMulticast() || a == QHostAddress(QHostAddress::AnyIPv4) || a == QHostAddress(QHostAddress::AnyIPv6)) {
+ return QStringLiteral("That address can't be another device.");
+ }
+ return {};
+}
+
+void Firewall::readOutput()
+{
+ while (m_process && m_process->canReadLine()) {
+ const QString line = QString::fromUtf8(m_process->readLine()).trimmed();
+ if (line.startsWith(QLatin1String("progress "))) {
+ m_progress = line.mid(9).toInt();
+ Q_EMIT busyChanged();
+ } else if (line.startsWith(QLatin1String("step "))) {
+ m_step = line.mid(5);
+ Q_EMIT busyChanged();
+ } else if (!line.isEmpty()) {
+ m_lastLine = line;
+ }
+ }
+}
+
+void Firewall::run(const QStringList &args, const QString &what, const QString &program)
+{
+ if (m_process) {
+ return;
+ }
+ m_busyWhat = what;
+ m_progress = -1;
+ m_step.clear();
+ m_lastLine.clear();
+ m_process = new QProcess(this);
+ m_process->setProcessChannelMode(QProcess::MergedChannels);
+ connect(m_process, &QProcess::readyRead, this, &Firewall::readOutput);
+ connect(m_process, &QProcess::finished, this, [this, args, what](int code, QProcess::ExitStatus status) {
+ readOutput();
+ const QString last = m_lastLine;
+ m_process->deleteLater();
+ m_process = nullptr;
+ const bool ok = status == QProcess::NormalExit && code == 0;
+ // Remote Desktop runs in the person's own session, so its service is
+ // theirs to start.
+ if (ok && what == QLatin1String("remote")) {
+ const bool on = args.value(2) == QLatin1String("on");
+ QProcess::execute(QStringLiteral("systemctl"), {QStringLiteral("--user"), on ? QStringLiteral("enable") : QStringLiteral("disable"),
+ QStringLiteral("--now"), krdpUnit});
+ // It stops again within a moment when no account can sign in yet.
+ QTimer::singleShot(3000, this, &Firewall::refresh);
+ }
+ m_busyWhat.clear();
+ Q_EMIT busyChanged();
+ refresh();
+ if (ok) {
+ Q_EMIT done(what);
+ } else if (status != QProcess::NormalExit || (code != 126 && code != 127)) {
+ // 126 and 127: the password prompt was dismissed, which needs no
+ // message.
+ Q_EMIT failed(last.isEmpty() ? QStringLiteral("Something went wrong. Nothing was changed.") : last);
+ }
+ });
+ Q_EMIT busyChanged();
+ m_process->start(QStringLiteral("pkexec"), QStringList{program.isEmpty() ? helper : program} + args);
+}
+
+void Firewall::setEnabled(bool on)
+{
+ if (on) {
+ run({QStringLiteral("enabled"), QStringLiteral("on")}, QStringLiteral("enabled"));
+ } else {
+ run({}, QStringLiteral("enabled"), offHelper);
+ }
+}
+
+void Firewall::setPublic(const QString &uuid, bool isPublic)
+{
+ run({QStringLiteral("trust"), uuid, isPublic ? QStringLiteral("public") : QStringLiteral("home")}, QStringLiteral("trust"));
+}
+
+void Firewall::setDiscovery(bool on)
+{
+ run({QStringLiteral("discovery"), on ? QStringLiteral("on") : QStringLiteral("off")}, QStringLiteral("discovery"));
+}
+
+void Firewall::setService(const QString &name, bool on)
+{
+ if (name != QLatin1String("ssh") && name != QLatin1String("files") && name != QLatin1String("remote")) {
+ return;
+ }
+ run({QStringLiteral("service"), name, on ? QStringLiteral("on") : QStringLiteral("off")}, name);
+}
+
+void Firewall::allow(const QString &name, int port, const QString &proto, const QString &scope, const QString &address, const QString &duration)
+{
+ run({QStringLiteral("allow"), name, QString::number(port), proto, scope, address.trimmed().isEmpty() ? QStringLiteral("-") : address.trimmed(),
+ duration},
+ QStringLiteral("allow"));
+}
+
+void Firewall::setRuleOn(const QString &id, bool on)
+{
+ run({QStringLiteral("rule"), id, on ? QStringLiteral("on") : QStringLiteral("off")}, id);
+}
+
+void Firewall::removeRule(const QString &id)
+{
+ run({QStringLiteral("remove"), id}, id);
+}
+
+void Firewall::clearBlocked()
+{
+ QDBusMessage call = QDBusMessage::createMethodCall(QStringLiteral("org.wildos.Network"), QStringLiteral("/org/wildos/Network"),
+ QStringLiteral("org.wildos.Network"), QStringLiteral("ClearBlocked"));
+ auto *watcher = new QDBusPendingCallWatcher(QDBusConnection::systemBus().asyncCall(call), this);
+ connect(watcher, &QDBusPendingCallWatcher::finished, this, [this](QDBusPendingCallWatcher *w) {
+ w->deleteLater();
+ if (w->isError()) {
+ Q_EMIT failed(QStringLiteral("The list could not be cleared. ") + w->error().message());
+ }
+ readBlocked();
+ });
+}
diff --git a/packages/wildos-settings/src/firewall.h b/packages/wildos-settings/src/firewall.h
new file mode 100644
index 0000000..31abfb2
--- /dev/null
+++ b/packages/wildos-settings/src/firewall.h
@@ -0,0 +1,123 @@
+#pragma once
+
+#include <QFileSystemWatcher>
+#include <QObject>
+#include <QQmlEngine>
+#include <QTimer>
+#include <QVariantList>
+#include <QVariantMap>
+
+class QProcess;
+
+// Settings > Privacy and security > Firewall. Reads the choices the root
+// helper settings-firewall keeps (/etc/wildos/firewall.json, rules that last
+// until a restart in /run), what it last loaded, and the list of blocked
+// connections wildos-network keeps; asks for every change through the
+// helper, behind the admin password.
+class Firewall : public QObject
+{
+ Q_OBJECT
+ QML_ELEMENT
+ QML_SINGLETON
+
+ Q_PROPERTY(bool available READ available CONSTANT)
+ Q_PROPERTY(bool enabled READ enabled NOTIFY changed)
+ // The rules are in place (settings-firewall's mark); false while on
+ // means they failed to load.
+ Q_PROPERTY(bool loaded READ loaded NOTIFY changed)
+ Q_PROPERTY(bool discovery READ discovery NOTIFY changed)
+ // Connection uuids marked public, and those marked home. A network in
+ // neither has not been chosen yet: only discovery is let in there.
+ Q_PROPERTY(QVariantMap publicNetworks READ publicNetworks NOTIFY changed)
+ Q_PROPERTY(QVariantMap homeNetworks READ homeNetworks NOTIFY changed)
+ // ssh, files, remote: {on, installed}; remote also {running}, KRdp's
+ // server being up in this session (it stops until an account is added).
+ Q_PROPERTY(QVariantMap services READ services NOTIFY changed)
+ // Rules the person added, oldest first: {id, name, port, proto, scope,
+ // address, until (date, invalid when none), on, session}.
+ Q_PROPERTY(QVariantList rules READ rules NOTIFY changed)
+ // Newest first: {when (date), source, proto, port, kind}, kind being
+ // router, local, internet or other.
+ Q_PROPERTY(QVariantList blocked READ blocked NOTIFY blockedChanged)
+ // Programs waiting for connections that the firewall turns away:
+ // {name, port, proto}.
+ Q_PROPERTY(QVariantList listening READ listening NOTIFY listeningChanged)
+ Q_PROPERTY(bool busy READ busy NOTIFY busyChanged)
+ // What is being changed: "enabled", "trust", "discovery", "ssh",
+ // "files", "remote", "allow", or a rule id.
+ Q_PROPERTY(QString busyWhat READ busyWhat NOTIFY busyChanged)
+ // While a server installs: 0 to 100, or -1 before apt says.
+ Q_PROPERTY(int progress READ progress NOTIFY busyChanged)
+ Q_PROPERTY(QString step READ step NOTIFY busyChanged)
+
+public:
+ explicit Firewall(QObject *parent = nullptr);
+
+ bool available() const;
+ bool enabled() const { return m_enabled; }
+ bool loaded() const { return m_loaded; }
+ bool discovery() const { return m_discovery; }
+ QVariantMap publicNetworks() const { return m_public; }
+ QVariantMap homeNetworks() const { return m_home; }
+ QVariantMap services() const { return m_services; }
+ QVariantList rules() const { return m_rules; }
+ QVariantList blocked() const { return m_blocked; }
+ QVariantList listening() const { return m_listening; }
+ bool busy() const { return m_process != nullptr; }
+ QString busyWhat() const { return m_busyWhat; }
+ int progress() const { return m_progress; }
+ QString step() const { return m_step; }
+
+ Q_INVOKABLE void refresh();
+ Q_INVOKABLE void refreshListening();
+ Q_INVOKABLE void setEnabled(bool on);
+ Q_INVOKABLE void setPublic(const QString &uuid, bool isPublic);
+ Q_INVOKABLE void setDiscovery(bool on);
+ // ssh, files or remote. The first time on, the server is downloaded.
+ Q_INVOKABLE void setService(const QString &name, bool on);
+ // scope network, device or anyone; duration forever, restart or hour.
+ Q_INVOKABLE void allow(const QString &name, int port, const QString &proto, const QString &scope, const QString &address,
+ const QString &duration);
+ Q_INVOKABLE void setRuleOn(const QString &id, bool on);
+ Q_INVOKABLE void removeRule(const QString &id);
+ Q_INVOKABLE void clearBlocked();
+ // Empty when the address is fine, otherwise why not, in words.
+ Q_INVOKABLE QString checkAddress(const QString &address) const;
+ // What usually waits on a port ("SSH", "Remote Desktop"), or "".
+ Q_INVOKABLE QString serviceName(int port, const QString &proto) const;
+ // A row that already lets the port in, or a rule that does.
+ Q_INVOKABLE bool allowed(int port, const QString &proto) const;
+
+Q_SIGNALS:
+ void changed();
+ void blockedChanged();
+ void listeningChanged();
+ void busyChanged();
+ // A change did not happen; the reason, in words.
+ void failed(const QString &message);
+ // A change went through.
+ void done(const QString &what);
+
+private:
+ void run(const QStringList &args, const QString &what, const QString &program = {});
+ void readBlocked();
+ void watch();
+ void readOutput();
+
+ QFileSystemWatcher m_watcher;
+ QTimer m_settle;
+ QProcess *m_process = nullptr;
+ QString m_busyWhat;
+ int m_progress = -1;
+ QString m_step;
+ QString m_lastLine;
+ bool m_enabled = true;
+ bool m_loaded = false;
+ bool m_discovery = true;
+ QVariantMap m_public;
+ QVariantMap m_home;
+ QVariantMap m_services;
+ QVariantList m_rules;
+ QVariantList m_blocked;
+ QVariantList m_listening;
+};
diff --git a/packages/wildos-settings/src/freespace.cpp b/packages/wildos-settings/src/freespace.cpp
new file mode 100644
index 0000000..3369385
--- /dev/null
+++ b/packages/wildos-settings/src/freespace.cpp
@@ -0,0 +1,189 @@
+#include "freespace.h"
+
+#include <QDir>
+#include <QFile>
+#include <QFileInfo>
+#include <QJsonArray>
+#include <QJsonDocument>
+#include <QJsonObject>
+#include <QProcess>
+#include <QSaveFile>
+#include <QStandardPaths>
+#include <QStorageInfo>
+
+namespace
+{
+const QString helper = QStringLiteral("/usr/libexec/wildos/settings-free-space");
+const QString timer = QStringLiteral("wildos-free-space.timer");
+// The items settings-free-space clears as root; the rest are the person's.
+const QStringList systemItems = {QStringLiteral("restorePoints"), QStringLiteral("updates"), QStringLiteral("leftovers"),
+ QStringLiteral("winmode")};
+
+QString prefsPath()
+{
+ return QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation) + QStringLiteral("/wildos/free-space.json");
+}
+}
+
+FreeSpace::FreeSpace(QObject *parent)
+ : QObject(parent)
+{
+ readDisk();
+ readPrefs();
+}
+
+void FreeSpace::readDisk()
+{
+ // root() hands back a copy made once; without refresh() the free space
+ // would not change after clearing.
+ QStorageInfo root = QStorageInfo::root();
+ root.refresh();
+ m_diskTotal = double(root.bytesTotal());
+ m_diskFree = double(root.bytesAvailable());
+}
+
+void FreeSpace::readPrefs()
+{
+ QFile file(prefsPath());
+ const QJsonObject prefs = file.open(QIODevice::ReadOnly) ? QJsonDocument::fromJson(file.readAll()).object() : QJsonObject();
+ m_hasSavedItems = prefs.contains(QStringLiteral("items"));
+ m_savedItems.clear();
+ for (const QJsonValue &v : prefs.value(QStringLiteral("items")).toArray()) {
+ m_savedItems << v.toString();
+ }
+ m_autoOn = prefs.value(QStringLiteral("auto")).toBool();
+ Q_EMIT prefsChanged();
+}
+
+void FreeSpace::writePrefs()
+{
+ QDir().mkpath(QFileInfo(prefsPath()).absolutePath());
+ QSaveFile file(prefsPath());
+ if (!file.open(QIODevice::WriteOnly)) {
+ return;
+ }
+ QJsonObject prefs;
+ prefs[QStringLiteral("auto")] = m_autoOn;
+ prefs[QStringLiteral("items")] = QJsonArray::fromStringList(m_savedItems);
+ file.write(QJsonDocument(prefs).toJson());
+ file.commit();
+}
+
+QStringList FreeSpace::systemPart(const QStringList &items)
+{
+ QStringList out;
+ for (const QString &i : systemItems) {
+ if (items.contains(i)) {
+ out << i;
+ }
+ }
+ return out;
+}
+
+void FreeSpace::measure()
+{
+ if (m_pending > 0 || m_cleaning) {
+ return;
+ }
+ readDisk();
+ m_pending = 2;
+ Q_EMIT changed();
+ start(QStringLiteral("pkexec"), {helper, QStringLiteral("measure")}, true);
+ start(helper, {QStringLiteral("measure-home")}, false);
+}
+
+void FreeSpace::start(const QString &program, const QStringList &args, bool system)
+{
+ auto process = new QProcess(this);
+ // stderr is only for people running it by hand; the JSON is on stdout.
+ process->setProcessChannelMode(QProcess::SeparateChannels);
+ connect(process, &QProcess::finished, this, [this, process, system](int code, QProcess::ExitStatus status) {
+ const QJsonDocument doc = QJsonDocument::fromJson(process->readAllStandardOutput());
+ process->deleteLater();
+ const bool ok = status == QProcess::NormalExit && code == 0 && doc.isObject();
+ if (system) {
+ m_system = ok ? doc.object().toVariantMap() : QVariantMap();
+ m_systemFailed = !ok;
+ } else {
+ m_home = ok ? doc.object().toVariantMap() : QVariantMap();
+ }
+ --m_pending;
+ Q_EMIT changed();
+ });
+ // A program that never starts never finishes either.
+ connect(process, &QProcess::errorOccurred, this, [this, process, system](QProcess::ProcessError error) {
+ if (error != QProcess::FailedToStart) {
+ return;
+ }
+ process->deleteLater();
+ if (system) {
+ m_system.clear();
+ m_systemFailed = true;
+ } else {
+ m_home.clear();
+ }
+ --m_pending;
+ Q_EMIT changed();
+ });
+ process->start(program, args);
+}
+
+void FreeSpace::clean(const QStringList &items, const QStringList &downloads)
+{
+ if (m_cleaning || m_pending > 0 || items.isEmpty()) {
+ return;
+ }
+ QStringList args{QStringLiteral("run")};
+ args << items;
+ for (const QString &path : downloads) {
+ args << QStringLiteral("--download") << path;
+ }
+ m_cleaning = true;
+ Q_EMIT changed();
+ auto process = new QProcess(this);
+ process->setProcessChannelMode(QProcess::SeparateChannels);
+ connect(process, &QProcess::finished, this, [this, process](int, QProcess::ExitStatus) {
+ const QVariantMap result = QJsonDocument::fromJson(process->readAllStandardOutput()).object().toVariantMap();
+ process->deleteLater();
+ m_cleaning = false;
+ Q_EMIT changed();
+ Q_EMIT cleaned(result);
+ measure();
+ });
+ process->start(helper, args);
+}
+
+void FreeSpace::saveItems(const QStringList &items)
+{
+ const QStringList before = systemPart(m_savedItems);
+ m_savedItems = items;
+ m_hasSavedItems = true;
+ writePrefs();
+ Q_EMIT prefsChanged();
+ // Tidy up automatically clears what is ticked, so its stored system
+ // items follow the ticks; that takes the password again (kept for a
+ // few minutes after the last time).
+ if (m_autoOn && systemPart(items) != before) {
+ QProcess::startDetached(QStringLiteral("pkexec"), QStringList{helper, QStringLiteral("set-auto")} + systemPart(items));
+ }
+}
+
+void FreeSpace::setAuto(bool on, const QStringList &items)
+{
+ auto process = new QProcess(this);
+ connect(process, &QProcess::finished, this, [this, process, on, items](int code, QProcess::ExitStatus status) {
+ process->deleteLater();
+ if (status == QProcess::NormalExit && code == 0) {
+ m_autoOn = on;
+ m_savedItems = items;
+ m_hasSavedItems = true;
+ writePrefs();
+ QProcess::startDetached(QStringLiteral("systemctl"),
+ {QStringLiteral("--user"), on ? QStringLiteral("enable") : QStringLiteral("disable"),
+ QStringLiteral("--now"), timer});
+ }
+ // Also when the password was not given, so the switch goes back.
+ Q_EMIT prefsChanged();
+ });
+ process->start(QStringLiteral("pkexec"), QStringList{helper, QStringLiteral("set-auto")} + (on ? systemPart(items) : QStringList()));
+}
diff --git a/packages/wildos-settings/src/freespace.h b/packages/wildos-settings/src/freespace.h
new file mode 100644
index 0000000..0a22971
--- /dev/null
+++ b/packages/wildos-settings/src/freespace.h
@@ -0,0 +1,81 @@
+#pragma once
+
+#include <QObject>
+#include <QQmlEngine>
+#include <QStringList>
+#include <QVariantMap>
+
+class QProcess;
+
+// System > Storage > Free up space: what each item would give back, and
+// clearing it. Measuring and clearing are settings-free-space's: its system
+// half as root through pkexec, its home half as the person.
+class FreeSpace : public QObject
+{
+ Q_OBJECT
+ QML_ELEMENT
+ QML_SINGLETON
+
+ Q_PROPERTY(bool measuring READ measuring NOTIFY changed)
+ Q_PROPERTY(bool cleaning READ cleaning NOTIFY changed)
+ // Each half's JSON, as settings-free-space prints it. Empty until
+ // measured, or when that half failed.
+ Q_PROPERTY(QVariantMap system READ system NOTIFY changed)
+ Q_PROPERTY(QVariantMap home READ home NOTIFY changed)
+ Q_PROPERTY(bool systemFailed READ systemFailed NOTIFY changed)
+ // The disk the system is on.
+ Q_PROPERTY(double diskTotal READ diskTotal NOTIFY changed)
+ Q_PROPERTY(double diskFree READ diskFree NOTIFY changed)
+ // The person's ticks (never Downloads, which is chosen in Review each
+ // time) and Tidy up automatically, from ~/.config/wildos/free-space.json.
+ Q_PROPERTY(bool hasSavedItems READ hasSavedItems NOTIFY prefsChanged)
+ Q_PROPERTY(QStringList savedItems READ savedItems NOTIFY prefsChanged)
+ Q_PROPERTY(bool autoOn READ autoOn NOTIFY prefsChanged)
+
+public:
+ explicit FreeSpace(QObject *parent = nullptr);
+
+ bool measuring() const { return m_pending > 0; }
+ bool cleaning() const { return m_cleaning; }
+ QVariantMap system() const { return m_system; }
+ QVariantMap home() const { return m_home; }
+ bool systemFailed() const { return m_systemFailed; }
+ double diskTotal() const { return m_diskTotal; }
+ double diskFree() const { return m_diskFree; }
+ bool hasSavedItems() const { return m_hasSavedItems; }
+ QStringList savedItems() const { return m_savedItems; }
+ bool autoOn() const { return m_autoOn; }
+
+ Q_INVOKABLE void measure();
+ // Clears the ticked items; downloads are the paths ticked in Review.
+ Q_INVOKABLE void clean(const QStringList &items, const QStringList &downloads);
+ Q_INVOKABLE void saveItems(const QStringList &items);
+ // Asks for the password to store which system items it may clear,
+ // then switches the person's timer on or off.
+ Q_INVOKABLE void setAuto(bool on, const QStringList &items);
+
+Q_SIGNALS:
+ void changed();
+ void prefsChanged();
+ // settings-free-space run's JSON: {items: {item: {freed, removed,
+ // skipped}}, freed}, or {cancelled: true}.
+ void cleaned(const QVariantMap &result);
+
+private:
+ void start(const QString &program, const QStringList &args, bool system);
+ void readDisk();
+ void readPrefs();
+ void writePrefs();
+ static QStringList systemPart(const QStringList &items);
+
+ int m_pending = 0;
+ bool m_cleaning = false;
+ QVariantMap m_system;
+ QVariantMap m_home;
+ bool m_systemFailed = false;
+ double m_diskTotal = 0;
+ double m_diskFree = 0;
+ bool m_hasSavedItems = false;
+ QStringList m_savedItems;
+ bool m_autoOn = false;
+};
diff --git a/packages/wildos-settings/src/history.cpp b/packages/wildos-settings/src/history.cpp
new file mode 100644
index 0000000..44b2441
--- /dev/null
+++ b/packages/wildos-settings/src/history.cpp
@@ -0,0 +1,292 @@
+#include "history.h"
+
+#include <QDateTime>
+#include <QDir>
+#include <QFile>
+#include <QFileInfo>
+#include <QJsonArray>
+#include <QJsonDocument>
+#include <QJsonObject>
+#include <QLocalSocket>
+#include <QProcess>
+#include <QSaveFile>
+#include <QStandardPaths>
+
+#include <unistd.h>
+
+namespace
+{
+const QString dir = QStringLiteral("/var/lib/wildos/history");
+const QString socketPath = QStringLiteral("/run/wildos-history.sock");
+constexpr qint64 keepSeconds = 30 * 24 * 3600;
+
+QString backupHistory()
+{
+ return QStandardPaths::writableLocation(QStandardPaths::GenericStateLocation) + QStringLiteral("/wildos-backup/history.json");
+}
+
+QVariantMap techLine(const QDateTime &when, const QString &source, const QString &text)
+{
+ return {{QStringLiteral("when"), when}, {QStringLiteral("source"), source}, {QStringLiteral("text"), text}};
+}
+}
+
+History::History(QObject *parent)
+ : QObject(parent)
+{
+ // The collector writes several files in one go; one read after it.
+ m_settle.setSingleShot(true);
+ m_settle.setInterval(300);
+ connect(&m_settle, &QTimer::timeout, this, &History::load);
+ connect(&m_watcher, &QFileSystemWatcher::directoryChanged, &m_settle, qOverload<>(&QTimer::start));
+ connect(&m_watcher, &QFileSystemWatcher::fileChanged, &m_settle, qOverload<>(&QTimer::start));
+ m_timeout.setSingleShot(true);
+ m_timeout.setInterval(20000);
+ connect(&m_timeout, &QTimer::timeout, this, [this]() {
+ if (m_socket) {
+ m_reply = QStringLiteral("error It took too long.");
+ m_socket->abort();
+ }
+ });
+ load();
+}
+
+void History::refresh()
+{
+ if (m_socket) {
+ return;
+ }
+ m_loading = true;
+ Q_EMIT loadingChanged();
+ m_reply.clear();
+ m_socket = new QLocalSocket(this);
+ connect(m_socket, &QLocalSocket::readyRead, this, [this]() {
+ m_reply += QString::fromUtf8(m_socket->readAll());
+ });
+ const auto finish = [this]() {
+ if (!m_socket) {
+ return;
+ }
+ m_socket->deleteLater();
+ m_socket = nullptr;
+ m_timeout.stop();
+ m_loading = false;
+ Q_EMIT loadingChanged();
+ load();
+ };
+ connect(m_socket, &QLocalSocket::disconnected, this, finish);
+ connect(m_socket, &QLocalSocket::errorOccurred, this, [this, finish](QLocalSocket::LocalSocketError error) {
+ if (error != QLocalSocket::PeerClosedError && m_reply.isEmpty()) {
+ m_reply = QStringLiteral("error ") + m_socket->errorString();
+ }
+ finish();
+ });
+ m_timeout.start();
+ m_socket->connectToServer(socketPath);
+}
+
+void History::readFile(const QString &path, QVariantList &into, bool *readable)
+{
+ QFile file(path);
+ if (!file.open(QIODevice::ReadOnly)) {
+ *readable = false;
+ return;
+ }
+ const qint64 oldest = QDateTime::currentSecsSinceEpoch() - keepSeconds;
+ while (!file.atEnd()) {
+ const QJsonObject o = QJsonDocument::fromJson(file.readLine()).object();
+ const double t = o.value(QStringLiteral("t")).toDouble();
+ if (o.isEmpty() || t < oldest) {
+ continue;
+ }
+ QVariantList tech;
+ for (const QJsonValue &v : o.value(QStringLiteral("tech")).toArray()) {
+ const QJsonArray line = v.toArray();
+ tech.append(techLine(QDateTime::fromMSecsSinceEpoch(qint64(line.at(0).toDouble() * 1000)), line.at(1).toString(), line.at(2).toString()));
+ }
+ into.append(QVariantMap{{QStringLiteral("id"), o.value(QStringLiteral("id")).toString()},
+ {QStringLiteral("when"), QDateTime::fromMSecsSinceEpoch(qint64(t * 1000))},
+ {QStringLiteral("kind"), o.value(QStringLiteral("kind")).toString()},
+ {QStringLiteral("data"), o.value(QStringLiteral("data")).toObject().toVariantMap()},
+ {QStringLiteral("tech"), tech}});
+ }
+}
+
+// Backup keeps its own runs in the home folder, where the root collector
+// has no business reading.
+void History::readBackups(QVariantList &into)
+{
+ QFile file(backupHistory());
+ if (!file.open(QIODevice::ReadOnly)) {
+ return;
+ }
+ const QDateTime oldest = QDateTime::currentDateTime().addSecs(-keepSeconds);
+ for (const QJsonValue &v : QJsonDocument::fromJson(file.readAll()).array()) {
+ const QJsonObject o = v.toObject();
+ const QDateTime at = QDateTime::fromString(o.value(QStringLiteral("at")).toString(), Qt::ISODate);
+ QDateTime finished = QDateTime::fromString(o.value(QStringLiteral("finished")).toString(), Qt::ISODate);
+ if (!at.isValid() || at < oldest) {
+ continue;
+ }
+ if (!finished.isValid()) {
+ finished = at;
+ }
+ const QString result = o.value(QStringLiteral("result")).toString();
+ const QString drive = o.value(QStringLiteral("driveName")).toString();
+ const int files = o.value(QStringLiteral("filesNew")).toInt() + o.value(QStringLiteral("filesChanged")).toInt();
+ QVariantList tech;
+ tech.append(techLine(at, QStringLiteral("wildos-backup"),
+ QStringLiteral("%1 backup started, to %2").arg(o.value(QStringLiteral("kind")).toString(QStringLiteral("scheduled")),
+ drive.isEmpty() ? QStringLiteral("the backup drive") : drive)));
+ if (result == QLatin1String("done")) {
+ tech.append(techLine(finished, QStringLiteral("wildos-backup"),
+ QStringLiteral("%1 new, %2 changed, %3 bytes added, snapshot %4")
+ .arg(o.value(QStringLiteral("filesNew")).toInt())
+ .arg(o.value(QStringLiteral("filesChanged")).toInt())
+ .arg(qint64(o.value(QStringLiteral("dataAdded")).toDouble()))
+ .arg(o.value(QStringLiteral("snapshot")).toString().left(8))));
+ }
+ if (!o.value(QStringLiteral("reason")).toString().isEmpty()) {
+ tech.append(techLine(finished, QStringLiteral("wildos-backup"), o.value(QStringLiteral("reason")).toString()));
+ }
+ if (!o.value(QStringLiteral("warning")).toString().isEmpty()) {
+ tech.append(techLine(finished, QStringLiteral("wildos-backup"), o.value(QStringLiteral("warning")).toString()));
+ }
+ tech.append(techLine(finished, QStringLiteral("wildos-backup"), QStringLiteral("finished: ") + result));
+ QVariantMap data{{QStringLiteral("result"), result},
+ {QStringLiteral("drive"), drive},
+ {QStringLiteral("files"), files},
+ {QStringLiteral("reason"), o.value(QStringLiteral("reason")).toString()},
+ {QStringLiteral("warning"), o.value(QStringLiteral("warning")).toString()},
+ {QStringLiteral("how"), o.value(QStringLiteral("kind")).toString()}};
+ into.append(QVariantMap{{QStringLiteral("id"), QStringLiteral("backup-") + o.value(QStringLiteral("at")).toString()},
+ {QStringLiteral("when"), finished},
+ {QStringLiteral("kind"), QStringLiteral("backup")},
+ {QStringLiteral("data"), data},
+ {QStringLiteral("tech"), tech}});
+ }
+}
+
+void History::load()
+{
+ QVariantList list;
+ bool systemReadable = true;
+ bool ownReadable = true;
+ readFile(dir + QStringLiteral("/system.jsonl"), list, &systemReadable);
+ const QString own = dir + QStringLiteral("/user-%1.jsonl").arg(getuid());
+ // An account with nothing of its own yet has no file.
+ if (QFileInfo::exists(own)) {
+ readFile(own, list, &ownReadable);
+ }
+ readBackups(list);
+ std::stable_sort(list.begin(), list.end(), [](const QVariant &a, const QVariant &b) {
+ return a.toMap().value(QStringLiteral("when")).toDateTime() > b.toMap().value(QStringLiteral("when")).toDateTime();
+ });
+
+ QFile statusFile(dir + QStringLiteral("/status.json"));
+ QJsonObject status;
+ if (statusFile.open(QIODevice::ReadOnly)) {
+ status = QJsonDocument::fromJson(statusFile.readAll()).object();
+ }
+ QString problem;
+ QString detail;
+ const bool collectorMissing = !QFileInfo::exists(dir) && !QFileInfo::exists(socketPath);
+ if (collectorMissing || (!systemReadable && QFileInfo::exists(dir + QStringLiteral("/system.jsonl")))) {
+ problem = QStringLiteral("unreadable");
+ detail = collectorMissing ? QStringLiteral("The part of Wild OS that keeps the history isn't installed.") : QStringLiteral("The history files can't be opened.");
+ } else if (!ownReadable) {
+ // What everyone on this PC sees is still there; this account's own
+ // sign-ins and app crashes are not.
+ problem = QStringLiteral("stale");
+ detail = QStringLiteral("Your own sign-ins and apps couldn't be read just now.");
+ } else if (!status.isEmpty() && !status.value(QStringLiteral("ok")).toBool(true)) {
+ // settings-history names what it could not read, in words.
+ problem = QStringLiteral("stale");
+ QStringList why;
+ for (const QJsonValue &v : status.value(QStringLiteral("problems")).toArray()) {
+ why << v.toString();
+ }
+ QString list = why.size() > 1 ? why.mid(0, why.size() - 1).join(QStringLiteral(", ")) + QStringLiteral(" and ") + why.last() : why.value(0);
+ if (!list.isEmpty()) {
+ list[0] = list.at(0).toUpper();
+ }
+ detail = list.isEmpty() ? QString() : list + QStringLiteral(" couldn't be read just now.");
+ } else if (m_reply.startsWith(QLatin1String("error"))) {
+ problem = QStringLiteral("stale");
+ detail = QStringLiteral("The part of Wild OS that keeps this list didn't answer.");
+ }
+
+ m_events = list;
+ m_problem = problem;
+ m_problemDetail = detail;
+ Q_EMIT eventsChanged();
+ watch();
+}
+
+void History::watch()
+{
+ if (QFileInfo::exists(dir) && !m_watcher.directories().contains(dir)) {
+ m_watcher.addPath(dir);
+ }
+ const QString backups = backupHistory();
+ if (QFileInfo::exists(backups) && !m_watcher.files().contains(backups)) {
+ m_watcher.addPath(backups);
+ }
+}
+
+bool History::saveTo(const QUrl &file, const QString &text)
+{
+ QSaveFile out(file.toLocalFile());
+ if (!out.open(QIODevice::WriteOnly)) {
+ return false;
+ }
+ out.write(text.toUtf8());
+ return out.commit();
+}
+
+QUrl History::defaultSaveFile() const
+{
+ const QString folder = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
+ return QUrl::fromLocalFile(folder + QStringLiteral("/History %1.txt").arg(QDate::currentDate().toString(QStringLiteral("d MMMM yyyy"))));
+}
+
+bool History::openReport() const
+{
+ const QString program = QStandardPaths::findExecutable(QStringLiteral("wildos-report"));
+ return !program.isEmpty() && QProcess::startDetached(program, {});
+}
+
+bool History::report(const QVariantMap &event, const QString &text)
+{
+ const QString program = QStandardPaths::findExecutable(QStringLiteral("wildos-report"));
+ if (program.isEmpty()) {
+ return false;
+ }
+ // Handed over in this account's own runtime folder, which nobody else
+ // can open; Report a problem deletes it once read.
+ const QString folder = QStandardPaths::writableLocation(QStandardPaths::RuntimeLocation) + QStringLiteral("/wildos-history");
+ QDir().mkpath(folder);
+ QFile::setPermissions(folder, QFileDevice::ReadOwner | QFileDevice::WriteOwner | QFileDevice::ExeOwner);
+ const QVariantMap data = event.value(QStringLiteral("data")).toMap();
+ const QString kind = event.value(QStringLiteral("kind")).toString();
+ QJsonObject note{{QStringLiteral("title"), event.value(QStringLiteral("title")).toString()},
+ {QStringLiteral("when"), event.value(QStringLiteral("when")).toDateTime().toSecsSinceEpoch()},
+ {QStringLiteral("text"), text},
+ {QStringLiteral("kind"), kind},
+ {QStringLiteral("program"), data.value(QStringLiteral("program")).toString()}};
+ if (kind == QLatin1String("crash")) {
+ note.insert(QStringLiteral("crash"), true);
+ note.insert(QStringLiteral("app"), data.value(QStringLiteral("app")).toString());
+ }
+ const QString path = folder + QStringLiteral("/report-%1.json").arg(event.value(QStringLiteral("id")).toString().left(32).remove(QLatin1Char('/')));
+ QSaveFile out(path);
+ if (!out.open(QIODevice::WriteOnly)) {
+ return false;
+ }
+ out.write(QJsonDocument(note).toJson(QJsonDocument::Compact));
+ out.setPermissions(QFileDevice::ReadOwner | QFileDevice::WriteOwner);
+ if (!out.commit()) {
+ return false;
+ }
+ return QProcess::startDetached(program, {QStringLiteral("--event"), path});
+}
diff --git a/packages/wildos-settings/src/history.h b/packages/wildos-settings/src/history.h
new file mode 100644
index 0000000..5f01073
--- /dev/null
+++ b/packages/wildos-settings/src/history.h
@@ -0,0 +1,73 @@
+#pragma once
+
+#include <QFileSystemWatcher>
+#include <QObject>
+#include <QQmlEngine>
+#include <QTimer>
+#include <QUrl>
+#include <QVariantList>
+
+class QLocalSocket;
+
+// Settings > System > History. Reads the records settings-history keeps
+// as root (/var/lib/wildos/history: what anyone may see, and this
+// account's own), plus this account's Backup runs, which Backup keeps in
+// the home folder. Asks settings-history to catch up through its socket
+// each time the page opens. The words for each kind of event are in
+// HistoryWords.qml; nothing here leaves the PC.
+class History : public QObject
+{
+ Q_OBJECT
+ QML_ELEMENT
+ QML_SINGLETON
+
+ // Newest first: {id, when (date), kind, data (map), tech (list of
+ // {when, source, text})}. Only the last 30 days.
+ Q_PROPERTY(QVariantList events READ events NOTIFY eventsChanged)
+ Q_PROPERTY(bool loading READ loading NOTIFY loadingChanged)
+ // "" when all is well; "stale" when the latest events could not be
+ // gathered (what is shown may be missing some); "unreadable" when
+ // nothing could be read at all.
+ Q_PROPERTY(QString problem READ problem NOTIFY eventsChanged)
+ // Why, in the words settings-history or the system gave.
+ Q_PROPERTY(QString problemDetail READ problemDetail NOTIFY eventsChanged)
+
+public:
+ explicit History(QObject *parent = nullptr);
+
+ QVariantList events() const { return m_events; }
+ bool loading() const { return m_loading; }
+ QString problem() const { return m_problem; }
+ QString problemDetail() const { return m_problemDetail; }
+
+ // Ask settings-history to catch up, then read the records again.
+ Q_INVOKABLE void refresh();
+ // Writes the text to the file chosen; false when it could not.
+ Q_INVOKABLE bool saveTo(const QUrl &file, const QString &text);
+ // Report a problem, with this event attached: title, when, the words
+ // shown, the technical lines, and the program for a crash.
+ Q_INVOKABLE bool report(const QVariantMap &event, const QString &text);
+ // Report a problem on its own, from the summary at the top.
+ Q_INVOKABLE bool openReport() const;
+ Q_INVOKABLE QUrl defaultSaveFile() const;
+
+Q_SIGNALS:
+ void eventsChanged();
+ void loadingChanged();
+
+private:
+ void load();
+ void readFile(const QString &path, QVariantList &into, bool *readable);
+ void readBackups(QVariantList &into);
+ void watch();
+
+ QFileSystemWatcher m_watcher;
+ QTimer m_settle;
+ QLocalSocket *m_socket = nullptr;
+ QTimer m_timeout;
+ QVariantList m_events;
+ bool m_loading = false;
+ QString m_problem;
+ QString m_problemDetail;
+ QString m_reply;
+};
diff --git a/packages/wildos-settings/src/keyboard.cpp b/packages/wildos-settings/src/keyboard.cpp
index 230ac77..6b93af1 100644
--- a/packages/wildos-settings/src/keyboard.cpp
+++ b/packages/wildos-settings/src/keyboard.cpp
@@ -9,10 +9,47 @@
#include <QDBusPendingCallWatcher>
#include <QDBusPendingReply>
#include <QFile>
+#include <QLocale>
+#include <QRegularExpression>
#include <QXmlStreamReader>
#include <algorithm>
+namespace
+{
+// What people search for besides a layout's own name: the countries and
+// languages xkeyboard-config lists for it (Belgium, Dutch, French for
+// "Belgian"), its code, and the letter order printed on the keys.
+QString searchWords(const QString &layout, const QString &description, const QStringList &countries, const QStringList &languages)
+{
+ QStringList words{layout};
+ for (const QString &code : countries) {
+ const QLocale::Territory territory = QLocale::codeToTerritory(code);
+ if (territory != QLocale::AnyTerritory) {
+ words << QLocale::territoryToString(territory);
+ }
+ }
+ for (const QString &code : languages) {
+ const QLocale::Language language = QLocale::codeToLanguage(code, QLocale::ISO639Part2);
+ if (language != QLocale::AnyLanguage) {
+ words << QLocale::languageToString(language);
+ }
+ }
+ static const QStringList azerty{QStringLiteral("be"), QStringLiteral("fr")};
+ static const QStringList qwertz{QStringLiteral("de"), QStringLiteral("at"), QStringLiteral("ch"), QStringLiteral("cz"), QStringLiteral("sk"),
+ QStringLiteral("hu"), QStringLiteral("si"), QStringLiteral("hr")};
+ static const QRegularExpression otherOrder(QStringLiteral("qwerty|bepo|bépo|dvorak|colemak|workman"), QRegularExpression::CaseInsensitiveOption);
+ if (!description.contains(otherOrder)) {
+ if (azerty.contains(layout)) {
+ words << QStringLiteral("azerty");
+ } else if (qwertz.contains(layout)) {
+ words << QStringLiteral("qwertz");
+ }
+ }
+ return words.join(QLatin1Char(' ')).toLower();
+}
+}
+
namespace
{
const QString service = QStringLiteral("org.kde.keyboard");
@@ -130,6 +167,10 @@ void Keyboard::loadNames()
QString layout;
QString name;
QString description;
+ QStringList countries;
+ QStringList languages;
+ QStringList layoutCountries;
+ QStringList layoutLanguages;
bool inVariant = false;
while (!xml.atEnd()) {
xml.readNext();
@@ -148,6 +189,12 @@ void Keyboard::loadNames()
} else if (tag == QLatin1String("configItem")) {
name.clear();
description.clear();
+ countries.clear();
+ languages.clear();
+ } else if (tag == QLatin1String("iso3166Id")) {
+ countries << xml.readElementText();
+ } else if (tag == QLatin1String("iso639Id")) {
+ languages << xml.readElementText();
} else if (tag == QLatin1String("name")) {
name = xml.readElementText();
} else if (tag == QLatin1String("description")) {
@@ -164,11 +211,22 @@ void Keyboard::loadNames()
continue;
} else if (!inVariant) {
layout = name;
+ layoutCountries = countries;
+ layoutLanguages = languages;
m_names.insert(layout + QLatin1Char('|'), description);
- m_available.append(QVariantMap{{QStringLiteral("layout"), layout}, {QStringLiteral("variant"), QString()}, {QStringLiteral("name"), description}});
+ m_available.append(QVariantMap{{QStringLiteral("layout"), layout},
+ {QStringLiteral("variant"), QString()},
+ {QStringLiteral("name"), description},
+ {QStringLiteral("keywords"), searchWords(layout, description, countries, languages)}});
} else if (!layout.isEmpty()) {
+ // A variant without its own lists is for the layout's.
m_names.insert(layout + QLatin1Char('|') + name, description);
- m_available.append(QVariantMap{{QStringLiteral("layout"), layout}, {QStringLiteral("variant"), name}, {QStringLiteral("name"), description}});
+ m_available.append(QVariantMap{{QStringLiteral("layout"), layout},
+ {QStringLiteral("variant"), name},
+ {QStringLiteral("name"), description},
+ {QStringLiteral("keywords"),
+ searchWords(layout, description, countries.isEmpty() ? layoutCountries : countries,
+ languages.isEmpty() ? layoutLanguages : languages)}});
}
} else if (xml.isEndElement() && xml.name() == QLatin1String("variant")) {
inVariant = false;
diff --git a/packages/wildos-settings/src/main.cpp b/packages/wildos-settings/src/main.cpp
index d2684bd..0cb8a70 100644
--- a/packages/wildos-settings/src/main.cpp
+++ b/packages/wildos-settings/src/main.cpp
@@ -195,6 +195,10 @@ int main(int argc, char *argv[])
const int code = app.exec();
// Modules hold items from the engine; drop them before the engine goes.
+ // KcmHost keeps its own reference for modules opened later; while it
+ // held one, the engine outlived the application and tore down its
+ // images after Qt had gone, which aborted Settings as it closed.
+ KcmHost::setEngine(nullptr);
engine.reset();
return code;
}
diff --git a/packages/wildos-settings/src/networkd/blocked.cpp b/packages/wildos-settings/src/networkd/blocked.cpp
new file mode 100644
index 0000000..036f3b0
--- /dev/null
+++ b/packages/wildos-settings/src/networkd/blocked.cpp
@@ -0,0 +1,313 @@
+#include "blocked.h"
+
+#include <QDebug>
+#include <QDir>
+#include <QFile>
+#include <QFileInfo>
+#include <QJsonDocument>
+#include <QJsonObject>
+#include <QSaveFile>
+#include <QSocketNotifier>
+#include <QtEndian>
+
+#include <arpa/inet.h>
+#include <cerrno>
+#include <cstring>
+#include <iterator>
+#include <fcntl.h>
+#include <linux/netfilter/nfnetlink.h>
+#include <linux/netfilter/nfnetlink_log.h>
+#include <linux/netlink.h>
+#include <net/if.h>
+#include <sys/socket.h>
+#include <unistd.h>
+
+namespace
+{
+const QString logDir = QStringLiteral("/var/lib/wildos/firewall");
+const QString logFile = QStringLiteral("/var/lib/wildos/firewall/blocked.log");
+const QString stateFile = QStringLiteral("/run/wildos/firewall-state.json");
+// settings-firewall's LOG_GROUP.
+constexpr quint16 logGroup = 47;
+constexpr qint64 keepSeconds = 7 * 24 * 3600;
+// Enough for a day of steady knocking from the internet at the firewall's
+// rate limit, and a bound on the file whatever happens.
+constexpr int maxLines = 20000;
+
+bool configure(int fd, quint16 attrType, const void *data, int size)
+{
+ static quint32 seq = 0;
+ alignas(nlmsghdr) char buf[128] = {};
+ auto *nh = reinterpret_cast<nlmsghdr *>(buf);
+ nh->nlmsg_type = (NFNL_SUBSYS_ULOG << 8) | NFULNL_MSG_CONFIG;
+ nh->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
+ nh->nlmsg_seq = ++seq;
+ auto *g = static_cast<nfgenmsg *>(NLMSG_DATA(nh));
+ g->nfgen_family = AF_UNSPEC;
+ g->version = NFNETLINK_V0;
+ g->res_id = htons(logGroup);
+ const int head = NLMSG_ALIGN(NLMSG_LENGTH(sizeof(nfgenmsg)));
+ auto *a = reinterpret_cast<nlattr *>(buf + head);
+ a->nla_type = attrType;
+ a->nla_len = NLA_HDRLEN + size;
+ std::memcpy(buf + head + NLA_HDRLEN, data, size);
+ nh->nlmsg_len = head + NLA_ALIGN(a->nla_len);
+
+ sockaddr_nl kernel{};
+ kernel.nl_family = AF_NETLINK;
+ if (sendto(fd, buf, nh->nlmsg_len, 0, reinterpret_cast<sockaddr *>(&kernel), sizeof kernel) < 0) {
+ return false;
+ }
+ alignas(nlmsghdr) char reply[1024];
+ for (int tries = 0; tries < 8; ++tries) {
+ int n = recv(fd, reply, sizeof reply, 0);
+ if (n <= 0) {
+ return false;
+ }
+ for (auto *r = reinterpret_cast<nlmsghdr *>(reply); NLMSG_OK(r, n); r = NLMSG_NEXT(r, n)) {
+ if (r->nlmsg_type == NLMSG_ERROR && r->nlmsg_seq == seq) {
+ const int error = static_cast<nlmsgerr *>(NLMSG_DATA(r))->error;
+ if (error != 0) {
+ qWarning() << "nflog config" << attrType << std::strerror(-error);
+ }
+ return error == 0;
+ }
+ }
+ }
+ return false;
+}
+
+bool isLocalRange(const QHostAddress &a)
+{
+ return a.isPrivateUse() || a.isLinkLocal() || a.isUniqueLocalUnicast()
+ || a.isInSubnet(QHostAddress::parseSubnet(QStringLiteral("100.64.0.0/10")));
+}
+}
+
+BlockedLog::BlockedLog(QObject *parent)
+ : QObject(parent)
+{
+ prune();
+ m_prune.setInterval(3600 * 1000);
+ connect(&m_prune, &QTimer::timeout, this, &BlockedLog::prune);
+ m_prune.start();
+ m_retry.setSingleShot(true);
+ m_retry.setInterval(30000);
+ connect(&m_retry, &QTimer::timeout, this, &BlockedLog::open);
+ open();
+}
+
+BlockedLog::~BlockedLog()
+{
+ if (m_fd >= 0) {
+ ::close(m_fd);
+ }
+}
+
+void BlockedLog::open()
+{
+ m_fd = socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_NETFILTER);
+ sockaddr_nl local{};
+ local.nl_family = AF_NETLINK;
+ nfulnl_msg_config_cmd bind{NFULNL_CFG_CMD_BIND};
+ nfulnl_msg_config_mode mode{};
+ // The IP header and the ports are all that is kept.
+ mode.copy_range = htonl(64);
+ mode.copy_mode = NFULNL_COPY_PACKET;
+ if (m_fd < 0 || ::bind(m_fd, reinterpret_cast<sockaddr *>(&local), sizeof local) < 0
+ || !configure(m_fd, NFULA_CFG_CMD, &bind, sizeof bind) || !configure(m_fd, NFULA_CFG_MODE, &mode, sizeof mode)) {
+ qWarning() << "cannot listen to the firewall's log; trying again shortly";
+ if (m_fd >= 0) {
+ ::close(m_fd);
+ m_fd = -1;
+ }
+ m_retry.start();
+ return;
+ }
+ int big = 1 << 20;
+ setsockopt(m_fd, SOL_SOCKET, SO_RCVBUF, &big, sizeof big);
+ fcntl(m_fd, F_SETFL, fcntl(m_fd, F_GETFL) | O_NONBLOCK);
+ m_notifier = new QSocketNotifier(m_fd, QSocketNotifier::Read, this);
+ connect(m_notifier, &QSocketNotifier::activated, this, &BlockedLog::read);
+}
+
+void BlockedLog::read()
+{
+ alignas(nlmsghdr) char buf[8192];
+ for (;;) {
+ int n = recv(m_fd, buf, sizeof buf, 0);
+ if (n <= 0) {
+ // ENOBUFS: some were lost while this was busy; carry on.
+ if (n < 0 && errno != EAGAIN && errno != EWOULDBLOCK && errno != ENOBUFS && errno != EINTR) {
+ qWarning() << "firewall log:" << std::strerror(errno);
+ }
+ return;
+ }
+ for (auto *nh = reinterpret_cast<nlmsghdr *>(buf); NLMSG_OK(nh, n); nh = NLMSG_NEXT(nh, n)) {
+ if (nh->nlmsg_type != ((NFNL_SUBSYS_ULOG << 8) | NFULNL_MSG_PACKET)) {
+ continue;
+ }
+ const char *start = reinterpret_cast<const char *>(NLMSG_DATA(nh)) + NLMSG_ALIGN(sizeof(nfgenmsg));
+ int rest = int(nh->nlmsg_len) - int(start - reinterpret_cast<const char *>(nh));
+ QByteArray payload;
+ QString device;
+ while (rest >= int(NLA_HDRLEN)) {
+ const auto *a = reinterpret_cast<const nlattr *>(start);
+ if (a->nla_len < NLA_HDRLEN || a->nla_len > rest) {
+ break;
+ }
+ const char *data = start + NLA_HDRLEN;
+ const int size = a->nla_len - NLA_HDRLEN;
+ switch (a->nla_type & NLA_TYPE_MASK) {
+ case NFULA_PAYLOAD:
+ payload = QByteArray(data, size);
+ break;
+ case NFULA_IFINDEX_INDEV:
+ if (size >= 4) {
+ quint32 index;
+ std::memcpy(&index, data, 4);
+ char name[IF_NAMESIZE] = {};
+ if (if_indextoname(ntohl(index), name)) {
+ device = QString::fromLatin1(name);
+ }
+ }
+ break;
+ }
+ start += NLA_ALIGN(a->nla_len);
+ rest -= NLA_ALIGN(a->nla_len);
+ }
+ if (!payload.isEmpty()) {
+ record(payload, device);
+ }
+ }
+ }
+}
+
+void BlockedLog::record(const QByteArray &packet, QString device)
+{
+ const auto *p = reinterpret_cast<const quint8 *>(packet.constData());
+ const int size = packet.size();
+ QHostAddress source;
+ int protocol = 0;
+ int l4 = 0;
+ if (size >= 20 && (p[0] >> 4) == 4) {
+ l4 = (p[0] & 0x0f) * 4;
+ protocol = p[9];
+ source = QHostAddress(qFromBigEndian<quint32>(p + 12));
+ } else if (size >= 40 && (p[0] >> 4) == 6) {
+ l4 = 40;
+ protocol = p[6];
+ source = QHostAddress(p + 8);
+ }
+ if ((protocol != 6 && protocol != 17) || size < l4 + 4 || source.isNull()) {
+ return;
+ }
+ const int port = (p[l4 + 2] << 8) | p[l4 + 3];
+ const QString proto = protocol == 6 ? QStringLiteral("tcp") : QStringLiteral("udp");
+ const qint64 now = QDateTime::currentSecsSinceEpoch();
+
+ const QString key = source.toString() + QLatin1Char('/') + proto + QLatin1Char('/') + QString::number(port);
+ const qint64 last = m_recent.value(key);
+ m_recent.insert(key, now);
+ if (now - last < 60) {
+ return;
+ }
+ if (m_recent.size() > 1000) {
+ for (auto it = m_recent.begin(); it != m_recent.end();) {
+ it = now - it.value() >= 60 ? m_recent.erase(it) : std::next(it);
+ }
+ }
+
+ const QString kind = kindOf(source, &device);
+ QJsonObject line{{QStringLiteral("t"), now},
+ {QStringLiteral("src"), source.toString()},
+ {QStringLiteral("proto"), proto},
+ {QStringLiteral("port"), port},
+ {QStringLiteral("kind"), kind},
+ {QStringLiteral("device"), device}};
+ QDir().mkpath(logDir);
+ QFile file(logFile);
+ if (file.open(QIODevice::Append)) {
+ file.setPermissions(QFileDevice::ReadOwner | QFileDevice::WriteOwner | QFileDevice::ReadGroup | QFileDevice::ReadOther);
+ file.write(QJsonDocument(line).toJson(QJsonDocument::Compact) + '\n');
+ }
+}
+
+// "router", "local" (another device on the network it came in from),
+// "internet", or "other" (a private address that is not on that network,
+// such as one behind a VPN). Nothing is guessed beyond that.
+QString BlockedLog::kindOf(const QHostAddress &source, QString *device)
+{
+ const QFileInfo info(stateFile);
+ if (info.lastModified() != m_stateRead) {
+ m_stateRead = info.lastModified();
+ QFile file(stateFile);
+ if (file.open(QIODevice::ReadOnly)) {
+ m_networks = QJsonDocument::fromJson(file.readAll()).object().value(QStringLiteral("networks")).toArray();
+ }
+ }
+ for (const QJsonValue &v : std::as_const(m_networks)) {
+ const QJsonObject net = v.toObject();
+ const QString dev = net.value(QStringLiteral("device")).toString();
+ if (!device->isEmpty() && dev != *device) {
+ continue;
+ }
+ for (const QJsonValue &g : net.value(QStringLiteral("gateways")).toArray()) {
+ if (QHostAddress(g.toString()).isEqual(source, QHostAddress::TolerantConversion)) {
+ *device = dev;
+ return QStringLiteral("router");
+ }
+ }
+ const QJsonArray ranges = net.value(QStringLiteral("v4")).toArray() + net.value(QStringLiteral("v6")).toArray();
+ for (const QJsonValue &r : ranges) {
+ if (source.isInSubnet(QHostAddress::parseSubnet(r.toString()))) {
+ *device = dev;
+ return QStringLiteral("local");
+ }
+ }
+ }
+ return isLocalRange(source) ? QStringLiteral("other") : QStringLiteral("internet");
+}
+
+void BlockedLog::prune()
+{
+ QFile file(logFile);
+ if (!file.open(QIODevice::ReadOnly)) {
+ return;
+ }
+ const qint64 oldest = QDateTime::currentSecsSinceEpoch() - keepSeconds;
+ QList<QByteArray> kept;
+ int total = 0;
+ while (!file.atEnd()) {
+ const QByteArray line = file.readLine();
+ ++total;
+ const QJsonObject o = QJsonDocument::fromJson(line).object();
+ if (o.value(QStringLiteral("t")).toInteger() >= oldest) {
+ kept.append(line);
+ }
+ }
+ file.close();
+ if (kept.size() > maxLines) {
+ kept = kept.mid(kept.size() - maxLines);
+ }
+ if (kept.size() == total) {
+ return;
+ }
+ QSaveFile out(logFile);
+ if (out.open(QIODevice::WriteOnly)) {
+ for (const QByteArray &line : std::as_const(kept)) {
+ out.write(line);
+ }
+ out.setPermissions(QFileDevice::ReadOwner | QFileDevice::WriteOwner | QFileDevice::ReadGroup | QFileDevice::ReadOther);
+ out.commit();
+ }
+}
+
+void BlockedLog::clear()
+{
+ QFile file(logFile);
+ if (file.exists()) {
+ file.resize(0);
+ }
+ m_recent.clear();
+}
diff --git a/packages/wildos-settings/src/networkd/blocked.h b/packages/wildos-settings/src/networkd/blocked.h
new file mode 100644
index 0000000..870484b
--- /dev/null
+++ b/packages/wildos-settings/src/networkd/blocked.h
@@ -0,0 +1,44 @@
+#pragma once
+
+#include <QDateTime>
+#include <QHash>
+#include <QHostAddress>
+#include <QJsonArray>
+#include <QObject>
+#include <QTimer>
+
+class QSocketNotifier;
+
+// "What the firewall blocked". The firewall's last rule hands a few new
+// connections a minute to netlink log group 47 (settings-firewall); this
+// reads them there rather than from the kernel log, so they never reach
+// the journal, which would keep them longer than the seven days Settings
+// promises. Each is written to a file Settings reads, with who sent it put
+// into words from the networks the firewall knew at that moment.
+class BlockedLog : public QObject
+{
+ Q_OBJECT
+
+public:
+ explicit BlockedLog(QObject *parent = nullptr);
+ ~BlockedLog() override;
+
+ void clear();
+
+private:
+ void open();
+ void read();
+ void record(const QByteArray &packet, QString device);
+ void prune();
+ QString kindOf(const QHostAddress &source, QString *device);
+
+ int m_fd = -1;
+ QSocketNotifier *m_notifier = nullptr;
+ QTimer m_prune;
+ QTimer m_retry;
+ // A refused connection is tried a few times over; one attempt is one
+ // line.
+ QHash<QString, qint64> m_recent;
+ QJsonArray m_networks;
+ QDateTime m_stateRead;
+};
diff --git a/packages/wildos-settings/src/networkd/main.cpp b/packages/wildos-settings/src/networkd/main.cpp
index d7eaf19..a647703 100644
--- a/packages/wildos-settings/src/networkd/main.cpp
+++ b/packages/wildos-settings/src/networkd/main.cpp
@@ -10,6 +10,18 @@
// servers is left as it is, and so is anything the person changes
// afterwards: each profile is only ever defaulted once.
//
+// Settings > Privacy and security > Advanced protection's Encrypted DNS
+// (dns, dns_strict and dns_provider in /etc/wildos/advanced-protection).
+// On is the default above, with the chosen provider in Quad9's place.
+// Strict (Maximum protection) makes every network Wild OS looks after use
+// the provider over TLS only, with nothing sent in plain text: the
+// profiles defaulted above and those left on the network's own servers.
+// Off, the person's choice, puts the profiles on Wild OS's default back on
+// the network's own servers, unencrypted, and new profiles stay there.
+// Servers someone typed in, or a provider picked for one network in
+// Advanced network settings, stay as they are. Each profile changed is
+// noted with what it had, so coming back to on puts that back.
+//
// 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
@@ -22,7 +34,21 @@
// 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.
-
+//
+// The firewall (settings-firewall) lets in what Settings allows from the
+// networks this computer is on, so its rules are loaded again whenever a
+// network comes or goes, an address changes or an allowed time runs out.
+// What it turns away is collected by BlockedLog, and Settings asks here
+// which programs wait for connections (only root can name them all).
+//
+// Settings > System > History: as the lid closes, settings-history notes
+// what decides whether anything happens next (KDE's lid setting, other
+// screens, apps holding inhibitor locks), which the journal never says,
+// so History can explain a lid that was closed while the PC stayed on. It
+// notes the lid opening too: UPower reads the switch itself, and logind
+// says nothing about it on some laptops while KDE holds the lid.
+
+#include "blocked.h"
#include "netshared.h"
#include <QCoreApplication>
@@ -30,6 +56,7 @@
#include <QDBusMessage>
#include <QDBusServiceWatcher>
#include <QDBusVariant>
+#include <QDateTime>
#include <QDebug>
#include <QDir>
#include <QFile>
@@ -37,10 +64,16 @@
#include <QHash>
#include <QHostAddress>
#include <QHostInfo>
+#include <QJsonArray>
+#include <QJsonDocument>
+#include <QJsonObject>
+#include <QNetworkInterface>
+#include <QRegularExpression>
#include <QProcess>
#include <QSaveFile>
#include <QSet>
#include <QTimer>
+#include <QVariantMap>
#include <iterator>
#include <utility>
@@ -55,7 +88,11 @@ 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 heldFile = QStringLiteral("/var/lib/wildos/network-dns-held");
+const QString advancedFile = QStringLiteral("/etc/wildos/advanced-protection");
const QString table = QStringLiteral("wildos_kill_switch");
+const QString firewallHelper = QStringLiteral("/usr/libexec/wildos/settings-firewall");
+const QString firewallState = QStringLiteral("/run/wildos/firewall-state.json");
const QString wifiType = QStringLiteral("802-11-wireless");
const QString wiredType = QStringLiteral("802-3-ethernet");
@@ -145,12 +182,26 @@ void writeFile(const QString &path, const QString &text)
}
}
+// One key of Advanced protection's store, or its default when missing.
+QString advanced(const QString &key, const QString &fallback)
+{
+ QString value = fallback;
+ for (const QString &line : readLines(advancedFile)) {
+ if (line.startsWith(key + QLatin1Char('='))) {
+ value = line.mid(key.size() + 1).trimmed();
+ }
+ }
+ return value;
+}
+
bool isVpn(const QString &type)
{
return type == QLatin1String("vpn") || type == QLatin1String("wireguard");
}
}
+const QString historyTool = QStringLiteral("/usr/libexec/wildos/settings-history");
+
class NetworkService : public QObject
{
Q_OBJECT
@@ -162,10 +213,18 @@ public:
m_timer.setSingleShot(true);
m_timer.setInterval(300);
connect(&m_timer, &QTimer::timeout, this, &NetworkService::reconcile);
+ m_expiry.setSingleShot(true);
+ connect(&m_expiry, &QTimer::timeout, this, &NetworkService::schedule);
for (const QString &uuid : readLines(defaultedFile)) {
m_defaulted.insert(uuid.trimmed());
}
+ for (const QString &line : readLines(heldFile)) {
+ const QStringList parts = line.split(QLatin1Char(' '), Qt::SkipEmptyParts);
+ if (parts.size() == 2) {
+ m_held.insert(parts.at(0), parts.at(1));
+ }
+ }
for (const QString &line : readLines(armedFile)) {
const QStringList parts = line.split(QLatin1Char(' '));
if (parts.size() >= 2) {
@@ -180,6 +239,8 @@ public:
QStringLiteral("NewConnection"), this, SLOT(schedule()));
bus.connect(NetShared::nmService, QStringLiteral("/org/freedesktop/NetworkManager/Settings"), QStringLiteral("org.freedesktop.NetworkManager.Settings"),
QStringLiteral("ConnectionRemoved"), this, SLOT(schedule()));
+ bus.connect(QStringLiteral("org.freedesktop.UPower"), QStringLiteral("/org/freedesktop/UPower"), QStringLiteral("org.freedesktop.DBus.Properties"),
+ QStringLiteral("PropertiesChanged"), this, SLOT(upowerChanged(QString, QVariantMap, QStringList)));
auto watcher = new QDBusServiceWatcher(NetShared::nmService, bus, QDBusServiceWatcher::WatchForRegistration, this);
connect(watcher, &QDBusServiceWatcher::serviceRegistered, this, &NetworkService::schedule);
@@ -215,12 +276,80 @@ public Q_SLOTS:
schedule();
}
+ // "What the firewall blocked" > Clear the list. It only empties a list
+ // kept on this computer, so it asks for no password.
+ Q_SCRIPTABLE void ClearBlocked()
+ {
+ m_blocked.clear();
+ // Cleared means cleared: History's copies go too.
+ QProcess::startDetached(historyTool, {QStringLiteral("forget"), QStringLiteral("firewall")});
+ }
+
+ // Programs waiting for connections from other computers, as JSON:
+ // [{proto, port, process, app}], app being a Flatpak or desktop id
+ // where the program's cgroup names one. Loopback-only sockets, and the
+ // ones a DHCP client, name lookups or network discovery hold, are left
+ // out, as security-status leaves them out.
+ Q_SCRIPTABLE QString Listening()
+ {
+ static const QSet<QString> system{QStringLiteral("avahi-daemon"), QStringLiteral("systemd-resolve"), QStringLiteral("NetworkManager"),
+ QStringLiteral("dhclient"), QStringLiteral("dnsmasq"), QStringLiteral("chronyd"),
+ QStringLiteral("cupsd"), QStringLiteral("systemd-network"), QStringLiteral("sdwdate")};
+ static const QRegularExpression proc(QStringLiteral("\\(\\(\"([^\"]+)\",pid=(\\d+)"));
+ bool ok = false;
+ const QString out = run(QStringLiteral("ss"), {QStringLiteral("-Hltunp")}, &ok);
+ QJsonArray list;
+ QSet<QString> seen;
+ for (const QString &line : out.split(QLatin1Char('\n'), Qt::SkipEmptyParts)) {
+ const QStringList f = line.simplified().split(QLatin1Char(' '));
+ if (f.size() < 5) {
+ continue;
+ }
+ const QString local = f.at(4);
+ const int colon = local.lastIndexOf(QLatin1Char(':'));
+ const int port = local.mid(colon + 1).toInt();
+ QString address = local.left(colon).remove(QLatin1Char('[')).remove(QLatin1Char(']')).section(QLatin1Char('%'), 0, 0);
+ if (address.startsWith(QLatin1String("::ffff:"))) {
+ address = address.mid(7);
+ }
+ const QHostAddress host(address);
+ if (port <= 0 || (!host.isNull() && host.isLoopback()) || local.contains(QLatin1String("%lo:"))) {
+ continue;
+ }
+ const QString proto = f.at(0);
+ if (proto == QLatin1String("udp") && (port == 68 || port == 546 || port == 5353 || port >= 32768)) {
+ continue;
+ }
+ const QRegularExpressionMatch m = proc.match(line);
+ const QString process = m.hasMatch() ? m.captured(1) : QString();
+ const QString key = proto + QString::number(port);
+ if (system.contains(process) || seen.contains(key)) {
+ continue;
+ }
+ seen.insert(key);
+ list.append(QJsonObject{{QStringLiteral("proto"), proto},
+ {QStringLiteral("port"), port},
+ {QStringLiteral("process"), process},
+ {QStringLiteral("app"), m.hasMatch() ? appId(m.captured(2)) : QString()}});
+ }
+ return QString::fromUtf8(QJsonDocument(list).toJson(QJsonDocument::Compact));
+ }
+
private Q_SLOTS:
void schedule()
{
m_timer.start();
}
+ void upowerChanged(const QString &interface, const QVariantMap &changed, const QStringList &)
+ {
+ // Both ways: while KDE holds the lid, logind may not log it at all.
+ if (interface == QLatin1String("org.freedesktop.UPower") && changed.contains(QStringLiteral("LidIsClosed"))) {
+ const bool closed = changed.value(QStringLiteral("LidIsClosed")).toBool();
+ QProcess::startDetached(historyTool, {closed ? QStringLiteral("lid-closed") : QStringLiteral("lid-opened")});
+ }
+ }
+
void activeStateChanged(uint state, uint reason, const QDBusMessage &message)
{
if (state == deactivated && (reason == userDisconnected || reason == connectionRemoved)) {
@@ -237,7 +366,9 @@ private Q_SLOTS:
readActive();
const auto all = readAll();
stampDefaults(all);
+ advancedDns(all);
killSwitch(all);
+ firewall();
}
private:
@@ -284,6 +415,7 @@ private:
void stampDefaults(const QHash<QString, QPair<QString, QString>> &all)
{
const int before = m_defaulted.size();
+ bool heldChanged = false;
for (auto it = all.cbegin(); it != all.cend(); ++it) {
const QString &uuid = it.key();
const QString &type = it.value().first;
@@ -306,9 +438,16 @@ private:
if (hotspot || ownServers) {
continue;
}
+ // With Encrypted DNS off the profile keeps the network's own
+ // servers, noted as owed the default when it is switched on.
+ if (dnsMode() == QLatin1String("off")) {
+ m_held.insert(uuid, QStringLiteral("default"));
+ heldChanged = true;
+ continue;
+ }
bool ok = false;
nmcli(QStringList{QStringLiteral("connection"), QStringLiteral("modify"), uuid}
- + NetShared::dnsModifyArgs(QStringLiteral("quad9"), {}, NetShared::ipv4TakesDns(method4), NetShared::ipv6TakesDns(method6), true),
+ + NetShared::dnsModifyArgs(dnsProvider(), {}, NetShared::ipv4TakesDns(method4), NetShared::ipv6TakesDns(method6), true),
&ok);
if (ok) {
m_reapply.insert(uuid);
@@ -319,9 +458,154 @@ private:
lines.sort();
writeFile(defaultedFile, lines.join(QLatin1Char('\n')) + QLatin1Char('\n'));
}
+ if (heldChanged) {
+ writeHeld();
+ }
+
+ reapplyJoined();
+ }
+
+ // "on", "strict" or "off". Off is the person's own choice, so it wins
+ // over strictness a protection level asked for.
+ static QString dnsMode()
+ {
+ if (advanced(QStringLiteral("dns"), QStringLiteral("on")) == QLatin1String("off")) {
+ return QStringLiteral("off");
+ }
+ return advanced(QStringLiteral("dns_strict"), QStringLiteral("off")) == QLatin1String("on") ? QStringLiteral("strict") : QStringLiteral("on");
+ }
+
+ void writeHeld()
+ {
+ QString text;
+ for (auto it = m_held.cbegin(); it != m_held.cend(); ++it) {
+ text += it.key() + QLatin1Char(' ') + it.value() + QLatin1Char('\n');
+ }
+ writeFile(heldFile, text);
+ }
+
+ static QString dnsProvider()
+ {
+ const QString id = advanced(QStringLiteral("dns_provider"), QStringLiteral("quad9"));
+ return NetShared::provider(id) ? id : QStringLiteral("quad9");
+ }
+
+ // Goes through every profile only when the choice changed or a profile
+ // came along that it has not seen, so a change the person makes to one
+ // network afterwards is left alone, as with the default.
+ void advancedDns(const QHash<QString, QPair<QString, QString>> &all)
+ {
+ const QString mode = dnsMode();
+ const QString provider = dnsProvider();
+ const QString choice = mode + QLatin1Char(' ') + provider;
+ QSet<QString> uuids;
+ for (auto it = all.cbegin(); it != all.cend(); ++it) {
+ if (it.value().first == wifiType || it.value().first == wiredType) {
+ uuids.insert(it.key());
+ }
+ }
+ if (choice == m_dnsChoice && uuids == m_dnsSeen) {
+ return;
+ }
+ const bool everything = choice != m_dnsChoice;
+ bool heldChanged = false;
+ for (const QString &uuid : std::as_const(uuids)) {
+ if (!everything && m_dnsSeen.contains(uuid)) {
+ continue;
+ }
+ const QString path = all.value(uuid).second;
+ if (connectionFlags(path) & externalFlag) {
+ continue;
+ }
+ const NetShared::Profile p = NetShared::profile(path);
+ if (p.isEmpty()) {
+ continue;
+ }
+ const QVariantMap ipv4 = p.value(QStringLiteral("ipv4"));
+ const QString method4 = ipv4.value(QStringLiteral("method")).toString();
+ const QString method6 = p.value(QStringLiteral("ipv6")).value(QStringLiteral("method")).toString();
+ if (p.value(wifiType).value(QStringLiteral("mode")).toString() == QLatin1String("ap") || method4 == QLatin1String("shared")) {
+ continue;
+ }
+ const bool ignoreAuto = ipv4.value(QStringLiteral("ignore-auto-dns")).toBool();
+ const QString now = NetShared::dnsChoice(NetShared::profileDnsAddresses(p), ignoreAuto);
+ const int tls = p.value(QStringLiteral("connection")).value(QStringLiteral("dns-over-tls"), -1).toInt();
+ // NetShared::dnsModifyArgs' asDefault: a provider, opportunistic,
+ // with the network's own servers behind it.
+ const bool wildosDefault = NetShared::provider(now) && tls == 1 && !ignoreAuto;
+ // What strict and off leave a profile with. A noted profile that
+ // looks like neither was changed by the person since, in
+ // Advanced network settings, and is theirs again.
+ const bool asLeft = (NetShared::provider(now) && tls == 2 && ignoreAuto) || now == QLatin1String("automatic");
+ if (m_held.contains(uuid) && !asLeft) {
+ m_held.remove(uuid);
+ heldChanged = true;
+ continue;
+ }
+ const bool held = m_held.contains(uuid);
+
+ QString target;
+ bool asDefault = false;
+ if (mode == QLatin1String("strict")) {
+ if (held ? !(now == provider && tls == 2) : (wildosDefault || now == QLatin1String("automatic"))) {
+ if (!held) {
+ m_held.insert(uuid, wildosDefault ? QStringLiteral("default") : QStringLiteral("automatic"));
+ heldChanged = true;
+ }
+ target = provider;
+ }
+ } else if (mode == QLatin1String("off")) {
+ if (held ? now != QLatin1String("automatic") : wildosDefault) {
+ if (!held) {
+ m_held.insert(uuid, QStringLiteral("default"));
+ heldChanged = true;
+ }
+ target = QStringLiteral("automatic");
+ }
+ } else if (held) {
+ const QString before = m_held.take(uuid);
+ heldChanged = true;
+ target = before == QLatin1String("automatic") ? QStringLiteral("automatic") : provider;
+ asDefault = target != QLatin1String("automatic");
+ if (target == now && (!asDefault || tls == 1)) {
+ target.clear();
+ }
+ } else if (wildosDefault && now != provider) {
+ target = provider;
+ asDefault = true;
+ }
+ if (target.isEmpty()) {
+ continue;
+ }
+ bool ok = false;
+ nmcli(QStringList{QStringLiteral("connection"), QStringLiteral("modify"), uuid}
+ + NetShared::dnsModifyArgs(target, {}, NetShared::ipv4TakesDns(method4), NetShared::ipv6TakesDns(method6), asDefault),
+ &ok);
+ if (ok) {
+ m_reapply.insert(uuid);
+ }
+ }
+ for (auto it = m_held.begin(); it != m_held.end();) {
+ if (all.contains(it.key())) {
+ ++it;
+ } else {
+ it = m_held.erase(it);
+ heldChanged = true;
+ }
+ }
+ if (heldChanged) {
+ writeHeld();
+ }
+ m_dnsChoice = choice;
+ m_dnsSeen = uuids;
+ reapplyJoined();
+ }
- // A connection being joined right now started with the network's
- // servers; once it is up it takes the new ones in place.
+ // A connection being joined right now started with the network's
+ // servers, or the ones it had; once it is up it takes the new ones in
+ // place.
+ void reapplyJoined()
+ {
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);
@@ -405,6 +689,73 @@ private:
}
}
+ static QString appId(const QString &pid)
+ {
+ // Flatpak runs each app in app-flatpak-<id>-<n>.scope, and the
+ // desktop starts others in app-<desktop id>-<random>.scope or
+ // app-<desktop id>@<instance>.service.
+ static const QRegularExpression flatpak(QStringLiteral("app-flatpak-([A-Za-z0-9._-]+?)-[0-9]+\\.scope"));
+ static const QRegularExpression desktop(QStringLiteral("/app-([A-Za-z0-9._-]+?)(?:@[^/]*)?(?:-[0-9a-f]{6,})?\\.(?:scope|service)$"));
+ QFile file(QStringLiteral("/proc/%1/cgroup").arg(pid));
+ if (!file.open(QIODevice::ReadOnly)) {
+ return {};
+ }
+ const QString cgroup = QString::fromUtf8(file.readAll()).trimmed();
+ QRegularExpressionMatch m = flatpak.match(cgroup);
+ if (m.hasMatch()) {
+ return m.captured(1);
+ }
+ m = desktop.match(cgroup);
+ return m.hasMatch() ? m.captured(1) : QString();
+ }
+
+ // Loads the firewall again when the networks it allows things from have
+ // changed, or a rule's time is up.
+ void firewall()
+ {
+ if (!QFile::exists(firewallHelper)) {
+ return;
+ }
+ QStringList parts;
+ for (const Active &a : std::as_const(m_active)) {
+ if (a.state != QLatin1String("activated") || a.device.isEmpty() || isVpn(a.type)) {
+ continue;
+ }
+ QString part = a.uuid + QLatin1Char('@') + a.device;
+ for (const QNetworkAddressEntry &e : QNetworkInterface::interfaceFromName(a.device).addressEntries()) {
+ part += QLatin1Char(' ') + e.ip().toString() + QLatin1Char('/') + QString::number(e.prefixLength());
+ }
+ parts.append(part);
+ }
+ parts.sort();
+ const QString signature = parts.join(QLatin1Char('\n'));
+
+ const qint64 now = QDateTime::currentSecsSinceEpoch();
+ qint64 expiry = nextExpiry();
+ if (signature != m_firewallSignature || (expiry > 0 && expiry <= now)) {
+ bool ok = false;
+ run(firewallHelper, {QStringLiteral("apply")}, &ok);
+ if (ok) {
+ m_firewallSignature = signature;
+ }
+ expiry = nextExpiry();
+ }
+ if (expiry > now) {
+ m_expiry.start(int(qMin<qint64>(expiry - now, 3600)) * 1000 + 500);
+ } else {
+ m_expiry.stop();
+ }
+ }
+
+ static qint64 nextExpiry()
+ {
+ QFile state(firewallState);
+ if (!state.open(QIODevice::ReadOnly)) {
+ return 0;
+ }
+ return QJsonDocument::fromJson(state.readAll()).object().value(QStringLiteral("next_expiry")).toInteger();
+ }
+
QStringList resolveServers(const QString &path)
{
QStringList addresses;
@@ -511,11 +862,19 @@ private:
QTimer m_timer;
QTimer m_poll;
+ QTimer m_expiry;
+ BlockedLog m_blocked;
+ QString m_firewallSignature;
QFileSystemWatcher m_files;
QList<Active> m_active;
QHash<QString, QString> m_pathToUuid;
QSet<QString> m_defaulted;
QSet<QString> m_reapply;
+ // Profiles Encrypted DNS's strict or off choice changed: uuid to what
+ // they had, "default" or "automatic".
+ QHash<QString, QString> m_held;
+ QString m_dnsChoice;
+ QSet<QString> m_dnsSeen;
QHash<QString, Armed> m_armed;
QSet<QString> m_userOff;
QSet<QString> m_wasUp;
diff --git a/packages/wildos-settings/src/pointerimport/cursor.h b/packages/wildos-settings/src/pointerimport/cursor.h
new file mode 100644
index 0000000..172d5aa
--- /dev/null
+++ b/packages/wildos-settings/src/pointerimport/cursor.h
@@ -0,0 +1,68 @@
+#pragma once
+
+#include <QByteArray>
+#include <QImage>
+#include <QList>
+#include <QMap>
+#include <QPoint>
+#include <QString>
+#include <QStringList>
+
+// One picture of a pointer: premultiplied ARGB, its hotspot in the
+// picture's own pixels, and for an animation how long it shows.
+struct Frame {
+ QImage image;
+ QPoint hotspot;
+ int delay = 0;
+};
+
+// A pointer: one frame, or the steps of an animation in order.
+using Pointer = QList<Frame>;
+
+// Windows pointer files, read as untrusted data: every length and offset is
+// checked against the bytes actually there before it is used.
+namespace WinCursor
+{
+// A .cur or .ico file: its largest, deepest picture.
+bool readCur(const QByteArray &data, Frame &out);
+// A .ani file (RIFF ACON): every step, with the rate and sequence applied.
+bool readAni(const QByteArray &data, Pointer &out);
+// Either of the two, told apart by the first bytes.
+bool read(const QByteArray &data, Pointer &out);
+
+// The roles of a Windows pointer scheme, in the order the scheme's registry
+// value lists them (Control Panel\Cursors\Schemes).
+enum Role {
+ Arrow,
+ Help,
+ AppStarting,
+ Wait,
+ Crosshair,
+ IBeam,
+ NWPen,
+ No,
+ SizeNS,
+ SizeWE,
+ SizeNWSE,
+ SizeNESW,
+ SizeAll,
+ UpArrow,
+ Hand,
+ RoleCount
+};
+
+// The file name install.inf gives each role, without any folder. Roles it
+// does not name are missing from the map.
+QMap<int, QString> readInf(const QByteArray &data);
+}
+
+namespace Xcursor
+{
+// The Xcursor file for one pointer at the given nominal sizes, each frame
+// scaled so its longer side is fill times the nominal size.
+QByteArray write(const Pointer &pointer, const QList<int> &sizes, qreal fill);
+
+// Reads an Xcursor file strictly and writes the same pictures back in a
+// fresh file, so nothing but well-formed pictures passes through.
+bool rewrite(const QByteArray &data, QByteArray &out);
+}
diff --git a/packages/wildos-settings/src/pointerimport/main.cpp b/packages/wildos-settings/src/pointerimport/main.cpp
new file mode 100644
index 0000000..e61c24f
--- /dev/null
+++ b/packages/wildos-settings/src/pointerimport/main.cpp
@@ -0,0 +1,647 @@
+// pointer-import: turns a Windows pointer, a Windows pointer pack or a
+// picture into the Xcursor theme Settings > Accessibility offers as "Your
+// own" pointer, and carries that theme to the sign-in screen.
+//
+// pointer-import convert FILE THEME-DIR [HOTSPOT-X HOTSPOT-Y]
+// FILE is a .cur, .ani, .zip pack, a pack's install.inf, or a .png or
+// .svg picture (the hotspot is a fraction of its width and height).
+// pointer-import export THEME-DIR > stream
+// pointer-import import THEME-DIR STAMP < stream
+// greeter-access runs export as the account and import as the sddm
+// user, so the sign-in screen only ever gets pictures this program
+// has checked and written again itself.
+//
+// Every file is untrusted: sizes and counts are capped, headers checked,
+// a pack's install.inf is only read for file names, and nothing in a pack
+// is run. Settings runs this as a separate process so a bad file can at
+// worst end this program, never Settings. Exit status 2 means the file is
+// not a pointer this can use, 1 that the theme could not be written.
+
+#include "cursor.h"
+
+#include <KZip>
+
+#include <QBuffer>
+#include <QDir>
+#include <QFile>
+#include <QFileInfo>
+#include <QGuiApplication>
+#include <QImageReader>
+#include <QPainter>
+#include <QRandomGenerator>
+#include <QRegularExpression>
+#include <QSaveFile>
+#include <QSet>
+#include <QSvgRenderer>
+#include <QtMath>
+
+#include <cstdio>
+#include <sys/resource.h>
+
+namespace
+{
+constexpr qint64 maxFile = 8 * 1024 * 1024;
+constexpr qint64 maxPack = 32 * 1024 * 1024;
+constexpr qint64 maxUnpacked = 64 * 1024 * 1024;
+constexpr qint64 maxTheme = 192 * 1024 * 1024;
+constexpr int maxPackEntries = 2000;
+constexpr int maxImageSide = 4096;
+
+// The pointer size slider's sizes, always made, and the larger ones a 150
+// or 200 per cent display scale asks for, made while the file stays under
+// a budget. Xcursor picks the nearest nominal size there is, so a long
+// animation without them is drawn smaller there rather than not at all.
+const QList<int> sliderSizes{24, 30, 36, 48, 60, 72, 96};
+const QList<int> scaledSizes{120, 144, 192};
+constexpr qint64 scaledBudget = 16 * 1024 * 1024;
+
+QList<int> sizesFor(const Pointer &pointer, qreal fill)
+{
+ auto bytes = [&](int nominal) {
+ const qint64 side = qCeil(nominal * fill);
+ return qint64(pointer.size()) * (side * side * 4 + 36);
+ };
+ QList<int> sizes = sliderSizes;
+ qint64 total = 0;
+ for (const int nominal : sliderSizes) {
+ total += bytes(nominal);
+ }
+ for (const int nominal : scaledSizes) {
+ total += bytes(nominal);
+ if (total > scaledBudget) {
+ break;
+ }
+ sizes << nominal;
+ }
+ return sizes;
+}
+
+// Each role's names: the first is the file, the rest links to it. Names
+// Breeze links to the same picture are added from Breeze itself, so old X11
+// apps asking for a hashed name get the same pointer.
+const QList<QStringList> roleNames{
+ {QStringLiteral("default"), QStringLiteral("left_ptr"), QStringLiteral("arrow"), QStringLiteral("top_left_arrow")},
+ {QStringLiteral("help"), QStringLiteral("question_arrow"), QStringLiteral("whats_this"), QStringLiteral("left_ptr_help")},
+ {QStringLiteral("progress"), QStringLiteral("left_ptr_watch"), QStringLiteral("half-busy")},
+ {QStringLiteral("wait"), QStringLiteral("watch")},
+ {QStringLiteral("crosshair"), QStringLiteral("cross"), QStringLiteral("tcross")},
+ {QStringLiteral("text"), QStringLiteral("xterm"), QStringLiteral("ibeam")},
+ {QStringLiteral("pencil"), QStringLiteral("draft")},
+ {QStringLiteral("not-allowed"), QStringLiteral("no-drop"), QStringLiteral("forbidden"), QStringLiteral("crossed_circle"), QStringLiteral("circle"),
+ QStringLiteral("dnd-no-drop")},
+ {QStringLiteral("ns-resize"), QStringLiteral("size_ver"), QStringLiteral("sb_v_double_arrow"), QStringLiteral("v_double_arrow"),
+ QStringLiteral("n-resize"), QStringLiteral("s-resize"), QStringLiteral("top_side"), QStringLiteral("bottom_side")},
+ {QStringLiteral("ew-resize"), QStringLiteral("size_hor"), QStringLiteral("sb_h_double_arrow"), QStringLiteral("h_double_arrow"),
+ QStringLiteral("e-resize"), QStringLiteral("w-resize"), QStringLiteral("left_side"), QStringLiteral("right_side")},
+ {QStringLiteral("nwse-resize"), QStringLiteral("size_fdiag"), QStringLiteral("nw-resize"), QStringLiteral("se-resize"),
+ QStringLiteral("top_left_corner"), QStringLiteral("bottom_right_corner")},
+ {QStringLiteral("nesw-resize"), QStringLiteral("size_bdiag"), QStringLiteral("ne-resize"), QStringLiteral("sw-resize"),
+ QStringLiteral("top_right_corner"), QStringLiteral("bottom_left_corner")},
+ {QStringLiteral("move"), QStringLiteral("all-scroll"), QStringLiteral("fleur"), QStringLiteral("size_all")},
+ {QStringLiteral("up-arrow"), QStringLiteral("center_ptr"), QStringLiteral("sb_up_arrow")},
+ {QStringLiteral("pointer"), QStringLiteral("hand2"), QStringLiteral("hand1"), QStringLiteral("pointing_hand"), QStringLiteral("hand")},
+};
+
+const QRegularExpression validName(QStringLiteral("^[A-Za-z0-9_-]{1,64}$"));
+
+int unusable(const char *why)
+{
+ std::fprintf(stderr, "pointer-import: %s\n", why);
+ return 2;
+}
+
+int failed(const QString &why)
+{
+ std::fprintf(stderr, "pointer-import: %s\n", qPrintable(why));
+ return 1;
+}
+
+bool readCapped(const QString &path, qint64 cap, QByteArray &out)
+{
+ QFile file(path);
+ if (!QFileInfo(path).isFile() || !file.open(QIODevice::ReadOnly) || file.size() > cap) {
+ return false;
+ }
+ out = file.read(cap + 1);
+ return out.size() <= cap;
+}
+
+// A picture as the normal arrow: a PNG, or an SVG drawn at 512 pixels so
+// every size is a sharp scale down.
+bool readPicture(const QByteArray &data, bool svg, QImage &out)
+{
+ if (svg) {
+ QSvgRenderer renderer(data);
+ QSizeF size = renderer.isValid() ? renderer.viewBoxF().size() : QSizeF();
+ if (size.isEmpty()) {
+ size = renderer.defaultSize();
+ }
+ if (!renderer.isValid() || size.isEmpty()) {
+ return false;
+ }
+ size.scale(512, 512, Qt::KeepAspectRatio);
+ out = QImage(qMax(1, qRound(size.width())), qMax(1, qRound(size.height())), QImage::Format_ARGB32_Premultiplied);
+ out.fill(Qt::transparent);
+ QPainter painter(&out);
+ renderer.render(&painter);
+ return true;
+ }
+ QBuffer buffer;
+ buffer.setData(data);
+ QImageReader reader(&buffer, "png");
+ reader.setAutoTransform(true);
+ const QSize size = reader.size();
+ if (!size.isValid() || size.width() > maxImageSide || size.height() > maxImageSide) {
+ return false;
+ }
+ out = reader.read();
+ if (out.isNull()) {
+ return false;
+ }
+ // A big picture is scaled down once here rather than at every size.
+ if (out.width() > 512 || out.height() > 512) {
+ out = out.scaled(512, 512, Qt::KeepAspectRatio, Qt::SmoothTransformation);
+ }
+ out = out.convertToFormat(QImage::Format_ARGB32_Premultiplied);
+ return true;
+}
+
+// Every file in a zip, by its path inside it, without unpacking anything
+// to disk.
+struct Pack {
+ QMap<QString, const KArchiveFile *> files;
+};
+
+bool listZip(const KArchiveDirectory *dir, const QString &prefix, Pack &pack, int depth)
+{
+ if (depth > 8) {
+ return false;
+ }
+ for (const QString &name : dir->entries()) {
+ if (pack.files.size() >= maxPackEntries) {
+ return false;
+ }
+ const KArchiveEntry *entry = dir->entry(name);
+ if (entry->isFile()) {
+ pack.files.insert(prefix + name, static_cast<const KArchiveFile *>(entry));
+ } else if (entry->isDirectory()) {
+ if (!listZip(static_cast<const KArchiveDirectory *>(entry), prefix + name + u'/', pack, depth + 1)) {
+ return false;
+ }
+ }
+ }
+ return true;
+}
+
+bool isPointerFile(const QString &name)
+{
+ return name.endsWith(QLatin1String(".cur"), Qt::CaseInsensitive) || name.endsWith(QLatin1String(".ani"), Qt::CaseInsensitive);
+}
+
+// The roles found in a pack, its files read through fetch(name), which
+// looks the name up beside install.inf.
+template<typename Fetch>
+QMap<int, Pointer> readScheme(const QMap<int, QString> &scheme, Fetch fetch)
+{
+ QMap<int, Pointer> roles;
+ QHash<QString, Pointer> done;
+ qint64 total = 0;
+ for (auto it = scheme.cbegin(); it != scheme.cend(); ++it) {
+ const QString key = it.value().toLower();
+ if (!done.contains(key)) {
+ QByteArray data;
+ Pointer pointer;
+ // A role whose file is missing or bad keeps the white pointer;
+ // the rest of the pack still works.
+ if (isPointerFile(key) && fetch(it.value(), data) && (total += data.size()) <= maxUnpacked && WinCursor::read(data, pointer)) {
+ done.insert(key, pointer);
+ } else {
+ done.insert(key, {});
+ }
+ }
+ if (!done.value(key).isEmpty()) {
+ roles.insert(it.key(), done.value(key));
+ }
+ }
+ return roles;
+}
+
+bool readZip(const QString &path, QMap<int, Pointer> &roles)
+{
+ if (QFileInfo(path).size() > maxPack) {
+ return false;
+ }
+ KZip zip(path);
+ if (!zip.open(QIODevice::ReadOnly)) {
+ return false;
+ }
+ Pack pack;
+ if (!listZip(zip.directory(), QString(), pack, 0)) {
+ return false;
+ }
+ auto readEntry = [](const KArchiveFile *file, QByteArray &data) {
+ if (file->size() > maxFile) {
+ return false;
+ }
+ data = file->data();
+ return data.size() <= maxFile;
+ };
+
+ // The install.inf nearest the top, and the files beside it. Packs that
+ // come in several sizes side by side (Regular, Large, Extra Large) get
+ // their regular one: the size slider makes it larger.
+ QString inf;
+ static const QRegularExpression regular(QStringLiteral("regular|normal|standard|default"), QRegularExpression::CaseInsensitiveOption);
+ auto rank = [](const QString &name) {
+ return name.count(u'/') * 2 + (regular.match(name).hasMatch() ? 0 : 1);
+ };
+ for (const QString &name : pack.files.keys()) {
+ if (QFileInfo(name).fileName().compare(QLatin1String("install.inf"), Qt::CaseInsensitive) == 0 && (inf.isEmpty() || rank(name) < rank(inf))) {
+ inf = name;
+ }
+ }
+ if (inf.isEmpty()) {
+ // No scheme: a zip holding a single pointer is that pointer.
+ QStringList pointers;
+ for (const QString &name : pack.files.keys()) {
+ if (isPointerFile(name)) {
+ pointers << name;
+ }
+ }
+ QByteArray data;
+ Pointer pointer;
+ if (pointers.size() != 1 || !readEntry(pack.files.value(pointers.first()), data) || !WinCursor::read(data, pointer)) {
+ return false;
+ }
+ roles.insert(WinCursor::Arrow, pointer);
+ return true;
+ }
+ QByteArray infData;
+ if (!readEntry(pack.files.value(inf), infData)) {
+ return false;
+ }
+ const QString folder = inf.left(inf.lastIndexOf(u'/') + 1);
+ roles = readScheme(WinCursor::readInf(infData), [&](const QString &name, QByteArray &data) {
+ const KArchiveFile *beside = nullptr;
+ const KArchiveFile *anywhere = nullptr;
+ for (auto it = pack.files.cbegin(); it != pack.files.cend(); ++it) {
+ if (QFileInfo(it.key()).fileName().compare(name, Qt::CaseInsensitive) == 0) {
+ if (it.key().left(it.key().lastIndexOf(u'/') + 1) == folder) {
+ beside = it.value();
+ } else if (!anywhere) {
+ anywhere = it.value();
+ }
+ }
+ }
+ const KArchiveFile *file = beside ? beside : anywhere;
+ return file && readEntry(file, data);
+ });
+ return !roles.isEmpty();
+}
+
+bool readFolder(const QString &infPath, QMap<int, Pointer> &roles)
+{
+ QByteArray infData;
+ if (!readCapped(infPath, 1024 * 1024, infData)) {
+ return false;
+ }
+ const QDir folder = QFileInfo(infPath).absoluteDir();
+ // Only regular files beside install.inf, never links out of the folder.
+ const QStringList files = folder.entryList(QDir::Files | QDir::NoSymLinks | QDir::Readable);
+ roles = readScheme(WinCursor::readInf(infData), [&](const QString &name, QByteArray &data) {
+ for (const QString &file : files) {
+ if (file.compare(name, Qt::CaseInsensitive) == 0) {
+ return readCapped(folder.filePath(file), maxFile, data);
+ }
+ }
+ return false;
+ });
+ return !roles.isEmpty();
+}
+
+// Breeze's own links: which names show the same picture.
+QHash<QString, QString> breezeLinks()
+{
+ QHash<QString, QString> picture;
+ const QDir dir(QStringLiteral("/usr/share/icons/Breeze_Light/cursors"));
+ for (const QFileInfo &info : dir.entryInfoList(QDir::Files)) {
+ const QString canonical = info.canonicalFilePath();
+ if (!canonical.isEmpty()) {
+ picture.insert(info.fileName(), QFileInfo(canonical).fileName());
+ }
+ }
+ return picture;
+}
+
+bool replaceDir(const QString &fresh, const QString &target)
+{
+ const QString old = target + QStringLiteral(".old");
+ QDir(old).removeRecursively();
+ if (QFileInfo::exists(target) && !QDir().rename(target, old)) {
+ return false;
+ }
+ if (!QDir().rename(fresh, target)) {
+ QDir().rename(old, target);
+ return false;
+ }
+ QDir(old).removeRecursively();
+ return true;
+}
+
+bool writeFile(const QString &path, const QByteArray &data)
+{
+ QSaveFile file(path);
+ return file.open(QIODevice::WriteOnly) && file.write(data) == data.size() && file.commit();
+}
+
+QByteArray indexTheme(const QString &source, const QString &stamp)
+{
+ QString clean = source;
+ clean.remove(QRegularExpression(QStringLiteral("[\\x00-\\x1f\\x7f\\[\\]]")));
+ QByteArray out = "[Icon Theme]\nName=Your own\nComment=A pointer added in Settings\nInherits=Breeze_Light\n\n[Wild OS]\n";
+ if (!clean.isEmpty()) {
+ out += "Source=" + clean.toUtf8() + '\n';
+ }
+ out += "Stamp=" + stamp.toLatin1() + '\n';
+ return out;
+}
+
+QString newStamp()
+{
+ return QString::number(QRandomGenerator::system()->generate64(), 16);
+}
+
+int convert(const QString &input, const QString &target, qreal hotX, qreal hotY)
+{
+ const QFileInfo info(input);
+ const QString suffix = info.suffix().toLower();
+ QMap<int, Pointer> roles;
+ qreal fill = 4.0 / 3.0;
+
+ if (suffix == QLatin1String("cur") || suffix == QLatin1String("ani") || suffix == QLatin1String("ico")) {
+ QByteArray data;
+ Pointer pointer;
+ if (!readCapped(input, maxFile, data) || !WinCursor::read(data, pointer)) {
+ return unusable("not a Windows pointer");
+ }
+ roles.insert(WinCursor::Arrow, pointer);
+ } else if (suffix == QLatin1String("png") || suffix == QLatin1String("svg")) {
+ QByteArray data;
+ Frame frame;
+ if (!readCapped(input, suffix == QLatin1String("svg") ? 2 * 1024 * 1024 : maxFile, data) || !readPicture(data, suffix == QLatin1String("svg"), frame.image)) {
+ return unusable("not a picture");
+ }
+ frame.hotspot = QPoint(qBound(0, int(hotX * frame.image.width()), frame.image.width() - 1),
+ qBound(0, int(hotY * frame.image.height()), frame.image.height() - 1));
+ roles.insert(WinCursor::Arrow, {frame});
+ // A picture is all pointer, with no empty canvas round it.
+ fill = 1.0;
+ } else if (suffix == QLatin1String("zip")) {
+ if (!readZip(input, roles)) {
+ return unusable("not a pointer pack");
+ }
+ } else if (info.fileName().compare(QLatin1String("install.inf"), Qt::CaseInsensitive) == 0 || suffix == QLatin1String("inf")) {
+ if (!readFolder(input, roles)) {
+ return unusable("not a pointer pack");
+ }
+ } else {
+ return unusable("not a kind of file this reads");
+ }
+
+ const QString fresh = target + QStringLiteral(".new");
+ QDir(fresh).removeRecursively();
+ if (!QDir().mkpath(fresh + QStringLiteral("/cursors"))) {
+ return failed(QStringLiteral("cannot write ") + fresh);
+ }
+ const QHash<QString, QString> breeze = breezeLinks();
+ QSet<QString> taken;
+ qint64 total = 0;
+ for (auto it = roles.cbegin(); it != roles.cend(); ++it) {
+ const QStringList &names = roleNames.at(it.key());
+ const QByteArray data = Xcursor::write(it.value(), sizesFor(it.value(), fill), fill);
+ total += data.size();
+ if (total > maxTheme) {
+ QDir(fresh).removeRecursively();
+ return unusable("too many or too large pictures");
+ }
+ const QString file = names.first();
+ if (!writeFile(fresh + QStringLiteral("/cursors/") + file, data)) {
+ QDir(fresh).removeRecursively();
+ return failed(QStringLiteral("cannot write ") + file);
+ }
+ taken.insert(file);
+ QSet<QString> pictures;
+ for (const QString &name : names) {
+ if (breeze.contains(name)) {
+ pictures.insert(breeze.value(name));
+ }
+ }
+ QStringList links = names.mid(1);
+ for (auto b = breeze.cbegin(); b != breeze.cend(); ++b) {
+ if (pictures.contains(b.value())) {
+ links << b.key();
+ }
+ }
+ for (const QString &link : std::as_const(links)) {
+ if (!taken.contains(link) && validName.match(link).hasMatch()) {
+ taken.insert(link);
+ QFile::link(file, fresh + QStringLiteral("/cursors/") + link);
+ }
+ }
+ }
+
+ // The picture Settings shows in the "Your own" swatch.
+ const Frame shown = roles.contains(WinCursor::Arrow) ? roles.value(WinCursor::Arrow).first() : roles.first().first();
+ shown.image.scaled(64, 64, Qt::KeepAspectRatio, Qt::SmoothTransformation).save(fresh + QStringLiteral("/preview.png"), "png");
+
+ // A folder pack is known by its folder, not by install.inf.
+ const QString source = suffix == QLatin1String("inf") ? info.absoluteDir().dirName() : info.fileName();
+ if (!writeFile(fresh + QStringLiteral("/index.theme"), indexTheme(source, newStamp())) || !replaceDir(fresh, target)) {
+ QDir(fresh).removeRecursively();
+ return failed(QStringLiteral("cannot write ") + target);
+ }
+ return 0;
+}
+
+void putBytes(QByteArray &out, const QByteArray &bytes)
+{
+ const quint32 size = quint32(bytes.size());
+ out.append(char(size & 0xff)).append(char((size >> 8) & 0xff)).append(char((size >> 16) & 0xff)).append(char(size >> 24));
+ out.append(bytes);
+}
+
+bool takeBytes(const QByteArray &in, qsizetype &at, qint64 cap, QByteArray &bytes)
+{
+ if (at + 4 > in.size()) {
+ return false;
+ }
+ const auto *p = reinterpret_cast<const uchar *>(in.constData() + at);
+ const quint32 size = quint32(p[0]) | (quint32(p[1]) << 8) | (quint32(p[2]) << 16) | (quint32(p[3]) << 24);
+ at += 4;
+ if (size > cap || size > quint64(in.size() - at)) {
+ return false;
+ }
+ bytes = in.mid(at, size);
+ at += size;
+ return true;
+}
+
+const QByteArray streamMagic = QByteArrayLiteral("WildOS pointer 1\n");
+
+int exportTheme(const QString &theme)
+{
+ const QDir dir(theme + QStringLiteral("/cursors"));
+ QByteArray out = streamMagic;
+ qint64 total = 0;
+ for (const QFileInfo &info : dir.entryInfoList(QDir::Files | QDir::System | QDir::NoDotAndDotDot, QDir::Name)) {
+ const QString name = info.fileName();
+ if (!validName.match(name).hasMatch()) {
+ continue;
+ }
+ if (info.isSymLink()) {
+ const QString target = QFileInfo(info.symLinkTarget()).fileName();
+ if (validName.match(target).hasMatch() && QFileInfo(info.symLinkTarget()).absolutePath() == dir.absolutePath()) {
+ out += 'L';
+ putBytes(out, name.toLatin1());
+ putBytes(out, target.toLatin1());
+ }
+ continue;
+ }
+ QByteArray data;
+ if (!readCapped(info.filePath(), 32 * 1024 * 1024, data) || (total += data.size()) > maxTheme) {
+ return failed(QStringLiteral("cannot read ") + name);
+ }
+ out += 'F';
+ putBytes(out, name.toLatin1());
+ putBytes(out, data);
+ }
+ out += 'E';
+ return std::fwrite(out.constData(), 1, size_t(out.size()), stdout) == size_t(out.size()) && std::fflush(stdout) == 0 ? 0 : 1;
+}
+
+int importTheme(const QString &target, const QString &stamp)
+{
+ if (!QRegularExpression(QStringLiteral("^[0-9a-f]{1,32}$")).match(stamp).hasMatch()) {
+ return unusable("bad stamp");
+ }
+ QFile in;
+ if (!in.open(stdin, QIODevice::ReadOnly)) {
+ return failed(QStringLiteral("cannot read the stream"));
+ }
+ QByteArray stream;
+ for (;;) {
+ const QByteArray chunk = in.read(1024 * 1024);
+ if (chunk.isEmpty()) {
+ break;
+ }
+ stream += chunk;
+ if (stream.size() > maxTheme * 2) {
+ return unusable("stream too large");
+ }
+ }
+ if (!stream.startsWith(streamMagic)) {
+ return unusable("not a pointer stream");
+ }
+
+ const QString fresh = target + QStringLiteral(".new");
+ QDir(fresh).removeRecursively();
+ if (!QDir().mkpath(fresh + QStringLiteral("/cursors"))) {
+ return failed(QStringLiteral("cannot write ") + fresh);
+ }
+ auto fail = [&](const char *why) {
+ QDir(fresh).removeRecursively();
+ return unusable(why);
+ };
+ QSet<QString> files;
+ QList<QPair<QString, QString>> links;
+ qsizetype at = streamMagic.size();
+ bool ended = false;
+ while (at < stream.size() && !ended) {
+ const char kind = stream.at(at++);
+ QByteArray name, body;
+ if (kind == 'E') {
+ ended = true;
+ } else if (kind == 'F' || kind == 'L') {
+ if (!takeBytes(stream, at, 64, name) || !validName.match(QString::fromLatin1(name)).hasMatch()
+ || !takeBytes(stream, at, kind == 'F' ? 32 * 1024 * 1024 : 64, body)) {
+ return fail("damaged stream");
+ }
+ const QString n = QString::fromLatin1(name);
+ if (files.contains(n) || files.size() + links.size() > 1000) {
+ return fail("damaged stream");
+ }
+ if (kind == 'F') {
+ QByteArray clean;
+ if (!Xcursor::rewrite(body, clean) || !writeFile(fresh + QStringLiteral("/cursors/") + n, clean)) {
+ return fail("bad picture");
+ }
+ files.insert(n);
+ } else {
+ const QString target = QString::fromLatin1(body);
+ if (!validName.match(target).hasMatch()) {
+ return fail("damaged stream");
+ }
+ links << qMakePair(n, target);
+ }
+ } else {
+ return fail("damaged stream");
+ }
+ }
+ // A stream cut short (the account's half failed) changes nothing.
+ if (!ended || files.isEmpty()) {
+ return fail("incomplete stream");
+ }
+ for (const auto &link : std::as_const(links)) {
+ if (files.contains(link.second) && !files.contains(link.first)) {
+ QFile::link(link.second, fresh + QStringLiteral("/cursors/") + link.first);
+ }
+ }
+ if (!writeFile(fresh + QStringLiteral("/index.theme"), indexTheme(QString(), stamp)) || !replaceDir(fresh, target)) {
+ QDir(fresh).removeRecursively();
+ return failed(QStringLiteral("cannot write ") + target);
+ }
+ return 0;
+}
+
+void limit(int resource, rlim_t value)
+{
+ const rlimit lim{value, value};
+ setrlimit(resource, &lim);
+}
+}
+
+int main(int argc, char *argv[])
+{
+ // A crafted file should run out of these long before it hurts anything.
+ limit(RLIMIT_CPU, 60);
+ limit(RLIMIT_AS, rlim_t(4) * 1024 * 1024 * 1024);
+ limit(RLIMIT_FSIZE, 64 * 1024 * 1024);
+ limit(RLIMIT_CORE, 0);
+ QImageReader::setAllocationLimit(64);
+
+ const QString mode = argc > 1 ? QString::fromLocal8Bit(argv[1]) : QString();
+ if (mode == QLatin1String("convert") && (argc == 4 || argc == 6)) {
+ // Drawing an SVG needs fonts, which need a GUI application, never
+ // a screen.
+ qputenv("QT_QPA_PLATFORM", "offscreen");
+ QGuiApplication app(argc, argv);
+ const QStringList args = app.arguments();
+ bool okX = true, okY = true;
+ const qreal x = argc == 6 ? args.at(4).toDouble(&okX) : 0;
+ const qreal y = argc == 6 ? args.at(5).toDouble(&okY) : 0;
+ if (!okX || !okY || x < 0 || x > 1 || y < 0 || y > 1) {
+ return unusable("bad hotspot");
+ }
+ return convert(args.at(2), args.at(3), x, y);
+ }
+ if (mode == QLatin1String("export") && argc == 3) {
+ QCoreApplication app(argc, argv);
+ return exportTheme(app.arguments().at(2));
+ }
+ if (mode == QLatin1String("import") && argc == 4) {
+ QCoreApplication app(argc, argv);
+ return importTheme(app.arguments().at(2), app.arguments().at(3));
+ }
+ std::fprintf(stderr, "usage: pointer-import convert FILE THEME-DIR [HOTSPOT-X HOTSPOT-Y] | export THEME-DIR | import THEME-DIR STAMP\n");
+ return 1;
+}
diff --git a/packages/wildos-settings/src/pointerimport/wincursor.cpp b/packages/wildos-settings/src/pointerimport/wincursor.cpp
new file mode 100644
index 0000000..d2ccff2
--- /dev/null
+++ b/packages/wildos-settings/src/pointerimport/wincursor.cpp
@@ -0,0 +1,471 @@
+#include "cursor.h"
+
+#include <QBuffer>
+#include <QImageReader>
+#include <QRegularExpression>
+#include <QStringDecoder>
+
+#include <cstring>
+
+namespace
+{
+// Windows draws pointers up to 256 pixels; a PNG inside a .cur may claim
+// more, which is refused rather than decoded.
+constexpr int maxSide = 256;
+constexpr int maxFrames = 64;
+constexpr int maxSteps = 256;
+
+quint16 u16(const QByteArray &d, qsizetype at)
+{
+ const auto *p = reinterpret_cast<const uchar *>(d.constData() + at);
+ return quint16(p[0] | (p[1] << 8));
+}
+
+quint32 u32(const QByteArray &d, qsizetype at)
+{
+ const auto *p = reinterpret_cast<const uchar *>(d.constData() + at);
+ return quint32(p[0]) | (quint32(p[1]) << 8) | (quint32(p[2]) << 16) | (quint32(p[3]) << 24);
+}
+
+quint32 be32(const QByteArray &d, qsizetype at)
+{
+ const auto *p = reinterpret_cast<const uchar *>(d.constData() + at);
+ return (quint32(p[0]) << 24) | (quint32(p[1]) << 16) | (quint32(p[2]) << 8) | quint32(p[3]);
+}
+
+bool fits(const QByteArray &d, quint64 at, quint64 length)
+{
+ return at <= quint64(d.size()) && length <= quint64(d.size()) - at;
+}
+
+bool isPng(const QByteArray &d)
+{
+ return d.startsWith(QByteArrayLiteral("\x89PNG\r\n\x1a\n"));
+}
+
+bool readPng(const QByteArray &bytes, QImage &out)
+{
+ // The size from the header first, so a huge PNG is never allocated.
+ if (bytes.size() < 24 || be32(bytes, 16) == 0 || be32(bytes, 20) == 0 || be32(bytes, 16) > maxSide || be32(bytes, 20) > maxSide) {
+ return false;
+ }
+ QBuffer buffer;
+ buffer.setData(bytes);
+ QImageReader reader(&buffer, "png");
+ reader.setAutoTransform(false);
+ out = reader.read();
+ return !out.isNull() && out.width() <= maxSide && out.height() <= maxSide;
+}
+
+// A device-independent bitmap as an icon stores it: the colour picture
+// followed by its one-bit transparency mask, both bottom row first, and a
+// header height that counts both.
+bool readDib(const QByteArray &d, QImage &out)
+{
+ if (d.size() < 40) {
+ return false;
+ }
+ const quint32 headerSize = u32(d, 0);
+ const qint32 width = qint32(u32(d, 4));
+ const qint32 doubled = qint32(u32(d, 8));
+ const quint16 planes = u16(d, 12);
+ const quint16 bits = u16(d, 14);
+ const quint32 compression = u32(d, 16);
+ quint32 coloursUsed = u32(d, 32);
+ if (headerSize < 40 || headerSize > 124 || planes != 1 || compression != 0) {
+ return false;
+ }
+ if (width <= 0 || width > maxSide || doubled <= 0 || doubled % 2 != 0 || doubled / 2 > maxSide) {
+ return false;
+ }
+ if (bits != 1 && bits != 4 && bits != 8 && bits != 24 && bits != 32) {
+ return false;
+ }
+ const int height = doubled / 2;
+ quint32 paletteCount = 0;
+ if (bits <= 8) {
+ const quint32 full = 1u << bits;
+ paletteCount = coloursUsed == 0 || coloursUsed > full ? full : coloursUsed;
+ }
+ const quint64 paletteAt = headerSize;
+ const quint64 pixelsAt = paletteAt + quint64(paletteCount) * 4;
+ const quint64 stride = ((quint64(width) * bits + 31) / 32) * 4;
+ const quint64 maskStride = ((quint64(width) + 31) / 32) * 4;
+ const quint64 maskAt = pixelsAt + stride * height;
+ if (!fits(d, paletteAt, quint64(paletteCount) * 4) || !fits(d, pixelsAt, stride * height)) {
+ return false;
+ }
+ // Some 32-bit pictures leave the mask out and rely on their alpha.
+ const bool hasMask = fits(d, maskAt, maskStride * height);
+ if (!hasMask && bits != 32) {
+ return false;
+ }
+
+ const auto *bytes = reinterpret_cast<const uchar *>(d.constData());
+ auto palette = [&](quint32 index) -> QRgb {
+ if (index >= paletteCount) {
+ return qRgb(0, 0, 0);
+ }
+ const uchar *p = bytes + paletteAt + index * 4;
+ return qRgb(p[2], p[1], p[0]);
+ };
+
+ QImage image(width, height, QImage::Format_ARGB32);
+ bool anyAlpha = false;
+ for (int row = 0; row < height; ++row) {
+ const uchar *line = bytes + pixelsAt + stride * (height - 1 - row);
+ const uchar *mask = hasMask ? bytes + maskAt + maskStride * (height - 1 - row) : nullptr;
+ auto *outLine = reinterpret_cast<QRgb *>(image.scanLine(row));
+ for (int x = 0; x < width; ++x) {
+ QRgb colour;
+ int alpha = 255;
+ switch (bits) {
+ case 1:
+ colour = palette((line[x / 8] >> (7 - x % 8)) & 1);
+ break;
+ case 4:
+ colour = palette((line[x / 2] >> (x % 2 ? 0 : 4)) & 0x0f);
+ break;
+ case 8:
+ colour = palette(line[x]);
+ break;
+ case 24:
+ colour = qRgb(line[x * 3 + 2], line[x * 3 + 1], line[x * 3]);
+ break;
+ default:
+ colour = qRgb(line[x * 4 + 2], line[x * 4 + 1], line[x * 4]);
+ alpha = line[x * 4 + 3];
+ anyAlpha = anyAlpha || alpha != 0;
+ break;
+ }
+ const bool masked = mask && ((mask[x / 8] >> (7 - x % 8)) & 1);
+ if (bits != 32) {
+ // A masked pixel with colour inverts the screen on Windows
+ // (the classic text pointer); black is the nearest a
+ // picture can show and stays visible on light windows.
+ if (masked) {
+ alpha = (colour & 0xffffff) ? 255 : 0;
+ if (alpha) {
+ colour = qRgb(0, 0, 0);
+ }
+ }
+ }
+ outLine[x] = qRgba(qRed(colour), qGreen(colour), qBlue(colour), alpha);
+ }
+ }
+ if (bits == 32 && !anyAlpha) {
+ // Old 32-bit pictures with an empty alpha channel use the mask.
+ for (int row = 0; row < height; ++row) {
+ const uchar *mask = hasMask ? bytes + maskAt + maskStride * (height - 1 - row) : nullptr;
+ auto *outLine = reinterpret_cast<QRgb *>(image.scanLine(row));
+ for (int x = 0; x < width; ++x) {
+ const bool masked = mask && ((mask[x / 8] >> (7 - x % 8)) & 1);
+ outLine[x] = (outLine[x] & 0xffffff) | (masked ? 0u : 0xff000000u);
+ }
+ }
+ }
+ out = image;
+ return true;
+}
+
+QString decode(const QByteArray &data)
+{
+ if (data.startsWith("\xff\xfe") || data.startsWith("\xfe\xff")) {
+ QStringDecoder decoder(QStringDecoder::Utf16);
+ return decoder.decode(data);
+ }
+ if (data.startsWith("\xef\xbb\xbf")) {
+ return QString::fromUtf8(data.mid(3));
+ }
+ QStringDecoder utf8(QStringDecoder::Utf8);
+ const QString text = utf8.decode(data);
+ return utf8.hasError() ? QString::fromLatin1(data) : text;
+}
+
+// The fields of an inf line, split at commas outside quotes, unquoted.
+QStringList fields(const QString &line)
+{
+ QStringList out;
+ QString current;
+ bool quoted = false;
+ for (const QChar c : line) {
+ if (c == u'"') {
+ quoted = !quoted;
+ } else if (c == u',' && !quoted) {
+ out << current.trimmed();
+ current.clear();
+ } else {
+ current += c;
+ }
+ }
+ out << current.trimmed();
+ return out;
+}
+
+QString fileName(const QString &path)
+{
+ QString name = path.trimmed();
+ name.replace(u'/', u'\\');
+ name = name.mid(name.lastIndexOf(u'\\') + 1);
+ return name.trimmed();
+}
+}
+
+namespace WinCursor
+{
+bool readCur(const QByteArray &data, Frame &out)
+{
+ if (data.size() < 6 || u16(data, 0) != 0) {
+ return false;
+ }
+ const quint16 type = u16(data, 2);
+ const quint16 count = u16(data, 4);
+ if ((type != 1 && type != 2) || count == 0 || count > 64 || !fits(data, 6, quint64(count) * 16)) {
+ return false;
+ }
+
+ // The largest picture, then the deepest, judged from each picture's
+ // own header rather than the directory, which old tools fill badly.
+ int best = -1;
+ quint64 bestScore = 0;
+ for (int i = 0; i < count; ++i) {
+ const qsizetype entry = 6 + i * 16;
+ const quint32 length = u32(data, entry + 8);
+ const quint32 offset = u32(data, entry + 12);
+ if (length < 40 || !fits(data, offset, length)) {
+ return false;
+ }
+ const QByteArray picture = QByteArray::fromRawData(data.constData() + offset, length);
+ quint64 width = 0, height = 0, depth = 0;
+ if (isPng(picture)) {
+ if (length < 26) {
+ return false;
+ }
+ width = be32(picture, 16);
+ height = be32(picture, 20);
+ depth = 32;
+ } else {
+ width = u32(picture, 4);
+ height = u32(picture, 8) / 2;
+ depth = u16(picture, 14);
+ }
+ if (width == 0 || height == 0 || width > maxSide || height > maxSide) {
+ return false;
+ }
+ const quint64 score = width * height * 64 + depth;
+ if (score > bestScore) {
+ bestScore = score;
+ best = i;
+ }
+ }
+
+ const qsizetype entry = 6 + best * 16;
+ const QByteArray picture = data.mid(u32(data, entry + 12), u32(data, entry + 8));
+ QImage image;
+ if (!(isPng(picture) ? readPng(picture, image) : readDib(picture, image))) {
+ return false;
+ }
+ out.image = image.convertToFormat(QImage::Format_ARGB32_Premultiplied);
+ // An .ico has no hotspot; its directory holds colour counts there.
+ out.hotspot = type == 2 ? QPoint(u16(data, entry + 4), u16(data, entry + 6)) : QPoint(0, 0);
+ out.hotspot.setX(qBound(0, out.hotspot.x(), out.image.width() - 1));
+ out.hotspot.setY(qBound(0, out.hotspot.y(), out.image.height() - 1));
+ out.delay = 0;
+ return true;
+}
+
+bool readAni(const QByteArray &data, Pointer &out)
+{
+ if (data.size() < 12 || !data.startsWith("RIFF") || data.mid(8, 4) != "ACON") {
+ return false;
+ }
+ const quint64 end = qMin<quint64>(quint64(u32(data, 4)) + 8, quint64(data.size()));
+
+ QList<QByteArray> icons;
+ QList<quint32> rates, sequence;
+ bool haveHeader = false;
+ quint32 flags = 0, displayRate = 0;
+
+ // Chunks, and the chunks inside a LIST fram, which hold the frames.
+ struct Span {
+ quint64 at, end;
+ };
+ QList<Span> spans{{12, end}};
+ while (!spans.isEmpty()) {
+ Span span = spans.takeLast();
+ quint64 at = span.at;
+ while (at + 8 <= span.end) {
+ const QByteArray id = data.mid(at, 4);
+ const quint64 size = u32(data, at + 4);
+ const quint64 body = at + 8;
+ if (size > span.end - body) {
+ return false;
+ }
+ if (id == "anih") {
+ if (size < 36) {
+ return false;
+ }
+ displayRate = u32(data, body + 28);
+ flags = u32(data, body + 32);
+ haveHeader = true;
+ } else if (id == "rate" || id == "seq ") {
+ if (size / 4 > maxSteps) {
+ return false;
+ }
+ QList<quint32> &list = id == "rate" ? rates : sequence;
+ list.clear();
+ for (quint64 i = 0; i + 4 <= size; i += 4) {
+ list << u32(data, body + i);
+ }
+ } else if (id == "LIST") {
+ if (size >= 4 && data.mid(body, 4) == "fram") {
+ if (spans.size() > 4) {
+ return false;
+ }
+ spans << Span{body + 4, body + size};
+ }
+ } else if (id == "icon") {
+ if (icons.size() >= maxFrames) {
+ return false;
+ }
+ icons << data.mid(body, size);
+ }
+ at = body + size + (size & 1);
+ }
+ }
+
+ // Frames stored as bare bitmaps (flag 1 clear) were never common and
+ // are not read.
+ if (!haveHeader || !(flags & 1) || icons.isEmpty()) {
+ return false;
+ }
+ QList<Frame> frames;
+ for (const QByteArray &icon : icons) {
+ Frame frame;
+ if (!readCur(icon, frame)) {
+ return false;
+ }
+ frames << frame;
+ }
+
+ const qsizetype steps = !sequence.isEmpty() ? sequence.size() : !rates.isEmpty() ? qMin(rates.size(), frames.size()) : frames.size();
+ if (steps == 0 || steps > maxSteps) {
+ return false;
+ }
+ out.clear();
+ for (qsizetype i = 0; i < steps; ++i) {
+ const quint32 index = sequence.isEmpty() ? quint32(i) : sequence.at(i);
+ if (index >= quint32(frames.size())) {
+ return false;
+ }
+ // Rates are in jiffies, sixtieths of a second.
+ const quint32 jiffies = qBound<quint32>(1, i < rates.size() ? rates.at(i) : displayRate, 600);
+ Frame frame = frames.at(index);
+ frame.delay = int(jiffies * 1000 / 60);
+ out << frame;
+ }
+ return true;
+}
+
+bool read(const QByteArray &data, Pointer &out)
+{
+ if (data.startsWith("RIFF")) {
+ return readAni(data, out);
+ }
+ Frame frame;
+ if (!readCur(data, frame)) {
+ return false;
+ }
+ out = {frame};
+ return true;
+}
+
+QMap<int, QString> readInf(const QByteArray &data)
+{
+ const QString text = decode(data);
+ // Comments start with ; outside quotes; sections and keys ignore case.
+ QMap<QString, QList<QStringList>> sections;
+ QMap<QString, QString> strings;
+ QString section;
+ for (QString line : text.split(QRegularExpression(QStringLiteral("[\r\n]+")))) {
+ bool quoted = false;
+ for (qsizetype i = 0; i < line.size(); ++i) {
+ if (line.at(i) == u'"') {
+ quoted = !quoted;
+ } else if (line.at(i) == u';' && !quoted) {
+ line.truncate(i);
+ break;
+ }
+ }
+ line = line.trimmed();
+ if (line.isEmpty()) {
+ continue;
+ }
+ if (line.startsWith(u'[') && line.endsWith(u']')) {
+ section = line.mid(1, line.size() - 2).trimmed().toLower();
+ continue;
+ }
+ if (section == QLatin1String("strings")) {
+ const qsizetype eq = line.indexOf(u'=');
+ if (eq > 0) {
+ QString value = line.mid(eq + 1).trimmed();
+ if (value.size() >= 2 && value.startsWith(u'"') && value.endsWith(u'"')) {
+ value = value.mid(1, value.size() - 2);
+ }
+ strings.insert(line.left(eq).trimmed().toLower(), value);
+ }
+ } else {
+ sections[section] << fields(line);
+ }
+ }
+
+ // %name% from [Strings]; %10% and other numbers are Windows folders,
+ // which only matter for the folder part this drops anyway.
+ auto expand = [&](QString value) {
+ static const QRegularExpression token(QStringLiteral("%([^%]*)%"));
+ QString result;
+ qsizetype last = 0;
+ auto it = token.globalMatch(value);
+ while (it.hasNext()) {
+ const auto match = it.next();
+ result += value.mid(last, match.capturedStart() - last);
+ result += strings.value(match.captured(1).toLower());
+ last = match.capturedEnd();
+ }
+ result += value.mid(last);
+ return result;
+ };
+
+ static const char *const valueNames[RoleCount] = {"arrow", "help", "appstarting", "wait", "crosshair", "ibeam", "nwpen",
+ "no", "sizens", "sizewe", "sizenwse", "sizenesw", "sizeall", "uparrow", "hand"};
+ QMap<int, QString> roles;
+ for (const auto &lines : std::as_const(sections)) {
+ for (const QStringList &f : lines) {
+ if (f.size() < 5 || f.at(0).compare(QLatin1String("HKCU"), Qt::CaseInsensitive) != 0) {
+ continue;
+ }
+ const QString key = expand(f.at(1)).replace(u'/', u'\\').toLower();
+ if (key.endsWith(QLatin1String("control panel\\cursors\\schemes"))) {
+ // The scheme: every role's file in the standard order,
+ // comma separated inside one value.
+ const QStringList files = expand(f.mid(4).join(u',')).split(u',');
+ for (int role = 0; role < RoleCount && role < files.size(); ++role) {
+ const QString name = fileName(files.at(role));
+ if (!name.isEmpty()) {
+ roles.insert(role, name);
+ }
+ }
+ } else if (key.endsWith(QLatin1String("control panel\\cursors"))) {
+ const QString valueName = expand(f.at(2)).toLower();
+ for (int role = 0; role < RoleCount; ++role) {
+ const QString name = fileName(expand(f.at(4)));
+ if (valueName == QLatin1String(valueNames[role]) && !name.isEmpty() && !roles.contains(role)) {
+ roles.insert(role, name);
+ }
+ }
+ }
+ }
+ }
+ return roles;
+}
+}
diff --git a/packages/wildos-settings/src/pointerimport/xcursor.cpp b/packages/wildos-settings/src/pointerimport/xcursor.cpp
new file mode 100644
index 0000000..ec4a1e1
--- /dev/null
+++ b/packages/wildos-settings/src/pointerimport/xcursor.cpp
@@ -0,0 +1,156 @@
+#include "cursor.h"
+
+#include <QHash>
+#include <QtEndian>
+
+#include <cmath>
+
+// The Xcursor format, as libXcursor and KWin read it: a header, a table of
+// contents, and one chunk per picture holding its nominal size, size,
+// hotspot, delay and premultiplied ARGB pixels, all little endian.
+namespace
+{
+constexpr quint32 magic = 0x72756358; // "Xcur"
+constexpr quint32 imageType = 0xfffd0002;
+constexpr quint32 fileHeader = 16;
+constexpr quint32 chunkHeader = 36;
+constexpr quint32 maxPictureSide = 1024;
+constexpr quint32 maxPictures = 4096;
+
+void put(QByteArray &out, quint32 value)
+{
+ const quint32 le = qToLittleEndian(value);
+ out.append(reinterpret_cast<const char *>(&le), 4);
+}
+
+quint32 get(const QByteArray &d, qsizetype at)
+{
+ return qFromLittleEndian<quint32>(d.constData() + at);
+}
+
+struct Picture {
+ quint32 nominal;
+ QImage image;
+ QPoint hotspot;
+ quint32 delay;
+};
+
+QByteArray assemble(const QList<Picture> &pictures)
+{
+ QByteArray out;
+ put(out, magic);
+ put(out, fileHeader);
+ put(out, 0x10000);
+ put(out, quint32(pictures.size()));
+ quint32 position = fileHeader + 12 * quint32(pictures.size());
+ for (const Picture &p : pictures) {
+ put(out, imageType);
+ put(out, p.nominal);
+ put(out, position);
+ position += chunkHeader + 4 * quint32(p.image.width() * p.image.height());
+ }
+ for (const Picture &p : pictures) {
+ put(out, chunkHeader);
+ put(out, imageType);
+ put(out, p.nominal);
+ put(out, 1);
+ put(out, quint32(p.image.width()));
+ put(out, quint32(p.image.height()));
+ put(out, quint32(p.hotspot.x()));
+ put(out, quint32(p.hotspot.y()));
+ put(out, p.delay);
+ for (int y = 0; y < p.image.height(); ++y) {
+ const auto *line = reinterpret_cast<const quint32 *>(p.image.constScanLine(y));
+ for (int x = 0; x < p.image.width(); ++x) {
+ put(out, line[x]);
+ }
+ }
+ }
+ return out;
+}
+}
+
+namespace Xcursor
+{
+QByteArray write(const Pointer &pointer, const QList<int> &sizes, qreal fill)
+{
+ QList<Picture> pictures;
+ // An animation repeats frames; each is scaled once per size.
+ QHash<QPair<qint64, int>, Picture> scaled;
+ for (const int nominal : sizes) {
+ for (const Frame &frame : pointer) {
+ const auto key = qMakePair(frame.image.cacheKey(), nominal);
+ auto it = scaled.constFind(key);
+ if (it == scaled.constEnd()) {
+ const QImage &src = frame.image;
+ const qreal scale = nominal * fill / qMax(src.width(), src.height());
+ const int width = qBound(1, qRound(src.width() * scale), int(maxPictureSide));
+ const int height = qBound(1, qRound(src.height() * scale), int(maxPictureSide));
+ Picture p;
+ p.nominal = quint32(nominal);
+ p.image = (src.size() == QSize(width, height) ? src : src.scaled(width, height, Qt::IgnoreAspectRatio, Qt::SmoothTransformation))
+ .convertToFormat(QImage::Format_ARGB32_Premultiplied);
+ // The middle of the hotspot pixel lands in the same place.
+ p.hotspot = QPoint(qBound(0, int(std::floor((frame.hotspot.x() + 0.5) * width / src.width())), width - 1),
+ qBound(0, int(std::floor((frame.hotspot.y() + 0.5) * height / src.height())), height - 1));
+ it = scaled.insert(key, p);
+ }
+ Picture p = it.value();
+ p.delay = quint32(pointer.size() > 1 ? qMax(frame.delay, 1) : 0);
+ pictures << p;
+ }
+ }
+ return assemble(pictures);
+}
+
+bool rewrite(const QByteArray &data, QByteArray &out)
+{
+ if (data.size() < qsizetype(fileHeader) || get(data, 0) != magic) {
+ return false;
+ }
+ const quint32 header = get(data, 4);
+ const quint32 count = get(data, 12);
+ if (header < fileHeader || count == 0 || count > maxPictures || quint64(header) + 12ull * count > quint64(data.size())) {
+ return false;
+ }
+ QList<Picture> pictures;
+ for (quint32 i = 0; i < count; ++i) {
+ const qsizetype entry = header + 12 * i;
+ if (get(data, entry) != imageType) {
+ continue; // comments and other chunk types are left behind
+ }
+ const quint64 at = get(data, entry + 8);
+ if (at + chunkHeader > quint64(data.size()) || get(data, at) != chunkHeader || get(data, at + 4) != imageType) {
+ return false;
+ }
+ Picture p;
+ p.nominal = get(data, at + 8);
+ const quint32 width = get(data, at + 16);
+ const quint32 height = get(data, at + 20);
+ const quint32 x = get(data, at + 24);
+ const quint32 y = get(data, at + 28);
+ p.delay = qMin<quint32>(get(data, at + 32), 60000);
+ if (p.nominal == 0 || p.nominal > maxPictureSide || width == 0 || height == 0 || width > maxPictureSide || height > maxPictureSide
+ || x >= width || y >= height || at + chunkHeader + 4ull * width * height > quint64(data.size())) {
+ return false;
+ }
+ p.image = QImage(int(width), int(height), QImage::Format_ARGB32_Premultiplied);
+ for (quint32 row = 0; row < height; ++row) {
+ auto *line = reinterpret_cast<quint32 *>(p.image.scanLine(int(row)));
+ for (quint32 col = 0; col < width; ++col) {
+ // Premultiplied: no channel may be brighter than alpha.
+ const quint32 v = get(data, at + chunkHeader + 4 * (row * width + col));
+ const quint32 a = v >> 24;
+ line[col] = (a << 24) | (qMin((v >> 16) & 0xff, a) << 16) | (qMin((v >> 8) & 0xff, a) << 8) | qMin(v & 0xff, a);
+ }
+ }
+ p.hotspot = QPoint(int(x), int(y));
+ pictures << p;
+ }
+ if (pictures.isEmpty()) {
+ return false;
+ }
+ out = assemble(pictures);
+ return true;
+}
+}
diff --git a/packages/wildos-settings/src/printers.cpp b/packages/wildos-settings/src/printers.cpp
index 849224e..d87026f 100644
--- a/packages/wildos-settings/src/printers.cpp
+++ b/packages/wildos-settings/src/printers.cpp
@@ -3,13 +3,20 @@
#include <QCoreApplication>
#include <QDateTime>
#include <QHash>
+#include <QMutex>
+#include <QMutexLocker>
#include <QPointer>
#include <QProcess>
#include <QRegularExpression>
#include <QSet>
+#include <QStandardPaths>
#include <QThread>
+#include <QTimer>
#include <QUrl>
+#include <KConfigGroup>
+#include <KSharedConfig>
+
#include <cups/adminutil.h>
#include <cups/cups.h>
#include <cups/pwg.h>
@@ -64,6 +71,204 @@ QString problem(const QStringList &reasons)
return {};
}
+// One ink or toner supply, from marker-* (what CUPS and AirPrint printers
+// report) or a printer-supply entry (what IPP Everywhere requires).
+struct Marker {
+ QString name;
+ QString color;
+ QString type;
+ int level = -1;
+};
+
+bool consumable(const Marker &m)
+{
+ const QString type = m.type.toLower();
+ return m.level >= 0 && !type.contains(QLatin1String("waste")) && (type.isEmpty() || type.contains(QLatin1String("ink")) || type.contains(QLatin1String("toner")));
+}
+
+bool isBlack(const Marker &m)
+{
+ return m.color.compare(QLatin1String("#000000"), Qt::CaseInsensitive) == 0
+ || (m.color.isEmpty() && m.name.contains(QLatin1String("black"), Qt::CaseInsensitive));
+}
+
+// "Black ink 62%, colour 40%": the colours as the one that runs out first,
+// since that is the one to buy.
+QString inkSummary(const QList<Marker> &markers)
+{
+ int black = -1;
+ int colour = -1;
+ bool toner = false;
+ bool ink = false;
+ for (const Marker &m : markers) {
+ if (!consumable(m)) {
+ continue;
+ }
+ toner = toner || m.type.contains(QLatin1String("toner"), Qt::CaseInsensitive);
+ ink = ink || m.type.contains(QLatin1String("ink"), Qt::CaseInsensitive);
+ int &slot = isBlack(m) ? black : colour;
+ slot = slot < 0 ? m.level : std::min(slot, m.level);
+ }
+ const QString substance = toner && !ink ? QStringLiteral("toner") : QStringLiteral("ink");
+ QStringList parts;
+ if (black >= 0) {
+ parts << QStringLiteral("Black %1 %2%").arg(substance).arg(black);
+ }
+ if (colour >= 0) {
+ parts << (black >= 0 ? QStringLiteral("colour %1%").arg(colour) : QStringLiteral("Colour %1 %2%").arg(substance).arg(colour));
+ }
+ return parts.join(QStringLiteral(", "));
+}
+
+// Every supply by the name the printer gives it: "Black Cartridge 62%,
+// Cyan Cartridge 40%".
+QString inkDetail(const QList<Marker> &markers)
+{
+ QStringList parts;
+ for (const Marker &m : markers) {
+ if (consumable(m)) {
+ parts << QStringLiteral("%1 %2%").arg(m.name.isEmpty() ? QStringLiteral("Ink") : m.name).arg(m.level);
+ }
+ }
+ return parts.join(QStringLiteral(", "));
+}
+
+// marker-* lists kept while one printer's attributes are read.
+struct MarkerLists {
+ QStringList names;
+ QStringList colors;
+ QStringList types;
+ QList<int> levels;
+ QList<QByteArray> supplies;
+ QStringList supplyNames;
+
+ bool take(const QByteArray &key, ipp_attribute_t *attr)
+ {
+ if (key == "marker-names") {
+ names = texts(attr);
+ } else if (key == "marker-colors") {
+ colors = texts(attr);
+ } else if (key == "marker-types") {
+ types = texts(attr);
+ } else if (key == "marker-levels") {
+ levels.clear();
+ for (int i = 0; i < ippGetCount(attr); ++i) {
+ levels << ippGetInteger(attr, i);
+ }
+ } else if (key == "printer-supply") {
+ supplies.clear();
+ for (int i = 0; i < ippGetCount(attr); ++i) {
+ int length = 0;
+ const auto *data = static_cast<const char *>(ippGetOctetString(attr, i, &length));
+ supplies << QByteArray(data, data ? length : 0);
+ }
+ } else if (key == "printer-supply-description") {
+ supplyNames = texts(attr);
+ } else {
+ return false;
+ }
+ return true;
+ }
+
+ QList<Marker> markers() const
+ {
+ QList<Marker> out;
+ for (int i = 0; i < levels.size(); ++i) {
+ out << Marker{names.value(i), colors.value(i), types.value(i), levels.at(i)};
+ }
+ if (!out.isEmpty()) {
+ return out;
+ }
+ // "type=inkCartridge;maxcapacity=100;level=62;colorantname=black;"
+ for (int i = 0; i < supplies.size(); ++i) {
+ QHash<QString, QString> fields;
+ for (const QByteArray &pair : supplies.at(i).split(';')) {
+ const int eq = pair.indexOf('=');
+ if (eq > 0) {
+ fields.insert(QString::fromLatin1(pair.left(eq)), QString::fromUtf8(pair.mid(eq + 1)));
+ }
+ }
+ const int capacity = fields.value(QStringLiteral("maxcapacity")).toInt();
+ const int level = fields.value(QStringLiteral("level"), QStringLiteral("-1")).toInt();
+ const QString colorant = fields.value(QStringLiteral("colorantname"));
+ out << Marker{supplyNames.value(i, colorant), colorant.compare(QLatin1String("black"), Qt::CaseInsensitive) == 0 ? QStringLiteral("#000000") : QString(),
+ fields.value(QStringLiteral("type")), capacity > 0 && level >= 0 ? level * 100 / capacity : -1};
+ }
+ return out;
+ }
+};
+
+const char *const markerAttributes[] = {"marker-names", "marker-colors", "marker-types", "marker-levels", "printer-supply", "printer-supply-description"};
+
+// A driverless printer's own supply levels, for a queue CUPS has not
+// printed through yet (the backend copies them into the queue only while
+// it prints). Asked at most once a minute per printer, and never twice at
+// once, so the page's four-second refresh does not wait on a printer that
+// is off.
+QList<Marker> askPrinter(const QString &uri)
+{
+ struct Entry {
+ qint64 at = 0;
+ QList<Marker> markers;
+ };
+ static QMutex mutex;
+ static QHash<QString, Entry> cache;
+ static QSet<QString> asking;
+ const qint64 now = QDateTime::currentSecsSinceEpoch();
+ {
+ QMutexLocker lock(&mutex);
+ const Entry entry = cache.value(uri);
+ if (asking.contains(uri) || (entry.at > 0 && now - entry.at < 60)) {
+ return entry.markers;
+ }
+ asking.insert(uri);
+ }
+
+ QList<Marker> markers;
+ const QByteArray raw = uri.toUtf8();
+ if (cups_dest_t *dest = cupsGetDestWithURI(nullptr, raw.constData())) {
+ char resource[1024];
+ int cancel = 0;
+ // CUPS_DEST_FLAGS_DEVICE talks to the printer, resolving a dnssd://
+ // address first, rather than to the queue.
+ if (http_t *http = cupsConnectDest(dest, CUPS_DEST_FLAGS_DEVICE, 2000, &cancel, resource, sizeof resource, nullptr, nullptr)) {
+ httpSetTimeout(http, 3.0, nullptr, nullptr);
+ const char *resolved = cupsGetOption("resolved_device_uri", dest->num_options, dest->options);
+ ipp_t *request = ippNewRequest(IPP_OP_GET_PRINTER_ATTRIBUTES);
+ ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", nullptr, resolved ? resolved : raw.constData());
+ ippAddStrings(request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD, "requested-attributes", int(std::size(markerAttributes)), nullptr, markerAttributes);
+ if (ipp_t *response = cupsDoRequest(http, request, resource)) {
+ MarkerLists lists;
+ for (ipp_attribute_t *attr = ippFirstAttribute(response); attr; attr = ippNextAttribute(response)) {
+ if (const char *name = ippGetName(attr)) {
+ lists.take(QByteArray(name), attr);
+ }
+ }
+ markers = lists.markers();
+ ippDelete(response);
+ }
+ httpClose(http);
+ }
+ cupsFreeDests(1, dest);
+ }
+
+ // A printer that is off keeps the levels it last reported.
+ QMutexLocker lock(&mutex);
+ asking.remove(uri);
+ if (markers.isEmpty()) {
+ markers = cache.value(uri).markers;
+ }
+ cache.insert(uri, Entry{now, markers});
+ return markers;
+}
+
+// Printers that answer IPP themselves (IPP Everywhere, AirPrint, ipp-usb).
+bool speaksIpp(const QString &uri)
+{
+ return uri.startsWith(QLatin1String("ipp://")) || uri.startsWith(QLatin1String("ipps://"))
+ || (uri.startsWith(QLatin1String("dnssd://")) && uri.contains(QLatin1String("._ipp")));
+}
+
bool cupsRunning()
{
http_t *http = httpConnect2(cupsServer(), ippPort(), nullptr, AF_UNSPEC, cupsEncryption(), 1, 3000, nullptr);
@@ -87,7 +292,8 @@ QVariantList readQueues()
ipp_t *request = ippNewRequest(IPP_OP_CUPS_GET_PRINTERS);
static const char *const wanted[] = {"printer-name", "printer-info", "printer-location", "printer-make-and-model", "printer-state",
- "printer-state-reasons", "printer-is-accepting-jobs", "device-uri", "queued-job-count"};
+ "printer-state-reasons", "printer-is-accepting-jobs", "device-uri", "queued-job-count",
+ "printer-state-message", "marker-names", "marker-colors", "marker-types", "marker-levels"};
ippAddStrings(request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD, "requested-attributes", int(std::size(wanted)), nullptr, wanted);
ipp_t *response = cupsDoRequest(CUPS_HTTP_DEFAULT, request, "/");
if (!response) {
@@ -95,14 +301,35 @@ QVariantList readQueues()
}
QVariantMap current;
+ MarkerLists markers;
auto finish = [&] {
const QString name = current.value(QStringLiteral("name")).toString();
if (!name.isEmpty()) {
+ QList<Marker> supplies = markers.markers();
+ const QString uri = current.value(QStringLiteral("uri")).toString();
+ if (supplies.isEmpty() && speaksIpp(uri)) {
+ supplies = askPrinter(uri);
+ }
+ current.insert(QStringLiteral("ink"), inkSummary(supplies));
+ current.insert(QStringLiteral("inkDetail"), inkDetail(supplies));
+ current.insert(QStringLiteral("scans"), false);
if (current.value(QStringLiteral("info")).toString().isEmpty()) {
current.insert(QStringLiteral("info"), name);
}
const int state = current.value(QStringLiteral("stateCode")).toInt();
- const QString trouble = problem(current.value(QStringLiteral("reasons")).toStringList());
+ QString trouble = problem(current.value(QStringLiteral("reasons")).toStringList());
+ // The usb and ipp backends wait for an unplugged or switched off
+ // printer saying so only in the message, with no reason set.
+ static const QStringList waiting = {QStringLiteral("Waiting for printer to become available"),
+ QStringLiteral("The printer may not exist or is unavailable"), QStringLiteral("Unable to locate printer"),
+ QStringLiteral("The printer is not responding")};
+ const QString message = current.value(QStringLiteral("message")).toString();
+ if (trouble.isEmpty() && current.value(QStringLiteral("stateCode")).toInt() == IPP_PSTATE_PROCESSING
+ && std::any_of(waiting.cbegin(), waiting.cend(), [&message](const QString &w) {
+ return message.startsWith(w);
+ })) {
+ trouble = QStringLiteral("Offline");
+ }
QString status = state == IPP_PSTATE_PROCESSING ? QStringLiteral("Printing")
: state == IPP_PSTATE_STOPPED ? QStringLiteral("Paused")
: QStringLiteral("Ready");
@@ -116,6 +343,7 @@ QVariantList readQueues()
list << current;
}
current.clear();
+ markers = MarkerLists();
};
for (ipp_attribute_t *attr = ippFirstAttribute(response); attr; attr = ippNextAttribute(response)) {
const char *name = ippGetName(attr);
@@ -139,12 +367,16 @@ QVariantList readQueues()
current.insert(QStringLiteral("uri"), text(attr));
} else if (key == "printer-state") {
current.insert(QStringLiteral("stateCode"), ippGetInteger(attr, 0));
+ } else if (key == "printer-state-message") {
+ current.insert(QStringLiteral("message"), text(attr));
} else if (key == "printer-state-reasons") {
current.insert(QStringLiteral("reasons"), texts(attr));
} else if (key == "printer-is-accepting-jobs") {
current.insert(QStringLiteral("accepting"), ippGetBoolean(attr, 0) != 0);
} else if (key == "queued-job-count") {
current.insert(QStringLiteral("jobs"), ippGetInteger(attr, 0));
+ } else {
+ markers.take(key, attr);
}
}
finish();
@@ -218,6 +450,7 @@ int onDest(void *data, unsigned flags, cups_dest_t *dest)
{QStringLiteral("model"), QString::fromUtf8(cupsGetOption("printer-make-and-model", dest->num_options, dest->options))},
{QStringLiteral("location"), QString::fromUtf8(cupsGetOption("printer-location", dest->num_options, dest->options))},
{QStringLiteral("uri"), uri},
+ {QStringLiteral("scans"), false},
};
state->publish(state->found);
return 1;
@@ -234,6 +467,22 @@ void detach(QProcess *process)
process->setStandardInputFile(QProcess::nullDevice());
}
+// lpadmin's last line, with the two failures people meet most put in
+// plain words.
+QString plainReason(const QString &output)
+{
+ static const QRegularExpression unreachable(QStringLiteral("Unable to connect|not known|No route to host|Connection refused|timed out"),
+ QRegularExpression::CaseInsensitiveOption);
+ static const QRegularExpression needsDriver(QStringLiteral("Unable to create PPD|does not support required IPP"), QRegularExpression::CaseInsensitiveOption);
+ if (unreachable.match(output).hasMatch()) {
+ return QStringLiteral("Nothing answered at that address. Check the address, and that the printer is switched on and on the same network.");
+ }
+ if (needsDriver.match(output).hasMatch()) {
+ return QStringLiteral("This printer doesn't work without a driver. Choose one in More printer settings.");
+ }
+ return output.section(QLatin1Char('\n'), -1).remove(QRegularExpression(QStringLiteral("^\\S+: ")));
+}
+
bool refused(const QString &output)
{
static const QRegularExpression words(QStringLiteral("forbidden|unauthori[sz]ed|not authori[sz]ed|password|permission"),
@@ -267,6 +516,7 @@ void Printers::reload()
}
self->m_available = running;
self->m_printers = queues;
+ self->markScanners();
Q_EMIT self->changed();
});
});
@@ -296,6 +546,7 @@ void Printers::search()
QMetaObject::invokeMethod(qApp, [self, generation, found] {
if (self && self->m_searchGeneration == generation) {
self->m_found = found;
+ self->markScanners();
Q_EMIT self->foundChanged();
}
});
@@ -323,6 +574,7 @@ void Printers::search()
});
connect(thread, &QThread::finished, thread, &QObject::deleteLater);
thread->start();
+ findScanners();
}
void Printers::stopSearch()
@@ -367,7 +619,7 @@ QString Printers::queueName(const QString &name) const
}
void Printers::admin(const QString &busy, const QString &program, const QStringList &arguments, const QString &successTitle, const QString &success,
- const QString &failure, const std::function<void()> &then)
+ const QString &failure, const std::function<void()> &then, const std::function<void()> &otherwise)
{
setBusy(busy);
auto process = new QProcess(this);
@@ -388,7 +640,10 @@ void Printers::admin(const QString &busy, const QString &program, const QStringL
if (!refused(output)) {
setBusy({});
reload();
- Q_EMIT failed(failure, output.section(QLatin1Char('\n'), -1).remove(QRegularExpression(QStringLiteral("^\\S+: "))));
+ Q_EMIT failed(failure, plainReason(output));
+ if (otherwise) {
+ otherwise();
+ }
return;
}
// CUPS wants an administrator: ask through polkit.
@@ -405,10 +660,15 @@ void Printers::admin(const QString &busy, const QString &program, const QStringL
if (then) {
then();
}
- } else if (code == 126 || code == 127) {
- Q_EMIT failed(failure, QStringLiteral("An administrator's password is needed for this."));
} else {
- Q_EMIT failed(failure, more.section(QLatin1Char('\n'), -1).remove(QRegularExpression(QStringLiteral("^\\S+: "))));
+ if (code == 126 || code == 127) {
+ Q_EMIT failed(failure, QStringLiteral("An administrator's password is needed for this."));
+ } else {
+ Q_EMIT failed(failure, plainReason(more));
+ }
+ if (otherwise) {
+ otherwise();
+ }
}
});
elevated->start(QStringLiteral("pkexec"), QStringList{program} + arguments);
@@ -438,6 +698,18 @@ void Printers::add(const QString &uri, const QString &name)
if (first) {
setDefault(queue, false);
}
+ },
+ [this, queue] {
+ // lpadmin creates the queue before it asks the printer what it
+ // can do, so a printer it can't drive would leave a queue that
+ // only ever fails.
+ auto cleanup = new QProcess(this);
+ detach(cleanup);
+ connect(cleanup, &QProcess::finished, this, [this, cleanup] {
+ cleanup->deleteLater();
+ reload();
+ });
+ cleanup->start(QStringLiteral("/usr/sbin/lpadmin"), {QStringLiteral("-x"), queue});
});
}
@@ -689,7 +961,8 @@ void onDevice(const char *deviceClass, const char *, const char *info, const cha
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)) {
+ // cups-brf is CUPS's braille embosser output to a file, not a device.
+ if (!address.contains(QLatin1Char(':')) || address.startsWith(QLatin1String("cups-brf:")) || list->known.contains(address)) {
return;
}
QString makeAndModel = QString::fromUtf8(model);
@@ -945,3 +1218,209 @@ void Printers::addWithDriver(const QString &uri, const QString &driver, const QS
}
});
}
+
+namespace
+{
+bool loopback(const QString &host)
+{
+ return host == QLatin1String("localhost") || host.startsWith(QLatin1String("127.")) || host == QLatin1String("::1");
+}
+
+// sane-airscan's own list of the eSCL and WSD scanners it finds, one per
+// line under [devices]: Office printer = http://192.168.1.20:80/eSCL/, eSCL
+QVariantList parseAirscan(const QString &output)
+{
+ static const QRegularExpression line(QStringLiteral("^\\s*(.+?)\\s*=\\s*(\\S+?)\\s*,\\s*(eSCL|WSD)\\s*$"));
+ // The same scanner over eSCL and WSD, IPv4 and IPv6, and on loopback
+ // too when it is on this computer, is one entry: the address another
+ // computer would use, over eSCL, where it offers one.
+ auto rank = [](const QString &url, const QString &protocol) {
+ const QString host = QUrl(url).host();
+ return (protocol == QLatin1String("eSCL") ? 4 : 0) + (url.contains(QLatin1Char('[')) ? 0 : 2) + (loopback(host) ? 0 : 1);
+ };
+ QVariantList out;
+ QHash<QString, int> at;
+ const QStringList lines = output.split(QLatin1Char('\n'));
+ for (const QString &text : lines) {
+ const auto m = line.match(text);
+ if (!m.hasMatch()) {
+ continue;
+ }
+ const QString name = m.captured(1);
+ const QString url = m.captured(2);
+ const QString protocol = m.captured(3);
+ const QVariantMap entry{{QStringLiteral("name"), name}, {QStringLiteral("url"), url}, {QStringLiteral("protocol"), protocol}};
+ const QString key = name.toLower();
+ if (!at.contains(key)) {
+ at.insert(key, int(out.size()));
+ out << entry;
+ } else {
+ const QVariantMap kept = out.at(at.value(key)).toMap();
+ if (rank(url, protocol) > rank(kept.value(QStringLiteral("url")).toString(), kept.value(QStringLiteral("protocol")).toString())) {
+ out[at.value(key)] = entry;
+ }
+ }
+ }
+ return out;
+}
+
+// The DNS-SD instance name in a dnssd:// device address, the name a
+// printer's scanner half announces itself by too.
+QString serviceName(const QString &uri)
+{
+ if (!uri.startsWith(QLatin1String("dnssd://"))) {
+ return {};
+ }
+ const QString rest = uri.mid(8);
+ const int end = int(rest.indexOf(QLatin1String("._")));
+ return QUrl::fromPercentEncoding(rest.left(end < 0 ? rest.size() : end).toUtf8());
+}
+
+bool sameDevice(const QVariantMap &scanner, const QVariantMap &printer)
+{
+ const QString name = scanner.value(QStringLiteral("name")).toString();
+ const QString uri = printer.value(QStringLiteral("uri")).toString();
+ QString queue = printer.value(QStringLiteral("name")).toString();
+ queue.replace(QLatin1Char('_'), QLatin1Char(' '));
+ for (const QString &candidate : {serviceName(uri), printer.value(QStringLiteral("info")).toString(), queue}) {
+ if (!candidate.isEmpty() && candidate.compare(name, Qt::CaseInsensitive) == 0) {
+ return true;
+ }
+ }
+ // A printer added by its address: the same host. Every ipp-usb device
+ // is on this computer's own address, so there only the name counts.
+ const QString host = QUrl(uri).host();
+ return !host.isEmpty() && !loopback(host) && host.compare(QUrl(scanner.value(QStringLiteral("url")).toString()).host(), Qt::CaseInsensitive) == 0;
+}
+
+KConfigGroup scannerConfig()
+{
+ return KSharedConfig::openConfig(QStringLiteral("wildos-settingsrc"), KConfig::NoGlobals)->group(QStringLiteral("Scanners"));
+}
+}
+
+QStringList Printers::addedScanners() const
+{
+ return scannerConfig().readEntry("Added", QStringList());
+}
+
+QVariantList Printers::scanners() const
+{
+ QVariantList out;
+ const QStringList added = addedScanners();
+ for (const QString &name : added) {
+ QVariantMap entry{{QStringLiteral("name"), name}, {QStringLiteral("url"), QString()}, {QStringLiteral("seen"), false}};
+ for (const QVariant &s : m_networkScanners) {
+ if (s.toMap().value(QStringLiteral("name")).toString().compare(name, Qt::CaseInsensitive) == 0) {
+ entry.insert(QStringLiteral("url"), s.toMap().value(QStringLiteral("url")));
+ entry.insert(QStringLiteral("seen"), true);
+ }
+ }
+ out << entry;
+ }
+ return out;
+}
+
+bool Printers::partOfPrinter(const QVariantMap &scanner) const
+{
+ for (const QVariantList *list : {&m_printers, &m_found}) {
+ for (const QVariant &p : *list) {
+ if (sameDevice(scanner, p.toMap())) {
+ return true;
+ }
+ }
+ }
+ return false;
+}
+
+QVariantList Printers::foundScanners() const
+{
+ QVariantList out;
+ const QStringList added = addedScanners();
+ for (const QVariant &s : m_networkScanners) {
+ const QVariantMap scanner = s.toMap();
+ if (!added.contains(scanner.value(QStringLiteral("name")).toString(), Qt::CaseInsensitive) && !partOfPrinter(scanner)) {
+ out << scanner;
+ }
+ }
+ return out;
+}
+
+void Printers::markScanners()
+{
+ for (QVariantList *list : {&m_printers, &m_found}) {
+ for (QVariant &p : *list) {
+ QVariantMap map = p.toMap();
+ const bool scans = std::any_of(m_networkScanners.cbegin(), m_networkScanners.cend(), [&map](const QVariant &s) {
+ return sameDevice(s.toMap(), map);
+ });
+ if (map.value(QStringLiteral("scans")).toBool() != scans) {
+ map.insert(QStringLiteral("scans"), scans);
+ p = map;
+ }
+ }
+ }
+ Q_EMIT scannersChanged();
+}
+
+void Printers::findScanners()
+{
+ const QString program = QStandardPaths::findExecutable(QStringLiteral("airscan-discover"));
+ if (m_findingScanners || program.isEmpty()) {
+ return;
+ }
+ m_findingScanners = true;
+ Q_EMIT scannersChanged();
+ auto process = new QProcess(this);
+ detach(process);
+ connect(process, &QProcess::finished, this, [this, process] {
+ const QVariantList found = parseAirscan(QString::fromUtf8(process->readAllStandardOutput()));
+ process->deleteLater();
+ m_networkScanners = found;
+ m_findingScanners = false;
+ m_scannersLooked = true;
+ markScanners();
+ Q_EMIT changed();
+ Q_EMIT foundChanged();
+ });
+ // airscan-discover listens for a few seconds, then prints what it
+ // heard; a network that never answers must not leave it running.
+ QTimer::singleShot(20000, process, [process] {
+ process->kill();
+ });
+ process->start(program, {});
+}
+
+void Printers::addScanner(const QString &name)
+{
+ QStringList added = addedScanners();
+ if (!added.contains(name, Qt::CaseInsensitive)) {
+ added << name;
+ KConfigGroup group = scannerConfig();
+ group.writeEntry("Added", added);
+ group.sync();
+ }
+ Q_EMIT scannersChanged();
+ Q_EMIT done(QStringLiteral("Scanner added"), name + QStringLiteral(" is ready to use in Capture."));
+}
+
+void Printers::removeScanner(const QString &name)
+{
+ QStringList added = addedScanners();
+ added.removeIf([&name](const QString &n) {
+ return n.compare(name, Qt::CaseInsensitive) == 0;
+ });
+ KConfigGroup group = scannerConfig();
+ group.writeEntry("Added", added);
+ group.sync();
+ Q_EMIT scannersChanged();
+ Q_EMIT done(QStringLiteral("Scanner removed"), QStringLiteral("It's no longer in your list. Capture can still find it on the network."));
+}
+
+bool Printers::openCapture() const
+{
+ // Started by name, like Devices' openBackup: gtk-launch isn't in the
+ // image.
+ const QString program = QStandardPaths::findExecutable(QStringLiteral("wildos-capture"));
+ return !program.isEmpty() && QProcess::startDetached(program, {QStringLiteral("--scan")});
+}
diff --git a/packages/wildos-settings/src/printers.h b/packages/wildos-settings/src/printers.h
index 071b3af..9d976eb 100644
--- a/packages/wildos-settings/src/printers.h
+++ b/packages/wildos-settings/src/printers.h
@@ -20,6 +20,15 @@
// 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).
//
+// Printers and scanners also shows ink and toner levels, from the queue
+// (marker-levels, which CUPS copies from the printer while it prints) or,
+// for a driverless printer CUPS has not printed to yet, asked of the
+// printer itself. Scanners come from sane-airscan's discovery of eSCL and
+// WSD scanners on the network: one that is part of a printer marks that
+// printer as one that scans; one on its own can be added to the list,
+// which only remembers it for this account, since sane-airscan finds it
+// without being told.
+//
// 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
@@ -39,6 +48,16 @@ class Printers : public QObject
Q_PROPERTY(bool findingDevices READ findingDevices NOTIFY devicesChanged)
Q_PROPERTY(bool driversReady READ driversReady NOTIFY driversChanged)
Q_PROPERTY(bool loadingDrivers READ loadingDrivers NOTIFY driversChanged)
+ // Network scanners added to the list: { name, url, seen }, where seen
+ // says the last look found it.
+ Q_PROPERTY(QVariantList scanners READ scanners NOTIFY scannersChanged)
+ // Network scanners found that are neither added nor part of a printer
+ // in the list or in `found`: { name, url }.
+ Q_PROPERTY(QVariantList foundScanners READ foundScanners NOTIFY scannersChanged)
+ Q_PROPERTY(bool findingScanners READ findingScanners NOTIFY scannersChanged)
+ // At least one look for scanners has finished, so a scanner not seen is
+ // really missing.
+ Q_PROPERTY(bool scannersLooked READ scannersLooked NOTIFY scannersChanged)
public:
explicit Printers(QObject *parent = nullptr);
@@ -53,8 +72,13 @@ public:
bool findingDevices() const { return m_findingDevices; }
bool driversReady() const { return !m_drivers.isEmpty(); }
bool loadingDrivers() const { return m_loadingDrivers; }
+ QVariantList scanners() const;
+ QVariantList foundScanners() const;
+ bool findingScanners() const { return m_findingScanners; }
+ bool scannersLooked() const { return m_scannersLooked; }
Q_INVOKABLE void reload();
+ // Looks for printers (CUPS's DNS-SD browse) and scanners at once.
Q_INVOKABLE void search();
Q_INVOKABLE void stopSearch();
// uri is a device URI from `found` (dnssd://...) or ipp://host/...
@@ -90,21 +114,32 @@ public:
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_INVOKABLE void addScanner(const QString &name);
+ Q_INVOKABLE void removeScanner(const QString &name);
+ // Capture, on its Scan tab.
+ Q_INVOKABLE bool openCapture() const;
+
Q_SIGNALS:
void changed();
void foundChanged();
void busyChanged();
void devicesChanged();
void driversChanged();
+ void scannersChanged();
void failed(const QString &title, const QString &reason);
void done(const QString &title, const QString &message);
private:
void setBusy(const QString &busy);
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 = {});
+ const QString &failure, const std::function<void()> &then = {}, const std::function<void()> &otherwise = {});
QString queueName(const QString &name) const;
void finishDevices(const QVariantList &devices);
+ void findScanners();
+ // Sets `scans` on each printer and found printer from the scanners seen.
+ void markScanners();
+ bool partOfPrinter(const QVariantMap &scanner) const;
+ QStringList addedScanners() const;
struct Driver {
QString ppd;
@@ -123,4 +158,7 @@ private:
bool m_findingDevices = false;
QList<Driver> m_drivers;
bool m_loadingDrivers = false;
+ QVariantList m_networkScanners;
+ bool m_findingScanners = false;
+ bool m_scannersLooked = false;
};
diff --git a/packages/wildos-settings/src/processor.cpp b/packages/wildos-settings/src/processor.cpp
index c29a68f..743abe7 100644
--- a/packages/wildos-settings/src/processor.cpp
+++ b/packages/wildos-settings/src/processor.cpp
@@ -7,22 +7,46 @@
namespace
{
const QString wildosDir = QStringLiteral("/etc/wildos");
-const QString choiceFile = QStringLiteral("/etc/wildos/cpu-threads");
const QString helper = QStringLiteral("/usr/libexec/wildos/settings-cpu-threads");
-QByteArray readSmt(const char *name)
+QByteArray readFile(const QString &path)
{
- QFile file(QStringLiteral("/sys/devices/system/cpu/smt/") + QLatin1String(name));
+ QFile file(path);
return file.open(QIODevice::ReadOnly) ? file.readAll().trimmed() : QByteArray();
}
+
+QByteArray readSmt(const char *name)
+{
+ return readFile(QStringLiteral("/sys/devices/system/cpu/smt/") + QLatin1String(name));
+}
+
+// "on", "off", or empty while the kernel decides.
+QByteArray threadChoice()
+{
+ return readFile(QStringLiteral("/etc/wildos/cpu-threads"));
+}
+
+bool strictLevel()
+{
+ const QByteArray level = readFile(QStringLiteral("/etc/wildos/protection-level"));
+ return level == "strict" || level == "maximum";
+}
+
+// 40_wildos.cfg takes spectre_v2=on off the start-up options unless extra
+// protection applies, so its presence says which the running kernel got.
+bool extraProtectionRunning()
+{
+ const QByteArray cmdline = readFile(QStringLiteral("/proc/cmdline"));
+ return (" " + cmdline + " ").contains(" spectre_v2=on ");
+}
}
Processor::Processor(QObject *parent)
: QObject(parent)
, m_watcher(new QFileSystemWatcher(this))
{
- // The choice and the protection level both live in /etc/wildos, written by
- // root helpers, so the switch follows them without Settings asking.
+ // The choices and the protection level all live in /etc/wildos, written
+ // by root helpers, so the switches follow them without Settings asking.
if (QFile::exists(wildosDir)) {
m_watcher->addPath(wildosDir);
}
@@ -38,7 +62,17 @@ bool Processor::threadsAvailable() const
bool Processor::everyThread() const
{
- return QFile::exists(choiceFile);
+ if (everyThreadLocked()) {
+ return false;
+ }
+ const QByteArray choice = threadChoice();
+ if (choice == "on") {
+ return true;
+ }
+ if (choice == "off") {
+ return false;
+ }
+ return everyThreadActive();
}
bool Processor::everyThreadActive() const
@@ -46,11 +80,36 @@ bool Processor::everyThreadActive() const
return readSmt("active") == "1";
}
+bool Processor::threadsPending() const
+{
+ if (everyThreadLocked()) {
+ return everyThreadActive();
+ }
+ const QByteArray choice = threadChoice();
+ if (choice != "on" && choice != "off") {
+ return false;
+ }
+ return (choice == "on") != everyThreadActive();
+}
+
bool Processor::everyThreadLocked() const
{
- QFile file(QStringLiteral("/etc/wildos/protection-level"));
- const QByteArray level = file.open(QIODevice::ReadOnly) ? file.readAll().trimmed() : QByteArray();
- return level == "strict" || level == "maximum";
+ return extraProtection();
+}
+
+bool Processor::extraProtection() const
+{
+ return strictLevel() || readFile(QStringLiteral("/etc/wildos/cpu-protection")) == "extra";
+}
+
+bool Processor::extraProtectionLocked() const
+{
+ return strictLevel();
+}
+
+bool Processor::extraProtectionPending() const
+{
+ return extraProtection() != extraProtectionRunning();
}
void Processor::setEveryThread(bool on)
@@ -58,6 +117,19 @@ void Processor::setEveryThread(bool on)
if (m_busy || on == everyThread() || (on && everyThreadLocked())) {
return;
}
+ run({helper, on ? QStringLiteral("on") : QStringLiteral("off")});
+}
+
+void Processor::setExtraProtection(bool on)
+{
+ if (m_busy || on == extraProtection() || (!on && extraProtectionLocked())) {
+ return;
+ }
+ run({helper, QStringLiteral("protect"), on ? QStringLiteral("on") : QStringLiteral("off")});
+}
+
+void Processor::run(const QStringList &args)
+{
m_busy = true;
Q_EMIT changed();
auto process = new QProcess(this);
@@ -67,11 +139,11 @@ void Processor::setEveryThread(bool on)
if (code == 126 || code == 127) {
Q_EMIT failed(QStringLiteral("Nothing was changed because the password was not given."));
} else if (code == 3) {
- Q_EMIT failed(QStringLiteral("Strict and Maximum protection keep this off."));
+ Q_EMIT failed(QStringLiteral("Strict and Maximum protection keep every processor protection on."));
} else if (code != 0) {
Q_EMIT failed(QStringLiteral("The setting could not be changed."));
}
Q_EMIT changed();
});
- process->start(QStringLiteral("pkexec"), {helper, on ? QStringLiteral("on") : QStringLiteral("off")});
+ process->start(QStringLiteral("pkexec"), args);
}
diff --git a/packages/wildos-settings/src/processor.h b/packages/wildos-settings/src/processor.h
index e6acc97..8b58172 100644
--- a/packages/wildos-settings/src/processor.h
+++ b/packages/wildos-settings/src/processor.h
@@ -5,11 +5,20 @@
class QFileSystemWatcher;
+// The processor's thread and flaw protection choices. Both are boot options
+// that /etc/default/grub.d/40_wildos.cfg builds from files settings-cpu-threads
+// writes, so what was chosen and what the running kernel does can differ
+// until the next start-up.
+//
// "Use every processor thread" (hyper-threading), in System > Power and
-// battery, with shortcuts from Windows mode. Wild OS starts with the second
-// thread of each core off; turning it on is a boot option written by
-// settings-cpu-threads, so what was chosen and what the running kernel does
-// can differ until the next start-up. Strict and Maximum protection keep it off.
+// battery, with shortcuts from Windows mode. Until it is touched the kernel
+// decides: every thread, except on processors it lists as unsafe for sharing
+// a core.
+//
+// "Extra processor protection", in Privacy and security: Kicksecure's full
+// set of processor flaw protections, forced on whether or not the processor
+// needs them, with the second thread of every core off. Off by default;
+// Strict and Maximum protection always have it.
class Processor : public QObject
{
Q_OBJECT
@@ -18,12 +27,21 @@ class Processor : public QObject
// Whether the processor has two threads per core at all.
Q_PROPERTY(bool threadsAvailable READ threadsAvailable CONSTANT)
- // What was chosen; it applies from the next start-up.
+ // What the switch shows: the choice, or what the kernel does until one
+ // is made.
Q_PROPERTY(bool everyThread READ everyThread NOTIFY changed)
// What the running kernel does.
Q_PROPERTY(bool everyThreadActive READ everyThreadActive NOTIFY changed)
- // Strict or Maximum protection, which keep it off.
+ // A restart is needed for the thread choice to take effect.
+ Q_PROPERTY(bool threadsPending READ threadsPending NOTIFY changed)
+ // Extra processor protection, Strict or Maximum, which keep it off.
Q_PROPERTY(bool everyThreadLocked READ everyThreadLocked NOTIFY changed)
+ // Extra processor protection is chosen, or comes with Strict or Maximum.
+ Q_PROPERTY(bool extraProtection READ extraProtection NOTIFY changed)
+ // Strict or Maximum protection, which keep extra protection on.
+ Q_PROPERTY(bool extraProtectionLocked READ extraProtectionLocked NOTIFY changed)
+ // A restart is needed for extra protection to take effect.
+ Q_PROPERTY(bool extraProtectionPending READ extraProtectionPending NOTIFY changed)
// A change is waiting for the password or being written.
Q_PROPERTY(bool busy READ busy NOTIFY changed)
@@ -33,16 +51,23 @@ public:
bool threadsAvailable() const;
bool everyThread() const;
bool everyThreadActive() const;
+ bool threadsPending() const;
bool everyThreadLocked() const;
+ bool extraProtection() const;
+ bool extraProtectionLocked() const;
+ bool extraProtectionPending() const;
bool busy() const { return m_busy; }
Q_INVOKABLE void setEveryThread(bool on);
+ Q_INVOKABLE void setExtraProtection(bool on);
Q_SIGNALS:
void changed();
void failed(const QString &message);
private:
+ void run(const QStringList &args);
+
QFileSystemWatcher *m_watcher = nullptr;
bool m_busy = false;
};
diff --git a/packages/wildos-settings/src/recovery.cpp b/packages/wildos-settings/src/recovery.cpp
index f1ab551..b57056f 100644
--- a/packages/wildos-settings/src/recovery.cpp
+++ b/packages/wildos-settings/src/recovery.cpp
@@ -207,7 +207,11 @@ void Recovery::reset(const QString &how)
void Recovery::openBackup()
{
- QProcess::startDetached(QStringLiteral("gtk-launch"), {backupDesktop});
+ // By name, as Devices does: gtk-launch isn't in the image.
+ const QString program = QStandardPaths::findExecutable(QStringLiteral("wildos-backup"));
+ if (!program.isEmpty()) {
+ QProcess::startDetached(program, {});
+ }
}
void Recovery::restart()
diff --git a/packages/wildos-settings/src/securetime.cpp b/packages/wildos-settings/src/securetime.cpp
new file mode 100644
index 0000000..7a43bdd
--- /dev/null
+++ b/packages/wildos-settings/src/securetime.cpp
@@ -0,0 +1,77 @@
+#include "securetime.h"
+
+#include <QDBusConnection>
+#include <QDBusMessage>
+#include <QDBusObjectPath>
+#include <QDBusVariant>
+#include <QDateTime>
+#include <QFile>
+#include <QRegularExpression>
+
+#include <algorithm>
+
+namespace SecureTime
+{
+bool running()
+{
+ const QString systemd = QStringLiteral("org.freedesktop.systemd1");
+ auto getUnit = QDBusMessage::createMethodCall(systemd, QStringLiteral("/org/freedesktop/systemd1"), QStringLiteral("org.freedesktop.systemd1.Manager"),
+ QStringLiteral("GetUnit"));
+ getUnit << QStringLiteral("sdwdate.service");
+ const QDBusMessage unit = QDBusConnection::systemBus().call(getUnit, QDBus::Block, 3000);
+ // Not loaded means not installed, masked, or never started.
+ if (unit.type() != QDBusMessage::ReplyMessage) {
+ return false;
+ }
+ auto get = QDBusMessage::createMethodCall(systemd, unit.arguments().value(0).value<QDBusObjectPath>().path(),
+ QStringLiteral("org.freedesktop.DBus.Properties"), QStringLiteral("Get"));
+ get << QStringLiteral("org.freedesktop.systemd1.Unit") << QStringLiteral("ActiveState");
+ const QDBusMessage reply = QDBusConnection::systemBus().call(get, QDBus::Block, 3000);
+ if (reply.type() != QDBusMessage::ReplyMessage) {
+ return false;
+ }
+ const QString state = reply.arguments().value(0).value<QDBusVariant>().variant().toString();
+ return state == QLatin1String("active") || state == QLatin1String("activating") || state == QLatin1String("reloading");
+}
+
+bool setThisBoot()
+{
+ return QFile::exists(QStringLiteral("/run/sdwdate/first_success"));
+}
+
+bool settingNow()
+{
+ return !setThisBoot() && running();
+}
+
+qint64 secondsBehind(const QString &aptDetails)
+{
+ static const QRegularExpression stamp(QStringLiteral("not live until (\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\dZ)"),
+ QRegularExpression::CaseInsensitiveOption);
+ qint64 newest = 0;
+ auto it = stamp.globalMatch(aptDetails);
+ while (it.hasNext()) {
+ const QDateTime at = QDateTime::fromString(it.next().captured(1), Qt::ISODate);
+ if (at.isValid()) {
+ newest = std::max(newest, at.toSecsSinceEpoch());
+ }
+ }
+ return newest > 0 ? std::max<qint64>(0, newest - QDateTime::currentSecsSinceEpoch()) : 0;
+}
+
+QString durationText(qint64 seconds)
+{
+ // Rounded down: the signing times only show the clock is at least this
+ // far behind.
+ auto count = [](qint64 n, const char *one, const char *many) {
+ return QStringLiteral("%1 %2").arg(n).arg(QLatin1String(n == 1 ? one : many));
+ };
+ if (seconds >= 2 * 86400) {
+ return count(seconds / 86400, "day", "days");
+ }
+ if (seconds >= 3600) {
+ return count(seconds / 3600, "hour", "hours");
+ }
+ return count(std::max<qint64>(1, seconds / 60), "minute", "minutes");
+}
+}
diff --git a/packages/wildos-settings/src/securetime.h b/packages/wildos-settings/src/securetime.h
new file mode 100644
index 0000000..f97be58
--- /dev/null
+++ b/packages/wildos-settings/src/securetime.h
@@ -0,0 +1,25 @@
+#pragma once
+
+#include <QString>
+
+// sdwdate, Kicksecure's time service: it sets the clock from onion sites
+// through Tor a few minutes after start-up, instead of asking a time server
+// directly, so timedated knows nothing of it and reports no automatic time.
+namespace SecureTime
+{
+// The service is running or starting (it restarts itself after a failure).
+bool running();
+// It has set the clock since this start-up: it writes this marker in /run,
+// which every start-up empties.
+bool setThisBoot();
+// Running but not done yet, so a clock that is hours off is still expected
+// to be put right without anyone's help.
+bool settingNow();
+
+// How far behind the clock is at least, from the signing times apt named
+// that are still in the future ("Not live until 2026-11-14T03:33:03Z" from
+// sqv). 0 when none is.
+qint64 secondsBehind(const QString &aptDetails);
+// "8 hours", "25 minutes", "3 days"
+QString durationText(qint64 seconds);
+}
diff --git a/packages/wildos-settings/src/updates.cpp b/packages/wildos-settings/src/updates.cpp
index 2cac5e0..4c3258a 100644
--- a/packages/wildos-settings/src/updates.cpp
+++ b/packages/wildos-settings/src/updates.cpp
@@ -1,24 +1,31 @@
#include "updates.h"
+#include "securetime.h"
#include <algorithm>
+#include <ctime>
#include <KService>
+#include <NetworkManagerQt/Manager>
#include <PackageKit/Daemon>
+#include <QCoreApplication>
#include <QDBusConnection>
#include <QDBusConnectionInterface>
#include <QDBusMessage>
#include <QDBusObjectPath>
#include <QDBusPendingCallWatcher>
#include <QDBusPendingReply>
+#include <QDBusVariant>
#include <QDir>
#include <QFile>
#include <QFileInfo>
+#include <QFileSystemWatcher>
#include <QHash>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
+#include <QMetaEnum>
#include <QNetworkAccessManager>
#include <QNetworkProxy>
#include <QNetworkReply>
@@ -41,6 +48,22 @@ namespace
constexpr qint64 lockPatienceMs = 30 * 60 * 1000;
constexpr int lockRetryMs = 15 * 1000;
+// A check that fails because the connection is not ready yet tries again,
+// first after a few seconds and then less often, for about three minutes
+// before it says why. Tor alone can take that long after start-up.
+constexpr qint64 quietRetryMs = 3 * 60 * 1000;
+constexpr int firstRetryMs = 5 * 1000;
+constexpr int longestRetryMs = 60 * 1000;
+// In the first minutes after start-up any failure is treated so: the
+// network, Tor and the clock (sdwdate may move it) are all still settling.
+constexpr qint64 settlingSeconds = 5 * 60;
+// A clock that sdwdate has yet to set is waited for this long at most,
+// looking every few seconds whether it has. Its first run after start-up
+// took four minutes on the PC this was seen on, with two onion sites
+// timing out.
+constexpr qint64 clockWaitMs = 15 * 60 * 1000;
+constexpr int clockPollMs = 2000;
+
// Where Settings remembers, until the PC restarts, that an update asked for
// a restart: the runtime folder is emptied at every boot.
QString restartMarker()
@@ -140,12 +163,10 @@ bool needsRestart(const QStringList &packageIds)
return false;
}
-// The servers Wild OS's own updates come from. Any other source was added
-// by the person or by an app's installer (Steam, Chrome, VS Code).
-QStringList ownHosts()
+QStringList hostsIn(const QString &path)
{
- QStringList hosts{QStringLiteral("deb.wildos.io")};
- QFile sources(QStringLiteral("/etc/apt/sources.list.d/wildos.sources"));
+ QStringList hosts;
+ QFile sources(path);
if (sources.open(QIODevice::ReadOnly)) {
static const QRegularExpression uri(QStringLiteral("https?://([^/\\s]+)"));
auto it = uri.globalMatch(QString::fromUtf8(sources.readAll()));
@@ -159,6 +180,248 @@ QStringList ownHosts()
return hosts;
}
+// The servers Wild OS's own packages come from.
+QStringList wildosHosts()
+{
+ QStringList hosts{QStringLiteral("deb.wildos.io")};
+ for (const QString &host : hostsIn(QStringLiteral("/etc/apt/sources.list.d/wildos.sources"))) {
+ if (!hosts.contains(host)) {
+ hosts << host;
+ }
+ }
+ return hosts;
+}
+
+// Every server the system itself updates from: Wild OS's, and Debian's and
+// Kicksecure's, which Kicksecure lists in debian.sources and the image in
+// sources.list, mostly through Tor. Any other source was added by the
+// person or by an app's installer (Steam, Chrome, VS Code).
+QStringList ownHosts()
+{
+ QStringList hosts = wildosHosts();
+ hosts << QStringLiteral("deb.debian.org") << QStringLiteral("security.debian.org") << QStringLiteral("fasttrack.debian.net")
+ << QStringLiteral("deb.kicksecure.com");
+ for (const QString &path : {QStringLiteral("/etc/apt/sources.list.d/debian.sources"), QStringLiteral("/etc/apt/sources.list")}) {
+ for (const QString &host : hostsIn(path)) {
+ if (!hosts.contains(host)) {
+ hosts << host;
+ }
+ }
+ }
+ return hosts;
+}
+
+// apt's lines that name a source, without its notices about sources that
+// are fine, such as one without 32-bit packages on a PC with 32-bit support
+// turned on.
+QStringList sourceLines(const QString &details)
+{
+ QStringList lines;
+ const QStringList all = details.split(QLatin1Char('\n'), Qt::SkipEmptyParts);
+ for (const QString &line : all) {
+ if (!line.contains(QLatin1String("Skipping acquire")) && !line.contains(QLatin1String("support architecture"))) {
+ lines << line;
+ }
+ }
+ return lines;
+}
+
+bool aboutSigning(const QString &line)
+{
+ static const QStringList words = {
+ QStringLiteral("signature"), QStringLiteral("not signed"), QStringLiteral("NO_PUBKEY"), QStringLiteral("EXPKEYSIG"),
+ QStringLiteral("Signing key"), QStringLiteral("OpenPGP"), QStringLiteral("not valid yet"), QStringLiteral("is expired"),
+ };
+ return std::any_of(words.cbegin(), words.cend(), [&line](const QString &word) {
+ return line.contains(word, Qt::CaseInsensitive);
+ });
+}
+
+// A signature from after the time the clock shows. Right after start-up
+// sdwdate can set the clock back a minute or two, and a source signed in
+// that gap (Wild OS's, right after a release) fails until the clock passes
+// the signing time again. Seen as sqv's "created after the --not-after
+// date" and "Not live until <time>"; the second is also what a clock hours
+// behind gives (a PC whose hardware clock kept local time for Windows).
+bool signedLater(const QString &line)
+{
+ return line.contains(QLatin1String("not-after")) || line.contains(QLatin1String("created after"))
+ || line.contains(QLatin1String("not valid yet"), Qt::CaseInsensitive) || line.contains(QLatin1String("not live until"), Qt::CaseInsensitive);
+}
+
+bool clockProblemIn(const QString &details)
+{
+ const QStringList lines = sourceLines(details);
+ return std::any_of(lines.cbegin(), lines.cend(), signedLater);
+}
+
+// apt reaches Debian through Tor's SOCKS port; a Tor that is not running
+// or has not finished connecting fails every one of those sources.
+bool throughTor(const QString &line)
+{
+ return line.contains(QLatin1String("tor+http")) || line.contains(QLatin1String(":9050"));
+}
+
+bool offline()
+{
+ switch (NetworkManager::status()) {
+ case NetworkManager::Asleep:
+ case NetworkManager::Disconnected:
+ case NetworkManager::Disconnecting:
+ case NetworkManager::ConnectedLinkLocal:
+ return true;
+ default:
+ return false;
+ }
+}
+
+// Since start-up finished, not since the kernel started: the wait at the
+// disk password comes before Tor, sdwdate and the network even start.
+qint64 secondsSinceStart()
+{
+ auto get = QDBusMessage::createMethodCall(QStringLiteral("org.freedesktop.systemd1"), QStringLiteral("/org/freedesktop/systemd1"),
+ QStringLiteral("org.freedesktop.DBus.Properties"), QStringLiteral("Get"));
+ get << QStringLiteral("org.freedesktop.systemd1.Manager") << QStringLiteral("FinishTimestampMonotonic");
+ const QDBusMessage reply = QDBusConnection::systemBus().call(get, QDBus::Block, 3000);
+ const qulonglong finished = reply.type() == QDBusMessage::ReplyMessage ? reply.arguments().value(0).value<QDBusVariant>().variant().toULongLong() : 0;
+ timespec now{};
+ if (finished > 0 && clock_gettime(CLOCK_MONOTONIC, &now) == 0) {
+ const qint64 nowUs = qint64(now.tv_sec) * 1000000 + now.tv_nsec / 1000;
+ return std::max<qint64>(0, (nowUs - qint64(finished)) / 1000000);
+ }
+ QFile uptime(QStringLiteral("/proc/uptime"));
+ if (!uptime.open(QIODevice::ReadOnly)) {
+ return -1;
+ }
+ return qint64(uptime.readAll().split(' ').value(0).toDouble());
+}
+
+// The check result Settings shares with the taskbar's Updates icon
+// (/usr/libexec/wildos/update-status), which reads and writes the same
+// files: "checking" names the process running a check (its pid, then its
+// name, then "clock N" while it waits for sdwdate to set a clock at least N
+// seconds behind), "failed" holds the last failed check (when the lists had
+// last been refreshed as it failed, the reasons one per line, an empty line,
+// then PackageKit's and apt's details). The failure stands until a refresh is
+// newer than that, which holds however the clock moves: right after
+// start-up sdwdate may set it back. In the runtime folder, so a failure is
+// forgotten at the next start-up.
+QString sharedDir()
+{
+ return QStandardPaths::writableLocation(QStandardPaths::RuntimeLocation) + QStringLiteral("/wildos-updates");
+}
+
+QString checkingFile()
+{
+ return sharedDir() + QStringLiteral("/checking");
+}
+
+QString failedFile()
+{
+ return sharedDir() + QStringLiteral("/failed");
+}
+
+// When the list was last refreshed by a check from Settings or the
+// taskbar's icon, including one PackageKit does not record because it only
+// missed sources added by other software.
+QString checkedFile()
+{
+ QString state = qEnvironmentVariable("XDG_STATE_HOME");
+ if (state.isEmpty()) {
+ state = QDir::homePath() + QStringLiteral("/.local/state");
+ }
+ return state + QStringLiteral("/wildos/updates-checked");
+}
+
+QString processName(qint64 pid)
+{
+ QFile comm(pid > 0 ? QStringLiteral("/proc/%1/comm").arg(pid) : QStringLiteral("/proc/self/comm"));
+ return comm.open(QIODevice::ReadOnly) ? QString::fromUtf8(comm.readAll()).trimmed() : QString();
+}
+
+QStringList fileLines(const QString &path)
+{
+ QFile file(path);
+ if (!file.open(QIODevice::ReadOnly)) {
+ return {};
+ }
+ return QString::fromUtf8(file.readAll()).split(QLatin1Char('\n'));
+}
+
+void writeLines(const QString &path, const QStringList &lines)
+{
+ QDir().mkpath(QFileInfo(path).path());
+ QSaveFile file(path);
+ if (file.open(QIODevice::WriteOnly)) {
+ file.write((lines.join(QLatin1Char('\n')) + QLatin1Char('\n')).toUtf8());
+ file.commit();
+ }
+}
+
+// Another process running a check now: the taskbar's icon. One that quit
+// or crashed no longer counts.
+bool otherChecking()
+{
+ const QStringList lines = fileLines(checkingFile());
+ const qint64 pid = lines.value(0).toLongLong();
+ return pid > 0 && pid != QCoreApplication::applicationPid() && !lines.value(1).isEmpty() && processName(pid) == lines.value(1);
+}
+
+// While a check waits for sdwdate to set the clock, its checking file has a
+// third line, "clock" and how many seconds behind the clock was at least.
+QStringList checkingLines(qint64 clockBehind)
+{
+ QStringList lines{QString::number(QCoreApplication::applicationPid()), processName(0)};
+ if (clockBehind > 0) {
+ lines << QStringLiteral("clock %1").arg(clockBehind);
+ }
+ return lines;
+}
+
+qint64 sharedClockWait()
+{
+ const QString line = fileLines(checkingFile()).value(2);
+ return line.startsWith(QLatin1String("clock ")) ? line.mid(6).toLongLong() : 0;
+}
+
+struct SharedFailure {
+ qint64 refreshedBefore = 0;
+ QStringList reasons;
+ QString details;
+};
+
+SharedFailure sharedFailure()
+{
+ SharedFailure failure;
+ const QStringList lines = fileLines(failedFile());
+ failure.refreshedBefore = lines.value(0).toLongLong();
+ int i = 1;
+ for (; i < lines.size() && !lines.at(i).isEmpty(); ++i) {
+ failure.reasons << lines.at(i);
+ }
+ failure.details = lines.mid(i + 1).join(QLatin1Char('\n')).trimmed();
+ return failure;
+}
+
+qint64 mtimeOf(const QString &path)
+{
+ const QFileInfo info(path);
+ return info.exists() ? info.lastModified().toSecsSinceEpoch() : 0;
+}
+
+// The last refresh by anyone, as the taskbar's icon reads it: apt's daily
+// one leaves its stamp and the lists' times, a check from Settings or the
+// icon leaves the checked file.
+qint64 lastRefreshOnDisk()
+{
+ qint64 at = std::max(mtimeOf(QStringLiteral("/var/lib/apt/periodic/update-success-stamp")), fileLines(checkedFile()).value(0).toLongLong());
+ const QFileInfoList lists = QDir(QStringLiteral("/var/lib/apt/lists")).entryInfoList({QStringLiteral("*Release")}, QDir::Files);
+ for (const QFileInfo &list : lists) {
+ at = std::max(at, list.lastModified().toSecsSinceEpoch());
+ }
+ return at;
+}
+
// The sources a refresh could not use, read from apt's messages, which
// PackageKit passes on as the error's details: each host, and whether it
// failed on its signature rather than on the connection. apt checks every
@@ -166,26 +429,15 @@ QStringList ownHosts()
QList<QPair<QString, bool>> failedSources(const QString &details)
{
static const QRegularExpression address(QStringLiteral("(?:tor\\+)?https?://([^/\\s'\"]+)"));
- static const QStringList signing = {
- QStringLiteral("signature"), QStringLiteral("not signed"), QStringLiteral("NO_PUBKEY"),
- QStringLiteral("EXPKEYSIG"), QStringLiteral("Signing key"), QStringLiteral("OpenPGP"),
- };
QList<QPair<QString, bool>> failed;
- const QStringList lines = details.split(QLatin1Char('\n'), Qt::SkipEmptyParts);
+ const QStringList lines = sourceLines(details);
for (const QString &line : lines) {
- // apt's notices name sources that are fine, such as one without
- // 32-bit packages on a PC with 32-bit support turned on.
- if (line.contains(QLatin1String("Skipping acquire")) || line.contains(QLatin1String("support architecture"))) {
- continue;
- }
const auto match = address.match(line);
if (!match.hasMatch()) {
continue;
}
const QString host = match.captured(1).toLower();
- const bool key = std::any_of(signing.cbegin(), signing.cend(), [&line](const QString &word) {
- return line.contains(word, Qt::CaseInsensitive);
- });
+ const bool key = aboutSigning(line);
auto existing = std::find_if(failed.begin(), failed.end(), [&host](const auto &entry) {
return entry.first == host;
});
@@ -234,6 +486,15 @@ Updates::Updates(QObject *parent)
readNotes(cache.readAll());
}
if (available()) {
+ // A check started or finished on the taskbar's Updates icon shows
+ // here at once, and one that stopped without a word (the icon's
+ // shell restarted) is noticed within seconds.
+ QDir().mkpath(sharedDir());
+ m_sharedWatch = new QFileSystemWatcher({sharedDir()}, this);
+ connect(m_sharedWatch, &QFileSystemWatcher::directoryChanged, this, &Updates::applyShared);
+ m_followTimer = new QTimer(this);
+ m_followTimer->setInterval(3000);
+ connect(m_followTimer, &QTimer::timeout, this, &Updates::applyShared);
readLastChecked();
listUpdates();
loadHistory();
@@ -251,6 +512,11 @@ bool Updates::available() const
|| bus->activatableServiceNames().value().contains(QStringLiteral("org.freedesktop.PackageKit"));
}
+QString Updates::clockBehind() const
+{
+ return m_clockBehind >= 60 ? SecureTime::durationText(m_clockBehind) : QString();
+}
+
int Updates::securityCount() const
{
int count = 0;
@@ -262,10 +528,15 @@ int Updates::securityCount() const
return count;
}
-void Updates::setState(const QString &state, const QString &error)
+void Updates::setState(const QString &state, const QString &error, bool checkFailed)
{
m_state = state;
m_error = error;
+ m_checkFailed = checkFailed;
+ if (!checkFailed) {
+ m_errorDetails.clear();
+ }
+ m_clockProblem = checkFailed && state == QLatin1String("error") && clockProblemIn(m_errorDetails);
Q_EMIT stateChanged();
}
@@ -281,6 +552,13 @@ void Updates::readLastChecked()
} else {
m_lastChecked = {};
}
+ // The same time the taskbar's icon shows, which also counts apt's
+ // daily refresh and checks PackageKit did not record.
+ const qint64 onDisk = lastRefreshOnDisk();
+ if (onDisk > 0 && (!m_lastChecked.isValid() || onDisk > m_lastChecked.toSecsSinceEpoch())) {
+ m_lastChecked = QDateTime::fromSecsSinceEpoch(onDisk);
+ }
+ applyShared();
Q_EMIT lastCheckedChanged();
});
}
@@ -358,11 +636,89 @@ void Updates::check()
if (m_state == QLatin1String("checking") || m_state == QLatin1String("installing")) {
return;
}
+ // One check at a time: when the taskbar's icon is already checking,
+ // its result is this one's too.
+ if (otherChecking()) {
+ applyShared();
+ return;
+ }
m_lockWait.invalidate();
+ m_quietRetry.invalidate();
+ m_clockWait.invalidate();
+ m_retryDelayMs = firstRetryMs;
+ startOwnCheck();
setState(QStringLiteral("checking"));
refreshForCheck();
}
+void Updates::startOwnCheck()
+{
+ m_ownCheck = true;
+ m_following = false;
+ if (m_followTimer) {
+ m_followTimer->stop();
+ }
+ writeLines(checkingFile(), checkingLines(0));
+}
+
+// The result goes where the taskbar's icon reads it before the check is
+// marked as done, so it never shows the state from before the check.
+void Updates::finishOwnCheck(const QStringList &reasons, const QString &details)
+{
+ if (reasons.isEmpty()) {
+ QFile::remove(failedFile());
+ } else {
+ writeLines(failedFile(), QStringList{QString::number(lastRefreshOnDisk())} + reasons + QStringList{QString()} + details.split(QLatin1Char('\n')));
+ }
+ QFile::remove(checkingFile());
+ m_ownCheck = false;
+}
+
+// Shows what the taskbar's icon found: its check while it runs, then its
+// result, so Settings and the icon always say the same thing. Settings'
+// own check and installs are left alone.
+void Updates::applyShared()
+{
+ if (m_ownCheck || m_state == QLatin1String("installing")) {
+ return;
+ }
+ if (otherChecking()) {
+ m_following = true;
+ if (m_state != QLatin1String("checking")) {
+ m_skipped.clear();
+ setState(QStringLiteral("checking"));
+ }
+ setClockBehind(sharedClockWait());
+ if (m_followTimer) {
+ m_followTimer->start();
+ }
+ return;
+ }
+ if (m_followTimer) {
+ m_followTimer->stop();
+ }
+ setClockBehind(0);
+ const bool followed = m_following;
+ m_following = false;
+ if (m_state == QLatin1String("installed")) {
+ return;
+ }
+ const SharedFailure failure = sharedFailure();
+ // Nothing has refreshed the lists since the check failed.
+ if (!failure.reasons.isEmpty() && lastRefreshOnDisk() <= failure.refreshedBefore) {
+ const QString reason = failure.reasons.join(QLatin1Char('\n'));
+ if (m_state != QLatin1String("error") || !m_checkFailed || m_error != reason) {
+ m_errorDetails = failure.details;
+ setState(QStringLiteral("error"), reason, true);
+ }
+ return;
+ }
+ if (followed || (m_state == QLatin1String("error") && m_checkFailed)) {
+ readLastChecked();
+ listUpdates();
+ }
+}
+
// A source someone else added (Steam's, with a signing key Debian no
// longer accepts) fails the whole refresh in PackageKit, though apt
// refreshed every other source. That is no reason to say Wild OS could not
@@ -389,6 +745,13 @@ void Updates::refreshForCheck()
// Someone asked to check: fetch the lists again even if they are recent.
m_skipped.clear();
m_partialRefresh = false;
+ m_checkErrored = false;
+ // With no connection at all a refresh waits minutes on Tor before it
+ // fails, so it is not started.
+ if (offline()) {
+ checkFailedWith(Transaction::ErrorNoNetwork, QString());
+ return;
+ }
Transaction *refresh = Daemon::refreshCache(true);
watchProgress(refresh);
connect(refresh, &Transaction::errorCode, this, [this](Transaction::Error error, const QString &details) {
@@ -399,7 +762,9 @@ void Updates::refreshForCheck()
m_partialRefresh = true;
return;
}
- setState(QStringLiteral("error"), errorText(error, false));
+ m_checkErrored = true;
+ m_checkError = error;
+ m_checkDetails = details;
});
connect(refresh, &Transaction::finished, this, [this](Transaction::Exit status, uint) {
if (m_lockBlocked) {
@@ -411,21 +776,229 @@ void Updates::refreshForCheck()
setWaiting(false);
// PackageKit records only a refresh with no failures, so a partial
// one is timed here.
- if (m_partialRefresh && m_state != QLatin1String("error")) {
+ if (m_partialRefresh && !m_checkErrored) {
m_lastChecked = QDateTime::currentDateTime();
Q_EMIT lastCheckedChanged();
status = Transaction::ExitSuccess;
} else {
readLastChecked();
}
- if (status == Transaction::ExitSuccess) {
+ if (status == Transaction::ExitSuccess && !m_checkErrored) {
+ writeLines(checkedFile(), {QString::number(QDateTime::currentSecsSinceEpoch())});
+ finishOwnCheck();
listUpdates();
fetchNotes();
- } else if (m_state != QLatin1String("error")) {
- setState(QStringLiteral("error"), status == Transaction::ExitCancelled ? QStringLiteral("The check was cancelled.")
- : QStringLiteral("Wild OS could not check for updates."));
+ } else if (status == Transaction::ExitCancelled) {
+ finishOwnCheck({QStringLiteral("The check was cancelled.")});
+ setState(QStringLiteral("error"), QStringLiteral("The check was cancelled."), true);
+ } else {
+ checkFailedWith(m_checkErrored ? m_checkError : Transaction::ErrorUnknown, m_checkErrored ? m_checkDetails : QString());
+ }
+ });
+}
+
+void Updates::checkFailedWith(Transaction::Error error, const QString &details)
+{
+ const char *name = QMetaEnum::fromType<Transaction::Error>().valueToKey(error);
+ const QString code = QStringLiteral("PackageKit %1 (%2)").arg(name ? QString::fromLatin1(name) : QStringLiteral("Error"), QString::number(int(error)));
+ // In the journal too, since PackageKit's own lines only say "failed".
+ qWarning().noquote() << "Update check failed:" << code << details.trimmed();
+ if (retryQuietly(error, details)) {
+ return;
+ }
+ m_errorDetails = details.trimmed().isEmpty() ? code : code + QLatin1Char('\n') + details.trimmed();
+ const QString reason = whyCheckFailed(error, details);
+ finishOwnCheck(reason.split(QLatin1Char('\n')), m_errorDetails);
+ setState(QStringLiteral("error"), reason, true);
+}
+
+// Whether a failed check is worth trying again by itself: in the first
+// minutes after start-up, or when the connection, Tor or the clock was not
+// ready (the taskbar's icon decides the same in update-status), a
+// minute later usually works, as it did on the PC this was seen on. A
+// refusal, a full disk or a bad signature after that will not change.
+bool Updates::retryQuietly(Transaction::Error error, const QString &details)
+{
+ if (error == Transaction::ErrorNotAuthorized || error == Transaction::ErrorTransactionCancelled || error == Transaction::ErrorNoSpaceOnDevice
+ || error == Transaction::ErrorCannotGetLock || error == Transaction::ErrorLockRequired) {
+ return false;
+ }
+ const QStringList lines = sourceLines(details);
+ const bool settling = secondsSinceStart() >= 0 && secondsSinceStart() < settlingSeconds;
+ // No connection at all long after start-up is said at once: waiting
+ // will not bring one.
+ if (offline() && !settling) {
+ return false;
+ }
+ // apt's lines for a signature from the future include one that only
+ // says verification failed, so one line naming the time is enough, and
+ // PackageKit may still call it a signing error.
+ const bool clockBehind = std::any_of(lines.cbegin(), lines.cend(), signedLater);
+ // A clock hours behind stays so until sdwdate sets it through Tor, so
+ // the check waits for that rather than for a fixed time.
+ if (clockBehind && SecureTime::settingNow()) {
+ if (!m_clockWait.isValid()) {
+ m_clockWait.start();
+ }
+ if (m_clockWait.elapsed() < clockWaitMs) {
+ waitForClock(SecureTime::secondsBehind(details));
+ return true;
+ }
+ }
+ const bool signing = !clockBehind
+ && (error == Transaction::ErrorGpgFailure || error == Transaction::ErrorBadGpgSignature || error == Transaction::ErrorMissingGpgSignature
+ || error == Transaction::ErrorCannotUpdateRepoUnsigned || std::any_of(lines.cbegin(), lines.cend(), aboutSigning));
+ const bool connection = error == Transaction::ErrorNoNetwork || error == Transaction::ErrorNoCache || error == Transaction::ErrorRepoNotAvailable
+ || error == Transaction::ErrorCannotFetchSources || error == Transaction::ErrorPackageDownloadFailed
+ || error == Transaction::ErrorNoMoreMirrorsToTry || std::any_of(lines.cbegin(), lines.cend(), throughTor) || offline() || clockBehind;
+ if (!settling && (signing || !connection)) {
+ return false;
+ }
+ if (!m_quietRetry.isValid()) {
+ m_quietRetry.start();
+ }
+ if (m_quietRetry.elapsed() + m_retryDelayMs > quietRetryMs) {
+ return false;
+ }
+ QTimer::singleShot(m_retryDelayMs, this, [this] {
+ if (m_state == QLatin1String("checking")) {
+ refreshForCheck();
}
});
+ m_retryDelayMs = std::min(m_retryDelayMs * 2, longestRetryMs);
+ return true;
+}
+
+void Updates::setClockBehind(qint64 seconds)
+{
+ if (m_clockBehind == seconds) {
+ return;
+ }
+ m_clockBehind = seconds;
+ Q_EMIT progressChanged();
+}
+
+void Updates::waitForClock(qint64 behind)
+{
+ // At least a second, so the page says it is waiting even when every
+ // signing time named has just passed.
+ setClockBehind(std::max<qint64>(behind, 1));
+ writeLines(checkingFile(), checkingLines(m_clockBehind));
+ if (!m_clockTimer) {
+ m_clockTimer = new QTimer(this);
+ m_clockTimer->setInterval(clockPollMs);
+ connect(m_clockTimer, &QTimer::timeout, this, [this] {
+ if (m_state == QLatin1String("checking") && SecureTime::settingNow() && m_clockWait.elapsed() < clockWaitMs) {
+ return;
+ }
+ m_clockTimer->stop();
+ setClockBehind(0);
+ if (m_state != QLatin1String("checking")) {
+ return;
+ }
+ writeLines(checkingFile(), checkingLines(0));
+ // The usual quiet retries start over: sdwdate's first setting
+ // can leave the clock a moment before a source signed just now.
+ m_quietRetry.invalidate();
+ m_retryDelayMs = firstRetryMs;
+ refreshForCheck();
+ });
+ }
+ m_clockTimer->start();
+}
+
+// Why a check failed, one line for each likely cause, from PackageKit's
+// error and the sources apt named.
+QString Updates::whyCheckFailed(Transaction::Error error, const QString &details)
+{
+ switch (error) {
+ case Transaction::ErrorNotAuthorized:
+ return errorText(error, false);
+ case Transaction::ErrorCannotGetLock:
+ case Transaction::ErrorLockRequired:
+ return QStringLiteral("Another install is still running, such as the automatic security updates. Try again when it has finished.");
+ case Transaction::ErrorNoSpaceOnDevice:
+ return QStringLiteral("There is not enough free space to check for updates.");
+ default:
+ break;
+ }
+ if (offline() || error == Transaction::ErrorNoNetwork) {
+ return QStringLiteral("This computer is not connected to the internet.");
+ }
+ static const QRegularExpression address(QStringLiteral("(?:tor\\+)?https?://([^/\\s'\"]+)"));
+ // A clock far behind fails every source, so it is the one reason given.
+ const qint64 behind = clockProblemIn(details) ? SecureTime::secondsBehind(details) : 0;
+ if (behind >= 60) {
+ const QString clock = QStringLiteral("The clock on this computer is at least %1 behind, so the updates look as if they were signed in the future.")
+ .arg(SecureTime::durationText(behind));
+ return clock + QLatin1Char('\n')
+ + (SecureTime::settingNow()
+ ? QStringLiteral("Wild OS sets the clock through Tor after start-up and has not managed to yet. Set the date and time in Settings > Date and time, then try again.")
+ : QStringLiteral("Set the date and time in Settings > Date and time, then try again."));
+ }
+ const QStringList wildos = wildosHosts();
+ const QStringList own = ownHosts();
+ bool wildosDown = false;
+ bool debianDown = false;
+ bool torDown = false;
+ bool signing = error == Transaction::ErrorGpgFailure || error == Transaction::ErrorBadGpgSignature
+ || error == Transaction::ErrorMissingGpgSignature || error == Transaction::ErrorCannotUpdateRepoUnsigned;
+ const QStringList lines = sourceLines(details);
+ // Every server reached directly failing to resolve is no internet at
+ // all, though NetworkManager still has a connection (a router with no
+ // line behind it).
+ QSet<QString> unresolved;
+ bool failedOtherwise = false;
+ for (const QString &line : lines) {
+ const auto match = address.match(line);
+ if (!match.hasMatch() || throughTor(line)) {
+ continue;
+ }
+ if (line.contains(QLatin1String("Temporary failure resolving")) || line.contains(QLatin1String("Could not resolve"))) {
+ unresolved.insert(match.captured(1).toLower());
+ } else {
+ failedOtherwise = true;
+ }
+ }
+ if (unresolved.size() >= 2 && !failedOtherwise) {
+ return QStringLiteral("This computer is not connected to the internet.");
+ }
+ for (const QString &line : lines) {
+ const auto match = address.match(line);
+ const QString host = match.hasMatch() ? match.captured(1).toLower() : QString();
+ if (aboutSigning(line)) {
+ signing = signing || host.isEmpty() || own.contains(host);
+ } else if (throughTor(line)) {
+ torDown = true;
+ } else if (wildos.contains(host)) {
+ wildosDown = true;
+ } else if (own.contains(host)) {
+ debianDown = true;
+ }
+ }
+ QStringList reasons;
+ if (wildosDown) {
+ reasons << QStringLiteral("Wild OS's update server could not be reached.");
+ }
+ if (torDown) {
+ // Long after start-up, waiting for Tor is no longer the likely fix.
+ const qint64 up = secondsSinceStart();
+ reasons << (up >= 0 && up < 2 * settlingSeconds
+ ? QStringLiteral("Debian's updates could not be reached through Tor. Tor can take a few minutes to connect after start-up.")
+ : QStringLiteral("Debian's updates could not be reached through Tor."));
+ } else if (debianDown) {
+ reasons << QStringLiteral("Debian's update servers could not be reached.");
+ }
+ if (signing) {
+ reasons << QStringLiteral("The updates' signatures could not be checked. This happens when the date and time on this computer are wrong.");
+ }
+ if (reasons.isEmpty()) {
+ reasons << (error == Transaction::ErrorNoCache || error == Transaction::ErrorRepoNotAvailable || error == Transaction::ErrorCannotFetchSources
+ || error == Transaction::ErrorPackageDownloadFailed
+ ? QStringLiteral("The update servers could not be reached. Check your internet connection.")
+ : QStringLiteral("Something went wrong while checking. Try again in a few minutes."));
+ }
+ return reasons.join(QLatin1Char('\n'));
}
void Updates::listUpdates()
@@ -507,6 +1080,9 @@ void Updates::readUpdates(bool quiet)
}
}
setState(m_updates.isEmpty() ? QStringLiteral("uptodate") : QStringLiteral("available"));
+ // A failed check from the taskbar's icon still stands over the list
+ // read at start-up.
+ applyShared();
});
}
diff --git a/packages/wildos-settings/src/updates.h b/packages/wildos-settings/src/updates.h
index 4d70ac5..724f27c 100644
--- a/packages/wildos-settings/src/updates.h
+++ b/packages/wildos-settings/src/updates.h
@@ -13,7 +13,9 @@
// Checks for and installs system updates through PackageKit, the service the
// Store uses, so both always agree on what is waiting.
+class QFileSystemWatcher;
class QNetworkAccessManager;
+class QTimer;
class Updates : public QObject
{
@@ -32,7 +34,20 @@ class Updates : public QObject
// Another install (usually the automatic security updates) holds the
// package system, and the check or install waits for it.
Q_PROPERTY(bool waiting READ waiting NOTIFY progressChanged)
+ // The check is waiting for sdwdate to set the clock, which was this far
+ // behind at least ("8 hours"; empty under a minute).
+ Q_PROPERTY(bool clockWaiting READ clockWaiting NOTIFY progressChanged)
+ Q_PROPERTY(QString clockBehind READ clockBehind NOTIFY progressChanged)
Q_PROPERTY(QString error READ error NOTIFY stateChanged)
+ // The error is a check that failed rather than an install, so the page
+ // says so even while updates from an earlier check are still listed.
+ Q_PROPERTY(bool checkFailed READ checkFailed NOTIFY stateChanged)
+ // PackageKit's error and apt's own lines for the last failed check, for
+ // anyone helping to fix it. Never shown as the reason itself.
+ Q_PROPERTY(QString errorDetails READ errorDetails NOTIFY stateChanged)
+ // The failed check was the clock being wrong, so Date and time is where
+ // to fix it.
+ Q_PROPERTY(bool clockProblem READ clockProblem NOTIFY stateChanged)
// Software sources added by other software that the last check could
// not use, in a sentence, while everything else was checked. Empty when
// none failed.
@@ -60,7 +75,12 @@ public:
int progress() const { return m_progress; }
QString detail() const { return m_detail; }
bool waiting() const { return m_waiting; }
+ bool clockWaiting() const { return m_clockBehind > 0; }
+ QString clockBehind() const;
+ bool clockProblem() const { return m_clockProblem; }
QString error() const { return m_error; }
+ bool checkFailed() const { return m_checkFailed; }
+ QString errorDetails() const { return m_errorDetails; }
QString skippedSources() const { return m_skipped; }
bool restartNeeded() const { return m_restartNeeded; }
bool available() const;
@@ -99,20 +119,28 @@ private Q_SLOTS:
void onHistoryFinished(uint exit, uint runtime);
private:
- void setState(const QString &state, const QString &error = {});
+ void setState(const QString &state, const QString &error = {}, bool checkFailed = false);
void readLastChecked();
void watchProgress(PackageKit::Transaction *transaction);
static QString errorText(PackageKit::Transaction::Error error, bool installing);
void startInstall();
void refreshThenInstall();
void refreshForCheck();
+ void checkFailedWith(PackageKit::Transaction::Error error, const QString &details);
+ bool retryQuietly(PackageKit::Transaction::Error error, const QString &details);
+ static QString whyCheckFailed(PackageKit::Transaction::Error error, const QString &details);
bool onlyOthersFailed(const QString &details);
void readUpdates(bool quiet);
bool lockHeld(PackageKit::Transaction::Error error);
void retryAfterLock(const std::function<void()> &retry);
void setWaiting(bool waiting);
+ void setClockBehind(qint64 seconds);
+ void waitForClock(qint64 behind);
void readInstalledBuild();
bool readNotes(const QByteArray &json);
+ void startOwnCheck();
+ void finishOwnCheck(const QStringList &reasons = {}, const QString &details = {});
+ void applyShared();
QString m_state = QStringLiteral("idle");
QVariantList m_updates;
@@ -124,6 +152,32 @@ private:
int m_progress = 0;
QString m_detail;
QString m_error;
+ bool m_checkFailed = false;
+ QString m_errorDetails;
+ // The failure a check's refresh reported, kept until it finishes, when
+ // a quiet retry or the reason is decided.
+ bool m_checkErrored = false;
+ PackageKit::Transaction::Error m_checkError = PackageKit::Transaction::ErrorUnknown;
+ QString m_checkDetails;
+ // A check that fails while the connection is still coming up (Tor
+ // takes a minute or two after start-up) tries again by itself for a
+ // while before it says anything.
+ QElapsedTimer m_quietRetry;
+ int m_retryDelayMs = 0;
+ // sdwdate sets a clock that is hours off a few minutes after start-up;
+ // until then the check waits for it (since m_clockWait), and says how
+ // far behind the clock was at least in m_clockBehind, in seconds.
+ QElapsedTimer m_clockWait;
+ QTimer *m_clockTimer = nullptr;
+ qint64 m_clockBehind = 0;
+ bool m_clockProblem = false;
+ // The check result Settings shares with the taskbar's Updates icon
+ // (update-status), so both always show the same state: this app is
+ // running its own check, or showing one the icon is running.
+ bool m_ownCheck = false;
+ bool m_following = false;
+ QFileSystemWatcher *m_sharedWatch = nullptr;
+ QTimer *m_followTimer = nullptr;
QString m_skipped;
bool m_partialRefresh = false;
bool m_restartNeeded = false;
diff --git a/packages/wildos-settings/src/users.cpp b/packages/wildos-settings/src/users.cpp
index fe5d98f..eef377b 100644
--- a/packages/wildos-settings/src/users.cpp
+++ b/packages/wildos-settings/src/users.cpp
@@ -255,6 +255,12 @@ void Users::reload()
continue;
}
const QString name = QString::fromUtf8(pw->pw_name);
+ // The guest session's account comes and goes with its switch on
+ // Advanced protection (wildos-base guest-account); making it an
+ // administrator or removing it here would undo what that promises.
+ if (!own && name == QLatin1String("guest") && pw->pw_passwd[0] == '\0') {
+ continue;
+ }
const QString full = QString::fromUtf8(pw->pw_gecos).section(QLatin1Char(','), 0, 0).trimmed();
const bool admin = isAdmin(pw->pw_name, pw->pw_gid);
if (admin && pw->pw_uid >= 1000) {
diff --git a/packages/wildos-settings/src/windowsmode.cpp b/packages/wildos-settings/src/windowsmode.cpp
index 1883ba8..2da5bcd 100644
--- a/packages/wildos-settings/src/windowsmode.cpp
+++ b/packages/wildos-settings/src/windowsmode.cpp
@@ -153,6 +153,39 @@ QString WindowsMode::openDesktop()
return call(QStringLiteral("OpenDesktop"));
}
+void WindowsMode::activateWithAccount()
+{
+ // Windows may start from off first, then the account is made.
+ callAsync(QStringLiteral("ActivateWithAccount"), 900000, &WindowsMode::accountActivationDone);
+}
+
+void WindowsMode::endAccountActivation()
+{
+ // Signing the account out and deleting its profile takes a minute.
+ callAsync(QStringLiteral("EndActivation"), 480000, &WindowsMode::accountActivationDone);
+}
+
+QString WindowsMode::activationPassword()
+{
+ return m_service ? call(QStringLiteral("ActivationPassword")) : QString();
+}
+
+void WindowsMode::callAsync(const QString &method, int timeoutMs, void (WindowsMode::*done)(const QString &))
+{
+ if (!m_service) {
+ Q_EMIT(this->*done)(QStringLiteral("Windows mode isn't installed on this PC."));
+ return;
+ }
+ m_service->setTimeout(timeoutMs);
+ auto *watcher = new QDBusPendingCallWatcher(m_service->asyncCall(method), this);
+ connect(watcher, &QDBusPendingCallWatcher::finished, this, [this, watcher, done] {
+ watcher->deleteLater();
+ const QDBusPendingReply<QString> reply = *watcher;
+ Q_EMIT(this->*done)(reply.isError() ? QStringLiteral("Windows mode didn't answer. Restart the PC, then try again.") : reply.value());
+ refresh();
+ });
+}
+
QString WindowsMode::repair()
{
return call(QStringLiteral("Repair"), {}, 180000);
diff --git a/packages/wildos-settings/src/windowsmode.h b/packages/wildos-settings/src/windowsmode.h
index 7537e96..161e896 100644
--- a/packages/wildos-settings/src/windowsmode.h
+++ b/packages/wildos-settings/src/windowsmode.h
@@ -51,6 +51,16 @@ public:
Q_INVOKABLE bool keyShapeValid(const QString &key) const;
Q_INVOKABLE QString checkUpdates();
Q_INVOKABLE QString openDesktop();
+ // Activating with a licence on the person's Microsoft account: Windows
+ // mode adds a second Windows account just for it and opens the Windows
+ // desktop signed in to it. status.activation follows it (state:
+ // starting, open, ending or "", result: {activated, message}). Both
+ // answer with accountActivationDone: "" or why not.
+ Q_INVOKABLE void activateWithAccount();
+ Q_INVOKABLE void endAccountActivation();
+ // That account's password, which Windows asks for once while it becomes
+ // a Microsoft account. "" when there is no such account.
+ Q_INVOKABLE QString activationPassword();
Q_INVOKABLE QString repair();
// The Windows account's password, for when Windows itself asks for it
// (activation, an installer that wants an administrator). "" when it
@@ -74,6 +84,7 @@ Q_SIGNALS:
void statusChanged();
void activatingChanged();
void productKeyDone(const QString &result);
+ void accountActivationDone(const QString &result);
void powerActionChanged();
void powerDone(const QString &result);
void removingChanged();
@@ -84,6 +95,7 @@ private Q_SLOTS:
private:
QString call(const QString &method, const QVariantList &args = {}, int timeoutMs = 25000);
+ void callAsync(const QString &method, int timeoutMs, void (WindowsMode::*done)(const QString &));
QDBusInterface *m_service = nullptr;
QVariantMap m_status;
diff --git a/packages/wildos-shell/CMakeLists.txt b/packages/wildos-shell/CMakeLists.txt
index 67b31e0..7e03be1 100644
--- a/packages/wildos-shell/CMakeLists.txt
+++ b/packages/wildos-shell/CMakeLists.txt
@@ -48,6 +48,7 @@ endif()
add_subdirectory(effects/roundcorners)
add_subdirectory(effects/outline)
add_subdirectory(effects/blurinactive)
+add_subdirectory(effects/crossfade)
add_subdirectory(effects/gestures)
add_subdirectory(windowmenu)
add_subdirectory(slowkeys)
diff --git a/packages/wildos-shell/applet/CompactApplet.qml b/packages/wildos-shell/applet/CompactApplet.qml
index 569f169..638b1b3 100644
--- a/packages/wildos-shell/applet/CompactApplet.qml
+++ b/packages/wildos-shell/applet/CompactApplet.qml
@@ -12,6 +12,7 @@ import org.kde.ksvg 1.0 as KSvg
import org.kde.plasma.plasmoid 2.0
import org.kde.kquickcontrolsaddons 2.0
import org.kde.kirigami 2.20 as Kirigami
+import org.wildos.shell as WildOS
PlasmaCore.ToolTipArea {
id: root
@@ -48,6 +49,91 @@ PlasmaCore.ToolTipArea {
fullRepresentation.parent = appletParent;
fullRepresentation.anchors.fill = appletParent;
}
+ maybeWarmUp();
+ }
+
+ // Wild OS: an applet that preloads (Start) also draws its pop-up once
+ // while the sign-in splash still covers the screen, and the splash waits
+ // for that (wildos-wait-desktop). Preloading only builds the contents;
+ // the window and every image in it were still made on the first click,
+ // which stuttered.
+ property bool warming: false
+ property bool warmedUp: false
+ property int warmFrames: 0
+
+ onPlasmoidItemChanged: maybeWarmUp()
+ Component.onCompleted: maybeWarmUp()
+ Connections {
+ target: root.plasmoidItem
+ function onFullRepresentationItemChanged() { root.maybeWarmUp(); }
+ // Opened for real during the first draw: that is now the real pop-up.
+ function onExpandedChanged() {
+ if (root.plasmoidItem.expanded && dialog.warmShown) {
+ root.finishWarmUp();
+ dialog.warmShown = false;
+ dialog.oldStatus = Plasmoid.status;
+ Plasmoid.status = PlasmaCore.Types.RequiresAttentionStatus;
+ dialog.requestActivate();
+ }
+ }
+ }
+
+ function warmUpWanted() {
+ return !!(plasmoidItem && plasmoidItem.preloadFullRepresentation
+ && (fullRepresentation || plasmoidItem.fullRepresentationItem)
+ && compactRepresentation && !warmedUp);
+ }
+ // The panel hands the contents over more than once while it lays out,
+ // so the draw waits until that has settled. The longest pause between
+ // handovers seen on software rendering is 111 ms; the start-up
+ // animation waits on this, so the quiet spell is kept just above it.
+ function maybeWarmUp() {
+ if (warmUpWanted()) {
+ warmUp.restart();
+ }
+ }
+ function finishWarmUp() {
+ warming = false;
+ warmLimit.stop();
+ WildOS.Session.desktopReady();
+ }
+ Timer {
+ id: warmUp
+ interval: 150
+ onTriggered: {
+ if (!root.warmUpWanted() || root.plasmoidItem.expanded) {
+ return;
+ }
+ root.warmedUp = true;
+ // After a plasmashell restart nothing covers the screen, so the
+ // pop-up would flash up: the first click does the work instead.
+ if (!WildOS.Session.splashShowing) {
+ return;
+ }
+ // Plasma hands the preloaded contents to the pop-up only when it
+ // opens; the first draw needs them now.
+ if (!root.fullRepresentation) {
+ root.fullRepresentation = root.plasmoidItem.fullRepresentationItem;
+ }
+ root.warmFrames = 0;
+ root.warming = true;
+ warmLimit.start();
+ }
+ }
+ Timer {
+ id: warmLimit
+ interval: 2000
+ onTriggered: root.finishWarmUp()
+ }
+ Connections {
+ target: dialog
+ enabled: root.warming
+ function onFrameSwapped() {
+ // The second frame has every image in it; the first may not.
+ if (++root.warmFrames >= 2) {
+ root.finishWarmUp();
+ }
+ }
}
FocusScope {
@@ -203,14 +289,26 @@ PlasmaCore.ToolTipArea {
: PlasmaCore.AppletPopup.AtScreenEdges | PlasmaCore.AppletPopup.AtPanelEdges
hideOnWindowDeactivate: root.plasmoidItem && root.plasmoidItem.hideOnWindowDeactivate
- visible: root.plasmoidItem && root.plasmoidItem.expanded && fullRepresentation
+ visible: root.plasmoidItem && (root.plasmoidItem.expanded || root.warming) && fullRepresentation
visualParent: root.compactRepresentation
backgroundHints: (Plasmoid.containmentDisplayHints & PlasmaCore.Types.ContainmentPrefersOpaqueBackground) ? PlasmaCore.AppletPopup.SolidBackground : PlasmaCore.AppletPopup.StandardBackground
appletInterface: root.plasmoidItem
property var oldStatus: PlasmaCore.Types.UnknownStatus
+ // Set while the unseen first draw is on screen, so its showing and
+ // hiding don't count as the pop-up opening and closing.
+ property bool warmShown: false
+
onVisibleChanged: {
+ if (visible && root.warming) {
+ warmShown = true;
+ return;
+ }
+ if (!visible && warmShown) {
+ warmShown = false;
+ return;
+ }
if (!visible) {
expandedSync.restart();
Plasmoid.status = oldStatus;
diff --git a/packages/wildos-shell/debian/changelog b/packages/wildos-shell/debian/changelog
index 97a29f1..e9e5d31 100644
--- a/packages/wildos-shell/debian/changelog
+++ b/packages/wildos-shell/debian/changelog
@@ -1,3 +1,52 @@
+wildos-shell (0.1.16) trixie; urgency=medium
+
+ * The desktop is ready a little sooner after signing in.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 14:08:15 +0000
+
+wildos-shell (0.1.15) trixie; urgency=medium
+
+ * Tells the start-up animation when the taskbar is ready, so it can open
+ onto the desktop.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 13:52:18 +0000
+
+wildos-shell (0.1.14) trixie; urgency=medium
+
+ * Double-clicking the edge of an app that draws its own frame, such as
+ Brave, stretches it to the screen's full height or width, as it
+ already did for other windows. Wild OS's own apps ask for the same.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 10:05:00 +0000
+
+wildos-shell (0.1.13) trixie; urgency=medium
+
+ * Start opens smoothly the first time after signing in, including after
+ an update. It is drawn once under the sign-in screen, which now waits
+ for that and for the taskbar to finish loading (3 seconds at most).
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 09:10:00 +0000
+
+wildos-shell (0.1.12) trixie; urgency=medium
+
+ * Picking an accent colour no longer flashes a darker shadow round the
+ windows, and with Blur windows in the background on, no longer makes
+ the desktop darker with every pick. Windows now fade to their new
+ colours through a Wild OS effect that mixes the old and new looks in
+ one pass, in place of KWin's Blend Changes, which laid the old look
+ over the new one so their shadows added up. The background blur also
+ keeps its own drawing while any such fade runs, rather than blurring
+ the fade's snapshot of its own work again.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 07:50:46 +0000
+
+wildos-shell (0.1.11) trixie; urgency=medium
+
+ * The taskbar can be told whether an app's right-click menu offers End
+ task (wildosrc [Taskbar] EndTask), and follows the change at once.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 18:44:54 +0000
+
wildos-shell (0.1.10) trixie; urgency=medium
* Three and four-finger swipes each have their own actions. The thumb
diff --git a/packages/wildos-shell/debian/install b/packages/wildos-shell/debian/install
index 3ec8ae7..b86df2e 100644
--- a/packages/wildos-shell/debian/install
+++ b/packages/wildos-shell/debian/install
@@ -3,3 +3,5 @@ decoration/aurorae.qml usr/share/kwin/aurorae/
sessions/wildos.desktop usr/share/wayland-sessions/
applet/CompactApplet.qml usr/share/plasma/shells/org.kde.plasma.desktop/contents/applet/
updates/wildos-docked-taskbar.js usr/share/plasma/shells/org.kde.plasma.desktop/contents/updates/
+splash/wildos-wait-desktop usr/libexec/wildos/
+splash/plasma-ksplash-ready.service.d usr/lib/systemd/user/
diff --git a/packages/wildos-shell/effects/blurinactive/blurinactive.cpp b/packages/wildos-shell/effects/blurinactive/blurinactive.cpp
index eb75bb1..09792ba 100644
--- a/packages/wildos-shell/effects/blurinactive/blurinactive.cpp
+++ b/packages/wildos-shell/effects/blurinactive/blurinactive.cpp
@@ -66,6 +66,16 @@ static constexpr Strength s_strengths[] = {
static const QString s_configGroup = QStringLiteral("Effect-wildos_blurinactive");
+// KWin's fade between the old and new look of every window when the colours
+// or the accent change. Wild OS turns it off for its own (crossfade), which
+// sits before this effect; this keeps the blur right if KWin's is turned
+// back on. KWin's sits after this effect, so for its length a window drawn
+// through the rest of the chain comes back as its snapshot from before,
+// which this effect had already blurred and dimmed. Blurring that again,
+// and keeping it once the fade was over, darkened the desktop a little more
+// with every accent picked.
+static const QString s_crossFade = QStringLiteral("blendchanges");
+
// A blurred window's outline fades as it blurs. The outline reaches past
// the window, further than a repaint of a window without a shadow covers.
static void repaintWithOutline(EffectWindow *w)
@@ -252,6 +262,16 @@ void BlurInactiveEffect::forget(EffectWindow *w)
void BlurInactiveEffect::prePaintScreen(ScreenPrePaintData &data, std::chrono::milliseconds presentTime)
{
+ const bool crossFading = effects->isEffectActive(s_crossFade);
+ if (m_crossFading && !crossFading) {
+ // The windows are drawn afresh in their new colours.
+ for (auto &[w, state] : m_windows) {
+ state->dirty = true;
+ w->addRepaintFull();
+ }
+ }
+ m_crossFading = crossFading;
+
bool moving = false;
for (const auto &[w, state] : m_windows) {
moving = moving || state->progress != state->target;
@@ -402,9 +422,12 @@ bool BlurInactiveEffect::render(EffectWindow *w, State &state)
}
state.textureScale = scale;
state.dirty = true;
+ state.drawn = false;
}
- if (state.dirty && !w->isDeleted()) {
+ // While colours cross fade, a window keeps the blur it had: what the
+ // chain would draw now is the fade's snapshot, made of this blur.
+ if (state.dirty && !w->isDeleted() && !(m_crossFading && state.drawn)) {
RenderTarget renderTarget(state.framebuffers[0].get());
RenderViewport viewport(logical, scale, renderTarget);
GLFramebuffer::pushFramebuffer(state.framebuffers[0].get());
@@ -419,6 +442,7 @@ bool BlurInactiveEffect::render(EffectWindow *w, State &state)
GLFramebuffer::popFramebuffer();
blur(state);
state.dirty = false;
+ state.drawn = true;
}
return true;
}
diff --git a/packages/wildos-shell/effects/blurinactive/blurinactive.h b/packages/wildos-shell/effects/blurinactive/blurinactive.h
index 7957c7e..1b48e42 100644
--- a/packages/wildos-shell/effects/blurinactive/blurinactive.h
+++ b/packages/wildos-shell/effects/blurinactive/blurinactive.h
@@ -57,6 +57,8 @@ private:
qreal progress = 0;
qreal target = 0;
bool dirty = true;
+ // Whether textures hold a drawing of the window yet.
+ bool drawn = false;
qreal textureScale = 1;
// Level 0 is the window as drawn, each further level half the size
// of the one before; after blurring, level 1 holds the result.
@@ -87,6 +89,7 @@ private:
qreal m_dim = 0.14;
qreal m_duration = 250;
std::chrono::milliseconds m_lastPresent = std::chrono::milliseconds::zero();
+ bool m_crossFading = false;
bool m_shadersFailed = false;
std::unique_ptr<GLShader> m_downsample;
diff --git a/packages/wildos-shell/effects/crossfade/CMakeLists.txt b/packages/wildos-shell/effects/crossfade/CMakeLists.txt
new file mode 100644
index 0000000..6b50b76
--- /dev/null
+++ b/packages/wildos-shell/effects/crossfade/CMakeLists.txt
@@ -0,0 +1,12 @@
+# Built the same way as roundcorners, which explains the finds.
+find_package(ECM 6.0 REQUIRED NO_MODULE)
+list(APPEND CMAKE_MODULE_PATH ${ECM_MODULE_PATH} ${ECM_FIND_MODULE_DIR})
+find_package(Qt6 6.8 REQUIRED COMPONENTS DBus Quick Widgets)
+find_package(KWin 6.3 REQUIRED)
+
+add_library(wildos_crossfade MODULE crossfade.cpp crossfade.h crossfade.qrc)
+set_target_properties(wildos_crossfade PROPERTIES AUTOMOC ON AUTORCC ON PREFIX "")
+set_property(TARGET wildos_crossfade APPEND PROPERTY AUTOMOC_MACRO_NAMES KWIN_EFFECT_FACTORY_SUPPORTED)
+target_link_libraries(wildos_crossfade PRIVATE KWin::kwin Qt6::Core Qt6::Gui Qt6::DBus)
+
+install(TARGETS wildos_crossfade LIBRARY DESTINATION ${QT6_INSTALL_PLUGINS}/kwin/effects/plugins)
diff --git a/packages/wildos-shell/effects/crossfade/crossfade.cpp b/packages/wildos-shell/effects/crossfade/crossfade.cpp
new file mode 100644
index 0000000..06a6a70
--- /dev/null
+++ b/packages/wildos-shell/effects/crossfade/crossfade.cpp
@@ -0,0 +1,357 @@
+/*
+ SPDX-FileCopyrightText: 2026 Wild OS Developers <[email protected]>
+
+ SPDX-License-Identifier: GPL-2.0-or-later
+*/
+
+#include "crossfade.h"
+
+#include <core/output.h>
+#include <core/pixelgrid.h>
+#include <core/rendertarget.h>
+#include <core/renderviewport.h>
+#include <effect/effecthandler.h>
+#include <effect/effectwindow.h>
+#include <opengl/glframebuffer.h>
+#include <opengl/glplatform.h>
+#include <opengl/glshader.h>
+#include <opengl/glshadermanager.h>
+#include <opengl/gltexture.h>
+#include <opengl/glvertexbuffer.h>
+#include <opengl/openglcontext.h>
+#include <scene/windowitem.h>
+
+#include <QDBusConnection>
+#include <QFile>
+#include <QTimer>
+#include <QVector3D>
+
+#include <cmath>
+
+Q_LOGGING_CATEGORY(WILDOS_CROSSFADE, "wildos.crossfade", QtWarningMsg)
+
+static void ensureResources()
+{
+ Q_INIT_RESOURCE(crossfade);
+}
+
+namespace KWin
+{
+
+static const QString s_path = QStringLiteral("/org/kde/KWin/BlendChanges");
+static const QString s_interface = QStringLiteral("org.kde.KWin.BlendChanges");
+
+ColourFadeEffect::ColourFadeEffect()
+{
+ m_timeline.setEasingCurve(QEasingCurve::InOutCubic);
+
+ // KWin's own Blend Changes holds the path while it is loaded; Wild OS
+ // turns it off in /etc/xdg/kwinrc. If someone turns it back on, theirs
+ // answers and this effect stays idle.
+ m_registered = QDBusConnection::sessionBus().registerObject(s_path, s_interface, this, QDBusConnection::ExportAllSlots);
+ if (!m_registered) {
+ qCWarning(WILDOS_CROSSFADE) << "Another effect answers" << s_path;
+ }
+
+ connect(effects, &EffectsHandler::windowDeleted, this, [this](EffectWindow *w) {
+ if (auto it = m_windows.find(w); it != m_windows.end()) {
+ effects->makeOpenGLContextCurrent();
+ m_windows.erase(it);
+ }
+ });
+}
+
+ColourFadeEffect::~ColourFadeEffect()
+{
+ if (m_registered) {
+ QDBusConnection::sessionBus().unregisterObject(s_path);
+ }
+ effects->makeOpenGLContextCurrent();
+ m_windows.clear();
+ m_shader.reset();
+}
+
+bool ColourFadeEffect::supported()
+{
+ return effects->isOpenGLCompositing() && effects->animationsSupported();
+}
+
+bool ColourFadeEffect::allocate(const QSize &size, std::unique_ptr<GLTexture> &texture, std::unique_ptr<GLFramebuffer> &target)
+{
+ // Shadows are mostly faint alpha, which eight bits round off visibly.
+ texture = GLTexture::allocate(GL_RGBA16F, size);
+ if (!texture) {
+ texture = GLTexture::allocate(GL_RGBA8, size);
+ }
+ if (!texture) {
+ return false;
+ }
+ texture->setFilter(GL_LINEAR);
+ texture->setWrapMode(GL_CLAMP_TO_EDGE);
+ target = std::make_unique<GLFramebuffer>(texture.get());
+ if (!target->valid()) {
+ target.reset();
+ texture.reset();
+ return false;
+ }
+ return true;
+}
+
+void ColourFadeEffect::render(EffectWindow *w, const QRectF &geometry, qreal scale, GLFramebuffer *target)
+{
+ RenderTarget renderTarget(target);
+ RenderViewport viewport(geometry, scale, renderTarget);
+ GLFramebuffer::pushFramebuffer(target);
+ glClearColor(0.0, 0.0, 0.0, 0.0);
+ glClear(GL_COLOR_BUFFER_BIT);
+ WindowPaintData data;
+ data.setOpacity(1.0);
+ effects->drawWindow(renderTarget, viewport, w, PAINT_WINDOW_TRANSFORMED | PAINT_WINDOW_TRANSLUCENT, infiniteRegion(), data);
+ GLFramebuffer::popFramebuffer();
+}
+
+void ColourFadeEffect::start(int delay)
+{
+ if (!supported() || m_state != State::Off || effects->hasActiveFullScreenEffect()) {
+ return;
+ }
+
+ effects->makeOpenGLContextCurrent();
+ const auto windows = effects->stackingOrder();
+ for (EffectWindow *w : windows) {
+ // Full screen windows are games and video, left to draw at once,
+ // as KWin's version does.
+ if (w->isFullScreen() || w->isDeleted()) {
+ continue;
+ }
+ const Output *screen = w->screen();
+ const qreal scale = screen ? screen->scale() : 1.0;
+ const QRectF geometry = snapToPixels(w->expandedGeometry(), scale);
+ const QSize size = (geometry.size() * scale).toSize();
+ if (size.isEmpty()) {
+ continue;
+ }
+ auto snapshot = std::make_unique<Snapshot>();
+ if (!allocate(size, snapshot->before, snapshot->beforeTarget)) {
+ continue;
+ }
+
+ // Outside a frame, drawing a window runs the whole chain, this
+ // effect included (it passes the window on, not holding it yet).
+ // Blur and contrast behind the window would see an empty texture
+ // rather than the screen, so they are kept out, as KWin does.
+ const QVariant blurRole = w->data(WindowForceBlurRole);
+ const QVariant contrastRole = w->data(WindowForceBackgroundContrastRole);
+ w->setData(WindowForceBlurRole, QVariant());
+ w->setData(WindowForceBackgroundContrastRole, QVariant());
+ render(w, geometry, scale, snapshot->beforeTarget.get());
+ w->setData(WindowForceBlurRole, blurRole);
+ w->setData(WindowForceBackgroundContrastRole, contrastRole);
+
+ snapshot->scale = scale;
+ snapshot->itemEffect = ItemEffect(w->windowItem());
+ m_windows[w] = std::move(snapshot);
+ }
+ if (m_windows.empty()) {
+ return;
+ }
+
+ m_state = State::Holding;
+ QTimer::singleShot(delay, this, [this] {
+ if (m_state != State::Holding) {
+ return;
+ }
+ m_timeline.reset();
+ m_timeline.setDuration(std::chrono::milliseconds(std::lround(animationTime(std::chrono::milliseconds(400)))));
+ m_state = State::Fading;
+ effects->addRepaintFull();
+ });
+ effects->addRepaintFull();
+}
+
+void ColourFadeEffect::finish()
+{
+ effects->makeOpenGLContextCurrent();
+ m_windows.clear();
+ m_state = State::Off;
+ effects->addRepaintFull();
+}
+
+void ColourFadeEffect::prePaintScreen(ScreenPrePaintData &data, std::chrono::milliseconds presentTime)
+{
+ if (m_state == State::Fading) {
+ m_timeline.advance(presentTime);
+ }
+ effects->prePaintScreen(data, presentTime);
+}
+
+void ColourFadeEffect::postPaintScreen()
+{
+ if (m_state == State::Fading && m_timeline.done()) {
+ finish();
+ } else if (m_state != State::Off) {
+ effects->addRepaintFull();
+ }
+ effects->postPaintScreen();
+}
+
+bool ColourFadeEffect::ensureShader()
+{
+ if (m_shader) {
+ return true;
+ }
+ if (m_shaderFailed) {
+ return false;
+ }
+ ensureResources();
+
+ // Same choice of dialect as KWin's own generated shaders.
+ const auto context = OpenGlContext::currentContext();
+ QByteArray header;
+ bool modern;
+ if (context->isOpenGLES()) {
+ modern = context->glslVersion() >= Version(3, 0);
+ header = modern ? QByteArrayLiteral("#version 300 es\n") : QByteArray();
+ header += QByteArrayLiteral("precision highp float;\n");
+ } else {
+ modern = context->glslVersion() >= Version(1, 40);
+ header = modern ? QByteArrayLiteral("#version 140\n") : QByteArray();
+ }
+ if (modern) {
+ header += QByteArrayLiteral("#define IN in\n#define TEXTURE texture\n#define FRAG_COLOR fragColor\nout vec4 fragColor;\n");
+ } else {
+ header += QByteArrayLiteral("#define IN varying\n#define TEXTURE texture2D\n#define FRAG_COLOR gl_FragColor\n");
+ }
+
+ QFile file(QStringLiteral(":/wildos/crossfade/crossfade.frag"));
+ if (!file.open(QIODevice::ReadOnly)) {
+ qCWarning(WILDOS_CROSSFADE) << "Could not read the shader";
+ m_shaderFailed = true;
+ return false;
+ }
+ m_shader = ShaderManager::instance()->generateCustomShader(ShaderTrait::MapTexture | ShaderTrait::Modulate | ShaderTrait::AdjustSaturation | ShaderTrait::TransformColorspace,
+ QByteArray(), header + file.readAll());
+ if (!m_shader || !m_shader->isValid()) {
+ qCWarning(WILDOS_CROSSFADE) << "The shader failed to build";
+ m_shader.reset();
+ m_shaderFailed = true;
+ return false;
+ }
+ m_progressLocation = m_shader->uniformLocation("progress");
+ return true;
+}
+
+void ColourFadeEffect::drawWindow(const RenderTarget &renderTarget, const RenderViewport &viewport, EffectWindow *w, int mask, const QRegion &region, WindowPaintData &data)
+{
+ const auto it = m_windows.find(w);
+ if (it == m_windows.end() || !ensureShader()) {
+ effects->drawWindow(renderTarget, viewport, w, mask, region, data);
+ return;
+ }
+ Snapshot &snapshot = *it->second;
+
+ // A window that changed size or moved to a screen of another scale
+ // since the snapshot cannot be mixed with it pixel for pixel; it shows
+ // its new look straight away.
+ const qreal scale = viewport.scale();
+ const QRectF expanded = snapToPixels(w->expandedGeometry(), scale);
+ const QSize size = (expanded.size() * scale).toSize();
+ if (scale != snapshot.scale || size != snapshot.before->size()) {
+ m_windows.erase(it);
+ effects->drawWindow(renderTarget, viewport, w, mask, region, data);
+ return;
+ }
+
+ const qreal progress = m_state == State::Fading ? m_timeline.value() : 0.0;
+ GLTexture *now = snapshot.before.get();
+ if (progress > 0.0 && !w->isDeleted()) {
+ if (snapshot.now || allocate(size, snapshot.now, snapshot.nowTarget)) {
+ render(w, expanded, scale, snapshot.nowTarget.get());
+ now = snapshot.now.get();
+ }
+ }
+
+ const QRectF frame = snapToPixels(w->frameGeometry(), scale);
+ const QRectF visible = expanded.translated(-frame.topLeft());
+
+ GLVertexBuffer *vbo = GLVertexBuffer::streamingBuffer();
+ vbo->reset();
+ vbo->setAttribLayout(std::span(GLVertexBuffer::GLVertex2DLayout), sizeof(GLVertex2D));
+ const auto map = vbo->map<GLVertex2D>(6);
+ if (!map) {
+ return;
+ }
+ // Offscreen textures are the GL way up: y runs bottom to top.
+ const float x0 = visible.left() * scale;
+ const float y0 = visible.top() * scale;
+ const float x1 = visible.right() * scale;
+ const float y1 = visible.bottom() * scale;
+ (*map)[0] = GLVertex2D{.position = {x0, y0}, .texcoord = {0, 1}};
+ (*map)[1] = GLVertex2D{.position = {x1, y1}, .texcoord = {1, 0}};
+ (*map)[2] = GLVertex2D{.position = {x0, y1}, .texcoord = {0, 0}};
+ (*map)[3] = GLVertex2D{.position = {x0, y0}, .texcoord = {0, 1}};
+ (*map)[4] = GLVertex2D{.position = {x1, y0}, .texcoord = {1, 1}};
+ (*map)[5] = GLVertex2D{.position = {x1, y1}, .texcoord = {1, 0}};
+ vbo->unmap();
+ vbo->bindArrays();
+
+ const qreal rgb = data.brightness() * data.opacity();
+ const qreal a = data.opacity();
+ const auto toXYZ = renderTarget.colorDescription().containerColorimetry().toXYZ();
+
+ ShaderBinder binder(m_shader.get());
+ QMatrix4x4 mvp = viewport.projectionMatrix();
+ mvp.translate(std::round(frame.x() * scale), std::round(frame.y() * scale));
+ m_shader->setUniform(GLShader::Mat4Uniform::ModelViewProjectionMatrix, mvp * data.toMatrix(scale));
+ m_shader->setUniform(GLShader::Vec4Uniform::ModulationConstant, QVector4D(rgb, rgb, rgb, a));
+ m_shader->setUniform(GLShader::FloatUniform::Saturation, data.saturation());
+ m_shader->setUniform(GLShader::Vec3Uniform::PrimaryBrightness, QVector3D(toXYZ(1, 0), toXYZ(1, 1), toXYZ(1, 2)));
+ m_shader->setUniform(GLShader::IntUniform::Sampler, 0);
+ m_shader->setUniform(GLShader::IntUniform::Sampler1, 1);
+ m_shader->setColorspaceUniforms(ColorDescription::sRGB, renderTarget.colorDescription(), RenderingIntent::Perceptual);
+ m_shader->setUniform(m_progressLocation, float(progress));
+
+ const bool clipping = region != infiniteRegion();
+ const QRegion clipRegion = clipping ? viewport.mapToRenderTarget(region) : infiniteRegion();
+ if (clipping) {
+ glEnable(GL_SCISSOR_TEST);
+ }
+ glEnable(GL_BLEND);
+ glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
+
+ glActiveTexture(GL_TEXTURE1);
+ snapshot.before->bind();
+ glActiveTexture(GL_TEXTURE0);
+ now->bind();
+ vbo->draw(clipRegion, GL_TRIANGLES, 0, 6, clipping);
+ now->unbind();
+ glActiveTexture(GL_TEXTURE1);
+ snapshot.before->unbind();
+ glActiveTexture(GL_TEXTURE0);
+
+ glDisable(GL_BLEND);
+ if (clipping) {
+ glDisable(GL_SCISSOR_TEST);
+ }
+ vbo->unbindArrays();
+}
+
+bool ColourFadeEffect::isActive() const
+{
+ return m_state != State::Off;
+}
+
+int ColourFadeEffect::requestedEffectChainPosition() const
+{
+ // After KWin's blur and contrast behind translucent windows (20, 21),
+ // which draw onto the screen and so are never part of either look;
+ // before the outline (55), the background blur (58) and the rounded
+ // corners (60), which are.
+ return 52;
+}
+
+KWIN_EFFECT_FACTORY_SUPPORTED(ColourFadeEffect, "metadata.json", return ColourFadeEffect::supported();)
+
+} // namespace KWin
+
+#include "crossfade.moc"
diff --git a/packages/wildos-shell/effects/crossfade/crossfade.h b/packages/wildos-shell/effects/crossfade/crossfade.h
new file mode 100644
index 0000000..7be2f4d
--- /dev/null
+++ b/packages/wildos-shell/effects/crossfade/crossfade.h
@@ -0,0 +1,93 @@
+/*
+ SPDX-FileCopyrightText: 2026 Wild OS Developers <[email protected]>
+
+ SPDX-License-Identifier: GPL-2.0-or-later
+*/
+
+#pragma once
+
+#include <effect/effect.h>
+#include <effect/timeline.h>
+#include <scene/item.h>
+
+#include <chrono>
+#include <map>
+#include <memory>
+
+namespace KWin
+{
+
+class GLFramebuffer;
+class GLShader;
+class GLTexture;
+class EffectWindow;
+
+// Fades every window from its old look to its new one when the colour
+// scheme or the accent changes, in place of KWin's Blend Changes, and
+// answers the same D-Bus call (plasma-apply-colorscheme makes it).
+//
+// KWin's version draws the window as it is now and lays the snapshot from
+// before over it, fading the snapshot out. Where a window is see-through,
+// its shadow and its outline, the two add up, so every accent picked in
+// Settings flashed a darker shadow round the window. Here the old and new
+// looks are mixed in one pass instead, so anything that did not change
+// stays exactly as it was.
+//
+// It sits before the outline and the background blur in the chain, so both
+// looks include them, and the background blur never draws a window from a
+// snapshot of its own work.
+class ColourFadeEffect : public Effect
+{
+ Q_OBJECT
+
+public:
+ ColourFadeEffect();
+ ~ColourFadeEffect() override;
+
+ static bool supported();
+
+ void prePaintScreen(ScreenPrePaintData &data, std::chrono::milliseconds presentTime) override;
+ void drawWindow(const RenderTarget &renderTarget, const RenderViewport &viewport, EffectWindow *w, int mask, const QRegion &region, WindowPaintData &data) override;
+ void postPaintScreen() override;
+ bool isActive() const override;
+ int requestedEffectChainPosition() const override;
+
+public Q_SLOTS:
+ // Called before the colours change. The windows keep their old look
+ // for delay milliseconds, long enough for every app to repaint, and
+ // then fade to the new one.
+ void start(int delay = 300);
+
+private:
+ struct Snapshot {
+ std::unique_ptr<GLTexture> before;
+ std::unique_ptr<GLFramebuffer> beforeTarget;
+ std::unique_ptr<GLTexture> now;
+ std::unique_ptr<GLFramebuffer> nowTarget;
+ qreal scale = 1;
+ // Keeps the window off direct scanout while it is drawn by us.
+ ItemEffect itemEffect;
+ };
+
+ enum class State {
+ Off,
+ Holding,
+ Fading,
+ };
+
+ bool ensureShader();
+ static bool allocate(const QSize &size, std::unique_ptr<GLTexture> &texture, std::unique_ptr<GLFramebuffer> &target);
+ static void render(EffectWindow *w, const QRectF &geometry, qreal scale, GLFramebuffer *target);
+ void finish();
+
+ std::map<EffectWindow *, std::unique_ptr<Snapshot>> m_windows;
+ State m_state = State::Off;
+ TimeLine m_timeline;
+ bool m_registered = false;
+
+ bool m_shaderFailed = false;
+ std::unique_ptr<GLShader> m_shader;
+ int m_progressLocation = -1;
+};
+
+} // namespace KWin
diff --git a/packages/wildos-shell/effects/crossfade/crossfade.qrc b/packages/wildos-shell/effects/crossfade/crossfade.qrc
new file mode 100644
index 0000000..05aa742
--- /dev/null
+++ b/packages/wildos-shell/effects/crossfade/crossfade.qrc
@@ -0,0 +1,5 @@
+<!DOCTYPE RCC><RCC version="1.0">
+<qresource prefix="/wildos/crossfade/">
+ <file alias="crossfade.frag">shaders/crossfade.frag</file>
+</qresource>
+</RCC>
diff --git a/packages/wildos-shell/effects/crossfade/metadata.json b/packages/wildos-shell/effects/crossfade/metadata.json
new file mode 100644
index 0000000..819f232
--- /dev/null
+++ b/packages/wildos-shell/effects/crossfade/metadata.json
@@ -0,0 +1,10 @@
+{
+ "KPlugin": {
+ "Category": "Appearance",
+ "Description": "Fades every window from its old colours to its new ones when the theme or accent changes",
+ "EnabledByDefault": true,
+ "License": "GPL",
+ "Name": "Colour change fade"
+ },
+ "X-KWin-Internal": true
+}
diff --git a/packages/wildos-shell/effects/crossfade/shaders/crossfade.frag b/packages/wildos-shell/effects/crossfade/shaders/crossfade.frag
new file mode 100644
index 0000000..ff001bc
--- /dev/null
+++ b/packages/wildos-shell/effects/crossfade/shaders/crossfade.frag
@@ -0,0 +1,27 @@
+// Puts a window on screen part way between its look before a colour change
+// and its look now. The effect prepends the #version line and the IN,
+// TEXTURE and FRAG_COLOR macros.
+
+#include "colormanagement.glsl"
+#include "saturation.glsl"
+
+// The window now, and its snapshot from before the change.
+uniform sampler2D sampler;
+uniform sampler2D sampler1;
+uniform vec4 modulation;
+// 0 the old look, 1 the new.
+uniform float progress;
+
+IN vec2 texcoord0;
+
+void main()
+{
+ // Both are premultiplied, so mixing them mixes their coverage too: a
+ // shadow that is the same before and after stays exactly as it is.
+ vec4 result = mix(TEXTURE(sampler1, texcoord0), TEXTURE(sampler, texcoord0), progress);
+
+ result = sourceEncodingToNitsInDestinationColorspace(result);
+ result = adjustSaturation(result);
+ result *= modulation;
+ FRAG_COLOR = nitsToDestinationEncoding(result);
+}
diff --git a/packages/wildos-shell/splash/plasma-ksplash-ready.service.d/wildos-wait-desktop.conf b/packages/wildos-shell/splash/plasma-ksplash-ready.service.d/wildos-wait-desktop.conf
new file mode 100644
index 0000000..6340507
--- /dev/null
+++ b/packages/wildos-shell/splash/plasma-ksplash-ready.service.d/wildos-wait-desktop.conf
@@ -0,0 +1,2 @@
+[Service]
+ExecStartPre=-/usr/libexec/wildos/wildos-wait-desktop
diff --git a/packages/wildos-shell/splash/wildos-wait-desktop b/packages/wildos-shell/splash/wildos-wait-desktop
new file mode 100644
index 0000000..a16364e
--- /dev/null
+++ b/packages/wildos-shell/splash/wildos-wait-desktop
@@ -0,0 +1,17 @@
+#!/bin/sh
+# Runs before KSplash's "ready" stage closes the sign-in splash. Waits, for
+# at most 3 seconds, until plasmashell says the taskbar has loaded and Start
+# has drawn its pop-up once under the splash (Session.desktopReady in
+# org.wildos.shell), so neither the taskbar's loading nor Start's first
+# draw is seen.
+mark="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}/wildos-desktop-ready"
+i=0
+while [ $i -lt 30 ]; do
+ shell=$(pgrep -u "$(id -u)" -x plasmashell | head -n 1)
+ if [ -n "$shell" ] && [ "$(cat "$mark" 2>/dev/null)" = "$shell" ]; then
+ exit 0
+ fi
+ sleep 0.1
+ i=$((i + 1))
+done
+exit 0
diff --git a/packages/wildos-shell/src/session.cpp b/packages/wildos-shell/src/session.cpp
index 797e4e4..a2e0abd 100644
--- a/packages/wildos-shell/src/session.cpp
+++ b/packages/wildos-shell/src/session.cpp
@@ -2,13 +2,18 @@
#include <KScreenDpms/Dpms>
+#include <QCoreApplication>
#include <QDBusConnection>
+#include <QDBusConnectionInterface>
#include <QDBusMessage>
#include <QDBusPendingCallWatcher>
#include <QDBusPendingReply>
+#include <QDBusServiceWatcher>
#include <QDBusVariant>
#include <QGuiApplication>
+#include <QSaveFile>
#include <QScreen>
+#include <QStandardPaths>
namespace
{
@@ -17,6 +22,7 @@ const QString screenSaverPath = QStringLiteral("/ScreenSaver");
const QString profilesService = QStringLiteral("org.freedesktop.UPower.PowerProfiles");
const QString profilesPath = QStringLiteral("/org/freedesktop/UPower/PowerProfiles");
const QString propertiesInterface = QStringLiteral("org.freedesktop.DBus.Properties");
+const QString splashService = QStringLiteral("org.kde.KSplash");
}
Session::Session(QObject *parent)
@@ -41,10 +47,35 @@ Session::Session(QObject *parent)
setScreenOff(screen->name(), false);
});
+ // KSplash leaves the bus as the splash closes; it never comes back in
+ // the same session.
+ auto splash = new QDBusServiceWatcher(splashService, QDBusConnection::sessionBus(), QDBusServiceWatcher::WatchForUnregistration, this);
+ connect(splash, &QDBusServiceWatcher::serviceUnregistered, this, [this] {
+ if (m_splashShowing) {
+ m_splashShowing = false;
+ Q_EMIT splashShowingChanged();
+ }
+ });
+ m_splashShowing = QDBusConnection::sessionBus().interface()->isServiceRegistered(splashService);
+
readLocked();
readProfile();
}
+void Session::desktopReady()
+{
+ // Names this plasmashell, so a mark left by an earlier one never counts.
+ QSaveFile file(QStandardPaths::writableLocation(QStandardPaths::RuntimeLocation) + QStringLiteral("/wildos-desktop-ready"));
+ if (file.open(QIODevice::WriteOnly)) {
+ file.write(QByteArray::number(QCoreApplication::applicationPid()));
+ file.commit();
+ }
+ // The start-up animation watches for this name and opens onto the real
+ // desktop once it appears. It goes with plasmashell, so it never counts
+ // for a later one.
+ QDBusConnection::sessionBus().registerService(QStringLiteral("org.wildos.shell.DesktopReady"));
+}
+
void Session::readLocked()
{
const QDBusMessage call = QDBusMessage::createMethodCall(screenSaverService, screenSaverPath, screenSaverService, QStringLiteral("GetActive"));
diff --git a/packages/wildos-shell/src/session.h b/packages/wildos-shell/src/session.h
index bd946aa..22cb87f 100644
--- a/packages/wildos-shell/src/session.h
+++ b/packages/wildos-shell/src/session.h
@@ -26,6 +26,8 @@ class Session : public QObject
// The names (QScreen::name, Screen.name in QML) of the screens KWin has
// switched off.
Q_PROPERTY(QStringList screensOff READ screensOff NOTIFY screensOffChanged)
+ // The sign-in splash is still covering the screen.
+ Q_PROPERTY(bool splashShowing READ splashShowing NOTIFY splashShowingChanged)
public:
explicit Session(QObject *parent = nullptr);
@@ -33,11 +35,17 @@ public:
bool locked() const { return m_locked; }
bool powerSaver() const { return m_powerSaver; }
QStringList screensOff() const { return m_screensOff; }
+ bool splashShowing() const { return m_splashShowing; }
+
+ // The taskbar has loaded and drawn what it draws ahead of time, so the
+ // sign-in splash can go (wildos-wait-desktop, before KSplash's "ready").
+ Q_INVOKABLE void desktopReady();
Q_SIGNALS:
void lockedChanged();
void powerSaverChanged();
void screensOffChanged();
+ void splashShowingChanged();
private Q_SLOTS:
void setLocked(bool locked);
@@ -53,4 +61,5 @@ private:
bool m_locked = false;
bool m_powerSaver = false;
QStringList m_screensOff;
+ bool m_splashShowing = false;
};
diff --git a/packages/wildos-shell/src/taskbarstyle.cpp b/packages/wildos-shell/src/taskbarstyle.cpp
index 316b463..6449b92 100644
--- a/packages/wildos-shell/src/taskbarstyle.cpp
+++ b/packages/wildos-shell/src/taskbarstyle.cpp
@@ -41,4 +41,9 @@ void TaskbarStyle::read()
m_batteryPercent = battery;
Q_EMIT itemsChanged();
}
+ const bool endTask = taskbar.readEntry("EndTask", false);
+ if (endTask != m_endTask) {
+ m_endTask = endTask;
+ Q_EMIT endTaskChanged();
+ }
}
diff --git a/packages/wildos-shell/src/taskbarstyle.h b/packages/wildos-shell/src/taskbarstyle.h
index 8fafee1..3b0496e 100644
--- a/packages/wildos-shell/src/taskbarstyle.h
+++ b/packages/wildos-shell/src/taskbarstyle.h
@@ -10,8 +10,10 @@
// panels. Settings writes wildosrc [Taskbar] Style; the panel follows the
// change straight away. The same group holds the show desktop sliver at the
// bar's right end (ShowDesktop) and whether hovering it peeks (PeekDesktop),
-// and the clock and battery choices (ClockSeconds, ClockLongDate,
-// BatteryPercent).
+// the clock and battery choices (ClockSeconds, ClockLongDate,
+// BatteryPercent), and whether an app's taskbar menu offers End task
+// (EndTask, off by default as on Windows 11, where it sits in the developer
+// settings: ending an app loses whatever it had unsaved).
class TaskbarStyle : public QObject
{
Q_OBJECT
@@ -23,6 +25,7 @@ class TaskbarStyle : public QObject
Q_PROPERTY(bool clockSeconds READ clockSeconds NOTIFY itemsChanged)
Q_PROPERTY(bool clockLongDate READ clockLongDate NOTIFY itemsChanged)
Q_PROPERTY(bool batteryPercent READ batteryPercent NOTIFY itemsChanged)
+ Q_PROPERTY(bool endTask READ endTask NOTIFY endTaskChanged)
public:
explicit TaskbarStyle(QObject *parent = nullptr);
@@ -33,11 +36,13 @@ public:
bool clockSeconds() const { return m_clockSeconds; }
bool clockLongDate() const { return m_clockLongDate; }
bool batteryPercent() const { return m_batteryPercent; }
+ bool endTask() const { return m_endTask; }
Q_SIGNALS:
void floatingChanged();
void showDesktopChanged();
void itemsChanged();
+ void endTaskChanged();
private:
void read();
@@ -49,4 +54,5 @@ private:
bool m_clockSeconds = false;
bool m_clockLongDate = false;
bool m_batteryPercent = false;
+ bool m_endTask = false;
};
diff --git a/packages/wildos-shell/windowmenu/windowmenu.cpp b/packages/wildos-shell/windowmenu/windowmenu.cpp
index efc1b64..3fdf654 100644
--- a/packages/wildos-shell/windowmenu/windowmenu.cpp
+++ b/packages/wildos-shell/windowmenu/windowmenu.cpp
@@ -16,6 +16,8 @@
#include <QAction>
#include <QDBusConnection>
+#include <QGuiApplication>
+#include <QStyleHints>
#include <QQmlComponent>
#include <QQmlEngine>
#include <QQuickWindow>
@@ -70,6 +72,9 @@ void WindowMenu::takeOverShortcut()
bool WindowMenu::pointerButton(KWin::PointerButtonEvent *event)
{
+ if (event->button == Qt::LeftButton) {
+ return edgeDoubleClick(event);
+ }
if (event->button != Qt::RightButton) {
return false;
}
@@ -106,6 +111,82 @@ void WindowMenu::ShowAtPointer()
show(window, at);
}
+void WindowMenu::MaximizeEdgeAtPointer(int edges)
+{
+ KWin::Window *window = KWin::input()->findToplevel(KWin::input()->globalPointer());
+ if (!window || window->isInternal()) {
+ window = KWin::workspace()->activeWindow();
+ }
+ maximizeForEdges(window, Qt::Edges(edges));
+}
+
+void WindowMenu::maximizeForEdges(KWin::Window *window, Qt::Edges edges)
+{
+ if (!window || !window->isMaximizable() || !edges) {
+ return;
+ }
+ const bool vertical = edges & (Qt::TopEdge | Qt::BottomEdge);
+ const bool horizontal = edges & (Qt::LeftEdge | Qt::RightEdge);
+ // KWin's own operations, so a second double click puts the window back,
+ // as it does on a frame KWin draws.
+ KWin::workspace()->performWindowOperation(window,
+ vertical && horizontal ? KWin::Options::MaximizeOp
+ : vertical ? KWin::Options::VMaximizeOp
+ : KWin::Options::HMaximizeOp);
+}
+
+// KWin handles a double click on the edge of a frame it draws. An app that
+// draws its own (Brave, GTK apps) keeps its resize margin just outside the
+// window it shows and starts the resize itself, so KWin never sees the
+// double click; it is caught here instead.
+bool WindowMenu::edgeDoubleClick(KWin::PointerButtonEvent *event)
+{
+ if (event->state == KWin::PointerButtonState::Released) {
+ const bool swallow = m_swallowLeftRelease;
+ m_swallowLeftRelease = false;
+ return swallow;
+ }
+ const QPointF at = event->position;
+ KWin::Window *window = KWin::input()->findToplevel(at);
+ if (!window || window->isInternal() || window->isDecorated() || !window->isMaximizable()) {
+ m_edgeClick.invalidate();
+ return false;
+ }
+ const QRectF frame = window->frameGeometry();
+ constexpr qreal margin = 12;
+ Qt::Edges edges;
+ if (at.y() < frame.top() && at.y() >= frame.top() - margin) {
+ edges |= Qt::TopEdge;
+ } else if (at.y() >= frame.bottom() && at.y() < frame.bottom() + margin) {
+ edges |= Qt::BottomEdge;
+ }
+ if (at.x() < frame.left() && at.x() >= frame.left() - margin) {
+ edges |= Qt::LeftEdge;
+ } else if (at.x() >= frame.right() && at.x() < frame.right() + margin) {
+ edges |= Qt::RightEdge;
+ }
+ const bool inBand = edges && !frame.contains(at)
+ && at.y() >= frame.top() - margin && at.y() < frame.bottom() + margin
+ && at.x() >= frame.left() - margin && at.x() < frame.right() + margin;
+ if (!inBand) {
+ m_edgeClick.invalidate();
+ return false;
+ }
+ const bool second = m_edgeClick.isValid() && m_edgeClick.elapsed() <= QGuiApplication::styleHints()->mouseDoubleClickInterval()
+ && m_edgeWindow == window && m_edgeEdges == edges && (at - m_edgePosition).manhattanLength() < 10;
+ if (!second) {
+ m_edgeClick.start();
+ m_edgeWindow = window;
+ m_edgeEdges = edges;
+ m_edgePosition = at;
+ return false;
+ }
+ m_edgeClick.invalidate();
+ m_swallowLeftRelease = true;
+ maximizeForEdges(window, edges);
+ return true;
+}
+
void WindowMenu::showForActive()
{
KWin::Window *window = KWin::workspace()->activeWindow();
diff --git a/packages/wildos-shell/windowmenu/windowmenu.h b/packages/wildos-shell/windowmenu/windowmenu.h
index d404dea..78ec344 100644
--- a/packages/wildos-shell/windowmenu/windowmenu.h
+++ b/packages/wildos-shell/windowmenu/windowmenu.h
@@ -9,6 +9,7 @@
#include <input.h>
#include <plugin.h>
+#include <QElapsedTimer>
#include <QPointer>
#include <QVariantMap>
@@ -48,6 +49,11 @@ public:
public Q_SLOTS:
Q_SCRIPTABLE void ShowAtPointer();
+ // A double click on a resize edge, as on Windows: top or bottom stretches
+ // the window under the pointer to the screen's height, left or right to
+ // its width, a corner fills the screen. For apps that draw their own
+ // frame with WildOS.UI (ResizeHandles); edges is Qt::Edges.
+ Q_SCRIPTABLE void MaximizeEdgeAtPointer(int edges);
private:
void takeOverShortcut();
@@ -55,9 +61,18 @@ private:
void show(KWin::Window *window, const QPointF &position);
QVariantMap describe(KWin::Window *window) const;
bool ensureView();
+ bool edgeDoubleClick(KWin::PointerButtonEvent *event);
+ void maximizeForEdges(KWin::Window *window, Qt::Edges edges);
std::unique_ptr<QQmlEngine> m_engine;
std::unique_ptr<QQuickWindow> m_view;
+ // The last press in the resize margin of a window that draws its own
+ // frame, to tell a double click there.
+ QElapsedTimer m_edgeClick;
+ QPointer<KWin::Window> m_edgeWindow;
+ Qt::Edges m_edgeEdges;
+ QPointF m_edgePosition;
+ bool m_swallowLeftRelease = false;
QPointer<KWin::Window> m_window;
bool m_swallowRelease = false;
};
diff --git a/packages/wildos-store/CMakeLists.txt b/packages/wildos-store/CMakeLists.txt
index e23e573..02d3be0 100644
--- a/packages/wildos-store/CMakeLists.txt
+++ b/packages/wildos-store/CMakeLists.txt
@@ -44,6 +44,7 @@ qt_add_qml_module(wildos-store
src/catalog.cpp src/catalog.h
src/storeapp.cpp src/storeapp.h
src/packagekitbackend.cpp src/packagekitbackend.h
+ src/packagesizes.cpp src/packagesizes.h
src/flatpakbackend.cpp src/flatpakbackend.h
src/localpackage.cpp src/localpackage.h
src/network.cpp src/network.h
@@ -64,5 +65,8 @@ install(TARGETS wildos-store RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
install(FILES data/org.wildos.store.desktop DESTINATION ${CMAKE_INSTALL_DATADIR}/applications)
install(FILES data/curated.json DESTINATION ${CMAKE_INSTALL_DATADIR}/wildos-store)
install(FILES data/org.wildos.store.svg DESTINATION ${CMAKE_INSTALL_DATADIR}/icons/hicolor/scalable/apps)
+# Apps listed in the Wild OS section before they are installed need their
+# Wild OS theme icon to be here already (Ganger's package used to ship it).
+install(FILES data/icons/wildos-ganger.svg DESTINATION ${CMAKE_INSTALL_DATADIR}/icons/WildOS/scalable/apps)
install(FILES data/60wildos-store-icons DESTINATION ${CMAKE_INSTALL_SYSCONFDIR}/apt/apt.conf.d)
install(FILES data/wildos-store-update.service data/wildos-store-update.timer DESTINATION ${CMAKE_INSTALL_PREFIX}/lib/systemd/user)
diff --git a/packages/wildos-store/data/curated.json b/packages/wildos-store/data/curated.json
index 58ae05f..4cc64a0 100644
--- a/packages/wildos-store/data/curated.json
+++ b/packages/wildos-store/data/curated.json
@@ -59,6 +59,23 @@
"org.kde.discover.packagekit",
"org.wildos.store"
],
+ "wildos": [
+ "org.wildos.write",
+ "org.wildos.tables",
+ "org.wildos.mail",
+ "org.wildos.pdf",
+ "org.wildos.screenshot",
+ "org.wildos.notes",
+ "org.wildos.remote",
+ "org.wildos.music",
+ "org.wildos.videos",
+ "org.wildos.voice",
+ "org.wildos.backup",
+ "org.wildos.archive",
+ "org.kde.kcalc",
+ "org.wildos.terminal",
+ "io.wildos.ganger"
+ ],
"apps": [
{
"key": "libreoffice",
@@ -544,6 +561,202 @@
"swapTitle": "A good swap for Snipping Tool",
"swapText": "Press Print Screen to grab the screen, a window or an area, then mark it up.",
"category": "utilities"
+ },
+ {
+ "key": "org.wildos.write",
+ "ids": [
+ "org.wildos.write"
+ ],
+ "packages": [
+ "wildos-write"
+ ],
+ "desktop": "libreoffice-writer",
+ "name": "Write",
+ "tagline": "Opens your Word files.",
+ "icon": "org.wildos.write"
+ },
+ {
+ "key": "org.wildos.tables",
+ "ids": [
+ "org.wildos.tables"
+ ],
+ "packages": [
+ "wildos-tables"
+ ],
+ "desktop": "libreoffice-calc",
+ "name": "Tables",
+ "tagline": "Opens your Excel files.",
+ "icon": "org.wildos.tables"
+ },
+ {
+ "key": "org.wildos.mail",
+ "ids": [
+ "org.wildos.mail"
+ ],
+ "packages": [
+ "wildos-mail"
+ ],
+ "desktop": "org.wildos.mail",
+ "name": "Mail",
+ "tagline": "Mail, calendar and people.",
+ "icon": "org.wildos.mail"
+ },
+ {
+ "key": "org.wildos.pdf",
+ "ids": [
+ "org.wildos.pdf"
+ ],
+ "packages": [
+ "wildos-pdf"
+ ],
+ "desktop": "org.wildos.pdf",
+ "name": "PDF",
+ "tagline": "Read, fill in and sign.",
+ "icon": "org.wildos.pdf"
+ },
+ {
+ "key": "org.wildos.screenshot",
+ "ids": [
+ "org.wildos.screenshot"
+ ],
+ "packages": [
+ "wildos-capture"
+ ],
+ "desktop": "org.wildos.screenshot",
+ "name": "Capture",
+ "tagline": "Screenshots and recording.",
+ "icon": "org.wildos.capture"
+ },
+ {
+ "key": "org.wildos.notes",
+ "ids": [
+ "org.wildos.notes"
+ ],
+ "packages": [
+ "wildos-notes"
+ ],
+ "desktop": "org.wildos.notes",
+ "name": "Notes",
+ "tagline": "Notes that stay on this PC.",
+ "icon": "org.wildos.notes"
+ },
+ {
+ "key": "org.wildos.remote",
+ "ids": [
+ "org.wildos.remote"
+ ],
+ "packages": [
+ "wildos-remote"
+ ],
+ "desktop": "org.wildos.remote",
+ "name": "Remote",
+ "tagline": "Remote Desktop and SSH.",
+ "icon": "org.wildos.remote"
+ },
+ {
+ "key": "org.wildos.music",
+ "ids": [
+ "org.wildos.music"
+ ],
+ "packages": [
+ "wildos-music"
+ ],
+ "desktop": "org.wildos.music",
+ "name": "Music",
+ "tagline": "Plays your own music files.",
+ "icon": "org.wildos.music"
+ },
+ {
+ "key": "org.wildos.videos",
+ "ids": [
+ "org.wildos.videos"
+ ],
+ "packages": [
+ "wildos-videos"
+ ],
+ "desktop": "org.wildos.videos",
+ "name": "Videos",
+ "tagline": "Plays your own videos.",
+ "icon": "org.wildos.videos"
+ },
+ {
+ "key": "org.wildos.voice",
+ "ids": [
+ "org.wildos.voice"
+ ],
+ "packages": [
+ "wildos-voice"
+ ],
+ "desktop": "org.wildos.voice",
+ "name": "Voice",
+ "tagline": "Record, with a transcript.",
+ "icon": "org.wildos.voice"
+ },
+ {
+ "key": "org.wildos.backup",
+ "ids": [
+ "org.wildos.backup"
+ ],
+ "packages": [
+ "wildos-backup"
+ ],
+ "desktop": "org.wildos.backup",
+ "name": "Backup",
+ "tagline": "Encrypted backups to a drive.",
+ "icon": "org.wildos.backup"
+ },
+ {
+ "key": "org.wildos.archive",
+ "ids": [
+ "org.wildos.archive"
+ ],
+ "packages": [
+ "wildos-archive"
+ ],
+ "desktop": "org.wildos.archive",
+ "name": "Archive",
+ "tagline": "Open and make zip files.",
+ "icon": "org.wildos.archive"
+ },
+ {
+ "key": "org.kde.kcalc",
+ "ids": [
+ "org.kde.kcalc"
+ ],
+ "packages": [
+ "kcalc"
+ ],
+ "desktop": "org.kde.kcalc",
+ "name": "Calculator",
+ "tagline": "Standard and scientific.",
+ "icon": "accessories-calculator"
+ },
+ {
+ "key": "org.wildos.terminal",
+ "ids": [
+ "org.wildos.terminal"
+ ],
+ "packages": [
+ "wildos-terminal"
+ ],
+ "desktop": "org.wildos.terminal",
+ "name": "Terminal",
+ "tagline": "The command line.",
+ "icon": "org.wildos.terminal"
+ },
+ {
+ "key": "io.wildos.ganger",
+ "ids": [
+ "io.wildos.ganger"
+ ],
+ "packages": [
+ "ganger"
+ ],
+ "desktop": "Ganger",
+ "name": "Ganger",
+ "tagline": "AI coding agents on this PC.",
+ "icon": "wildos-ganger",
+ "onlyIfAvailable": true
}
]
}
diff --git a/packages/wildos-store/data/icons/wildos-ganger.svg b/packages/wildos-store/data/icons/wildos-ganger.svg
new file mode 100644
index 0000000..2e2b0fb
--- /dev/null
+++ b/packages/wildos-store/data/icons/wildos-ganger.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" width="256" height="256"><defs><filter id="gas" x="-25%" y="-25%" width="150%" height="150%"><feDropShadow dx="0" dy="7" stdDeviation="8" flood-color="#060c2a" flood-opacity="0.35"/></filter><linearGradient id="gat" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#ef6ee0"/><stop offset="1" stop-color="#9a1db4"/></linearGradient><linearGradient id="gag" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#fff" stop-opacity="0.22"/><stop offset="0.55" stop-color="#fff" stop-opacity="0"/></linearGradient><linearGradient id="gab" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#fdf2fd"/><stop offset="1" stop-color="#f1d3f3"/></linearGradient><linearGradient id="gaa" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#f58fe6"/><stop offset="1" stop-color="#c13fcf"/></linearGradient></defs><g filter="url(#gas)"><rect x="70" y="40" width="170" height="160" rx="22" fill="url(#gab)"/></g><rect x="146" y="58" width="24" height="7" rx="3.5" fill="#e3b6e8"/><rect x="174" y="58" width="24" height="7" rx="3.5" fill="#e3b6e8"/><rect x="202" y="58" width="24" height="7" rx="3.5" fill="#e3b6e8"/><rect x="146" y="74" width="24" height="26" rx="6" fill="#ffffff"/><rect x="146" y="106" width="24" height="26" rx="6" fill="#ffffff"/><rect x="146" y="138" width="24" height="26" rx="6" fill="#ffffff"/><rect x="174" y="74" width="24" height="26" rx="6" fill="url(#gaa)"/><rect x="174" y="106" width="24" height="26" rx="6" fill="#ffffff"/><rect x="202" y="74" width="24" height="26" rx="6" fill="#ffffff"/><circle cx="214" cy="87" r="5" fill="#3dd68c"/><rect x="202" y="106" width="24" height="26" rx="6" fill="#ffffff"/><circle cx="214" cy="119" r="5" fill="#3dd68c"/><g filter="url(#gas)"><rect x="14" y="70" width="124" height="124" rx="30" fill="url(#gat)"/><rect x="14" y="70" width="124" height="124" rx="30" fill="url(#gag)"/><rect x="15.5" y="71.5" width="121" height="121" rx="28" fill="none" stroke="#fff" stroke-opacity="0.18" stroke-width="2"/><g transform="translate(76.0 132.0)"><rect x="-2.5" y="-38" width="5" height="12" rx="2.5" fill="#ffffff"/><circle cx="0" cy="-40" r="6" fill="#ffffff"/><rect x="-42" y="-6" width="8" height="20" rx="4" fill="#ffffff"/><rect x="34" y="-6" width="8" height="20" rx="4" fill="#ffffff"/><rect x="-32" y="-26" width="64" height="54" rx="16" fill="#ffffff"/><circle cx="-12" cy="-2" r="7" fill="#b02cc4"/><circle cx="12" cy="-2" r="7" fill="#b02cc4"/><rect x="-11" y="14" width="22" height="5" rx="2.5" fill="#b02cc4"/></g></g></svg>
diff --git a/packages/wildos-store/debian/changelog b/packages/wildos-store/debian/changelog
index 0354636..53e782d 100644
--- a/packages/wildos-store/debian/changelog
+++ b/packages/wildos-store/debian/changelog
@@ -1,3 +1,35 @@
+wildos-store (0.1.9) trixie; urgency=medium
+
+ * An app from a repository only some PCs use is listed only where that
+ repository is set up.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 14:30:00 +0000
+
+wildos-store (0.1.8) trixie; urgency=medium
+
+ * The Wild OS section lists only the apps that can be removed and put
+ back, so the Store and Settings are no longer in it.
+ * Reinstall all sits beside the section's title, in place of the
+ summary box.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 14:37:24 +0000
+
+wildos-store (0.1.7) trixie; urgency=medium
+
+ * New Wild OS section: every app we make, with Reinstall for any
+ that were removed and Reinstall all.
+ * The Store can't be removed, even from a terminal.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 14:12:36 +0000
+
+wildos-store (0.1.6) trixie; urgency=medium
+
+ * Apps installed from a .flatpakref file, such as the Install button on
+ flathub.org, are really installed. The Store said they were installed
+ without downloading anything.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 13:47:46 +0000
+
wildos-store (0.1.5) trixie; urgency=medium
* New Store and Settings icons: a white shopping bag with the Wild OS
diff --git a/packages/wildos-store/debian/control b/packages/wildos-store/debian/control
index 60be083..c2b7da1 100644
--- a/packages/wildos-store/debian/control
+++ b/packages/wildos-store/debian/control
@@ -18,6 +18,12 @@ Rules-Requires-Root: no
Package: wildos-store
Architecture: any
+# Where apps come from, and the only way back for one that was removed:
+# apt refuses to remove it, even from a terminal, unless told
+# --allow-remove-essential.
+Protected: yes
+# Takes over the Wild OS theme's Ganger icon from older Ganger packages.
+Replaces: ganger (<< 0.16.0~beta.2+r1)
Depends:
${shlibs:Depends},
${misc:Depends},
diff --git a/packages/wildos-store/qml/Main.qml b/packages/wildos-store/qml/Main.qml
index 571299b..2817789 100644
--- a/packages/wildos-store/qml/Main.qml
+++ b/packages/wildos-store/qml/Main.qml
@@ -35,7 +35,7 @@ UI.AppWindow {
title: "Store"
deep: true
- readonly property var sections: ["discover", "swap", "create", "work", "play", "develop", "categories", "windowsapps", "updates", "library"]
+ readonly property var sections: ["discover", "wildos", "swap", "create", "work", "play", "develop", "categories", "windowsapps", "updates", "library"]
// Names other parts of Wild OS, the command line and D-Bus may still
// use for the pages these replaced.
readonly property var aliases: ({ home: "discover", installed: "library", windows: "swap" })
@@ -43,6 +43,7 @@ UI.AppWindow {
function titleOf(entry) {
switch (entry.page) {
case "discover": return "Discover";
+ case "wildos": return "Wild OS";
case "swap": return "Swap from Windows";
case "create": return "Create";
case "work": return "Work";
@@ -71,6 +72,7 @@ UI.AppWindow {
}
const urls = {
discover: "pages/DiscoverPage.qml",
+ wildos: "pages/WildOSPage.qml",
swap: "pages/SwapPage.qml",
create: "pages/CategoryPage.qml",
work: "pages/CategoryPage.qml",
@@ -367,6 +369,13 @@ UI.AppWindow {
onClicked: root.open("discover")
}
+ NavItem {
+ mark: true
+ text: "Wild OS"
+ current: root.current.section === "wildos"
+ onClicked: root.open("wildos")
+ }
+
NavItem {
iconName: "swap-windows"
text: "Swap from Windows"
diff --git a/packages/wildos-store/qml/components/NavItem.qml b/packages/wildos-store/qml/components/NavItem.qml
index 0a18e69..b9ed4a4 100644
--- a/packages/wildos-store/qml/components/NavItem.qml
+++ b/packages/wildos-store/qml/components/NavItem.qml
@@ -12,6 +12,8 @@ T.AbstractButton {
property bool current: false
property int badge: 0
property bool working: false
+ // The Wild OS mark in place of a line icon.
+ property bool mark: false
implicitHeight: Math.max(34, Math.ceil(label.implicitHeight) + 14)
// Read by the window, which widens the sidebar to fit the longest name.
@@ -43,12 +45,20 @@ T.AbstractButton {
id: icon
x: 10
anchors.verticalCenter: parent.verticalCenter
+ visible: !item.mark
name: item.iconName
size: 17
strokeWidth: 1.8
color: item.current ? UI.Style.accent : Metrics.inkSecondary
}
+ WildOSMark {
+ visible: item.mark
+ x: 10
+ anchors.verticalCenter: parent.verticalCenter
+ size: 17
+ }
+
UI.Label {
id: label
anchors.left: icon.right
diff --git a/packages/wildos-store/qml/components/StoreButton.qml b/packages/wildos-store/qml/components/StoreButton.qml
index 0213845..d4c31e6 100644
--- a/packages/wildos-store/qml/components/StoreButton.qml
+++ b/packages/wildos-store/qml/components/StoreButton.qml
@@ -19,6 +19,9 @@ T.AbstractButton {
property bool showStatus: !big
// A curated line for when there is no status to give ("Opens PSD").
property string note
+ property color noteColor: Metrics.inkTertiary
+ // What Get says: "Reinstall" for one of Wild OS's own apps.
+ property string getLabel: "Get"
// Turned into Open (or Update, or Installed) from a ring: the app page
// gives its icon a small bounce.
@@ -34,7 +37,7 @@ T.AbstractButton {
: shown === "installed" ? "Installed"
: shown === "update" ? "Update"
: shown === "retry" ? "Retry"
- : "Get"
+ : getLabel
readonly property int buttonHeight: big ? 34 : 28
readonly property int minWidth: big ? 84 : 66
@@ -135,7 +138,7 @@ T.AbstractButton {
font.letterSpacing: UI.Style.tracking(UI.Style.px(control.fontSize))
font.pixelSize: UI.Style.px(control.fontSize)
font.weight: UI.Style.weightBold
- text: "Installed"
+ text: control.getLabel.length > "Installed".length ? control.getLabel : "Installed"
}
contentItem: Item {}
@@ -256,9 +259,10 @@ T.AbstractButton {
visible: control.showStatus && text.length > 0
y: control.buttonHeight + 3
x: Math.min(control.width - width, pillLayer.centreX - width / 2)
- text: control.app && control.app.statusLine.length > 0 ? control.app.statusLine : control.note
+ readonly property bool status: control.app && control.app.statusLine.length > 0
+ text: status ? control.app.statusLine : control.note
size: 11
- color: Metrics.inkTertiary
+ color: status ? Metrics.inkTertiary : control.noteColor
}
}
}
diff --git a/packages/wildos-store/qml/components/WildOSMark.qml b/packages/wildos-store/qml/components/WildOSMark.qml
new file mode 100644
index 0000000..bd2ee4f
--- /dev/null
+++ b/packages/wildos-store/qml/components/WildOSMark.qml
@@ -0,0 +1,41 @@
+import QtQuick
+import QtQuick.Shapes
+import WildOS.UI as UI
+
+// The Wild OS mark, filled, as the Wild OS section's sidebar item and its
+// summary bar draw it.
+Item {
+ id: mark
+
+ property real size: 17
+ property color color: UI.Style.inkAlpha(0.86, 0.86)
+
+ implicitWidth: size
+ implicitHeight: size
+
+ Shape {
+ width: 150
+ height: 150
+ preferredRendererType: Shape.CurveRenderer
+ transform: [
+ Translate { x: -18; y: 10.5 },
+ Scale { xScale: mark.size / 150; yScale: mark.size / 150 }
+ ]
+
+ ShapePath {
+ strokeColor: "transparent"
+ fillColor: mark.color
+ PathSvg {
+ path: "M37 17 L50.34 40 L64.75 64.84 L79.16 40 L92.5 17 L105.84 40 L134.26 89 L120.76 112.28 L92.5 63.55 L64.91 111.12 L23.66 40Z"
+ }
+ }
+
+ ShapePath {
+ strokeColor: "transparent"
+ fillColor: mark.color
+ PathSvg {
+ path: "M148.5 17 L162 40 L148.5 63 L135 40Z"
+ }
+ }
+ }
+}
diff --git a/packages/wildos-store/qml/components/WildOSRow.qml b/packages/wildos-store/qml/components/WildOSRow.qml
new file mode 100644
index 0000000..f513429
--- /dev/null
+++ b/packages/wildos-store/qml/components/WildOSRow.qml
@@ -0,0 +1,107 @@
+import QtQuick
+import QtQuick.Templates as T
+import WildOS.Store
+import WildOS.UI as UI
+
+// One of Wild OS's own apps in the Wild OS section (StoreWildOS.dc.html):
+// the 52px icon, name and one line, and at the right Open, or Reinstall
+// with the icon dimmed and "Removed" under it. Under the button: what the
+// app takes up, "Reinstalling" while it comes back, or what went wrong.
+T.AbstractButton {
+ id: row
+
+ property string appKey
+ property bool divider: true
+ readonly property var app: Catalog.app(appKey)
+ readonly property bool working: !!app && (app.busy || app.queued)
+ readonly property bool removed: !!app && !app.installed && !working
+ readonly property string sizeText: Catalog.stateRevision >= 0 && app ? Catalog.sizeText(Catalog.appSize(appKey)) : ""
+
+ signal activated(string key)
+
+ implicitHeight: Math.max(52, Math.ceil(texts.implicitHeight), Math.ceil(button.implicitHeight)) + 20
+ hoverEnabled: true
+ focusPolicy: Qt.TabFocus
+ Accessible.role: Accessible.Button
+ Accessible.name: app ? app.name + ", " + app.tagline + (removed ? ", removed" : "") : ""
+ onClicked: activated(appKey)
+
+ AppMenuArea {
+ appKey: row.appKey
+ }
+
+ background: Item {
+ Rectangle {
+ anchors.fill: parent
+ anchors.leftMargin: -8
+ anchors.rightMargin: -8
+ anchors.topMargin: 1
+ anchors.bottomMargin: 1
+ radius: UI.Style.radiusSm
+ color: row.down ? Metrics.pill : row.hovered ? Metrics.rowHover : "transparent"
+ Behavior on color {
+ ColorAnimation { duration: UI.Style.hoverDuration }
+ }
+
+ UI.FocusRing {
+ visible: row.visualFocus
+ targetRadius: UI.Style.radiusSm
+ }
+ }
+
+ Rectangle {
+ visible: row.divider
+ anchors.bottom: parent.bottom
+ width: parent.width
+ height: 1
+ color: Metrics.divider
+ }
+ }
+
+ contentItem: Item {
+ AppIcon {
+ id: icon
+ anchors.verticalCenter: parent.verticalCenter
+ size: 52
+ source: row.app ? row.app.iconSource : ""
+ opacity: row.removed ? 0.45 : 1
+ Behavior on opacity {
+ NumberAnimation { duration: UI.Style.hoverDuration }
+ }
+ }
+
+ Column {
+ id: texts
+ anchors.left: icon.right
+ anchors.leftMargin: 13
+ anchors.right: button.left
+ anchors.rightMargin: 13
+ anchors.verticalCenter: parent.verticalCenter
+ spacing: 3
+
+ UI.Label {
+ width: parent.width
+ text: row.app ? row.app.name : ""
+ size: 14.5
+ font.weight: UI.Style.weightSemiBold
+ }
+
+ UI.Label {
+ width: parent.width
+ text: row.app ? row.app.tagline : ""
+ size: 13
+ color: Metrics.inkSecondary
+ }
+ }
+
+ StoreButton {
+ id: button
+ anchors.right: parent.right
+ anchors.verticalCenter: parent.verticalCenter
+ app: row.app
+ getLabel: "Reinstall"
+ note: row.working ? "Reinstalling" : row.removed ? "Removed" : row.sizeText
+ noteColor: row.removed ? UI.Style.warning : Metrics.inkTertiary
+ }
+ }
+}
diff --git a/packages/wildos-store/qml/pages/WildOSPage.qml b/packages/wildos-store/qml/pages/WildOSPage.qml
new file mode 100644
index 0000000..a6ddac4
--- /dev/null
+++ b/packages/wildos-store/qml/pages/WildOSPage.qml
@@ -0,0 +1,70 @@
+import QtQuick
+import QtQuick.Layouts
+import WildOS.Store
+import WildOS.UI as UI
+
+// Wild OS (StoreWildOS.dc.html): every app we make, from the curated
+// file's "wildos" list, each with Open or Reinstall, and Reinstall all
+// beside the title while any were removed.
+PageFlick {
+ id: page
+
+ property var store
+ property string arg
+ property string kind
+
+ readonly property var keys: Catalog.catalogRevision >= 0 ? Catalog.wildosApps() : []
+ readonly property var apps: keys.map(k => Catalog.app(k)).filter(a => !!a)
+ // Read again whenever an app's state changes.
+ readonly property int revision: Catalog.stateRevision
+ readonly property var putting: revision >= 0 ? apps.filter(a => (a.busy || a.queued) && !a.installed && a.action !== "remove") : []
+ readonly property var removed: revision >= 0 ? apps.filter(a => !a.installed && !a.busy && !a.queued) : []
+
+ PageTitle {
+ title: "Wild OS"
+ subtitle: "The apps we make. They come with Wild OS, cost nothing and need no account."
+
+ PillButton {
+ visible: page.removed.length > 0 || page.putting.length > 0
+ big: true
+ filled: true
+ enabled: page.removed.length > 0 && page.putting.length === 0
+ text: "Reinstall all"
+ onClicked: Catalog.reinstallWildOS()
+ }
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: 0
+
+ SectionHeader {
+ title: "All " + page.apps.length + " apps"
+ }
+
+ Grid {
+ id: grid
+ Layout.fillWidth: true
+ columns: width > 640 ? 2 : 1
+ columnSpacing: Metrics.columnGap
+ readonly property real cellWidth: (width - columnSpacing * (columns - 1)) / columns
+ // Down each column, as the board fills them: the first half on
+ // the left.
+ flow: Grid.TopToBottom
+ rows: Math.ceil(page.keys.length / columns)
+
+ Repeater {
+ model: page.keys
+
+ WildOSRow {
+ required property string modelData
+ required property int index
+ width: grid.cellWidth
+ appKey: modelData
+ divider: (index + 1) % grid.rows !== 0 && index !== page.keys.length - 1
+ onActivated: key => page.store.openApp(key)
+ }
+ }
+ }
+ }
+}
diff --git a/packages/wildos-store/src/catalog.cpp b/packages/wildos-store/src/catalog.cpp
index d982a67..9fae9fd 100644
--- a/packages/wildos-store/src/catalog.cpp
+++ b/packages/wildos-store/src/catalog.cpp
@@ -4,6 +4,7 @@
#include "flatpakbackend.h"
#include "packagekitbackend.h"
+#include "packagesizes.h"
#include "storeapp.h"
#include "timing.h"
@@ -513,9 +514,14 @@ Catalog::Catalog(QObject *parent)
: QObject(parent)
, m_packagekit(new PackageKitBackend(this))
, m_flatpak(new FlatpakBackend(this))
+ , m_sizes(new PackageSizes(this))
{
s_instance = this;
loadCurated();
+ connect(m_sizes, &PackageSizes::changed, this, &Catalog::bumpState);
+ connect(m_packagekit, &PackageKitBackend::installedChanged, this, [this] {
+ m_sizes->refresh(wildosPackages());
+ });
// An app installed or removed changes which launchers exist.
auto installsChanged = [this] {
@@ -629,6 +635,20 @@ Catalog *Catalog::create(QQmlEngine *, QJSEngine *)
return s_instance;
}
+
+// Whether apt has this package from any repository this PC uses, installed
+// or not. Only asked for the few curated apps that need it.
+static bool aptKnows(const QString &package)
+{
+ QProcess apt;
+ apt.start(QStringLiteral("apt-cache"), {QStringLiteral("show"), QStringLiteral("--no-all-versions"), package});
+ if (!apt.waitForFinished(5000)) {
+ apt.kill();
+ return false;
+ }
+ return apt.exitCode() == 0 && apt.readAllStandardOutput().contains("Package: ");
+}
+
void Catalog::loadCurated()
{
// The installed copy wins so the list can be tuned without a rebuild;
@@ -662,11 +682,17 @@ void Catalog::loadCurated()
c.icon = o.value(QStringLiteral("icon")).toString();
c.desktop = o.value(QStringLiteral("desktop")).toString();
c.category = o.value(QStringLiteral("category")).toString();
+ // An app from a repository only some PCs have (such as Ganger's)
+ // is listed only where apt knows its package.
+ if (o.value(QStringLiteral("onlyIfAvailable")).toBool() && (c.packages.isEmpty() || !aptKnows(c.packages.constFirst()))) {
+ continue;
+ }
m_curated.append(c);
}
m_homeSwaps = strings(root.value(QStringLiteral("homeSwaps")));
m_homeInstalled = strings(root.value(QStringLiteral("homeInstalled")));
m_essentials = strings(root.value(QStringLiteral("essentials")));
+ m_wildos = strings(root.value(QStringLiteral("wildos")));
const QJsonObject featured = root.value(QStringLiteral("featured")).toObject();
for (auto it = featured.begin(); it != featured.end(); ++it) {
m_featured.insert(it.key(), strings(it.value()));
@@ -1057,9 +1083,51 @@ qint64 Catalog::installedSize(const QString &key) const
if (r && installedSource(key) == QLatin1String("flatpak")) {
return m_flatpak->installedSizes().value(r->flatpakId, -1);
}
+ if (r && !r->packages.isEmpty() && installedSource(key) == QLatin1String("apt")) {
+ return m_sizes->size(r->packages.constFirst());
+ }
return -1;
}
+qint64 Catalog::appSize(const QString &key) const
+{
+ const Record *r = record(key);
+ return r && !r->packages.isEmpty() ? m_sizes->size(r->packages.constFirst()) : -1;
+}
+
+QStringList Catalog::wildosApps() const
+{
+ QStringList out;
+ for (const QString &id : m_wildos) {
+ const QString key = keyFor(id);
+ if (!key.isEmpty() && !out.contains(key)) {
+ out << key;
+ }
+ }
+ return out;
+}
+
+QStringList Catalog::wildosPackages() const
+{
+ QStringList out;
+ for (const Curated &c : m_curated) {
+ if (m_wildos.contains(c.key) && !c.packages.isEmpty()) {
+ out << c.packages.constFirst();
+ }
+ }
+ return out;
+}
+
+void Catalog::reinstallWildOS()
+{
+ for (const QString &key : wildosApps()) {
+ const Record *r = record(key);
+ if (r && !isInstalled(key)) {
+ install(key);
+ }
+ }
+}
+
int Catalog::updateCount() const
{
return updates().size();
diff --git a/packages/wildos-store/src/catalog.h b/packages/wildos-store/src/catalog.h
index 5515668..3726bb2 100644
--- a/packages/wildos-store/src/catalog.h
+++ b/packages/wildos-store/src/catalog.h
@@ -23,6 +23,7 @@ class Pool;
class FlatpakBackend;
class PackageKitBackend;
+class PackageSizes;
struct FlatpakPlan;
// Hand-picked details that AppStream does not carry: what an app replaces
@@ -209,6 +210,13 @@ public:
// device pixels without being much larger.
Q_INVOKABLE QString pickImage(const QVariantList &images, int width, int height) const;
Q_INVOKABLE void installEssentials();
+ // The Wild OS section: the apps we make, in the curated file's order,
+ // and putting back every one that was removed.
+ Q_INVOKABLE QStringList wildosApps() const;
+ Q_INVOKABLE void reinstallWildOS();
+ // What a Wild OS package's app takes up, installed, or would take up
+ // once put back; -1 until dpkg and apt have said.
+ Q_INVOKABLE qint64 appSize(const QString &key) const;
Q_INVOKABLE void updateAll();
Q_INVOKABLE void refresh();
Q_INVOKABLE void openSettings(const QString &page);
@@ -283,6 +291,7 @@ private:
void checkPartDone(bool ok);
QString keyFor(const QString &id) const;
Job *job(int id);
+ QStringList wildosPackages() const;
static Catalog *s_instance;
@@ -308,6 +317,7 @@ private:
QStringList m_essentials;
QHash<QString, QStringList> m_featured;
QSet<QString> m_hidden;
+ QStringList m_wildos;
QHash<QString, Record> m_records;
QHash<QString, QString> m_aliases;
@@ -328,6 +338,7 @@ private:
PackageKitBackend *m_packagekit;
FlatpakBackend *m_flatpak;
+ PackageSizes *m_sizes;
bool m_checking = false;
int m_checkParts = 0;
diff --git a/packages/wildos-store/src/flatpakbackend.cpp b/packages/wildos-store/src/flatpakbackend.cpp
index 942ea10..a79efac 100644
--- a/packages/wildos-store/src/flatpakbackend.cpp
+++ b/packages/wildos-store/src/flatpakbackend.cpp
@@ -788,7 +788,9 @@ void FlatpakWorker::runTransaction(const QList<int> &jobs, Op op, const QStringL
break;
}
- if (failure.isEmpty() && added > 0 && !flatpak_transaction_is_empty(transaction)) {
+ // A .flatpakref only becomes operations inside flatpak_transaction_run,
+ // so its transaction looks empty until then and must run anyway.
+ if (failure.isEmpty() && added > 0 && (op == Op::InstallRefFile || !flatpak_transaction_is_empty(transaction))) {
g_signal_connect(transaction, "new-operation", G_CALLBACK(onNewOperation), &state);
g_signal_connect(transaction, "ready", G_CALLBACK(onReady), &state);
g_signal_connect(transaction, "operation-error", G_CALLBACK(onOperationError), &state);
@@ -803,13 +805,16 @@ void FlatpakWorker::runTransaction(const QList<int> &jobs, Op op, const QStringL
if (!flatpak_transaction_run(transaction, cancellable, &error)) {
if (g_cancellable_is_cancelled(cancellable)) {
failure = QString::fromLatin1(cancelledMarker);
+ } else if (g_error_matches(error, FLATPAK_ERROR, FLATPAK_ERROR_ALREADY_INSTALLED)) {
+ // A .flatpakref is only checked against what is installed
+ // once it runs; its app being there already is no failure.
} else {
failure = state.error.isEmpty() ? takeError(error) : state.error;
+ if (failure.isEmpty()) {
+ failure = QStringLiteral("Flathub stopped part way through.");
+ }
}
g_clear_error(&error);
- if (failure.isEmpty()) {
- failure = QStringLiteral("Flathub stopped part way through.");
- }
}
{
QMutexLocker lock(&m_runningMutex);
diff --git a/packages/wildos-store/src/packagesizes.cpp b/packages/wildos-store/src/packagesizes.cpp
new file mode 100644
index 0000000..c01ed7d
--- /dev/null
+++ b/packages/wildos-store/src/packagesizes.cpp
@@ -0,0 +1,212 @@
+#include "packagesizes.h"
+
+#include <QProcess>
+#include <QProcessEnvironment>
+#include <QSet>
+
+namespace
+{
+// Every package a Depends-style field names, alternatives included, without
+// versions or architectures.
+QStringList names(const QString &field)
+{
+ QStringList out;
+ for (const QString &group : field.split(QLatin1Char(','), Qt::SkipEmptyParts)) {
+ for (const QString &alt : group.split(QLatin1Char('|'), Qt::SkipEmptyParts)) {
+ const QString name = alt.trimmed().section(QLatin1Char(' '), 0, 0).section(QLatin1Char('('), 0, 0).section(QLatin1Char(':'), 0, 0);
+ if (!name.isEmpty()) {
+ out << name;
+ }
+ }
+ }
+ return out;
+}
+}
+
+PackageSizes::PackageSizes(QObject *parent)
+ : QObject(parent)
+{
+}
+
+QProcess *PackageSizes::run(const QString &program, const QStringList &args)
+{
+ auto proc = new QProcess(this);
+ QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
+ env.insert(QStringLiteral("LC_ALL"), QStringLiteral("C.UTF-8"));
+ proc->setProcessEnvironment(env);
+ proc->setProcessChannelMode(QProcess::SeparateChannels);
+ proc->start(program, args);
+ return proc;
+}
+
+void PackageSizes::refresh(const QStringList &packages)
+{
+ m_wanted = packages;
+ if (m_running) {
+ m_again = true;
+ return;
+ }
+ m_running = true;
+ m_again = false;
+ m_next.clear();
+ m_missing.clear();
+ m_brings.clear();
+ readInstalled();
+}
+
+void PackageSizes::readInstalled()
+{
+ QProcess *proc = run(QStringLiteral("dpkg-query"),
+ {QStringLiteral("-W"), QStringLiteral("-f=${Package}\t${db:Status-Abbrev}\t${Installed-Size}\t${Pre-Depends}, ${Depends}\t${Recommends}\t${Provides}\n")});
+ connect(proc, &QProcess::finished, this, [this, proc] {
+ proc->deleteLater();
+ QHash<QString, qint64> kib;
+ QHash<QString, QStringList> deps;
+ QHash<QString, QStringList> needs;
+ QHash<QString, QStringList> providers;
+ const QStringList lines = QString::fromUtf8(proc->readAllStandardOutput()).split(QLatin1Char('\n'), Qt::SkipEmptyParts);
+ for (const QString &line : lines) {
+ const QStringList f = line.split(QLatin1Char('\t'));
+ if (f.size() < 6 || f.at(1).size() < 2 || f.at(1).at(1) != QLatin1Char('i')) {
+ continue;
+ }
+ const QString &name = f.at(0);
+ // A package installed for two architectures (the 32-bit switch)
+ // takes room twice.
+ kib[name] += f.at(2).toLongLong();
+ const QStringList own = names(f.at(3));
+ deps[name] << own;
+ needs[name] << own << names(f.at(4));
+ for (const QString &virt : names(f.at(5))) {
+ providers[virt] << name;
+ }
+ }
+ auto resolve = [&kib, &providers](const QString &dep) {
+ return kib.contains(dep) ? QStringList{dep} : providers.value(dep);
+ };
+ // What keeps each package from being taken away: everything installed
+ // that depends on or recommends it, as apt's own autoremove counts.
+ QHash<QString, QSet<QString>> neededBy;
+ for (auto it = needs.cbegin(); it != needs.cend(); ++it) {
+ for (const QString &dep : it.value()) {
+ for (const QString &real : resolve(dep)) {
+ if (real != it.key()) {
+ neededBy[real].insert(it.key());
+ }
+ }
+ }
+ }
+ for (const QString &package : std::as_const(m_wanted)) {
+ if (!kib.contains(package)) {
+ m_missing << package;
+ continue;
+ }
+ QSet<QString> owned{package};
+ bool grew = true;
+ while (grew) {
+ grew = false;
+ const QSet<QString> now = owned;
+ for (const QString &o : now) {
+ for (const QString &dep : deps.value(o)) {
+ for (const QString &real : resolve(dep)) {
+ if (!owned.contains(real) && owned.contains(neededBy.value(real))) {
+ owned.insert(real);
+ grew = true;
+ }
+ }
+ }
+ }
+ }
+ qint64 total = 0;
+ for (const QString &o : std::as_const(owned)) {
+ total += kib.value(o);
+ }
+ m_next.insert(package, total * 1024);
+ }
+ simulateNext();
+ });
+}
+
+void PackageSizes::simulateNext()
+{
+ const QString package = [this] {
+ for (const QString &p : std::as_const(m_missing)) {
+ if (!m_brings.contains(p)) {
+ return p;
+ }
+ }
+ return QString();
+ }();
+ if (package.isEmpty()) {
+ readCandidates();
+ return;
+ }
+ // A simulation needs no password and changes nothing.
+ QProcess *proc = run(QStringLiteral("apt-get"), {QStringLiteral("-s"), QStringLiteral("-q"), QStringLiteral("--no-install-recommends"),
+ QStringLiteral("install"), package});
+ connect(proc, &QProcess::finished, this, [this, proc, package] {
+ proc->deleteLater();
+ QStringList brings;
+ const QStringList lines = QString::fromUtf8(proc->readAllStandardOutput()).split(QLatin1Char('\n'), Qt::SkipEmptyParts);
+ for (const QString &line : lines) {
+ if (line.startsWith(QLatin1String("Inst "))) {
+ brings << line.section(QLatin1Char(' '), 1, 1).section(QLatin1Char(':'), 0, 0);
+ }
+ }
+ m_brings.insert(package, brings);
+ simulateNext();
+ });
+}
+
+void PackageSizes::readCandidates()
+{
+ QSet<QString> all;
+ for (const QStringList &brings : std::as_const(m_brings)) {
+ for (const QString &p : brings) {
+ all.insert(p);
+ }
+ }
+ if (all.isEmpty()) {
+ finish();
+ return;
+ }
+ QStringList args{QStringLiteral("show"), QStringLiteral("--no-all-versions")};
+ args << QStringList(all.cbegin(), all.cend());
+ QProcess *proc = run(QStringLiteral("apt-cache"), args);
+ connect(proc, &QProcess::finished, this, [this, proc] {
+ proc->deleteLater();
+ QHash<QString, qint64> kib;
+ QString current;
+ const QStringList lines = QString::fromUtf8(proc->readAllStandardOutput()).split(QLatin1Char('\n'));
+ for (const QString &line : lines) {
+ if (line.startsWith(QLatin1String("Package: "))) {
+ current = line.mid(9).trimmed();
+ } else if (line.startsWith(QLatin1String("Installed-Size: ")) && !kib.contains(current)) {
+ kib.insert(current, line.mid(16).trimmed().toLongLong());
+ }
+ }
+ for (auto it = m_brings.cbegin(); it != m_brings.cend(); ++it) {
+ if (it.value().isEmpty()) {
+ continue;
+ }
+ qint64 total = 0;
+ for (const QString &p : it.value()) {
+ total += kib.value(p);
+ }
+ m_next.insert(it.key(), total * 1024);
+ }
+ finish();
+ });
+}
+
+void PackageSizes::finish()
+{
+ m_running = false;
+ if (m_next != m_sizes) {
+ m_sizes = m_next;
+ Q_EMIT changed();
+ }
+ if (m_again) {
+ refresh(m_wanted);
+ }
+}
diff --git a/packages/wildos-store/src/packagesizes.h b/packages/wildos-store/src/packagesizes.h
new file mode 100644
index 0000000..1e54c2e
--- /dev/null
+++ b/packages/wildos-store/src/packagesizes.h
@@ -0,0 +1,44 @@
+#pragma once
+
+#include <QHash>
+#include <QObject>
+#include <QStringList>
+
+class QProcess;
+
+// How much room the Wild OS section's apps take, read from dpkg and apt
+// rather than any list of our own. An installed package counts with what
+// only it needs, the parts apt would take away with it. A removed one
+// counts with everything putting it back would install. Both are what an
+// uninstall or a reinstall would really change on this PC.
+class PackageSizes : public QObject
+{
+ Q_OBJECT
+
+public:
+ explicit PackageSizes(QObject *parent = nullptr);
+
+ // Works the sizes out again for these packages, after anything was
+ // installed or removed.
+ void refresh(const QStringList &packages);
+ // Bytes, or -1 while not known.
+ qint64 size(const QString &package) const { return m_sizes.value(package, -1); }
+
+Q_SIGNALS:
+ void changed();
+
+private:
+ void readInstalled();
+ void simulateNext();
+ void readCandidates();
+ void finish();
+ QProcess *run(const QString &program, const QStringList &args);
+
+ QStringList m_wanted;
+ QHash<QString, qint64> m_sizes;
+ QHash<QString, qint64> m_next;
+ QStringList m_missing;
+ QHash<QString, QStringList> m_brings;
+ bool m_running = false;
+ bool m_again = false;
+};
diff --git a/packages/wildos-system-dialogs/CMakeLists.txt b/packages/wildos-system-dialogs/CMakeLists.txt
index bfa07cb..6b493a9 100644
--- a/packages/wildos-system-dialogs/CMakeLists.txt
+++ b/packages/wildos-system-dialogs/CMakeLists.txt
@@ -48,8 +48,20 @@ target_link_libraries(wildos-dialogs PRIVATE
add_executable(32bit-blocked src/32bit-blocked.c)
target_link_options(32bit-blocked PRIVATE -static)
+# sudo in a terminal: one prompt that takes a password or a finger.
+add_library(pam_wildos_fingerprint MODULE src/pam_wildos_fingerprint.c)
+set_target_properties(pam_wildos_fingerprint PROPERTIES PREFIX "")
+target_compile_options(pam_wildos_fingerprint PRIVATE -Wall -Wextra)
+target_link_libraries(pam_wildos_fingerprint PRIVATE pam)
+install(TARGETS pam_wildos_fingerprint LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}/security)
+
+# Advanced protection's fingerprint rule: notes each password sign-in.
+add_executable(fingerprint-stamp src/fingerprint-stamp.c)
+target_compile_options(fingerprint-stamp PRIVATE -Wall -Wextra)
+
set(LIBEXEC ${CMAKE_INSTALL_PREFIX}/libexec/wildos)
-install(TARGETS wildos-dialogs 32bit-blocked RUNTIME DESTINATION ${LIBEXEC})
+install(TARGETS wildos-dialogs 32bit-blocked fingerprint-stamp RUNTIME DESTINATION ${LIBEXEC})
+install(FILES data/fingerprint-stamp.socket data/[email protected] DESTINATION ${CMAKE_INSTALL_PREFIX}/lib/systemd/system)
install(PROGRAMS data/32bit-prompt-setup DESTINATION ${LIBEXEC})
install(FILES data/wildos-32bit-prompt.service DESTINATION ${CMAKE_INSTALL_PREFIX}/lib/systemd/system)
install(PROGRAMS data/record-package-sources DESTINATION ${LIBEXEC})
diff --git a/packages/wildos-system-dialogs/data/fingerprint-stamp.socket b/packages/wildos-system-dialogs/data/fingerprint-stamp.socket
new file mode 100644
index 0000000..9511423
--- /dev/null
+++ b/packages/wildos-system-dialogs/data/fingerprint-stamp.socket
@@ -0,0 +1,13 @@
+[Unit]
+Description=Note password unlocks for fingerprint sign-in
+
+[Socket]
+# The lock screen runs as the person, who can't write the root-owned note
+# fingerprint-stamp keeps; it hands the password over here instead.
+ListenStream=/run/wildos/fingerprint-stamp.socket
+SocketMode=0666
+Accept=yes
+MaxConnections=8
+
+[Install]
+WantedBy=sockets.target
diff --git a/packages/wildos-system-dialogs/data/[email protected] b/packages/wildos-system-dialogs/data/[email protected]
new file mode 100644
index 0000000..528ed9c
--- /dev/null
+++ b/packages/wildos-system-dialogs/data/[email protected]
@@ -0,0 +1,17 @@
+[Unit]
+Description=Note a password unlock for fingerprint sign-in
+CollectMode=inactive-or-failed
+
+[Service]
+ExecStart=/usr/libexec/wildos/fingerprint-stamp --serve
+StandardInput=socket
+StandardOutput=socket
+StandardError=journal
+# Reads /etc/shadow through unix_chkpwd and writes only /run/wildos.
+ProtectSystem=strict
+ReadWritePaths=/run/wildos
+ProtectHome=yes
+PrivateNetwork=yes
+PrivateTmp=yes
+NoNewPrivileges=yes
+RestrictAddressFamilies=AF_UNIX
diff --git a/packages/wildos-system-dialogs/debian/changelog b/packages/wildos-system-dialogs/debian/changelog
index da12d71..e49525d 100644
--- a/packages/wildos-system-dialogs/debian/changelog
+++ b/packages/wildos-system-dialogs/debian/changelog
@@ -1,3 +1,42 @@
+wildos-system-dialogs (0.1.15) trixie; urgency=medium
+
+ * The fingerprint keeps working after a restart again: asking for the
+ password after a restart or every so many hours is off unless you
+ switch it on in Advanced protection (Strict and Maximum switch it on).
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 16:00:00 +0000
+
+wildos-system-dialogs (0.1.14) trixie; urgency=medium
+
+ * Notes each password sign-in and unlock, so the fingerprint can ask
+ for the password again after a restart and after the hours chosen in
+ Advanced protection.
+ * The password prompt for turning the camera or microphone back on for
+ every app says so, under the name Camera and microphone.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 14:56:10 +0000
+
+wildos-system-dialogs (0.1.13) trixie; urgency=medium
+
+ * The password box in the permission prompt takes only what is typed:
+ nothing can be pasted into it.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 09:45:00 +0000
+
+wildos-system-dialogs (0.1.12) trixie; urgency=medium
+
+ * The details in a permission request can be copied from a right-
+ click menu.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 08:54:22 +0000
+
+wildos-system-dialogs (0.1.11) trixie; urgency=medium
+
+ * sudo in a terminal takes your password or your fingerprint from the
+ same prompt, whichever comes first.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 15:30:00 +0000
+
wildos-system-dialogs (0.1.10) trixie; urgency=medium
* Opening a 32-bit program, such as Steam, while 32-bit apps are off
diff --git a/packages/wildos-system-dialogs/debian/control b/packages/wildos-system-dialogs/debian/control
index 905efd7..ba8f31e 100644
--- a/packages/wildos-system-dialogs/debian/control
+++ b/packages/wildos-system-dialogs/debian/control
@@ -12,6 +12,7 @@ Build-Depends:
libkf6windowsystem-dev,
liblayershellqtinterface-dev,
libpolkit-qt6-1-dev,
+ libpam0g-dev,
Standards-Version: 4.7.0
Rules-Requires-Root: no
@@ -20,7 +21,7 @@ Architecture: any
Depends:
${shlibs:Depends},
${misc:Depends},
- wildos-ui,
+ wildos-ui (>= 0.1.12),
polkitd,
kwin-common,
dpkg,
diff --git a/packages/wildos-system-dialogs/qml/PermissionCard.qml b/packages/wildos-system-dialogs/qml/PermissionCard.qml
index 9e7edd3..b656e07 100644
--- a/packages/wildos-system-dialogs/qml/PermissionCard.qml
+++ b/packages/wildos-system-dialogs/qml/PermissionCard.qml
@@ -214,6 +214,7 @@ Item {
UI.TextField {
id: password
+ UI.NoPaste {}
Layout.fillWidth: true
implicitHeight: 40
echoMode: TextInput.Password
@@ -304,6 +305,16 @@ Item {
font.family: UI.Style.fontFamily
font.letterSpacing: UI.Style.tracking(UI.Style.px(12))
font.pixelSize: UI.Style.px(12)
+ Keys.onPressed: event => {
+ if (valueMenu.isMenuKey(event)) {
+ valueMenu.openAtCaret();
+ event.accepted = true;
+ }
+ }
+
+ UI.TextMenu {
+ id: valueMenu
+ }
}
}
}
diff --git a/packages/wildos-system-dialogs/src/fingerprint-stamp.c b/packages/wildos-system-dialogs/src/fingerprint-stamp.c
new file mode 100644
index 0000000..6252764
--- /dev/null
+++ b/packages/wildos-system-dialogs/src/fingerprint-stamp.c
@@ -0,0 +1,237 @@
+// fingerprint-stamp: notes that a password was just typed, for Advanced
+// protection's "Fingerprint needs your password sometimes".
+//
+// fingerprint-turn and pam_wildos_fingerprint turn the finger down after a
+// restart until the password has been typed once, and again once the
+// chosen hours have passed. They read /run/wildos/fingerprint/USER, which
+// holds the seconds since start-up at the last password sign-in: /run is
+// empty after a restart, and seconds since start-up don't move when the
+// clock is changed.
+//
+// The file is root's, so nothing running as the person can make the
+// finger last longer. PAM runs this after the password with pam_exec's
+// expose_authtok, and it checks the password again itself with
+// unix_chkpwd before writing anything:
+//
+// fingerprint-stamp From PAM. As root (sign-in screen, sudo,
+// administrator prompts) it checks and writes
+// for PAM_USER; as the person (the lock
+// screen) it hands the password to the
+// service below, which can write the file.
+// fingerprint-stamp --serve [email protected], one connection
+// on fingerprint-stamp.socket as its stdin.
+// Only ever notes the password of the account
+// on the other end of the socket.
+//
+// A wrong password writes nothing; the service then waits two seconds, so
+// it is no quicker to guess with than the lock screen.
+
+#define _GNU_SOURCE
+#include <errno.h>
+#include <fcntl.h>
+#include <pwd.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <sys/un.h>
+#include <sys/wait.h>
+#include <time.h>
+#include <unistd.h>
+
+#define STAMPS "/run/wildos/fingerprint"
+#define SOCKET_PATH "/run/wildos/fingerprint-stamp.socket"
+#define CHKPWD "/usr/sbin/unix_chkpwd"
+// PAM_MAX_RESP_SIZE, the most pam_exec hands over.
+#define MAX_PASSWORD 512
+
+static int name_ok(const char *user)
+{
+ if (!user || !*user || !strcmp(user, ".") || !strcmp(user, "..") || strlen(user) > 64)
+ return 0;
+ return strchr(user, '/') == NULL;
+}
+
+// Up to the NUL pam_exec ends it with, or the end of the input.
+static ssize_t read_password(int fd, char *buf, size_t size)
+{
+ size_t n = 0;
+
+ while (n < size) {
+ ssize_t got = read(fd, buf + n, size - n);
+ if (got < 0 && errno == EINTR)
+ continue;
+ if (got <= 0)
+ break;
+ void *nul = memchr(buf + n, '\0', (size_t)got);
+ n += (size_t)got;
+ if (nul) {
+ n = (size_t)((char *)nul - buf);
+ break;
+ }
+ }
+ return (ssize_t)n;
+}
+
+static int write_all(int fd, const char *buf, size_t len)
+{
+ while (len > 0) {
+ ssize_t put = write(fd, buf, len);
+ if (put < 0 && errno == EINTR)
+ continue;
+ if (put <= 0)
+ return -1;
+ buf += put;
+ len -= (size_t)put;
+ }
+ return 0;
+}
+
+// unix_chkpwd checks any account's password when run by root, reading it
+// from stdin up to a NUL.
+static int password_right(const char *user, const char *password, size_t len)
+{
+ int in[2];
+ pid_t pid;
+ int status = 0;
+
+ if (pipe2(in, O_CLOEXEC) < 0)
+ return 0;
+ pid = fork();
+ if (pid < 0) {
+ close(in[0]);
+ close(in[1]);
+ return 0;
+ }
+ if (pid == 0) {
+ int null = open("/dev/null", O_RDWR);
+ dup2(in[0], STDIN_FILENO);
+ if (null >= 0) {
+ dup2(null, STDOUT_FILENO);
+ dup2(null, STDERR_FILENO);
+ }
+ execl(CHKPWD, CHKPWD, user, "nonull", (char *)NULL);
+ _exit(127);
+ }
+ close(in[0]);
+ signal(SIGPIPE, SIG_IGN);
+ write_all(in[1], password, len);
+ write_all(in[1], "", 1);
+ close(in[1]);
+ while (waitpid(pid, &status, 0) < 0 && errno == EINTR)
+ ;
+ return WIFEXITED(status) && WEXITSTATUS(status) == 0;
+}
+
+static int write_stamp(const char *user)
+{
+ char path[256];
+ char tmp[300];
+ char text[32];
+ struct timespec now;
+ int fd;
+ int len;
+
+ if (clock_gettime(CLOCK_BOOTTIME, &now) < 0)
+ return -1;
+ mkdir("/run/wildos", 0755);
+ if (mkdir(STAMPS, 0755) < 0 && errno != EEXIST)
+ return -1;
+ snprintf(path, sizeof path, "%s/%s", STAMPS, user);
+ snprintf(tmp, sizeof tmp, "%s/.%s.new", STAMPS, user);
+ len = snprintf(text, sizeof text, "%lld\n", (long long)now.tv_sec);
+ fd = open(tmp, O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW | O_CLOEXEC, 0644);
+ if (fd < 0)
+ return -1;
+ if (write_all(fd, text, (size_t)len) < 0 || fchmod(fd, 0644) < 0) {
+ close(fd);
+ unlink(tmp);
+ return -1;
+ }
+ close(fd);
+ if (rename(tmp, path) < 0) {
+ unlink(tmp);
+ return -1;
+ }
+ return 0;
+}
+
+static int serve(void)
+{
+ struct ucred cred;
+ socklen_t size = sizeof cred;
+ struct passwd *pw;
+ char password[MAX_PASSWORD];
+ ssize_t len;
+ int ok = 0;
+
+ if (getsockopt(STDIN_FILENO, SOL_SOCKET, SO_PEERCRED, &cred, &size) < 0)
+ return 1;
+ pw = getpwuid(cred.uid);
+ if (!pw || cred.uid == 0 || !name_ok(pw->pw_name))
+ return 1;
+ len = read_password(STDIN_FILENO, password, sizeof password);
+ if (len > 0 && password_right(pw->pw_name, password, (size_t)len))
+ ok = write_stamp(pw->pw_name) == 0;
+ explicit_bzero(password, sizeof password);
+ if (!ok)
+ sleep(2);
+ write_all(STDOUT_FILENO, ok ? "1" : "0", 1);
+ // The answer goes back on the socket; a wrong password is no failure of
+ // the service's own.
+ return 0;
+}
+
+static int hand_over(const char *password, size_t len)
+{
+ struct sockaddr_un addr = {.sun_family = AF_UNIX};
+ char answer = '0';
+ int fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
+
+ if (fd < 0)
+ return 1;
+ strncpy(addr.sun_path, SOCKET_PATH, sizeof addr.sun_path - 1);
+ signal(SIGPIPE, SIG_IGN);
+ if (connect(fd, (struct sockaddr *)&addr, sizeof addr) < 0 || write_all(fd, password, len) < 0) {
+ close(fd);
+ return 1;
+ }
+ shutdown(fd, SHUT_WR);
+ while (read(fd, &answer, 1) < 0 && errno == EINTR)
+ ;
+ close(fd);
+ return answer == '1' ? 0 : 1;
+}
+
+int main(int argc, char **argv)
+{
+ const char *type = getenv("PAM_TYPE");
+ const char *user = getenv("PAM_USER");
+ char password[MAX_PASSWORD];
+ ssize_t len;
+ int status = 1;
+
+ if (argc == 2 && !strcmp(argv[1], "--serve"))
+ return serve();
+ if (argc != 1)
+ return 2;
+ // pam_exec also runs for the other PAM steps; only a sign-in counts.
+ if (!type || strcmp(type, "auth") || !name_ok(user))
+ return 0;
+ len = read_password(STDIN_FILENO, password, sizeof password);
+ if (len <= 0)
+ return 1;
+ if (geteuid() == 0) {
+ if (password_right(user, password, (size_t)len))
+ status = write_stamp(user) == 0 ? 0 : 1;
+ } else {
+ const struct passwd *pw = getpwuid(getuid());
+ if (pw && !strcmp(pw->pw_name, user))
+ status = hand_over(password, (size_t)len);
+ }
+ explicit_bzero(password, sizeof password);
+ return status;
+}
diff --git a/packages/wildos-system-dialogs/src/pam_wildos_fingerprint.c b/packages/wildos-system-dialogs/src/pam_wildos_fingerprint.c
new file mode 100644
index 0000000..d90686d
--- /dev/null
+++ b/packages/wildos-system-dialogs/src/pam_wildos_fingerprint.c
@@ -0,0 +1,589 @@
+// pam_wildos_fingerprint: sudo in a terminal takes a password or a finger,
+// whichever comes first, from one prompt.
+//
+// pam_fprintd can only wait for the finger or let the password through, one
+// after the other, so Wild OS's common-auth asks for an empty password to mean
+// "use my finger" (fingerprint-turn). Here the reader listens while the
+// password is typed: fprintd's own fprintd-verify runs in a child process,
+// and the terminal and the child's output are watched together with poll().
+// Nothing is interrupted with signals or cancelled threads, so the terminal
+// always gets its echo back.
+//
+// A typed password is handed on as PAM_AUTHTOK and checked by pam_unix as
+// before, with faillock and Kicksecure's checks untouched. A finger returns
+// PAM_SUCCESS, which the wildos-fingerprint profile turns into a jump to
+// faillock's authsucc, as pam_fprintd's success already did.
+//
+// Whenever this cannot do the job properly it returns PAM_IGNORE and changes
+// nothing, so the stack carries on exactly as it did before this module:
+// another service than sudo, sudo -n/-S/-A or a custom -p prompt, no
+// terminal, the "administrator prompts" fingerprint switch off, no enrolled
+// finger, or a locked password.
+
+#define _GNU_SOURCE
+#include <errno.h>
+#include <fcntl.h>
+#include <ftw.h>
+#include <poll.h>
+#include <shadow.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <termios.h>
+#include <time.h>
+#include <unistd.h>
+
+#include <security/pam_ext.h>
+#include <security/pam_modules.h>
+
+#define FPRINTD_VERIFY "/usr/bin/fprintd-verify"
+#define SWITCHES "/etc/wildos/fingerprint.conf"
+#define PRINTS "/var/lib/fprint"
+#define ADVANCED "/etc/wildos/advanced-protection"
+#define STAMPS "/run/wildos/fingerprint"
+#define FINGER_TRIES 3
+// sudo's own default password timeout.
+#define WAIT_SECONDS (5 * 60)
+
+static volatile sig_atomic_t interrupted;
+
+static void on_interrupt(int sig)
+{
+ interrupted = sig;
+}
+
+static int name_ok(const char *user)
+{
+ if (!user || !*user || !strcmp(user, ".") || !strcmp(user, ".."))
+ return 0;
+ return strchr(user, '/') == NULL;
+}
+
+// Settings > Accounts > Sign-in options writes admin=off to stop fingerprints
+// at administrator prompts; anything else, or no file, leaves them on.
+static int switch_on(void)
+{
+ FILE *f = fopen(SWITCHES, "re");
+ char line[256];
+ int on = 1;
+
+ if (!f)
+ return 1;
+ while (fgets(line, sizeof line, f)) {
+ char *p = line;
+ while (*p == ' ' || *p == '\t')
+ p++;
+ if (strncmp(p, "admin", 5))
+ continue;
+ p += 5;
+ while (*p == ' ' || *p == '\t')
+ p++;
+ if (*p++ != '=')
+ continue;
+ while (*p == ' ' || *p == '\t')
+ p++;
+ on = strncmp(p, "off", 3) != 0;
+ }
+ fclose(f);
+ return on;
+}
+
+// Settings > Privacy and security > Advanced protection's "Fingerprint
+// needs your password sometimes" (fingerprint_hours, off unless set;
+// Strict and Maximum set it): no finger after a restart until the password has been typed once,
+// nor once that many hours have passed since. fingerprint-stamp notes each
+// password sign-in in /run, in seconds since start-up; fingerprint-turn
+// reads the same files.
+static long finger_hours(void)
+{
+ FILE *f = fopen(ADVANCED, "re");
+ char line[256];
+ long hours = 0;
+
+ if (!f)
+ return hours;
+ while (fgets(line, sizeof line, f)) {
+ char *end;
+ long value;
+ if (strncmp(line, "fingerprint_hours=", 18))
+ continue;
+ value = strtol(line + 18, &end, 10);
+ if (end != line + 18 && (*end == '\n' || *end == '\0') && value >= 0)
+ hours = value;
+ }
+ fclose(f);
+ return hours;
+}
+
+static int password_recent(const char *user)
+{
+ long hours = finger_hours();
+ char path[512];
+ FILE *f;
+ long typed = -1;
+ double now = -1;
+
+ if (hours == 0)
+ return 1;
+ if (snprintf(path, sizeof path, "%s/%s", STAMPS, user) >= (int)sizeof path)
+ return 0;
+ f = fopen(path, "re");
+ if (!f)
+ return 0;
+ if (fscanf(f, "%ld", &typed) != 1)
+ typed = -1;
+ fclose(f);
+ f = fopen("/proc/uptime", "re");
+ if (!f)
+ return 0;
+ if (fscanf(f, "%lf", &now) != 1)
+ now = -1;
+ fclose(f);
+ return typed >= 0 && now >= typed && (long)now - typed < hours * 3600;
+}
+
+static int found_print;
+
+static int look(const char *path, const struct stat *st, int type, struct FTW *ftw)
+{
+ (void)path;
+ (void)st;
+ (void)ftw;
+ if (type == FTW_F) {
+ found_print = 1;
+ return 1;
+ }
+ return 0;
+}
+
+static int enrolled(const char *user)
+{
+ char dir[512];
+
+ if (snprintf(dir, sizeof dir, "%s/%s", PRINTS, user) >= (int)sizeof dir)
+ return 0;
+ found_print = 0;
+ nftw(dir, look, 8, FTW_PHYS);
+ return found_print;
+}
+
+// A locked password (passwd -l) locks the account; a finger must not get
+// round it.
+static int locked(const char *user)
+{
+ struct spwd *sp = getspnam(user);
+
+ if (!sp || !sp->sp_pwdp)
+ return 1;
+ return sp->sp_pwdp[0] == '!' || sp->sp_pwdp[0] == '*';
+}
+
+// Only an ordinary interactive sudo: not -n (nothing may be asked), -S (the
+// password comes on stdin), -A (an askpass helper asks) or -p (the caller
+// chose its own prompt). Reading sudo's options from its command line is
+// crude, so anything unexpected counts as "not ordinary" and falls back.
+static int ordinary_sudo(void)
+{
+ static const char *const long_with_arg[] = {
+ "user", "group", "close-from", "chdir", "chroot", "host", "role",
+ "type", "command-timeout", "other-user", NULL
+ };
+ static const char *const long_refused[] = {
+ "non-interactive", "stdin", "askpass", "prompt", NULL
+ };
+ char exe[64], buf[8192];
+ ssize_t n;
+ int fd;
+ size_t len, i;
+ char *arg, *end;
+
+ n = readlink("/proc/self/exe", exe, sizeof exe - 1);
+ if (n <= 0)
+ return 0;
+ exe[n] = 0;
+ if (strcmp(exe, "/usr/bin/sudo"))
+ return 0;
+
+ fd = open("/proc/self/cmdline", O_RDONLY | O_CLOEXEC);
+ if (fd < 0)
+ return 0;
+ len = 0;
+ while (len < sizeof buf - 1 && (n = read(fd, buf + len, sizeof buf - 1 - len)) > 0)
+ len += n;
+ close(fd);
+ if (len == 0 || len >= sizeof buf - 1)
+ return 0;
+ buf[len] = 0;
+ end = buf + len;
+
+ arg = buf + strlen(buf) + 1;
+ while (arg < end) {
+ char *next = arg + strlen(arg) + 1;
+
+ if (arg[0] != '-' || !strcmp(arg, "-") || !strcmp(arg, "--"))
+ break;
+ if (arg[1] == '-') {
+ const char *name = arg + 2;
+ size_t nl = strcspn(name, "=");
+
+ for (i = 0; long_refused[i]; i++)
+ if (strlen(long_refused[i]) == nl && !strncmp(name, long_refused[i], nl))
+ return 0;
+ if (!name[nl])
+ for (i = 0; long_with_arg[i]; i++)
+ if (!strcmp(name, long_with_arg[i])) {
+ next = next < end ? next + strlen(next) + 1 : next;
+ break;
+ }
+ } else {
+ for (const char *c = arg + 1; *c; c++) {
+ if (strchr("nSAp", *c))
+ return 0;
+ if (*c == 'h')
+ break;
+ if (strchr("CDgRrTtUu", *c)) {
+ if (!c[1] && next < end)
+ next += strlen(next) + 1;
+ break;
+ }
+ }
+ }
+ arg = next;
+ }
+ return 1;
+}
+
+static pid_t start_verify(const char *user, int *out)
+{
+ int pipefd[2];
+ pid_t pid;
+
+ if (pipe2(pipefd, O_CLOEXEC) < 0)
+ return -1;
+ pid = fork();
+ if (pid < 0) {
+ close(pipefd[0]);
+ close(pipefd[1]);
+ return -1;
+ }
+ if (pid == 0) {
+ char *const args[] = { "fprintd-verify", (char *)user, NULL };
+ char *const env[] = { "PATH=/usr/bin:/bin", "LC_ALL=C", NULL };
+ int null = open("/dev/null", O_RDWR);
+
+ // sudo authenticates as the invoking user with root's effective id;
+ // fprintd only lets root verify another account's finger.
+ if (setresgid(0, 0, 0) < 0 || setresuid(0, 0, 0) < 0)
+ _exit(127);
+ if (null >= 0)
+ dup2(null, 0);
+ dup2(pipefd[1], 1);
+ dup2(pipefd[1], 2);
+ signal(SIGINT, SIG_DFL);
+ signal(SIGQUIT, SIG_DFL);
+ signal(SIGTSTP, SIG_DFL);
+ execve(FPRINTD_VERIFY, args, env);
+ _exit(127);
+ }
+ close(pipefd[1]);
+ *out = pipefd[0];
+ return pid;
+}
+
+static void stop_verify(pid_t *pid, int *out)
+{
+ if (*out >= 0) {
+ close(*out);
+ *out = -1;
+ }
+ if (*pid > 0) {
+ // fprintd releases the reader when the client leaves the bus.
+ kill(*pid, SIGTERM);
+ waitpid(*pid, NULL, 0);
+ *pid = -1;
+ }
+}
+
+static void say(int tty, const char *text)
+{
+ size_t left = strlen(text);
+
+ while (left > 0) {
+ ssize_t n = write(tty, text, left);
+ if (n < 0 && errno == EINTR)
+ continue;
+ if (n <= 0)
+ return;
+ text += n;
+ left -= n;
+ }
+}
+
+// The prompt again after a message, with a star for each key already typed.
+static void reprompt(int tty, const char *prompt, size_t typed, size_t *shown)
+{
+ say(tty, prompt);
+ for (*shown = 0; *shown < typed; (*shown)++)
+ say(tty, "*");
+}
+
+PAM_EXTERN int pam_sm_authenticate(pam_handle_t *pamh, int flags, int argc, const char **argv)
+{
+ const char *service = NULL, *user = NULL;
+ const void *token = NULL;
+ char prompt[300], line[1024], out[512];
+ size_t used = 0, outlen = 0, shown = 0;
+ int tty, verify_out = -1, tries = 0, matched = 0, result = PAM_IGNORE;
+ int listening, discard = 0;
+ pid_t verify = -1;
+ struct termios saved, quiet;
+ struct sigaction act, old_int, old_quit, old_tstp;
+ sigset_t mask;
+ time_t deadline;
+
+ (void)flags;
+ (void)argc;
+ (void)argv;
+
+ if (pam_get_item(pamh, PAM_SERVICE, (const void **)&service) != PAM_SUCCESS || !service)
+ return PAM_IGNORE;
+ if (strcmp(service, "sudo") && strcmp(service, "sudo-i"))
+ return PAM_IGNORE;
+ if (pam_get_item(pamh, PAM_AUTHTOK, &token) == PAM_SUCCESS && token)
+ return PAM_IGNORE;
+ if (pam_get_item(pamh, PAM_USER, (const void **)&user) != PAM_SUCCESS || !name_ok(user))
+ return PAM_IGNORE;
+ if (!switch_on() || !enrolled(user) || locked(user) || !password_recent(user) || !ordinary_sudo())
+ return PAM_IGNORE;
+ if (access(FPRINTD_VERIFY, X_OK) < 0)
+ return PAM_IGNORE;
+
+ tty = open("/dev/tty", O_RDWR | O_NOCTTY | O_CLOEXEC);
+ if (tty < 0)
+ return PAM_IGNORE;
+ if (tcgetattr(tty, &saved) < 0) {
+ close(tty);
+ return PAM_IGNORE;
+ }
+
+ verify = start_verify(user, &verify_out);
+ if (verify < 0) {
+ close(tty);
+ return PAM_IGNORE;
+ }
+ listening = 1;
+
+ interrupted = 0;
+ memset(&act, 0, sizeof act);
+ act.sa_handler = on_interrupt;
+ sigemptyset(&act.sa_mask);
+ sigaction(SIGINT, &act, &old_int);
+ sigaction(SIGQUIT, &act, &old_quit);
+ act.sa_handler = SIG_IGN;
+ sigaction(SIGTSTP, &act, &old_tstp);
+ sigprocmask(SIG_SETMASK, NULL, &mask);
+ sigdelset(&mask, SIGINT);
+ sigdelset(&mask, SIGQUIT);
+
+ // Keys are read one at a time so each shows as a star, as sudo's own
+ // prompt does with Kicksecure's pwfeedback. Ctrl+C still signals.
+ quiet = saved;
+ quiet.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL | ICANON);
+ quiet.c_cc[VMIN] = 1;
+ quiet.c_cc[VTIME] = 0;
+ tcsetattr(tty, TCSAFLUSH, &quiet);
+
+ snprintf(prompt, sizeof prompt, "[sudo] password or fingerprint for %s: ", user);
+ reprompt(tty, prompt, 0, &shown);
+ deadline = time(NULL) + WAIT_SECONDS;
+
+ for (;;) {
+ struct pollfd fds[2] = {
+ { .fd = tty, .events = POLLIN },
+ { .fd = verify_out, .events = POLLIN },
+ };
+ time_t left = deadline - time(NULL);
+ struct timespec wait = { .tv_sec = left > 0 ? left : 0 };
+ int n;
+
+ if (left <= 0) {
+ say(tty, "\nTimed out.\n");
+ result = PAM_AUTH_ERR;
+ break;
+ }
+ n = ppoll(fds, verify_out >= 0 ? 2 : 1, &wait, &mask);
+ if (interrupted)
+ break;
+ if (n < 0) {
+ if (errno == EINTR)
+ continue;
+ break;
+ }
+
+ if (fds[0].revents & (POLLIN | POLLHUP | POLLERR)) {
+ unsigned char keys[64];
+ ssize_t got = read(tty, keys, sizeof keys);
+ int entered = 0, gone = 0;
+
+ if (got < 0 && errno == EINTR)
+ continue;
+ if (got <= 0)
+ gone = 1;
+ for (ssize_t i = 0; i < got && !entered && !gone; i++) {
+ unsigned char c = keys[i];
+
+ if (c == '\r' || c == '\n') {
+ entered = 1;
+ } else if (c == saved.c_cc[VERASE] || c == 0x7f || c == 0x08) {
+ if (used > 0) {
+ used--;
+ if (shown > 0) {
+ say(tty, "\b \b");
+ shown--;
+ }
+ }
+ } else if (c == saved.c_cc[VKILL]) {
+ for (; shown > 0; shown--)
+ say(tty, "\b \b");
+ used = 0;
+ } else if (c == saved.c_cc[VEOF]) {
+ if (used == 0)
+ gone = 1;
+ } else if (used < sizeof line - 1) {
+ line[used++] = c;
+ say(tty, "*");
+ shown++;
+ } else {
+ // Far longer than any password: refused at Enter.
+ discard = 1;
+ }
+ }
+ explicit_bzero(keys, sizeof keys);
+ if (gone) {
+ // Ctrl+D or a vanished terminal: leave it to the next module.
+ say(tty, "\n");
+ break;
+ }
+ if (!entered)
+ continue;
+ line[used] = 0;
+ say(tty, "\n");
+ if (discard) {
+ result = PAM_AUTH_ERR;
+ break;
+ }
+ if (used == 0) {
+ if (listening) {
+ // Enter on its own while the reader listens: nothing to
+ // check yet, keep waiting.
+ reprompt(tty, prompt, 0, &shown);
+ continue;
+ }
+ break;
+ }
+ pam_set_item(pamh, PAM_AUTHTOK, line);
+ break;
+ }
+
+ if (verify_out >= 0 && (fds[1].revents & (POLLIN | POLLHUP | POLLERR))) {
+ ssize_t got = read(verify_out, out + outlen, sizeof out - 1 - outlen);
+ char *nl;
+
+ if (got > 0) {
+ outlen += got;
+ out[outlen] = 0;
+ while ((nl = strchr(out, '\n'))) {
+ *nl = 0;
+ if (!strcmp(out, "Verify result: verify-match (done)"))
+ matched = 1;
+ else if (!strncmp(out, "Verify result: verify-no-match", 30))
+ tries++;
+ else if (!strncmp(out, "Verify result: verify-retry", 27)
+ || !strncmp(out, "Verify result: verify-swipe", 27)
+ || !strncmp(out, "Verify result: verify-finger", 28)
+ || !strncmp(out, "Verify result: verify-remove", 28)) {
+ say(tty, "\nTouch the reader again, or type your password.\n");
+ reprompt(tty, prompt, used, &shown);
+ }
+ outlen -= nl + 1 - out;
+ memmove(out, nl + 1, outlen + 1);
+ }
+ if (outlen == sizeof out - 1)
+ outlen = 0;
+ continue;
+ }
+ if (got < 0 && errno == EINTR)
+ continue;
+
+ // The verify tool finished: a match needs both its last word and
+ // its exit status.
+ {
+ int status = 0;
+ close(verify_out);
+ verify_out = -1;
+ waitpid(verify, &status, 0);
+ verify = -1;
+ if (matched && WIFEXITED(status) && WEXITSTATUS(status) == 0) {
+ say(tty, "\n");
+ result = PAM_SUCCESS;
+ break;
+ }
+ matched = 0;
+ }
+ if (tries > 0 && tries < FINGER_TRIES) {
+ say(tty, "\nFingerprint not recognised. Try again, or type your password.\n");
+ reprompt(tty, prompt, used, &shown);
+ verify = start_verify(user, &verify_out);
+ if (verify < 0)
+ listening = 0;
+ } else {
+ if (tries >= FINGER_TRIES)
+ say(tty, "\nFingerprint not recognised. Type your password.\n");
+ else
+ say(tty, "\nThe fingerprint reader stopped. Type your password.\n");
+ reprompt(tty, prompt, used, &shown);
+ listening = 0;
+ }
+ }
+ }
+
+ explicit_bzero(line, sizeof line);
+ stop_verify(&verify, &verify_out);
+ tcsetattr(tty, TCSAFLUSH, &saved);
+ close(tty);
+ sigaction(SIGTSTP, &old_tstp, NULL);
+ sigaction(SIGQUIT, &old_quit, NULL);
+ sigaction(SIGINT, &old_int, NULL);
+
+ if (interrupted) {
+ // Ctrl+C ends sudo there and then, as at its own prompt. sudo keeps a
+ // handler of its own during authentication that would only note the
+ // signal, so it goes out with the default action, now that the
+ // terminal is back to normal.
+ struct sigaction dfl;
+ sigset_t only;
+
+ memset(&dfl, 0, sizeof dfl);
+ dfl.sa_handler = SIG_DFL;
+ sigemptyset(&dfl.sa_mask);
+ sigaction(interrupted, &dfl, NULL);
+ sigemptyset(&only);
+ sigaddset(&only, interrupted);
+ sigprocmask(SIG_UNBLOCK, &only, NULL);
+ raise(interrupted);
+ return PAM_ABORT;
+ }
+ return result;
+}
+
+PAM_EXTERN int pam_sm_setcred(pam_handle_t *pamh, int flags, int argc, const char **argv)
+{
+ (void)pamh;
+ (void)flags;
+ (void)argc;
+ (void)argv;
+ return PAM_IGNORE;
+}
diff --git a/packages/wildos-system-dialogs/src/verifier.cpp b/packages/wildos-system-dialogs/src/verifier.cpp
index 07b4d89..8d48f04 100644
--- a/packages/wildos-system-dialogs/src/verifier.cpp
+++ b/packages/wildos-system-dialogs/src/verifier.cpp
@@ -558,6 +558,9 @@ const QHash<QString, Wording> &wordings()
{QStringLiteral("org.wildos.appbridge.enable-32bit"), {"Wants to install Windows app support.", "Windows apps", "wildos-windows-app"}},
{QStringLiteral("org.wildos.usb.allow-device"), {"Wants to allow a USB device Wild OS blocked, until you unplug it."}},
+ {QStringLiteral("org.wildos.camera-mic.block"), {"Wants to turn off the camera or microphone for every app.", "Camera and microphone", "camera-web"}},
+ {QStringLiteral("org.wildos.camera-mic.unblock"), {"Wants to turn the camera or microphone back on for every app.", "Camera and microphone", "camera-web"}},
+ {QStringLiteral("org.wildos.camera-mic.release"), {"Wants to stop an app using the camera.", "Camera and microphone", "camera-web"}},
{QStringLiteral("org.wildos.update-checks"), {"Wants to change how this computer checks for updates.", "Updates", "wildos-updates"}},
{QStringLiteral("org.wildos.settings.update-policy"), {"Wants to change how Wild OS installs updates.", "Updates", "wildos-updates"}},
{QStringLiteral("org.wildos.settings.users"), {"Wants to change who can use this computer."}},
@@ -577,6 +580,7 @@ QString programPurpose(const QString &program)
{QStringLiteral("/usr/libexec/wildos/settings-locale"), QStringLiteral("Wants to set up a new language on this computer.")},
{QStringLiteral("/usr/libexec/wildos/settings-update-policy"), QStringLiteral("Wants to change how Wild OS installs updates.")},
{QStringLiteral("/usr/libexec/wildos/usb-allow"), QStringLiteral("Wants to allow a USB device Wild OS blocked, until you unplug it.")},
+ {QStringLiteral("/usr/libexec/wildos/camera-mic-block"), QStringLiteral("Wants to turn the camera or microphone on or off for every app.")},
{QStringLiteral("/usr/libexec/wildos/update-checks"), QStringLiteral("Wants to change how this computer checks for updates.")},
{QStringLiteral("/usr/libexec/wildos/appbridge-enable-32bit"), QStringLiteral("Wants to install Windows app support.")},
};
diff --git a/packages/wildos-taskmanager/debian/changelog b/packages/wildos-taskmanager/debian/changelog
index a3c6026..e52d1db 100644
--- a/packages/wildos-taskmanager/debian/changelog
+++ b/packages/wildos-taskmanager/debian/changelog
@@ -1,3 +1,17 @@
+wildos-taskmanager (0.1.2) trixie; urgency=medium
+
+ * End task closes an app that has stopped responding: an app still
+ running three seconds after being asked to quit is ended, and a
+ suspended one is woken so it can quit.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 18:44:54 +0000
+
+wildos-taskmanager (0.1.1) trixie; urgency=medium
+
+ * Windows mode's windows are listed as Windows mode.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 13:36:51 +0000
+
wildos-taskmanager (0.1.0) trixie; urgency=medium
* Initial release.
diff --git a/packages/wildos-taskmanager/src/processes.cpp b/packages/wildos-taskmanager/src/processes.cpp
index dd67996..1c43463 100644
--- a/packages/wildos-taskmanager/src/processes.cpp
+++ b/packages/wildos-taskmanager/src/processes.cpp
@@ -123,7 +123,7 @@ const QHash<QString, Known> &known()
{QStringLiteral("flatpak-session-helper"), {"Sandboxed app helper"}},
{QStringLiteral("flatpak-portal"), {"Sandboxed app helper"}},
{QStringLiteral("winmoded"), {"Windows mode"}},
- {QStringLiteral("xfreerdp3"), {"Windows mode"}},
+ {QStringLiteral("wildos-rdp"), {"Windows mode"}},
{QStringLiteral("(sd-pam)"), {"Session helper", false, true}},
{QStringLiteral("dconf-service"), {"App settings storage"}},
{QStringLiteral("drkonqi-coredump-processor"), {"Crash reporter"}},
@@ -214,6 +214,20 @@ QDBusMessage systemdUser(const QString &method, const QVariantList &args)
return QDBusConnection::sessionBus().call(message, QDBus::Block, 3000);
}
+// A process's start time from /proc, which tells a process apart from a
+// later one that was given the same id.
+QByteArray startedAt(qint64 pid)
+{
+ QFile file(QStringLiteral("/proc/%1/stat").arg(pid));
+ if (!file.open(QIODevice::ReadOnly)) {
+ return {};
+ }
+ const QByteArray stat = file.readAll();
+ // The name in brackets may hold spaces; the fields after it do not.
+ const QList<QByteArray> fields = stat.mid(stat.lastIndexOf(')') + 2).split(' ');
+ return fields.size() > 19 ? fields.at(19) : QByteArray();
+}
+
QString resultText(KSysGuard::ProcessController::Result result)
{
using R = KSysGuard::ProcessController::Result;
@@ -1038,6 +1052,33 @@ QString Processes::signal(const QList<qint64> &pids, int sig)
return resultText(m_controller->sendSignal(list, sig));
}
+// End task as on Windows: the app is asked to quit, and whatever is still
+// running three seconds later is killed, so an app that has stopped
+// responding still goes. A suspended process only acts on the request once
+// it runs again, so it is woken too.
+QString Processes::end(const QList<qint64> &pids)
+{
+ QList<QPair<qint64, QByteArray>> started;
+ for (qint64 pid : pids) {
+ started.append({pid, startedAt(pid)});
+ }
+ const QString error = signal(pids, SIGTERM);
+ if (!error.isEmpty()) {
+ return error;
+ }
+ signal(pids, SIGCONT);
+ QTimer::singleShot(3000, this, [this, started] {
+ QList<qint64> left;
+ for (const auto &[pid, at] : started) {
+ if (!at.isEmpty() && startedAt(pid) == at) {
+ left << pid;
+ }
+ }
+ signal(left, SIGKILL);
+ });
+ return {};
+}
+
QString Processes::endTask(const QString &key)
{
const Item *item = find(key);
@@ -1052,7 +1093,7 @@ QString Processes::endTask(const QString &key)
return {};
}
}
- return signal(item->pids, SIGTERM);
+ return end(item->pids);
}
QString Processes::endTree(const QString &key)
@@ -1061,7 +1102,7 @@ QString Processes::endTree(const QString &key)
if (!item || !item->canEnd || item->winMode) {
return endTask(key);
}
- return signal(treeOf(item->pids), SIGTERM);
+ return end(treeOf(item->pids));
}
QString Processes::setPriority(const QString &key, int nice)
diff --git a/packages/wildos-taskmanager/src/processes.h b/packages/wildos-taskmanager/src/processes.h
index 32d4134..2cc446f 100644
--- a/packages/wildos-taskmanager/src/processes.h
+++ b/packages/wildos-taskmanager/src/processes.h
@@ -200,6 +200,7 @@ private:
const Item *find(const QString &key) const;
QList<qint64> treeOf(const QList<qint64> &pids) const;
QString signal(const QList<qint64> &pids, int signal);
+ QString end(const QList<qint64> &pids);
KSysGuard::ProcessDataModel *m_source = nullptr;
KSysGuard::ProcessController *m_controller = nullptr;
diff --git a/packages/wildos-terminal/debian/changelog b/packages/wildos-terminal/debian/changelog
index 135b08f..9ca0653 100644
--- a/packages/wildos-terminal/debian/changelog
+++ b/packages/wildos-terminal/debian/changelog
@@ -1,3 +1,10 @@
+wildos-terminal (0.1.2) trixie; urgency=medium
+
+ * Pasting into a setting's box from its right-click menu is no
+ longer undone before you finish.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 08:54:22 +0000
+
wildos-terminal (0.1.1) trixie; urgency=medium
* No navy left: surfaces, glass, shadows and the logo tile use the
diff --git a/packages/wildos-terminal/debian/control b/packages/wildos-terminal/debian/control
index 21e95e0..bd80072 100644
--- a/packages/wildos-terminal/debian/control
+++ b/packages/wildos-terminal/debian/control
@@ -20,7 +20,7 @@ Depends:
${shlibs:Depends},
${misc:Depends},
qtermwidget-data,
- wildos-ui,
+ wildos-ui (>= 0.1.11),
qml6-module-qtcore,
qml6-module-qtquick,
qml6-module-qtquick-controls,
diff --git a/packages/wildos-terminal/qml/Field.qml b/packages/wildos-terminal/qml/Field.qml
index b71a3bf..0f62135 100644
--- a/packages/wildos-terminal/qml/Field.qml
+++ b/packages/wildos-terminal/qml/Field.qml
@@ -18,7 +18,9 @@ UI.TextField {
font.family: monospace ? Config.fontFamily : UI.Style.fontFamily
Accessible.name: placeholderText
- onValueChanged: if (!activeFocus) text = value
+ // The text menu holds focus while it is open; the box is still being
+ // edited then.
+ onValueChanged: if (!activeFocus && !textMenuOpen) text = value
Component.onCompleted: text = value
function commit() {
@@ -35,8 +37,12 @@ UI.TextField {
}
onTextEdited: settle.restart()
- onEditingFinished: commit()
- onActiveFocusChanged: if (!activeFocus) {
+ onEditingFinished: if (!textMenuOpen) commit()
+ onActiveFocusChanged: if (!activeFocus && !textMenuOpen) {
+ commit();
+ text = value;
+ }
+ onTextMenuFocusLeft: {
commit();
text = value;
}
diff --git a/packages/wildos-ui/CMakeLists.txt b/packages/wildos-ui/CMakeLists.txt
index 5ccada9..0d1fbfb 100644
--- a/packages/wildos-ui/CMakeLists.txt
+++ b/packages/wildos-ui/CMakeLists.txt
@@ -39,6 +39,8 @@ qt_add_qml_module(wildosui
src/system.cpp src/system.h
src/accessshortcuts.cpp src/accessshortcuts.h
src/historyswipe.cpp src/historyswipe.h
+ src/nopaste.cpp src/nopaste.h
+ src/secretcopy.cpp src/secretcopy.h
src/timeformat.cpp src/timeformat.h src/clockformat.h
)
diff --git a/packages/wildos-ui/debian/changelog b/packages/wildos-ui/debian/changelog
index 604e5ac..cbf9f40 100644
--- a/packages/wildos-ui/debian/changelog
+++ b/packages/wildos-ui/debian/changelog
@@ -1,3 +1,55 @@
+wildos-ui (0.1.14) trixie; urgency=medium
+
+ * The fingerprint keeps working after a restart again: asking for the
+ password after a restart or every so many hours is off unless you
+ switch it on in Advanced protection (Strict and Maximum switch it on).
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 16:00:00 +0000
+
+wildos-ui (0.1.13) trixie; urgency=medium
+
+ * A password shown as text and then copied goes on the clipboard
+ marked as a password, so the clipboard history leaves it out.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 14:56:10 +0000
+
+wildos-ui (0.1.12) trixie; urgency=medium
+
+ * NoPaste: a field with it takes only what is typed. Paste, Shift+Insert,
+ middle click and dropped text do nothing, and its right-click menu has
+ no Paste.
+ * Double-clicking the top or bottom edge of a Wild OS app's window
+ stretches it to the screen's full height, a side to its full width,
+ as on Windows. Double-click again to put it back.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 09:45:00 +0000
+
+wildos-ui (0.1.11) trixie; urgency=medium
+
+ * The right-click menu for text no longer ends what you were typing
+ in boxes that finish when you click away, such as renaming a file.
+ Closing the menu with Escape puts you back in the box instead of
+ nowhere, and clicking elsewhere finishes the box as before. An app
+ with its own undo, like Notes, can send Undo through the menu.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 08:54:22 +0000
+
+wildos-ui (0.1.10) trixie; urgency=medium
+
+ * Boxes that take several lines of text get the same right-click menu
+ as single line ones: Undo, Cut, Copy, Paste, Select all and Emoji.
+ The Menu key and Shift+F10 open it too.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 07:54:43 +0000
+
+wildos-ui (0.1.9) trixie; urgency=medium
+
+ * Spinners and busy bars stop animating while their window is hidden
+ or minimised, so background prompts no longer keep the processor
+ awake.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 14:40:00 +0000
+
wildos-ui (0.1.8) trixie; urgency=medium
* Two fingers swiped left or right on a touchpad go back and forward in
diff --git a/packages/wildos-ui/gallery/Gallery.qml b/packages/wildos-ui/gallery/Gallery.qml
index 6b1d28b..8969a4a 100644
--- a/packages/wildos-ui/gallery/Gallery.qml
+++ b/packages/wildos-ui/gallery/Gallery.qml
@@ -294,6 +294,11 @@ Window {
UI.SearchField { implicitWidth: 170; text: "blue"; previewFocus: true }
UI.SearchField { implicitWidth: 200; pill: true; placeholderText: "Search apps" }
}
+ States {
+ label: "Several lines"
+ UI.TextArea { implicitWidth: 240; placeholderText: "What went wrong?" }
+ UI.TextArea { implicitWidth: 240; text: "Right click for Cut, Copy and Paste"; previewFocus: true }
+ }
}
Section {
diff --git a/packages/wildos-ui/qml/ProgressBar.qml b/packages/wildos-ui/qml/ProgressBar.qml
index 1dd24a3..a63c0d9 100644
--- a/packages/wildos-ui/qml/ProgressBar.qml
+++ b/packages/wildos-ui/qml/ProgressBar.qml
@@ -42,7 +42,10 @@ T.ProgressBar {
color: Style.accent
NumberAnimation on x {
+ // Stops in hidden and minimised windows too (see Spinner).
running: control.indeterminate && control.visible
+ && control.Window.visibility !== Window.Hidden
+ && control.Window.visibility !== Window.Minimized
from: -sweep.width
to: control.width
duration: 1400
diff --git a/packages/wildos-ui/qml/ResizeHandles.qml b/packages/wildos-ui/qml/ResizeHandles.qml
index d9babff..091a8f4 100644
--- a/packages/wildos-ui/qml/ResizeHandles.qml
+++ b/packages/wildos-ui/qml/ResizeHandles.qml
@@ -16,12 +16,31 @@ Item {
anchors.fill: parent
z: 2000
+ // The last press on a grip. The first press hands the pointer to KWin
+ // for the resize, so no double-click event ever arrives; a second press
+ // on the same grip soon after is the double click.
+ property int lastEdges: 0
+ property double lastPress: 0
+
component Grip: MouseArea {
property int edges
enabled: handles.active
hoverEnabled: true
acceptedButtons: Qt.LeftButton
- onPressed: if (Window.window) Window.window.startSystemResize(edges)
+ onPressed: {
+ const now = Date.now();
+ // As on Windows: double-click the top or bottom edge for the
+ // screen's full height, a side for its width.
+ if (handles.lastEdges === edges && now - handles.lastPress <= Qt.styleHints.mouseDoubleClickInterval) {
+ handles.lastEdges = 0;
+ System.maximizeEdge(edges);
+ return;
+ }
+ handles.lastEdges = edges;
+ handles.lastPress = now;
+ if (Window.window)
+ Window.window.startSystemResize(edges);
+ }
}
Grip { edges: Qt.LeftEdge; x: 0; y: handles.corner; width: handles.edge; height: parent.height - 2 * handles.corner; cursorShape: Qt.SizeHorCursor }
diff --git a/packages/wildos-ui/qml/Spinner.qml b/packages/wildos-ui/qml/Spinner.qml
index 6e3aa46..04eb279 100644
--- a/packages/wildos-ui/qml/Spinner.qml
+++ b/packages/wildos-ui/qml/Spinner.qml
@@ -7,7 +7,11 @@ Item {
property real size: 16
property color color: Style.accent
- property bool running: visible
+ // A hidden or minimised window still counts its items as visible, so a
+ // spinner in a prompt that is not on screen would keep the animation
+ // timer waking its process about 75 times a second.
+ property bool running: visible && Window.visibility !== Window.Hidden
+ && Window.visibility !== Window.Minimized
implicitWidth: size
implicitHeight: size
diff --git a/packages/wildos-ui/qml/TextArea.qml b/packages/wildos-ui/qml/TextArea.qml
new file mode 100644
index 0000000..69ffb96
--- /dev/null
+++ b/packages/wildos-ui/qml/TextArea.qml
@@ -0,0 +1,78 @@
+import QtQuick
+import QtQuick.Templates as T
+
+// Several lines of input: TextField's sunken field (surface sunken, 1px
+// 0.10 edge, radius 8, 13px text) with room to wrap, and the same text
+// menu on a right click, the Menu key or Shift+F10. Put it in a ScrollView
+// for long text; a field that draws its own frame sets `background: null`.
+T.TextArea {
+ id: control
+
+ property bool error: false
+ property bool previewFocus: false
+ // Off for a field that brings its own right-click menu.
+ property bool textMenu: true
+ // The text menu holds focus while it is open. A field that ends its
+ // editing when focus leaves waits while this is true, and finishes on
+ // textMenuFocusLeft if a click elsewhere closed the menu.
+ readonly property bool textMenuOpen: menu.opened
+ signal textMenuFocusLeft()
+
+ readonly property bool editingNow: activeFocus || previewFocus
+
+ implicitWidth: 240
+ implicitHeight: Math.max(Style.controlHeight * 2, contentHeight + topPadding + bottomPadding)
+ leftPadding: 12
+ rightPadding: 12
+ topPadding: 9
+ bottomPadding: 9
+ wrapMode: TextEdit.Wrap
+ color: Style.inkField
+ selectionColor: Style.textSelection
+ selectedTextColor: Style.ink
+ placeholderTextColor: Style.inkPlaceholder
+ font.family: Style.fontFamily
+ font.letterSpacing: Style.tracking(Style.px(13))
+ font.pixelSize: Style.px(13)
+ opacity: enabled ? 1 : 0.5
+ Accessible.name: placeholderText
+
+ function openTextMenu(px: real, py: real): void {
+ menu.open(px, py);
+ }
+
+ TextMenu {
+ id: menu
+ enabled: control.textMenu && control.enabled
+ onFocusLeft: control.textMenuFocusLeft()
+ }
+
+ Keys.onPressed: event => {
+ if (textMenu && menu.isMenuKey(event)) {
+ menu.openAtCaret();
+ event.accepted = true;
+ }
+ }
+
+ background: Rectangle {
+ radius: Style.radiusSm
+ color: Style.surfaceSunken
+ border.width: 1
+ border.color: control.error ? Style.danger : control.editingNow ? Style.accentBorderStrong : Style.borderField
+ Behavior on border.color {
+ ColorAnimation { duration: Style.hoverDuration }
+ }
+ }
+
+ Label {
+ x: control.leftPadding
+ y: control.topPadding
+ width: control.width - control.leftPadding - control.rightPadding
+ visible: control.text.length === 0 && control.placeholderText.length > 0 && control.preeditText.length === 0
+ text: control.placeholderText
+ size: 13
+ wrapMode: Text.Wrap
+ elide: Text.ElideNone
+ color: Style.inkPlaceholder
+ }
+}
diff --git a/packages/wildos-ui/qml/TextField.qml b/packages/wildos-ui/qml/TextField.qml
index c2acaa0..be978cb 100644
--- a/packages/wildos-ui/qml/TextField.qml
+++ b/packages/wildos-ui/qml/TextField.qml
@@ -7,10 +7,9 @@ import QtQuick.Templates as T
// is the 42px, radius 10, 14px field of the account and installer forms
// (Account.dc). A password field gets a show and hide button with
// `revealable`. A right click, the Menu key or Shift+F10 opens the text
-// menu (MenusApps.dc "Text you're typing"): Undo, Cut, Copy, Paste, Select
-// all and Emoji, with their shortcuts. A single line field holds plain
-// text only, so Paste already pastes plain text and the board's "Paste as
-// plain text" has nothing to add here; spelling suggestions need a spell
+// menu (TextMenu.qml). A single line field holds plain text only, so
+// Paste already pastes plain text and the board's "Paste as plain
+// text" has nothing to add here; spelling suggestions need a spell
// checked text box, which this is not.
T.TextField {
id: control
@@ -24,6 +23,11 @@ T.TextField {
property alias trailing: trailingRow.data
// Off for a field that brings its own right-click menu.
property bool textMenu: true
+ // The text menu holds focus while it is open. A field that ends its
+ // editing when focus leaves waits while this is true, and finishes on
+ // textMenuFocusLeft if a click elsewhere closed the menu.
+ readonly property bool textMenuOpen: menu.opened
+ signal textMenuFocusLeft()
readonly property bool large: size === "large"
readonly property bool editingNow: activeFocus || previewFocus
@@ -45,56 +49,24 @@ T.TextField {
opacity: enabled ? 1 : 0.5
Accessible.name: placeholderText
- property Menu textMenuPopup: null
-
function openTextMenu(px: real, py: real): void {
- if (!textMenuPopup) {
- textMenuPopup = menuComponent.createObject(control);
- }
- const secret = echoMode === TextInput.Password || echoMode === TextInput.PasswordEchoOnEdit;
- const entries = [];
- if (!readOnly) {
- entries.push({ text: "Undo", icon: "undo", shortcut: "Ctrl+Z", enabled: canUndo, run: () => control.undo() },
- { separator: true });
- }
- if (!readOnly && !secret) {
- entries.push({ text: "Cut", icon: "menu-cut", shortcut: "Ctrl+X", enabled: selectedText.length > 0, run: () => control.cut() });
- }
- if (!secret) {
- entries.push({ text: "Copy", icon: "menu-copy", shortcut: "Ctrl+C", enabled: selectedText.length > 0, run: () => control.copy() });
- }
- if (!readOnly) {
- entries.push({ text: "Paste", icon: "menu-paste", shortcut: "Ctrl+V", enabled: canPaste, run: () => control.paste() });
- }
- if (entries.length > 0 && !entries[entries.length - 1].separator) {
- entries.push({ separator: true });
- }
- entries.push({ text: "Select all", icon: "select-all", shortcut: "Ctrl+A", enabled: length > 0, run: () => control.selectAll() });
- if (!readOnly && !secret && System.canRun("wildos-clipboard")) {
- entries.push({ text: "Emoji", icon: "emoji", shortcut: "Win+.", run: () => System.run("wildos-clipboard", ["--emoji"]) });
- }
- forceActiveFocus(Qt.PopupFocusReason);
- textMenuPopup.entries = entries;
- textMenuPopup.popup(control, px, py);
+ menu.open(px, py);
}
- Component {
- id: menuComponent
- Menu {
- minimumWidth: 236
- }
+ TextMenu {
+ id: menu
+ enabled: control.textMenu && control.enabled
+ onFocusLeft: control.textMenuFocusLeft()
}
- TapHandler {
- enabled: control.textMenu && control.enabled
- acceptedButtons: Qt.RightButton
- onTapped: eventPoint => control.openTextMenu(eventPoint.position.x, eventPoint.position.y)
+ // A password shown as text is copied marked as a secret.
+ SecretCopy {
+ enabled: control.revealable
}
Keys.onPressed: event => {
- if (textMenu && (event.key === Qt.Key_Menu || (event.key === Qt.Key_F10 && (event.modifiers & Qt.ShiftModifier)))) {
- const caret = cursorRectangle;
- openTextMenu(caret.x, caret.y + caret.height);
+ if (textMenu && menu.isMenuKey(event)) {
+ menu.openAtCaret();
event.accepted = true;
}
}
diff --git a/packages/wildos-ui/qml/TextMenu.qml b/packages/wildos-ui/qml/TextMenu.qml
new file mode 100644
index 0000000..84d0336
--- /dev/null
+++ b/packages/wildos-ui/qml/TextMenu.qml
@@ -0,0 +1,120 @@
+import QtQuick
+
+// The right-click menu for text you're typing (MenusApps.dc "Text you're
+// typing"): Undo, Cut, Copy, Paste, Select all and Emoji, with their
+// shortcuts. TextField and TextArea carry one; an app's own TextInput or
+// TextEdit gets the same menu by declaring `UI.TextMenu {}` inside it, and
+// calls open() from its Menu key handler. A handler rather than an item, so
+// it receives the clicks on the field it is declared in.
+TapHandler {
+ id: handler
+
+ readonly property Item field: parent
+
+ property Menu menu: null
+ // For an editor that keeps an undo of its own (Notes holds its line
+ // spacing pass off while stepping back); the field's undo otherwise.
+ property var undoAction: null
+ // The open menu holds the field's focus, so a field that ends its
+ // editing when focus leaves (a rename, an address bar) waits while
+ // this is true. A click elsewhere that closes the menu leaves focus
+ // there instead of handing it back, which focusLeft reports.
+ readonly property bool opened: menu !== null && menu.visible
+ signal focusLeft()
+
+ // A field with an enabled NoPaste in it (Wild OS's own password boxes).
+ function pasteBlocked(f): bool {
+ for (let i = 0; i < f.data.length; ++i) {
+ if (f.data[i] instanceof NoPaste && f.data[i].enabled) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ // A field with an enabled SecretCopy in it (a password shown as text).
+ function secretCopy(f) {
+ for (let i = 0; i < f.data.length; ++i) {
+ if (f.data[i] instanceof SecretCopy && f.data[i].enabled) {
+ return f.data[i];
+ }
+ }
+ return null;
+ }
+
+ function open(px: real, py: real): void {
+ const f = field;
+ if (!menu) {
+ menu = menuComponent.createObject(f);
+ }
+ // TextEdit and TextArea have no echoMode; undefined is never a password.
+ const secret = f.echoMode === TextInput.Password || f.echoMode === TextInput.PasswordEchoOnEdit;
+ const editable = !f.readOnly;
+ const marked = secretCopy(f);
+ const entries = [];
+ if (editable) {
+ entries.push({ text: "Undo", icon: "undo", shortcut: "Ctrl+Z", enabled: f.canUndo, run: () => handler.undoAction ? handler.undoAction() : f.undo() },
+ { separator: true });
+ }
+ if (editable && !secret) {
+ entries.push({ text: "Cut", icon: "menu-cut", shortcut: "Ctrl+X", enabled: f.selectedText.length > 0, run: () => marked ? marked.cut() : f.cut() });
+ }
+ if (!secret) {
+ entries.push({ text: "Copy", icon: "menu-copy", shortcut: "Ctrl+C", enabled: f.selectedText.length > 0, run: () => marked ? marked.copy() : f.copy() });
+ }
+ if (editable && !pasteBlocked(f)) {
+ entries.push({ text: "Paste", icon: "menu-paste", shortcut: "Ctrl+V", enabled: f.canPaste, run: () => f.paste() });
+ }
+ if (entries.length > 0 && !entries[entries.length - 1].separator) {
+ entries.push({ separator: true });
+ }
+ entries.push({ text: "Select all", icon: "select-all", shortcut: "Ctrl+A", enabled: f.length > 0, run: () => f.selectAll() });
+ if (editable && !secret && System.canRun("wildos-clipboard")) {
+ entries.push({ text: "Emoji", icon: "emoji", shortcut: "Win+.", run: () => System.run("wildos-clipboard", ["--emoji"]) });
+ }
+ f.forceActiveFocus(Qt.PopupFocusReason);
+ menu.entries = entries;
+ menu.popup(f, px, py);
+ }
+
+ // For the Menu key and Shift+F10, which open it at the caret.
+ function openAtCaret(): void {
+ const caret = field.cursorRectangle;
+ open(caret.x, caret.y + caret.height);
+ }
+
+ function isMenuKey(event) {
+ return event.key === Qt.Key_Menu || (event.key === Qt.Key_F10 && (event.modifiers & Qt.ShiftModifier));
+ }
+
+ enabled: field !== null && field.enabled
+ acceptedButtons: Qt.RightButton
+ onTapped: eventPoint => open(eventPoint.position.x, eventPoint.position.y)
+
+ property Connections closing: Connections {
+ target: handler.menu
+ function onClosed() {
+ const f = handler.field;
+ if (!f || f.activeFocus) {
+ return;
+ }
+ // Qt hands focus back to the window rather than the field when
+ // the field sits in a focus scope (a Loader, a dialog), which
+ // would leave a rename open with nowhere to type. Focus taken
+ // by something else means a click went elsewhere.
+ const w = f.Window.window;
+ const now = w ? w.activeFocusItem : null;
+ if (!now || now === w.contentItem) {
+ f.forceActiveFocus(Qt.PopupFocusReason);
+ } else {
+ handler.focusLeft();
+ }
+ }
+ }
+
+ property Component menuComponent: Component {
+ Menu {
+ minimumWidth: 236
+ }
+ }
+}
diff --git a/packages/wildos-ui/src/nopaste.cpp b/packages/wildos-ui/src/nopaste.cpp
new file mode 100644
index 0000000..df23c71
--- /dev/null
+++ b/packages/wildos-ui/src/nopaste.cpp
@@ -0,0 +1,49 @@
+#include "nopaste.h"
+
+#include <QKeyEvent>
+#include <QMouseEvent>
+
+NoPaste::NoPaste(QObject *parent)
+ : QObject(parent)
+{
+}
+
+void NoPaste::componentComplete()
+{
+ m_field = qobject_cast<QQuickItem *>(parent());
+ if (m_field) {
+ m_field->installEventFilter(this);
+ }
+}
+
+bool NoPaste::eventFilter(QObject *watched, QEvent *event)
+{
+ if (!m_enabled || watched != m_field) {
+ return false;
+ }
+ switch (event->type()) {
+ case QEvent::ShortcutOverride:
+ case QEvent::KeyPress: {
+ auto key = static_cast<QKeyEvent *>(event);
+ const bool shiftInsert = key->key() == Qt::Key_Insert && (key->modifiers() & Qt::ShiftModifier);
+ if (key->matches(QKeySequence::Paste) || shiftInsert) {
+ // Taken for the field so it reaches no shortcut either, then
+ // dropped.
+ event->accept();
+ return event->type() == QEvent::KeyPress;
+ }
+ return false;
+ }
+ case QEvent::MouseButtonPress:
+ case QEvent::MouseButtonRelease:
+ case QEvent::MouseButtonDblClick:
+ return static_cast<QMouseEvent *>(event)->button() == Qt::MiddleButton;
+ case QEvent::DragEnter:
+ case QEvent::DragMove:
+ case QEvent::Drop:
+ event->ignore();
+ return true;
+ default:
+ return false;
+ }
+}
diff --git a/packages/wildos-ui/src/nopaste.h b/packages/wildos-ui/src/nopaste.h
new file mode 100644
index 0000000..b52e7e3
--- /dev/null
+++ b/packages/wildos-ui/src/nopaste.h
@@ -0,0 +1,41 @@
+#pragma once
+
+#include <QObject>
+#include <QPointer>
+#include <QQmlEngine>
+#include <QQmlParserStatus>
+#include <QQuickItem>
+
+// Put inside a text field to stop anything being pasted into it: Ctrl+V,
+// Shift+Insert, a middle click (the selection) and text dropped on it. Wild
+// OS's own password boxes (signing in, unlocking, approving a change, the
+// disk password) take only what is typed, so a password never has to sit
+// on the clipboard where any app can read it.
+//
+// TextInput { echoMode: TextInput.Password; UI.NoPaste {} }
+//
+// TextMenu leaves Paste out of the right-click menu of a field that has one.
+class NoPaste : public QObject, public QQmlParserStatus
+{
+ Q_OBJECT
+ Q_INTERFACES(QQmlParserStatus)
+ QML_ELEMENT
+
+ Q_PROPERTY(bool enabled MEMBER m_enabled NOTIFY enabledChanged)
+
+public:
+ explicit NoPaste(QObject *parent = nullptr);
+
+ void classBegin() override { }
+ void componentComplete() override;
+
+Q_SIGNALS:
+ void enabledChanged();
+
+protected:
+ bool eventFilter(QObject *watched, QEvent *event) override;
+
+private:
+ QPointer<QQuickItem> m_field;
+ bool m_enabled = true;
+};
diff --git a/packages/wildos-ui/src/secretcopy.cpp b/packages/wildos-ui/src/secretcopy.cpp
new file mode 100644
index 0000000..1984b75
--- /dev/null
+++ b/packages/wildos-ui/src/secretcopy.cpp
@@ -0,0 +1,68 @@
+#include "secretcopy.h"
+
+#include <QClipboard>
+#include <QGuiApplication>
+#include <QKeyEvent>
+#include <QMimeData>
+
+SecretCopy::SecretCopy(QObject *parent)
+ : QObject(parent)
+{
+}
+
+void SecretCopy::componentComplete()
+{
+ m_field = qobject_cast<QQuickItem *>(parent());
+ if (m_field) {
+ m_field->installEventFilter(this);
+ }
+}
+
+void SecretCopy::copy()
+{
+ if (!m_field) {
+ return;
+ }
+ const QString text = m_field->property("selectedText").toString();
+ if (text.isEmpty()) {
+ return;
+ }
+ auto *mime = new QMimeData;
+ mime->setText(text);
+ mime->setData(QStringLiteral("x-kde-passwordManagerHint"), QByteArrayLiteral("secret"));
+ QGuiApplication::clipboard()->setMimeData(mime, QClipboard::Clipboard);
+}
+
+void SecretCopy::cut()
+{
+ if (!m_field || m_field->property("readOnly").toBool() || m_field->property("selectedText").toString().isEmpty()) {
+ return;
+ }
+ copy();
+ QMetaObject::invokeMethod(m_field, "remove", Q_ARG(int, m_field->property("selectionStart").toInt()),
+ Q_ARG(int, m_field->property("selectionEnd").toInt()));
+}
+
+bool SecretCopy::eventFilter(QObject *watched, QEvent *event)
+{
+ if (!m_enabled || watched != m_field || (event->type() != QEvent::ShortcutOverride && event->type() != QEvent::KeyPress)) {
+ return false;
+ }
+ auto key = static_cast<QKeyEvent *>(event);
+ const bool isCopy = key->matches(QKeySequence::Copy);
+ const bool isCut = key->matches(QKeySequence::Cut);
+ if (!isCopy && !isCut) {
+ return false;
+ }
+ // Taken for the field so it reaches no shortcut, then done here on the
+ // key press instead of by the field.
+ event->accept();
+ if (event->type() == QEvent::KeyPress) {
+ // A hidden password can't be copied at all, as before.
+ if (m_field->property("echoMode").toInt() == 0) {
+ isCut ? cut() : copy();
+ }
+ return true;
+ }
+ return false;
+}
diff --git a/packages/wildos-ui/src/secretcopy.h b/packages/wildos-ui/src/secretcopy.h
new file mode 100644
index 0000000..8c9e8a0
--- /dev/null
+++ b/packages/wildos-ui/src/secretcopy.h
@@ -0,0 +1,44 @@
+#pragma once
+
+#include <QObject>
+#include <QPointer>
+#include <QQmlEngine>
+#include <QQmlParserStatus>
+#include <QQuickItem>
+
+// Put inside a password field that can show what is typed (TextField's
+// revealable): whatever is copied or cut from it goes on the clipboard
+// marked x-kde-passwordManagerHint=secret, as password managers mark what
+// they copy. The clipboard history leaves it out, and with Advanced
+// protection's "Clipboard forgets passwords" on it is wiped after 60
+// seconds. Ctrl+C, Ctrl+X, Ctrl+Insert and Shift+Delete are taken here;
+// TextMenu calls copy() and cut() for its Copy and Cut.
+//
+// TextField { revealable: true; UI.SecretCopy {} }
+class SecretCopy : public QObject, public QQmlParserStatus
+{
+ Q_OBJECT
+ Q_INTERFACES(QQmlParserStatus)
+ QML_ELEMENT
+
+ Q_PROPERTY(bool enabled MEMBER m_enabled NOTIFY enabledChanged)
+
+public:
+ explicit SecretCopy(QObject *parent = nullptr);
+
+ void classBegin() override { }
+ void componentComplete() override;
+
+ Q_INVOKABLE void copy();
+ Q_INVOKABLE void cut();
+
+Q_SIGNALS:
+ void enabledChanged();
+
+protected:
+ bool eventFilter(QObject *watched, QEvent *event) override;
+
+private:
+ QPointer<QQuickItem> m_field;
+ bool m_enabled = true;
+};
diff --git a/packages/wildos-ui/src/system.cpp b/packages/wildos-ui/src/system.cpp
index 56520f4..12ddd31 100644
--- a/packages/wildos-ui/src/system.cpp
+++ b/packages/wildos-ui/src/system.cpp
@@ -47,6 +47,14 @@ void System::showWindowMenu() const
windowMenuService, QStringLiteral("/WindowMenu"), windowMenuService, QStringLiteral("ShowAtPointer")));
}
+void System::maximizeEdge(int edges) const
+{
+ QDBusMessage call = QDBusMessage::createMethodCall(windowMenuService, QStringLiteral("/WindowMenu"), windowMenuService,
+ QStringLiteral("MaximizeEdgeAtPointer"));
+ call << edges;
+ QDBusConnection::sessionBus().asyncCall(call);
+}
+
QString System::passwordHint(const QString &userName) const
{
// Asked only after a failed attempt, so a short wait is fine; the
@@ -94,3 +102,38 @@ bool System::fingerprintReader() const
const QDBusReply<QDBusObjectPath> device = QDBusConnection::systemBus().call(call, QDBus::Block, 3000);
return device.isValid();
}
+
+bool System::fingerprintAllowed(const QString &userName) const
+{
+ int hours = 0;
+ QFile store(QStringLiteral("/etc/wildos/advanced-protection"));
+ if (store.open(QIODevice::ReadOnly | QIODevice::Text)) {
+ while (!store.atEnd()) {
+ const QByteArray line = store.readLine().trimmed();
+ if (line.startsWith("fingerprint_hours=")) {
+ bool ok = false;
+ const int value = line.mid(18).toInt(&ok);
+ if (ok) {
+ hours = value;
+ }
+ }
+ }
+ }
+ if (hours <= 0) {
+ return true;
+ }
+ if (userName.isEmpty() || userName.contains(QLatin1Char('/')) || userName.startsWith(QLatin1Char('.'))) {
+ return false;
+ }
+ // Both in seconds since start-up, so changing the clock moves neither.
+ QFile stamp(QStringLiteral("/run/wildos/fingerprint/") + userName);
+ QFile uptime(QStringLiteral("/proc/uptime"));
+ if (!stamp.open(QIODevice::ReadOnly) || !uptime.open(QIODevice::ReadOnly)) {
+ return false;
+ }
+ bool okStamp = false;
+ bool okNow = false;
+ const qint64 typed = stamp.readAll().trimmed().toLongLong(&okStamp);
+ const qint64 now = static_cast<qint64>(uptime.readAll().split(' ').value(0).toDouble(&okNow));
+ return okStamp && okNow && now >= typed && now - typed < qint64(hours) * 3600;
+}
diff --git a/packages/wildos-ui/src/system.h b/packages/wildos-ui/src/system.h
index f198028..74ec8a7 100644
--- a/packages/wildos-ui/src/system.h
+++ b/packages/wildos-ui/src/system.h
@@ -22,6 +22,9 @@ public:
Q_INVOKABLE bool run(const QString &program, const QStringList &arguments = {}) const;
Q_INVOKABLE bool hasWindowMenu() const;
Q_INVOKABLE void showWindowMenu() const;
+ // A double click on a resize edge (Qt::Edges): KWin stretches the window
+ // to the screen's height or width, as on Windows.
+ Q_INVOKABLE void maximizeEdge(int edges) const;
// The hint a person set with their password (Welcome, Settings), shown
// by the sign-in and lock screens after a wrong attempt.
Q_INVOKABLE QString passwordHint(const QString &userName = {}) const;
@@ -30,4 +33,10 @@ public:
// reader whenever there is one, unless Sign-in options has "Sign in and
// unlock" off.
Q_INVOKABLE bool fingerprintReader() const;
+ // Whether a finger may be used for this account now. Advanced
+ // protection's "Fingerprint needs your password sometimes" turns it
+ // down after every restart until the password is typed once, and again
+ // once the chosen hours have passed since (wildos-desktop's
+ // fingerprint-turn decides the same way, from the same files).
+ Q_INVOKABLE bool fingerprintAllowed(const QString &userName) const;
};
diff --git a/packages/wildos-voice/debian/changelog b/packages/wildos-voice/debian/changelog
index 4f1a2b6..a2b8bf0 100644
--- a/packages/wildos-voice/debian/changelog
+++ b/packages/wildos-voice/debian/changelog
@@ -1,3 +1,10 @@
+wildos-voice (0.1.1) trixie; urgency=medium
+
+ * The empty search box stays open while its right-click menu is up,
+ so you can paste into it.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 08:54:22 +0000
+
wildos-voice (0.1.0) trixie; urgency=medium
* Initial release.
diff --git a/packages/wildos-voice/debian/control b/packages/wildos-voice/debian/control
index 6861c24..555a7e3 100644
--- a/packages/wildos-voice/debian/control
+++ b/packages/wildos-voice/debian/control
@@ -22,7 +22,7 @@ Architecture: any
Depends:
${shlibs:Depends},
${misc:Depends},
- wildos-ui (>= 0.1.6),
+ wildos-ui (>= 0.1.11),
qml6-module-qtcore,
qml6-module-qtquick,
qml6-module-qtquick-controls,
diff --git a/packages/wildos-voice/qml/Sidebar.qml b/packages/wildos-voice/qml/Sidebar.qml
index 8ae4f29..32a08d1 100644
--- a/packages/wildos-voice/qml/Sidebar.qml
+++ b/packages/wildos-voice/qml/Sidebar.qml
@@ -91,8 +91,16 @@ Rectangle {
placeholderText: qsTr("Search recordings")
onTextChanged: side.query = text
onEscapePressed: side.endSearch()
+ // An empty box closes when you leave it, but not for the text
+ // menu, which holds focus while it is up and may be there to
+ // paste.
onActiveFocusChanged: {
- if (!activeFocus && text.length === 0) {
+ if (!activeFocus && !textMenuOpen && text.length === 0) {
+ visible = false;
+ }
+ }
+ onTextMenuFocusLeft: {
+ if (text.length === 0) {
visible = false;
}
}
diff --git a/packages/wildos-welcome/debian/changelog b/packages/wildos-welcome/debian/changelog
index 4503cac..73517e2 100644
--- a/packages/wildos-welcome/debian/changelog
+++ b/packages/wildos-welcome/debian/changelog
@@ -1,3 +1,10 @@
+wildos-welcome (0.1.5) trixie; urgency=medium
+
+ * Password boxes in setup (your account and Wi-Fi) take only what is
+ typed: nothing can be pasted into them.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 10:30:00 +0000
+
wildos-welcome (0.1.4) trixie; urgency=medium
* Step 7 asks whether to use your Windows programs here, only when
diff --git a/packages/wildos-welcome/debian/control b/packages/wildos-welcome/debian/control
index a122440..fa75439 100644
--- a/packages/wildos-welcome/debian/control
+++ b/packages/wildos-welcome/debian/control
@@ -29,7 +29,7 @@ Depends:
qml6-module-qtquick-effects,
qml6-module-qtquick-window,
qt6-svg-plugins,
- wildos-ui,
+ wildos-ui (>= 0.1.12),
packagekit,
udisks2,
util-linux,
diff --git a/packages/wildos-welcome/qml/setup/AccountStep.qml b/packages/wildos-welcome/qml/setup/AccountStep.qml
index eb335a3..125dda1 100644
--- a/packages/wildos-welcome/qml/setup/AccountStep.qml
+++ b/packages/wildos-welcome/qml/setup/AccountStep.qml
@@ -169,6 +169,7 @@ StepPage {
Layout.fillWidth: true
size: "large"
revealable: true
+ UI.NoPaste {}
error: page.passwordShort && !activeFocus
Accessible.name: "Password"
onAccepted: page.submit()
@@ -190,6 +191,7 @@ StepPage {
Layout.fillWidth: true
size: "large"
revealable: true
+ UI.NoPaste {}
error: page.mismatch && !activeFocus
Accessible.name: "Type the password again"
onAccepted: page.submit()
diff --git a/packages/wildos-welcome/qml/setup/WifiStep.qml b/packages/wildos-welcome/qml/setup/WifiStep.qml
index b5ea2cf..09d93b8 100644
--- a/packages/wildos-welcome/qml/setup/WifiStep.qml
+++ b/packages/wildos-welcome/qml/setup/WifiStep.qml
@@ -226,6 +226,7 @@ StepPage {
Layout.fillWidth: true
implicitHeight: 40
revealable: true
+ UI.NoPaste {}
placeholderText: "Network password"
enabled: page.wifi.connectingSsid === ""
onAccepted: if (connectButton.enabled) connectButton.clicked()
@@ -360,6 +361,7 @@ StepPage {
id: hiddenPassword
Layout.fillWidth: true
revealable: true
+ UI.NoPaste {}
placeholderText: "Password, if it has one"
}
diff --git a/packages/wildos-winmode/debian/changelog b/packages/wildos-winmode/debian/changelog
index 5c69f52..e515bf5 100644
--- a/packages/wildos-winmode/debian/changelog
+++ b/packages/wildos-winmode/debian/changelog
@@ -1,3 +1,50 @@
+wildos-winmode (0.3.20) trixie; urgency=medium
+
+ * Windows can be activated with a licence on your Microsoft account,
+ through a second Windows account that is removed again afterwards.
+
+ -- Wild OS Developers <[email protected]> Sat, 14 Nov 2026 08:39:52 +0000
+
+wildos-winmode (0.3.19) trixie; urgency=medium
+
+ * Setup only offers every processor thread when the threads are
+ really off.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 16:30:00 +0000
+
+wildos-winmode (0.3.18) trixie; urgency=medium
+
+ * Windows apps can be uninstalled from Settings.
+ * The Windows desktop opens in Wild OS's own window; FreeRDP is no
+ longer installed.
+ * Setup shows real progress while it gets the parts Windows mode
+ runs on, instead of sitting at 1%.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 13:36:51 +0000
+
+wildos-winmode (0.3.17) trixie; urgency=medium
+
+ * Windows mode setup knows when the PC is offline: it says so straight
+ away, waits, and carries on by itself once the connection is back,
+ instead of showing Download paused while online and nothing while
+ offline. Other download problems say what happened.
+ * Start over goes back to the first step once setup has stopped,
+ instead of leaving an empty progress page.
+ * Installing the parts Windows mode runs on happens outside its own
+ service, so stopping the service part way can no longer leave software
+ installs (Settings' updates too) refusing to run. An install left
+ half done that way is finished first.
+
+ -- Wild OS Developers <[email protected]> Fri, 13 Nov 2026 11:00:00 +0000
+
+wildos-winmode (0.3.16) trixie; urgency=medium
+
+ * Setting up Windows mode while Settings checks for updates no longer
+ stops at the start with "connection dropped": it waits for the update
+ check, and a setup problem says what actually happened.
+
+ -- Wild OS Developers <[email protected]> Thu, 12 Nov 2026 21:59:00 +0000
+
wildos-winmode (0.3.15) trixie; urgency=medium
* Opening a Windows app while Windows is paused no longer starts a new
diff --git a/packages/wildos-winmode/debian/control b/packages/wildos-winmode/debian/control
index 3190712..7c51fc2 100644
--- a/packages/wildos-winmode/debian/control
+++ b/packages/wildos-winmode/debian/control
@@ -69,11 +69,10 @@ Depends:
ovmf,
swtpm,
swtpm-tools,
- freerdp3-x11,
wildos-rdp,
xorriso,
Description: Wild OS Windows mode, the virtual PC it runs on
- QEMU, libvirt and FreeRDP, which Windows mode needs only once it is set
+ QEMU, libvirt and wildos-rdp, which Windows mode needs only once it is set
up. Setting up Windows mode installs this package, so the Wild OS image
and PCs that never use Windows mode do without it.
diff --git a/packages/wildos-winmode/debian/wildos-winmode.install b/packages/wildos-winmode/debian/wildos-winmode.install
index f27d784..5ace3b8 100644
--- a/packages/wildos-winmode/debian/wildos-winmode.install
+++ b/packages/wildos-winmode/debian/wildos-winmode.install
@@ -1,3 +1,4 @@
+winmode/activation.py usr/lib/wildos/winmode/winmode
winmode/agent.py usr/lib/wildos/winmode/winmode
winmode/cli.py usr/lib/wildos/winmode/winmode
winmode/config.py usr/lib/wildos/winmode/winmode
diff --git a/packages/wildos-winmode/guest/api.txt b/packages/wildos-winmode/guest/api.txt
index 7d348e7..56f8a33 100644
--- a/packages/wildos-winmode/guest/api.txt
+++ b/packages/wildos-winmode/guest/api.txt
@@ -33,11 +33,14 @@ member [System]System.Diagnostics.Process.GetCurrentProcess :: class [System]Sys
member [System]System.Diagnostics.Process.GetProcesses :: class [System]System.Diagnostics.Process[]()
member [System]System.Diagnostics.Process.GetProcessesByName :: class [System]System.Diagnostics.Process[](string)
member [System]System.Diagnostics.Process.Start :: class [System]System.Diagnostics.Process(class [System]System.Diagnostics.ProcessStartInfo)
+member [System]System.Diagnostics.Process.WaitForExit :: instance bool(int32)
+member [System]System.Diagnostics.Process.get_ExitCode :: instance int32()
member [System]System.Diagnostics.Process.get_Id :: instance int32()
member [System]System.Diagnostics.Process.get_SessionId :: instance int32()
member [System]System.Diagnostics.Process.get_StartTime :: instance valuetype [mscorlib]System.DateTime()
member [System]System.Diagnostics.Process.set_PriorityClass :: instance void(valuetype [System]System.Diagnostics.ProcessPriorityClass)
member [System]System.Diagnostics.ProcessStartInfo..ctor :: instance void(string, string)
+member [System]System.Diagnostics.ProcessStartInfo.set_CreateNoWindow :: instance void(bool)
member [System]System.Diagnostics.ProcessStartInfo.set_UseShellExecute :: instance void(bool)
member [System]System.Diagnostics.ProcessStartInfo.set_WorkingDirectory :: instance void(string)
member [System]System.Text.RegularExpressions.Capture.get_Value :: instance string()
@@ -49,7 +52,10 @@ member [System]System.Text.RegularExpressions.Regex.IsMatch :: instance bool(str
member [System]System.Text.RegularExpressions.Regex.Match :: instance class [System]System.Text.RegularExpressions.Match(string)
member [mscorlib]Microsoft.Win32.Registry.CurrentUser :: class [mscorlib]Microsoft.Win32.RegistryKey
member [mscorlib]Microsoft.Win32.Registry.LocalMachine :: class [mscorlib]Microsoft.Win32.RegistryKey
+member [mscorlib]Microsoft.Win32.Registry.Users :: class [mscorlib]Microsoft.Win32.RegistryKey
member [mscorlib]Microsoft.Win32.RegistryKey.CreateSubKey :: instance class [mscorlib]Microsoft.Win32.RegistryKey(string)
+member [mscorlib]Microsoft.Win32.RegistryKey.Dispose :: instance void()
+member [mscorlib]Microsoft.Win32.RegistryKey.GetSubKeyNames :: instance string[]()
member [mscorlib]Microsoft.Win32.RegistryKey.GetValue :: instance object(string)
member [mscorlib]Microsoft.Win32.RegistryKey.OpenSubKey :: instance class [mscorlib]Microsoft.Win32.RegistryKey(string)
member [mscorlib]Microsoft.Win32.RegistryKey.SetValue :: instance void(string, object, valuetype [mscorlib]Microsoft.Win32.RegistryValueKind)
@@ -218,8 +224,10 @@ member [mscorlib]System.String.EndsWith :: instance bool(string, valuetype [msco
member [mscorlib]System.String.Equals :: bool(string, string, valuetype [mscorlib]System.StringComparison)
member [mscorlib]System.String.IndexOf :: instance int32(char)
member [mscorlib]System.String.IndexOf :: instance int32(char, int32)
+member [mscorlib]System.String.IndexOf :: instance int32(string, valuetype [mscorlib]System.StringComparison)
member [mscorlib]System.String.IndexOfAny :: instance int32(char[])
member [mscorlib]System.String.IsNullOrEmpty :: bool(string)
+member [mscorlib]System.String.Join :: string(string, string[], int32, int32)
member [mscorlib]System.String.LastIndexOf :: instance int32(char)
member [mscorlib]System.String.Replace :: instance string(char, char)
member [mscorlib]System.String.Split :: instance string[](char[])
@@ -346,6 +354,9 @@ member class [mscorlib]System.Collections.Generic.List`1<class WildOS.Guest.Warm
member class [mscorlib]System.Collections.Generic.List`1<class WildOS.Guest.WarmPool/Entry>.Remove :: instance bool(!0)
member class [mscorlib]System.Collections.Generic.List`1<class WildOS.Guest.WarmPool/Entry>.RemoveAll :: instance int32(class [mscorlib]System.Predicate`1<!0>)
member class [mscorlib]System.Collections.Generic.List`1<class WildOS.Guest.WarmPool/Entry>.ToArray :: instance !0[]()
+member class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]Microsoft.Win32.RegistryKey>..ctor :: instance void()
+member class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]Microsoft.Win32.RegistryKey>.Add :: instance void(!0)
+member class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]Microsoft.Win32.RegistryKey>.GetEnumerator :: instance valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<!0>()
member class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>..ctor :: instance void()
member class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>.Add :: instance void(!0)
member class [mscorlib]System.Collections.Generic.List`1<class [mscorlib]System.Action>.RemoveAt :: instance void(int32)
@@ -405,6 +416,8 @@ member valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<class Wi
member valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<class WildOS.Guest.SessionClient>.get_Current :: instance !0()
member valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<class WildOS.Guest.WarmPool/Entry>.MoveNext :: instance bool()
member valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<class WildOS.Guest.WarmPool/Entry>.get_Current :: instance !0()
+member valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<class [mscorlib]Microsoft.Win32.RegistryKey>.MoveNext :: instance bool()
+member valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<class [mscorlib]Microsoft.Win32.RegistryKey>.get_Current :: instance !0()
member valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<class [mscorlib]System.Collections.Generic.Dictionary`2<string,object>>.MoveNext :: instance bool()
member valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<class [mscorlib]System.Collections.Generic.Dictionary`2<string,object>>.get_Current :: instance !0()
member valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<object>.MoveNext :: instance bool()
diff --git a/packages/wildos-winmode/guest/tune.ps1 b/packages/wildos-winmode/guest/tune.ps1
index de125a3..0a77da0 100644
--- a/packages/wildos-winmode/guest/tune.ps1
+++ b/packages/wildos-winmode/guest/tune.ps1
@@ -17,7 +17,9 @@
param([switch]$Install)
-$version = '2'
+$version = '3'
+# The capabilities and features list below, which takes a while to check.
+$featuresVersion = '2'
$ErrorActionPreference = 'Continue'
$ProgressPreference = 'SilentlyContinue'
$dir = 'C:\Program Files\Wild OS'
@@ -95,7 +97,14 @@ Set-Policy 'HKLM:\SOFTWARE\Policies\Microsoft\Edge' 'BackgroundModeEnabled' 0
# and Windows 11 then allows only Windows Hello for it, so every sign-in
# from Wild OS stops at "The username or password is incorrect". Office and
# the Store can still sign in to a Microsoft account for themselves.
-Set-Policy 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' 'NoConnectedUser' 1
+# While Windows mode activates Windows with a licence on a Microsoft account
+# (Settings, issue 56), the policy is off for a second account made only for
+# that, and the host puts it back and removes the marker afterwards. A
+# marker older than a day was left behind and doesn't count.
+$activation = Get-Item "$stateDir\activation.json" -ErrorAction SilentlyContinue
+if (-not $activation -or $activation.LastWriteTime -lt (Get-Date).AddDays(-1)) {
+ Set-Policy 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' 'NoConnectedUser' 1
+}
Set-Policy 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\PasswordLess\Device' 'DevicePasswordLessBuildVersion' 0
# With 3.5 GB or more Windows gives every service its own process. Grouped
# as on smaller PCs they share one: 71 svchost processes became 38 and
@@ -197,8 +206,8 @@ $build = Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion'
$buildId = "$($build.CurrentBuild).$($build.UBR)"
# Listing capabilities and features takes a while, so only for a new
-# version of this script or a new Windows build.
-if ($state.features -ne "$version/$buildId") {
+# list ($featuresVersion) or a new Windows build.
+if ($state.features -ne "$featuresVersion/$buildId") {
foreach ($c in Get-WindowsCapability -Online -ErrorAction SilentlyContinue | Where-Object State -eq 'Installed') {
foreach ($want in 'App.StepsRecorder', 'Hello.Face', 'MathRecognizer', 'Media.WindowsMediaPlayer', 'Microsoft.Windows.WordPad',
'Microsoft.Wallpapers.Extended', 'OneCoreUAP.OneSync', 'Microsoft.Windows.PowerShell.ISE', 'App.Support.QuickAssist') {
@@ -215,7 +224,7 @@ if ($state.features -ne "$version/$buildId") {
$changes.Add("feature $f")
}
}
- $state.features = "$version/$buildId"
+ $state.features = "$featuresVersion/$buildId"
}
# Each update keeps the components it replaced. Cleared once per build, at
diff --git a/packages/wildos-winmode/guest/wild-guest/Service.cs b/packages/wildos-winmode/guest/wild-guest/Service.cs
index c52ae32..8e3f6b4 100644
--- a/packages/wildos-winmode/guest/wild-guest/Service.cs
+++ b/packages/wildos-winmode/guest/wild-guest/Service.cs
@@ -248,6 +248,15 @@ namespace WildOS.Guest
Reply(id, Message("icon", "path", Json.Str(m, "path"), "icon", ico == null ? null : Convert.ToBase64String(ico)));
});
break;
+ case "uninstall":
+ ThreadPool.QueueUserWorkItem(delegate
+ {
+ Dictionary<string, object> answer;
+ try { answer = Uninstall.Run(Json.Str(m, "path"), account); }
+ catch (Exception e) { answer = Message("error", "error", e.Message); }
+ Reply(id, answer);
+ });
+ break;
case "theme":
try { Theme.Save(m); } catch (Exception e) { Log.Write("theme: " + e.Message); }
int sent = 0;
diff --git a/packages/wildos-winmode/guest/wild-guest/Uninstall.cs b/packages/wildos-winmode/guest/wild-guest/Uninstall.cs
new file mode 100644
index 0000000..0c5067b
--- /dev/null
+++ b/packages/wildos-winmode/guest/wild-guest/Uninstall.cs
@@ -0,0 +1,260 @@
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Globalization;
+using System.IO;
+using Microsoft.Win32;
+
+namespace WildOS.Guest
+{
+ // Uninstalling a Windows app from Wild OS. A program from the Store is
+ // removed here and now; any other program is removed by its own
+ // uninstaller, the entry Windows' Installed apps lists for it, which Wild
+ // OS opens in a window so the person sees it through.
+ static class Uninstall
+ {
+ const string Key = @"Software\Microsoft\Windows\CurrentVersion\Uninstall";
+ const string WowKey = @"Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall";
+
+ public static Dictionary<string, object> Run(string path, string account)
+ {
+ var result = new Dictionary<string, object>();
+ string aumid = Packages.AumidFor(path ?? "");
+ if (aumid != null)
+ {
+ result["type"] = "uninstalled";
+ string error = RemovePackage(Packages.Family(aumid));
+ if (error != null)
+ {
+ result["type"] = "error";
+ result["error"] = error;
+ }
+ return result;
+ }
+ var entry = Find(path, account);
+ if (entry == null)
+ {
+ result["type"] = "error";
+ result["error"] = "no-uninstaller";
+ return result;
+ }
+ result["type"] = "uninstaller";
+ result["name"] = entry.Name;
+ // Split here, where the quoting rules are Windows' own: many
+ // uninstallers leave a path with spaces unquoted.
+ string program = Program(entry.Command);
+ int at = entry.Command.IndexOf(program, StringComparison.OrdinalIgnoreCase);
+ string rest = at < 0 ? "" : entry.Command.Substring(at + program.Length).TrimStart(new[] { '"' }).Trim();
+ result["program"] = program;
+ result["arguments"] = rest;
+ return result;
+ }
+
+ // Removed for every account, as the service runs as LocalSystem; the
+ // Windows mode account is the only one that uses it. The family
+ // comes from Packages' own pattern, so it is never more than letters,
+ // digits, dots, dashes and one underscore.
+ static string RemovePackage(string family)
+ {
+ if (string.IsNullOrEmpty(family)) return "not-a-package";
+ string script = "$ErrorActionPreference='Stop'; " +
+ "$p = @(Get-AppxPackage -AllUsers | Where-Object { $_.PackageFamilyName -eq '" + family + "' -and -not $_.IsFramework }); " +
+ "if ($p.Count -eq 0) { exit 3 }; " +
+ "foreach ($x in $p) { Remove-AppxPackage -Package $x.PackageFullName -AllUsers }; exit 0";
+ var start = new ProcessStartInfo("powershell.exe", "-NoProfile -NonInteractive -ExecutionPolicy Bypass -Command \"" + script + "\"");
+ start.UseShellExecute = false;
+ start.CreateNoWindow = true;
+ var p = Process.Start(start);
+ if (p == null) return "powershell-failed";
+ if (!p.WaitForExit(180000)) return "timeout";
+ if (p.ExitCode == 3) return "not-installed";
+ return p.ExitCode == 0 ? null : "remove-failed";
+ }
+
+ class Entry
+ {
+ public string Name;
+ public string Command;
+ public int Score;
+ }
+
+ static Entry Find(string target, string account)
+ {
+ if (string.IsNullOrEmpty(target)) return null;
+ string program = Unquote(target);
+ string folder = Path.GetDirectoryName(program) ?? "";
+ Entry best = null;
+ bool tied = false;
+ var roots = new List<RegistryKey> { Registry.LocalMachine };
+ RegistryKey user = AccountHive(account);
+ if (user != null) roots.Add(user);
+ foreach (RegistryKey root in roots)
+ {
+ foreach (string keyPath in new[] { Key, WowKey })
+ {
+ RegistryKey list;
+ try { list = root.OpenSubKey(keyPath); }
+ catch (Exception) { continue; }
+ if (list == null) continue;
+ using (list)
+ {
+ foreach (string name in list.GetSubKeyNames())
+ {
+ Entry e = Read(list, name, program, folder);
+ if (e == null) continue;
+ if (best == null || e.Score > best.Score) { best = e; tied = false; }
+ else if (e.Score == best.Score && e.Command != best.Command) tied = true;
+ }
+ }
+ }
+ }
+ if (user != null) user.Dispose();
+ return tied ? null : best;
+ }
+
+ static Entry Read(RegistryKey list, string name, string program, string folder)
+ {
+ RegistryKey k;
+ try { k = list.OpenSubKey(name); }
+ catch (Exception) { return null; }
+ if (k == null) return null;
+ using (k)
+ {
+ string uninstall = k.GetValue("UninstallString") as string;
+ if (string.IsNullOrEmpty(uninstall) || Number(k.GetValue("SystemComponent")) == 1 || k.GetValue("ParentKeyName") != null) return null;
+
+ int score = 0;
+ string icon = k.GetValue("DisplayIcon") as string;
+ if (!string.IsNullOrEmpty(icon))
+ {
+ string iconPath = Unquote(icon);
+ int comma = iconPath.LastIndexOf(',');
+ if (comma > 2 && !File.Exists(iconPath)) iconPath = iconPath.Substring(0, comma);
+ if (string.Equals(iconPath, program, StringComparison.OrdinalIgnoreCase)) score = 300;
+ }
+ string location = k.GetValue("InstallLocation") as string;
+ if (score == 0 && Owns(location, folder)) score = 200 + Unquote(location).Length;
+ // An uninstaller beside the program is its own. One that is
+ // the program itself may be a launcher removing something
+ // else it installed (Steam removing a game), so it ranks
+ // below, and a tie between two entries is never guessed.
+ string remover = Program(uninstall);
+ if (score == 0 && Owns(Path.GetDirectoryName(remover), folder))
+ {
+ score = string.Equals(remover, program, StringComparison.OrdinalIgnoreCase) ? 50 : 100;
+ }
+ if (score == 0) return null;
+
+ // An MSI entry's UninstallString often opens Change (/I), so
+ // the product code is uninstalled directly instead.
+ string command = uninstall;
+ if (Number(k.GetValue("WindowsInstaller")) == 1 && name.StartsWith("{", StringComparison.Ordinal) && name.EndsWith("}", StringComparison.Ordinal))
+ {
+ command = "MsiExec.exe /X" + name;
+ }
+ return new Entry { Name = (k.GetValue("DisplayName") as string) ?? name, Command = command, Score = score };
+ }
+ }
+
+ // Whether an app's own folder holds the program. Folders every app
+ // shares (Program Files, AppData, Windows) never count, or every
+ // program in them would match.
+ static bool Owns(string owner, string folder)
+ {
+ if (string.IsNullOrEmpty(owner) || string.IsNullOrEmpty(folder)) return false;
+ string o = Unquote(owner).TrimEnd(new[] { '\\' });
+ if (o.Length < 4 || Shared(o)) return false;
+ return string.Equals(folder, o, StringComparison.OrdinalIgnoreCase)
+ || folder.StartsWith(o + "\\", StringComparison.OrdinalIgnoreCase);
+ }
+
+ static bool Shared(string folder)
+ {
+ var shared = new List<string>
+ {
+ Environment.GetEnvironmentVariable("ProgramFiles"),
+ Environment.GetEnvironmentVariable("ProgramFiles(x86)"),
+ Environment.GetEnvironmentVariable("ProgramData"),
+ Environment.GetEnvironmentVariable("CommonProgramFiles"),
+ Environment.GetEnvironmentVariable("CommonProgramFiles(x86)"),
+ Environment.GetEnvironmentVariable("SystemRoot"),
+ };
+ foreach (string s in shared)
+ {
+ if (!string.IsNullOrEmpty(s) && string.Equals(folder, s.TrimEnd(new[] { '\\' }), StringComparison.OrdinalIgnoreCase)) return true;
+ }
+ // Everything an account's own installs share: its profile,
+ // AppData and the folders under it that hold many apps.
+ string[] parts = folder.Split(new[] { '\\' });
+ int users = -1;
+ for (int i = 0; i < parts.Length; i++)
+ {
+ if (string.Equals(parts[i], "Users", StringComparison.OrdinalIgnoreCase)) { users = i; break; }
+ }
+ if (users < 0) return false;
+ int below = parts.Length - users - 2;
+ if (below <= 0) return true;
+ string rest = string.Join("\\", parts, users + 2, below).ToLowerInvariant();
+ return rest == "appdata" || rest == "appdata\\local" || rest == "appdata\\roaming" || rest == "appdata\\locallow"
+ || rest == "appdata\\local\\programs" || rest == "appdata\\local\\microsoft" || rest == "appdata\\roaming\\microsoft";
+ }
+
+ // The account's own registry, where programs installed for it alone
+ // list themselves. It is loaded while the account is signed in,
+ // which Windows mode's session is whenever an app is open.
+ static RegistryKey AccountHive(string account)
+ {
+ if (string.IsNullOrEmpty(account)) return null;
+ try
+ {
+ using (var profiles = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList"))
+ {
+ if (profiles == null) return null;
+ foreach (string sid in profiles.GetSubKeyNames())
+ {
+ using (var p = profiles.OpenSubKey(sid))
+ {
+ string home = p == null ? null : p.GetValue("ProfileImagePath") as string;
+ if (home != null && home.EndsWith("\\" + account, StringComparison.OrdinalIgnoreCase))
+ {
+ return Registry.Users.OpenSubKey(sid);
+ }
+ }
+ }
+ }
+ }
+ catch (Exception e)
+ {
+ Log.Write("uninstall: " + e.Message);
+ }
+ return null;
+ }
+
+ // The program a command line starts: quoted, or up to the first
+ // ".exe" for the unquoted ones with spaces in their folder.
+ static string Program(string command)
+ {
+ string c = command.Trim();
+ if (c.StartsWith("\"", StringComparison.Ordinal))
+ {
+ int end = c.IndexOf('"', 1);
+ return end > 1 ? c.Substring(1, end - 1) : c.Trim(new[] { '"' });
+ }
+ string lower = c.ToLowerInvariant();
+ int exe = lower.IndexOf(".exe", StringComparison.Ordinal);
+ return exe > 0 ? c.Substring(0, exe + 4) : c;
+ }
+
+ static string Unquote(string value)
+ {
+ return (value ?? "").Trim().Trim(new[] { '"' });
+ }
+
+ static long Number(object value)
+ {
+ if (value == null) return 0;
+ try { return Convert.ToInt64(value, CultureInfo.InvariantCulture); }
+ catch (Exception) { return 0; }
+ }
+ }
+}
diff --git a/packages/wildos-winmode/setup/qml/Main.qml b/packages/wildos-winmode/setup/qml/Main.qml
index a313776..a4ca6bc 100644
--- a/packages/wildos-winmode/setup/qml/Main.qml
+++ b/packages/wildos-winmode/setup/qml/Main.qml
@@ -18,6 +18,9 @@ UI.AppWindow {
property string page: "check"
property string problem
property string startError
+ // The setup page has seen a setup under way, so the service saying
+ // there is none means Start over has finished.
+ property bool following: false
readonly property int step: page === "check" ? 1 : page === "options" ? 2 : page === "setup" ? 3 : 4
@@ -56,11 +59,26 @@ UI.AppWindow {
} else if (s === "ready" && window.page === "check") {
window.page = "ready";
}
+ if (window.page === "setup" && (s === "setup" || s === "failed")) {
+ window.following = true;
+ } else if (window.page === "setup" && window.following && (s === "none" || s === "")) {
+ // Start over removed what setup had made: begin again from
+ // the checks, which run afresh.
+ window.following = false;
+ window.problem = "";
+ window.startError = "";
+ window.page = "check";
+ Setup.recheck();
+ return;
+ }
const kind = (Setup.status.problem || {}).kind || "";
if (s === "failed" && window.page === "setup") {
window.problem = "failed";
} else if ((kind === "download" || kind === "space") && window.page === "setup") {
window.problem = kind;
+ } else if ((window.problem === "download" || window.problem === "space") && kind !== window.problem) {
+ // Back online, or the space was freed: setup has carried on.
+ window.problem = "";
}
}
}
@@ -145,6 +163,7 @@ UI.AppWindow {
solid: true
kind: window.problem
received: (Setup.status.problem || {}).received || 0
+ offline: (Setup.status.problem || {}).offline === true
failure: window.startError.length > 0 ? window.startError : ((Setup.status.problem || {}).text || "")
detail: window.startError.length > 0 ? "" : ((Setup.status.problem || {}).detail || "")
onDismissed: problemPopup.close()
diff --git a/packages/wildos-winmode/setup/qml/ProblemCard.qml b/packages/wildos-winmode/setup/qml/ProblemCard.qml
index 54496a6..845e13b 100644
--- a/packages/wildos-winmode/setup/qml/ProblemCard.qml
+++ b/packages/wildos-winmode/setup/qml/ProblemCard.qml
@@ -14,6 +14,9 @@ Item {
// virtualisation, unsupported, noaccess, space, download or failed
property string kind
property real received: 0
+ // A download problem because this PC is offline (board 9.7's card), as
+ // opposed to one the server or the package system caused.
+ property bool offline: false
property string failure
// An unexpected error's own words, for reporting it.
property string detail
@@ -88,7 +91,7 @@ Item {
case "unsupported": return "This PC can't run Windows mode";
case "noaccess": return "Windows mode needs the PC's own screen";
case "space": return "Not enough space";
- case "download": return "Download paused";
+ case "download": return card.offline ? "Download paused" : "Download stopped";
default: return "Setup couldn't finish";
}
}
@@ -112,9 +115,17 @@ Item {
case "space":
return "Windows mode needs about " + Setup.needLabel + " and this PC has " + Setup.freeLabel + " free. Clearing the Downloads folder and emptying the Recycle Bin usually frees enough.";
case "download":
- return card.received > 0
- ? "The connection dropped at " + card.gb(card.received) + ". Nothing is lost; setup carries on from where it stopped as soon as you're back online."
- : "The connection dropped. Nothing is lost; setup carries on from where it stopped as soon as you're back online.";
+ // Offline: setup waits and carries on by itself once
+ // NetworkManager says the PC is back online. Anything
+ // else (updates holding the package lock, Microsoft
+ // refusing the download) says what actually happened
+ // and waits for Try again.
+ if (card.offline) {
+ return card.received > 0
+ ? "The connection dropped at " + card.gb(card.received) + ". Nothing is lost; setup carries on from where it stopped as soon as you're back online."
+ : "This PC is offline. Nothing is lost; setup carries on from where it stopped as soon as you're back online.";
+ }
+ return (card.failure.length > 0 ? card.failure : "The download stopped.") + " Nothing is lost; Try again carries on from where it stopped.";
default:
return (card.failure.length > 0 ? card.failure + " " : "") + "Nothing was left half installed.";
}
diff --git a/packages/wildos-winmode/setup/qml/ProblemsBoard.qml b/packages/wildos-winmode/setup/qml/ProblemsBoard.qml
index 97a6649..eacfad6 100644
--- a/packages/wildos-winmode/setup/qml/ProblemsBoard.qml
+++ b/packages/wildos-winmode/setup/qml/ProblemsBoard.qml
@@ -60,6 +60,7 @@ Rectangle {
ProblemCard {
kind: "download"
+ offline: true
received: 3.8e9
}
}
diff --git a/packages/wildos-winmode/setup/qml/StepSetup.qml b/packages/wildos-winmode/setup/qml/StepSetup.qml
index 9655dc7..59a42fe 100644
--- a/packages/wildos-winmode/setup/qml/StepSetup.qml
+++ b/packages/wildos-winmode/setup/qml/StepSetup.qml
@@ -16,6 +16,12 @@ Page {
readonly property var problem: status.problem || ({})
readonly property bool paused: status.paused === true
readonly property bool waitingForWindows: problem.kind === "iso" || problem.kind === "iso-refused"
+ // Setup is waiting for the internet and carries on by itself.
+ readonly property bool offline: problem.kind === "download" && problem.offline === true
+ // Start over pressed: the service is stopping setup and clearing up,
+ // which can take a little while; the window then goes back to the checks.
+ property bool stopping: false
+ onVisibleChanged: if (!visible) stopping = false
readonly property var active: {
for (const s of stages) {
if (s.state === "active") {
@@ -52,13 +58,14 @@ Page {
UI.Label {
Layout.fillWidth: true
- text: page.paused ? "Paused" : page.waitingForWindows ? "Waiting for Windows" : page.active ? page.activeLabel(page.active.id) : "Getting ready"
+ text: page.stopping ? "Stopping setup" : page.paused ? "Paused" : page.offline ? "Waiting for the internet"
+ : page.waitingForWindows ? "Waiting for Windows" : page.active ? page.activeLabel(page.active.id) : "Getting ready"
size: 13
font.weight: UI.Style.weightSemiBold
}
UI.Label {
- text: page.paused || page.waitingForWindows ? "" : (page.status.left || "")
+ text: page.stopping || page.paused || page.offline || page.waitingForWindows ? "" : (page.status.left || "")
size: 13
color: UI.Style.inkMuted
}
@@ -147,7 +154,14 @@ Page {
}
Banner {
- visible: !page.waitingForWindows && !page.status.notice
+ visible: page.offline && !page.stopping
+ iconName: "wifi-off"
+ title: "Waiting for the internet"
+ text: "This PC is offline. Setup carries on from where it stopped as soon as you're back online, with nothing to press."
+ }
+
+ Banner {
+ visible: !page.waitingForWindows && !page.status.notice && !page.offline
iconName: "monitor"
title: "Carry on while it works"
text: "Close this window and Wild OS tells you when it's ready. Setup only uses spare capacity."
@@ -171,6 +185,7 @@ Page {
text: "Start over"
onClicked: {
startOverDialog.close();
+ page.stopping = true;
Setup.cancel();
}
},
@@ -184,12 +199,12 @@ Page {
buttons: [
UI.Button {
text: "Start over"
- visible: page.status.state === "setup" || page.status.state === "failed"
+ visible: !page.stopping && (page.status.state === "setup" || page.status.state === "failed")
onClicked: startOverDialog.open()
},
UI.Button {
text: page.paused ? "Resume" : "Pause"
- visible: page.status.state === "setup" && page.problem.kind !== "download" && !page.waitingForWindows
+ visible: !page.stopping && page.status.state === "setup" && (page.problem.kind !== "download" || page.offline) && !page.waitingForWindows
onClicked: page.paused ? Setup.resume() : Setup.pause()
},
UI.Button {
diff --git a/packages/wildos-winmode/setup/src/setupapp.cpp b/packages/wildos-winmode/setup/src/setupapp.cpp
index 617e347..0bbf75f 100644
--- a/packages/wildos-winmode/setup/src/setupapp.cpp
+++ b/packages/wildos-winmode/setup/src/setupapp.cpp
@@ -108,7 +108,7 @@ void SetupApp::loadPreview()
{QStringLiteral("percent"), paused ? 15 : 46},
{QStringLiteral("left"), QStringLiteral("About 14 minutes left")},
{QStringLiteral("paused"), paused},
- {QStringLiteral("problem"), paused ? QVariantMap{{QStringLiteral("kind"), QStringLiteral("download")}, {QStringLiteral("received"), 3.8e9}} : QVariantMap()},
+ {QStringLiteral("problem"), paused ? QVariantMap{{QStringLiteral("kind"), QStringLiteral("download")}, {QStringLiteral("offline"), true}, {QStringLiteral("received"), 3.8e9}} : QVariantMap()},
{QStringLiteral("stages"), QVariantList{
stage(QStringLiteral("media"), QStringLiteral("Download Windows 11 from Microsoft"), QStringLiteral("6.1 GB, checked against Microsoft's signature"),
paused ? QStringLiteral("active") : QStringLiteral("done"), paused ? 62 : 100),
@@ -419,10 +419,18 @@ QByteArray readSmt(const char *name)
QFile file(QStringLiteral("/sys/devices/system/cpu/smt/") + QLatin1String(name));
return file.open(QIODevice::ReadOnly) ? file.readAll().trimmed() : QByteArray();
}
+
+QByteArray readEtc(const char *name)
+{
+ QFile file(QStringLiteral("/etc/wildos/") + QLatin1String(name));
+ return file.open(QIODevice::ReadOnly) ? file.readAll().trimmed() : QByteArray();
+}
}
-// Offered only on a processor with two threads per core, while it is off, and
-// not at Strict or Maximum protection, which keep it off.
+// Offered only on a processor with two threads per core whose second threads
+// are off and not already chosen on, and not while extra processor protection
+// (or Strict or Maximum, which include it) keeps them off. Most processors
+// run every thread by default, so this rarely shows.
bool SetupApp::hyperThreadingAvailable() const
{
// The boards' made-up PC has the row.
@@ -430,15 +438,15 @@ bool SetupApp::hyperThreadingAvailable() const
return true;
}
const QByteArray control = readSmt("control");
- QFile levelFile(QStringLiteral("/etc/wildos/protection-level"));
- const QByteArray level = levelFile.open(QIODevice::ReadOnly) ? levelFile.readAll().trimmed() : QByteArray();
+ const QByteArray level = readEtc("protection-level");
return QFile::exists(cpuThreadsHelper) && !control.isEmpty() && control != "notsupported" && control != "notimplemented"
- && !QFile::exists(QStringLiteral("/etc/wildos/cpu-threads")) && level != "strict" && level != "maximum";
+ && readSmt("active") != "1" && readEtc("cpu-threads") != "on" && readEtc("cpu-protection") != "extra"
+ && level != "strict" && level != "maximum";
}
bool SetupApp::hyperThreadingNeedsRestart() const
{
- return QFile::exists(QStringLiteral("/etc/wildos/cpu-threads")) && readSmt("active") != "1";
+ return readEtc("cpu-threads") == "on" && readSmt("active") != "1";
}
QString SetupApp::setupRequest(bool background) const
diff --git a/packages/wildos-winmode/tests/test_recovery.py b/packages/wildos-winmode/tests/test_recovery.py
index a58838b..c1d8413 100644
--- a/packages/wildos-winmode/tests/test_recovery.py
+++ b/packages/wildos-winmode/tests/test_recovery.py
@@ -2,14 +2,33 @@
fails is tried again, a second failure clears what it made and goes back a
stage, and two more failures stop with the problem shown as before."""
+import contextlib
import os
import shutil
import tempfile
+import threading
+import time
import unittest
from winmode import setup
+def online_as(answers):
+ """setup.online() answering from a list (the last answer repeats), with
+ the offline wait looking again at once."""
+ answers = list(answers)
+ saved = setup.online, setup.OFFLINE_POLL
+
+ def online():
+ return answers.pop(0) if len(answers) > 1 else answers[0]
+ setup.online, setup.OFFLINE_POLL = online, 0.01
+ try:
+ yield
+ finally:
+ setup.online, setup.OFFLINE_POLL = saved
+
+
class Svc:
def __init__(self, rec=None):
self.cfg = {"domain": "wildos-windows", "account": "wild", "share_root": "/nonexistent-share"}
@@ -162,12 +181,68 @@ class Flow(unittest.TestCase):
def test_downloads_still_pause(self):
def media():
- raise setup.Problem("download", "The internet connection dropped.")
+ raise setup.Problem("download", "Microsoft didn't allow the download from here.")
self.s.step_media = media
- self.s.work()
+ with online_as([True]):
+ self.s.work()
self.assertTrue(self.s.rec["paused"])
+ self.assertEqual(self.s.rec["problem"], {"kind": "download", "text": "Microsoft didn't allow the download from here."})
self.assertIsNone(self.s.rec.get("recovery"))
+ def test_offline_waits_and_carries_on_by_itself(self):
+ tries = {"media": 1}
+ problems = []
+ save = self.s.save
+
+ def watch(**changes):
+ save(**changes)
+ if "problem" in changes:
+ problems.append(changes["problem"])
+ self.s.save = watch
+
+ def media():
+ self.ran.append("media")
+ if tries["media"]:
+ tries["media"] -= 1
+ raise setup.Problem("download", "Windows mode couldn't download the parts it runs on.")
+ self.s.stage_done("media")
+ self.s.step_media = media
+ # Offline when the step fails and for two looks after, then back.
+ with online_as([False, False, False, True]):
+ self.s.work()
+ self.assertEqual(self.ran[:2], ["media", "media"])
+ self.assertEqual(self.s.rec["stage"], "done")
+ self.assertFalse(self.s.rec.get("paused"))
+ self.assertIsNone(self.s.rec.get("problem"))
+ offline = [p for p in problems if p and p.get("offline")]
+ self.assertEqual(len(offline), 1)
+ self.assertEqual(offline[0]["text"], setup.OFFLINE_TEXT)
+
+ def test_start_over_while_offline_stops_the_wait(self):
+ def media():
+ raise setup.Problem("download", "The download stopped.")
+ self.s.step_media = media
+ self.s.svc.refresh = lambda: None
+ with online_as([False] * 1000):
+ worker = threading.Thread(target=self.s.work)
+ self.s.thread = worker
+ worker.start()
+ deadline = time.monotonic() + 5
+ while not (self.s.rec.get("problem") or {}).get("offline") and time.monotonic() < deadline:
+ time.sleep(0.01)
+ self.assertTrue(self.s.rec["problem"]["offline"])
+ self.s.stop.set()
+ self.s.resume_event.set()
+ worker.join(5)
+ self.assertFalse(worker.is_alive())
+
+ def test_nothing_is_written_once_start_over_cleared_the_record(self):
+ self.s.stop.set()
+ self.s.svc.state.pop("setup")
+ self.s.save(download={"received": 1})
+ self.s.set_stage("media", "active", 50)
+ self.assertNotIn("setup", self.s.svc.state)
+
def test_missing_result_of_an_earlier_stage_is_redone(self):
gone = {"once": True}
tune = self.s.step_tune
diff --git a/packages/wildos-winmode/tests/test_winmode.py b/packages/wildos-winmode/tests/test_winmode.py
index 0792217..6fbf37c 100644
--- a/packages/wildos-winmode/tests/test_winmode.py
+++ b/packages/wildos-winmode/tests/test_winmode.py
@@ -319,19 +319,14 @@ class NativeClient(unittest.TestCase):
f.write('#!/bin/sh\nprintf "%s\\n" "$@" > "$0.argv"\ncat > "$0.stdin"\n')
os.chmod(self.client, 0o755)
- def test_the_own_client_unless_missing_or_asked_not_to(self):
- self.assertEqual(rdp.client_program("auto", native=self.client), self.client)
- self.assertEqual(rdp.client_program("xfreerdp3", native=self.client), "xfreerdp3")
- self.assertEqual(rdp.client_program("auto", native=os.path.join(self.dir, "missing")), "xfreerdp3")
-
- def test_the_desktop_opens_in_xfreerdp3_unless_remote_is_asked_for(self):
- remote = os.path.join(self.dir, "wildos-remote")
- with open(remote, "w") as f:
- f.write("#!/bin/sh\n")
- os.chmod(remote, 0o755)
- self.assertEqual(rdp.desktop_client("xfreerdp3", remote=remote), "xfreerdp3")
- self.assertEqual(rdp.desktop_client("remote", remote=remote), remote)
- self.assertEqual(rdp.desktop_client("remote", remote=os.path.join(self.dir, "missing")), "xfreerdp3")
+ def test_the_desktop_opens_in_wildos_rdp(self):
+ conn = rdp.Connection(lambda o: None, lambda: None, os.path.join(self.dir, "log", "d.log"), desktop=True)
+ conn.native_client = self.client
+ conn.start(["/v:192.168.207.10:3389", "/u:wild", "/title:Windows desktop"], "secret")
+ self.wait(conn)
+ self.assertEqual(read(self.client + ".argv").split(NL)[:2], ["--desktop", "/args-from:stdin"])
+ self.assertNotIn("secret", read(self.client + ".argv"))
+ self.assertEqual(read(self.client + ".stdin").splitlines()[-1], "/p:secret")
def test_loading_arguments_are_one_line_each(self):
args = rdp.loading_arguments("wildos-winmode-word", "Word\n/drive:all,/", "wildos-winmode-word", "Slow, really",
@@ -404,9 +399,8 @@ class NativeClient(unittest.TestCase):
self.assertEqual(read(self.client + ".stdin"), "")
self.assertFalse(conn.open)
- def test_xfreerdp_is_never_started_early(self):
- conn = rdp.Connection(lambda o: None, lambda: None, os.path.join(self.dir, "c.log"), program="xfreerdp3")
- self.assertFalse(conn.native)
+ def test_the_desktop_is_never_started_early(self):
+ conn = rdp.Connection(lambda o: None, lambda: None, os.path.join(self.dir, "c.log"), desktop=True)
self.assertFalse(conn.spawn("a", "b", "c"))
self.assertIsNone(conn.proc)
@@ -560,7 +554,7 @@ class Desktop(unittest.TestCase):
def agent(self, desktop_running=False):
from winmode import agent
a = agent.Agent.__new__(agent.Agent)
- a.removing, a.preparing, a.queue = False, None, []
+ a.removing, a.preparing, a.queue, a.activation = False, None, [], None
a.host = {"guest_address": "192.168.207.10", "rdp_port": 3389, "account": "wild"}
a.conn, a.desktop = Client(), Client(desktop_running)
a.call_json = lambda method, args=None, signature=None, done=None, timeout=600: done({"ok": True})
@@ -943,6 +937,23 @@ class Setup(unittest.TestCase):
body[9] = (256 - sum(body) % 256) % 256
return bytes(body)
+ def test_apt_status_lines_become_progress(self):
+ from winmode import setup
+ self.assertEqual(setup.apt_progress("dlstatus:3:42.7:Retrieving file 3 of 40"),
+ "Downloading the parts Windows mode runs on, 42%")
+ self.assertEqual(setup.apt_progress("pmstatus:qemu-system-x86:80:Installing qemu"),
+ "Installing the parts Windows mode runs on, 80%")
+ self.assertIsNone(setup.apt_progress("E: Could not get lock /var/lib/dpkg/lock-frontend"))
+ self.assertIsNone(setup.apt_progress("dlstatus:junk"))
+
+ def test_the_latest_apt_progress_is_shown(self):
+ from winmode import setup
+ log = ("Reading package lists...\ndlstatus:1:10:a\ndlstatus:2:60:b\n"
+ "E: something\npmstatus:qemu:30:Unpacking\nSetting up qemu\n")
+ self.assertEqual(setup.latest_apt_progress(log), "Installing the parts Windows mode runs on, 30%")
+ self.assertIsNone(setup.latest_apt_progress("Reading package lists...\n"))
+ self.assertIsNone(setup.latest_apt_progress(""))
+
def test_firmware_key(self):
from winmode import setup
key = "VK7JG-NPHTM-C97JM-9MPGT-3V66T"
@@ -1083,3 +1094,368 @@ class Setup(unittest.TestCase):
self.assertEqual(st["percent"], 56)
self.assertEqual(st["stages"][2]["title"], "Activation")
self.assertTrue(st["left"].startswith("About "))
+
+
+class UninstallApp(unittest.TestCase):
+ """Settings' Uninstall for a Windows app (wild-guest's Uninstall.cs)."""
+
+ def agent(self, answers):
+ from winmode import agent
+ a = agent.Agent.__new__(agent.Agent)
+ a.removing = False
+ a.registry = {"steam": {"name": "Steam", "target": r"C:\Program Files (x86)\Steam\steam.exe"}}
+ a.installers, a.installed_since_refresh = {}, False
+ a.asked, a.launched, a.refreshed = [], [], 0
+
+ def call_json(method, args=None, signature=None, done=None, timeout=600):
+ a.asked.append((method, args))
+ done(answers[method])
+ a.call_json = call_json
+ a.m_refresh = lambda sender, defer=None: setattr(a, "refreshed", a.refreshed + 1)
+
+ def launch(path, args, name, app_id, done):
+ a.launched.append((path, args, name, app_id))
+ done("")
+ a.launch = launch
+ return a
+
+ def answer(self, d):
+ import json
+ return json.loads(d.out[0])
+
+ def test_a_program_opens_its_own_uninstaller_unsplit(self):
+ a, d = self.agent({"Wake": {"ok": True},
+ "Uninstall": {"type": "uninstaller", "name": "Steam",
+ "program": r"C:\Program Files (x86)\Steam\uninstall.exe", "arguments": ""}}), Defer()
+ a.m_uninstall_app(None, "steam", d)
+ self.assertEqual(a.asked[1], ("Uninstall", (r"C:\Program Files (x86)\Steam\steam.exe",)))
+ self.assertEqual(a.launched, [(r"C:\Program Files (x86)\Steam\uninstall.exe", [], "Steam", "installer")])
+ self.assertIn("uninstall", a.installers)
+ self.assertTrue(a.installed_since_refresh)
+ self.assertEqual(self.answer(d)["state"], "opened")
+
+ def test_msi_arguments_are_split_windows_style(self):
+ a, d = self.agent({"Wake": {"ok": True},
+ "Uninstall": {"type": "uninstaller", "name": "X", "program": "MsiExec.exe",
+ "arguments": '/X{23C28AD0-2B29-414F-89FA-C8CB0BE36CFD} NAME="a b"'}}), Defer()
+ a.m_uninstall_app(None, "steam", d)
+ self.assertEqual(a.launched[0][1], ["/X{23C28AD0-2B29-414F-89FA-C8CB0BE36CFD}", "NAME=a b"])
+
+ def test_a_store_app_is_removed_and_start_refreshed(self):
+ a, d = self.agent({"Wake": {"ok": True}, "Uninstall": {"type": "uninstalled"}}), Defer()
+ a.m_uninstall_app(None, "steam", d)
+ self.assertEqual(self.answer(d)["state"], "removed")
+ self.assertEqual(a.refreshed, 1)
+ self.assertEqual(a.launched, [])
+
+ def test_no_uninstaller_says_where_to_go(self):
+ a, d = self.agent({"Wake": {"ok": True}, "Uninstall": {"type": "error", "error": "no-uninstaller"}}), Defer()
+ a.m_uninstall_app(None, "steam", d)
+ out = self.answer(d)
+ self.assertEqual(out["state"], "failed")
+ self.assertIn("Windows' own Settings", out["message"])
+
+ def test_windows_that_will_not_start_is_said(self):
+ a, d = self.agent({"Wake": {"ok": False, "message": "No room."}}), Defer()
+ a.m_uninstall_app(None, "steam", d)
+ self.assertEqual(self.answer(d), {"state": "failed", "message": "No room."})
+ self.assertEqual([m for m, _ in a.asked], ["Wake"])
+
+ def test_an_app_already_gone_counts_as_removed(self):
+ import json
+ a = self.agent({})
+ self.assertEqual(json.loads(a.m_uninstall_app(None, "nothing", Defer()))["state"], "removed")
+
+
+class MicrosoftAccountActivation(unittest.TestCase):
+ """Settings' Use a licence on my Microsoft account (issue 56): a second
+ account just for it, the policy lifted meanwhile, everything put back
+ afterwards, even after an interruption."""
+
+ def service(self, licence_status="0", fail_create=False, cleanup="done", ping=True):
+ from types import SimpleNamespace
+ from unittest import mock
+ from winmode import activation
+ saved, ran, passwords, setup_saves = [], [], [], []
+ svc = SimpleNamespace(domain="w", cfg={"account": "wild"}, state={})
+ svc.save_state = lambda: saved.append(json.loads(json.dumps(svc.state)))
+ svc.setup = SimpleNamespace(rec={"licence": {"source": "none", "activated": False}},
+ save=lambda **kw: setup_saves.append(kw))
+
+ def powershell(domain, script, timeout=60):
+ if "SoftwareLicensingProduct" in script:
+ ran.append("status")
+ return 0, licence_status + "\r\n", ""
+ if "New-LocalUser" in script:
+ ran.append("create")
+ # The record is on disk before Windows changes.
+ self.assertEqual(saved[-1]["activation"]["stage"], "creating")
+ return (1, "", "boom") if fail_create else (0, "sid S-1-5-21-1-2-3-1002\r\n", "")
+ if "Remove-LocalUser" in script:
+ ran.append("cleanup")
+ return 0, cleanup + "\r\n", ""
+ raise AssertionError(script)
+
+ for p in (mock.patch.object(activation.qga, "powershell", powershell),
+ mock.patch.object(activation.qga, "set_password", lambda d, account, pw: passwords.append((account, pw))),
+ mock.patch.object(activation.qga, "ping", lambda d, t=3: ping)):
+ p.start()
+ self.addCleanup(p.stop)
+ act = activation.Activation(svc, lambda: "Secret123a7Q")
+ return act, svc, ran, passwords, saved, setup_saves
+
+ def test_the_account_is_made_and_its_password_set_off_the_command_line(self):
+ from winmode import activation
+ act, svc, ran, passwords, saved, _ = self.service()
+ out = act.start()
+ self.assertEqual(out, {"account": "activate", "password": "Secret123a7Q"})
+ self.assertEqual(ran, ["status", "create"])
+ self.assertEqual(passwords, [("activate", "Secret123a7Q")])
+ self.assertEqual(svc.state["activation"]["stage"], "open")
+ self.assertEqual(svc.state["activation"]["sid"], "S-1-5-21-1-2-3-1002")
+ self.assertNotIn("Secret123a7Q", activation.create_script("activate", "wild"))
+ self.assertNotIn("Secret123a7Q", json.dumps(saved))
+ self.assertFalse(act.needs_cleanup())
+
+ def test_an_activated_windows_needs_no_account(self):
+ act, svc, ran, passwords, _, setup_saves = self.service(licence_status="1")
+ out = act.start()
+ self.assertTrue(out["activated"])
+ self.assertEqual(ran, ["status"])
+ self.assertEqual(passwords, [])
+ self.assertNotIn("activation", svc.state)
+ # Activated before this started: the licence's source stays as it was.
+ self.assertEqual(setup_saves, [{"licence": {"source": "none", "activated": True}}])
+
+ def test_activated_during_it_is_recorded_as_the_accounts(self):
+ act, svc, ran, _, _, setup_saves = self.service()
+ act.start()
+ ran.clear()
+ self.assertFalse(act.check())
+ self.assertEqual(setup_saves, [])
+ act.license_status = lambda: 1
+ self.assertTrue(act.check())
+ self.assertEqual(setup_saves, [{"licence": {"source": "account", "activated": True}}])
+
+ def test_ending_removes_the_record_only_once_windows_is_put_back(self):
+ act, svc, ran, _, _, _ = self.service()
+ act.start()
+ self.assertEqual(act.end(), "")
+ self.assertNotIn("activation", svc.state)
+ self.assertEqual(ran[-1], "cleanup")
+ self.assertFalse(act.needs_cleanup())
+
+ def test_a_clean_up_that_did_not_finish_is_tried_again(self):
+ act, svc, ran, _, _, _ = self.service(cleanup="left profile")
+ act.start()
+ self.assertIn("tries again", act.end())
+ self.assertIn("activation", svc.state)
+ self.assertTrue(act.needs_cleanup())
+
+ def test_windows_not_running_keeps_the_record_for_later(self):
+ act, svc, ran, _, _, _ = self.service(ping=False)
+ svc.state["activation"] = {"stage": "open", "account": "activate", "sid": "S-1-5-21-9", "started": time.time()}
+ self.assertIn("next time it starts", act.end())
+ self.assertIn("activation", svc.state)
+ self.assertNotIn("cleanup", ran)
+ self.assertTrue(act.needs_cleanup())
+
+ def test_a_failed_start_cleans_up_what_it_made(self):
+ act, svc, ran, passwords, _, _ = self.service(fail_create=True)
+ out = act.start()
+ self.assertIn("couldn't add the account", out["message"])
+ self.assertEqual(ran, ["status", "create", "cleanup"])
+ self.assertEqual(passwords, [])
+ self.assertNotIn("activation", svc.state)
+
+ def test_a_record_from_an_earlier_run_is_cleaned_up(self):
+ act, svc, _, _, _, _ = self.service()
+ svc.state["activation"] = {"stage": "open", "account": "activate", "sid": "S-1-5-21-9", "started": time.time()}
+ # Found at start-up: this run of the service didn't start it.
+ self.assertTrue(act.needs_cleanup())
+ act.owned = True
+ self.assertFalse(act.needs_cleanup())
+ # Past its hour, even this run's own is ended.
+ svc.state["activation"]["started"] = time.time() - 3700
+ self.assertTrue(act.needs_cleanup())
+
+ def test_a_new_start_clears_a_leftover_first(self):
+ act, svc, ran, _, _, _ = self.service()
+ svc.state["activation"] = {"stage": "ending", "account": "activate", "sid": "S-1-5-21-9", "started": time.time()}
+ act.start()
+ self.assertEqual(ran, ["cleanup", "status", "create"])
+ self.assertEqual(svc.state["activation"]["stage"], "open")
+ self.assertTrue(act.owned)
+
+ def test_windows_modes_own_account_is_never_used(self):
+ from winmode import activation
+ self.assertFalse(activation.safe_name("wild", "wild"))
+ self.assertFalse(activation.safe_name("WILD", "wild"))
+ self.assertFalse(activation.safe_name("a'b", "wild"))
+ self.assertTrue(activation.safe_name("activate", "wild"))
+ script = activation.cleanup_script("activate", "S-1-5-21-9", "wild")
+ self.assertIn("$keep = 'wild'", script)
+ self.assertIn("'refused'; exit 1", script)
+ self.assertIn("throw 'refusing the Windows mode account'", activation.create_script("activate", "wild"))
+
+ def test_the_policy_goes_back_before_anything_else(self):
+ from winmode import activation
+ script = activation.cleanup_script("activate", "S-1-5-21-9", "wild")
+ restore = script.index("-Name 'NoConnectedUser' -Value 1")
+ self.assertLess(restore, script.index("logoff.exe"))
+ self.assertLess(restore, script.index("Remove-LocalUser"))
+ self.assertLess(script.index("Remove-Item -Force 'C:\\ProgramData\\WildOS\\activation.json'"), script.index("logoff.exe"))
+ create = activation.create_script("activate", "wild")
+ self.assertIn("-Name 'NoConnectedUser' -Value 0", create)
+ # The marker tune.ps1 honours is written before the policy is lifted.
+ self.assertLess(create.index("activation.json"), create.index("'NoConnectedUser' -Value 0"))
+ self.assertIn("S-1-5-32-544", create)
+
+ def test_tune_leaves_the_policy_alone_while_activating(self):
+ tune = read(os.path.join(DATA, "..", "guest", "tune.ps1"))
+ gate = tune.index('$activation = Get-Item "$stateDir\\activation.json"')
+ policy = tune.index("'NoConnectedUser' 1")
+ self.assertLess(gate, policy)
+ self.assertIn("if (-not $activation -or $activation.LastWriteTime -lt (Get-Date).AddDays(-1)) {", tune[gate:policy])
+ # The new version reaches Windows through upkeep, but the long
+ # capabilities check stays keyed to its own version.
+ self.assertIn("$version = '3'", tune)
+ self.assertIn("$featuresVersion = '2'", tune)
+ self.assertIn('$state.features -ne "$featuresVersion/$buildId"', tune)
+
+
+class AccountActivationAgent(unittest.TestCase):
+ def agent(self, start_reply=None):
+ from winmode import agent
+ a = agent.Agent.__new__(agent.Agent)
+ a.removing, a.preparing, a.queue, a.windows = False, None, [], []
+ a.host = {"guest_address": "192.168.207.10", "rdp_port": 3389, "account": "wild"}
+ a.conn, a.desktop, a.activation_desktop = Client(True), Client(True), Client()
+ a.activation = a.activation_account = a.activation_result = a.activation_timer = None
+ a.activation_tidied = False
+ a.asked, a.forgotten, a.reopened = [], [], []
+ a.keyring = type("K", (), {"memory": {}, "put": lambda self, k, v: None,
+ "forget": lambda self, k: a.forgotten.append(k)})()
+ a.replies = {"ActivationStart": start_reply or {"account": "activate", "password": "pw2", "domain": "WILDPC"},
+ "ActivationCheck": {"activated": False, "active": True}}
+
+ def call_json(method, args=None, signature=None, done=None, timeout=600):
+ a.asked.append(method)
+ done(a.replies[method])
+ a.call_json = call_json
+ a.call = lambda method, args=None, signature=None, done=None, timeout=600: (a.asked.append(method), done(""))
+ a.end_preparing = lambda: None
+ a.changed = lambda: None
+ a.refresh_host = lambda then=None: None
+ a.reopen_windows = lambda within=90: a.reopened.append(within)
+ return a
+
+ def run_in(self, fn):
+ from unittest import mock
+ from winmode import agent
+ with mock.patch.object(agent.dbusutil, "in_thread", lambda fn, *args, done=None: fn(*args)), \
+ mock.patch.object(agent.GLib, "timeout_add_seconds", lambda s, fn: 7), \
+ mock.patch.object(agent.GLib, "source_remove", lambda t: None):
+ return fn()
+
+ def start(self, a):
+ d = Defer()
+ self.run_in(lambda: a.m_activate_with_account(None, d))
+ return d
+
+ def test_the_desktop_opens_signed_in_to_the_account_for_activating(self):
+ a = self.agent()
+ d = self.start(a)
+ self.assertEqual(d.out, [""])
+ self.assertEqual(a.activation, "open")
+ self.assertEqual(a.conn.stopped, 1)
+ self.assertEqual(a.desktop.stopped, 1)
+ args = a.activation_desktop.started[0]
+ self.assertIn("/u:activate", args)
+ self.assertIn("/d:WILDPC", args)
+ self.assertIn("/title:Activate Windows", args)
+ # Not the person's shared folders.
+ self.assertFalse(any(x.startswith("/drive:") for x in args))
+ self.assertEqual(a.m_activation_password(None), "pw2")
+
+ def test_nothing_else_takes_the_session_meanwhile(self):
+ from winmode import agent
+ a = self.agent()
+ self.start(a)
+ out = []
+ a.launch(r"C:\Windows\notepad.exe", [], "Notepad", "notepad", out.append)
+ self.assertEqual(out, [agent.ACTIVATING])
+ self.assertEqual(a.m_open_desktop(None, Defer()), agent.ACTIVATING)
+
+ def test_closing_the_window_ends_it_and_forgets_the_password(self):
+ a = self.agent()
+ self.start(a)
+ self.run_in(lambda: a.activation_desktop_changed(False))
+ self.assertEqual(a.asked[-2:], ["ActivationCheck", "ActivationEnd"])
+ self.assertIsNone(a.activation)
+ self.assertEqual(a.forgotten, ["activate"])
+ self.assertEqual(a.activation_result, {"activated": False, "message": ""})
+ self.assertEqual(a.m_activation_password(None), "")
+ self.assertEqual(a.reopened, [60])
+
+ def test_done_counts_an_activation_windows_reports_late(self):
+ a = self.agent()
+ self.start(a)
+ a.replies["ActivationCheck"] = {"activated": True, "active": True}
+ d = Defer()
+ self.run_in(lambda: a.m_end_activation(None, d))
+ self.assertEqual(d.out, [""])
+ self.assertTrue(a.activation_result["activated"])
+
+ def test_activated_ends_it_by_itself(self):
+ a = self.agent()
+ self.start(a)
+ a.replies["ActivationCheck"] = {"activated": True, "active": True}
+ self.run_in(a.check_activation)
+ self.assertEqual(a.asked[-1], "ActivationEnd")
+ self.assertTrue(a.activation_result["activated"])
+
+ def test_already_activated_opens_nothing(self):
+ a = self.agent({"activated": True, "message": "Windows is already activated."})
+ d = self.start(a)
+ self.assertEqual(d.out, [""])
+ self.assertIsNone(a.activation)
+ self.assertTrue(a.activation_result["already"])
+ self.assertEqual(a.activation_desktop.started, [])
+ self.assertEqual(a.conn.stopped, 0)
+
+ def test_a_service_refusal_is_said(self):
+ a = self.agent({"message": "No room."})
+ d = self.start(a)
+ self.assertEqual(d.out, ["No room."])
+ self.assertIsNone(a.activation)
+
+ def test_an_activation_from_before_the_agent_restarted_is_ended_once(self):
+ from winmode import agent
+ a = self.agent()
+ st = {"state": "Running", "activation": {"stage": "open"}}
+ a.call_json = lambda method, args=None, signature=None, done=None, timeout=600: (a.asked.append(method), done(st))
+ a.set_windows = lambda ws: None
+ a.end_connection_if_gone = lambda s: None
+ for _ in range(2):
+ self.run_in(lambda: agent.Agent.refresh_host(a))
+ a.activation = None
+ self.assertEqual(a.asked.count("ActivationEnd"), 1)
+
+
+class AccountActivationService(unittest.TestCase):
+ def test_cleanup_resumes_once_windows_runs(self):
+ from types import SimpleNamespace
+ from winmode import system
+ ended = []
+ s = SimpleNamespace(busy_action=None, activation=SimpleNamespace(needs_cleanup=lambda: True),
+ end_activation=lambda done=None: ended.append(True))
+ system.Service.resume_activation_cleanup(s)
+ self.assertEqual(ended, [True])
+ s.busy_action = "save"
+ system.Service.resume_activation_cleanup(s)
+ self.assertEqual(ended, [True])
+
+ def test_the_title_stays_one_argument(self):
+ args = rdp.desktop_arguments("h", 3389, "activate", "", title="Activate, Windows")
+ self.assertIn("/title:Activate Windows", args)
diff --git a/packages/wildos-winmode/winmode/activation.py b/packages/wildos-winmode/winmode/activation.py
new file mode 100644
index 0000000..3a55fdb
--- /dev/null
+++ b/packages/wildos-winmode/winmode/activation.py
@@ -0,0 +1,281 @@
+"""Activating Windows with a digital licence on the person's Microsoft
+account (issue 56).
+
+Microsoft moves such a licence to new hardware only through activation's
+troubleshooter ("I changed hardware on this device"), and only for a
+Microsoft account that is an administrator on the PC. Windows mode's own
+account must never become one: that swaps its password for the Microsoft
+one and every sign-in from Wild OS fails (issue 12), so tune.ps1 sets
+NoConnectedUser. Instead, for the length of one activation, a second local
+administrator ("activate") is made, the policy is lifted, and the person
+does the troubleshooter in a Windows desktop signed in to that account.
+Afterwards the account and its profile are deleted and the policy goes
+back. The activation belongs to the virtual PC, so it stays.
+
+The record in the service's state (state["activation"]) is written before
+anything changes in Windows and removed only once everything is back, so a
+restart of Wild OS or of Windows mode part way through still ends with the
+clean-up (Service.slow_check resumes it).
+"""
+
+import re
+import sys
+import time
+
+from . import qga, virsh
+
+ACCOUNT = "activate"
+# Keeps Windows from being paused or saved while the person works in it.
+HOLD = "activation"
+# The policy is off for at most this long; past it the clean-up runs even
+# with the desktop still open.
+LIMIT = 3600
+MARKER = r"C:\ProgramData\WildOS\activation.json"
+POLICY_KEY = r"HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System"
+LICENSE_STATUS_SCRIPT = (
+ "(Get-CimInstance SoftwareLicensingProduct -Filter \"ApplicationID='55c92734-d682-4d71-983e-d6ec3f16059f'"
+ " and PartialProductKey is not null\" | Select-Object -First 1).LicenseStatus")
+
+
+def quoted(text):
+ """A PowerShell single-quoted string."""
+ return "'" + str(text).replace("'", "''") + "'"
+
+
+def safe_name(account, keep):
+ """Only a plain account name, and never Windows mode's own."""
+ return bool(re.fullmatch(r"[A-Za-z0-9_-]{1,20}", account or "")) and account.lower() != (keep or "").lower()
+
+
+def create_script(account, keep):
+ """Makes the account (with no password until the guest agent sets one,
+ so it never appears on a command line), an administrator, then the
+ marker tune.ps1 honours and the policy lifted. Its last line is the
+ account's SID. Windows allows descriptions of 48 characters at most."""
+ return f"""
+$ErrorActionPreference = 'Stop'
+$name = {quoted(account)}
+$keep = {quoted(keep)}
+if ($name -ieq $keep) {{ throw 'refusing the Windows mode account' }}
+$u = Get-LocalUser -Name $name -ErrorAction SilentlyContinue
+if (-not $u) {{
+ $u = New-LocalUser -Name $name -NoPassword -AccountNeverExpires -FullName 'Activation' `
+ -Description 'Wild OS: for activating Windows, then removed'
+}}
+Set-LocalUser -Name $name -PasswordNeverExpires $true
+if (-not (Get-LocalGroupMember -SID 'S-1-5-32-544' | Where-Object {{ $_.SID -eq $u.SID }})) {{
+ Add-LocalGroupMember -SID 'S-1-5-32-544' -Member $u
+}}
+@{{ account = $name; sid = $u.SID.Value; started = (Get-Date).ToString('s') }} | ConvertTo-Json -Compress |
+ Set-Content -Encoding UTF8 {quoted(MARKER)}
+if (-not (Test-Path {quoted(POLICY_KEY)})) {{ New-Item -Path {quoted(POLICY_KEY)} -Force | Out-Null }}
+New-ItemProperty -Path {quoted(POLICY_KEY)} -Name 'NoConnectedUser' -Value 0 -PropertyType DWord -Force | Out-Null
+"sid $($u.SID.Value)"
+"""
+
+
+def cleanup_script(account, sid, keep):
+ """Puts the policy back first, since that matters most, then signs the
+ account's sessions out and deletes it and its profile. Never touches
+ Windows mode's own account, even if the SID recorded were its. The last
+ line is "done", or "left" and what is still there."""
+ return f"""
+$ErrorActionPreference = 'Continue'
+$name = {quoted(account)}
+$sid = {quoted(sid or '')}
+$keep = {quoted(keep)}
+New-ItemProperty -Path {quoted(POLICY_KEY)} -Name 'NoConnectedUser' -Value 1 -PropertyType DWord -Force | Out-Null
+Remove-Item -Force {quoted(MARKER)} -ErrorAction SilentlyContinue
+$keepSid = (Get-LocalUser -Name $keep -ErrorAction SilentlyContinue).SID.Value
+$u = $null
+if ($sid) {{ $u = Get-LocalUser -SID $sid -ErrorAction SilentlyContinue }}
+if (-not $u) {{ $u = Get-LocalUser -Name $name -ErrorAction SilentlyContinue }}
+if ($u -and ($u.Name -ieq $keep -or $u.SID.Value -eq $keepSid)) {{ 'refused'; exit 1 }}
+if ($u) {{ $sid = $u.SID.Value; $name = $u.Name }}
+# A Microsoft account keeps its local name, so sessions are found by it:
+# from quser (any session, even one with nothing running yet) and from the
+# processes running as it.
+function Sessions {{
+ $ids = @()
+ foreach ($line in (quser 2>$null)) {{
+ $t = $line.Trim().TrimStart('>') -split '\\s+'
+ if ($t.Count -gt 1 -and $t[0] -ieq $name) {{ $ids += ($t[1..($t.Count - 1)] | Where-Object {{ $_ -match '^\\d+$' }} | Select-Object -First 1) }}
+ }}
+ foreach ($p in (Get-Process -IncludeUserName -ErrorAction SilentlyContinue)) {{
+ if ($p.SessionId -ne 0 -and $p.UserName -and ($p.UserName -split '\\\\')[-1] -ieq $name) {{ $ids += $p.SessionId }}
+ }}
+ $ids | Where-Object {{ $_ -ne $null }} | ForEach-Object {{ [int]$_ }} | Sort-Object -Unique
+}}
+for ($i = 0; $i -lt 30; $i++) {{
+ $s = @(Sessions)
+ if ($s.Count -eq 0) {{ break }}
+ foreach ($id in $s) {{ logoff.exe $id 2>$null }}
+ Start-Sleep -Seconds 2
+}}
+if ($u) {{ Remove-LocalUser -SID $sid -ErrorAction SilentlyContinue }}
+# The profile's registry hive unloads a moment after the sign-out.
+if ($sid) {{
+ for ($i = 0; $i -lt 20; $i++) {{
+ $p = Get-CimInstance Win32_UserProfile -Filter "SID='$sid'" -ErrorAction SilentlyContinue
+ if (-not $p) {{ break }}
+ try {{ $p | Remove-CimInstance -ErrorAction Stop }} catch {{ Start-Sleep -Seconds 3 }}
+ }}
+}}
+$left = @()
+if (@(Sessions).Count) {{ $left += 'session' }}
+if (Get-LocalUser -Name $name -ErrorAction SilentlyContinue) {{ $left += 'account' }}
+if ($sid -and (Get-CimInstance Win32_UserProfile -Filter "SID='$sid'" -ErrorAction SilentlyContinue)) {{ $left += 'profile' }}
+if ((Get-ItemProperty -Path {quoted(POLICY_KEY)} -Name 'NoConnectedUser' -ErrorAction SilentlyContinue).NoConnectedUser -ne 1) {{ $left += 'policy' }}
+if ($left.Count) {{ "left $($left -join ' ')" }} else {{ 'done' }}
+"""
+
+
+def last_line(out):
+ lines = [line.strip() for line in (out or "").splitlines() if line.strip()]
+ return lines[-1] if lines else ""
+
+
+class Activation:
+ """The service's side: the record, and the scripts run through the
+ guest agent. Every method runs on a worker thread; the record is the
+ service's state, saved at each step."""
+
+ def __init__(self, svc, new_password):
+ self.svc = svc
+ self.new_password = new_password
+ # Started by this run of the service. A record found at start-up
+ # belongs to a run that ended part way, and is cleaned up.
+ self.owned = False
+ self.ending = False
+
+ @property
+ def rec(self):
+ return self.svc.state.get("activation")
+
+ def status(self):
+ rec = self.rec
+ if not rec:
+ return None
+ return {"stage": rec.get("stage"), "account": rec.get("account"), "started": rec.get("started")}
+
+ def save(self, rec):
+ if rec is None:
+ self.svc.state.pop("activation", None)
+ else:
+ self.svc.state["activation"] = rec
+ self.svc.save_state()
+
+ def overdue(self, now=None):
+ rec = self.rec
+ return bool(rec) and (now if now is not None else time.time()) - rec.get("started", 0) > LIMIT
+
+ def needs_cleanup(self):
+ return bool(self.rec) and not self.ending and (not self.owned or self.overdue())
+
+ def keep(self):
+ return self.svc.cfg["account"]
+
+ def license_status(self):
+ _, out, _ = qga.powershell(self.svc.domain, LICENSE_STATUS_SCRIPT, 60)
+ line = last_line(out)
+ return int(line) if line.isdigit() else None
+
+ def start(self):
+ """Windows is running. {account, password} for the desktop, or
+ {message} for why not."""
+ if self.rec:
+ # Left from an earlier try: that one goes first, so this one
+ # starts from a fresh account and profile.
+ why = self.end()
+ if why:
+ return {"message": why}
+ try:
+ if self.license_status() == 1:
+ self.record_activated(None)
+ return {"message": "Windows is already activated.", "activated": True}
+ except (virsh.VirshError, ValueError, KeyError, TimeoutError) as e:
+ self.log("licence status:", e)
+ account, keep = ACCOUNT, self.keep()
+ if not safe_name(account, keep):
+ return {"message": "Windows mode couldn't add the account for activating."}
+ self.owned = True
+ # Written before Windows changes, so an interruption from here on is
+ # cleaned up.
+ self.save({"stage": "creating", "account": account, "sid": None, "started": time.time()})
+ try:
+ code, out, err = qga.powershell(self.svc.domain, create_script(account, keep), 120)
+ line = last_line(out)
+ if code != 0 or not line.startswith("sid S-1-"):
+ raise RuntimeError((err or out).strip()[-300:] or f"exit {code}")
+ sid = line.split(" ", 1)[1]
+ password = self.new_password()
+ qga.set_password(self.svc.domain, account, password)
+ except (virsh.VirshError, ValueError, KeyError, TimeoutError, RuntimeError) as e:
+ self.log("adding the account for activating:", e)
+ self.end()
+ # Whatever is left is the service's to clean up from now on.
+ self.owned = False
+ return {"message": "Windows mode couldn't add the account for activating. Try again, or restart the PC."}
+ self.save(dict(self.rec, stage="open", sid=sid))
+ return {"account": account, "password": password}
+
+ def check(self):
+ """Whether Windows says it is activated, which is recorded when so."""
+ if not self.rec:
+ return False
+ try:
+ activated = self.license_status() == 1
+ except (virsh.VirshError, ValueError, KeyError, TimeoutError) as e:
+ self.log("licence status:", e)
+ return False
+ if activated:
+ self.record_activated("account")
+ return activated
+
+ def record_activated(self, source):
+ """Settings' licence row. Activated during this flow means the
+ licence came from the Microsoft account; found activated before it
+ started, the licence is whatever Windows already had."""
+ setup = self.svc.setup
+ lic = dict((setup.rec or {}).get("licence") or {})
+ if lic.get("activated") is True:
+ return
+ if source:
+ lic["source"] = source
+ lic["activated"] = True
+ setup.save(licence=lic)
+
+ def end(self):
+ """Signs the account out, deletes it and its profile and puts the
+ policy back. "" when all of that is done (or there was nothing to
+ do), else why not; the record then stays, and the clean-up is
+ tried again."""
+ rec = self.rec
+ if not rec:
+ self.owned = False
+ return ""
+ self.ending = True
+ # Until it succeeds, the service retries by itself (needs_cleanup).
+ self.owned = False
+ try:
+ try:
+ if not qga.ping(self.svc.domain, 5):
+ return "Windows isn't running, so the account for activating is removed the next time it starts."
+ self.save(dict(rec, stage="ending"))
+ code, out, err = qga.powershell(self.svc.domain, cleanup_script(rec.get("account") or ACCOUNT, rec.get("sid"),
+ self.keep()), 300)
+ except (virsh.VirshError, ValueError, KeyError, TimeoutError) as e:
+ self.log("removing the account for activating:", e)
+ return "Windows mode couldn't remove the account for activating yet. It tries again by itself."
+ line = last_line(out)
+ if line != "done":
+ self.log("removing the account for activating:", line or (err or "").strip()[-300:])
+ return "Windows mode couldn't remove the account for activating yet. It tries again by itself."
+ self.save(None)
+ self.log("the account for activating is removed and Windows mode's own account is protected again")
+ return ""
+ finally:
+ self.ending = False
+
+ def log(self, *parts):
+ print(*parts, file=sys.stderr, flush=True)
diff --git a/packages/wildos-winmode/winmode/agent.py b/packages/wildos-winmode/winmode/agent.py
index 2d13f0d..003cda9 100644
--- a/packages/wildos-winmode/winmode/agent.py
+++ b/packages/wildos-winmode/winmode/agent.py
@@ -38,6 +38,10 @@ XML = """
<arg name="args" type="as" direction="in"/>
<arg type="s" direction="out"/>
</method>
+ <method name="UninstallApp">
+ <arg name="app" type="s" direction="in"/>
+ <arg type="s" direction="out"/>
+ </method>
<method name="RunInstaller">
<arg name="path" type="s" direction="in"/>
<arg type="s" direction="out"/>
@@ -67,6 +71,9 @@ XML = """
</method>
<method name="CheckUpdates"><arg type="s" direction="out"/></method>
<method name="OpenDesktop"><arg type="s" direction="out"/></method>
+ <method name="ActivateWithAccount"><arg type="s" direction="out"/></method>
+ <method name="EndActivation"><arg type="s" direction="out"/></method>
+ <method name="ActivationPassword"><arg type="s" direction="out"/></method>
<method name="Repair"><arg type="s" direction="out"/></method>
<method name="Remove"><arg type="s" direction="out"/></method>
<method name="StartSetup">
@@ -90,6 +97,11 @@ XML = """
NOT_YET = "This isn't available yet."
REMOVING = "Windows mode is being removed."
+ACTIVATING = ("Windows is open for activation. Finish in the Windows desktop, or press Cancel in Settings, "
+ "then try again.")
+# How often Windows is asked whether it is activated while the person works
+# through Microsoft's troubleshooter.
+ACTIVATION_CHECK_SECONDS = 10
# 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.
@@ -287,7 +299,17 @@ class Agent:
# Anything installed from the whole Windows desktop gets its Start
# entry once the desktop closes.
self.desktop = rdp.Connection(self.desktop_changed, self.auth_failed,
- os.path.join(config.user_data_dir(), "desktop.log"), program=rdp.desktop_client())
+ os.path.join(config.user_data_dir(), "desktop.log"), desktop=True)
+ # Activating with a Microsoft account (issue 56): the desktop signed
+ # in to the account made for it, what stage it is at (starting, open
+ # or ending) and how the last one went.
+ self.activation_desktop = rdp.Connection(self.activation_desktop_changed, lambda: None,
+ os.path.join(config.user_data_dir(), "activation.log"), desktop=True)
+ self.activation = None
+ self.activation_account = None
+ self.activation_result = None
+ self.activation_timer = None
+ self.activation_tidied = False
# wildos-rdp's windows for apps being opened, by token, and its
# interface on the session bus.
self.loading = {}
@@ -304,6 +326,7 @@ class Agent:
"Launch": (self.m_launch, "s", False),
"LaunchProgram": (self.m_launch_program, "s", False),
"RunInstaller": (self.m_run_installer, "s", False),
+ "UninstallApp": (self.m_uninstall_app, "s", False),
"OutsideSharedFolders": (self.m_outside, "as", False),
"CopyIntoDocuments": (self.m_copy, "as", False),
"RefreshApps": (self.m_refresh, "s", False),
@@ -313,6 +336,9 @@ class Agent:
"SetProductKey": (self.m_set_product_key, "s", False),
"CheckUpdates": (lambda sender: NOT_YET, "s", False),
"OpenDesktop": (self.m_open_desktop, "s", False),
+ "ActivateWithAccount": (self.m_activate_with_account, "s", False),
+ "EndActivation": (self.m_end_activation, "s", False),
+ "ActivationPassword": (self.m_activation_password, "s", False),
"Repair": (lambda sender: NOT_YET, "s", False),
"Remove": (self.m_remove, "s", False),
"StartSetup": (self.m_start_setup, "s", False),
@@ -353,7 +379,7 @@ class Agent:
self.session_end = xsmp.Client(session, self.windows_open, self.ask_before_leaving, log)
def prestart(self):
- if self.host.get("kept") or self.removing:
+ if self.host.get("kept") or self.removing or self.activation:
return
def done(reply):
if isinstance(reply, GLib.Error):
@@ -371,9 +397,9 @@ class Agent:
"""Windows was started ahead of time: it is signed in to as well, and
the session left disconnected, so the first app takes it over in a
couple of seconds instead of waiting for Windows to sign in and start
- its shell (about three seconds more, measured). Only with wildos-rdp,
- and only while no connection is open or opening."""
- if not self.conn.native or self.conn.running or self.preparing is not None:
+ its shell (about three seconds more, measured). Only while no
+ connection is open or opening."""
+ if self.conn.running or self.preparing is not None or self.activation:
return
def go(creds):
@@ -465,6 +491,12 @@ class Agent:
if isinstance(st.get("windows"), list):
self.set_windows(st["windows"])
self.end_connection_if_gone(st)
+ if st.get("activation") and not self.activation and not self.activation_tidied:
+ self.activation_tidied = True
+ # Started before this agent did (it restarted part way):
+ # nothing here can finish it, so it is tidied up.
+ log("an activation from before this agent started is being ended")
+ self.finish_activation("restarted")
self.changed()
if then:
then()
@@ -642,6 +674,9 @@ class Agent:
if self.removing:
done(REMOVING)
return
+ if self.activation:
+ done(ACTIVATING)
+ return
started = time.monotonic()
self.end_preparing()
window = self.open_app_window(app_id, name, path)
@@ -749,9 +784,7 @@ class Agent:
"""wildos-rdp's window for an app being opened: through the running
client when the connection is open, or by starting the client now
when it is not, so the window is there while Windows wakes. Returns
- what close_app_window() needs, or None with xfreerdp3."""
- if not self.conn.native:
- return None
+ what close_app_window() needs."""
known = app_id in self.registry
desktop_id = launchers.PREFIX + app_id if known else ""
icon = launchers.PREFIX + app_id if known else ""
@@ -935,9 +968,138 @@ class Agent:
if self.removing:
return REMOVING
+ if self.activation:
+ return ACTIVATING
self.call_json("Wake", done=woke)
return defer
+ def m_activate_with_account(self, sender, defer):
+ """Settings' Use a licence on my Microsoft account: the service makes
+ a second Windows account just for this (activation.py), and the whole
+ desktop opens signed in to it for Microsoft's troubleshooter. The
+ app connection and any Windows desktop close first, since Windows
+ shows one session at a time; their apps keep running and come back
+ afterwards."""
+ if self.removing:
+ return REMOVING
+ if self.activation:
+ return ""
+ self.activation = "starting"
+ self.activation_result = None
+ self.changed()
+
+ def started(reply):
+ if not reply.get("password"):
+ self.activation = None
+ if reply.get("activated"):
+ self.activation_result = {"activated": True, "already": True, "message": ""}
+ self.refresh_host()
+ defer.done("")
+ return
+ self.changed()
+ defer.done(reply.get("message") or "Windows mode's background service didn't answer. Restart the PC, then try again.")
+ return
+ account = reply["account"]
+ self.activation_account = account
+ self.keyring.memory[account] = reply["password"]
+ dbusutil.in_thread(self.keyring.put, account, reply["password"])
+ self.conn.stop_now()
+ self.end_preparing()
+ self.desktop.stop_now()
+ if self.activation_desktop.running:
+ self.activation_desktop.stop_now()
+ args = rdp.desktop_arguments(self.host.get("guest_address"), self.host.get("rdp_port", 3389), account,
+ reply.get("domain", ""), title="Activate Windows")
+ self.activation = "open"
+ try:
+ self.activation_desktop.start(args, reply["password"])
+ except OSError as e:
+ self.finish_activation("failed")
+ defer.done(f"The Windows desktop couldn't open. ({e.strerror})")
+ return
+ self.activation_timer = GLib.timeout_add_seconds(ACTIVATION_CHECK_SECONDS, self.check_activation)
+ self.refresh_host()
+ defer.done("")
+
+ # Windows may have to start from off, then the account is made.
+ self.call_json("ActivationStart", done=started, timeout=840)
+ return defer
+
+ def check_activation(self):
+ if self.activation != "open":
+ self.activation_timer = None
+ return False
+
+ def got(reply):
+ if self.activation != "open":
+ return
+ if reply.get("activated"):
+ log("Windows says it is activated")
+ self.finish_activation("activated")
+ elif reply.get("active") is False:
+ # The service ended it itself: its hour was up.
+ self.finish_activation("expired")
+ self.call_json("ActivationCheck", done=got, timeout=90)
+ return True
+
+ def activation_desktop_changed(self, is_open):
+ if not is_open and self.activation == "open":
+ self.finish_activation("closed")
+
+ def m_end_activation(self, sender, defer):
+ """Done or Cancel in Settings."""
+ if self.activation in (None, "starting"):
+ return ""
+ self.finish_activation("done", defer.done)
+ return defer
+
+ def m_activation_password(self, sender):
+ """For the one time Windows asks for the account's current password
+ (turning it into a Microsoft account), and only while it exists."""
+ if self.activation != "open" or not self.activation_account:
+ return ""
+ return self.keyring.memory.get(self.activation_account, "")
+
+ def finish_activation(self, why, done=None):
+ """The desktop closes and the service signs the account out, deletes
+ it and its profile and protects Windows mode's own account again.
+ Windows is asked once more first, so Done pressed straight after
+ the troubleshooter still counts."""
+ if self.activation == "ending":
+ if done:
+ done("")
+ return
+ self.activation = "ending"
+ if self.activation_timer:
+ GLib.source_remove(self.activation_timer)
+ self.activation_timer = None
+ self.activation_desktop.close()
+ self.changed()
+ account = self.activation_account
+
+ def ended(reply, activated):
+ message = reply if isinstance(reply, str) else \
+ "Windows mode's background service didn't answer. It removes the extra account by itself when it next starts."
+ self.activation = None
+ self.activation_account = None
+ if account:
+ dbusutil.in_thread(self.keyring.forget, account)
+ self.activation_result = {"activated": activated, "message": message}
+ log("activation ended:", why, "activated" if activated else "not activated", message)
+ self.refresh_host()
+ self.reopen_windows(within=60)
+ if done:
+ done("")
+
+ def checked(reply):
+ activated = bool(reply.get("activated")) or why == "activated"
+ self.call("ActivationEnd", done=lambda r: ended(r, activated), timeout=420)
+
+ if why in ("activated", "restarted", "failed"):
+ checked({"activated": why == "activated"})
+ else:
+ self.call_json("ActivationCheck", done=checked, timeout=90)
+
def credentials(self, done):
"""The account and its password: from the keyring (secret-tool, which
KWallet can keep waiting for seconds, so off the main loop) or else
@@ -1113,6 +1275,9 @@ class Agent:
"lastApp": self.app_summary(launchers.last_app(self.registry, self.last_app, self.history)),
"progressRequests": self.progress_requests,
"removing": self.removing,
+ # Settings' Microsoft account activation: starting, open, ending
+ # or "", and how the last one went ({activated, message}).
+ "activation": {"state": self.activation or "", "result": self.activation_result},
}
def app_summary(self, app_id):
@@ -1139,6 +1304,56 @@ class Agent:
self.launch(path, list(args), launchers.exe_stem(path) or "Windows app", app_id, defer.done)
return defer
+ def m_uninstall_app(self, sender, app_id, defer):
+ """Settings' Uninstall for a Windows app. A Store app is removed
+ inside Windows at once; any other program's own uninstaller opens
+ in a window like an installer, and its Start entry goes once that
+ window closes. The answer is JSON: "removed" (gone already),
+ "opened" (its uninstaller is on screen) or a message."""
+ def answer(state, message=""):
+ defer.done(json.dumps({"state": state, "message": message}))
+
+ if self.removing:
+ return json.dumps({"state": "failed", "message": REMOVING})
+ app = self.registry.get(app_id)
+ if not app:
+ return json.dumps({"state": "removed", "message": ""})
+ name = app.get("name") or "That app"
+ deadline = time.monotonic() + SESSION_WAIT
+
+ def found(reply):
+ kind = reply.get("type")
+ if kind == "uninstalled" or reply.get("error") == "not-installed":
+ self.m_refresh(None)
+ answer("removed")
+ elif kind == "uninstaller" and reply.get("program"):
+ program = reply["program"]
+ self.installers[launchers.exe_stem(program)] = False
+ self.installed_since_refresh = True
+ self.launch(program, split_arguments(reply.get("arguments", "")), name, "installer",
+ lambda message: answer("failed", message) if message else answer("opened"))
+ elif reply.get("error") in ("not-connected", "timeout") and time.monotonic() < deadline:
+ # Windows has only just started: wild-guest connects soon.
+ GLib.timeout_add_seconds(2, lambda: (ask(), False)[1])
+ elif reply.get("error") == "no-uninstaller":
+ answer("failed", f"Windows doesn't list an uninstaller for {name}. Open the Windows desktop from Windows mode "
+ "in Settings and remove it in Windows' own Settings.")
+ else:
+ log("uninstall failed:", reply)
+ answer("failed", f"{name} couldn't be uninstalled. Try again.")
+
+ def ask():
+ self.call_json("Uninstall", (app["target"],), "(s)", found, timeout=210)
+
+ def woke(reply):
+ if not reply.get("ok"):
+ answer("failed", reply.get("message") or "Windows mode couldn't start. Try again, or restart the PC.")
+ return
+ ask()
+
+ self.call_json("Wake", done=woke)
+ return defer
+
def m_run_installer(self, sender, host_path, defer):
"""App Bridge and wild-run hand Windows installers here: the file is
copied into the shared Downloads folder unless Windows can already
@@ -1572,6 +1787,7 @@ def main():
# its windows on screen and hold up systemd stopping the agent.
agent.conn.stop_now()
agent.desktop.stop_now()
+ agent.activation_desktop.stop_now()
# Held until here, so it lives as long as the loop.
del agent
return 0
diff --git a/packages/wildos-winmode/winmode/config.py b/packages/wildos-winmode/winmode/config.py
index f0e8ac8..c17d421 100644
--- a/packages/wildos-winmode/winmode/config.py
+++ b/packages/wildos-winmode/winmode/config.py
@@ -38,12 +38,6 @@ DEFAULTS = {
# keep, save or automatic
"when_idle": "automatic",
"guest_exe": DATA + "/guest/wild-guest.exe",
- # The RemoteApp client: "auto" is Wild OS's own (wildos-rdp) when it is
- # installed, "xfreerdp3" the fallback.
- "rdp_client": "auto",
- # The whole Windows desktop (Settings, "Open Windows desktop"):
- # "xfreerdp3", or "remote" for the Remote app's desktop window.
- "desktop_client": "xfreerdp3",
}
OPTION_KEYS = {"when_idle": ("keep", "save", "automatic")}
diff --git a/packages/wildos-winmode/winmode/rdp.py b/packages/wildos-winmode/winmode/rdp.py
index 45cd476..aa3a0cd 100644
--- a/packages/wildos-winmode/winmode/rdp.py
+++ b/packages/wildos-winmode/winmode/rdp.py
@@ -7,13 +7,11 @@ by wild-guest. Its first program is wild-guest's "--start", which starts
the app and ends, because FreeRDP's /app option splits on commas and
cannot carry a file name that has one.
-The client is Wild OS's own, wildos-rdp, when it is installed: native
-Wayland windows at the screen's own scale, and the app's window on screen
-with the loading W the moment the app is opened (boards 9.11 to 9.13).
-xfreerdp3, under XWayland, is the fallback, and is what "rdp_client":
-"xfreerdp3" in /etc/wildos/winmode.json, or WILDOS_RDP_CLIENT=xfreerdp3 in
-the agent's environment, asks for. Both take the same arguments the same
-way.
+The client is Wild OS's own, wildos-rdp: native Wayland windows at the
+screen's own scale, and the app's window on screen with the loading W the
+moment the app is opened (boards 9.11 to 9.13). The whole Windows desktop
+opens in it too (--desktop). It takes FreeRDP's arguments, one per line on
+standard input with the password last.
"""
import base64
@@ -27,7 +25,6 @@ from gi.repository import Gio, GLib
from . import config
NATIVE_CLIENT = "/usr/libexec/wildos/wildos-rdp"
-REMOTE_CLIENT = "/usr/bin/wildos-remote"
REMOTE_APP_BUS = ("org.wildos.RemoteApp", "/org/wildos/RemoteApp", "org.wildos.RemoteApp")
GUEST_EXE = r"C:\Program Files\Wild OS\wild-guest.exe"
AUTH_FAILED = ("LOGON_FAILURE", "AUTHENTICATION_FAILED", "ERRCONNECT_LOGON_FAILURE", "STATUS_LOGON_FAILURE",
@@ -137,7 +134,7 @@ def drive_arguments(drive):
return [f"/drive:wildos,{drive}"] if drive else []
-def desktop_arguments(host, port, account, domain, drive=None):
+def desktop_arguments(host, port, account, domain, drive=None, title="Windows desktop"):
"""The whole Windows desktop in a window of its own, for Settings'
Windows desktop button. It takes the one session over, so the app
windows go into it until it closes."""
@@ -148,7 +145,7 @@ def desktop_arguments(host, port, account, domain, drive=None):
"/cert:tofu",
"/sec:nla",
"/auth-pkg-list:!kerberos",
- "/title:Windows desktop",
+ f"/title:{plain(title)}",
"/dynamic-resolution",
*drive_arguments(drive),
"+clipboard",
@@ -176,26 +173,6 @@ def forget_certificate(host, port, config_home=None):
return False
-def client_program(choice=None, native=NATIVE_CLIENT):
- """The RemoteApp client to run: wildos-rdp unless it is missing or the
- installation asks for xfreerdp3."""
- choice = choice or os.environ.get("WILDOS_RDP_CLIENT") or config.load().get("rdp_client", "auto")
- if choice != "xfreerdp3" and os.access(native, os.X_OK):
- return native
- return "xfreerdp3"
-
-
-def desktop_client(choice=None, remote=REMOTE_CLIENT):
- """The client for the whole Windows desktop: xfreerdp3 unless the
- installation asks for Remote ("desktop_client": "remote" in
- /etc/wildos/winmode.json, or WILDOS_DESKTOP_CLIENT=remote) and it is
- installed. Remote reads the same arguments from standard input."""
- choice = choice or os.environ.get("WILDOS_DESKTOP_CLIENT") or config.load().get("desktop_client", "xfreerdp3")
- if choice == "remote" and os.access(remote, os.X_OK):
- return remote
- return "xfreerdp3"
-
-
def loading_arguments(app_id, title, icon, reason="", program=""):
"""wildos-rdp's window for the app being opened, before the connection's
own arguments arrive on standard input. Nothing here is secret: an app
@@ -213,29 +190,27 @@ def loading_arguments(app_id, title, icon, reason="", program=""):
class Connection:
- """One RemoteApp client process. on_change(open) runs when it opens or
- ends; on_auth_failed runs when Windows refused the password.
+ """One wildos-rdp process: the RemoteApp connection, or with desktop
+ the whole Windows desktop in one window. on_change(open) runs when it
+ opens or ends; on_auth_failed runs when Windows refused the password.
- wildos-rdp can start before Windows is awake (spawn()), with the app's
- window already on screen, and take the connection's arguments when they
- are known (start()). Until then the connection does not count as open."""
+ For apps, wildos-rdp can start before Windows is awake (spawn()), with
+ the app's window already on screen, and take the connection's arguments
+ when they are known (start()). Until then the connection does not count
+ as open."""
# Where wildos-rdp is; tests point it elsewhere.
native_client = NATIVE_CLIENT
- def __init__(self, on_change, on_auth_failed, log_path, program=None):
+ def __init__(self, on_change, on_auth_failed, log_path, desktop=False):
self.proc = None
self.on_change = on_change
self.on_auth_failed = on_auth_failed
self.log_path = log_path
self.started = None
- self.program = program
+ self.desktop = desktop
self.waiting = False
- @property
- def native(self):
- return (self.program or client_program(native=self.native_client)) == self.native_client
-
@property
def running(self):
return self.proc is not None and self.proc.poll() is None
@@ -258,11 +233,10 @@ class Connection:
def spawn(self, app_id="", title="", icon="", reason="", program="", env=None):
"""Starts wildos-rdp now, the app's window up at once, the
- connection's arguments to follow. False with xfreerdp3, or when a
+ connection's arguments to follow. False for the desktop, or when a
client is already running."""
- if self.running or not self.native:
+ if self.running or self.desktop:
return False
- self.program = self.native_client
self.waiting = True
self._popen([self.native_client, *loading_arguments(app_id, title, icon, reason, program), "/args-from:stdin"], env)
return True
@@ -281,8 +255,7 @@ class Connection:
def start(self, args, password, env=None):
if not (self.waiting and self.running):
self.waiting = False
- self.program = self.program or client_program(native=self.native_client)
- self._popen([self.program, "/args-from:stdin"], env)
+ self._popen([self.native_client, *(["--desktop"] if self.desktop else []), "/args-from:stdin"], env)
self.waiting = False
self.proc.stdin.write(("\n".join(args + [f"/p:{password}"]) + "\n").encode())
self.proc.stdin.close()
@@ -295,7 +268,6 @@ class Connection:
was_open = not self.waiting
self.proc = None
self.waiting = False
- self.program = None
if not was_open:
return
failed = False
diff --git a/packages/wildos-winmode/winmode/setup.py b/packages/wildos-winmode/winmode/setup.py
index 2836924..84a0055 100644
--- a/packages/wildos-winmode/winmode/setup.py
+++ b/packages/wildos-winmode/winmode/setup.py
@@ -30,6 +30,7 @@ import sys
import threading
import time
import urllib.error
+import urllib.parse
import urllib.request
from . import config, firewall, isocheck, msdl, qga, virsh
@@ -121,6 +122,97 @@ class Stopped(Exception):
"""The worker was asked to stop (cancel, or the service is going)."""
+def apt_locked(p):
+ """An apt-get run that stopped because another one, or Settings'
+ updates, held the package lock."""
+ out = (p.stderr or "") + (p.stdout or "")
+ return "Could not get lock" in out or "Unable to acquire" in out or "is held by process" in out
+
+
+# How long a download may sit without a byte before it counts as stopped.
+READ_TIMEOUT = 20
+# While offline: how often to look again, and how often to try the server
+# itself in case NetworkManager's own check is what fails (a network that
+# blocks it).
+OFFLINE_POLL = 3
+OFFLINE_PROBE = 30
+OFFLINE_TEXT = "Waiting for the internet. Setup carries on by itself as soon as you're back online."
+# The units apt-get runs in, outside Windows mode's own service: one that
+# installs, which is always let finish, and one that only refreshes the
+# package lists, which can be stopped at any point.
+APT_UNIT = "wildos-winmode-runtime-install"
+APT_REFRESH_UNIT = "wildos-winmode-apt-refresh"
+APT_LOG = "/run/wildos-winmode-apt.log"
+
+
+def online():
+ """False when NetworkManager says this PC has no working way to the
+ internet: no connection, a sign-in page or limited. When there is no
+ NetworkManager to ask, or it doesn't know, the download decides."""
+ try:
+ from gi.repository import Gio, GLib
+ bus = Gio.bus_get_sync(Gio.BusType.SYSTEM, None)
+ reply = bus.call_sync("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager",
+ "org.freedesktop.DBus.Properties", "Get",
+ GLib.Variant("(ss)", ("org.freedesktop.NetworkManager", "Connectivity")),
+ GLib.VariantType("(v)"), Gio.DBusCallFlags.NONE, 3000, None)
+ # 1 none, 2 portal, 3 limited, 4 full, 0 unknown
+ return reply.unpack()[0] not in (1, 2, 3)
+ except Exception: # noqa: BLE001 (no NetworkManager, or no D-Bus: can't tell)
+ return True
+
+
+def reachable(host, port=443, timeout=5):
+ try:
+ with socket.create_connection((host, port), timeout=timeout):
+ return True
+ except OSError:
+ return False
+
+
+def apt_command(args, unit=APT_UNIT):
+ """apt-get (or dpkg) in a unit of its own. Run as a child of the
+ service, it was killed with it when the service stopped part way (Task
+ Manager, or an update of Windows mode), and dpkg killed mid-install
+ leaves every later install refusing to run, Settings' updates included,
+ until someone runs dpkg --configure -a."""
+ if shutil.which("systemd-run") and os.path.isdir("/run/systemd/system"):
+ return ["systemd-run", "--quiet", "--wait", "--collect", "--service-type=exec", f"--unit={unit}",
+ "--setenv=DEBIAN_FRONTEND=noninteractive", "--setenv=LC_ALL=C.UTF-8",
+ f"--property=StandardOutput=truncate:{APT_LOG}", f"--property=StandardError=append:{APT_LOG}",
+ "--property=Nice=10", "--"] + args
+ return args
+
+
+def dpkg_interrupted(p):
+ out = (p.stderr or "") + (p.stdout or "")
+ return "dpkg was interrupted" in out
+
+
+def apt_progress(line):
+ """A line apt writes to APT::Status-Fd as what setup shows: the part
+ being downloaded or installed and how far through it is, or None."""
+ kind, _, rest = line.partition(":")
+ if kind not in ("dlstatus", "pmstatus"):
+ return None
+ try:
+ pct = int(float(rest.split(":")[1]))
+ except (IndexError, ValueError):
+ return None
+ verb = "Downloading" if kind == "dlstatus" else "Installing"
+ return f"{verb} the parts Windows mode runs on, {max(0, min(100, pct))}%"
+
+
+def latest_apt_progress(text):
+ """The last progress line in apt's output so far, as apt_progress
+ shows it, or None."""
+ for line in reversed(text.splitlines()):
+ shown = apt_progress(line)
+ if shown:
+ return shown
+ return None
+
+
class Problem(Exception):
"""A step failed in a way the person can act on. kind is what board 9.7
shows: download, space, virtualisation or failed. retry is False when
@@ -460,8 +552,15 @@ class Setup:
def rec(self):
return self.svc.state.get("setup") or {}
+ def cancelled(self):
+ """Start over has removed the record: whatever the worker was still
+ finishing must not write a new one."""
+ return self.stop.is_set() and "setup" not in self.svc.state
+
def save(self, **changes):
with self.lock:
+ if self.cancelled():
+ return
rec = dict(self.rec)
rec.update(changes)
self.svc.state["setup"] = rec
@@ -471,6 +570,8 @@ class Setup:
def set_stage(self, stage, state, percent=None, detail=None):
with self.lock:
+ if self.cancelled():
+ return
rec = dict(self.rec)
stages = dict(rec.get("stages") or {})
s = dict(stages.get(stage) or {})
@@ -540,6 +641,12 @@ class Setup:
def start(self, request, owner_uid):
"""Starts setting up from the wizard's request: {licence: {source:
firmware|key|none, key}, options: {...}}. "" or why not."""
+ if self.thread and self.thread.is_alive() and self.stop.is_set():
+ # Start over, straight after: the last worker may still be
+ # finishing a step it can't cut short (installing the runtime).
+ self.thread.join(90)
+ if self.thread.is_alive():
+ return "The last setup is still stopping. Try again in a minute."
if self.thread and self.thread.is_alive():
return "Windows mode is already being set up."
if self.rec.get("running"):
@@ -762,8 +869,13 @@ class Setup:
except Problem as p:
log("problem:", p.kind, p.text)
if p.kind == "download":
- self.save(problem={"kind": "download", "text": p.text,
- "received": (self.rec.get("download") or {}).get("received", 0)}, paused=True)
+ if not online():
+ # Every step that downloads carries on from where it
+ # stopped, so going round again once back online is
+ # the same as resuming.
+ self.wait_online()
+ continue
+ self.save(problem={"kind": "download", "text": p.text}, paused=True)
return
if p.kind == "space":
# Board 9.7: free some space and carry on; nothing failed.
@@ -834,6 +946,29 @@ class Setup:
if self.stop.wait(seconds):
raise Stopped()
+ def wait_online(self, host=None):
+ """Shows board 9.7's Download paused card and waits until the PC is
+ back online, then returns for the step to carry on where it stopped.
+ Pause and Start over work meanwhile; Try again looks at once."""
+ log("offline; waiting for the connection to come back")
+ problem = self.offline_problem()
+ probed = time.monotonic()
+ while True:
+ if self.rec.get("problem") != problem and not self.rec.get("paused"):
+ self.save(problem=problem)
+ self.resume_event.wait(OFFLINE_POLL)
+ self.resume_event.clear()
+ self.check()
+ if online():
+ break
+ if host and time.monotonic() - probed >= OFFLINE_PROBE:
+ probed = time.monotonic()
+ if reachable(host):
+ break
+ log("back online")
+ if (self.rec.get("problem") or {}).get("offline"):
+ self.save(problem=None)
+
def stage_done(self, stage):
"""A stage finished: marked done, and any automatic recovery for it
is over."""
@@ -944,24 +1079,111 @@ class Setup:
raise Problem("space", f"Windows mode needs {size_text(need)} free and this PC has {size_text(free)}.")
def runtime(self):
- """The virtual PC (QEMU, libvirt, FreeRDP) is its own package, which
+ """The virtual PC (QEMU, libvirt, wildos-rdp) is its own package, which
the Wild OS image leaves out so that people who never set up Windows
mode never download it."""
if runtime_installed():
return
- self.set_stage("media", "active", 1, "Getting the parts Windows mode runs on")
+ # No percentage until apt can give a real one: refreshing the package
+ # lists has none, and over Tor it takes minutes.
+ self.set_stage("media", "active", 0, "Getting ready to download the parts Windows mode runs on")
env = dict(os.environ, DEBIAN_FRONTEND="noninteractive", LC_ALL="C.UTF-8")
# Waits out an update that is already installing rather than failing.
apt = ["apt-get", "-o", "DPkg::Lock::Timeout=900", "-o", "Dpkg::Options::=--force-confold"]
- subprocess.run(apt + ["update", "-qq"], env=env, capture_output=True, timeout=900)
- p = subprocess.run(apt + ["install", "-y", "-qq", "--no-install-recommends", "wildos-winmode-runtime"], env=env,
- capture_output=True, text=True, timeout=3600)
+ # One left running by a service that was stopped part way: a refresh
+ # is stopped and done again, an install is let finish rather than
+ # started twice.
+ subprocess.run(["systemctl", "stop", APT_REFRESH_UNIT], capture_output=True)
+ while subprocess.run(["systemctl", "is-active", "--quiet", APT_UNIT]).returncode == 0:
+ self.wait(5)
+ # The lock timeout covers installing, not refreshing the package
+ # lists: while Settings checks for updates the refresh fails at once,
+ # and installing from a fresh install's old lists asks for versions
+ # the repository has since replaced. So the refresh waits its turn.
+ deadline = time.monotonic() + 900
+ while True:
+ p = self.apt(apt + ["update", "-qq"], env, 900, refresh=True)
+ if p.returncode != 0 and not online():
+ raise Problem("download", "Windows mode couldn't download the parts it runs on.")
+ if p.returncode == 0 or not apt_locked(p) or time.monotonic() > deadline:
+ break
+ self.wait(10)
+ if p.returncode != 0:
+ log("apt-get update:", (p.stderr or p.stdout).strip()[-500:])
+ self.check()
+ install = apt + ["install", "-y", "-qq", "--no-install-recommends", "wildos-winmode-runtime"]
+ p = self.apt(install, env, 3600, progress=True)
+ if p.returncode != 0 and dpkg_interrupted(p):
+ # An install cut off part way, by anything: finishing it is what
+ # apt itself asks for, and nothing installs until it's done.
+ log("dpkg was interrupted; finishing what it was doing")
+ self.apt(["dpkg", "--configure", "-a", "--force-confold"], env, 1800)
+ p = self.apt(install, env, 3600, progress=True)
if p.returncode != 0:
log("apt-get:", (p.stderr or p.stdout).strip()[-500:])
- raise Problem("download", "Windows mode couldn't download the parts it runs on. Check you're "
- "online, then carry on.")
+ if apt_locked(p):
+ raise Problem("download", "Wild OS is installing updates. Try again when they've finished.")
+ if dpkg_interrupted(p):
+ raise Problem("failed", "An earlier software install on this PC was left half done, and Windows mode "
+ "couldn't finish it. Send it with Report a problem so we can put it right.",
+ retry=False)
+ raise Problem("download", "Windows mode couldn't download the parts it runs on.")
self.svc.runtime_installed()
+ def apt(self, args, env, timeout, refresh=False, progress=False):
+ """apt-get or dpkg through apt_command, with its output read back
+ from the log the unit writes. apt can take minutes to give up on a
+ connection, so the network is watched meanwhile: offline shows the
+ Download paused card at once, and a refresh of the package lists
+ (refresh, which changes nothing installed) is stopped so setup
+ waits for the connection instead. An install is let finish.
+
+ With progress, apt's own figures for downloading and installing are
+ read from the log as it goes and shown in the stage's line."""
+ name = APT_REFRESH_UNIT if refresh else APT_UNIT
+ if progress:
+ args = args + ["-o", "APT::Status-Fd=1"]
+ cmd = apt_command(args, name)
+ unit = cmd[0] == "systemd-run"
+ proc = subprocess.Popen(cmd, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
+ deadline = time.monotonic() + timeout
+ shown = False
+ last = None
+ while True:
+ try:
+ out, err = proc.communicate(timeout=OFFLINE_POLL)
+ break
+ except subprocess.TimeoutExpired:
+ pass
+ if progress and unit:
+ now = latest_apt_progress(_read(APT_LOG))
+ if now and now != last:
+ last = now
+ self.set_stage("media", "active", 0, now)
+ offline = not online()
+ if offline != shown:
+ shown = offline
+ self.save(problem=self.offline_problem() if offline else None)
+ ended = time.monotonic() > deadline or (refresh and (offline or self.stop.is_set()))
+ if ended:
+ if unit:
+ subprocess.run(["systemctl", "stop", name], capture_output=True)
+ proc.kill()
+ out, err = proc.communicate()
+ break
+ if shown:
+ self.save(problem=None)
+ p = subprocess.CompletedProcess(cmd, proc.returncode, out, err)
+ if unit:
+ p.stdout = _read(APT_LOG)
+ if progress:
+ p.stdout = "\n".join(line for line in (p.stdout or "").splitlines() if apt_progress(line) is None)
+ return p
+
+ def offline_problem(self):
+ received = (self.rec.get("download") or {}).get("received", 0)
+ return {"kind": "download", "offline": True, "received": received, "text": OFFLINE_TEXT}
+
def licence_ready(self):
"""What the install and activate stages read from the licence step:
the key for the answer file, and the firmware table's copy."""
@@ -1146,7 +1368,7 @@ class Setup:
if have:
req.add_header("Range", f"bytes={have}-")
try:
- with urllib.request.urlopen(req, timeout=60) as r:
+ with urllib.request.urlopen(req, timeout=READ_TIMEOUT) as r:
if have and r.status != 206:
have = 0
total = have + int(r.headers.get("Content-Length") or 0)
@@ -1182,11 +1404,16 @@ class Setup:
continue
raise
except (urllib.error.URLError, OSError, socket.timeout) as e:
- tries += 1
log("download:", e)
+ if not online():
+ self.wait_online(urllib.parse.urlsplit(url).hostname)
+ tries = 0
+ continue
+ tries += 1
if tries >= 6:
- raise Problem("download", "The internet connection dropped. Setup carries on when it's back.") from e
- time.sleep(min(60, 5 * tries))
+ raise Problem("download", "The download kept stopping, although this PC is online. "
+ "The server may be busy.") from e
+ self.wait(min(60, 5 * tries))
def virtio_iso(self):
iso = os.path.join(CACHE, "virtio-win.iso")
diff --git a/packages/wildos-winmode/winmode/system.py b/packages/wildos-winmode/winmode/system.py
index 46ae7b2..c6267dd 100644
--- a/packages/wildos-winmode/winmode/system.py
+++ b/packages/wildos-winmode/winmode/system.py
@@ -23,7 +23,7 @@ import time
from gi.repository import Gio, GLib
-from . import config, dbusutil, documents, firewall, guestlink, hostinfo, lifecycle, paths, qga, setup, usb, virsh
+from . import activation, config, dbusutil, documents, firewall, guestlink, hostinfo, lifecycle, paths, qga, setup, usb, virsh
XML = """
<node>
@@ -55,6 +55,10 @@ XML = """
<arg name="icons" type="b" direction="in"/>
<arg type="s" direction="out"/>
</method>
+ <method name="Uninstall">
+ <arg name="path" type="s" direction="in"/>
+ <arg type="s" direction="out"/>
+ </method>
<method name="SetTheme">
<arg name="theme" type="s" direction="in"/>
<arg type="s" direction="out"/>
@@ -87,6 +91,9 @@ XML = """
<arg name="key" type="s" direction="in"/>
<arg type="s" direction="out"/>
</method>
+ <method name="ActivationStart"><arg type="s" direction="out"/></method>
+ <method name="ActivationCheck"><arg type="s" direction="out"/></method>
+ <method name="ActivationEnd"><arg type="s" direction="out"/></method>
<method name="EndProgram">
<arg name="pid" type="u" direction="in"/>
<arg name="image" type="s" direction="in"/>
@@ -270,6 +277,7 @@ class Service:
"Windows": (self.m_windows, "s", True),
"Window": (self.m_window, "s", True),
"Apps": (self.m_apps, "s", True),
+ "Uninstall": (self.m_uninstall, "s", True),
"SetTheme": (self.m_set_theme, "s", True),
"SetOption": (self.m_set_option, "s", True),
"SetWarm": (self.m_set_warm, "s", True),
@@ -282,6 +290,9 @@ class Service:
"SetupControl": (self.m_setup_control, "s", True),
"Firmware": (self.m_firmware, "s", True),
"SetProductKey": (self.m_set_product_key, "s", True),
+ "ActivationStart": (self.m_activation_start, "s", True),
+ "ActivationCheck": (self.m_activation_check, "s", True),
+ "ActivationEnd": (self.m_activation_end, "s", True),
"Remove": (self.m_remove, "s", True),
"UsbDevices": (self.usb.m_devices, "s", True),
"SetUsbDevice": (self.usb.m_set, "s", True),
@@ -294,6 +305,7 @@ class Service:
if not ok:
log("firewall:", why)
self.setup = setup.Setup(self)
+ self.activation = activation.Activation(self, random_password)
self.refresh()
self.setup_changed()
self.setup.resume_after_restart()
@@ -567,6 +579,7 @@ class Service:
self.restart_for_memory()
if st == "running":
self.trim_memory()
+ self.resume_activation_cleanup()
if not self.link.connected:
self.connect_guest()
else:
@@ -750,6 +763,7 @@ class Service:
if warm:
self.link.send(dict(warm, type="warm"))
self.link.request({"type": "windows"}, self.guest_event)
+ self.resume_activation_cleanup()
self.guest_upkeep()
self.changed()
@@ -1242,6 +1256,7 @@ class Service:
"share_root": self.cfg["share_root"],
"folders": self.cfg["folders"],
"setup": self.setup.status(),
+ "activation": self.activation.status(),
}
def m_status(self, sender):
@@ -1487,6 +1502,11 @@ class Service:
def m_apps(self, sender, icons, defer):
return self.guest_request({"type": "apps", "icons": bool(icons)}, defer, 120)
+ def m_uninstall(self, sender, path, defer):
+ """Removes a Store app in Windows, or finds another program's own
+ uninstaller for the agent to open (wild-guest's Uninstall.cs)."""
+ return self.guest_request({"type": "uninstall", "path": path}, defer, 200)
+
def m_set_theme(self, sender, theme_json):
try:
theme = json.loads(theme_json)
@@ -1668,6 +1688,88 @@ class Service:
dbusutil.in_thread(work, done=finished)
return defer
+ def m_activation_start(self, sender, defer):
+ """Settings' Use a licence on my Microsoft account (activation.py):
+ Windows woken, the account for it made and the policy lifted.
+ {account, password, domain} for the desktop, or {message}."""
+ why = self.claim(sender)
+ if why:
+ return json.dumps({"message": why})
+ if self.activation.ending:
+ return json.dumps({"message": "The last activation is still being tidied up. Try again in a minute."})
+ self.life.hold(time.monotonic(), activation.HOLD, True)
+ self.schedule_idle()
+
+ def work():
+ while self.busy_action:
+ time.sleep(0.1)
+ try:
+ self.wake()
+ except (RuntimeError, virsh.VirshError) as e:
+ log("waking Windows for activation:", e)
+ return {"message": "Windows mode couldn't start Windows. Try again, or restart the PC."}
+ return self.activation.start()
+
+ def finished(result):
+ if isinstance(result, Exception):
+ log("activation:", result)
+ result = {"message": "Windows mode couldn't add the account for activating. Try again, or restart the PC."}
+ if "password" in result:
+ result["domain"] = self.cfg["computer_name"] or self.state.get("computer_name", "")
+ else:
+ self.life.hold(time.monotonic(), activation.HOLD, False)
+ self.schedule_idle()
+ self.refresh()
+ self.changed()
+ defer.done(json.dumps(result))
+
+ dbusutil.in_thread(work, done=finished)
+ return defer
+
+ def m_activation_check(self, sender, defer):
+ why = self.claim(sender)
+ if why:
+ return json.dumps({"activated": False, "active": False})
+ dbusutil.in_thread(self.activation.check, done=lambda r: (self.changed(), defer.done(json.dumps({
+ "activated": r is True, "active": bool(self.activation.rec)})))[1])
+ return defer
+
+ def m_activation_end(self, sender, defer):
+ """Done or Cancel, the desktop closing, or Windows saying it is
+ activated: "" once the account is gone and the policy is back."""
+ why = self.claim(sender)
+ if why:
+ return why
+ self.end_activation(defer.done)
+ return defer
+
+ def end_activation(self, done=None):
+ def work():
+ while self.activation.ending:
+ time.sleep(0.2)
+ return self.activation.end()
+
+ def finished(result):
+ if isinstance(result, Exception):
+ log("activation clean-up:", result)
+ result = "Windows mode couldn't remove the account for activating yet. It tries again by itself."
+ if not self.activation.rec:
+ self.life.hold(time.monotonic(), activation.HOLD, False)
+ self.schedule_idle()
+ self.changed()
+ if done:
+ done(result)
+
+ dbusutil.in_thread(work, done=finished)
+
+ def resume_activation_cleanup(self):
+ """An activation this run of the service didn't start (Wild OS or
+ Windows mode restarted part way), or one past its hour: the account
+ goes and the policy comes back as soon as Windows runs."""
+ if self.activation.needs_cleanup() and not self.busy_action:
+ log("finishing the clean-up after activating with a Microsoft account")
+ self.end_activation()
+
def m_firmware(self, sender, defer):
"""Board 9.1's licence row: whether this PC's firmware has a key and
Windows is still on its disks. The key itself never leaves here."""