okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
4fb068a8c
main
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 ) { 16const text = prompt . replace ( / ' / g , "''" ); 17return [ 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 ) { 40return [ '-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 ) { 45const text = String ( value ?? '' ). trim (); 46if ( / ^ [ A - Za - z ] : [ \\ / ] * $ / . test ( text )) return text . slice ( 0 , 2 ) + '\\' ; 47return 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 } = {}) { 61return new Promise (( resolve , reject ) => { 62const child = spawnProcess ( shell , args , { windowsHide :true , stdio :[ 'ignore' , 'pipe' , 'ignore' ] }); 63let stdout = '' , ready = false , settled = false ; 64child . stdout ?. setEncoding ?.( 'utf8' ); // a multi-byte letter of a Cyrillic folder must not be cut between two chunks 65const end = ( fn , value ) => { if ( settled ) return ; settled = true ; clearTimeout ( timer ); try { child . kill (); } catch { /* gone */ } fn ( value ); }; 66const timer = setTimeout (() => end ( resolve , ready ?{ stdout :'' } :{ noDialog :true }), readyMs ); 67const later = () => { clearTimeout ( timer ); ready = true ; setTimeout (() => end ( resolve , { stdout :'' }), openMs ). unref ?.(); }; 68child . stdout ?. on ( 'data' , chunk => { stdout += chunk ; if ( ! ready && / ^READY\s * $ / m . test ( stdout )) { clearTimeout ( timer ); later (); } }); 69child . on ( 'error' , error => end ( reject , error )); 70child . 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. 72if ( ! ready ) return resolve ({ noDialog :true }); 73code === 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 = {}) { 82const { platform= process . platform , run= exec , portal= portalFolder , windowsDialog= options . run ?null :watchedWindowsDialog } = options ; 83if ( platform === 'darwin' ) { 84try { 85const { stdout} = await run ( 'osascript' , [ '-e' , MAC_SCRIPT ( prompt )]); 86return stdout . trim () ?{ path :cleanChosenPath ( stdout ) } :{ cancelled :true }; 87} catch { 88return { cancelled :true }; // dismissing the dialog is an exit code, not a failure 89} 90} 91if ( platform === 'win32' ) { 92const shell = ` ${ process . env . SystemRoot || 'C:\\Windows' } \\System32\\WindowsPowerShell\\v1.0\\powershell.exe` ; 93try { 94const done = windowsDialog ?await windowsDialog ( shell , windowsFolderArgs ( prompt )) :await run ( shell , windowsFolderArgs ( prompt )); 95if ( done . noDialog ) return { unavailable :true , failed :true , reason :'The folder window did not open. Type the folder path instead.' }; 96if ( / ^NODIALOG\s * $ / m . test ( String ( done . stdout ?? '' ))) return { unavailable :true , failed :true , reason :'The folder window could not open. Type the folder path instead.' }; 97const answer = answerOf ( done . stdout ). trim (); 98return answer ?{ path :cleanChosenPath ( answer ) } :{ cancelled :true }; 99} catch ( error ) { 100if ( 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. 102return { unavailable :true , failed :true , reason :'The folder window could not open. Type the folder path instead.' , detail :`exit ${ error ?. code ?? '?' } ` }; 103} 104} 105return 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}) { 118const env = externalEnvironment (); 119const candidates = [ 120[ 'zenity' , [ '--file-selection' , '--directory' , `--title= ${ prompt } ` ]], 121[ 'kdialog' , [ '--getexistingdirectory' , '.' , '--title' , prompt ]], 122]; 123const failures = []; 124for ( const [ command , args ] of candidates ) { 125try { 126const { stdout} = await run ( command , args , { env}); 127return stdout . trim () ?{ path :cleanChosenPath ( stdout ) } :{ cancelled :true }; 128} catch ( error ) { 129if ( missing ( error )) continue ; 130const detail = ` ${ error ?. stderr ?? '' } ` ; 131if ( error ?. code === 1 && ! BROKEN . test ( detail )) return { cancelled :true }; // both tools exit 1 when the dialog is dismissed 132failures . push ( ` ${ command } : ${ firstLine ( detail ) || firstLine ( error ?. message ) || `exit ${ error ?. code } ` } ` ); 133} 134} 135try { 136const picked = await portal ( prompt , { run, env}); 137if ( picked ) return picked ; 138} catch ( error ) { 139failures . push ( `portal: ${ firstLine ( error ?. message )} ` ); 140} 141return { 142unavailable :true , failed :failures . length > 0 , ...( failures . length ?{ detail :failures . join ( '; ' ) } :{}), 143reason :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 } = {}) { 154const monitor = spawnProcess ( 'gdbus' , [ 'monitor' , '--session' , '--dest' , 'org.freedesktop.portal.Desktop' ], { env, stdio :[ 'ignore' , 'pipe' , 'ignore' ] }); 155let seen = '' ; 156let ended = false ; 157monitor . on ( 'error' , () => { ended = true ; }); 158monitor . on ( 'close' , () => { ended = true ; }); 159monitor . stdout ?. on ( 'data' , chunk => { seen += chunk ; }); 160try { 161let call ; 162try { 163call = 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 { 166return null ; // no gdbus, or no portal on the session bus 167} 168const handle = / ' ( \/org\/freedesktop\/portal\/desktop\/request\/ [ ^ ' ] + ) ' / . exec ( call . stdout )?.[ 1 ]; 169if ( ! handle ) return null ; 170const deadline = Date . now () + timeoutMs ; 171while ( Date . now () < deadline ) { 172const line = seen . split ( '\n' ). find ( l => l . startsWith ( ` ${ handle } : org.freedesktop.portal.Request.Response` )); 173if ( line ) { 174const m = / \(uint32 ( \d + ) , ( . * ) \)\s * $ / . exec ( line ); 175if ( ! m || m [ 1 ] !== '0' ) return { cancelled :true }; 176const uri = / ' ( file:\/\/ [ ^ ' ] * ) ' / . exec ( m [ 2 ])?.[ 1 ]; 177return uri ?{ path :cleanChosenPath ( decodeURIComponent ( uri . replace ( / ^file:\/\/ / , '' ))) } :{ cancelled :true }; 178} 179if ( ended ) return null ; 180await new Promise ( r => setTimeout ( r , 100 )); 181} 182return { cancelled :true }; 183} finally { 184try { 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 ) { 192return { 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 }) { 198let text = typeof value === 'string' ?value . trim () :'' ; 199if ( text . length > 1 && / ^ ([ "' ])[ \s\S ] * \1$ / . test ( text )) text = text . slice ( 1 , - 1 ). trim (); 200if ( ! text || text . includes ( '\0' )) return null ; 201if ( ! isAbsolute ( text )) throw new Error ( fileType ?'Enter the full path of the folder or the file.' :'Enter the full path of the folder.' ); 202let info ; 203try { info = await stat ( text ); } catch { throw new Error ( fileType ?'That folder or file does not exist.' :'That folder does not exist.' ); } 204if ( info . isFile () && fileType ?. test ( text )) return text ; 205if ( ! info . isDirectory ()) throw new Error ( fileType ?'Choose a folder, or a .gguf file.' :'Choose a folder, not a file.' ); 206return cleanChosenPath ( text ); 207}