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
+103
View File
@@ -0,0 +1,103 @@
# SPDX-License-Identifier: GPL-3.0-or-later
name: Build and Publish Flatpak
on:
push:
tags:
- 'v*'
workflow_dispatch: {}
permissions:
contents: write # create releases / upload the bundle
pages: write # deploy the hosted Flatpak repo
id-token: write # required by actions/deploy-pages
concurrency:
group: pages
cancel-in-progress: false
jobs:
build:
name: Build Flatpak
runs-on: ubuntu-latest
container:
# Ships the KDE Platform/Sdk + flatpak-builder. Bump the tag to match
# runtime-version in the manifest.
image: ghcr.io/flathub-infra/flatpak-github-actions:kde-6.10
options: --privileged
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Build from the checked-out commit
run: |
python3 - <<'PY'
import re
p = "io.github.toservetheking.FlatKontrol.yml"
s = open(p).read()
s = re.sub(r" sources:.*\Z",
" sources:\n - type: dir\n path: .\n",
s, flags=re.S)
open(p, "w").write(s)
print(s)
PY
- name: Build repo and bundle
run: |
flatpak-builder --user --disable-rofiles-fuse --force-clean \
--default-branch=stable --repo=repo \
builddir io.github.toservetheking.FlatKontrol.yml
flatpak build-update-repo repo --generate-static-deltas
flatpak build-bundle repo \
io.github.toservetheking.FlatKontrol.flatpak \
io.github.toservetheking.FlatKontrol stable
- name: Add repo landing page and .flatpakrepo
run: |
cat > repo/flatkontrol.flatpakrepo <<'EOF'
[Flatpak Repo]
Title=FlatKontrol
Url=https://toservetheking.github.io/FlatKontrol/
Homepage=https://github.com/toservetheking/FlatKontrol
Description=Manage Flatpak permissions
EOF
cat > repo/index.html <<'EOF'
<!doctype html>
<meta charset="utf-8">
<title>FlatKontrol Flatpak repository</title>
<h1>FlatKontrol</h1>
<p>Add the repository and install:</p>
<pre>flatpak remote-add --if-not-exists --user flatkontrol https://toservetheking.github.io/FlatKontrol/flatkontrol.flatpakrepo
flatpak install --user flatkontrol io.github.toservetheking.FlatKontrol</pre>
<p>Or download the single-file bundle from the
<a href="https://github.com/toservetheking/FlatKontrol/releases">Releases page</a>.</p>
EOF
- name: Upload bundle artifact
uses: actions/upload-artifact@v4
with:
name: flatpak-bundle
path: io.github.toservetheking.FlatKontrol.flatpak
- name: Attach bundle to release
if: startsWith(github.ref, 'refs/tags/')
uses: softprops/action-gh-release@v2
with:
files: io.github.toservetheking.FlatKontrol.flatpak
- name: Upload Pages artifact
uses: actions/upload-pages-artifact@v3
with:
path: repo
deploy-pages:
name: Deploy hosted repo to Pages
needs: build
runs-on: ubuntu-latest
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
steps:
- name: Deploy
id: deployment
uses: actions/deploy-pages@v4
+10
View File
@@ -0,0 +1,10 @@
# Build output
/build/
/builddir/
# Flatpak build artifacts
/.flatpak-builder/
/repo/
*.flatpak
# Editor / misc
*.user
*.autosave
+61
View File
@@ -0,0 +1,61 @@
# SPDX-License-Identifier: GPL-3.0-or-later
# FlatKontrol - a Kirigami/Qt Flatpak permissions manager
cmake_minimum_required(VERSION 3.16)
project(flatkontrol VERSION 0.1.0 LANGUAGES CXX)
set(REQUIRED_QT_VERSION 6.6.0)
set(REQUIRED_KF_VERSION 6.5.0)
find_package(ECM ${REQUIRED_KF_VERSION} REQUIRED NO_MODULE)
set(CMAKE_MODULE_PATH ${ECM_MODULE_PATH})
include(KDEInstallDirs)
include(KDECMakeSettings)
include(KDECompilerSettings NO_POLICY_SCOPE)
include(ECMSetupVersion)
include(FeatureSummary)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
find_package(Qt6 ${REQUIRED_QT_VERSION} REQUIRED COMPONENTS
Core
Gui
Widgets
Qml
Quick
QuickControls2
DBus
)
find_package(KF6 ${REQUIRED_KF_VERSION} REQUIRED COMPONENTS
I18n
CoreAddons
IconThemes
Crash
DBusAddons
)
ecm_setup_version(${PROJECT_VERSION}
VARIABLE_PREFIX FLATKONTROL
VERSION_HEADER "${CMAKE_CURRENT_BINARY_DIR}/flatkontrol-version.h"
)
add_subdirectory(src)
install(PROGRAMS io.github.toservetheking.FlatKontrol.desktop
DESTINATION ${KDE_INSTALL_APPDIR})
install(FILES io.github.toservetheking.FlatKontrol.metainfo.xml
DESTINATION ${KDE_INSTALL_METAINFODIR})
install(FILES icons/io.github.toservetheking.FlatKontrol.svg
DESTINATION ${KDE_INSTALL_ICONDIR}/hicolor/scalable/apps)
install(FILES LICENSES/GPL-3.0-or-later.txt
DESTINATION ${KDE_INSTALL_DATAROOTDIR}/licenses/${PROJECT_NAME})
# Translations: add a po/ directory and re-enable ki18n_install(po) once present.
feature_summary(WHAT ALL INCLUDE_QUIET_PACKAGES FATAL_ON_MISSING_REQUIRED_PACKAGES)
+675
View File
@@ -0,0 +1,675 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
+73
View File
@@ -0,0 +1,73 @@
# FlatKontrol
A Flatpak permissions manager built the KDE way - C++ with a QML/Kirigami
frontend, ECM/CMake, and KDE Frameworks 6. Think [Flatseal], reimagined as if
the team behind [Elisa] had written it.
It reads each application's baseline permissions from its bundle `metadata`,
layers the global and per-application override files on top (the same
original → global → user resolution Flatseal uses), and writes changes back to
`~/.local/share/flatpak/overrides/`. Dynamic portal permissions are edited over
D-Bus via `org.freedesktop.impl.portal.PermissionStore`.
## Features
- Share (network, IPC), Sockets, Devices, Features - toggles
- Filesystem presets + custom paths (with `:ro`/`:rw`/`:create` and negation)
- Persistent home-relative directories
- Environment variables
- Session / System D-Bus name policies (talk / own)
- Portals (background, notifications, microphone, speakers, camera, location)
- Per-application reset with undo, and global defaults via the "All Applications" entry
- Live refresh when applications are installed or removed
## Install
Tagged releases are built by CI into a single-file bundle (attached to each
[GitHub Release]) and a hosted Flatpak repository on GitHub Pages:
```sh
flatpak remote-add --if-not-exists --user flatkontrol \
https://toservetheking.github.io/FlatKontrol/flatkontrol.flatpakrepo
flatpak install --user flatkontrol io.github.toservetheking.FlatKontrol
```
Or install the downloaded bundle directly:
```sh
flatpak install --user ./io.github.toservetheking.FlatKontrol.flatpak
```
[GitHub Release]: https://github.com/toservetheking/FlatKontrol/releases
## Building
Requires Qt 6, KDE Frameworks 6, Kirigami, Kirigami Addons and the CMake
toolchain. On Arch/CachyOS:
```sh
sudo pacman -S --needed cmake extra-cmake-modules base-devel \
qt6-base qt6-declarative kirigami kirigami-addons \
ki18n kcoreaddons kiconthemes kcrash kdbusaddons kitemmodels qqc2-desktop-style
```
Then:
```sh
cmake -B build -G Ninja
cmake --build build
./build/bin/flatkontrol
```
## Architecture
- `keyfile.{h,cpp}` - minimal GKeyFile/flatpak-compatible INI reader/writer.
- `flatpakinstallations.{h,cpp}` - installation discovery and per-app metadata/icon.
- `applicationsmodel.{h,cpp}` - sidebar model (`QAbstractListModel`, `QML_ELEMENT`).
- `permissioncatalog.{h,cpp}` - the static catalog of categories and options.
- `portalsbackend.{h,cpp}` - QtDBus PermissionStore client.
- `permissionscontroller.{h,cpp}` - per-app state, resolution, and the row model.
- `qml/` - Kirigami UI.
[Flatseal]: https://github.com/tchx84/Flatseal
[Elisa]: https://invent.kde.org/multimedia/elisa
@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- SPDX-License-Identifier: GPL-3.0-or-later -->
<svg width="128" height="128" viewBox="0 0 128 128" xmlns="http://www.w3.org/2000/svg">
<defs>
<linearGradient id="bg" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="#3daee9"/>
<stop offset="1" stop-color="#2b6cb0"/>
</linearGradient>
</defs>
<!-- rounded-square backdrop -->
<rect x="8" y="8" width="112" height="112" rx="28" ry="28" fill="url(#bg)"/>
<!-- three permission toggles -->
<g>
<!-- on -->
<rect x="32" y="34" width="64" height="16" rx="8" fill="#ffffff" fill-opacity="0.35"/>
<circle cx="88" cy="42" r="11" fill="#ffffff"/>
<!-- off -->
<rect x="32" y="56" width="64" height="16" rx="8" fill="#ffffff" fill-opacity="0.25"/>
<circle cx="40" cy="64" r="11" fill="#ffffff" fill-opacity="0.75"/>
<!-- on -->
<rect x="32" y="78" width="64" height="16" rx="8" fill="#ffffff" fill-opacity="0.35"/>
<circle cx="88" cy="86" r="11" fill="#ffffff"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

