Initial commit: FlatKontrol, a Kirigami Flatpak permissions manager

A KDE/Qt application to review and edit the permissions of installed
Flatpak applications, editing the same override files as Flatpak itself.
Covers shared subsystems, sockets, devices, features, filesystem access,
persistent paths, environment variables, D-Bus policies and portals.

Includes a Flatpak manifest and a CI workflow that publishes a bundle and
a hosted Flatpak repository on tagged releases.
This commit is contained in:
2026-06-30 19:31:10 -05:00
commit 3b639115c8
26 changed files with 4086 additions and 0 deletions
+43
View File
@@ -0,0 +1,43 @@
# SPDX-License-Identifier: GPL-3.0-or-later
add_executable(flatkontrol
main.cpp
keyfile.cpp
flatpakinstallations.cpp
portalsbackend.cpp
permissioncatalog.cpp
)
qt_add_qml_module(flatkontrol
URI io.github.toservetheking.FlatKontrol
VERSION 1.0
RESOURCE_PREFIX /qt/qml
QML_FILES
qml/Main.qml
qml/PermissionsPage.qml
SOURCES
applicationsmodel.cpp
applicationsmodel.h
permissionscontroller.cpp
permissionscontroller.h
)
target_include_directories(flatkontrol PRIVATE ${CMAKE_BINARY_DIR})
target_link_libraries(flatkontrol PRIVATE
Qt6::Core
Qt6::Gui
Qt6::Widgets
Qt6::Qml
Qt6::Quick
Qt6::QuickControls2
Qt6::DBus
KF6::I18n
KF6::I18nQml
KF6::CoreAddons
KF6::IconThemes
KF6::Crash
KF6::DBusAddons
)
install(TARGETS flatkontrol ${KDE_INSTALL_TARGETS_DEFAULT_ARGS})
+90
View File
@@ -0,0 +1,90 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include "applicationsmodel.h"
#include <KDirWatch>
#include <KLocalizedString>
ApplicationsModel::ApplicationsModel(QObject *parent)
: QAbstractListModel(parent)
, m_watch(new KDirWatch(this))
{
refresh();
const QStringList dirs = m_installations.appDirsToWatch();
for (const QString &dir : dirs) {
m_watch->addDir(dir, KDirWatch::WatchDirOnly);
}
connect(m_watch, &KDirWatch::dirty, this, &ApplicationsModel::refresh);
connect(m_watch, &KDirWatch::created, this, &ApplicationsModel::refresh);
connect(m_watch, &KDirWatch::deleted, this, &ApplicationsModel::refresh);
}
void ApplicationsModel::refresh()
{
beginResetModel();
m_apps.clear();
AppInfo global;
global.appId = QStringLiteral("global");
global.name = i18n("All Applications");
global.iconSource = QStringLiteral("preferences-desktop-default-applications");
m_apps.append(global);
const QStringList ids = m_installations.listApplications();
for (const QString &id : ids) {
m_apps.append(m_installations.appInfo(id));
}
endResetModel();
Q_EMIT countChanged();
}
int ApplicationsModel::rowCount(const QModelIndex &parent) const
{
if (parent.isValid()) {
return 0;
}
return m_apps.size();
}
QVariant ApplicationsModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid() || index.row() < 0 || index.row() >= m_apps.size()) {
return {};
}
const AppInfo &app = m_apps.at(index.row());
switch (role) {
case AppIdRole:
return app.appId;
case NameRole:
return app.name;
case IconSourceRole:
return app.iconSource;
case IsGlobalRole:
return app.appId == QStringLiteral("global");
default:
return {};
}
}
QHash<int, QByteArray> ApplicationsModel::roleNames() const
{
return {
{AppIdRole, "appId"},
{NameRole, "name"},
{IconSourceRole, "iconSource"},
{IsGlobalRole, "isGlobal"},
};
}
QVariantMap ApplicationsModel::infoFor(const QString &appId) const
{
const AppInfo info = m_installations.appInfo(appId);
return {
{QStringLiteral("appId"), info.appId},
{QStringLiteral("name"), info.name},
{QStringLiteral("iconSource"), info.iconSource},
{QStringLiteral("version"), info.version},
{QStringLiteral("runtime"), info.runtime},
};
}
+51
View File
@@ -0,0 +1,51 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include "flatpakinstallations.h"
#include <QAbstractListModel>
#include <QList>
#include <QQmlEngine>
class KDirWatch;
/**
* Sidebar model of installed flatpak applications. The first row is the special
* "All Applications" entry (app id "global") that edits the global override file.
* Refreshes automatically when applications are installed or removed.
*/
class ApplicationsModel : public QAbstractListModel
{
Q_OBJECT
QML_ELEMENT
Q_PROPERTY(int count READ rowCount NOTIFY countChanged)
public:
enum Roles {
AppIdRole = Qt::UserRole + 1,
NameRole,
IconSourceRole,
IsGlobalRole,
};
explicit ApplicationsModel(QObject *parent = nullptr);
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role) const override;
QHash<int, QByteArray> roleNames() const override;
/// Look up the AppInfo for an app id (for the details sheet etc.).
Q_INVOKABLE QVariantMap infoFor(const QString &appId) const;
public Q_SLOTS:
void refresh();
Q_SIGNALS:
void countChanged();
private:
FlatpakInstallations m_installations;
QList<AppInfo> m_apps;
KDirWatch *m_watch = nullptr;
};
+255
View File
@@ -0,0 +1,255 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include "flatpakinstallations.h"
#include "keyfile.h"
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QStandardPaths>
#include <QXmlStreamReader>
#include <algorithm>
FlatpakInstallations::FlatpakInstallations()
{
// User installation.
m_userPath = envOr("FLATPAK_USER_DIR", QString());
if (m_userPath.isEmpty()) {
QString dataHome = qEnvironmentVariable("XDG_DATA_HOME");
if (dataHome.isEmpty()) {
dataHome = QDir::homePath() + QStringLiteral("/.local/share");
}
m_userPath = dataHome + QStringLiteral("/flatpak");
}
// System installation.
const QString systemPath = envOr("FLATPAK_SYSTEM_DIR", QStringLiteral("/var/lib/flatpak"));
// Priority: custom (highest priority first), then user, then system.
m_paths = customInstallationPaths();
m_paths.prepend(m_userPath);
m_paths.append(systemPath);
}
QString FlatpakInstallations::envOr(const char *name, const QString &fallback)
{
const QString v = qEnvironmentVariable(name);
return v.isEmpty() ? fallback : v;
}
QStringList FlatpakInstallations::customInstallationPaths() const
{
const QString configPath = envOr("FLATPAK_CONFIG_DIR", QStringLiteral("/etc/flatpak"));
const QString dirPath = configPath + QStringLiteral("/installations.d");
QDir dir(dirPath);
if (!dir.exists()) {
return {};
}
struct Entry {
QString path;
int priority;
};
QList<Entry> entries;
const QStringList files = dir.entryList(QDir::Files, QDir::Name);
for (const QString &f : files) {
KeyFile kf;
if (!kf.load(dir.absoluteFilePath(f))) {
continue;
}
for (const QString &group : kf.groups()) {
if (!kf.hasKey(group, QStringLiteral("Path"))) {
continue;
}
const QString path = kf.value(group, QStringLiteral("Path"));
const int priority = kf.value(group, QStringLiteral("Priority"), QStringLiteral("0")).toInt();
entries.append({path, priority});
}
}
std::stable_sort(entries.begin(), entries.end(), [](const Entry &a, const Entry &b) {
return a.priority > b.priority;
});
QStringList paths;
for (const Entry &e : entries) {
paths.append(e.path);
}
return paths;
}
QStringList FlatpakInstallations::appDirsToWatch() const
{
QStringList dirs;
for (const QString &p : m_paths) {
dirs.append(p + QStringLiteral("/app"));
}
return dirs;
}
QStringList FlatpakInstallations::listApplications() const
{
QStringList result;
for (const QString &installation : m_paths) {
QDir appDir(installation + QStringLiteral("/app"));
if (!appDir.exists()) {
continue;
}
const QStringList ids = appDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot, QDir::Name);
for (const QString &id : ids) {
if (id.endsWith(QStringLiteral(".BaseApp"))) {
continue;
}
const QString active = appDir.absoluteFilePath(id) + QStringLiteral("/current/active");
if (QFileInfo::exists(active) && !result.contains(id)) {
result.append(id);
}
}
}
result.sort();
return result;
}
QString FlatpakInstallations::bundlePath(const QString &appId) const
{
for (const QString &installation : m_paths) {
const QString candidate = installation + QStringLiteral("/app/") + appId + QStringLiteral("/current/active");
if (QFileInfo::exists(candidate)) {
return candidate;
}
}
return QString();
}
QString FlatpakInstallations::metadataPath(const QString &appId) const
{
const QString bundle = bundlePath(appId);
if (bundle.isEmpty()) {
return QString();
}
return bundle + QStringLiteral("/metadata");
}
QString FlatpakInstallations::prettifyAppId(const QString &appId)
{
const QString last = appId.section(QLatin1Char('.'), -1);
if (last.isEmpty()) {
return appId;
}
return last.left(1).toUpper() + last.mid(1);
}
QString FlatpakInstallations::readMetainfoName(const QString &bundle, const QString &appId) const
{
QStringList candidates = {
bundle + QStringLiteral("/files/share/metainfo/") + appId + QStringLiteral(".metainfo.xml"),
bundle + QStringLiteral("/files/share/appdata/") + appId + QStringLiteral(".appdata.xml"),
};
for (const QString &path : candidates) {
QFile file(path);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
continue;
}
QXmlStreamReader xml(&file);
while (!xml.atEnd()) {
xml.readNext();
if (xml.isStartElement() && xml.name() == QLatin1String("name")) {
// Skip translated <name xml:lang="..."> entries; take the C locale one.
if (xml.attributes().hasAttribute(QStringLiteral("xml:lang"))) {
continue;
}
const QString name = xml.readElementText().trimmed();
if (!name.isEmpty()) {
return name;
}
}
}
}
return QString();
}
QString FlatpakInstallations::iconForApp(const QString &appId, const QString &bundle) const
{
// Resolve the icon name from the exported desktop entry, then look for a
// matching file under the bundle's exported icons; fall back to the themed name.
QString iconName = appId;
const QString desktopPath = bundle + QStringLiteral("/export/share/applications/") + appId + QStringLiteral(".desktop");
KeyFile desktop;
if (desktop.load(desktopPath)) {
const QString fromEntry = desktop.value(QStringLiteral("Desktop Entry"), QStringLiteral("Icon"));
if (!fromEntry.isEmpty()) {
iconName = fromEntry;
}
}
// If the icon name is already an absolute path, use it directly.
if (QFileInfo(iconName).isAbsolute() && QFileInfo::exists(iconName)) {
return iconName;
}
const QString iconsRoot = bundle + QStringLiteral("/export/share/icons/hicolor");
static const QStringList sizes = {
QStringLiteral("scalable"),
QStringLiteral("512x512"),
QStringLiteral("256x256"),
QStringLiteral("128x128"),
QStringLiteral("96x96"),
QStringLiteral("64x64"),
QStringLiteral("48x48"),
};
static const QStringList exts = {QStringLiteral("svg"), QStringLiteral("png")};
for (const QString &size : sizes) {
for (const QString &ext : exts) {
const QString candidate = iconsRoot + QLatin1Char('/') + size + QStringLiteral("/apps/") + iconName + QLatin1Char('.') + ext;
if (QFileInfo::exists(candidate)) {
return candidate;
}
}
}
return iconName.isEmpty() ? QStringLiteral("application-x-executable") : iconName;
}
AppInfo FlatpakInstallations::appInfo(const QString &appId) const
{
AppInfo info;
info.appId = appId;
info.name = prettifyAppId(appId);
info.iconSource = QStringLiteral("application-x-executable");
info.runtime = QStringLiteral("Unknown");
info.version = QStringLiteral("Unknown");
const QString bundle = bundlePath(appId);
if (bundle.isEmpty()) {
return info;
}
const QString name = readMetainfoName(bundle, appId);
if (!name.isEmpty()) {
info.name = name;
}
info.iconSource = iconForApp(appId, bundle);
KeyFile metadata;
if (metadata.load(bundle + QStringLiteral("/metadata"))) {
const QString rt = metadata.value(QStringLiteral("Application"), QStringLiteral("runtime"));
if (!rt.isEmpty()) {
info.runtime = rt;
}
}
return info;
}
QString FlatpakInstallations::overridePath(const QString &appId) const
{
return m_userPath + QStringLiteral("/overrides/") + appId;
}
QString FlatpakInstallations::globalOverridePath() const
{
return m_userPath + QStringLiteral("/overrides/global");
}
+73
View File
@@ -0,0 +1,73 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include <QString>
#include <QStringList>
/**
* Plain per-application display/metadata, gathered from the bundle on disk.
*/
struct AppInfo {
QString appId;
QString name; // human readable, falls back to a prettified app id
QString iconSource; // absolute file path or a themed icon name
QString version;
QString runtime;
};
/**
* Locates flatpak installations and applications purely by scanning the
* filesystem - the same approach Flatseal takes (no libflatpak linkage).
*
* Installation priority order mirrors Flatseal: custom installations (from
* /etc/flatpak/installations.d, highest Priority first), then the user
* installation, then the system installation.
*/
class FlatpakInstallations
{
public:
FlatpakInstallations();
/// Installation roots in priority order (e.g. ~/.local/share/flatpak).
QStringList installationPaths() const
{
return m_paths;
}
/// The user installation root - where per-app overrides are written.
QString userInstallation() const
{
return m_userPath;
}
/// The "app" directories that should be watched for install/uninstall.
QStringList appDirsToWatch() const;
/// Sorted, de-duplicated list of installed application ids (BaseApps filtered out).
QStringList listApplications() const;
/// "<installation>/app/<id>/current/active" for the first installation that has it.
QString bundlePath(const QString &appId) const;
/// Path to the bundle's "metadata" keyfile (baseline permissions).
QString metadataPath(const QString &appId) const;
/// Gather display info (name/icon/version/runtime) for an app.
AppInfo appInfo(const QString &appId) const;
/// Path of the user override file for an app id ("global" is the special id).
QString overridePath(const QString &appId) const;
/// Path of the global override file.
QString globalOverridePath() const;
static QString prettifyAppId(const QString &appId);
private:
static QString envOr(const char *name, const QString &fallback);
QStringList customInstallationPaths() const;
QString iconForApp(const QString &appId, const QString &bundle) const;
QString readMetainfoName(const QString &bundle, const QString &appId) const;
QStringList m_paths;
QString m_userPath;
};
+128
View File
@@ -0,0 +1,128 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include "keyfile.h"
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QSaveFile>
#include <QTextStream>
bool KeyFile::load(const QString &path)
{
m_groupOrder.clear();
m_groups.clear();
QFile file(path);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
return false;
}
QTextStream in(&file);
in.setEncoding(QStringConverter::Utf8);
QString currentGroup;
while (!in.atEnd()) {
QString line = in.readLine();
const QString trimmed = line.trimmed();
if (trimmed.isEmpty() || trimmed.startsWith(QLatin1Char('#'))) {
continue;
}
if (trimmed.startsWith(QLatin1Char('[')) && trimmed.endsWith(QLatin1Char(']'))) {
currentGroup = trimmed.mid(1, trimmed.length() - 2);
if (!m_groups.contains(currentGroup)) {
m_groupOrder.append(currentGroup);
m_groups.insert(currentGroup, Group{});
}
continue;
}
const int eq = trimmed.indexOf(QLatin1Char('='));
if (eq < 0 || currentGroup.isEmpty()) {
continue;
}
// Note: flatpak/GKeyFile allow "key[locale]=" but flatpak override files
// never use locales, so a plain key split is correct here.
const QString key = trimmed.left(eq).trimmed();
const QString val = trimmed.mid(eq + 1).trimmed();
setValue(currentGroup, key, val);
}
return true;
}
bool KeyFile::save(const QString &path) const
{
QFileInfo info(path);
QDir().mkpath(info.absolutePath());
QSaveFile file(path);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
return false;
}
QTextStream out(&file);
out.setEncoding(QStringConverter::Utf8);
bool firstGroup = true;
for (const QString &group : m_groupOrder) {
const Group &g = m_groups.value(group);
if (g.keyOrder.isEmpty()) {
continue;
}
if (!firstGroup) {
out << '\n';
}
firstGroup = false;
out << '[' << group << "]\n";
for (const QString &key : g.keyOrder) {
out << key << '=' << g.values.value(key) << '\n';
}
}
return file.commit();
}
bool KeyFile::isEmpty() const
{
for (const QString &group : m_groupOrder) {
if (!m_groups.value(group).keyOrder.isEmpty()) {
return false;
}
}
return true;
}
QStringList KeyFile::keys(const QString &group) const
{
return m_groups.value(group).keyOrder;
}
bool KeyFile::hasKey(const QString &group, const QString &key) const
{
return m_groups.contains(group) && m_groups.value(group).values.contains(key);
}
QString KeyFile::value(const QString &group, const QString &key, const QString &fallback) const
{
if (!m_groups.contains(group)) {
return fallback;
}
const Group &g = m_groups.value(group);
return g.values.value(key, fallback);
}
void KeyFile::setValue(const QString &group, const QString &key, const QString &value)
{
if (!m_groups.contains(group)) {
m_groupOrder.append(group);
m_groups.insert(group, Group{});
}
Group &g = m_groups[group];
if (!g.values.contains(key)) {
g.keyOrder.append(key);
}
g.values[key] = value;
}
+55
View File
@@ -0,0 +1,55 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include <QMap>
#include <QString>
#include <QStringList>
/**
* A minimal, GKeyFile/flatpak-compatible INI reader/writer.
*
* We deliberately avoid KConfig here: flatpak parses these files with GLib's
* GKeyFile, and we want byte-for-byte compatible output (no value escaping,
* spaces in group names like "Session Bus Policy", ';'-separated lists, and
* keys containing dots such as D-Bus well-known names). KConfig would re-escape
* and normalise the file in ways flatpak does not expect.
*
* Group insertion order and key insertion order are preserved.
*/
class KeyFile
{
public:
KeyFile() = default;
/// Parse from disk. Returns false if the file does not exist / cannot be read.
bool load(const QString &path);
/// Serialise to disk (creating parent dirs). Returns false on write failure.
bool save(const QString &path) const;
bool isEmpty() const;
QStringList groups() const
{
return m_groupOrder;
}
bool hasGroup(const QString &group) const
{
return m_groups.contains(group);
}
QStringList keys(const QString &group) const;
bool hasKey(const QString &group, const QString &key) const;
/// Raw value for group/key, or \a fallback when absent.
QString value(const QString &group, const QString &key, const QString &fallback = QString()) const;
void setValue(const QString &group, const QString &key, const QString &value);
private:
struct Group {
QStringList keyOrder;
QMap<QString, QString> values;
};
QStringList m_groupOrder;
QMap<QString, Group> m_groups;
};
+165
View File
@@ -0,0 +1,165 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include "flatkontrol-version.h"
#include "applicationsmodel.h"
#include "permissionscontroller.h"
#include <KAboutData>
#include <KCrash>
#include <KIconTheme>
#include <KLocalizedQmlContext>
#include <KLocalizedString>
#include <QApplication>
#include <QCommandLineParser>
#include <QDebug>
#include <QDir>
#include <QFile>
#include <QIcon>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QQuickStyle>
#include <QTextStream>
using namespace Qt::Literals::StringLiterals;
// Filter out a single, well-known benign framework artifact: Qt Quick emits
// "Created graphical object was not placed in the graphics scene" while Kirigami's
// PageRow incubates pages. It fires even for a trivial empty page, is harmless,
// and cannot be avoided from application code. Everything else is passed through.
static QtMessageHandler s_defaultMessageHandler = nullptr;
static void messageHandler(QtMsgType type, const QMessageLogContext &context, const QString &message)
{
// Qt Quick emits this while Kirigami's PageRow incubates pages. It fires even
// for a trivial empty page, is harmless, and cannot be avoided from app code.
if (message.contains(QLatin1String("was not placed in the graphics scene"))) {
return;
}
// Malformed path data in third-party icon SVGs (system/app icon themes) is not
// actionable from here; drop the noise rather than spam every render.
if (context.category && qstrcmp(context.category, "qt.svg") == 0) {
return;
}
// Qt's Wayland integration tries to self-register with xdg-desktop-portal for
// optional desktop features (global shortcuts, background). It is unrelated to
// our PermissionStore client use and fires harmlessly on hosts where portal
// app-info resolution is finicky.
if (message.contains(QLatin1String("Failed to register with host portal"))) {
return;
}
if (s_defaultMessageHandler) {
s_defaultMessageHandler(type, context, message);
}
}
// Headless verification helper: --selftest <app-id> [--write]
static int runSelfTest(const QString &appId, bool doWrite)
{
QTextStream out(stdout);
ApplicationsModel apps;
out << "Applications found: " << apps.rowCount() << Qt::endl;
for (int i = 0; i < qMin(apps.rowCount(), 6); ++i) {
const QModelIndex idx = apps.index(i);
out << " - " << apps.data(idx, ApplicationsModel::AppIdRole).toString() << " / " << apps.data(idx, ApplicationsModel::NameRole).toString() << Qt::endl;
}
PermissionsController c;
c.setAppId(appId);
out << "\nLoaded " << appId << " => " << c.appName() << " | version " << c.appVersion() << " | runtime " << c.appRuntime() << Qt::endl;
out << "Rows: " << c.rowCount() << " modified: " << c.modified() << Qt::endl;
int shareNetworkRow = -1;
for (int i = 0; i < c.rowCount(); ++i) {
const QModelIndex idx = c.index(i);
const int kind = c.data(idx, PermissionsController::RowTypeRole).toInt();
const QString catId = c.data(idx, PermissionsController::CategoryIdRole).toString();
if (kind == PermissionsController::Toggle) {
out << " [" << catId << "] toggle " << c.data(idx, PermissionsController::OptionKeyRole).toString() << " = " << c.data(idx, PermissionsController::ValueRole).toBool()
<< " status=" << c.data(idx, PermissionsController::StatusRole).toInt() << Qt::endl;
} else if (kind == PermissionsController::PathEntry || kind == PermissionsController::RelativePathEntry) {
out << " [" << catId << "] path '" << c.data(idx, PermissionsController::ValueRole).toString() << "' status=" << c.data(idx, PermissionsController::StatusRole).toInt() << Qt::endl;
} else if (kind == PermissionsController::VariableEntry || kind == PermissionsController::BusEntry) {
out << " [" << catId << "] entry '" << c.data(idx, PermissionsController::ValueRole).toString() << "' = '" << c.data(idx, PermissionsController::SecondaryRole).toString()
<< "' status=" << c.data(idx, PermissionsController::StatusRole).toInt() << Qt::endl;
}
if (catId == u"share"_s && c.data(idx, PermissionsController::OptionKeyRole).toString() == u"network"_s) {
shareNetworkRow = i;
}
}
if (doWrite && shareNetworkRow >= 0) {
const QString path = QDir::homePath() + u"/.local/share/flatpak/overrides/"_s + appId;
const bool current = c.data(c.index(shareNetworkRow), PermissionsController::ValueRole).toBool();
out << "\nToggling share=network from " << current << " to " << !current << Qt::endl;
c.setToggleValue(shareNetworkRow, !current);
out << "modified now: " << c.modified() << Qt::endl;
c.save();
out << "Saved. modified after save: " << c.modified() << Qt::endl;
out << "--- override file contents (" << path << ") ---" << Qt::endl;
QFile f(path);
if (f.open(QIODevice::ReadOnly | QIODevice::Text)) {
out << QString::fromUtf8(f.readAll()).trimmed() << Qt::endl;
f.close();
} else {
out << "(no file)" << Qt::endl;
}
out << "--- resetting (removes overrides) ---" << Qt::endl;
c.reset();
out << "After reset, file exists: " << QFile::exists(path) << Qt::endl;
}
out.flush();
return 0;
}
int main(int argc, char *argv[])
{
s_defaultMessageHandler = qInstallMessageHandler(messageHandler);
if (argc >= 3 && QString::fromLatin1(argv[1]) == u"--selftest"_s) {
QCoreApplication app(argc, argv);
const bool doWrite = QCoreApplication::arguments().contains(u"--write"_s);
return runSelfTest(QString::fromLatin1(argv[2]), doWrite);
}
KIconTheme::initTheme();
QApplication app(argc, argv);
KLocalizedString::setApplicationDomain(QByteArrayLiteral("flatkontrol"));
QCoreApplication::setOrganizationName(u"toservetheking"_s);
if (qEnvironmentVariableIsEmpty("QT_QUICK_CONTROLS_STYLE")) {
QQuickStyle::setStyle(u"org.kde.desktop"_s);
QQuickStyle::setFallbackStyle(u"Fusion"_s);
}
KAboutData aboutData(u"flatkontrol"_s,
i18nc("@title", "FlatKontrol"),
QStringLiteral(FLATKONTROL_VERSION_STRING),
i18n("Manage Flatpak permissions, the KDE way"),
KAboutLicense::GPL_V3,
i18n("© 2026 FlatKontrol contributors"));
aboutData.addAuthor(u"toservetheking"_s, i18nc("@label", "Author"), u"[email protected]"_s);
aboutData.setDesktopFileName(u"io.github.toservetheking.FlatKontrol"_s);
KAboutData::setApplicationData(aboutData);
QApplication::setWindowIcon(QIcon::fromTheme(u"io.github.toservetheking.FlatKontrol"_s, QIcon::fromTheme(u"preferences-desktop"_s)));
KCrash::initialize();
QCommandLineParser parser;
aboutData.setupCommandLine(&parser);
parser.process(app);
aboutData.processCommandLine(&parser);
QQmlApplicationEngine engine;
KLocalization::setupLocalizedContext(&engine);
engine.loadFromModule("io.github.toservetheking.FlatKontrol", u"Main"_s);
if (engine.rootObjects().isEmpty()) {
return -1;
}
return app.exec();
}
+148
View File
@@ -0,0 +1,148 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include "permissioncatalog.h"
#include <KLocalizedString>
namespace FlatKontrol
{
const QList<CategoryDef> &catalog()
{
static const QList<CategoryDef> cats = {
{
QStringLiteral("share"),
i18nc("@title permission section", "Share"),
i18n("Subsystems shared with the host system"),
QStringLiteral("Context"),
QStringLiteral("shared"),
RowType::Toggle,
{
{QStringLiteral("network"), i18n("Network"), QStringLiteral("share=network")},
{QStringLiteral("ipc"), i18n("Inter-process communication"), QStringLiteral("share=ipc")},
},
},
{
QStringLiteral("sockets"),
i18nc("@title permission section", "Socket"),
i18n("Well-known sockets available in the sandbox"),
QStringLiteral("Context"),
QStringLiteral("sockets"),
RowType::Toggle,
{
{QStringLiteral("x11"), i18n("X11 windowing system"), QStringLiteral("socket=x11")},
{QStringLiteral("fallback-x11"), i18n("Fallback to X11 windowing system"), QStringLiteral("socket=fallback-x11")},
{QStringLiteral("wayland"), i18n("Wayland windowing system"), QStringLiteral("socket=wayland")},
{QStringLiteral("inherit-wayland-socket"), i18n("Inherited Wayland socket"), QStringLiteral("socket=inherit-wayland-socket")},
{QStringLiteral("pulseaudio"), i18n("PulseAudio sound server"), QStringLiteral("socket=pulseaudio")},
{QStringLiteral("session-bus"), i18n("D-Bus session bus"), QStringLiteral("socket=session-bus")},
{QStringLiteral("system-bus"), i18n("D-Bus system bus"), QStringLiteral("socket=system-bus")},
{QStringLiteral("ssh-auth"), i18n("Secure Shell agent"), QStringLiteral("socket=ssh-auth")},
{QStringLiteral("pcsc"), i18n("Smart cards"), QStringLiteral("socket=pcsc")},
{QStringLiteral("cups"), i18n("Printing system"), QStringLiteral("socket=cups")},
{QStringLiteral("gpg-agent"), i18n("GPG agent"), QStringLiteral("socket=gpg-agent")},
},
},
{
QStringLiteral("devices"),
i18nc("@title permission section", "Device"),
i18n("Device files available in the sandbox"),
QStringLiteral("Context"),
QStringLiteral("devices"),
RowType::Toggle,
{
{QStringLiteral("dri"), i18n("GPU acceleration"), QStringLiteral("device=dri")},
{QStringLiteral("input"), i18n("Input devices"), QStringLiteral("device=input")},
{QStringLiteral("kvm"), i18n("Virtualization"), QStringLiteral("device=kvm")},
{QStringLiteral("shm"), i18n("Shared memory"), QStringLiteral("device=shm")},
{QStringLiteral("usb"), i18n("USB devices"), QStringLiteral("device=usb")},
{QStringLiteral("all"), i18n("All devices (e.g. webcam)"), QStringLiteral("device=all")},
},
},
{
QStringLiteral("features"),
i18nc("@title permission section", "Features"),
i18n("Extra features available to the application"),
QStringLiteral("Context"),
QStringLiteral("features"),
RowType::Toggle,
{
{QStringLiteral("devel"), i18n("Development syscalls (e.g. ptrace)"), QStringLiteral("feature=devel")},
{QStringLiteral("multiarch"), i18n("Programs from other architectures"), QStringLiteral("feature=multiarch")},
{QStringLiteral("bluetooth"), i18n("Bluetooth"), QStringLiteral("feature=bluetooth")},
{QStringLiteral("canbus"), i18n("Controller Area Network bus"), QStringLiteral("feature=canbus")},
{QStringLiteral("per-app-dev-shm"), i18n("Application shared memory"), QStringLiteral("feature=per-app-dev-shm")},
},
},
{
QStringLiteral("filesystems-presets"),
i18nc("@title permission section", "Filesystem"),
i18n("Predefined filesystem subsets available to the application"),
QStringLiteral("Context"),
QStringLiteral("filesystems"),
RowType::Toggle,
{
{QStringLiteral("host"), i18n("All system files"), QStringLiteral("filesystem=host")},
{QStringLiteral("host-os"), i18n("All system libraries, executables and static data"), QStringLiteral("filesystem=host-os")},
{QStringLiteral("host-etc"), i18n("All system configuration"), QStringLiteral("filesystem=host-etc")},
{QStringLiteral("home"), i18n("All user files"), QStringLiteral("filesystem=home")},
},
},
{
QStringLiteral("filesystems-other"),
i18nc("@title permission section", "Other files"),
i18n("Other filesystem paths available to the application"),
QStringLiteral("Context"),
QStringLiteral("filesystems"),
RowType::PathEntry,
{},
},
{
QStringLiteral("persistent"),
i18nc("@title permission section", "Persistent"),
i18n("Home-relative paths created inside the sandbox"),
QStringLiteral("Context"),
QStringLiteral("persistent"),
RowType::RelativePathEntry,
{},
},
{
QStringLiteral("environment"),
i18nc("@title permission section", "Environment"),
i18n("Variables exported to the application"),
QStringLiteral("Environment"),
QString(),
RowType::VariableEntry,
{},
},
{
QStringLiteral("session-bus"),
i18nc("@title permission section", "Session Bus"),
i18n("Well-known names on the session bus"),
QStringLiteral("Session Bus Policy"),
QString(),
RowType::BusEntry,
{},
},
{
QStringLiteral("system-bus"),
i18nc("@title permission section", "System Bus"),
i18n("Well-known names on the system bus"),
QStringLiteral("System Bus Policy"),
QString(),
RowType::BusEntry,
{},
},
{
QStringLiteral("portals"),
i18nc("@title permission section", "Portals"),
i18n("Resources selectively granted through portals"),
QString(),
QString(),
RowType::Portal,
{},
},
};
return cats;
}
} // namespace FlatKontrol
+54
View File
@@ -0,0 +1,54 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include <QList>
#include <QString>
namespace FlatKontrol
{
/// Where a permission's current value comes from (drives the status badge).
enum class Status {
Original = 0, // baseline, from the app's metadata
Global = 1, // from the global override file
User = 2, // from the per-app override file
};
/// The kind of delegate a permission row should be rendered with.
enum class RowType {
Toggle = 0, // boolean switch (share/sockets/devices/features/filesystem presets)
PathEntry = 1, // free-form filesystem path (with optional :ro/:rw/:create)
RelativePathEntry = 2, // home-relative persistent path
VariableEntry = 3, // KEY + VALUE environment variable
BusEntry = 4, // D-Bus name + talk/own policy
Portal = 5, // tri-state portal permission (unset/allowed/disallowed)
};
/// A single fixed toggle within a category (e.g. "network" within Share).
struct OptionDef {
QString option;
QString label;
QString example;
};
/// A category groups related permissions under one FormCard section.
struct CategoryDef {
QString id; // stable id, e.g. "share"
QString title; // section header, e.g. "Share"
QString description;
QString group; // keyfile group, e.g. "Context"
QString key; // keyfile key, e.g. "shared" (empty for key-per-entry groups)
RowType type;
QList<OptionDef> options; // populated only for Toggle categories
};
/// The full, ordered catalog of categories FlatKontrol presents.
const QList<CategoryDef> &catalog();
/// Convenience: the toggle category ids, in catalog order.
inline QString tr_noop(const char *s)
{
return QString::fromUtf8(s);
}
} // namespace FlatKontrol
+946
View File
@@ -0,0 +1,946 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include "permissionscontroller.h"
#include <KLocalizedString>
#include <QFile>
using namespace FlatKontrol;
namespace
{
QStringList splitTokens(const QString &value)
{
QStringList out;
const QStringList parts = value.split(QLatin1Char(';'));
for (const QString &p : parts) {
const QString t = p.trimmed();
if (!t.isEmpty()) {
out.append(t);
}
}
return out;
}
QString joinSorted(const QStringList &tokens)
{
QStringList copy = tokens;
copy.sort();
return copy.join(QLatin1Char(';'));
}
// Normalise a KeyFile to a canonical string so two override sets can be
// compared regardless of group/key/token ordering.
QString normalize(const KeyFile &kf)
{
QStringList groups = kf.groups();
groups.sort();
QString out;
for (const QString &g : std::as_const(groups)) {
QStringList keys = kf.keys(g);
keys.sort();
for (const QString &k : std::as_const(keys)) {
const QString v = kf.value(g, k);
const QString nv = v.contains(QLatin1Char(';')) ? joinSorted(splitTokens(v)) : v;
out += QLatin1Char('[') + g + QStringLiteral("]\n") + k + QLatin1Char('=') + nv + QLatin1Char('\n');
}
}
return out;
}
} // namespace
PermissionsController::PermissionsController(QObject *parent)
: QAbstractListModel(parent)
{
}
bool PermissionsController::isFilesystemPreset(const QString &bareToken)
{
static const QSet<QString> presets = {
QStringLiteral("host"),
QStringLiteral("host-os"),
QStringLiteral("host-etc"),
QStringLiteral("home"),
};
return presets.contains(bareToken);
}
bool PermissionsController::fsIsNegated(const QString &t)
{
return t.startsWith(QLatin1Char('!'));
}
QString PermissionsController::fsNegate(const QString &t)
{
return fsIsNegated(t) ? t.mid(1) : (QLatin1Char('!') + t);
}
QString PermissionsController::fsStripMode(const QString &t)
{
return t.section(QLatin1Char(':'), 0, 0);
}
bool PermissionsController::fsIsOverridden(const QSet<QString> &set, const QString &value)
{
QString path = fsStripMode(value);
if (path.startsWith(QLatin1Char('!'))) {
path = path.mid(1);
}
static const char *suffixes[] = {"", ":ro", ":rw", ":create"};
for (const char *s : suffixes) {
if (set.contains(path + QString::fromLatin1(s)) || set.contains(QLatin1Char('!') + path + QString::fromLatin1(s))) {
return true;
}
}
return set.contains(QStringLiteral("!") + path + QStringLiteral(":reset"));
}
// --- application selection / loading -----------------------------------------
void PermissionsController::setAppId(const QString &appId)
{
if (m_appId == appId) {
return;
}
m_appId = appId;
if (isGlobal()) {
m_appName = i18n("All Applications");
m_appIcon = QStringLiteral("preferences-desktop-default-applications");
m_appVersion.clear();
m_appRuntime.clear();
} else {
const AppInfo info = m_installations.appInfo(appId);
m_appName = info.name;
m_appIcon = info.iconSource;
m_appVersion = info.version;
m_appRuntime = info.runtime;
}
m_portals.setAppId(appId);
m_canUndo = false;
Q_EMIT canUndoChanged();
Q_EMIT appIdChanged();
reload();
}
void PermissionsController::reload()
{
beginResetModel();
loadBaselines();
m_savedSnapshot = KeyFile();
m_savedSnapshot.load(m_installations.overridePath(m_appId));
m_portals.reload();
rebuild();
endResetModel();
updateModified();
}
bool PermissionsController::toggleBaseline(const Baseline &b, const QString &option) const
{
bool val = false;
if (b.setOriginals.contains(option)) {
val = true;
}
if (b.setOriginals.contains(QLatin1Char('!') + option)) {
val = false;
}
if (b.setGlobals.contains(option)) {
val = true;
}
if (b.setGlobals.contains(QLatin1Char('!') + option)) {
val = false;
}
return val;
}
void PermissionsController::loadBaselines()
{
const auto &cats = catalog();
m_baselines.clear();
m_baselines.resize(cats.size());
if (isGlobal()) {
return; // no per-app baselines for the global override file
}
KeyFile metadata;
metadata.load(m_installations.metadataPath(m_appId));
KeyFile globals;
globals.load(m_installations.globalOverridePath());
for (int i = 0; i < cats.size(); ++i) {
const CategoryDef &cat = cats.at(i);
Baseline &b = m_baselines[i];
if (cat.type == RowType::VariableEntry) {
for (const QString &k : metadata.keys(cat.group)) {
const QString v = metadata.value(cat.group, k);
if (!v.isEmpty()) {
b.mapOriginals.insert(k, v);
}
}
for (const QString &k : globals.keys(cat.group)) {
const QString v = globals.value(cat.group, k);
if (!v.isEmpty()) {
b.mapGlobals.insert(k, v);
}
}
} else if (cat.type == RowType::BusEntry) {
for (const QString &k : metadata.keys(cat.group)) {
b.mapOriginals.insert(k, metadata.value(cat.group, k));
}
for (const QString &k : globals.keys(cat.group)) {
b.mapGlobals.insert(k, globals.value(cat.group, k));
}
} else if (cat.type == RowType::Portal) {
continue;
} else {
// token categories (toggles, filesystem presets/other, persistent)
const bool fsPresets = cat.id == QStringLiteral("filesystems-presets");
const bool fsOther = cat.id == QStringLiteral("filesystems-other");
const auto route = [&](const QStringList &tokens, QSet<QString> &dest) {
for (const QString &t : tokens) {
if (fsPresets || fsOther) {
const QString bare = fsStripMode(t.startsWith(QLatin1Char('!')) ? t.mid(1) : t);
const bool preset = isFilesystemPreset(bare);
if (fsPresets && !preset) {
continue;
}
if (fsOther && preset) {
continue;
}
}
dest.insert(t);
}
};
route(splitTokens(metadata.value(cat.group, cat.key)), b.setOriginals);
route(splitTokens(globals.value(cat.group, cat.key)), b.setGlobals);
}
}
}
QSet<QString> PermissionsController::fsRender(const Baseline &b, const QSet<QString> &overrides) const
{
const auto isReset = [](const QString &v) {
const QString path = v.section(QLatin1Char(':'), 0, 0);
const QString mode = v.section(QLatin1Char(':'), 1, 1);
return path.startsWith(QLatin1Char('!')) && mode == QStringLiteral("reset");
};
QSet<QString> result;
for (const QString &o : b.setOriginals) {
if (!fsIsOverridden(b.setGlobals, o) && !fsIsOverridden(overrides, o)) {
result.insert(o);
}
}
for (const QString &g : b.setGlobals) {
if (b.setOriginals.contains(fsNegate(g)) || fsIsOverridden(overrides, g)) {
continue;
}
if (fsIsOverridden(b.setOriginals, g) && fsIsNegated(g) && !isReset(g)) {
continue;
}
result.insert(g);
}
for (const QString &v : overrides) {
if (b.setOriginals.contains(fsNegate(v)) || b.setGlobals.contains(fsNegate(v))) {
continue;
}
if (fsIsOverridden(b.setOriginals, v) && fsIsNegated(v) && !isReset(v)) {
continue;
}
if (fsIsOverridden(b.setGlobals, v) && fsIsNegated(v) && !isReset(v)) {
continue;
}
result.insert(v);
}
// Only positive grants are shown as rows.
QSet<QString> positive;
for (const QString &t : std::as_const(result)) {
if (!fsIsNegated(t)) {
positive.insert(t);
}
}
return positive;
}
// --- row construction --------------------------------------------------------
void PermissionsController::rebuild()
{
const auto &cats = catalog();
m_rows.clear();
m_nextEntryId = 1;
for (int i = 0; i < cats.size(); ++i) {
const CategoryDef &cat = cats.at(i);
const Baseline &b = m_baselines.at(i);
if (cat.type == RowType::Toggle) {
// Overrides relevant to this key (filesystem categories share a key).
QSet<QString> ov;
const QStringList toks = splitTokens(m_savedSnapshot.value(cat.group, cat.key));
for (const QString &t : toks) {
const QString bare = fsStripMode(t.startsWith(QLatin1Char('!')) ? t.mid(1) : t);
if (cat.id == QStringLiteral("filesystems-presets") && !isFilesystemPreset(bare)) {
continue;
}
ov.insert(t);
}
for (const OptionDef &opt : cat.options) {
Row r;
r.catIndex = i;
r.kind = Toggle;
r.optionKey = opt.option;
r.primary = opt.label;
r.boolValue = toggleBaseline(b, opt.option);
if (ov.contains(opt.option)) {
r.boolValue = true;
}
if (ov.contains(QLatin1Char('!') + opt.option)) {
r.boolValue = false;
}
m_rows.append(r);
}
} else if (cat.type == RowType::PathEntry) {
QSet<QString> ov;
for (const QString &t : splitTokens(m_savedSnapshot.value(cat.group, cat.key))) {
const QString bare = fsStripMode(t.startsWith(QLatin1Char('!')) ? t.mid(1) : t);
if (!isFilesystemPreset(bare)) {
ov.insert(t);
}
}
QStringList rendered = fsRender(b, ov).values();
rendered.sort();
for (const QString &t : std::as_const(rendered)) {
Row r;
r.catIndex = i;
r.kind = PathEntry;
r.primary = t;
r.removable = true;
r.entryId = m_nextEntryId++;
m_rows.append(r);
}
} else if (cat.type == RowType::RelativePathEntry) {
QSet<QString> baseline = b.setOriginals;
baseline.unite(b.setGlobals);
QStringList rendered = baseline.values();
for (const QString &t : splitTokens(m_savedSnapshot.value(cat.group, cat.key))) {
if (!rendered.contains(t)) {
rendered.append(t);
}
}
rendered.sort();
for (const QString &t : std::as_const(rendered)) {
Row r;
r.catIndex = i;
r.kind = RelativePathEntry;
r.primary = t;
r.removable = !baseline.contains(t);
r.entryId = m_nextEntryId++;
m_rows.append(r);
}
} else if (cat.type == RowType::VariableEntry) {
QMap<QString, QString> effective = b.mapOriginals;
for (auto it = b.mapGlobals.cbegin(); it != b.mapGlobals.cend(); ++it) {
effective.insert(it.key(), it.value());
}
for (const QString &k : m_savedSnapshot.keys(cat.group)) {
effective.insert(k, m_savedSnapshot.value(cat.group, k));
}
for (auto it = effective.cbegin(); it != effective.cend(); ++it) {
if (it.value().isEmpty()) {
continue;
}
Row r;
r.catIndex = i;
r.kind = VariableEntry;
r.primary = it.key();
r.secondary = it.value();
r.removable = true;
r.entryId = m_nextEntryId++;
m_rows.append(r);
}
} else if (cat.type == RowType::BusEntry) {
QMap<QString, QString> effective = b.mapOriginals;
for (auto it = b.mapGlobals.cbegin(); it != b.mapGlobals.cend(); ++it) {
effective.insert(it.key(), it.value());
}
for (const QString &k : m_savedSnapshot.keys(cat.group)) {
effective.insert(k, m_savedSnapshot.value(cat.group, k));
}
for (auto it = effective.cbegin(); it != effective.cend(); ++it) {
if (it.value() != QStringLiteral("talk") && it.value() != QStringLiteral("own")) {
continue;
}
Row r;
r.catIndex = i;
r.kind = BusEntry;
r.primary = it.key();
r.secondary = it.value();
r.removable = true;
r.entryId = m_nextEntryId++;
m_rows.append(r);
}
} else if (cat.type == RowType::Portal) {
if (isGlobal()) {
continue; // portals are meaningless for the global override file
}
for (const PortalDef &def : PortalsBackend::definitions()) {
Row r;
r.catIndex = i;
r.kind = Portal;
r.primary = def.property;
r.supported = m_portals.isSupported(def);
r.reason = m_portals.unsupportedReason(def);
r.portalValue = static_cast<int>(m_portals.state(def));
m_rows.append(r);
}
}
// Trailing "add" affordance for the editable list categories.
if (cat.type == RowType::PathEntry || cat.type == RowType::RelativePathEntry || cat.type == RowType::VariableEntry
|| cat.type == RowType::BusEntry) {
Row r;
r.catIndex = i;
r.kind = AddRow;
m_rows.append(r);
}
}
for (int i = 0; i < m_baselines.size(); ++i) {
recomputeStatusesFor(i);
}
}
// --- model interface ---------------------------------------------------------
int PermissionsController::rowCount(const QModelIndex &parent) const
{
return parent.isValid() ? 0 : m_rows.size();
}
QVariant PermissionsController::data(const QModelIndex &index, int role) const
{
if (!index.isValid() || index.row() < 0 || index.row() >= m_rows.size()) {
return {};
}
const Row &r = m_rows.at(index.row());
const CategoryDef &cat = catalog().at(r.catIndex);
switch (role) {
case CategoryIdRole:
return cat.id;
case CategoryTitleRole:
return cat.title;
case CategoryDescriptionRole:
return cat.description;
case IsFirstInCategoryRole:
return index.row() == 0 || m_rows.at(index.row() - 1).catIndex != r.catIndex;
case RowTypeRole:
return static_cast<int>(r.kind);
case OptionKeyRole:
return r.optionKey;
case LabelRole:
if (r.kind == Toggle) {
return r.primary;
}
if (r.kind == Portal) {
for (const PortalDef &def : PortalsBackend::definitions()) {
if (def.property == r.primary) {
return def.label;
}
}
}
return r.primary;
case ExampleRole:
if (r.kind == Toggle) {
for (const OptionDef &opt : cat.options) {
if (opt.option == r.optionKey) {
return opt.example;
}
}
}
if (r.kind == Portal) {
for (const PortalDef &def : PortalsBackend::definitions()) {
if (def.property == r.primary) {
return def.example;
}
}
}
return QString();
case ValueRole:
if (r.kind == Toggle) {
return r.boolValue;
}
if (r.kind == Portal) {
return r.portalValue;
}
return r.primary;
case SecondaryRole:
return r.secondary;
case StatusRole:
return r.status;
case SupportedRole:
return r.supported;
case UnsupportedReasonRole:
return r.reason;
case RemovableRole:
return r.removable;
default:
return {};
}
}
QHash<int, QByteArray> PermissionsController::roleNames() const
{
return {
{CategoryIdRole, "categoryId"},
{CategoryTitleRole, "categoryTitle"},
{CategoryDescriptionRole, "categoryDescription"},
{IsFirstInCategoryRole, "isFirstInCategory"},
{RowTypeRole, "rowType"},
{OptionKeyRole, "optionKey"},
{LabelRole, "label"},
{ExampleRole, "example"},
{ValueRole, "value"},
{SecondaryRole, "secondary"},
{StatusRole, "status"},
{SupportedRole, "supported"},
{UnsupportedReasonRole, "unsupportedReason"},
{RemovableRole, "removable"},
};
}
// --- editing -----------------------------------------------------------------
void PermissionsController::setToggleValue(int row, bool value)
{
if (row < 0 || row >= m_rows.size() || m_rows[row].kind != Toggle) {
return;
}
m_rows[row].boolValue = value;
recomputeStatusesFor(m_rows[row].catIndex);
const QModelIndex idx = index(row);
Q_EMIT dataChanged(idx, idx, {ValueRole, StatusRole});
updateModified();
}
void PermissionsController::setEntryPrimary(int row, const QString &text)
{
if (row < 0 || row >= m_rows.size()) {
return;
}
m_rows[row].primary = text;
recomputeStatusesFor(m_rows[row].catIndex);
const QModelIndex idx = index(row);
Q_EMIT dataChanged(idx, idx, {StatusRole});
updateModified();
}
void PermissionsController::setEntrySecondary(int row, const QString &text)
{
if (row < 0 || row >= m_rows.size()) {
return;
}
m_rows[row].secondary = text;
recomputeStatusesFor(m_rows[row].catIndex);
const QModelIndex idx = index(row);
Q_EMIT dataChanged(idx, idx, {SecondaryRole, StatusRole});
updateModified();
}
void PermissionsController::addEntry(const QString &categoryId)
{
const auto &cats = catalog();
int catIndex = -1;
for (int i = 0; i < cats.size(); ++i) {
if (cats.at(i).id == categoryId) {
catIndex = i;
break;
}
}
if (catIndex < 0) {
return;
}
// Insert just before the category's trailing "add" row so the new entry
// lands at the end of the right section.
int insertAt = m_rows.size();
for (int i = 0; i < m_rows.size(); ++i) {
if (m_rows.at(i).catIndex == catIndex && m_rows.at(i).kind == AddRow) {
insertAt = i;
break;
}
}
Row r;
r.catIndex = catIndex;
switch (cats.at(catIndex).type) {
case RowType::PathEntry:
r.kind = PathEntry;
break;
case RowType::RelativePathEntry:
r.kind = RelativePathEntry;
break;
case RowType::VariableEntry:
r.kind = VariableEntry;
break;
case RowType::BusEntry:
r.kind = BusEntry;
r.secondary = QStringLiteral("talk");
break;
default:
return;
}
r.removable = true;
r.status = User;
r.entryId = m_nextEntryId++;
beginInsertRows(QModelIndex(), insertAt, insertAt);
m_rows.insert(insertAt, r);
endInsertRows();
updateModified();
}
void PermissionsController::removeEntry(int row)
{
if (row < 0 || row >= m_rows.size() || !m_rows.at(row).removable) {
return;
}
const int catIndex = m_rows.at(row).catIndex;
beginRemoveRows(QModelIndex(), row, row);
m_rows.removeAt(row);
endRemoveRows();
recomputeStatusesFor(catIndex);
updateModified();
}
void PermissionsController::setPortalValue(int row, int value)
{
if (row < 0 || row >= m_rows.size() || m_rows[row].kind != Portal) {
return;
}
m_rows[row].portalValue = value;
const QModelIndex idx = index(row);
Q_EMIT dataChanged(idx, idx, {ValueRole});
updateModified();
}
// --- status & modified -------------------------------------------------------
void PermissionsController::recomputeStatusesFor(int catIndex)
{
const Baseline &b = m_baselines.at(catIndex);
for (int i = 0; i < m_rows.size(); ++i) {
Row &r = m_rows[i];
if (r.catIndex != catIndex) {
continue;
}
int status = Original;
switch (r.kind) {
case Toggle: {
const bool base = toggleBaseline(b, r.optionKey);
if (r.boolValue != base) {
status = User;
} else if (b.setGlobals.contains(r.optionKey) || b.setGlobals.contains(QLatin1Char('!') + r.optionKey)) {
status = Global;
}
break;
}
case PathEntry: {
if (!b.setOriginals.contains(r.primary) && !b.setGlobals.contains(r.primary)) {
status = User;
} else if (b.setGlobals.contains(r.primary)) {
status = Global;
}
break;
}
case RelativePathEntry: {
if (!b.setOriginals.contains(r.primary) && !b.setGlobals.contains(r.primary)) {
status = User;
} else if (b.setGlobals.contains(r.primary)) {
status = Global;
}
break;
}
case VariableEntry: {
const bool inBase = b.mapOriginals.contains(r.primary) || b.mapGlobals.contains(r.primary);
const QString baseVal = b.mapGlobals.contains(r.primary) ? b.mapGlobals.value(r.primary) : b.mapOriginals.value(r.primary);
if (!inBase || baseVal != r.secondary) {
status = User;
} else if (b.mapGlobals.contains(r.primary)) {
status = Global;
}
break;
}
case BusEntry: {
const bool inBase = b.mapOriginals.contains(r.primary) || b.mapGlobals.contains(r.primary);
const QString baseVal = b.mapGlobals.contains(r.primary) ? b.mapGlobals.value(r.primary) : b.mapOriginals.value(r.primary);
if (!inBase || baseVal != r.secondary) {
status = User;
} else if (b.mapGlobals.contains(r.primary)) {
status = Global;
}
break;
}
case Portal:
case AddRow:
continue;
}
if (r.status != status) {
r.status = status;
const QModelIndex idx = index(i);
Q_EMIT dataChanged(idx, idx, {StatusRole});
}
}
}
KeyFile PermissionsController::buildOverrides() const
{
const auto &cats = catalog();
KeyFile kf;
// Accumulate ';'-list override tokens per (group,key) so the shared
// "filesystems" key receives both presets and custom paths.
QMap<QString, QStringList> listOverrides; // "group\x1fkey" -> tokens
const auto pushToken = [&](const QString &group, const QString &key, const QString &token) {
listOverrides[group + QChar(0x1f) + key].append(token);
};
for (int i = 0; i < cats.size(); ++i) {
const CategoryDef &cat = cats.at(i);
const Baseline &b = m_baselines.at(i);
if (cat.type == RowType::Toggle) {
for (const Row &r : m_rows) {
if (r.catIndex != i) {
continue;
}
const bool base = toggleBaseline(b, r.optionKey);
if (r.boolValue != base) {
pushToken(cat.group, cat.key, r.boolValue ? r.optionKey : (QLatin1Char('!') + r.optionKey));
}
}
} else if (cat.type == RowType::PathEntry) {
QSet<QString> desired;
for (const Row &r : m_rows) {
if (r.catIndex == i && !r.primary.trimmed().isEmpty()) {
desired.insert(r.primary.trimmed());
}
}
// Port of filesystemsOther.updateFromProxyProperty (presets separated).
QSet<QString> added;
for (const QString &p : std::as_const(desired)) {
if (!b.setOriginals.contains(p) && !b.setGlobals.contains(p)) {
added.insert(p);
}
}
QSet<QString> overrides = added;
for (const QString &o : b.setOriginals) {
if (!fsIsOverridden(b.setGlobals, o) && !fsIsOverridden(added, o) && !desired.contains(o)) {
overrides.insert(fsNegate(fsStripMode(o)));
}
}
for (const QString &g : b.setGlobals) {
if (!fsIsOverridden(b.setOriginals, g) && !fsIsOverridden(added, g) && !desired.contains(g)) {
overrides.insert(fsNegate(fsStripMode(g)));
}
}
for (const QString &t : std::as_const(overrides)) {
pushToken(cat.group, cat.key, t);
}
} else if (cat.type == RowType::RelativePathEntry) {
QSet<QString> baseline = b.setOriginals;
baseline.unite(b.setGlobals);
for (const Row &r : m_rows) {
if (r.catIndex != i) {
continue;
}
const QString t = r.primary.trimmed();
if (!t.isEmpty() && !baseline.contains(t)) {
pushToken(cat.group, cat.key, t);
}
}
} else if (cat.type == RowType::VariableEntry) {
QMap<QString, QString> desired;
for (const Row &r : m_rows) {
if (r.catIndex != i) {
continue;
}
const QString k = r.primary.trimmed();
if (k.isEmpty() || k.contains(QLatin1Char(';')) || k.contains(QLatin1Char(' ')) || r.secondary.isEmpty()) {
continue;
}
desired.insert(k, r.secondary);
}
QMap<QString, QString> baseline = b.mapOriginals;
for (auto it = b.mapGlobals.cbegin(); it != b.mapGlobals.cend(); ++it) {
baseline.insert(it.key(), it.value());
}
for (auto it = desired.cbegin(); it != desired.cend(); ++it) {
if (!baseline.contains(it.key()) || baseline.value(it.key()) != it.value()) {
kf.setValue(cat.group, it.key(), it.value());
}
}
for (auto it = baseline.cbegin(); it != baseline.cend(); ++it) {
if (!desired.contains(it.key()) && !it.value().isEmpty()) {
kf.setValue(cat.group, it.key(), QString());
}
}
} else if (cat.type == RowType::BusEntry) {
QMap<QString, QString> desired;
for (const Row &r : m_rows) {
if (r.catIndex != i) {
continue;
}
const QString name = r.primary.trimmed();
if (!name.isEmpty() && (r.secondary == QStringLiteral("talk") || r.secondary == QStringLiteral("own"))) {
desired.insert(name, r.secondary);
}
}
QMap<QString, QString> baseline = b.mapOriginals;
for (auto it = b.mapGlobals.cbegin(); it != b.mapGlobals.cend(); ++it) {
baseline.insert(it.key(), it.value());
}
for (auto it = desired.cbegin(); it != desired.cend(); ++it) {
if (!baseline.contains(it.key()) || baseline.value(it.key()) != it.value()) {
kf.setValue(cat.group, it.key(), it.value());
}
}
for (auto it = baseline.cbegin(); it != baseline.cend(); ++it) {
const QString v = it.value();
if ((v == QStringLiteral("talk") || v == QStringLiteral("own")) && !desired.contains(it.key())) {
kf.setValue(cat.group, it.key(), QStringLiteral("none"));
}
}
}
}
for (auto it = listOverrides.cbegin(); it != listOverrides.cend(); ++it) {
if (it.value().isEmpty()) {
continue;
}
const QString combined = it.key();
const int sep = combined.indexOf(QChar(0x1f));
const QString group = combined.left(sep);
const QString key = combined.mid(sep + 1);
QStringList tokens = it.value();
tokens.removeDuplicates();
kf.setValue(group, key, tokens.join(QLatin1Char(';')));
}
return kf;
}
void PermissionsController::updateModified()
{
bool mod = normalize(buildOverrides()) != normalize(m_savedSnapshot);
if (!mod) {
for (const Row &r : m_rows) {
if (r.kind != Portal || !r.supported) {
continue;
}
for (const PortalDef &def : PortalsBackend::definitions()) {
if (def.property != r.primary) {
continue;
}
const int actual = static_cast<int>(m_portals.state(def));
if (r.portalValue != actual && r.portalValue != PortalUnknown && r.portalValue != PortalUnsupported) {
mod = true;
}
}
if (mod) {
break;
}
}
}
if (mod != m_modified) {
m_modified = mod;
Q_EMIT modifiedChanged();
}
}
// --- persistence -------------------------------------------------------------
void PermissionsController::save()
{
const QString path = m_installations.overridePath(m_appId);
const KeyFile overrides = buildOverrides();
if (overrides.isEmpty()) {
QFile::remove(path);
} else if (!overrides.save(path)) {
Q_EMIT error(i18n("Could not write override file: %1", path));
return;
}
// Apply batched portal changes.
for (const Row &r : m_rows) {
if (r.kind != Portal || !r.supported) {
continue;
}
for (const PortalDef &def : PortalsBackend::definitions()) {
if (def.property != r.primary) {
continue;
}
const int actual = static_cast<int>(m_portals.state(def));
if (r.portalValue != actual && r.portalValue != PortalUnknown && r.portalValue != PortalUnsupported) {
m_portals.setState(def, static_cast<PortalState>(r.portalValue));
}
}
}
Q_EMIT saved();
reload();
}
void PermissionsController::reset()
{
const QString path = m_installations.overridePath(m_appId);
// Capture undo state.
m_undoSnapshot = KeyFile();
m_undoSnapshot.load(path);
m_undoPortals.clear();
for (const PortalDef &def : PortalsBackend::definitions()) {
if (m_portals.isSupported(def)) {
m_undoPortals.insert(def.property, static_cast<int>(m_portals.state(def)));
}
}
QFile::remove(path);
m_portals.forget();
m_canUndo = true;
Q_EMIT canUndoChanged();
reload();
}
void PermissionsController::undo()
{
const QString path = m_installations.overridePath(m_appId);
if (m_undoSnapshot.isEmpty()) {
QFile::remove(path);
} else {
m_undoSnapshot.save(path);
}
for (auto it = m_undoPortals.cbegin(); it != m_undoPortals.cend(); ++it) {
for (const PortalDef &def : PortalsBackend::definitions()) {
if (def.property == it.key()) {
m_portals.setState(def, static_cast<PortalState>(it.value()));
}
}
}
m_canUndo = false;
Q_EMIT canUndoChanged();
reload();
}
+205
View File
@@ -0,0 +1,205 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include "flatpakinstallations.h"
#include "keyfile.h"
#include "permissioncatalog.h"
#include "portalsbackend.h"
#include <QAbstractListModel>
#include <QMap>
#include <QQmlEngine>
#include <QSet>
#include <QString>
/**
* Owns the editable permission state for one application (or the global
* pseudo-app) and exposes it as a flat list model of rows grouped by category.
*
* The display rows are the single source of truth for the UI; concrete override
* deltas are recomputed from them on demand (port of Flatseal's per-model
* original/global/user resolution). Portal permissions are batched and applied
* on save() alongside the override file.
*/
class PermissionsController : public QAbstractListModel
{
Q_OBJECT
QML_ELEMENT
Q_PROPERTY(QString appId READ appId WRITE setAppId NOTIFY appIdChanged)
Q_PROPERTY(QString appName READ appName NOTIFY appIdChanged)
Q_PROPERTY(QString appIcon READ appIcon NOTIFY appIdChanged)
Q_PROPERTY(QString appVersion READ appVersion NOTIFY appIdChanged)
Q_PROPERTY(QString appRuntime READ appRuntime NOTIFY appIdChanged)
Q_PROPERTY(bool isGlobal READ isGlobal NOTIFY appIdChanged)
Q_PROPERTY(bool modified READ modified NOTIFY modifiedChanged)
Q_PROPERTY(bool canUndo READ canUndo NOTIFY canUndoChanged)
public:
enum RowKind {
Toggle = 0,
PathEntry = 1,
RelativePathEntry = 2,
VariableEntry = 3,
BusEntry = 4,
Portal = 5,
AddRow = 6, // trailing "add entry" affordance for list categories
};
Q_ENUM(RowKind)
enum OverrideStatus {
Original = 0,
Global = 1,
User = 2,
};
Q_ENUM(OverrideStatus)
enum PortalValue {
PortalUnknown = 0,
PortalUnsupported = 1,
PortalUnset = 2,
PortalDisallowed = 3,
PortalAllowed = 4,
};
Q_ENUM(PortalValue)
enum Roles {
CategoryIdRole = Qt::UserRole + 1,
CategoryTitleRole,
CategoryDescriptionRole,
IsFirstInCategoryRole,
RowTypeRole,
OptionKeyRole,
LabelRole,
ExampleRole,
ValueRole, // bool (toggle), int (portal), or primary string (entries)
SecondaryRole, // variable value / bus policy
StatusRole,
SupportedRole,
UnsupportedReasonRole,
RemovableRole,
};
explicit PermissionsController(QObject *parent = nullptr);
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role) const override;
QHash<int, QByteArray> roleNames() const override;
QString appId() const
{
return m_appId;
}
void setAppId(const QString &appId);
QString appName() const
{
return m_appName;
}
QString appIcon() const
{
return m_appIcon;
}
QString appVersion() const
{
return m_appVersion;
}
QString appRuntime() const
{
return m_appRuntime;
}
bool isGlobal() const
{
return m_appId == QStringLiteral("global");
}
bool modified() const
{
return m_modified;
}
bool canUndo() const
{
return m_canUndo;
}
// --- Editing API, called from QML ---
Q_INVOKABLE void setToggleValue(int row, bool value);
Q_INVOKABLE void setEntryPrimary(int row, const QString &text);
Q_INVOKABLE void setEntrySecondary(int row, const QString &text);
Q_INVOKABLE void addEntry(const QString &categoryId);
Q_INVOKABLE void removeEntry(int row);
Q_INVOKABLE void setPortalValue(int row, int value);
Q_INVOKABLE void save();
Q_INVOKABLE void reset();
Q_INVOKABLE void undo();
Q_INVOKABLE void reload();
Q_SIGNALS:
void appIdChanged();
void modifiedChanged();
void canUndoChanged();
void saved();
void error(const QString &message);
private:
struct Row {
int catIndex = -1; // index into FlatKontrol::catalog()
PermissionsController::RowKind kind = Toggle;
QString optionKey; // toggle option id
QString primary; // toggle: option id; entries: path/key/name; portal: property
QString secondary; // variable value / bus policy ("talk"/"own")
bool boolValue = false; // toggle state
int portalValue = PortalUnknown;
int status = Original;
bool supported = true;
QString reason; // unsupported reason
bool removable = false;
int entryId = 0; // stable per-row id for entries
};
// Read-only baselines for one category (originals from metadata, globals
// from the global override file).
struct Baseline {
QSet<QString> setOriginals; // token sets (toggles, paths, persistent)
QSet<QString> setGlobals;
QMap<QString, QString> mapOriginals; // key/value (environment, bus)
QMap<QString, QString> mapGlobals;
};
void rebuild();
void loadBaselines();
bool toggleBaseline(const Baseline &b, const QString &option) const;
static bool fsIsNegated(const QString &t);
static QString fsNegate(const QString &t);
static QString fsStripMode(const QString &t);
static bool fsIsOverridden(const QSet<QString> &set, const QString &value);
QSet<QString> fsRender(const Baseline &b, const QSet<QString> &overrides) const;
// Build a KeyFile holding the current override deltas (empty groups omitted).
KeyFile buildOverrides() const;
void recomputeStatusesFor(int catIndex);
void updateModified();
QList<Row> rowsForCategory(int catIndex) const;
static bool isFilesystemPreset(const QString &bareToken);
FlatpakInstallations m_installations;
FlatKontrol::PortalsBackend m_portals;
QString m_appId;
QString m_appName;
QString m_appIcon;
QString m_appVersion;
QString m_appRuntime;
QList<Baseline> m_baselines; // aligned with catalog()
QList<Row> m_rows;
int m_nextEntryId = 1;
KeyFile m_savedSnapshot; // per-app override file as last persisted
bool m_modified = false;
bool m_canUndo = false;
// Backups captured by reset(), restored by undo().
KeyFile m_undoSnapshot;
QMap<QString, int> m_undoPortals; // property -> PortalValue
};
+257
View File
@@ -0,0 +1,257 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include "portalsbackend.h"
#include <KLocalizedString>
#include <QDBusArgument>
#include <QDBusConnection>
#include <QDBusInterface>
#include <QDBusMessage>
#include <QDBusReply>
namespace FlatKontrol
{
static constexpr uint SUPPORTED_SERVICE_VERSION = 2;
static const char *DBUS_PATH = "/org/freedesktop/impl/portal/PermissionStore";
static const char *DBUS_IFACE = "org.freedesktop.impl.portal.PermissionStore";
const QList<PortalDef> &PortalsBackend::definitions()
{
static const QList<PortalDef> defs = {
{QStringLiteral("portals-background"),
i18n("Background"),
i18n("Can run in the background"),
QStringLiteral("background"),
QStringLiteral("background"),
{QStringLiteral("yes")},
{QStringLiteral("no")}},
{QStringLiteral("portals-notification"),
i18n("Notifications"),
i18n("Can send notifications"),
QStringLiteral("notifications"),
QStringLiteral("notification"),
{QStringLiteral("yes")},
{QStringLiteral("no")}},
{QStringLiteral("portals-microphone"),
i18n("Microphone"),
i18n("Can listen to your microphone"),
QStringLiteral("devices"),
QStringLiteral("microphone"),
{QStringLiteral("yes")},
{QStringLiteral("no")}},
{QStringLiteral("portals-speakers"),
i18n("Speakers"),
i18n("Can play sounds to your speakers"),
QStringLiteral("devices"),
QStringLiteral("speakers"),
{QStringLiteral("yes")},
{QStringLiteral("no")}},
{QStringLiteral("portals-camera"),
i18n("Camera"),
i18n("Can record videos with your camera"),
QStringLiteral("devices"),
QStringLiteral("camera"),
{QStringLiteral("yes")},
{QStringLiteral("no")}},
{QStringLiteral("portals-location"),
i18n("Location"),
i18n("Can access your location"),
QStringLiteral("location"),
QStringLiteral("location"),
{QStringLiteral("EXACT"), QStringLiteral("0")},
{QStringLiteral("NONE"), QStringLiteral("0")}},
};
return defs;
}
PortalsBackend::PortalsBackend() = default;
PortalsBackend::~PortalsBackend()
{
delete m_proxy;
}
void PortalsBackend::ensureProxy()
{
if (m_proxy) {
return;
}
QString busName = qEnvironmentVariable("FLATKONTROL_PORTAL_BUS_NAME");
if (busName.isEmpty()) {
busName = qEnvironmentVariable("FLATSEAL_PORTAL_BUS_NAME");
}
if (busName.isEmpty()) {
busName = QString::fromLatin1(DBUS_IFACE);
}
m_proxy = new QDBusInterface(busName, QString::fromLatin1(DBUS_PATH), QString::fromLatin1(DBUS_IFACE), QDBusConnection::sessionBus());
}
uint PortalsBackend::serviceVersion()
{
ensureProxy();
const QVariant v = m_proxy->property("version");
return v.isValid() ? v.toUInt() : 0;
}
void PortalsBackend::setAppId(const QString &appId)
{
m_appId = appId;
reload();
}
QStringList PortalsBackend::lookupApps(const QString &table, const QString &id, bool *ok)
{
ensureProxy();
QDBusMessage reply = m_proxy->call(QStringLiteral("Lookup"), table, id);
if (reply.type() != QDBusMessage::ReplyMessage || reply.arguments().isEmpty()) {
if (ok) {
*ok = false;
}
return {};
}
if (ok) {
*ok = true;
}
// First out-arg is a{sas}: app id -> permission strings.
const QDBusArgument arg = reply.arguments().at(0).value<QDBusArgument>();
QMap<QString, QStringList> perms;
arg >> perms;
QStringList apps;
apps.reserve(perms.size());
for (auto it = perms.cbegin(); it != perms.cend(); ++it) {
apps.append(it.key());
}
return apps;
}
bool PortalsBackend::isSupported(const PortalDef &def)
{
if (m_supported.contains(def.property)) {
return m_supported.value(def.property);
}
auto markUnsupported = [&](const QString &reason) {
m_reasons[def.property] = reason;
m_supported[def.property] = false;
return false;
};
if (m_appId.isEmpty() || m_appId == QStringLiteral("global")) {
return markUnsupported(i18n("Not available for global overrides"));
}
ensureProxy();
if (!m_proxy->isValid()) {
return markUnsupported(i18n("The permission store service is not available"));
}
if (serviceVersion() < SUPPORTED_SERVICE_VERSION) {
return markUnsupported(i18n("Requires permission store version 2 or newer"));
}
bool ok = false;
lookupApps(def.table, def.id, &ok);
if (!ok) {
return markUnsupported(i18n("Portal data has not been set up yet"));
}
m_reasons[def.property] = QString();
m_supported[def.property] = true;
return true;
}
QString PortalsBackend::unsupportedReason(const PortalDef &def) const
{
return m_reasons.value(def.property);
}
PortalState PortalsBackend::state(const PortalDef &def)
{
if (!isSupported(def)) {
return PortalState::Unsupported;
}
ensureProxy();
QDBusMessage reply = m_proxy->call(QStringLiteral("Lookup"), def.table, def.id);
if (reply.type() != QDBusMessage::ReplyMessage || reply.arguments().isEmpty()) {
return PortalState::Unsupported;
}
const QDBusArgument arg = reply.arguments().at(0).value<QDBusArgument>();
QMap<QString, QStringList> perms;
arg >> perms;
if (!perms.contains(m_appId)) {
return PortalState::Unset;
}
const QStringList current = perms.value(m_appId);
if (!current.isEmpty() && current.first() == def.allowed.first()) {
return PortalState::Allowed;
}
return PortalState::Disallowed;
}
void PortalsBackend::setPermission(const QString &table, const QString &id, const QString &app, const QStringList &perms)
{
ensureProxy();
m_proxy->call(QStringLiteral("SetPermission"), table, false, id, app, perms);
}
void PortalsBackend::deletePermission(const QString &table, const QString &id, const QString &app)
{
ensureProxy();
m_proxy->call(QStringLiteral("DeletePermission"), table, id, app);
}
void PortalsBackend::unset(const PortalDef &def)
{
bool ok = false;
const QStringList apps = lookupApps(def.table, def.id, &ok);
if (!ok || !apps.contains(m_appId)) {
return;
}
// Work around xdg-desktop-portal#573: deleting the only app drops the table.
if (apps.size() == 1) {
setPermission(def.table, def.id, QString(), {});
}
deletePermission(def.table, def.id, m_appId);
}
void PortalsBackend::setState(const PortalDef &def, PortalState newState)
{
if (!isSupported(def)) {
return;
}
switch (newState) {
case PortalState::Unset:
unset(def);
break;
case PortalState::Allowed:
setPermission(def.table, def.id, m_appId, def.allowed);
break;
case PortalState::Disallowed:
setPermission(def.table, def.id, m_appId, def.disallowed);
break;
default:
break;
}
}
void PortalsBackend::forget()
{
for (const PortalDef &def : definitions()) {
if (isSupported(def)) {
unset(def);
}
}
}
void PortalsBackend::reload()
{
m_supported.clear();
m_reasons.clear();
}
} // namespace FlatKontrol
+75
View File
@@ -0,0 +1,75 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include <QHash>
#include <QList>
#include <QString>
#include <QStringList>
class QDBusInterface;
namespace FlatKontrol
{
/// Tri-state (plus availability) of a portal permission, matching Flatseal.
enum class PortalState {
Unknown = 0,
Unsupported = 1,
Unset = 2,
Disallowed = 3,
Allowed = 4,
};
struct PortalDef {
QString property; // stable id, e.g. "portals-notification"
QString label;
QString example;
QString table; // PermissionStore table, e.g. "notifications"
QString id; // PermissionStore id, e.g. "notification"
QStringList allowed;
QStringList disallowed;
};
/**
* Talks directly to org.freedesktop.impl.portal.PermissionStore on the session
* bus to read and edit dynamic portal permissions. Faithful port of Flatseal's
* portals.js (file-less, D-Bus backed).
*/
class PortalsBackend
{
public:
PortalsBackend();
~PortalsBackend();
static const QList<PortalDef> &definitions();
void setAppId(const QString &appId);
/// (Re)reads supported-state of every portal; call on app change.
void reload();
bool isSupported(const PortalDef &def);
QString unsupportedReason(const PortalDef &def) const;
PortalState state(const PortalDef &def);
/// Apply a new state for one portal permission.
void setState(const PortalDef &def, PortalState newState);
/// Unset every portal permission for the current app (used by reset).
void forget();
private:
void ensureProxy();
QStringList lookupApps(const QString &table, const QString &id, bool *ok = nullptr);
void setPermission(const QString &table, const QString &id, const QString &app, const QStringList &perms);
void deletePermission(const QString &table, const QString &id, const QString &app);
void unset(const PortalDef &def);
uint serviceVersion();
QDBusInterface *m_proxy = nullptr;
QString m_appId;
QHash<QString, bool> m_supported; // property -> supported
QHash<QString, QString> m_reasons; // property -> reason
};
} // namespace FlatKontrol
+138
View File
@@ -0,0 +1,138 @@
// SPDX-License-Identifier: GPL-3.0-or-later
pragma ComponentBehavior: Bound
import QtQuick
import QtQuick.Controls as QQC2
import QtQuick.Layouts
import org.kde.kirigami as Kirigami
import org.kde.kitemmodels as KItemModels
import org.kde.kirigamiaddons.delegates as Delegates
import io.github.toservetheking.FlatKontrol
Kirigami.ApplicationWindow {
id: root
title: i18nc("@title:window", "FlatKontrol")
minimumWidth: Kirigami.Units.gridUnit * 32
minimumHeight: Kirigami.Units.gridUnit * 24
width: Kirigami.Units.gridUnit * 48
height: Kirigami.Units.gridUnit * 34
ApplicationsModel {
id: appsModel
}
PermissionsController {
id: controller
}
KItemModels.KSortFilterProxyModel {
id: filteredApps
sourceModel: appsModel
filterRoleName: "name"
filterCaseSensitivity: Qt.CaseInsensitive
sortRoleName: "name"
}
pageStack.defaultColumnWidth: Kirigami.Units.gridUnit * 16
pageStack.globalToolBar.style: Kirigami.ApplicationHeaderStyle.ToolBar
// Two static columns (sidebar + permissions) - no dynamic page pushing.
pageStack.initialPage: [sidebarComponent, permsComponent]
function showDetails(): void {
detailsDialog.open();
}
function selectApp(appId: string): void {
controller.appId = appId;
// On narrow layouts, reveal the permissions column.
root.pageStack.currentIndex = 1;
}
Component {
id: sidebarComponent
Kirigami.ScrollablePage {
title: i18nc("@title", "Applications")
titleDelegate: Kirigami.SearchField {
Layout.fillWidth: true
onTextChanged: filteredApps.filterString = text
}
ListView {
id: appList
model: filteredApps
currentIndex: -1
delegate: Delegates.RoundedItemDelegate {
id: appDelegate
required property int index
required property string appId
required property string name
required property string iconSource
required property bool isGlobal
text: name
icon.source: iconSource
highlighted: controller.appId === appId
contentItem: Delegates.SubtitleContentItem {
itemDelegate: appDelegate
subtitle: appDelegate.isGlobal ? i18n("Default settings for all apps") : appDelegate.appId
}
onClicked: {
appList.currentIndex = index;
root.selectApp(appId);
}
}
Kirigami.PlaceholderMessage {
anchors.centerIn: parent
width: parent.width - Kirigami.Units.gridUnit * 4
visible: appList.count === 0
icon.name: "flatpak-symbolic"
text: i18n("No Flatpak applications found")
}
}
}
}
Component {
id: permsComponent
PermissionsPage {
controller: controller
}
}
Kirigami.Dialog {
id: detailsDialog
title: i18nc("@title", "Application Details")
standardButtons: QQC2.Dialog.Close
preferredWidth: Kirigami.Units.gridUnit * 24
padding: Kirigami.Units.largeSpacing
Kirigami.FormLayout {
QQC2.Label {
Kirigami.FormData.label: i18n("Name:")
text: controller.appName
}
QQC2.Label {
Kirigami.FormData.label: i18n("Application ID:")
text: controller.appId
}
QQC2.Label {
Kirigami.FormData.label: i18n("Version:")
text: controller.appVersion
}
QQC2.Label {
Kirigami.FormData.label: i18n("Runtime:")
text: controller.appRuntime
}
}
}
}
+330
View File
@@ -0,0 +1,330 @@
// SPDX-License-Identifier: GPL-3.0-or-later
pragma ComponentBehavior: Bound
import QtQuick
import QtQuick.Controls as QQC2
import QtQuick.Layouts
import Qt.labs.qmlmodels
import org.kde.kirigami as Kirigami
import io.github.toservetheking.FlatKontrol
Kirigami.ScrollablePage {
id: page
required property PermissionsController controller
readonly property bool hasSelection: controller.appId.length > 0
title: hasSelection ? controller.appName : i18nc("@title", "Permissions")
// --- shared bits ---------------------------------------------------------
component StatusBadge: Kirigami.Icon {
property int badgeStatus: 0
visible: badgeStatus > 0
implicitWidth: Kirigami.Units.iconSizes.small
implicitHeight: Kirigami.Units.iconSizes.small
source: badgeStatus === 2 ? "document-edit" : "globe"
HoverHandler {
id: hover
}
QQC2.ToolTip.visible: hover.hovered
QQC2.ToolTip.text: badgeStatus === 2 ? i18n("Set by you") : i18n("Set by a global override")
}
actions: [
Kirigami.Action {
text: i18nc("@action:button", "Save")
icon.name: "document-save"
enabled: page.controller.modified
onTriggered: page.controller.save()
},
Kirigami.Action {
text: i18nc("@action:button", "Reset")
icon.name: "edit-reset"
enabled: page.hasSelection
onTriggered: page.controller.reset()
},
Kirigami.Action {
text: i18nc("@action:button", "Undo Reset")
icon.name: "edit-undo"
visible: page.controller.canUndo
onTriggered: page.controller.undo()
},
Kirigami.Action {
text: i18nc("@action:button", "Details")
icon.name: "documentinfo"
visible: page.hasSelection && !page.controller.isGlobal
onTriggered: applicationWindow().showDetails()
}
]
Connections {
target: page.controller
function onSaved() {
applicationWindow().showPassiveNotification(i18n("Permissions saved"));
}
function onError(message) {
applicationWindow().showPassiveNotification(message, "long");
}
}
// --- the list ------------------------------------------------------------
ListView {
id: permsView
model: page.controller
Kirigami.PlaceholderMessage {
anchors.centerIn: parent
width: parent.width - Kirigami.Units.gridUnit * 4
visible: !page.hasSelection
icon.name: "preferences-desktop"
text: i18n("Select an application")
explanation: i18n("Choose an application to review and adjust its permissions.")
}
section.property: "categoryTitle"
section.delegate: Kirigami.ListSectionHeader {
required property string section
width: ListView.view.width
text: section
}
delegate: DelegateChooser {
role: "rowType"
// Toggle (share/sockets/devices/features/filesystem presets)
DelegateChoice {
roleValue: 0
delegate: QQC2.ItemDelegate {
id: toggleDelegate
required property int index
required property string label
required property string example
required property bool value
required property int status
width: ListView.view.width
hoverEnabled: true
onClicked: toggleSwitch.toggle()
contentItem: RowLayout {
spacing: Kirigami.Units.largeSpacing
ColumnLayout {
Layout.fillWidth: true
spacing: 0
QQC2.Label {
text: toggleDelegate.label
Layout.fillWidth: true
elide: Text.ElideRight
}
QQC2.Label {
text: toggleDelegate.example
visible: text.length > 0
opacity: 0.6
font: Kirigami.Theme.smallFont
Layout.fillWidth: true
elide: Text.ElideRight
}
}
StatusBadge {
badgeStatus: toggleDelegate.status
}
QQC2.Switch {
id: toggleSwitch
checked: toggleDelegate.value
onToggled: page.controller.setToggleValue(toggleDelegate.index, checked)
}
}
}
}
// Filesystem path entry
DelegateChoice {
roleValue: 1
delegate: page.entryDelegate
}
// Persistent (relative path) entry
DelegateChoice {
roleValue: 2
delegate: page.entryDelegate
}
// Environment variable
DelegateChoice {
roleValue: 3
delegate: QQC2.ItemDelegate {
id: varDelegate
required property int index
required property string value
required property string secondary
required property int status
required property bool removable
width: ListView.view.width
hoverEnabled: true
background: null
contentItem: RowLayout {
spacing: Kirigami.Units.smallSpacing
QQC2.TextField {
text: varDelegate.value
placeholderText: i18n("VARIABLE")
Layout.preferredWidth: Kirigami.Units.gridUnit * 10
onTextEdited: page.controller.setEntryPrimary(varDelegate.index, text)
}
QQC2.Label {
text: "="
}
QQC2.TextField {
text: varDelegate.secondary
placeholderText: i18n("value")
Layout.fillWidth: true
onTextEdited: page.controller.setEntrySecondary(varDelegate.index, text)
}
StatusBadge {
badgeStatus: varDelegate.status
}
QQC2.ToolButton {
icon.name: "edit-delete-remove"
visible: varDelegate.removable
onClicked: page.controller.removeEntry(varDelegate.index)
}
}
}
}
// D-Bus name policy
DelegateChoice {
roleValue: 4
delegate: QQC2.ItemDelegate {
id: busDelegate
required property int index
required property string value
required property string secondary
required property int status
required property bool removable
width: ListView.view.width
hoverEnabled: true
background: null
contentItem: RowLayout {
spacing: Kirigami.Units.smallSpacing
QQC2.TextField {
text: busDelegate.value
placeholderText: i18n("e.g. org.freedesktop.Notifications")
Layout.fillWidth: true
onTextEdited: page.controller.setEntryPrimary(busDelegate.index, text)
}
QQC2.ComboBox {
model: ["talk", "own"]
currentIndex: busDelegate.secondary === "own" ? 1 : 0
onActivated: page.controller.setEntrySecondary(busDelegate.index, currentValue)
}
StatusBadge {
badgeStatus: busDelegate.status
}
QQC2.ToolButton {
icon.name: "edit-delete-remove"
visible: busDelegate.removable
onClicked: page.controller.removeEntry(busDelegate.index)
}
}
}
}
// Portal (tri-state)
DelegateChoice {
roleValue: 5
delegate: QQC2.ItemDelegate {
id: portalDelegate
required property int index
required property string label
required property string example
required property int value
required property bool supported
required property string unsupportedReason
width: ListView.view.width
hoverEnabled: true
background: null
readonly property var states: [2, 4, 3] // Unset, Allowed, Disallowed
contentItem: RowLayout {
spacing: Kirigami.Units.largeSpacing
ColumnLayout {
Layout.fillWidth: true
spacing: 0
QQC2.Label {
text: portalDelegate.label
Layout.fillWidth: true
elide: Text.ElideRight
}
QQC2.Label {
text: portalDelegate.supported ? portalDelegate.example : portalDelegate.unsupportedReason
visible: text.length > 0
opacity: 0.6
font: Kirigami.Theme.smallFont
Layout.fillWidth: true
wrapMode: Text.WordWrap
}
}
QQC2.ComboBox {
enabled: portalDelegate.supported
model: [i18n("Unset"), i18n("Allowed"), i18n("Disallowed")]
currentIndex: portalDelegate.value === 4 ? 1 : (portalDelegate.value === 3 ? 2 : 0)
onActivated: page.controller.setPortalValue(portalDelegate.index, portalDelegate.states[currentIndex])
}
}
}
}
// "Add entry" affordance
DelegateChoice {
roleValue: 6
delegate: QQC2.ItemDelegate {
id: addDelegate
required property string categoryId
width: ListView.view.width
icon.name: "list-add"
text: i18nc("@action", "Add…")
onClicked: page.controller.addEntry(categoryId)
}
}
}
}
// Shared delegate for path / relative-path entries.
property Component entryDelegate: Component {
QQC2.ItemDelegate {
id: pathDelegate
required property int index
required property string value
required property string categoryId
required property int status
required property bool removable
width: ListView.view.width
hoverEnabled: true
background: null
contentItem: RowLayout {
spacing: Kirigami.Units.smallSpacing
QQC2.TextField {
text: pathDelegate.value
placeholderText: pathDelegate.categoryId === "persistent" ? i18n("e.g. .thunderbird") : i18n("e.g. ~/games:ro")
Layout.fillWidth: true
onTextEdited: page.controller.setEntryPrimary(pathDelegate.index, text)
}
StatusBadge {
badgeStatus: pathDelegate.status
}
QQC2.ToolButton {
icon.name: "edit-delete-remove"
visible: pathDelegate.removable
onClicked: page.controller.removeEntry(pathDelegate.index)
}
}
}
}
}