mirror of
https://github.com/morluto/rea.git
synced 2026-11-19 13:12:26 +00:00
fix(desktop): install effective AppImage launcher fields (#12191)
This commit is contained in:
1 parent
94129cadcd
commit
4e4e99864e
7 files changed
+169
-51
No files matched your search
@@ -205,10 +205,13 @@ refused unless its SHA-256 is the one named, and unpacked by a root build
|
||||
step, `install-download.sh`, under `/opt/rea-apps/<desktop_entry>`; the
|
||||
export writes the same step. An AppImage is extracted with its own
|
||||
`--appimage-extract`, so no FUSE is needed, and the step installs the image's
|
||||
own `<desktop_entry>.desktop` under `/usr/local/share/applications` with
|
||||
each `Exec` program replaced by the image's `AppRun`, after any `env` prefix
|
||||
and its assignments, without `TryExec`, and its icon; an image without that entry fails the build, naming the entries it
|
||||
has. A tarball is read with Python's `tarfile`, since the computer has no
|
||||
own `<desktop_entry>.desktop` under `/usr/local/share/applications`. It replaces
|
||||
the effective `Exec` program in the main group and each desktop action with the
|
||||
image's `AppRun`, preserving any `env` prefix and its assignments. It removes
|
||||
main-group `TryExec` declarations and installs the main group's effective icon.
|
||||
Repeated declarations follow GLib's last-key rule. An image missing the
|
||||
requested desktop entry fails the build and lists the entries it has. A
|
||||
tarball is read with Python's `tarfile`, since the computer has no
|
||||
`xz` program, so gzip, bzip2 and xz archives work. Its `data` filter refuses
|
||||
links that point outside the folder, absolute ones included, and special
|
||||
files, so such an archive fails the build. Its `program` is a path
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import {
|
||||
DESKTOP_ENTRY_GROUP,
|
||||
DESKTOP_GROUP,
|
||||
DESKTOP_KEY,
|
||||
DESKTOP_KEY_SEPARATOR,
|
||||
DESKTOP_VALUE_ESCAPE,
|
||||
DESKTOP_VALUE_ESCAPES,
|
||||
@@ -8,6 +11,7 @@ import {
|
||||
EXEC_LEXEME,
|
||||
QUOTED_ESCAPE,
|
||||
} from "./desktopLaunchSyntax.js";
|
||||
import { PYTHON_ECMASCRIPT_TRIM_CHARACTERS } from "./desktopTextSyntax.js";
|
||||
|
||||
const pythonJson = (value: unknown): string =>
|
||||
`json.loads(${JSON.stringify(JSON.stringify(value))})`;
|
||||
@@ -17,8 +21,10 @@ const pythonJson = (value: unknown): string =>
|
||||
export const rewriteAppImageDesktop = String.raw`import json
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from shutil import copyfile
|
||||
|
||||
source, destination, app_run = sys.argv[1:]
|
||||
source, destination, app_run, svg_icons, pixmaps = sys.argv[1:]
|
||||
value_escapes = ${pythonJson(DESKTOP_VALUE_ESCAPES)}
|
||||
value_lexeme = re.compile(${pythonJson(String.raw`${DESKTOP_VALUE_ESCAPE}|([\s\S])`)})
|
||||
exec_lexeme = re.compile(${pythonJson(EXEC_LEXEME)})
|
||||
@@ -26,15 +32,23 @@ quoted_escape = re.compile(${pythonJson(QUOTED_ESCAPE)})
|
||||
env_wrapper = re.compile(${pythonJson(ENV_WRAPPER)})
|
||||
env_unset_name = re.compile(${pythonJson(ENV_UNSET_NAME)})
|
||||
env_phases = ${pythonJson(ENV_PREFIX)}
|
||||
launch_key = re.compile(${pythonJson(String.raw`[ \t]*(TryExec|Exec)${DESKTOP_KEY_SEPARATOR}`)})
|
||||
group_header = re.compile(${pythonJson(DESKTOP_GROUP)})
|
||||
entry_key = re.compile(${pythonJson(`(${DESKTOP_KEY})${DESKTOP_KEY_SEPARATOR}`)})
|
||||
desktop_entry_group = ${pythonJson(DESKTOP_ENTRY_GROUP)}
|
||||
action_group = re.compile(${pythonJson(`Desktop Action ${DESKTOP_KEY}`)})
|
||||
trim_characters = ${PYTHON_ECMASCRIPT_TRIM_CHARACTERS}
|
||||
|
||||
def desktop_value_characters(raw):
|
||||
for part in value_lexeme.finditer(raw):
|
||||
escaped, character = part.groups()
|
||||
yield character if escaped is None else value_escapes[escaped], part.end()
|
||||
|
||||
def exec_tokens(raw):
|
||||
# Decode the value layer while recording where its characters came from.
|
||||
value, offsets = [], [0]
|
||||
for part in value_lexeme.finditer(raw):
|
||||
escaped, character = part.groups()
|
||||
value.append(character if escaped is None else value_escapes[escaped])
|
||||
offsets.append(part.end())
|
||||
for character, end in desktop_value_characters(raw):
|
||||
value.append(character)
|
||||
offsets.append(end)
|
||||
value = "".join(value)
|
||||
|
||||
tokens, parts = [], []
|
||||
@@ -95,18 +109,57 @@ def program_span(raw):
|
||||
raise ValueError("missing program in desktop Exec")
|
||||
return tokens[index][1:]
|
||||
|
||||
rewritten = []
|
||||
def line_end(line):
|
||||
if line.endswith("\r\n"):
|
||||
return len(line) - 2
|
||||
if line.endswith("\n"):
|
||||
return len(line) - 1
|
||||
return len(line)
|
||||
|
||||
# GLib merges repeated groups and selects the last declaration of each key.
|
||||
# Only effective launch commands need to be parsed or rewritten.
|
||||
with open(source, encoding="utf-8", newline="\n") as f:
|
||||
for line in f:
|
||||
key = launch_key.match(line)
|
||||
if key and key.group(1) == "TryExec":
|
||||
continue
|
||||
if key:
|
||||
newline = "\r\n" if line.endswith("\r\n") else "\n" if line.endswith("\n") else ""
|
||||
raw = line[key.end():len(line) - len(newline)]
|
||||
start, end = program_span(raw)
|
||||
line = line[:key.end()] + raw[:start] + app_run + raw[end:] + newline
|
||||
rewritten.append(line)
|
||||
lines = f.readlines()
|
||||
group = ""
|
||||
execs = {}
|
||||
icon = ""
|
||||
for index, line in enumerate(lines):
|
||||
header = group_header.fullmatch(line.strip(trim_characters))
|
||||
if header:
|
||||
group = header[1]
|
||||
continue
|
||||
if group != desktop_entry_group and not action_group.fullmatch(group):
|
||||
continue
|
||||
indent = len(line) - len(line.lstrip(trim_characters))
|
||||
key = entry_key.match(line, indent)
|
||||
if not key:
|
||||
continue
|
||||
if key[1] == "Exec":
|
||||
execs[group] = index, key.end()
|
||||
elif group == desktop_entry_group:
|
||||
if key[1] == "TryExec":
|
||||
# Remove every declaration so an earlier one cannot become effective.
|
||||
lines[index] = ""
|
||||
elif key[1] == "Icon":
|
||||
icon = line[key.end():line_end(line)]
|
||||
|
||||
for index, value_start in sorted(execs.values()):
|
||||
line = lines[index]
|
||||
value_end = line_end(line)
|
||||
raw = line[value_start:value_end]
|
||||
start, end = program_span(raw)
|
||||
lines[index] = line[:value_start] + raw[:start] + app_run + raw[end:] + line[value_end:]
|
||||
with open(destination, "w", encoding="utf-8", newline="") as f:
|
||||
f.writelines(rewritten)
|
||||
f.writelines(lines)
|
||||
|
||||
icon = "".join(character for character, _ in desktop_value_characters(icon))
|
||||
if icon and "/" not in icon and "\x00" not in icon:
|
||||
root = Path(source).parent
|
||||
for suffix, folder in ((".svg", svg_icons), (".png", pixmaps)):
|
||||
name = icon + suffix
|
||||
if (root / name).is_file():
|
||||
target = Path(folder)
|
||||
target.mkdir(parents=True, exist_ok=True)
|
||||
copyfile(root / name, target / name)
|
||||
break
|
||||
`;
|
||||
@@ -138,22 +138,9 @@ const appImageScript = (install: DownloadInstall): string =>
|
||||
"fi",
|
||||
'chmod -R a+rX "$prefix"',
|
||||
// The installer and export share this format-aware rewrite.
|
||||
`python3 - "$desktop" "${APPLICATIONS}/$entry.desktop" "$prefix/squashfs-root/AppRun" <<'PY'`,
|
||||
`python3 - "$desktop" "${APPLICATIONS}/$entry.desktop" "$prefix/squashfs-root/AppRun" /usr/local/share/icons/hicolor/scalable/apps /usr/local/share/pixmaps <<'PY'`,
|
||||
rewriteAppImageDesktop,
|
||||
"PY",
|
||||
`icon=$(sed -n 's/^Icon=//p' "$desktop" | head -n 1)`,
|
||||
'case "$icon" in',
|
||||
" '' | */*) ;;",
|
||||
" *)",
|
||||
' if [ -f "squashfs-root/$icon.svg" ]; then',
|
||||
" mkdir -p /usr/local/share/icons/hicolor/scalable/apps",
|
||||
' cp "squashfs-root/$icon.svg" /usr/local/share/icons/hicolor/scalable/apps/',
|
||||
' elif [ -f "squashfs-root/$icon.png" ]; then',
|
||||
" mkdir -p /usr/local/share/pixmaps",
|
||||
' cp "squashfs-root/$icon.png" /usr/local/share/pixmaps/',
|
||||
" fi",
|
||||
" ;;",
|
||||
"esac",
|
||||
"",
|
||||
].join("\n");
|
||||
|
||||
|
||||
@@ -572,6 +572,16 @@ describe("electronLaunchArguments", () => {
|
||||
});
|
||||
|
||||
describe("adjustInstalledDesktopText", () => {
|
||||
it("keeps the original separators around the effective Exec", () => {
|
||||
const text =
|
||||
"[Desktop Entry]\r\nName=App\nExec=old-app\r\nExec=current-app\n";
|
||||
expect(adjustInstalledDesktopText(text, true)).toEqual({
|
||||
ok: true,
|
||||
value:
|
||||
"[Desktop Entry]\r\nName=App\nExec=old-app\r\nExec=current-app --no-sandbox\n",
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["", "[Desktop Action New]\nExec=action-app\n[Desktop Entry]\n"])(
|
||||
"rewrites the effective command rather than an overridden Exec (%j)",
|
||||
(between) => {
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { err, ok, type Result } from "../result.js";
|
||||
import {
|
||||
DESKTOP_ENTRY_GROUP,
|
||||
DESKTOP_GROUP,
|
||||
DESKTOP_KEY,
|
||||
DESKTOP_KEY_SEPARATOR,
|
||||
DESKTOP_VALUE_ESCAPE,
|
||||
@@ -11,6 +13,7 @@ import {
|
||||
QUOTABLE,
|
||||
QUOTED_ESCAPE,
|
||||
} from "./desktopLaunchSyntax.js";
|
||||
import { DESKTOP_LINE_BREAK } from "./desktopTextSyntax.js";
|
||||
|
||||
/** The unlocalized `[Desktop Entry]` keys a desktop capture uses. */
|
||||
export interface DesktopEntry {
|
||||
@@ -26,7 +29,8 @@ export interface DesktopEntry {
|
||||
readonly terminal: boolean;
|
||||
}
|
||||
|
||||
const GROUP = /^\[(?<name>[^\]]+)\]$/u;
|
||||
const GROUP = new RegExp(`^${DESKTOP_GROUP}$`, "u");
|
||||
const LINE_WITH_SEPARATOR = new RegExp(`(${DESKTOP_LINE_BREAK})`, "u");
|
||||
// Only LF separates records; Unicode line/paragraph separators are value data.
|
||||
const ENTRY = new RegExp(
|
||||
`^(?<key>${DESKTOP_KEY})${DESKTOP_KEY_SEPARATOR}(?<value>.*)$`,
|
||||
@@ -101,34 +105,35 @@ const listValue = (value: string | undefined): readonly string[] => {
|
||||
|
||||
/** GLib merges repeated groups and gives the last occurrence of a key precedence. */
|
||||
const readDesktopEntryFields = (text: string) => {
|
||||
const lines = text.split(/\r?\n/u);
|
||||
const parts = text.split(LINE_WITH_SEPARATOR);
|
||||
const fields = new Map<
|
||||
string,
|
||||
{ readonly value: string; readonly line: number }
|
||||
{ readonly value: string; readonly part: number }
|
||||
>();
|
||||
let group: string | undefined;
|
||||
let found = false;
|
||||
for (const [index, raw] of lines.entries()) {
|
||||
for (let index = 0; index < parts.length; index += 2) {
|
||||
const raw = parts[index]!;
|
||||
const line = raw.trim();
|
||||
if (line.length === 0 || line.startsWith("#")) continue;
|
||||
const header = GROUP.exec(line);
|
||||
if (header?.groups !== undefined) {
|
||||
group = header.groups.name;
|
||||
found ||= group === "Desktop Entry";
|
||||
const header = GROUP.exec(line)?.[1];
|
||||
if (header !== undefined) {
|
||||
group = header;
|
||||
found ||= group === DESKTOP_ENTRY_GROUP;
|
||||
continue;
|
||||
}
|
||||
// Full-line trimming is syntax-only: string-value suffixes are data.
|
||||
const entry = ENTRY.exec(raw.trimStart());
|
||||
if (group !== "Desktop Entry" || entry?.groups === undefined) continue;
|
||||
if (group !== DESKTOP_ENTRY_GROUP || entry?.groups === undefined) continue;
|
||||
const { key, value } = entry.groups;
|
||||
if (key !== undefined && value !== undefined)
|
||||
// Keep the existing enum/boolean token treatment before value unescaping.
|
||||
fields.set(key, {
|
||||
value: key === "Type" || key === "Terminal" ? value.trimEnd() : value,
|
||||
line: index,
|
||||
part: index,
|
||||
});
|
||||
}
|
||||
return { lines, fields, found };
|
||||
return { parts, fields, found };
|
||||
};
|
||||
|
||||
/** Read the effective main-group keys, ignoring localized keys and action groups. */
|
||||
@@ -208,12 +213,11 @@ export const replaceDesktopExec = (
|
||||
text: string,
|
||||
exec: string,
|
||||
): Result<string, "missing_exec_line"> => {
|
||||
const newline = text.includes("\r\n") ? "\r\n" : "\n";
|
||||
const { lines, fields } = readDesktopEntryFields(text);
|
||||
const { parts, fields } = readDesktopEntryFields(text);
|
||||
const execField = fields.get("Exec");
|
||||
if (execField === undefined) return err("missing_exec_line");
|
||||
lines[execField.line] = `Exec=${escapeDesktopEntryValue(exec)}`;
|
||||
return ok(lines.join(newline));
|
||||
parts[execField.part] = `Exec=${escapeDesktopEntryValue(exec)}`;
|
||||
return ok(parts.join(""));
|
||||
};
|
||||
|
||||
/** Facts substituted for the `%i`, `%c` and `%k` field codes. */
|
||||
|
||||
@@ -14,6 +14,8 @@ const escapeKeys = Object.keys(DESKTOP_VALUE_ESCAPES)
|
||||
export const DESKTOP_VALUE_ESCAPE = String.raw`\\([${escapeKeys}])`;
|
||||
export const DESKTOP_KEY = String.raw`[A-Za-z0-9-]+`;
|
||||
export const DESKTOP_KEY_SEPARATOR = String.raw`[ \t]*=[ \t]*`;
|
||||
export const DESKTOP_GROUP = String.raw`\[([^\]]+)\]`;
|
||||
export const DESKTOP_ENTRY_GROUP = "Desktop Entry";
|
||||
|
||||
export const QUOTABLE = String.raw`["\x60$\\]`;
|
||||
export const QUOTED_ESCAPE = String.raw`\\(${QUOTABLE})`;
|
||||
|
||||
@@ -253,6 +253,65 @@ it("preserves Exec key spacing and line endings while removing TryExec", async (
|
||||
);
|
||||
});
|
||||
|
||||
it("installs the effective AppImage launcher and action keys while keeping extension fields", async () => {
|
||||
const root = await stage("rea-appimage-effective-entry-");
|
||||
const image = join(root, "env/vendor/app.AppImage");
|
||||
const source = join(root, "source.desktop");
|
||||
const desktop = [
|
||||
"[Desktop Entry]",
|
||||
"Type=Application",
|
||||
"Name=Draw",
|
||||
'Exec="overridden',
|
||||
"Icon=earlier",
|
||||
"Actions=New;",
|
||||
"TryExec=earlier",
|
||||
"[Desktop Action New]",
|
||||
"Name=New Window",
|
||||
'Exec="overridden-action',
|
||||
"[X-Extension]",
|
||||
'Exec="extension-data',
|
||||
"TryExec=extension-data",
|
||||
"[Desktop Entry]",
|
||||
"Exec=drawio --current %U",
|
||||
"Icon=current",
|
||||
"TryExec=current",
|
||||
"[Desktop Action New]",
|
||||
"Exec=drawio --new-window",
|
||||
"",
|
||||
].join("\n");
|
||||
await writeFile(source, desktop);
|
||||
await writeFile(
|
||||
image,
|
||||
STUB_APPIMAGE +
|
||||
`cp -- "${source}" squashfs-root/drawio.desktop\n` +
|
||||
"printf 'earlier' > squashfs-root/earlier.svg\n" +
|
||||
"printf 'current' > squashfs-root/current.svg\n",
|
||||
{ mode: 0o755 },
|
||||
);
|
||||
|
||||
await runDownloadInstall(
|
||||
renderBuildBundle(appImageRequest("drawio"), localPayload),
|
||||
root,
|
||||
);
|
||||
|
||||
const appRun = join(root, "opt/rea-apps/drawio/squashfs-root/AppRun");
|
||||
expect(
|
||||
await readFile(
|
||||
join(root, "local-share/applications/drawio.desktop"),
|
||||
"utf8",
|
||||
),
|
||||
).toBe(
|
||||
desktop
|
||||
.replace("TryExec=earlier\n", "")
|
||||
.replace("TryExec=current\n", "")
|
||||
.replace("Exec=drawio --current", `Exec=${appRun} --current`)
|
||||
.replace("Exec=drawio --new-window", `Exec=${appRun} --new-window`),
|
||||
);
|
||||
const icons = join(root, "local-share/icons/hicolor/scalable/apps");
|
||||
expect(await readFile(join(icons, "current.svg"), "utf8")).toBe("current");
|
||||
expect(await exists(join(icons, "earlier.svg"))).toBe(false);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['env "drawio %U', "unterminated quote"],
|
||||
["env -i", "missing program"],
|
||||
|
||||
Reference in new issue
Block a user