Skip to content

Commit 5c62ee1

Browse files
hinermCopilot GPT-6 Luna
andcommitted
Release script bindings when editor sessions end
Track bindings used by script runs and REPL sessions, clearing them after the final association is released. Use the ScriptModule's engine so cleanup targets the bindings used during execution. Closes #79 Co-authored-by: Copilot GPT-6 Luna <copilot@github.com>
1 parent 9caaf57 commit 5c62ee1

2 files changed

Lines changed: 198 additions & 11 deletions

File tree

‎src/main/java/org/scijava/ui/swing/script/TextEditor.java‎

Lines changed: 170 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,16 @@
2929

3030
package 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;
3342
import java.awt.datatransfer.DataFlavor;
3443
import java.awt.datatransfer.Transferable;
3544
import java.awt.datatransfer.UnsupportedFlavorException;
@@ -77,38 +86,71 @@
7786
import java.nio.file.Paths;
7887
import java.nio.file.StandardCopyOption;
7988
import java.nio.file.StandardOpenOption;
89+
import java.time.LocalDateTime;
90+
import java.time.format.DateTimeFormatter;
8091
import java.util.ArrayList;
8192
import java.util.Arrays;
8293
import java.util.Collection;
8394
import java.util.Collections;
8495
import java.util.ConcurrentModificationException;
85-
import java.time.LocalDateTime;
86-
import java.time.format.DateTimeFormatter;
8796
import java.util.Date;
8897
import java.util.Enumeration;
8998
import java.util.HashMap;
9099
import java.util.HashSet;
91-
import java.util.LinkedHashSet;
100+
import java.util.IdentityHashMap;
92101
import java.util.LinkedHashMap;
102+
import java.util.LinkedHashSet;
93103
import java.util.List;
94-
import java.util.concurrent.CopyOnWriteArrayList;
95104
import java.util.Map;
96105
import java.util.Objects;
97106
import java.util.Set;
98-
import java.util.function.BiConsumer;
99-
import java.util.function.IntPredicate;
100107
import java.util.TreeMap;
101108
import java.util.Vector;
109+
import java.util.concurrent.CancellationException;
110+
import java.util.concurrent.CopyOnWriteArrayList;
102111
import java.util.concurrent.ExecutionException;
112+
import java.util.concurrent.Future;
113+
import java.util.function.BiConsumer;
114+
import java.util.function.IntPredicate;
103115
import java.util.jar.JarEntry;
104116
import java.util.jar.JarOutputStream;
105117
import java.util.regex.Matcher;
106118
import java.util.regex.Pattern;
107119
import java.util.zip.ZipException;
108120

121+
import javax.script.Bindings;
122+
import javax.script.ScriptContext;
109123
import javax.script.ScriptEngine;
110124
import 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;
112154
import javax.swing.event.ChangeEvent;
113155
import javax.swing.event.ChangeListener;
114156
import javax.swing.event.DocumentEvent;
@@ -125,9 +167,9 @@
125167
import org.fife.ui.rsyntaxtextarea.RSyntaxDocument;
126168
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
127169
import org.fife.ui.rsyntaxtextarea.Theme;
170+
import org.fife.ui.rsyntaxtextarea.TokenMakerFactory;
128171
import org.fife.ui.rsyntaxtextarea.parser.ParserNotice;
129172
import org.fife.ui.rsyntaxtextarea.parser.TaskTagParser;
130-
import org.fife.ui.rsyntaxtextarea.TokenMakerFactory;
131173
import org.fife.ui.rtextarea.ClipboardHistory;
132174
import org.fife.ui.rtextarea.Macro;
133175
import 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();

‎src/test/java/org/scijava/ui/swing/script/TextEditorThreadOwnershipTest.java‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,17 +29,22 @@
2929
package org.scijava.ui.swing.script;
3030

3131
import static org.junit.Assert.assertFalse;
32+
import static org.junit.Assert.assertEquals;
3233
import static org.junit.Assert.assertNotNull;
3334
import static org.junit.Assert.assertNull;
3435
import static org.junit.Assert.assertSame;
3536
import static org.junit.Assert.assertTrue;
3637

3738
import java.lang.reflect.Modifier;
39+
import java.util.HashMap;
3840
import java.util.concurrent.CountDownLatch;
3941
import java.util.concurrent.Future;
4042
import java.util.concurrent.TimeUnit;
4143
import java.util.concurrent.atomic.AtomicReference;
4244

45+
import javax.script.Bindings;
46+
import javax.script.SimpleBindings;
47+
4348
import org.junit.After;
4449
import org.junit.Before;
4550
import org.junit.Test;
@@ -68,6 +73,29 @@ public void testTitleSetterDoesNotSynchronizeOnEditor() throws Exception {
6873
String.class).getModifiers()));
6974
}
7075

76+
@Test
77+
public void testBindingsAreClearedAfterLastAssociation() {
78+
final TextEditor.BindingsRegistry registry = new TextEditor.BindingsRegistry();
79+
final Object image = new Object();
80+
final Bindings first = new SimpleBindings();
81+
first.put("image", image);
82+
final Bindings second = new SimpleBindings();
83+
second.put("image", image);
84+
assertEquals(new HashMap<>(first), new HashMap<>(second));
85+
86+
final TextEditor.BindingsRegistry.Lease firstLease = registry.retain(first);
87+
final TextEditor.BindingsRegistry.Lease secondLease = registry.retain(first);
88+
final TextEditor.BindingsRegistry.Lease distinctLease = registry.retain(second);
89+
90+
firstLease.close();
91+
assertSame(image, first.get("image"));
92+
secondLease.close();
93+
assertTrue(first.isEmpty());
94+
assertSame(image, second.get("image"));
95+
distinctLease.close();
96+
assertTrue(second.isEmpty());
97+
}
98+
7199
@Test
72100
public void testOrdinaryChildThreadBelongsToRun() {
73101
final ThreadGroup runGroup = new ThreadGroup("script-run");

0 commit comments

Comments
 (0)