Give each default-application role a whole family of types

Every role carried a single representative type, so setting "Images"
changed image/png and left image/jpeg wherever it landed. That is how
this desktop ended up opening PDFs in GIMP, PNGs in a pixel-art editor
and MP3s in a video transcoder: nobody chose any of it, applications
registered themselves for everything they could read, and the roles
governed one type each.

Roles now own families and write every type when set, the settings page
exposes the documents, text and archives roles it never offered, and a
new seed command curates a fresh machine during setup while always
keeping a choice the user has already made.

The shipped editor entry launches kitty explicitly. The stock
nvim.desktop sets Terminal=true, which defers to whatever the system
considers default rather than the terminal this desktop themes.

Claude-Session: https://claude.ai/code/session_01BRvzt4H8XXLPVH5MyYdk9L
This commit is contained in:
Gabriel Brown
2026-08-19 09:17:33 -04:00
parent 2fcaada7e8
commit b4ce148caf
6 changed files with 355 additions and 42 deletions
@@ -14,14 +14,21 @@ SettingsPage {
property string expandedRole: ""
property bool addingAutostart: false
readonly property var applications: DesktopEntries.applications.values
// Each role governs a whole family of types, not one representative: setting
// "Images" writes PNG, JPEG, WebP and the rest together, so a file manager
// can never open one image in a viewer and its neighbour in an editor.
// The detail line names the family the way someone would describe it.
readonly property var roles: [
{ key: "browser", label: "Browser", detail: "Web links and HTML pages", categorySets: [["webbrowser"]], terms: ["web browser", "browser"] },
{ key: "mail", label: "Mail", detail: "Email links", categorySets: [["email"]], terms: ["mail client", "email client"] },
{ key: "files", label: "Files", detail: "Folders and file locations", categorySets: [["filemanager"]], terms: ["file manager"] },
{ key: "terminal", label: "Terminal", detail: "Terminal links and command-line handoffs", categorySets: [["terminalemulator"]], terms: ["terminal emulator", "terminal"] },
{ key: "music", label: "Music", detail: "MP3 audio", categorySets: [["music"], ["audio", "player"]], terms: ["music player", "audio player"] },
{ key: "images", label: "Images", detail: "PNG images", categorySets: [], terms: ["image viewer", "image editor", "photo viewer", "photo editor", "picture viewer"] },
{ key: "video", label: "Video", detail: "MP4 video", categorySets: [["video"]], terms: ["video player", "movie player"] }
{ key: "images", label: "Images", detail: "PNG, JPEG, GIF, WebP, SVG and other pictures", categorySets: [], terms: ["image viewer", "image editor", "photo viewer", "photo editor", "picture viewer"] },
{ key: "music", label: "Music", detail: "MP3, FLAC, Ogg and other audio", categorySets: [["music"], ["audio", "player"]], terms: ["music player", "audio player"] },
{ key: "video", label: "Video", detail: "MP4, MKV, WebM and other video", categorySets: [["video"]], terms: ["video player", "movie player"] },
{ key: "documents", label: "Documents", detail: "PDF and EPUB documents", categorySets: [["office", "viewer"]], terms: ["document viewer", "pdf viewer", "ebook", "e-book"] },
{ key: "text", label: "Text", detail: "Plain text, Markdown, and source files", categorySets: [["texteditor"]], terms: ["text editor", "code editor"] },
{ key: "archives", label: "Archives", detail: "Zip, tar, and other archives", categorySets: [["archiving"], ["filemanager"]], terms: ["archive manager", "file roller", "file manager"] }
]
function desktopId(entry: var): string {
+124 -16
View File
@@ -14,14 +14,46 @@ import sys
import tempfile
# A role owns a FAMILY of types, not one representative.
#
# Each role used to carry a single mime type, so setting "images" changed
# image/png and left image/jpeg wherever it happened to land. That is exactly
# how this machine ended up opening PNGs in a pixel-art editor, MP3s in a video
# transcoder and PDFs in GIMP: nobody chose any of it, the applications
# registered themselves and the roles only ever governed one type each.
#
# The FIRST entry in each list is the one queried when reporting the current
# handler; all of them are written when the role is set, so a family cannot
# drift apart again.
ROLE_TARGETS = {
"browser": ("settings", "default-web-browser"),
"mail": ("mime", "x-scheme-handler/mailto"),
"files": ("mime", "inode/directory"),
"terminal": ("mime", "x-scheme-handler/terminal"),
"music": ("mime", "audio/mpeg"),
"images": ("mime", "image/png"),
"video": ("mime", "video/mp4"),
"browser": ("settings", ["default-web-browser"]),
"mail": ("mime", ["x-scheme-handler/mailto"]),
"files": ("mime", ["inode/directory"]),
"terminal": ("mime", ["x-scheme-handler/terminal"]),
"music": ("mime", [
"audio/mpeg", "audio/flac", "audio/x-vorbis+ogg", "audio/ogg",
"audio/x-wav", "audio/mp4", "audio/aac", "audio/opus",
]),
"images": ("mime", [
"image/png", "image/jpeg", "image/gif", "image/webp",
"image/tiff", "image/bmp", "image/svg+xml", "image/avif",
]),
"video": ("mime", [
"video/mp4", "video/x-matroska", "video/webm", "video/quicktime",
"video/x-msvideo", "video/mpeg",
]),
"documents": ("mime", [
"application/pdf", "application/epub+zip",
]),
"text": ("mime", [
"text/plain", "text/markdown", "text/x-python", "text/x-csrc",
"text/x-chdr", "text/x-c++src", "text/x-shellscript",
"application/json", "application/x-yaml", "text/xml",
]),
"archives": ("mime", [
"application/zip", "application/x-tar", "application/gzip",
"application/x-7z-compressed", "application/vnd.rar",
]),
}
DESKTOP_ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._+-]*\.desktop$")
EXEC_CMD = re.compile(r"hl\.exec_cmd\(\s*(\"(?:\\.|[^\"\\])*\")\s*\)")
@@ -70,7 +102,9 @@ def run(command: list[str]) -> str:
def query_handlers() -> dict[str, str]:
handlers: dict[str, str] = {}
for role, (kind, target) in ROLE_TARGETS.items():
for role, (kind, targets) in ROLE_TARGETS.items():
# The first type represents the family when reporting.
target = targets[0]
command = (
["xdg-settings", "get", target]
if kind == "settings"
@@ -179,13 +213,85 @@ def set_default(role: str, desktop_id: str) -> None:
if target is None:
raise BoundaryError("That default application role is not supported.")
require_desktop_id(desktop_id, discovered=discovered_desktop_ids())
kind, setting = target
command = (
["xdg-settings", "set", setting, desktop_id]
if kind == "settings"
else ["xdg-mime", "default", desktop_id, setting]
)
run(command)
kind, settings = target
if kind == "settings":
run(["xdg-settings", "set", settings[0], desktop_id])
return
# Every type in the family, so a role cannot be half-applied. xdg-mime
# accepts several types in one call, but they are written individually so a
# type this system does not know about cannot fail the whole role.
for setting in settings:
run(["xdg-mime", "default", desktop_id, setting])
# What this desktop opens a file with, when nobody has said otherwise.
#
# Applications register themselves for every type they can technically read, so
# an unattended machine decides these by installation order: a pixel-art editor
# claims PNG, a video transcoder claims MP3, an image editor claims PDF. None of
# that is a choice anyone made, and it is only discovered by double-clicking.
#
# Each role lists candidates best-first; the first one installed wins. A role
# with no candidate installed is left alone rather than forced.
PREFERRED_HANDLERS = {
"images": ["org.gnome.Loupe.desktop", "org.gnome.eog.desktop"],
"music": ["org.gnome.Decibels.desktop", "io.bassi.Amberol.desktop", "io.mpv.Mpv.desktop"],
"video": ["io.mpv.Mpv.desktop", "mpv.desktop", "org.gnome.Totem.desktop"],
"documents": ["org.gnome.Papers.desktop", "org.gnome.Evince.desktop"],
"text": ["panama-nvim.desktop"],
"archives": ["org.gnome.Nautilus.desktop", "org.gnome.FileRoller.desktop"],
}
def user_mimeapps() -> Path:
config_home = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config"))
return config_home / "mimeapps.list"
def chosen_types() -> set[str]:
"""Types the person using this machine has already assigned by hand.
A type listed under [Default Applications] in the user's own mimeapps.list
got there because someone picked "Open With" and made it stick, or because
the settings page wrote it. Seeding must never overrule that.
"""
path = user_mimeapps()
if not path.is_file():
return set()
chosen: set[str] = set()
section = ""
try:
lines = path.read_text(encoding="utf-8").splitlines()
except (OSError, UnicodeError):
return set()
for line in lines:
stripped = line.strip()
if stripped.startswith("[") and stripped.endswith("]"):
section = stripped[1:-1]
continue
if section != "Default Applications" or "=" not in line or stripped.startswith("#"):
continue
chosen.add(line.split("=", 1)[0].strip())
return chosen
def seed() -> None:
"""Apply Panama's curated defaults to roles nobody has chosen for."""
discovered = discovered_desktop_ids()
already = chosen_types()
for role, candidates in PREFERRED_HANDLERS.items():
kind, targets = ROLE_TARGETS[role]
if kind != "mime":
continue
if any(target in already for target in targets):
print(f"{role}: keeping the existing choice")
continue
preferred = next((entry for entry in candidates if entry in discovered), None)
if preferred is None:
print(f"{role}: no preferred application installed, leaving it alone")
continue
set_default(role, preferred)
print(f"{role}: {preferred}")
def with_hidden(original: str, *, hidden: bool) -> str:
@@ -294,6 +400,8 @@ def main(arguments: list[str]) -> int:
try:
if arguments == ["snapshot"]:
print(json.dumps(snapshot(), separators=(",", ":")))
elif arguments == ["seed"]:
seed()
elif len(arguments) == 3 and arguments[0] == "set-default":
set_default(arguments[1], arguments[2])
elif len(arguments) == 3 and arguments[0] == "set-autostart":
@@ -302,7 +410,7 @@ def main(arguments: list[str]) -> int:
add_autostart(arguments[1])
else:
raise BoundaryError(
"Usage: panama-default-apps snapshot | set-default ROLE DESKTOP_ID | "
"Usage: panama-default-apps snapshot | seed | set-default ROLE DESKTOP_ID | "
"set-autostart DESKTOP_ID true|false | add-autostart DESKTOP_ID"
)
except BoundaryError as error:
@@ -0,0 +1,17 @@
[Desktop Entry]
Type=Application
Name=Neovim
GenericName=Text Editor
Comment=Edit text in a Panama terminal window
# The stock nvim.desktop sets Terminal=true, which hands the launch to whatever
# the system considers the default terminal -- not necessarily the one this
# desktop ships and themes. Naming kitty explicitly means a text file opened
# from the file manager lands in the same terminal, with the same font and the
# same colour scheme, as one opened from the dock.
Exec=kitty --class panama-editor -e nvim %F
Icon=nvim
Terminal=false
StartupNotify=false
Categories=Utility;TextEditor;
MimeType=text/plain;text/markdown;text/english;text/x-makefile;text/x-c++hdr;text/x-c++src;text/x-chdr;text/x-csrc;text/x-java;text/x-moc;text/x-pascal;text/x-tcl;text/x-tex;application/x-shellscript;text/x-c;text/x-c++;text/x-python;application/json;text/xml;
Keywords=vim;neovim;editor;text;code;