@domicile-desktop/system-apps 0.0.0-stage → 1.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +53 -2
- package/package.json +57 -4
- package/src/app-icons.ts +413 -0
- package/src/app-id-name.ts +10 -0
- package/src/apps-desktop.ts +12 -0
- package/src/bookmark.ts +39 -0
- package/src/content-type.ts +75 -0
- package/src/curl.ts +54 -0
- package/src/data-dirs.ts +29 -0
- package/src/data-url.ts +12 -0
- package/src/describe-apps.ts +110 -0
- package/src/desktop-entry.ts +98 -0
- package/src/environment.ts +38 -0
- package/src/escapes.ts +16 -0
- package/src/exec.ts +60 -0
- package/src/fake-desktop.ts +209 -0
- package/src/favicon.ts +164 -0
- package/src/favicons.ts +117 -0
- package/src/find-apps.ts +21 -0
- package/src/glob.ts +33 -0
- package/src/icon-theme-index.ts +148 -0
- package/src/installed.ts +135 -0
- package/src/mime-apps.ts +82 -0
- package/src/omit.ts +24 -0
- package/src/openers.ts +137 -0
- package/src/opens.ts +43 -0
- package/src/ranked.ts +60 -0
- package/src/results.ts +48 -0
- package/src/supertypes.ts +70 -0
package/src/favicon.ts
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
// A bookmark's icon, picked as a browser picks one: the page's
|
|
2
|
+
// `<link rel="icon">`, else `/favicon.ico`. The caller does the fetching.
|
|
3
|
+
|
|
4
|
+
import type { Option, Result } from "@cprussin/option-result";
|
|
5
|
+
import { None, Ok, Some } from "@cprussin/option-result";
|
|
6
|
+
import type { SystemError } from "@domicile-desktop/sdk/system";
|
|
7
|
+
|
|
8
|
+
import { dataUrl } from "./data-url";
|
|
9
|
+
|
|
10
|
+
/** Largest icon drawn, as for an application's. */
|
|
11
|
+
const LARGEST = 128 * 1024;
|
|
12
|
+
|
|
13
|
+
/** Assumed size of an unsized touch icon, per Apple. */
|
|
14
|
+
const TOUCH_ICON_SIZE = 180;
|
|
15
|
+
|
|
16
|
+
/** Assumed size of an unsized icon, as in a browser tab. */
|
|
17
|
+
const UNSIZED = 16;
|
|
18
|
+
|
|
19
|
+
/** How an icon's bytes start, for a server that names no image type. */
|
|
20
|
+
const MAGIC: readonly [start: readonly number[], mime: string][] = [
|
|
21
|
+
[[0x89, 0x50, 0x4e, 0x47], "image/png"],
|
|
22
|
+
[[0, 0, 1, 0], "image/x-icon"],
|
|
23
|
+
[[0x47, 0x49, 0x46, 0x38], "image/gif"],
|
|
24
|
+
[[0xff, 0xd8, 0xff], "image/jpeg"],
|
|
25
|
+
[[0x3c, 0x73, 0x76, 0x67], "image/svg+xml"],
|
|
26
|
+
];
|
|
27
|
+
|
|
28
|
+
/** A fetched URL: where it landed after redirects, its type and its body. */
|
|
29
|
+
export type Page = {
|
|
30
|
+
url: string;
|
|
31
|
+
contentType: string | undefined;
|
|
32
|
+
body: Uint8Array;
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
/** Fetches a URL, or nothing if it does not answer. */
|
|
36
|
+
export type Fetch = (url: string) => Promise<Result<Option<Page>, SystemError>>;
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* The icon for `url` as a `data:` URL, or nothing if none is usable.
|
|
40
|
+
*
|
|
41
|
+
* Tries the page's icon links first, SVG then largest. Links are ignored if
|
|
42
|
+
* the page redirected off-site, for example to a sign-in page; a parent or
|
|
43
|
+
* subdomain such as `www.` counts as the same site. Then tries
|
|
44
|
+
* `/favicon.ico`.
|
|
45
|
+
*/
|
|
46
|
+
export const favicon = async (
|
|
47
|
+
url: string,
|
|
48
|
+
fetch: Fetch,
|
|
49
|
+
): Promise<Result<Option<string>, SystemError>> => {
|
|
50
|
+
const asked = new URL(url);
|
|
51
|
+
return (await fetch(url)).andThenAsync((page) =>
|
|
52
|
+
firstPicture(
|
|
53
|
+
[
|
|
54
|
+
...page.match({
|
|
55
|
+
None: () => [],
|
|
56
|
+
Some: (found) =>
|
|
57
|
+
isHtml(found) && sameSite(asked, new URL(found.url))
|
|
58
|
+
? iconLinks(found)
|
|
59
|
+
: [],
|
|
60
|
+
}),
|
|
61
|
+
new URL("/favicon.ico", asked).href,
|
|
62
|
+
],
|
|
63
|
+
fetch,
|
|
64
|
+
),
|
|
65
|
+
);
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
/** The first of `urls` that answers with a picture. */
|
|
69
|
+
const firstPicture = async (
|
|
70
|
+
urls: readonly string[],
|
|
71
|
+
fetch: Fetch,
|
|
72
|
+
): Promise<Result<Option<string>, SystemError>> => {
|
|
73
|
+
for (const url of urls) {
|
|
74
|
+
const found = (await fetch(url)).map((page) =>
|
|
75
|
+
page.andThen((answer) => picture(answer)),
|
|
76
|
+
);
|
|
77
|
+
if (found.mapOr(true, (icon) => icon.isSome())) {
|
|
78
|
+
return found;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return Ok(None());
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
const isHtml = ({ contentType }: Page): boolean => {
|
|
85
|
+
const type = contentType?.toLowerCase() ?? "";
|
|
86
|
+
return (
|
|
87
|
+
type.startsWith("text/html") || type.startsWith("application/xhtml+xml")
|
|
88
|
+
);
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
/** Whether the hosts match or one is a subdomain of the other. */
|
|
92
|
+
const sameSite = (asked: URL, landed: URL): boolean =>
|
|
93
|
+
asked.hostname === landed.hostname ||
|
|
94
|
+
asked.hostname.endsWith(`.${landed.hostname}`) ||
|
|
95
|
+
landed.hostname.endsWith(`.${asked.hostname}`);
|
|
96
|
+
|
|
97
|
+
/** The icons `page` links, resolved against it, best first. */
|
|
98
|
+
const iconLinks = (page: Page): string[] =>
|
|
99
|
+
[
|
|
100
|
+
...new DOMParser()
|
|
101
|
+
.parseFromString(new TextDecoder().decode(page.body), "text/html")
|
|
102
|
+
.querySelectorAll("link"),
|
|
103
|
+
]
|
|
104
|
+
.flatMap((link) => {
|
|
105
|
+
const rels = (link.getAttribute("rel") ?? "").toLowerCase().split(/\s+/);
|
|
106
|
+
const touch = rels.includes("apple-touch-icon");
|
|
107
|
+
const href = link.getAttribute("href");
|
|
108
|
+
if (
|
|
109
|
+
(rels.includes("icon") || touch) &&
|
|
110
|
+
href !== null &&
|
|
111
|
+
URL.canParse(href, page.url)
|
|
112
|
+
) {
|
|
113
|
+
const url = new URL(href, page.url);
|
|
114
|
+
const drawn =
|
|
115
|
+
link.getAttribute("type")?.toLowerCase() === "image/svg+xml" ||
|
|
116
|
+
url.pathname.toLowerCase().endsWith(".svg");
|
|
117
|
+
const size =
|
|
118
|
+
largestSize(link.getAttribute("sizes") ?? "") ??
|
|
119
|
+
(touch ? TOUCH_ICON_SIZE : UNSIZED);
|
|
120
|
+
return [{ drawn, size, url: url.href }];
|
|
121
|
+
} else {
|
|
122
|
+
return [];
|
|
123
|
+
}
|
|
124
|
+
})
|
|
125
|
+
// Stable, so page order holds among equal icons.
|
|
126
|
+
.toSorted((a, b) => Number(b.drawn) - Number(a.drawn) || b.size - a.size)
|
|
127
|
+
.map(({ url }) => url);
|
|
128
|
+
|
|
129
|
+
/** The largest size in a `sizes` attribute; `any` is largest. */
|
|
130
|
+
const largestSize = (sizes: string): number | undefined => {
|
|
131
|
+
const each = sizes
|
|
132
|
+
.toLowerCase()
|
|
133
|
+
.split(/\s+/)
|
|
134
|
+
.map((size) => {
|
|
135
|
+
const [width, height] = size.split("x").map(Number);
|
|
136
|
+
return size === "any"
|
|
137
|
+
? Number.POSITIVE_INFINITY
|
|
138
|
+
: Math.max(width ?? Number.NaN, height ?? Number.NaN);
|
|
139
|
+
})
|
|
140
|
+
.filter((size) => !Number.isNaN(size));
|
|
141
|
+
return each.length === 0 ? undefined : Math.max(...each);
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* `page` as a `data:` URL if it is a small enough picture. Sniffs the body
|
|
146
|
+
* when the type is not `image/*`, since some servers send `.ico` without one.
|
|
147
|
+
*/
|
|
148
|
+
const picture = ({ body, contentType }: Page): Option<string> => {
|
|
149
|
+
const said = contentType?.split(";")[0]?.trim();
|
|
150
|
+
const mime = said?.toLowerCase().startsWith("image/") ? said : sniffed(body);
|
|
151
|
+
return mime === undefined || body.length > LARGEST
|
|
152
|
+
? None()
|
|
153
|
+
: Some(dataUrl(mime, body));
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
const sniffed = (body: Uint8Array): string | undefined => {
|
|
157
|
+
const start = body.findIndex(
|
|
158
|
+
(byte) => ![0x20, 0x09, 0x0a, 0x0d, 0x0c].includes(byte),
|
|
159
|
+
);
|
|
160
|
+
const trimmed = start === -1 ? new Uint8Array() : body.subarray(start);
|
|
161
|
+
return MAGIC.find(([magic]) =>
|
|
162
|
+
magic.every((byte, at) => trimmed[at] === byte),
|
|
163
|
+
)?.[1];
|
|
164
|
+
};
|
package/src/favicons.ts
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
// Bookmark icons, looked up in the background and kept for the page's life. A
|
|
2
|
+
// site can take seconds to answer, so a search shows the icons found so far.
|
|
3
|
+
|
|
4
|
+
import type { Option, Result } from "@cprussin/option-result";
|
|
5
|
+
import { None, Some } from "@cprussin/option-result";
|
|
6
|
+
import type { SystemError } from "@domicile-desktop/sdk/system";
|
|
7
|
+
|
|
8
|
+
/** How long to wait before asking again a site that gave no icon. */
|
|
9
|
+
const RETRY_AFTER_MS = 60_000;
|
|
10
|
+
|
|
11
|
+
enum LookedKind {
|
|
12
|
+
InFlight,
|
|
13
|
+
Found,
|
|
14
|
+
/** The site gave no icon, or the lookup failed. */
|
|
15
|
+
Missed,
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const Looked = {
|
|
19
|
+
Found: (icon: string) => ({ icon, kind: LookedKind.Found as const }),
|
|
20
|
+
InFlight: () => ({ kind: LookedKind.InFlight as const }),
|
|
21
|
+
Missed: (atMs: number) => ({ atMs, kind: LookedKind.Missed as const }),
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
type Looked = ReturnType<(typeof Looked)[keyof typeof Looked]>;
|
|
25
|
+
|
|
26
|
+
export type Favicons = {
|
|
27
|
+
/** The icon found for `url`, if one has been. */
|
|
28
|
+
icon: (url: string) => Option<string>;
|
|
29
|
+
/**
|
|
30
|
+
* Looks up, one at a time, each of `urls` that is new or whose miss is due
|
|
31
|
+
* a retry. Settles when they are done.
|
|
32
|
+
*/
|
|
33
|
+
lookFor: (urls: readonly string[]) => Promise<void>;
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
/** How {@link favicons} keeps time and reports failures; for tests. */
|
|
37
|
+
export type FaviconsOptions = {
|
|
38
|
+
retryAfterMs?: number;
|
|
39
|
+
now?: () => number;
|
|
40
|
+
/** Told of each failed lookup, which is retried later. Logs by default. */
|
|
41
|
+
failed?: (url: string, error: SystemError) => void;
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Icons `find` finds, by bookmark URL. A miss or a failure is asked again
|
|
46
|
+
* after a minute, since the network may come up after the desktop.
|
|
47
|
+
*/
|
|
48
|
+
export const favicons = (
|
|
49
|
+
find: (url: string) => Promise<Result<Option<string>, SystemError>>,
|
|
50
|
+
{
|
|
51
|
+
failed = logged,
|
|
52
|
+
now = Date.now,
|
|
53
|
+
retryAfterMs = RETRY_AFTER_MS,
|
|
54
|
+
}: FaviconsOptions = {},
|
|
55
|
+
): Favicons => {
|
|
56
|
+
const looked = new Map<string, Looked>();
|
|
57
|
+
return {
|
|
58
|
+
icon: (url) => {
|
|
59
|
+
const known = looked.get(url);
|
|
60
|
+
return known?.kind === LookedKind.Found ? Some(known.icon) : None();
|
|
61
|
+
},
|
|
62
|
+
lookFor: async (urls) => {
|
|
63
|
+
const wanted = [...new Set(urls)].filter((url) =>
|
|
64
|
+
due(looked.get(url), now(), retryAfterMs),
|
|
65
|
+
);
|
|
66
|
+
for (const url of wanted) {
|
|
67
|
+
looked.set(url, Looked.InFlight());
|
|
68
|
+
}
|
|
69
|
+
for (const url of wanted) {
|
|
70
|
+
looked.set(url, lookedOf(await find(url), url, now(), failed));
|
|
71
|
+
}
|
|
72
|
+
},
|
|
73
|
+
};
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
const due = (
|
|
77
|
+
known: Looked | undefined,
|
|
78
|
+
nowMs: number,
|
|
79
|
+
retryAfterMs: number,
|
|
80
|
+
): boolean => {
|
|
81
|
+
if (known === undefined) {
|
|
82
|
+
return true;
|
|
83
|
+
} else {
|
|
84
|
+
switch (known.kind) {
|
|
85
|
+
case LookedKind.Missed: {
|
|
86
|
+
return nowMs - known.atMs >= retryAfterMs;
|
|
87
|
+
}
|
|
88
|
+
case LookedKind.InFlight:
|
|
89
|
+
case LookedKind.Found: {
|
|
90
|
+
return false;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
const lookedOf = (
|
|
97
|
+
found: Result<Option<string>, SystemError>,
|
|
98
|
+
url: string,
|
|
99
|
+
nowMs: number,
|
|
100
|
+
failed: (url: string, error: SystemError) => void,
|
|
101
|
+
): Looked =>
|
|
102
|
+
found.match({
|
|
103
|
+
Err: (error): Looked => {
|
|
104
|
+
failed(url, error);
|
|
105
|
+
return Looked.Missed(nowMs);
|
|
106
|
+
},
|
|
107
|
+
Ok: (icon) =>
|
|
108
|
+
icon.match({
|
|
109
|
+
None: (): Looked => Looked.Missed(nowMs),
|
|
110
|
+
Some: (each): Looked => Looked.Found(each),
|
|
111
|
+
}),
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
const logged = (url: string, error: SystemError): void => {
|
|
115
|
+
// biome-ignore lint/suspicious/noConsole: surfacing a lookup that is retried later
|
|
116
|
+
console.error(`could not look for ${url}'s icon`, error);
|
|
117
|
+
};
|
package/src/find-apps.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// A launcher's search over installed applications.
|
|
2
|
+
|
|
3
|
+
import type { DesktopEntry } from "./desktop-entry";
|
|
4
|
+
import { ranked } from "./ranked";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Up to `limit` applications matching `query`, best first.
|
|
8
|
+
*
|
|
9
|
+
* Every query word must appear, case-insensitively, in the name, generic name
|
|
10
|
+
* or keywords. Names that start with the query rank first, then sort by name.
|
|
11
|
+
*/
|
|
12
|
+
export const findApps = (
|
|
13
|
+
entries: readonly DesktopEntry[],
|
|
14
|
+
query: string,
|
|
15
|
+
limit: number,
|
|
16
|
+
): DesktopEntry[] =>
|
|
17
|
+
ranked(entries, query, limit, {
|
|
18
|
+
name: ({ name }) => name,
|
|
19
|
+
tieBreak: ({ id }) => id,
|
|
20
|
+
words: ({ words }) => words,
|
|
21
|
+
});
|
package/src/glob.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// Shell-style globs, as the XDG specs use them.
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* `pattern` as an anchored regular expression: `*` matches any run, `?` one
|
|
5
|
+
* character and `[…]` one of a set. Throws on a pattern that is not a glob.
|
|
6
|
+
*/
|
|
7
|
+
export const globOf = (pattern: string): RegExp => {
|
|
8
|
+
const parts = pattern.match(/\[[^\]]*\]|\*|\?|\[|[^*?[]+/g) ?? [];
|
|
9
|
+
return new RegExp(
|
|
10
|
+
`^${parts
|
|
11
|
+
.map((part) => {
|
|
12
|
+
switch (part) {
|
|
13
|
+
case "*": {
|
|
14
|
+
return ".*";
|
|
15
|
+
}
|
|
16
|
+
case "?": {
|
|
17
|
+
return ".";
|
|
18
|
+
}
|
|
19
|
+
case "[": {
|
|
20
|
+
throw new Error(
|
|
21
|
+
`\`${pattern}\` is not a glob: \`[\` is not closed`,
|
|
22
|
+
);
|
|
23
|
+
}
|
|
24
|
+
default: {
|
|
25
|
+
// A `[…]` set reads the same as a regular expression's.
|
|
26
|
+
return part.startsWith("[") ? part : RegExp.escape(part);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
})
|
|
30
|
+
.join("")}$`,
|
|
31
|
+
"s",
|
|
32
|
+
);
|
|
33
|
+
};
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
// An icon theme's `index.theme`: its parents and the directories it holds
|
|
2
|
+
// icons in. See
|
|
3
|
+
// https://specifications.freedesktop.org/icon-theme-spec/latest/.
|
|
4
|
+
|
|
5
|
+
/** How a directory's icons scale. */
|
|
6
|
+
export enum DirectoryType {
|
|
7
|
+
Fixed,
|
|
8
|
+
Scalable,
|
|
9
|
+
Threshold,
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** A theme directory and the icon sizes it suits. */
|
|
13
|
+
export type ThemeDirectory = {
|
|
14
|
+
/** Relative to the theme, such as `16x16/actions`. */
|
|
15
|
+
path: string;
|
|
16
|
+
/** As `contexts` name it: `apps`, `actions`, `status` and so on. */
|
|
17
|
+
context: string | undefined;
|
|
18
|
+
type: DirectoryType;
|
|
19
|
+
size: number;
|
|
20
|
+
minSize: number;
|
|
21
|
+
maxSize: number;
|
|
22
|
+
threshold: number;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
export type IndexTheme = {
|
|
26
|
+
/** `Inherits`, in order. */
|
|
27
|
+
inherits: readonly string[];
|
|
28
|
+
/** `Directories`, in order. */
|
|
29
|
+
directories: readonly ThemeDirectory[];
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
/** The spec's contexts, by the directory names themes install them under. */
|
|
33
|
+
const CONTEXTS: Readonly<Record<string, string>> = {
|
|
34
|
+
Actions: "actions",
|
|
35
|
+
Animations: "animations",
|
|
36
|
+
Applications: "apps",
|
|
37
|
+
Categories: "categories",
|
|
38
|
+
Devices: "devices",
|
|
39
|
+
Emblems: "emblems",
|
|
40
|
+
Emotes: "emotes",
|
|
41
|
+
International: "intl",
|
|
42
|
+
MimeTypes: "mimetypes",
|
|
43
|
+
Places: "places",
|
|
44
|
+
Status: "status",
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
/** `text` read as an `index.theme`. A directory with no `Size` is skipped. */
|
|
48
|
+
export const parseIndexTheme = (text: string): IndexTheme => {
|
|
49
|
+
const groups = groupsOf(text);
|
|
50
|
+
const theme = groups.get("Icon Theme") ?? new Map<string, string>();
|
|
51
|
+
return {
|
|
52
|
+
directories: listOf(theme.get("Directories")).flatMap((path) => {
|
|
53
|
+
const keys = groups.get(path) ?? new Map<string, string>();
|
|
54
|
+
const size = numberOf(keys.get("Size"));
|
|
55
|
+
const context = keys.get("Context");
|
|
56
|
+
return size === undefined
|
|
57
|
+
? []
|
|
58
|
+
: [
|
|
59
|
+
{
|
|
60
|
+
context:
|
|
61
|
+
context === undefined
|
|
62
|
+
? undefined
|
|
63
|
+
: (CONTEXTS[context] ?? context.toLowerCase()),
|
|
64
|
+
maxSize: numberOf(keys.get("MaxSize")) ?? size,
|
|
65
|
+
minSize: numberOf(keys.get("MinSize")) ?? size,
|
|
66
|
+
path,
|
|
67
|
+
size,
|
|
68
|
+
threshold: numberOf(keys.get("Threshold")) ?? 2,
|
|
69
|
+
type: typeOf(keys.get("Type")),
|
|
70
|
+
},
|
|
71
|
+
];
|
|
72
|
+
}),
|
|
73
|
+
inherits: listOf(theme.get("Inherits")),
|
|
74
|
+
};
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* How far `directory`'s icons are from `size` pixels: 0 where they suit it.
|
|
79
|
+
* The spec's `DirectorySizeDistance`, at scale 1.
|
|
80
|
+
*/
|
|
81
|
+
export const sizeDistance = (
|
|
82
|
+
{ maxSize, minSize, size: own, threshold, type }: ThemeDirectory,
|
|
83
|
+
size: number,
|
|
84
|
+
): number => {
|
|
85
|
+
switch (type) {
|
|
86
|
+
case DirectoryType.Fixed: {
|
|
87
|
+
return Math.abs(own - size);
|
|
88
|
+
}
|
|
89
|
+
case DirectoryType.Scalable: {
|
|
90
|
+
return Math.max(minSize - size, size - maxSize, 0);
|
|
91
|
+
}
|
|
92
|
+
case DirectoryType.Threshold: {
|
|
93
|
+
if (size < own - threshold) {
|
|
94
|
+
return minSize - size;
|
|
95
|
+
} else {
|
|
96
|
+
return size > own + threshold ? size - maxSize : 0;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
/** Each group's keys; the first of a repeated key wins. */
|
|
103
|
+
const groupsOf = (
|
|
104
|
+
text: string,
|
|
105
|
+
): ReadonlyMap<string, ReadonlyMap<string, string>> => {
|
|
106
|
+
const groups = new Map<string, Map<string, string>>();
|
|
107
|
+
let group = new Map<string, string>();
|
|
108
|
+
for (const line of text.split("\n").map((each) => each.trim())) {
|
|
109
|
+
if (line.startsWith("[") && line.endsWith("]")) {
|
|
110
|
+
const name = line.slice(1, -1);
|
|
111
|
+
group = groups.get(name) ?? new Map<string, string>();
|
|
112
|
+
groups.set(name, group);
|
|
113
|
+
} else {
|
|
114
|
+
const at = line.indexOf("=");
|
|
115
|
+
const key = line.slice(0, at).trim();
|
|
116
|
+
if (at > 0 && !group.has(key)) {
|
|
117
|
+
group.set(key, line.slice(at + 1).trim());
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return groups;
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
const listOf = (value: string | undefined): string[] =>
|
|
125
|
+
(value ?? "")
|
|
126
|
+
.split(",")
|
|
127
|
+
.map((each) => each.trim())
|
|
128
|
+
.filter((each) => each !== "");
|
|
129
|
+
|
|
130
|
+
const numberOf = (value: string | undefined): number | undefined => {
|
|
131
|
+
const read = Number.parseInt(value ?? "", 10);
|
|
132
|
+
return Number.isNaN(read) ? undefined : read;
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
/** `Type`, which is `Threshold` when absent or unknown. */
|
|
136
|
+
const typeOf = (value: string | undefined): DirectoryType => {
|
|
137
|
+
switch (value) {
|
|
138
|
+
case "Fixed": {
|
|
139
|
+
return DirectoryType.Fixed;
|
|
140
|
+
}
|
|
141
|
+
case "Scalable": {
|
|
142
|
+
return DirectoryType.Scalable;
|
|
143
|
+
}
|
|
144
|
+
default: {
|
|
145
|
+
return DirectoryType.Threshold;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
};
|
package/src/installed.ts
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
// Every application installed in the XDG data directories.
|
|
2
|
+
|
|
3
|
+
import type { Option, Result } from "@cprussin/option-result";
|
|
4
|
+
import { None, Ok, Some } from "@cprussin/option-result";
|
|
5
|
+
import type { DirEntry, SystemError } from "@domicile-desktop/sdk/system";
|
|
6
|
+
import { FileType } from "@domicile-desktop/sdk/system";
|
|
7
|
+
import type { AppsDesktop } from "./apps-desktop";
|
|
8
|
+
|
|
9
|
+
import type { DesktopEntry } from "./desktop-entry";
|
|
10
|
+
import { parseDesktopEntry } from "./desktop-entry";
|
|
11
|
+
import { allOk, orAbsent } from "./results";
|
|
12
|
+
|
|
13
|
+
/** A desktop file ID and the file it names. */
|
|
14
|
+
type EntryFile = { id: string; path: string };
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Every application in `applications/` under `dataDirs`, unordered.
|
|
18
|
+
*
|
|
19
|
+
* `dataDirs` is highest priority first (see `./data-dirs`). An ID in an
|
|
20
|
+
* earlier directory hides the same ID in later ones, even when the earlier
|
|
21
|
+
* entry is `Hidden`: that is how a user removes a system entry. Missing
|
|
22
|
+
* directories and unreadable files are skipped.
|
|
23
|
+
*/
|
|
24
|
+
export const installedApps = async (
|
|
25
|
+
domicile: AppsDesktop,
|
|
26
|
+
dataDirs: readonly string[],
|
|
27
|
+
): Promise<Result<DesktopEntry[], SystemError>> => {
|
|
28
|
+
const listed = allOk(
|
|
29
|
+
await Promise.all(
|
|
30
|
+
dataDirs.map((dir) => entryFiles(domicile, `${dir}/applications`, "")),
|
|
31
|
+
),
|
|
32
|
+
);
|
|
33
|
+
return (
|
|
34
|
+
await listed.andThenAsync(async (dirs) =>
|
|
35
|
+
allOk(
|
|
36
|
+
await Promise.all(
|
|
37
|
+
firstOfEach(dirs.flat()).map((file) => read(domicile, file)),
|
|
38
|
+
),
|
|
39
|
+
),
|
|
40
|
+
)
|
|
41
|
+
).map((read) =>
|
|
42
|
+
read.flatMap((entry) =>
|
|
43
|
+
entry.match({ None: () => [], Some: (found) => [found] }),
|
|
44
|
+
),
|
|
45
|
+
);
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* The application whose ID is `id`, `NoDisplay` or not, or nothing if none
|
|
50
|
+
* is usable. As `installedApps`, an ID in an earlier directory hides later
|
|
51
|
+
* ones.
|
|
52
|
+
*/
|
|
53
|
+
export const installedApp = async (
|
|
54
|
+
domicile: AppsDesktop,
|
|
55
|
+
dataDirs: readonly string[],
|
|
56
|
+
id: string,
|
|
57
|
+
): Promise<Result<Option<DesktopEntry>, SystemError>> =>
|
|
58
|
+
await allOk(
|
|
59
|
+
await Promise.all(
|
|
60
|
+
dataDirs.map((dir) => entryFiles(domicile, `${dir}/applications`, "")),
|
|
61
|
+
),
|
|
62
|
+
).andThenAsync((dirs) => {
|
|
63
|
+
const file = firstOfEach(dirs.flat()).find((each) => each.id === id);
|
|
64
|
+
return file === undefined
|
|
65
|
+
? Promise.resolve(Ok(None<DesktopEntry>()))
|
|
66
|
+
: read(domicile, file, false);
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
/** Each ID's first file, in priority order. */
|
|
70
|
+
const firstOfEach = (files: readonly EntryFile[]): EntryFile[] => {
|
|
71
|
+
const seen = new Set<string>();
|
|
72
|
+
return files.filter(({ id }) => {
|
|
73
|
+
const first = !seen.has(id);
|
|
74
|
+
seen.add(id);
|
|
75
|
+
return first;
|
|
76
|
+
});
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
/** `file` parsed, or nothing for an unreadable file or one not to offer. */
|
|
80
|
+
const read = async (
|
|
81
|
+
domicile: AppsDesktop,
|
|
82
|
+
{ id, path }: EntryFile,
|
|
83
|
+
shown = true,
|
|
84
|
+
) =>
|
|
85
|
+
orAbsent(
|
|
86
|
+
(await domicile.files.readText(path)).map((text) =>
|
|
87
|
+
parseDesktopEntry(id, text, shown),
|
|
88
|
+
),
|
|
89
|
+
None<DesktopEntry>(),
|
|
90
|
+
);
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Every `.desktop` file under `dir`, recursively, with its ID: `prefix` plus
|
|
94
|
+
* its path under `dir`, `/` read as `-`.
|
|
95
|
+
*/
|
|
96
|
+
const entryFiles = async (
|
|
97
|
+
domicile: AppsDesktop,
|
|
98
|
+
dir: string,
|
|
99
|
+
prefix: string,
|
|
100
|
+
): Promise<Result<EntryFile[], SystemError>> =>
|
|
101
|
+
orAbsent(await domicile.files.readDir(dir), []).andThenAsync(
|
|
102
|
+
async (entries) =>
|
|
103
|
+
allOk(
|
|
104
|
+
await Promise.all(
|
|
105
|
+
entries.map((entry) => filesAt(domicile, dir, prefix, entry)),
|
|
106
|
+
),
|
|
107
|
+
).map((found) => found.flat()),
|
|
108
|
+
);
|
|
109
|
+
|
|
110
|
+
/** The entry files `entry` in `dir` holds: itself, or those under it. */
|
|
111
|
+
const filesAt = async (
|
|
112
|
+
domicile: AppsDesktop,
|
|
113
|
+
dir: string,
|
|
114
|
+
prefix: string,
|
|
115
|
+
{ fileType, name }: DirEntry,
|
|
116
|
+
): Promise<Result<EntryFile[], SystemError>> => {
|
|
117
|
+
const path = `${dir}/${name}`;
|
|
118
|
+
const below = () => entryFiles(domicile, path, `${prefix}${name}-`);
|
|
119
|
+
if (fileType === FileType.Directory) {
|
|
120
|
+
return below();
|
|
121
|
+
} else if (name.endsWith(".desktop")) {
|
|
122
|
+
return Ok([{ id: `${prefix}${name}`, path }]);
|
|
123
|
+
} else if (fileType === FileType.Symlink) {
|
|
124
|
+
return orAbsent(
|
|
125
|
+
(await domicile.files.stat(path)).map(({ fileType: target }) =>
|
|
126
|
+
target === FileType.Directory ? Some(target) : None<FileType>(),
|
|
127
|
+
),
|
|
128
|
+
None<FileType>(),
|
|
129
|
+
).andThenAsync((linked) =>
|
|
130
|
+
linked.isSome() ? below() : Promise.resolve(Ok([])),
|
|
131
|
+
);
|
|
132
|
+
} else {
|
|
133
|
+
return Ok([]);
|
|
134
|
+
}
|
|
135
|
+
};
|
package/src/mime-apps.ts
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// The default applications `mimeapps.list` names for a content type. See
|
|
2
|
+
// https://specifications.freedesktop.org/mime-apps-spec/latest/.
|
|
3
|
+
|
|
4
|
+
import type { Result } from "@cprussin/option-result";
|
|
5
|
+
import type { SystemError } from "@domicile-desktop/sdk/system";
|
|
6
|
+
import type { AppsDesktop } from "./apps-desktop";
|
|
7
|
+
|
|
8
|
+
import { desktopEnvironment, setVariable } from "./environment";
|
|
9
|
+
import { allOk, orAbsent } from "./results";
|
|
10
|
+
|
|
11
|
+
/** The group defaults are read from. */
|
|
12
|
+
const GROUP = "[Default Applications]";
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* The desktop file IDs, `.desktop` included, set as `contentType`'s default,
|
|
16
|
+
* most preferred first. The caller takes the first it can offer.
|
|
17
|
+
*
|
|
18
|
+
* Reads every `mimeapps.list` the spec names, the current desktop's own
|
|
19
|
+
* (`domicile-mimeapps.list`) before each plain one. Missing lists are
|
|
20
|
+
* skipped.
|
|
21
|
+
*/
|
|
22
|
+
export const defaultApps = async (
|
|
23
|
+
domicile: AppsDesktop,
|
|
24
|
+
contentType: string,
|
|
25
|
+
): Promise<Result<string[], SystemError>> =>
|
|
26
|
+
(await desktopEnvironment(domicile)).andThenAsync(async (variables) =>
|
|
27
|
+
allOk(
|
|
28
|
+
await Promise.all(
|
|
29
|
+
listPaths(variables).map(async (path) =>
|
|
30
|
+
orAbsent(await domicile.files.readText(path), "").map((text) =>
|
|
31
|
+
defaultsIn(text, contentType),
|
|
32
|
+
),
|
|
33
|
+
),
|
|
34
|
+
),
|
|
35
|
+
).map((found) => found.flat()),
|
|
36
|
+
);
|
|
37
|
+
|
|
38
|
+
/** Every list to read, in the spec's order. */
|
|
39
|
+
const listPaths = (variables: ReadonlyMap<string, string>): string[] => {
|
|
40
|
+
const desktops = (setVariable(variables, "XDG_CURRENT_DESKTOP") ?? "")
|
|
41
|
+
.split(":")
|
|
42
|
+
.filter((desktop) => desktop !== "")
|
|
43
|
+
.map((desktop) => desktop.toLowerCase());
|
|
44
|
+
const names = [
|
|
45
|
+
...desktops.map((desktop) => `${desktop}-mimeapps.list`),
|
|
46
|
+
"mimeapps.list",
|
|
47
|
+
];
|
|
48
|
+
const dataDirs = [
|
|
49
|
+
setVariable(variables, "XDG_DATA_HOME") ?? ".local/share",
|
|
50
|
+
...(
|
|
51
|
+
setVariable(variables, "XDG_DATA_DIRS") ?? "/usr/local/share:/usr/share"
|
|
52
|
+
).split(":"),
|
|
53
|
+
].map((dir) => `${dir}/applications`);
|
|
54
|
+
return [
|
|
55
|
+
setVariable(variables, "XDG_CONFIG_HOME") ?? ".config",
|
|
56
|
+
...(setVariable(variables, "XDG_CONFIG_DIRS") ?? "/etc/xdg").split(":"),
|
|
57
|
+
...dataDirs,
|
|
58
|
+
].flatMap((dir) => names.map((name) => `${dir}/${name}`));
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
/** The IDs list `text` sets for `contentType`. */
|
|
62
|
+
const defaultsIn = (text: string, contentType: string): string[] => {
|
|
63
|
+
let group = "";
|
|
64
|
+
const found: string[] = [];
|
|
65
|
+
for (const line of text.split("\n").map((each) => each.trim())) {
|
|
66
|
+
if (line.startsWith("[")) {
|
|
67
|
+
group = line;
|
|
68
|
+
} else if (group === GROUP && !line.startsWith("#")) {
|
|
69
|
+
const equals = line.indexOf("=");
|
|
70
|
+
if (equals !== -1 && line.slice(0, equals).trim() === contentType) {
|
|
71
|
+
found.push(
|
|
72
|
+
...line
|
|
73
|
+
.slice(equals + 1)
|
|
74
|
+
.split(";")
|
|
75
|
+
.map((id) => id.trim())
|
|
76
|
+
.filter((id) => id !== ""),
|
|
77
|
+
);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return found;
|
|
82
|
+
};
|