Files
DroidDeck/tools/linuxfs/overlay/usr/local/bin/droiddeck-open
T
Kurt HimebauchandK11MCH1 906e60a042 feat(desktop): show programs installed by Windows installers (#2146)
* Desktop: programs a Windows installer adds get a menu entry and desktop icon

Opening a Windows installer on the desktop runs it with Proton in a prefix
of its own (droiddeck-proton-run's "own" prefix). Proton's menu builder
turns the installer's Start Menu links into .desktop files, but keeps them
in the prefix's drive_c/proton_shortcuts with a Windows .lnk path as Exec,
and nothing outside the prefix pointed at the installed program: Nexon
Launcher installed fine on an AYANEO Pocket FIT Elite and could only be
found by browsing the hidden compatdata folder.

droiddeck-desktop-programs reads proton_shortcuts in every prefix that is
neither a Steam game's nor a current Steam shortcut's, resolves each link to
its program inside the prefix, and writes a menu entry that opens it with
droiddeck-open, so it runs in that same prefix, with the icon Proton
extracted. A program whose installer also put a link on the Windows desktop
gets a desktop icon once; one the user deletes is not put back. Entries go
away with their program; uninstallers get none. It runs when the desktop
starts and after droiddeck-open finishes a Windows program.

* Desktop programs: only programs that run in their prefix, Windows argument rules, one refresh at a time

A link resolved through Proton's Z: mapping could name a program outside
the scanned prefix, and droiddeck-open would then run it in another one.
A program is now listed only when droiddeck-proton-run's prefix_of puts it
in the prefix it was found in.

Shortcut arguments were split with shlex, so a Windows argument with an
apostrophe raised and stopped the whole refresh; they are now split by
the Windows command-line rules.

The desktop start and the end of a Windows program can refresh at the
same time and race on the same temporary files; refreshes now take turns
on a lock beside the placement record.

* Desktop programs: extract the script at session start

SessionFiles lists the overlay scripts the app copies into the runtime;
droiddeck-desktop-programs was missing, so a real build would never have
installed it and check_session_assets failed the build.

* Desktop programs: a compatdata folder it cannot read changes nothing

Any error listing steamapps/compatdata made the refresh see no prefixes,
so it removed every program entry and forgot which desktop icons it had
placed; the next good run then put back icons the user had deleted. Only a
missing compatdata now means there is nothing installed; any other read
error leaves the menu, the desktop and the placement record as they were.

* Desktop programs: an unreadable shortcut or desktop folder changes nothing

os.path.isdir and glob read an unreadable proton_shortcuts or Windows
desktop folder as empty, so the refresh dropped that prefix's entries and
placement records and a later run put back icons the user had deleted.
Those folders are now listed directly: a missing one is still empty, and
any other error leaves the menu, the desktop and the record as they were.

* Desktop programs: only a missing file reads as absent

read(), link_target() and host_path()'s letter-case lookup turned any
error into "absent", so an unreadable placement record read as empty and
brought back icons the user had deleted, and an unreadable shortcut or
link dropped its program's entry. A missing file, a wrong file type and a
malformed link still read as absent; any other error now reaches main(),
which leaves the menu, the desktop and the record as they were.

* Desktop programs: keep the placement record true when a run fails part way

The placement record was read after the menu was already rewritten, so an
unreadable record changed the menu although the run reported it had not.
It is now read first.

When writing desktop icons failed part way, the icons already written were
not recorded, and the next run recreated any of them the user had deleted.
The record is now written from the icons that exist after the attempt,
icons are written in a fixed order, and a failed write leaves no temporary
file on the desktop.

os.path.exists and isfile also read a program whose path cannot be reached
as missing; a stat that fails only because the file is absent now counts
as missing, and any other error leaves everything as it was.

* Desktop programs: leave the menu alone when Steam's shortcuts cannot be read

The list of Steam shortcuts comes from a reader that treats an unreadable
or damaged shortcuts.vdf as having no shortcuts, so a Steam shortcut's
prefix could get a menu entry and a desktop icon of its own. The file is
now checked first: a missing one still means no shortcuts, and any other
read or parse failure leaves the menu and the desktop as they were.

* Desktop programs: an unreadable Steam account or empty shortcuts file also stops the refresh

account_dir takes an unreadable loginusers.vdf or userdata folder as
missing, so the shortcuts check could be skipped and a Steam shortcut's
prefix still get its own entry. Both are now read first, and an access
error leaves the menu as it was.

An empty shortcuts.vdf is now parsed like any other, so it stops the
refresh too, the same way droiddeck-steam-shortcuts refuses to rewrite it.

---------

Co-authored-by: K11MCH1 <81425424+K11MCH1@users.noreply.github.com>
2026-11-05 18:33:15 -05:00

409 lines
15 KiB
Python

#!/usr/bin/python3
import fcntl
import hashlib
import os
import runpy
import shutil
import stat
import subprocess
import sys
import time
HOME = os.environ.get("HOME") or "/root"
BIN = "/usr/local/bin"
FEX = os.path.join(BIN, "droiddeck-fex")
GPU = os.path.join(BIN, "droiddeck-gpu")
PROTON_RUN = os.path.join(BIN, "droiddeck-proton-run")
APPIMAGE_RUN = os.path.join(BIN, "droiddeck-appimage-run")
SCRIPT_RUN = os.path.join(BIN, "droiddeck-script-run")
STEAM_LAUNCH = os.path.join(BIN, "droiddeck-steam-launch")
PROGRAMS = os.path.join(BIN, "droiddeck-desktop-programs")
CACHE = os.path.join(HOME, ".cache", "droiddeck")
IMPORTS = {"appimage": ("/opt/appimages/user", "app"), "folder": ("/opt/droiddeck-apps", "entry")}
SHARED_FOLDERS = ("alarms", "android", "audiobooks", "dcim", "documents", "download", "movies", "music",
"notifications", "pictures", "podcasts", "recordings", "ringtones")
SCAN_LIMIT = 4000
APPS_DIR = "/usr/local/share/applications"
WINDOWS = (".exe", ".bat", ".cmd", ".com", ".msi")
NOT_PROGRAMS = (".dll", ".sys", ".drv", ".cpl", ".ocx", ".efi", ".scr", ".mui")
SCRIPTS = (".sh", ".bash")
MACHINES = {3: "i386", 62: "x86_64", 183: "arm64"}
EMULATED = (3, 62)
QUICK_FAILURE = 20
IMPORT_WAIT = 1800
WINDOWS_TYPES = ("application/x-ms-dos-executable", "application/x-msdownload",
"application/vnd.microsoft.portable-executable", "application/x-msi", "application/x-bat")
SCRIPT_TYPES = ("application/x-shellscript", "text/x-shellscript")
LINUX_TYPES = ("application/x-executable", "application/x-pie-executable", "application/vnd.appimage")
ENTRIES = (
("droiddeck-open.desktop", "Run", "", WINDOWS_TYPES + SCRIPT_TYPES + LINUX_TYPES),
("droiddeck-open-window.desktop", "Run in a Desktop Window", "--window ", WINDOWS_TYPES + SCRIPT_TYPES + LINUX_TYPES),
("droiddeck-open-terminal.desktop", "Run in Konsole", "--terminal ", SCRIPT_TYPES + LINUX_TYPES),
)
def say(message):
print("droiddeck-open: %s" % message, file=sys.stderr, flush=True)
def notify(title, body, icon="dialog-error"):
if not os.environ.get("DBUS_SESSION_BUS_ADDRESS") or not shutil.which("notify-send"):
return
try:
subprocess.run(["notify-send", "-a", "DroidDeck", "-i", icon, title, body],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=5)
except (OSError, subprocess.SubprocessError):
pass
def head(path, size=64):
try:
with open(path, "rb") as f:
return f.read(size)
except OSError:
return b""
def machine(data):
if len(data) < 20 or data[:4] != b"\x7fELF":
return None
return int.from_bytes(data[18:20], "big" if data[5] == 2 else "little")
def kind(path):
data = head(path)
ext = os.path.splitext(path)[1].lower()
if data[:4] == b"\x7fELF":
return "appimage" if data[8:11] == b"AI\x02" or ext == ".appimage" else "elf"
if ext in NOT_PROGRAMS:
return None
if ext in WINDOWS or data[:2] == b"MZ":
return "windows"
if data[:2] == b"#!" or ext in SCRIPTS:
return "script"
return None
def noexec(path):
try:
return bool(os.statvfs(path).f_flag & os.ST_NOEXEC)
except OSError:
return False
def interpreter(path):
line = head(path, 256).split(b"\n", 1)[0].rstrip(b"\r")
if line.startswith(b"#!"):
words = line[2:].decode("utf-8", "replace").split()
if words:
return words
return ["/bin/bash"]
def for_x86(script):
return subprocess.call([FEX, "needs", os.path.dirname(script)], stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL) == 0
def runnable(path):
if not noexec(path) or machine(head(path)) in EMULATED:
return path
st = os.stat(path)
key = hashlib.sha1(os.path.realpath(path).encode("utf-8")).hexdigest()[:16]
copy = os.path.join(CACHE, "exec", key, os.path.basename(path))
try:
same = os.stat(copy)
if same.st_size == st.st_size and same.st_mtime_ns == st.st_mtime_ns:
return copy
except OSError:
pass
os.makedirs(os.path.dirname(copy), exist_ok=True)
shutil.copyfile(path, copy + ".tmp")
os.utime(copy + ".tmp", ns=(st.st_atime_ns, st.st_mtime_ns))
os.chmod(copy + ".tmp", 0o755)
os.replace(copy + ".tmp", copy)
return copy
def appimage(path):
st = os.stat(path)
real = os.path.realpath(path)
key = hashlib.sha1(("%s\0%d\0%d" % (real, st.st_size, st.st_mtime_ns)).encode("utf-8")).hexdigest()[:16]
images = os.path.join(CACHE, "appimages")
return once(key, lambda: unpacked(path, real, key, images, os.path.join(images, key)))
def once(key, make):
locks = os.path.join(CACHE, "locks")
os.makedirs(locks, exist_ok=True)
with open(os.path.join(locks, key), "w") as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
return make()
def unpacked(path, real, key, images, folder):
if os.path.exists(os.path.join(folder, "app", "AppRun")):
return folder
earlier = import_of(key, "appimage")
if earlier:
return earlier
name = os.path.splitext(os.path.basename(path))[0]
notify("Preparing %s" % name, "Unpacking it for its first start.", "system-run")
work = folder + ".tmp"
shutil.rmtree(work, ignore_errors=True)
os.makedirs(work)
status = subprocess.call([FEX, "extract", real], cwd=work, stdout=subprocess.DEVNULL)
unpacked = os.path.realpath(os.path.join(work, "squashfs-root"))
if status != 0 or not os.path.isdir(unpacked):
shutil.rmtree(work, ignore_errors=True)
return imported("appimage", real, key, name)
os.replace(unpacked, os.path.join(work, "app"))
if os.path.islink(os.path.join(work, "squashfs-root")):
os.unlink(os.path.join(work, "squashfs-root"))
for file, value in (("name", name), ("arch", MACHINES.get(machine(head(path)), "")), ("source", real)):
with open(os.path.join(work, file), "w", encoding="utf-8") as f:
f.write(value + "\n")
for other in os.listdir(images):
old = os.path.join(images, other)
if other != key + ".tmp" and (head(os.path.join(old, "source"), 4096).decode("utf-8", "replace").strip() == real):
shutil.rmtree(old, ignore_errors=True)
os.replace(work, folder)
return folder
def import_of(key, what):
root, made = IMPORTS[what]
try:
entries = sorted(os.listdir(root))
except OSError:
return None
for entry in entries:
folder = os.path.join(root, entry)
if head(os.path.join(folder, "desktop-import"), 64).split(b"\n", 1)[0] == key.encode() \
and os.path.exists(os.path.join(folder, made)):
return folder
return None
def imported(what, real, key, name):
launch = os.environ.get("BL_LAUNCH_DIR")
if not launch or not os.path.isdir(launch):
raise RuntimeError("%s cannot run from here; add it in DroidDeck with Add an app." % name)
result = os.path.join(launch, "desktop-import-%s.result" % key)
request = os.path.join(launch, "desktop-import-%s.request" % key)
with open(request + ".tmp", "w", encoding="utf-8") as f:
f.write("id=%s\nkind=%s\npath=%s\n" % (key, what, real))
os.replace(request + ".tmp", request)
if what == "appimage":
notify("Adding %s to DroidDeck" % name, "It is unpacked once, then it starts, and it stays in the menu.", "system-run")
else:
notify("Adding %s to DroidDeck" % name, "Shared storage cannot run its programs, so the folder is copied in "
"once; then it starts, and it stays in the menu.", "system-run")
deadline = time.monotonic() + IMPORT_WAIT
while time.monotonic() < deadline:
try:
with open(result, encoding="utf-8") as f:
answer = f.read().strip()
except OSError:
time.sleep(1)
continue
os.unlink(result)
verdict, _, detail = answer.partition(" ")
if verdict == "ok" and os.path.exists(os.path.join(detail, IMPORTS[what][1])):
return detail
raise RuntimeError(detail or "DroidDeck could not add %s." % name)
raise RuntimeError("DroidDeck did not finish adding %s." % name)
def game_folder(path):
real = os.path.realpath(path)
folder = os.path.dirname(real)
if in_steam_library(real) or not noexec(folder):
return None
top = storage_root(folder)
parts = os.path.relpath(folder, top).split(os.sep)
if folder == top or (len(parts) == 1 and parts[0].lower() in SHARED_FOLDERS):
return None
seen = 0
for root, dirs, files in os.walk(folder):
if root[len(folder):].count(os.sep) >= 3:
dirs[:] = []
for name in files:
child = os.path.join(root, name)
if child == real:
continue
seen += 1
if seen > SCAN_LIMIT:
return None
if machine(head(child)) not in (None,) + EMULATED:
return folder
return None
def in_steam_library(path):
return "steamapps" in os.path.realpath(path).lower().split(os.sep)
def storage_root(folder):
top = folder
try:
dev = os.stat(folder).st_dev
while os.path.dirname(top) != top and os.stat(os.path.dirname(top)).st_dev == dev:
top = os.path.dirname(top)
except OSError:
pass
return top
def copied_in(path):
real = os.path.realpath(path)
key = hashlib.sha1(("folder\0%s" % real).encode("utf-8")).hexdigest()[:16]
name = os.path.basename(os.path.dirname(real))
return once(key, lambda: import_of(key, "folder") or imported("folder", real, key, name))
def steam_title(path):
try:
run = runpy.run_path(PROTON_RUN)
root = os.environ.get("STEAM_COMPAT_CLIENT_INSTALL_PATH") or run["STEAM_ROOT"]
target = run["locate"](path, root)
return target.appid if run["steam_launches"](target, path, root) else None
except (OSError, ValueError, KeyError, IndexError):
return None
def command(path, args, what, window=False, appid=None):
folder = os.path.dirname(path)
if what == "steam":
return [STEAM_LAUNCH, "desktop", appid], folder
if what == "windows":
return [PROTON_RUN] + (["--window"] if window else []) + [path] + args, folder
if what == "x86 script":
return [FEX, "run", "--mode", "on", "--for", folder, "--"] + interpreter(path) + [path] + args, folder
if what == "script":
return interpreter(path) + [path] + args, folder
if what == "appimage":
return [APPIMAGE_RUN, appimage(path)] + args, folder
if what == "folder":
return [SCRIPT_RUN, copied_in(path)] + args, folder
return [FEX, "run", "--mode", "auto", "--", runnable(path)] + args, folder
def on_desktop(env):
return env.get("BL_DESKTOP") == "1" and not env.get("GAMESCOPE_WAYLAND_DISPLAY") and os.access(GPU, os.X_OK)
def unattended(env):
try:
out = os.fstat(1)
except OSError:
return True
if stat.S_ISCHR(out.st_mode):
return not os.isatty(1)
folder = env.get("BL_DEBUG_DIR")
try:
log = os.stat(os.path.join(folder, "desktop.log")) if folder else None
except OSError:
log = None
return log is not None and (log.st_dev, log.st_ino) == (out.st_dev, out.st_ino)
def placed(cmd, what, mode, env):
if mode == "terminal" and what not in ("windows", "steam") and shutil.which("konsole"):
return ["konsole", "--hold", "-e"] + cmd
if mode == "window" or what in ("script", "steam") or not on_desktop(env):
return cmd
if mode == "exec" and what != "windows" and not unattended(env):
return cmd
return [GPU] + cmd
def install(directory=APPS_DIR):
os.makedirs(directory, exist_ok=True)
defaults = []
for file, name, option, types in ENTRIES:
body = ("[Desktop Entry]\nType=Application\nName=%s\nIcon=system-run\nExec=%s %s%%f\nTerminal=false\n"
"NoDisplay=true\nMimeType=%s;\n" % (name, os.path.join(BIN, "droiddeck-open"), option, ";".join(types)))
write(os.path.join(directory, file), body)
for mime in WINDOWS_TYPES + SCRIPT_TYPES + LINUX_TYPES:
defaults.append("%s=%s" % (mime, ENTRIES[0][0]))
added = ["%s=%s" % (mime, ";".join(f for f, _, _, types in ENTRIES if mime in types) + ";")
for mime in WINDOWS_TYPES + SCRIPT_TYPES + LINUX_TYPES]
write(os.path.join(directory, "mimeapps.list"),
"[Default Applications]\n%s\n\n[Added Associations]\n%s\n" % ("\n".join(defaults), "\n".join(added)))
return 0
def write(path, text):
try:
with open(path, encoding="utf-8") as f:
if f.read() == text:
return
except OSError:
pass
with open(path + ".tmp", "w", encoding="utf-8") as f:
f.write(text)
os.replace(path + ".tmp", path)
def main(argv):
mode = "run"
if argv and argv[0] == "--install":
return install()
if argv and argv[0] in ("--window", "--terminal", "--exec"):
mode = argv.pop(0)[2:]
if argv and argv[0] == "--":
argv.pop(0)
if not argv:
say("usage: droiddeck-open [--window | --terminal | --exec] FILE [ARGS...] | --install")
return 2
path = os.path.abspath(argv[0])
what = kind(path)
if what is None:
say("%s is not a program this desktop can run" % path)
if mode != "exec":
notify("Cannot run %s" % os.path.basename(path), "It is not a Windows or Linux program or a script.")
return 126
linux_game = what in ("script", "elf") and mode == "run" and in_steam_library(path)
appid = steam_title(path) if (what == "windows" and mode != "window") or linux_game else None
if appid:
what = "steam"
elif what == "script" and for_x86(path):
what = "x86 script"
elif what in ("script", "elf") and game_folder(path):
what = "folder"
try:
cmd, folder = command(path, argv[1:], what, mode == "window", appid)
except (OSError, RuntimeError) as error:
say(str(error))
notify("Cannot run %s" % os.path.basename(path), str(error))
return 126
cmd = placed(cmd, what, mode, os.environ)
if mode != "exec" or not sys.stderr.isatty():
say("%s (%s): %s" % (path, what, " ".join(cmd[:4])))
try:
os.chdir(folder)
except OSError:
pass
if mode == "exec":
os.execv(cmd[0], cmd)
started = time.monotonic()
try:
status = subprocess.call(cmd)
except OSError as error:
status = 127
say("%s: %s" % (cmd[0], error))
if status != 0 and time.monotonic() - started < QUICK_FAILURE:
notify("%s did not start" % os.path.basename(path),
"It exited with status %d; the session's desktop.log says why." % status)
if what == "windows":
try:
subprocess.call([sys.executable, PROGRAMS])
except OSError as error:
say("%s: %s" % (PROGRAMS, error))
return status
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))