Skip to content

Commit d81e38d

Browse files
committed
Report run time and acknowledge completion when running scripts
1 parent edd19c7 commit d81e38d

1 file changed

Lines changed: 122 additions & 4 deletions

File tree

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

Lines changed: 122 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,7 @@
8181
import java.util.Arrays;
8282
import java.util.Collection;
8383
import java.util.Collections;
84+
import java.util.ConcurrentModificationException;
8485
import java.time.LocalDateTime;
8586
import java.time.format.DateTimeFormatter;
8687
import java.util.Date;
@@ -286,6 +287,9 @@ public class TextEditor extends JFrame implements ActionListener,
286287
private int sideLastLocation = -1;
287288
private final JMenu languageMenu;
288289
private JLabel statusText;
290+
private JLabel statusRun; // run timer: elapsed time of the running script
291+
private boolean headerWritten; // whether the last markCompileStart() wrote a "Started" line
292+
private final Timer runTimer = new Timer(1000, e -> refreshRunStatus());
289293
private JLabel statusVim;
290294
private final FileSystemTreePanel filesPanel;
291295
private final JCheckBoxMenuItem autoSave;
@@ -2206,6 +2210,13 @@ public Dimension getPreferredSize() { // fixed width: neighbors do not move as t
22062210
bar.add(statusVim);
22072211
bar.add(statusText);
22082212
bar.add(Box.createHorizontalGlue());
2213+
statusRun = new JLabel();
2214+
statusRun.setFont(statusText.getFont());
2215+
statusRun.setForeground(GuiUtils.secondaryColor());
2216+
statusRun.setToolTipText("Time elapsed since the running script started");
2217+
statusRun.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 8));
2218+
statusRun.setVisible(false);
2219+
bar.add(statusRun);
22092220
bar.addSeparator();
22102221
bar.add(Box.createHorizontalStrut(gap));
22112222
bar.add(statusVimToggle);
@@ -3321,6 +3332,7 @@ public void dispose() {
33213332
disposed = true;
33223333
layoutSaveTimer.stop();
33233334
titleTimer.stop();
3335+
runTimer.stop();
33243336
UIManager.removePropertyChangeListener(lookAndFeelListener);
33253337
tree.destroy();
33263338
if (dragSource != null) { // necessary to prevent memory leaks
@@ -3520,20 +3532,100 @@ public void setTitle(final String title) {
35203532

35213533
private final ArrayList<Executer> executingTasks = new ArrayList<>();
35223534

3535+
/**
3536+
* Called once when a task ends: writes the matching "Finished" (or "Stopped") line to the consoles
3537+
* of its tab, if the run had a "Started" line, and updates the run timer
3538+
*/
3539+
private void reportRun(final Executer task, final boolean stopped) {
3540+
if (!task.reported.compareAndSet(false, true)) return;
3541+
final long ms = (System.nanoTime() - task.startNanos) / 1_000_000;
3542+
final Date end = new Date(); // the lambda below runs a bit later
3543+
SwingUtilities.invokeLater(() -> {
3544+
// Failed: a caught exception, or what makes the error console pop up (see markCompileEnd())
3545+
final boolean failed = !stopped && (task.failed || (task.unverifiedLang == null
3546+
&& task.runParser.isLogDetailed()
3547+
&& errorScreen.getDocument().getLength() != task.startOffset));
3548+
final String note = (stopped || failed || task.unverifiedLang == null) ? ""
3549+
: " (success not verified for " + task.unverifiedLang + ")";
3550+
final String footer = (stopped ? "Stopped " + task.runName + " after "
3551+
: failed ? "Failed " + task.runName + " after " : "Finished " + task.runName + " in ")
3552+
+ formatElapsed(ms, false) + note + " at " + end + "\n";
3553+
if (task.marked) { // same layout as the header: the errors view gets it too, the combined view once
3554+
task.runTab.withoutMirroringErrors(() -> append(errorScreen, footer));
3555+
append(task.runTab.screen, footer);
3556+
}
3557+
refreshRunStatus();
3558+
});
3559+
}
3560+
3561+
/** Name of the language if its failures cannot be detected (see ErrorParser), null otherwise */
3562+
private static String unverifiedLanguage(final ScriptLanguage lang) {
3563+
if (lang == null) return null;
3564+
final String name = lang.getLanguageName();
3565+
if ("ImageJ Macro".equals(name) || "IJ1 Macro".equals(name) || "Scala".equals(name) || "R".equals(name))
3566+
return name;
3567+
return null;
3568+
}
3569+
3570+
/** Updates the run timer of the status bar. Invoke in the context of the event dispatch thread */
3571+
private void refreshRunStatus() {
3572+
if (statusRun == null) return;
3573+
final List<Executer> running;
3574+
try {
3575+
running = new ArrayList<>(executingTasks);
3576+
} catch (final ConcurrentModificationException ex) {
3577+
return; // the next tick will get it
3578+
}
3579+
String text = null;
3580+
if (running.isEmpty()) {
3581+
runTimer.stop();
3582+
} else {
3583+
runTimer.start(); // no-op if already running
3584+
final Executer newest = Collections.max(running, java.util.Comparator.comparingLong(x -> x.startNanos));
3585+
final long ms = (System.nanoTime() - newest.startNanos) / 1_000_000;
3586+
// short runs do not flash the label
3587+
if (ms >= 900) text = "Running " + formatElapsed(ms, true) + (running.size() > 1 ? " (+" + (running.size() - 1) + ")" : "");
3588+
}
3589+
statusRun.setText(text == null ? "" : text);
3590+
statusRun.setVisible(text != null);
3591+
}
3592+
3593+
/** Elapsed time as "3.4 s" (finished runs under a minute), "12 s", "2:05" or "1:02:05" */
3594+
private static String formatElapsed(final long ms, final boolean running) {
3595+
if (ms < 60_000) return running ? (ms / 1000) + " s" : String.format(java.util.Locale.ROOT, "%.1f s", ms / 1000d);
3596+
final long totalSeconds = ms / 1000;
3597+
final long h = totalSeconds / 3600, m = (totalSeconds % 3600) / 60, sec = totalSeconds % 60;
3598+
return h > 0 ? String.format(java.util.Locale.ROOT, "%d:%02d:%02d", h, m, sec)
3599+
: String.format(java.util.Locale.ROOT, "%d:%02d", m, sec);
3600+
}
3601+
35233602
/**
35243603
* Generic Thread that keeps a starting time stamp, sets the priority to
35253604
* normal and starts itself.
35263605
*/
35273606
public abstract class Executer extends ThreadGroup {
35283607

35293608
JTextAreaWriter output, errors;
3609+
private final long startNanos = System.nanoTime();
3610+
private final java.util.concurrent.atomic.AtomicBoolean reported = new java.util.concurrent.atomic.AtomicBoolean();
3611+
// What the "Finished" line needs, recorded when the run starts (the tab may change or close later)
3612+
private final boolean marked = headerWritten;
3613+
private final String runName = getEditorPane().getFileName();
3614+
private final TextEditorTab runTab = getTab();
3615+
private final ErrorParser runParser = getEditorPane().getErrorHighlighter();
3616+
// Languages whose errors we cannot detect: ErrorParser skips them (and macros report errors in a dialog)
3617+
private final String unverifiedLang = unverifiedLanguage(getCurrentLanguage());
3618+
private volatile boolean failed; // an exception or compile error was caught
3619+
// length of the error console once the header (written by markCompileStart) is in
3620+
private final int startOffset = errorScreen.getDocument().getLength();
35303621

35313622
Executer(final JTextAreaWriter output, final JTextAreaWriter errors) {
35323623
super("Script Editor Run :: " + new Date().toString());
35333624
this.output = output;
35343625
this.errors = errors;
35353626
// Store itself for later
35363627
executingTasks.add(this);
3628+
SwingUtilities.invokeLater(TextEditor.this::refreshRunStatus);
35373629
setTitle();
35383630
// Enable kill menu
35393631
kill.setEnabled(true);
@@ -3588,6 +3680,7 @@ public void run() {
35883680
catch (final Exception e) {
35893681
handleException(e);
35903682
}
3683+
reportRun(Executer.this, false); // after the writers flushed: the last line of the run
35913684
// Leave kill menu item enabled if other tasks are running
35923685
kill.setEnabled(!executingTasks.isEmpty());
35933686
setTitle();
@@ -3667,6 +3760,7 @@ void obliterate() {
36673760
}
36683761
}
36693762
executingTasks.remove(this);
3763+
reportRun(this, true);
36703764
// The wrapper thread may survive (no Thread.stop()): refresh the state it would have
36713765
SwingUtilities.invokeLater(() -> kill.setEnabled(!executingTasks.isEmpty()));
36723766
setTitle();
@@ -3691,7 +3785,7 @@ private void reportSurvivors() {
36913785
errorScreen.append("\n[Kill] " + names.size() + " thread(s) of " + script
36923786
+ " still running 1s after Kill: " + String.join(", ", names) + "\n");
36933787
showTemporaryStatus(names.size() + " thread(s) of " + script + " still running after Kill. "
3694-
+ "See Errors", 15000, Icons.error());
3788+
+ "See Errors", 15000, Icons.error(statusText));
36953789
});
36963790
timer.setRepeats(false);
36973791
timer.start();
@@ -3707,17 +3801,17 @@ static boolean isScriptOwnedThread(final Thread thread,
37073801
final ThreadGroup runGroup, final ThreadService threadService)
37083802
{
37093803
if (thread == null || runGroup == null) return false;
3710-
if (threadService == null) return isInThreadGroup(thread, runGroup);
3804+
if (threadService == null) return isInThreadGroup(thread, runGroup) && !isIdleDaemon(thread);
37113805

37123806
final ThreadService.ThreadContext threadContext;
37133807
try {
37143808
threadContext = threadService.getThreadContext(thread);
37153809
}
37163810
catch (final RuntimeException e) {
3717-
return isInThreadGroup(thread, runGroup);
3811+
return isInThreadGroup(thread, runGroup) && !isIdleDaemon(thread);
37183812
}
37193813
if (threadContext == null || threadContext == ThreadService.ThreadContext.NONE) {
3720-
return isInThreadGroup(thread, runGroup);
3814+
return isInThreadGroup(thread, runGroup) && !isIdleDaemon(thread);
37213815
}
37223816

37233817
final Set<Thread> seenParents = new HashSet<>();
@@ -3729,6 +3823,17 @@ static boolean isScriptOwnedThread(final Thread thread,
37293823
return isInThreadGroup(thread, runGroup) && !isIdleThreadServiceWorker(thread);
37303824
}
37313825

3826+
/**
3827+
* Some scripts may launch Daemon threads parked in a wait. E.g., This happens when using SNT to connect to
3828+
* remote databases which causes Okio Watchdog or OkHttp TaskRunner to linger 1-5 minutes after the HTTP request.
3829+
* These should be filtered and not hold the run.
3830+
*/
3831+
private static boolean isIdleDaemon(final Thread thread) {
3832+
if (!thread.isDaemon()) return false;
3833+
final Thread.State state = thread.getState();
3834+
return state == Thread.State.WAITING || state == Thread.State.TIMED_WAITING;
3835+
}
3836+
37323837
private static boolean isIdleThreadServiceWorker(final Thread thread) {
37333838
final Thread.State state = thread.getState();
37343839
if (state != Thread.State.WAITING && state != Thread.State.TIMED_WAITING) {
@@ -4105,6 +4210,7 @@ public void markCompileStart() {
41054210
}
41064211

41074212
public void markCompileStart(final boolean with_timestamp) {
4213+
headerWritten = with_timestamp; // the run that follows gets a matching "Finished" line
41084214
errorHandler = null;
41094215
// Errors flagged by a previous run are outdated
41104216
getEditorPane().getErrorHighlighter().reset();
@@ -4463,7 +4569,18 @@ void showHTMLDialog(final String title, final String htmlContents) {
44634569
GuiUtils.showHTMLDialog(this, title, htmlContents);
44644570
}
44654571

4572+
/** Flags the run (if any) that the calling thread belongs to as failed */
4573+
private void flagFailedRun() {
4574+
for (ThreadGroup g = Thread.currentThread().getThreadGroup(); g != null; g = g.getParent()) {
4575+
if (g instanceof Executer) {
4576+
((Executer) g).failed = true;
4577+
return;
4578+
}
4579+
}
4580+
}
4581+
44664582
public void handleException(final Throwable e) {
4583+
flagFailedRun();
44674584
handleException(e, errorScreen);
44684585
getEditorPane().getErrorHighlighter().parse(e);
44694586
getTab().showErrors();
@@ -4589,6 +4706,7 @@ private Reader evalScript(final String filename, Reader reader,
45894706
}
45904707
catch (final ExecutionException e) {
45914708
log.error(e);
4709+
flagFailedRun();
45924710
getEditorPane().getErrorHighlighter().parse(e);
45934711
} finally {
45944712
getEditorPane().getErrorHighlighter().parse();

0 commit comments

Comments
 (0)