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:
@@ -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:
|
||||
|
||||
Reference in New Issue
Block a user