okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-split-linuxui (83aa59fdc) into f-split-int2b6a38b328

main
6.6 KiB108 linesraw
1/**
2 * Which window the person is using, and what only the app window can do.
3 *
4 * The Linux app starts the host itself (the "shell" process, which has no window) and shows the page in a separate window
5 * process. WebKitGTK can crash that process on some computers; the shell then keeps the host running and opens the same page
6 * in the default browser ("browser mode"). A person can also choose browser mode (`--browser`, STRATA_UI=browser).
7 *
8 *   mode 'window'   the app window shows the page; the window process registers the app updater here (Tauri's signed updater).
9 *   mode 'browser'  an ordinary browser tab shows the page. There is no window process, so the app cannot update itself, and
10 *                   closing the tab does not stop the engine: the menu has "Quit Strata" (POST /api/app/quit) and the command
11 *                   line has `--quit`.
12 *   mode null       not started by the app (the host run by hand, a test, a source checkout): nothing here applies.
13 *
14 * What needs the Tauri bridge and what happens without it (browser mode):
15 *   folder picker        works: the host runs zenity / kdialog / the desktop portal itself (folder-dialog.mjs), else the page asks for the path
16 *   open a file / folder works: the host runs xdg-open itself (chat-files.mjs, artifacts.mjs)
17 *   window controls      none to offer: the browser has its own tab and window; the page never called the shell for them
18 *   notifications        the page does not use the shell for them; the host sends the one desktop notification it needs (notify-send)
19 *   app updater          NOT available: Tauri's updater lives in the window process. Settings says so in plain words and the
20 *                        engine and component updates (Strata Control) still work.
21 */
22import { execFile, spawn } from 'node:child_process';
23import { externalEnvironment } from './external-env.mjs';
24import { createAppUpdater } from './app-updater.mjs';
25
26export const APP_UPDATE_UNAVAILABLE = 'app-update-unavailable';
27export const BROWSER_UPDATE_MESSAGE = "The Strata app itself can't be updated in browser mode. Start Strata from its icon, without --browser, to update it.";
28const BRIDGE_URL = /^http:\/\/127\.0\.0\.1:\d+$/;
29const MODES = new Set(['window', 'browser']);
30
31/** Browsers and openers to try, in order, when the address of the page is opened for the person. */
32export const OPENERS = [['xdg-open'], ['gio', 'open'], ['sensible-browser'], ['x-www-browser'], ['firefox'], ['chromium'], ['google-chrome']];
33
34/**
35 * Start one opener and say whether it took the address: false when the program is missing or ends with an error within a couple of
36 * seconds. xdg-open often stays running until the browser closes, so a program that is still running counts as success.
37 */
38export function startOpener(command, args, { spawnProcess = spawn, env = externalEnvironment(), settleMs = 2500 } = {}) {
39  return new Promise(resolve => {
40    let child;
41    try { child = spawnProcess(command, args, { detached: true, stdio: 'ignore', env }); } catch { return resolve(false); }
42    let done = false;
43    const finish = value => { if (!done) { done = true; clearTimeout(timer); resolve(value); } };
44    const timer = setTimeout(() => { try { child.unref?.(); } catch { /* ignore */ } finish(true); }, settleMs);
45    child.on('error', () => finish(false));
46    child.on('exit', code => finish(code === 0));
47  });
48}
49
50export async function openInBrowser(url, { openers = OPENERS, start = startOpener } = {}) {
51  for (const [command, ...rest] of openers) if (await start(command, [...rest, url])) return true;
52  return false;
53}
54
55/** One desktop notification (notify-send), best effort: no notification daemon or no notify-send is not an error. */
56export function sendNotification(message, { run = execFile, env = externalEnvironment() } = {}) {
57  return new Promise(resolve => {
58    try { run('notify-send', ['--app-name=Strata', '--icon=dialog-information', 'Strata', message], { env, timeout: 5000 }, error => resolve(!error)); }
59    catch { resolve(false); }
60  });
61}
62
63export function createAppUi({ env = process.env, shutdown = () => {}, open = openInBrowser, notify = sendNotification, createUpdater = createAppUpdater } = {}) {
64  let mode = MODES.has(env.STRATA_UI_MODE) ? env.STRATA_UI_MODE : null;
65  let reason = mode === 'browser' ? (env.STRATA_UI_REASON || 'chosen') : null;
66  let bridge = null;
67  const originalBridge = createUpdater({ env });   // the older way: the shell passed the bridge in the environment
68
69  /** The shell's updater as the rest of the host sees it, or null when no app started this host. */
70  const updater = mode === null && !originalBridge ? null : {
71    get unavailable() { return mode === 'browser' ? BROWSER_UPDATE_MESSAGE : null; },
72    async check() { return (await current()).check(); },
73    async install(options) { return (await current()).install(options); },
74  };
75  async function current() {
76    if (bridge) return bridge;
77    if (originalBridge) return originalBridge;
78    throw Object.assign(new Error(mode === 'browser' ? BROWSER_UPDATE_MESSAGE : 'The app updater is not ready yet. Try again in a moment.'), { code: APP_UPDATE_UNAVAILABLE });
79  }
80
81  return {
82    updater,
83    get mode() { return mode; },
84    /** What the page reads to decide what to show. */
85    state: () => ({ mode, reason, canQuit: mode === 'browser', appUpdate: mode === 'browser' || mode === null ? 'unavailable' : 'available' }),
86    /** The window process hands over its updater bridge (a loopback address and a token). */
87    setBridge({ url, token } = {}) {
88      if (typeof url !== 'string' || !BRIDGE_URL.test(url) || typeof token !== 'string' || token.length < 16) throw new Error('That is not a bridge address.');
89      bridge = createUpdater({ env: { STRATA_SHELL_BRIDGE: url, STRATA_SHELL_TOKEN: token } });
90      return true;
91    },
92    /** Open the page in the default browser without changing the mode (a second start while Strata runs). */
93    openPage: url => open(url),
94    /** The shell moves everyone to a browser tab: the window could not start or has stopped. */
95    async switchToBrowser({ url, reason: why = 'window-failed', notice = '', openPage = true } = {}) {
96      mode = 'browser'; reason = String(why).slice(0, 40); bridge = null;
97      const opened = openPage && url ? await open(url) : false;
98      if (notice) void notify(notice);
99      return { mode, reason, opened };
100    },
101    /** The "Quit Strata" menu entry: only in browser mode, where closing the tab leaves the engine running. */
102    quit() {
103      if (mode !== 'browser') return { ok: false, status: 409, error: 'Close the Strata window to quit.' };
104      setImmediate(() => void shutdown());
105      return { ok: true, status: 202 };
106    },
107  };
108}