2929
3030package org .scijava .ui .swing .script ;
3131
32- import java .awt .*;
32+ import java .awt .BorderLayout ;
33+ import java .awt .Color ;
34+ import java .awt .Component ;
35+ import java .awt .Cursor ;
36+ import java .awt .Desktop ;
37+ import java .awt .Dimension ;
38+ import java .awt .Font ;
39+ import java .awt .GridBagConstraints ;
40+ import java .awt .GridBagLayout ;
41+ import java .awt .Toolkit ;
3342import java .awt .datatransfer .DataFlavor ;
3443import java .awt .datatransfer .Transferable ;
3544import java .awt .datatransfer .UnsupportedFlavorException ;
7786import java .nio .file .Paths ;
7887import java .nio .file .StandardCopyOption ;
7988import java .nio .file .StandardOpenOption ;
89+ import java .time .LocalDateTime ;
90+ import java .time .format .DateTimeFormatter ;
8091import java .util .ArrayList ;
8192import java .util .Arrays ;
8293import java .util .Collection ;
8394import java .util .Collections ;
8495import java .util .ConcurrentModificationException ;
85- import java .time .LocalDateTime ;
86- import java .time .format .DateTimeFormatter ;
8796import java .util .Date ;
8897import java .util .Enumeration ;
8998import java .util .HashMap ;
9099import java .util .HashSet ;
91- import java .util .LinkedHashSet ;
100+ import java .util .IdentityHashMap ;
92101import java .util .LinkedHashMap ;
102+ import java .util .LinkedHashSet ;
93103import java .util .List ;
94- import java .util .concurrent .CopyOnWriteArrayList ;
95104import java .util .Map ;
96105import java .util .Objects ;
97106import java .util .Set ;
98- import java .util .function .BiConsumer ;
99- import java .util .function .IntPredicate ;
100107import java .util .TreeMap ;
101108import java .util .Vector ;
109+ import java .util .concurrent .CancellationException ;
110+ import java .util .concurrent .CopyOnWriteArrayList ;
102111import java .util .concurrent .ExecutionException ;
112+ import java .util .concurrent .Future ;
113+ import java .util .function .BiConsumer ;
114+ import java .util .function .IntPredicate ;
103115import java .util .jar .JarEntry ;
104116import java .util .jar .JarOutputStream ;
105117import java .util .regex .Matcher ;
106118import java .util .regex .Pattern ;
107119import java .util .zip .ZipException ;
108120
121+ import javax .script .Bindings ;
122+ import javax .script .ScriptContext ;
109123import javax .script .ScriptEngine ;
110124import javax .script .ScriptException ;
111- import javax .swing .*;
125+ import javax .swing .AbstractAction ;
126+ import javax .swing .AbstractButton ;
127+ import javax .swing .BorderFactory ;
128+ import javax .swing .Box ;
129+ import javax .swing .BoxLayout ;
130+ import javax .swing .ButtonGroup ;
131+ import javax .swing .Icon ;
132+ import javax .swing .JButton ;
133+ import javax .swing .JCheckBoxMenuItem ;
134+ import javax .swing .JComponent ;
135+ import javax .swing .JFrame ;
136+ import javax .swing .JLabel ;
137+ import javax .swing .JMenu ;
138+ import javax .swing .JMenuBar ;
139+ import javax .swing .JMenuItem ;
140+ import javax .swing .JOptionPane ;
141+ import javax .swing .JPanel ;
142+ import javax .swing .JPopupMenu ;
143+ import javax .swing .JRadioButtonMenuItem ;
144+ import javax .swing .JScrollPane ;
145+ import javax .swing .JSplitPane ;
146+ import javax .swing .JTabbedPane ;
147+ import javax .swing .JTextArea ;
148+ import javax .swing .JToggleButton ;
149+ import javax .swing .JToolBar ;
150+ import javax .swing .KeyStroke ;
151+ import javax .swing .SwingUtilities ;
152+ import javax .swing .Timer ;
153+ import javax .swing .UIManager ;
112154import javax .swing .event .ChangeEvent ;
113155import javax .swing .event .ChangeListener ;
114156import javax .swing .event .DocumentEvent ;
125167import org .fife .ui .rsyntaxtextarea .RSyntaxDocument ;
126168import org .fife .ui .rsyntaxtextarea .RSyntaxTextArea ;
127169import org .fife .ui .rsyntaxtextarea .Theme ;
170+ import org .fife .ui .rsyntaxtextarea .TokenMakerFactory ;
128171import org .fife .ui .rsyntaxtextarea .parser .ParserNotice ;
129172import org .fife .ui .rsyntaxtextarea .parser .TaskTagParser ;
130- import org .fife .ui .rsyntaxtextarea .TokenMakerFactory ;
131173import org .fife .ui .rtextarea .ClipboardHistory ;
132174import org .fife .ui .rtextarea .Macro ;
133175import org .fife .ui .rtextarea .RTextArea ;
@@ -376,6 +418,9 @@ public class TextEditor extends JFrame implements ActionListener,
376418
377419 private EditableScriptInfo scriptInfo ;
378420 private ScriptModule module ;
421+ private Bindings moduleBindings ;
422+ private BindingsRegistry .Lease replBindingsLease ;
423+ private static final BindingsRegistry BINDINGS_REGISTRY = new BindingsRegistry ();
379424 private boolean incremental = false ;
380425 private DragSource dragSource ;
381426 private boolean layoutLoading = true ;
@@ -3330,6 +3375,10 @@ static void deleteRecursively(final File directory) {
33303375 public void dispose () {
33313376 if (!disposed ) { // can be called more than once
33323377 disposed = true ;
3378+ releaseReplBindings ();
3379+ module = null ;
3380+ scriptInfo = null ;
3381+ moduleBindings = null ;
33333382 layoutSaveTimer .stop ();
33343383 titleTimer .stop ();
33353384 runTimer .stop ();
@@ -3353,6 +3402,9 @@ void setLanguage(final ScriptLanguage language) {
33533402
33543403 void setLanguage (final ScriptLanguage language , final boolean addHeader ) {
33553404 if (null != this .getCurrentLanguage () && (null == language || this .getCurrentLanguage ().getLanguageName () != language .getLanguageName ())) {
3405+ releaseReplBindings ();
3406+ this .module = null ;
3407+ this .moduleBindings = null ;
33563408 this .scriptInfo = null ;
33573409 }
33583410 getEditorPane ().setLanguage (language , addHeader );
@@ -4650,10 +4702,98 @@ public String getProcessedScript() {
46504702 }
46514703 }
46524704
4705+ static final class BindingsRegistry {
4706+
4707+ private final Map <Bindings , Integer > associationCounts = new IdentityHashMap <>();
4708+
4709+ synchronized Lease retain (final Bindings bindings ) {
4710+ if (bindings == null ) return new Lease (null , null );
4711+ final int count = associationCounts .getOrDefault (bindings , 0 ) + 1 ;
4712+ associationCounts .put (bindings , count );
4713+ return new Lease (this , bindings );
4714+ }
4715+
4716+ private synchronized void release (final Bindings bindings ) {
4717+ final Integer count = associationCounts .get (bindings );
4718+ if (count == null ) return ;
4719+ if (count > 1 ) associationCounts .put (bindings , count - 1 );
4720+ else {
4721+ associationCounts .remove (bindings );
4722+ bindings .clear ();
4723+ }
4724+ }
4725+
4726+ static final class Lease implements AutoCloseable {
4727+
4728+ private BindingsRegistry registry ;
4729+ private Bindings bindings ;
4730+
4731+ private Lease (final BindingsRegistry registry , final Bindings bindings ) {
4732+ this .registry = registry ;
4733+ this .bindings = bindings ;
4734+ }
4735+
4736+ @ Override
4737+ public synchronized void close () {
4738+ if (registry == null ) return ;
4739+ final BindingsRegistry owner = registry ;
4740+ final Bindings releasedBindings = bindings ;
4741+ registry = null ;
4742+ bindings = null ;
4743+ owner .release (releasedBindings );
4744+ }
4745+ }
4746+ }
4747+
4748+ private Bindings engineBindings (final ScriptModule module ) {
4749+ final ScriptEngine engine = module == null ? null : module .getEngine ();
4750+ return engine == null ? null : engine .getBindings (ScriptContext .ENGINE_SCOPE );
4751+ }
4752+
4753+ private synchronized void retainReplBindings (final Bindings bindings ) {
4754+ releaseReplBindings ();
4755+ if (!disposed ) replBindingsLease = BINDINGS_REGISTRY .retain (bindings );
4756+ }
4757+
4758+ private synchronized void releaseReplBindings () {
4759+ if (replBindingsLease == null ) return ;
4760+ replBindingsLease .close ();
4761+ replBindingsLease = null ;
4762+ }
4763+
4764+ private static void releaseBindingsWhenComplete (final Future <?> future ,
4765+ final BindingsRegistry .Lease lease )
4766+ {
4767+ final Thread cleanupThread = new Thread (() -> {
4768+ boolean interrupted = false ;
4769+ try {
4770+ while (true ) {
4771+ try {
4772+ future .get ();
4773+ return ;
4774+ }
4775+ catch (final InterruptedException e ) {
4776+ interrupted = true ;
4777+ }
4778+ catch (final ExecutionException | CancellationException e ) {
4779+ return ;
4780+ }
4781+ }
4782+ }
4783+ finally {
4784+ lease .close ();
4785+ if (interrupted ) Thread .currentThread ().interrupt ();
4786+ }
4787+ }, "script-editor-bindings-release" );
4788+ cleanupThread .setDaemon (true );
4789+ cleanupThread .start ();
4790+ }
4791+
46534792 private Reader evalScript (final String filename , Reader reader ,
46544793 final Writer output , final JTextAreaWriter errors ) throws ModuleException
46554794 {
46564795 final ScriptLanguage language = getCurrentLanguage ();
4796+ final boolean preserveState = incremental && !language .isCompiledLanguage ();
46574797
46584798 // If there's no engine or the language has changed or the language is compiled from a file
46594799 // then create the engine and module anew
@@ -4665,6 +4805,8 @@ private Reader evalScript(final String filename, Reader reader,
46654805 && this .scriptInfo .getLanguage ().getLanguageName ()
46664806 != getCurrentLanguage ().getLanguageName ()))
46674807 {
4808+ releaseReplBindings ();
4809+ this .moduleBindings = null ;
46684810 if (respectAutoImports ) {
46694811 reader =
46704812 DefaultAutoImporters .prefixAutoImports (context , language , reader ,
@@ -4678,6 +4820,8 @@ private Reader evalScript(final String filename, Reader reader,
46784820
46794821 this .module = this .scriptInfo .createModule ();
46804822 context .inject (this .module );
4823+ this .moduleBindings = engineBindings (this .module );
4824+ if (preserveState ) retainReplBindings (this .moduleBindings );
46814825 } else {
46824826 try {
46834827 // Same engine, with persistent state
@@ -4689,6 +4833,7 @@ private Reader evalScript(final String filename, Reader reader,
46894833
46904834 // map stdout and stderr to the UI
46914835 final ScriptModule runModule = this .module ;
4836+ final BindingsRegistry .Lease runBindingsLease = BINDINGS_REGISTRY .retain (moduleBindings );
46924837 runModule .setOutputWriter (output );
46934838 runModule .setErrorWriter (errors );
46944839
@@ -4698,8 +4843,10 @@ private Reader evalScript(final String filename, Reader reader,
46984843 getEditorPane ().getErrorHighlighter ().setWriter (errors );
46994844
47004845 // execute the script
4846+ Future <?> runFuture = null ;
47014847 try {
4702- moduleService .run (runModule , true ).get ();
4848+ runFuture = moduleService .run (runModule , true );
4849+ runFuture .get ();
47034850 }
47044851 catch (final InterruptedException e ) {
47054852 error ("Interrupted" );
@@ -4710,13 +4857,19 @@ private Reader evalScript(final String filename, Reader reader,
47104857 getEditorPane ().getErrorHighlighter ().parse (e );
47114858 } finally {
47124859 getEditorPane ().getErrorHighlighter ().parse ();
4860+ if (runFuture != null && !runFuture .isDone ()) {
4861+ releaseBindingsWhenComplete (runFuture , runBindingsLease );
4862+ }
4863+ else runBindingsLease .close ();
47134864 // A one-off run must not keep its module: it holds the script engine and thus every
47144865 // variable the script created (e.g., large images), even after this window is closed.
47154866 // Objects the script itself keeps alive (threads, listeners, displays) are not
47164867 // affected. In REPL mode the state is kept on purpose
4717- if (!incremental && this .module == runModule ) {
4868+ if ((!preserveState || disposed ) && this .module == runModule ) {
4869+ releaseReplBindings ();
47184870 this .module = null ;
47194871 this .scriptInfo = null ;
4872+ this .moduleBindings = null ;
47204873 }
47214874 }
47224875 return reader ;
@@ -4729,6 +4882,12 @@ public void setIncremental(final boolean incremental) {
47294882 return ;
47304883 }
47314884
4885+ if (!incremental && this .incremental ) {
4886+ releaseReplBindings ();
4887+ this .module = null ;
4888+ this .scriptInfo = null ;
4889+ this .moduleBindings = null ;
4890+ }
47324891 this .incremental = incremental ;
47334892
47344893 final JTextArea prompt = getTab ().getPrompt ();
0 commit comments