okami.mom/strata

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

Niko1221rc1 merge ds-coder (d6a5a7837)4fb068a8c

main
12.3 KiB207 linesraw
1/**
2 * The host's native "choose a folder" dialog, one per platform:
3 *   macOS    osascript (choose folder)            -- unchanged
4 *   Windows  PowerShell FolderBrowserDialog (STA, topmost owner so it never opens behind the app)
5 *   Linux    zenity, then kdialog, then the desktop portal (gdbus), all with the environment the AppImage was started from
6 * Where no dialog works the caller gets { unavailable: true } and the app shows a plain message and a field for the path.
7 */
8import { spawn } from 'node:child_process';
9import { stat } from 'node:fs/promises';
10import { exec } from './util.mjs';
11import { externalEnvironment } from './external-env.mjs';
12
13const MAC_SCRIPT = prompt => `POSIX path of (choose folder with prompt "${prompt.replace(/["\\]/g, '')}")`;
14
15export function windowsFolderScript(prompt) {
16  const text = prompt.replace(/'/g, "''");
17  return [
18    'Add-Type -AssemblyName System.Windows.Forms',
19    '[Console]::OutputEncoding = [System.Text.Encoding]::UTF8',
20    '$owner = New-Object System.Windows.Forms.Form',
21    '$owner.TopMost = $true; $owner.ShowInTaskbar = $false; $owner.StartPosition = "CenterScreen"; $owner.Size = New-Object System.Drawing.Size(0, 0)',
22    '$owner.Show(); $owner.Activate()',
23    '$dialog = New-Object System.Windows.Forms.FolderBrowserDialog',
24    `$dialog.Description = '${text}'`,
25    '$dialog.ShowNewFolderButton = $true',
26    // READY tells the host the window is about to open; a host that never sees it gives up and asks for the path in words (QA F06).
27    '[Console]::Out.WriteLine("READY"); [Console]::Out.Flush()',
28    // The dialog starts at the Desktop folder. Where that folder does not exist (it was deleted, a OneDrive move left a dead path, the profile was
29    // redirected) ShowDialog throws "Unable to retrieve the root folder" and no folder could be chosen at all: start at This PC instead, and when even
30    // that fails say NODIALOG so the app asks for the path.
31    '$answer = $null',
32    'try { $answer = $dialog.ShowDialog($owner) } catch { try { $dialog.RootFolder = [System.Environment+SpecialFolder]::MyComputer; $answer = $dialog.ShowDialog($owner) } catch { [Console]::Out.WriteLine("NODIALOG"); [Console]::Out.Flush() } }',
33    'if ($answer -eq "OK") { [Console]::Out.Write($dialog.SelectedPath) }',
34    '$owner.Close()',
35  ].join('; ');
36}
37
38/** powershell.exe takes the script as UTF-16LE base64, so no quoting survives to be mangled. */
39export function windowsFolderArgs(prompt) {
40  return ['-NoProfile', '-NonInteractive', '-STA', '-EncodedCommand', Buffer.from(windowsFolderScript(prompt), 'utf16le').toString('base64')];
41}
42
43/** Strip trailing separators, but leave a drive or filesystem root intact. */
44export function cleanChosenPath(value) {
45  const text = String(value ?? '').trim();
46  if (/^[A-Za-z]:[\\/]*$/.test(text)) return text.slice(0, 2) + '\\';
47  return text.length > 1 ? text.replace(/[\\/]+$/, '') || text.slice(0, 1) : text;
48}
49
50const missing = error => error?.code === 'ENOENT';
51
52/** What the script printed, without its READY line. */
53const answerOf = stdout => String(stdout ?? '').split(/\r?\n/).filter(line => line.trim() && line.trim() !== 'READY').join('\n');
54
55/**
56 * Runs the Windows dialog and watches it. Resolves { stdout } when it ends, { noDialog: true } when its window never got as far as
57 * opening (no READY within `readyMs`: PowerShell blocked, stuck or without a desktop), and rejects with { code } as exec does.
58 * The person's own time with the open dialog is not limited (a day at most).
59 */
60export function watchedWindowsDialog(shell, args, { readyMs = 30_000, openMs = 24 * 3600_000, spawnProcess = spawn } = {}) {
61  return new Promise((resolve, reject) => {
62    const child = spawnProcess(shell, args, { windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] });
63    let stdout = '', ready = false, settled = false;
64    child.stdout?.setEncoding?.('utf8');                 // a multi-byte letter of a Cyrillic folder must not be cut between two chunks
65    const end = (fn, value) => { if (settled) return; settled = true; clearTimeout(timer); try { child.kill(); } catch { /* gone */ } fn(value); };
66    const timer = setTimeout(() => end(resolve, ready ? { stdout: '' } : { noDialog: true }), readyMs);
67    const later = () => { clearTimeout(timer); ready = true; setTimeout(() => end(resolve, { stdout: '' }), openMs).unref?.(); };
68    child.stdout?.on('data', chunk => { stdout += chunk; if (!ready && /^READY\s*$/m.test(stdout)) { clearTimeout(timer); later(); } });
69    child.on('error', error => end(reject, error));
70    child.on('close', code => { if (settled) return; settled = true; clearTimeout(timer);
71      // PowerShell ended before its window opened (security software ended it, #3831): the person types the path instead.
72      if (!ready) return resolve({ noDialog: true });
73      code === 0 ? resolve({ stdout }) : reject(Object.assign(new Error('exit ' + code), { code })); });
74  });
75}
76
77/**
78 * Ask for a folder. Resolves { path } | { cancelled: true } | { unavailable: true, reason }.
79 * `run` is injectable for tests: (command, args) => Promise<{ stdout }>.
80 */
81export async function chooseFolder(prompt, options = {}) {
82  const { platform = process.platform, run = exec, portal = portalFolder, windowsDialog = options.run ? null : watchedWindowsDialog } = options;
83  if (platform === 'darwin') {
84    try {
85      const { stdout } = await run('osascript', ['-e', MAC_SCRIPT(prompt)]);
86      return stdout.trim() ? { path: cleanChosenPath(stdout) } : { cancelled: true };
87    } catch {
88      return { cancelled: true }; // dismissing the dialog is an exit code, not a failure
89    }
90  }
91  if (platform === 'win32') {
92    const shell = `${process.env.SystemRoot || 'C:\\Windows'}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
93    try {
94      const done = windowsDialog ? await windowsDialog(shell, windowsFolderArgs(prompt)) : await run(shell, windowsFolderArgs(prompt));
95      if (done.noDialog) return { unavailable: true, failed: true, reason: 'The folder window did not open. Type the folder path instead.' };
96      if (/^NODIALOG\s*$/m.test(String(done.stdout ?? ''))) return { unavailable: true, failed: true, reason: 'The folder window could not open. Type the folder path instead.' };
97      const answer = answerOf(done.stdout).trim();
98      return answer ? { path: cleanChosenPath(answer) } : { cancelled: true };
99    } catch (error) {
100      if (missing(error)) return { unavailable: true, reason: 'Windows PowerShell was not found.' };
101      // The window opened or tried to and ended with an error: the person is asked for the path instead of being left with an error and no way on.
102      return { unavailable: true, failed: true, reason: 'The folder window could not open. Type the folder path instead.', detail: `exit ${error?.code ?? '?'}` };
103    }
104  }
105  return chooseLinuxFolder(prompt, { run, portal });
106}
107
108/** A chooser that is there but broke (the display is missing, a library does not load) must say so; a bare exit 1 is a cancel. */
109const BROKEN = /unable to init server|cannot open display|can't open display|no protocol specified|error while loading shared libraries|symbol lookup error|version `[^']*' not found|cannot connect to|failed to connect|could not connect/i;
110const firstLine = text => String(text ?? '').split(/\r?\n/).map(l => l.trim()).find(Boolean)?.slice(0, 160) ?? '';
111
112/**
113 * Linux: zenity, then kdialog, then the desktop portal's file chooser through gdbus. Every one of them runs with the environment the
114 * AppImage was started from (external-env.mjs), not Strata's own libraries. A chooser that is missing is skipped; one that fails is
115 * remembered and the next is tried; when none works the answer says why and the person types the path.
116 */
117async function chooseLinuxFolder(prompt, { run, portal }) {
118  const env = externalEnvironment();
119  const candidates = [
120    ['zenity', ['--file-selection', '--directory', `--title=${prompt}`]],
121    ['kdialog', ['--getexistingdirectory', '.', '--title', prompt]],
122  ];
123  const failures = [];
124  for (const [command, args] of candidates) {
125    try {
126      const { stdout } = await run(command, args, { env });
127      return stdout.trim() ? { path: cleanChosenPath(stdout) } : { cancelled: true };
128    } catch (error) {
129      if (missing(error)) continue;
130      const detail = `${error?.stderr ?? ''}`;
131      if (error?.code === 1 && !BROKEN.test(detail)) return { cancelled: true }; // both tools exit 1 when the dialog is dismissed
132      failures.push(`${command}: ${firstLine(detail) || firstLine(error?.message) || `exit ${error?.code}`}`);
133    }
134  }
135  try {
136    const picked = await portal(prompt, { run, env });
137    if (picked) return picked;
138  } catch (error) {
139    failures.push(`portal: ${firstLine(error?.message)}`);
140  }
141  return {
142    unavailable: true, failed: failures.length > 0, ...(failures.length ? { detail: failures.join('; ') } : {}),
143    reason: failures.length
144      ? 'The folder chooser could not open. Install zenity or kdialog to pick a folder, or type the path.'
145      : 'No folder chooser was found. Install zenity or kdialog to pick a folder, or type the path.',
146  };
147}
148
149/**
150 * xdg-desktop-portal FileChooser through gdbus. Resolves { path } | { cancelled: true } | null when there is no portal or no gdbus.
151 * The answer arrives as a Response signal on the request the call returns, so a monitor is started first.
152 */
153export async function portalFolder(prompt, { run = exec, env = externalEnvironment(), spawnProcess = spawn, timeoutMs = 10 * 60_000 } = {}) {
154  const monitor = spawnProcess('gdbus', ['monitor', '--session', '--dest', 'org.freedesktop.portal.Desktop'], { env, stdio: ['ignore', 'pipe', 'ignore'] });
155  let seen = '';
156  let ended = false;
157  monitor.on('error', () => { ended = true; });
158  monitor.on('close', () => { ended = true; });
159  monitor.stdout?.on('data', chunk => { seen += chunk; });
160  try {
161    let call;
162    try {
163      call = await run('gdbus', ['call', '--session', '--dest', 'org.freedesktop.portal.Desktop', '--object-path', '/org/freedesktop/portal/desktop',
164        '--method', 'org.freedesktop.portal.FileChooser.OpenFile', '', prompt, "{'directory': <true>, 'modal': <true>}"], { env });
165    } catch {
166      return null;                                           // no gdbus, or no portal on the session bus
167    }
168    const handle = /'(\/org\/freedesktop\/portal\/desktop\/request\/[^']+)'/.exec(call.stdout)?.[1];
169    if (!handle) return null;
170    const deadline = Date.now() + timeoutMs;
171    while (Date.now() < deadline) {
172      const line = seen.split('\n').find(l => l.startsWith(`${handle}: org.freedesktop.portal.Request.Response`));
173      if (line) {
174        const m = /\(uint32 (\d+), (.*)\)\s*$/.exec(line);
175        if (!m || m[1] !== '0') return { cancelled: true };
176        const uri = /'(file:\/\/[^']*)'/.exec(m[2])?.[1];
177        return uri ? { path: cleanChosenPath(decodeURIComponent(uri.replace(/^file:\/\//, ''))) } : { cancelled: true };
178      }
179      if (ended) return null;
180      await new Promise(r => setTimeout(r, 100));
181    }
182    return { cancelled: true };
183  } finally {
184    try { monitor.kill(); } catch { /* already gone */ }
185  }
186}
187
188export const TYPE_A_PATH = 'No folder chooser is available on this system, so type the folder path instead.';
189
190/** The host's answer when no chooser works: a plain sentence and a code the app turns into a field for typing the path. */
191export function chooserUnavailable(picked) {
192  return { message: picked.reason, code: 'folder-chooser-unavailable', details: picked.detail };
193}
194
195/** A typed path stands in for the dialog: it must be an absolute directory that exists. `fileType` (a RegExp on the name) also lets a
196 *  file of that kind through (the model page takes a folder or one .gguf file). Quotes around the path (Windows "Copy as path") go. */
197export async function typedFolder(value, { isAbsolute, fileType = null }) {
198  let text = typeof value === 'string' ? value.trim() : '';
199  if (text.length > 1 && /^(["'])[\s\S]*\1$/.test(text)) text = text.slice(1, -1).trim();
200  if (!text || text.includes('\0')) return null;
201  if (!isAbsolute(text)) throw new Error(fileType ? 'Enter the full path of the folder or the file.' : 'Enter the full path of the folder.');
202  let info;
203  try { info = await stat(text); } catch { throw new Error(fileType ? 'That folder or file does not exist.' : 'That folder does not exist.'); }
204  if (info.isFile() && fileType?.test(text)) return text;
205  if (!info.isDirectory()) throw new Error(fileType ? 'Choose a folder, or a .gguf file.' : 'Choose a folder, not a file.');
206  return cleanChosenPath(text);
207}