okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
261145baa
main
1/** Open a file in the person's text editor (not the program a .json happens to belong to: that can be a browser). */ 2import { execFile } from 'node:child_process' ; 3import { launch } from './chat-files.mjs' ; 4import { externalEnvironment } from './external-env.mjs' ; 5 6/** The command that opens `file` as text on this system, or null when only the file's own program is known. */ 7export async function textEditorCommand ( file , { platform= process . platform , ask= askSystem } = {}) { 8if ( platform === 'win32' ) return [ 'notepad.exe' , [ file ]]; 9if ( platform === 'darwin' ) return [ 'open' , [ '-t' , file ]]; 10// Linux: the program the system opens plain text with (gedit, kate, mousepad, ...), through its desktop entry. 11const entry = ( await ask ( 'xdg-mime' , [ 'query' , 'default' , 'text/plain' ])). trim (); 12if ( / ^ [ \w .+- ] + \.desktop$ / . test ( entry )) { 13const gtk = ( await ask ( 'sh' , [ '-c' , 'command -v gtk-launch' ])). trim (); 14if ( gtk ) return [ gtk , [ entry , file ]]; 15const gio = ( await ask ( 'sh' , [ '-c' , 'command -v gio' ])). trim (); 16if ( gio ) { 17for ( const dir of [ '/usr/share/applications' , '/usr/local/share/applications' , ` ${ process . env . HOME ?? '' } /.local/share/applications` ]) { 18const path = ` ${ dir } / ${ entry } ` ; 19if (( await ask ( 'test' , [ '-f' , path ], true )) === 'yes' ) return [ gio , [ 'launch' , path , file ]]; 20} 21} 22} 23return null ; 24} 25 26function askSystem ( command , args , yesNo = false ) { 27return new Promise ( resolve => { 28execFile ( command , args , { timeout :3000 , env :externalEnvironment () }, ( error , stdout ) => resolve ( yesNo ?( error ?'no' :'yes' ) :( error ?'' :String ( stdout )))); 29}); 30} 31 32/** Start the editor and return at once. Falls back to the file's own program (xdg-open) when no text editor is known. */ 33export async function openTextFile ( file , { platform= process . platform , ask, recorder= null } = {}) { 34const found = await textEditorCommand ( file , { platform, ask}); 35const [ command , args ] = found ?? [ 'xdg-open' , [ file ]]; 36launch ( command , args , { recorder}); 37return { command, args}; 38}