3131
3232import java .io .File ;
3333import java .io .IOException ;
34- import java .io .InputStream ;
35- import java .net .URI ;
36- import java .nio .charset .StandardCharsets ;
3734import java .util .ArrayList ;
3835import java .util .Arrays ;
39- import java .util .Collections ;
40- import java .util .HashMap ;
4136import java .util .LinkedHashMap ;
4237import java .util .List ;
4338import java .util .Map ;
44- import java .util .WeakHashMap ;
4539
46- import org .apposed .appose .Appose ;
4740import org .apposed .appose .Environment ;
48- import org .apposed .appose .Service ;
4941import org .apposed .appose .util .Environments ;
50- import org .eclipse .lsp4j .TextDocumentItem ;
5142import org .scijava .plugins .scripting .appose .python .ScriptEnvironment ;
5243import org .scijava .plugins .scripting .appose .python ._internal .InlineMetadata ;
5344import org .scijava .plugins .scripting .appose .python ._internal .ResidentWorker ;
5647/**
5748 * Where Python scripts run via Appose, as their language servers need to
5849 * know: the Python of a script's environment, if built (in this session, or an
59- * earlier one; never building it, nor disturbing its worker); the overlay of
60- * packages it declares but its environment lacks (see
61- * {@link DependencyOverlays}), and the tooling environment overlays are
62- * installed from.
50+ * earlier one; never building it, nor disturbing its worker). (Packages a
51+ * script declares, but its environment lacks, are known to the servers too;
52+ * see scijava-code-lsp-jedi.)
6353 *
6454 * @author Gabriel Selzer
6555 */
6656final class ApposePythonEnvironments {
6757
68- /** Name of the tooling environment that installs overlays. */
69- static final String TOOLING_ENV = "appose-python-completion" ;
70-
71- /**
72- * How long a script's dependencies must stay unchanged before packages
73- * missing from its environment are installed for completion, in ms.
74- */
75- private static final long OVERLAY_SETTLE = 1500 ;
76-
77- /** Task scripts (see overlay.py), by resource name. */
78- private static final Map <String , String > SCRIPTS = new HashMap <>();
79-
80- /** One per resident worker service (that is, per context). */
81- private static final Map <ResidentWorkerService , ApposePythonEnvironments > ALL =
82- new WeakHashMap <>();
83-
58+ /** The resident workers, to find built environments; or null if none. */
8459 private final ResidentWorkerService workers ;
8560
8661 /** Python executables of script environments, by script and metadata. */
@@ -96,132 +71,25 @@ protected boolean removeEldestEntry(
9671 }
9772 };
9873
99- private DependencyOverlays overlays ;
100-
101- private ApposePythonEnvironments (final ResidentWorkerService workers ) {
74+ /** @param workers The resident workers, or null if none. */
75+ ApposePythonEnvironments (final ResidentWorkerService workers ) {
10276 this .workers = workers ;
10377 }
10478
105- /** Gets those of a context (by its resident worker service). */
106- static ApposePythonEnvironments of (final ResidentWorkerService workers ) {
107- synchronized (ALL ) {
108- return ALL .computeIfAbsent (workers , ApposePythonEnvironments ::new );
109- }
110- }
111-
112- /**
113- * Derives an {@link org.scijava.code.lsp.Environment} for an Appose script.
114- * <p>
115- * The {@code python} executable is found using the script's text and file
116- * path. For convenience, packages declared in the script but not yet
117- * installed (i.e. between the time the dependency is added to the script
118- * and the time when it is run) are provided to the language server in the
119- * <em>overlay</em>.
120- * </p>
121- *
122- * @param script the script
123- * @return an {@link org.scijava.code.lsp.Environment} where:
124- * <ul>
125- * <li>the interpreter is the Python executable of the script's
126- * declared environment, <b>if that has already been built</b>,
127- * or {@code null} otherwise;</li>
128- * <li>the paths hold the overlay, once installed; none if no package
129- * is missing, or until it is installed (which starts once the
130- * script's dependencies stop changing, or at once if the script was
131- * just opened).</li>
132- * </ul>
133- */
134- org .scijava .code .lsp .Environment environment (final TextDocumentItem script ) {
135- final String text = script .getText ();
136- final String path = path (script .getUri ());
137- final String python = scriptPython (text , path );
138- final boolean settled = script .getVersion () <= 1 ;
139- // NB: An alternative design could have all the script's dependencies
140- // in a constant overlay, but that would have the effect of installing them
141- // twice - once for the overlay and once for the script's environment.
142- final String overlay = overlay (text , path , python , settled );
143- return new org .scijava .code .lsp .Environment (python , overlay == null ? null
144- : Collections .singletonList (overlay ), null );
145- }
146-
147- /** Sets the dependency overlays, e.g. to use fake ones in tests. */
148- synchronized void setOverlays (final DependencyOverlays overlays ) {
149- this .overlays = overlays ;
150- }
151-
152- /** The file path of a {@code file:} URI, or null. */
153- static String path (final String uri ) {
154- try {
155- final URI u = URI .create (uri );
156- return "file" .equals (u .getScheme ()) ? new File (u ).getPath () : null ;
157- }
158- catch (final IllegalArgumentException exc ) {
159- return null ;
160- }
161- }
162-
16379 /**
164- * Gets the overlay of packages the script declares but its environment
165- * lacks (see {@link DependencyOverlays}), if ready; starts preparing it
166- * otherwise. Only for environments declared inline, for now .
80+ * Gets where an Appose script runs: the Python executable of its declared
81+ * environment, <b>if that has already been built</b>; or none (the
82+ * servers' own Python), otherwise .
16783 *
168- * @param settled Whether the dependencies are known not to be changing .
169- * @return The overlay directory , or null if none is needed or ready .
84+ * @param text The script's text .
85+ * @param path The script's file path , or null if it has none .
17086 */
171- String overlay (final String text , final String path ,
172- final String python , final boolean settled )
87+ org . scijava . code . lsp . Environment environment (final String text ,
88+ final String path )
17389 {
174- final DependencyOverlays overlays = overlays ();
175- if (overlays == null ) return null ;
176- final List <String > dependencies ;
177- final String name ;
178- try {
179- final String metadata = InlineMetadata .extract (text );
180- if (metadata == null ) return null ;
181- dependencies = InlineMetadata .dependencies (metadata );
182- // NB: Unsaved scripts' environments are named after their metadata,
183- // which changes as dependencies are edited: share one overlay.
184- name = path == null ? "unsaved" : ScriptEnvironment .inlineName (metadata ,
185- path );
186- }
187- catch (final RuntimeException exc ) {
188- return null ; // NB: E.g. half-typed metadata.
189- }
190- return overlays .overlay (name , python , dependencies , settled );
191- }
192-
193- /** Gets the dependency overlays, creating them on first use. */
194- private synchronized DependencyOverlays overlays () {
195- if (overlays != null ) return overlays ;
196- if (workers == null ) return null ;
197- overlays = new DependencyOverlays ((python , dependencies ,
198- dir ) -> installOverlay (workers , python , dependencies , dir ), new File (
199- Environments .apposeEnvsDir (), TOOLING_ENV + "-overlays" ),
200- OVERLAY_SETTLE , System ::currentTimeMillis );
201- return overlays ;
202- }
203-
204- /**
205- * Installs an overlay by running overlay.py on the tooling environment's
206- * worker. Called on the overlays' background thread.
207- */
208- private static String installOverlay (final ResidentWorkerService workers ,
209- final String python , final List <String > dependencies , final File dir )
210- {
211- final Map <String , Object > inputs = new HashMap <>();
212- inputs .put ("python" , python );
213- inputs .put ("dependencies" , dependencies );
214- inputs .put ("overlay" , dir .getAbsolutePath ());
215- try {
216- final Service .Task task = toolingWorker (workers ).task (resource (
217- "overlay.py" ), inputs );
218- task .waitFor ();
219- final Object overlay = task .outputs .get ("path" );
220- return overlay instanceof String ? (String ) overlay : null ;
221- }
222- catch (final Exception exc ) {
223- throw new IllegalStateException ("Overlay installation failed" , exc );
224- }
90+ final String python = scriptPython (text , path );
91+ return python == null ? org .scijava .code .lsp .Environment .NONE
92+ : new org .scijava .code .lsp .Environment (python , null , null );
22593 }
22694
22795 /**
@@ -340,56 +208,4 @@ private static String findPython(final List<File> dirs) {
340208 }
341209 return null ;
342210 }
343-
344- /** Gets the tooling environment's worker, building it first if needed. */
345- private static ResidentWorker toolingWorker (
346- final ResidentWorkerService workers )
347- {
348- final String config = toolingConfig ();
349- return workers .worker (TOOLING_ENV , null , config , () -> Appose .content (
350- config ).scheme ("pixi.toml" ), Environment ::python );
351- }
352-
353- /**
354- * The tooling environment: Python and Appose, to run overlay.py; and uv, to
355- * install packages for {@link DependencyOverlays}.
356- */
357- static String toolingConfig () {
358- return "[workspace]\n " + //
359- "name = \" " + TOOLING_ENV + "\" \n " + //
360- "channels = [\" conda-forge\" ]\n " + //
361- "platforms = [\" " + InlineMetadata .condaPlatform () + "\" ]\n " + //
362- "\n " + //
363- "[dependencies]\n " + //
364- // NB: The overlays of scripts whose environment is not built are
365- // installed for this Python, for jedi-language-server's Python (see
366- // code-lsp-jedi) to find: the versions must match.
367- "python = \" 3.12.*\" \n " + //
368- "\n " + //
369- "[pypi-dependencies]\n " + //
370- "appose = \" *\" \n " + //
371- "uv = \" *\" \n " ;
372- }
373-
374- /** Gets a task script (e.g. overlay.py), by resource name. */
375- private static String resource (final String name ) throws IOException {
376- synchronized (SCRIPTS ) {
377- final String known = SCRIPTS .get (name );
378- if (known != null ) return known ;
379- try (final InputStream in = ApposePythonEnvironments .class
380- .getResourceAsStream (name ))
381- {
382- if (in == null ) throw new IOException (name + " not found" );
383- final java .io .ByteArrayOutputStream out =
384- new java .io .ByteArrayOutputStream ();
385- final byte [] buf = new byte [8192 ];
386- int n ;
387- while ((n = in .read (buf )) > 0 ) out .write (buf , 0 , n );
388- final String script = new String (out .toByteArray (),
389- StandardCharsets .UTF_8 );
390- SCRIPTS .put (name , script );
391- return script ;
392- }
393- }
394- }
395211}
0 commit comments