@@ -0,0 +1,11 @@
[Desktop Entry]
Type=Application
Name=FlatKontrol
GenericName=Flatpak Permissions
Comment=Manage Flatpak permissions
Icon=io.github.toservetheking.FlatKontrol
Exec=flatkontrol
Terminal=false
Categories=Qt;KDE;Settings;
Keywords=flatpak;sandbox;permissions;flatseal;
StartupWMClass=flatkontrol
@@ -0,0 +1,70 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- SPDX-License-Identifier: CC0-1.0 -->
<component type="desktop-application">
<id>io.github.toservetheking.FlatKontrol</id>
<metadata_license>CC0-1.0</metadata_license>
<project_license>GPL-3.0-or-later</project_license>
<name>FlatKontrol</name>
<summary>Manage Flatpak permissions</summary>
<keywords>
<keyword>flatpak</keyword>
<keyword>sandbox</keyword>
<keyword>permissions</keyword>
<keyword>overrides</keyword>
<keyword>flatseal</keyword>
</keywords>
<description>
<p>
FlatKontrol is a Kirigami application for reviewing and changing the
permissions of installed Flatpak applications. It edits the same override
files as Flatpak's own tooling, so changes apply system-wide.
</p>
<p>It can manage:</p>
<ul>
<li>Shared subsystems (network, IPC)</li>
<li>Sockets, devices and extra features</li>
<li>Filesystem access, including custom paths and persistent directories</li>
<li>Environment variables</li>
<li>Session and system D-Bus name policies</li>
<li>Dynamic portal permissions</li>
</ul>
</description>
<launchable type="desktop-id">io.github.toservetheking.FlatKontrol.desktop</launchable>
<screenshots>
<screenshot type="default">
<image>https://raw.githubusercontent.com/toservetheking/FlatKontrol/main/screenshots/main.png</image>
<caption>Reviewing and adjusting an application's permissions</caption>
</screenshot>
</screenshots>
<branding>
<color type="primary" scheme_preference="light">#7fc7ee</color>
<color type="primary" scheme_preference="dark">#2b6cb0</color>
</branding>
<url type="homepage">https://github.com/toservetheking/FlatKontrol</url>
<url type="bugtracker">https://github.com/toservetheking/FlatKontrol/issues</url>
<provides>
<binary>flatkontrol</binary>
</provides>
<developer id="io.github.toservetheking">
<name>toservetheking</name>
</developer>
<content_rating type="oars-1.1"/>
<releases>
<release version="0.1.0" date="2026-06-30">
<description>
<p>Initial release.</p>
</description>
</release>
</releases>
</component>
+44
View File
@@ -0,0 +1,44 @@
# SPDX-License-Identifier: GPL-3.0-or-later
id: io.github.toservetheking.FlatKontrol
runtime: org.kde.Platform
# Use the latest Flathub KDE runtime available at submission time.
runtime-version: '6.10'
sdk: org.kde.Sdk
command: flatkontrol
# Permissions mirror Flatseal's published manifest exactly - the accepted shape
# for a Flatpak-permissions manager. No --filesystem=host, no --socket=session-bus,
# no wildcard --talk-name, no --device=all.
finish-args:
- --share=ipc
- --socket=fallback-x11
- --socket=wayland
- --device=dri
# Read installed apps' metadata (system + user installations).
- --filesystem=/var/lib/flatpak/app:ro
- --filesystem=xdg-data/flatpak/app:ro
# Read/write the per-app and global override files.
- --filesystem=xdg-data/flatpak/overrides:create
# Edit dynamic portal permissions.
- --talk-name=org.freedesktop.impl.portal.PermissionStore
cleanup:
- /include
- /lib/pkgconfig
- '*.a'
modules:
- name: flatkontrol
buildsystem: cmake-ninja
config-opts:
- -DCMAKE_BUILD_TYPE=Release
sources:
# For Flathub / release builds, pin to a tag AND commit:
- type: git
url: https://github.com/toservetheking/FlatKontrol.git
tag: v0.1.0
# commit: <fill in the exact commit SHA the tag points at>
#
# For local testing before the repo is pushed, replace the source above with:
# - type: dir
# path: .
Binary file not shown.

After

Width:  |  Height:  |  Size: 233 KiB

+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)
}
}
}
}
}