From b6430cf526bbc703d063daddac0c2eb742aaad57 Mon Sep 17 00:00:00 2001 From: Tiago Ferreira Date: Mon, 16 Nov 2026 15:02:00 -0500 Subject: [PATCH 1/3] Minor additions/tweaks - Zen mode :) - Option to copy file path - Option to reveal script path in the files tab - Option to export console output - Improve rendering consistency of pane headers - Fix scaling of error/help icons - Improve rendering consistency of toggle buttons - Do not use hard-coded colors - Fix not possible to create new empty documents (Pressing Ctrl/Cmd + multiple times did nothing) --- .../ui/swing/script/FileSystemTree.java | 27 +++ .../ui/swing/script/FileSystemTreePanel.java | 23 +-- .../org/scijava/ui/swing/script/GuiUtils.java | 122 +++++++---- .../org/scijava/ui/swing/script/Icons.java | 23 ++- .../scijava/ui/swing/script/NotesPanel.java | 17 +- .../scijava/ui/swing/script/TextEditor.java | 193 ++++++++++++++---- .../ui/swing/script/TextEditorTab.java | 13 +- 7 files changed, 299 insertions(+), 119 deletions(-) diff --git a/src/main/java/org/scijava/ui/swing/script/FileSystemTree.java b/src/main/java/org/scijava/ui/swing/script/FileSystemTree.java index 9097bbae..a6a6b642 100644 --- a/src/main/java/org/scijava/ui/swing/script/FileSystemTree.java +++ b/src/main/java/org/scijava/ui/swing/script/FileSystemTree.java @@ -872,6 +872,33 @@ private void addRoot(final String dir, final boolean checkIfChild) { getModel().insertNodeInto(new Node(dirPath), root, root.getChildCount()); } + /** + * Selects and scrolls to the given file or folder, expanding the tree as needed. If it is not under any + * top-level folder, its parent folder is added as one. + * + * @return true if the file itself was found (false: only its folder, if any, was revealed) + */ + public boolean reveal(final File file) { + if (file == null) return false; + restoreHiddenTops(); + final String target = withSlash(file.getAbsolutePath()); + for (int attempt = 0; attempt < 2; attempt++) { + final Node root = root(); + for (int i = 0; i < root.getChildCount(); i++) { + final TreePath path = pathTo(root.getChildAt(i), target); + if (path != null) { + expandPath(path.getParentPath()); + setSelectionPath(path); + scrollPathToVisible(path); + return true; + } + } + final File dir = file.isDirectory() ? file : file.getParentFile(); + if (attempt == 0 && dir != null) addRoot(dir.getAbsolutePath(), true); + } + return false; // e.g., hidden by the filter: the folder was revealed by addRoot() + } + /** Expands nodes downwards until reaching dirPath. Returns null if not found */ private TreePath pathTo(Node node, final String dirPath) { while (dirPath.startsWith(node.path)) { diff --git a/src/main/java/org/scijava/ui/swing/script/FileSystemTreePanel.java b/src/main/java/org/scijava/ui/swing/script/FileSystemTreePanel.java index a4cc236d..cb282ac6 100644 --- a/src/main/java/org/scijava/ui/swing/script/FileSystemTreePanel.java +++ b/src/main/java/org/scijava/ui/swing/script/FileSystemTreePanel.java @@ -104,15 +104,17 @@ class FileSystemTreePanel extends JPanel { bc.fill = GridBagConstraints.BOTH; bc.weightx = 1; bc.weighty = 0; - add(searchField, bc); + add(GuiUtils.getHeader("Files", this::showHelpMsg), bc); bc.gridy = 1; + add(searchField, bc); + bc.gridy = 2; bc.weightx = 1.0; bc.weighty = 1.0; bc.fill = GridBagConstraints.BOTH; final JScrollPane treePane = new JScrollPane(tree); GuiUtils.flattenScrollBars(treePane); add(treePane, bc); - bc.gridy = 2; + bc.gridy = 3; bc.weightx = 0; bc.weighty = 0; add(statusToolbar(), bc); @@ -171,18 +173,9 @@ private JToolBar statusToolbar() { toolbar.setBackground(tree.getBackground()); // Continue the outline of the tree's scroll pane (the latter provides the top edge) toolbar.setBorder(BorderFactory.createCompoundBorder(new SideBorder(), toolbar.getBorder())); - final JToggleButton statusFast = new JToggleButton("Fast Mode"); - statusFast.putClientProperty(FlatClientProperties.STYLE_CLASS, "small"); - statusFast.setForeground(GuiUtils.secondaryColor()); + final JToggleButton statusFast = GuiUtils.smallToggleButton("Fast Mode"); statusFast.setToolTipText("Fast mode for large folders: turns off live updates and the search of collapsed folders"); - statusFast.addActionListener(e -> { - final boolean selected = statusFast.isSelected(); - setFastMode(selected); - final Color fGrnd = (selected) ? UIManager.getColor("Tree.selectionForeground") : GuiUtils.secondaryColor(); - final Color bGrnd = (selected) ? UIManager.getColor("Tree.selectionBackground") : toolbar.getBackground(); - if (fGrnd!=null) statusFast.setForeground(fGrnd); - if (bGrnd!=null) statusFast.setBackground(bGrnd); - }); + statusFast.addActionListener(e -> setFastMode(statusFast.isSelected())); final JButton statusOptions = new JButton("Options"); final FlatFileChooserDetailsViewIcon optionsIcon = new FlatFileChooserDetailsViewIcon(); optionsIcon.setScale(.8f); // matches the font size set by the "small" style @@ -193,10 +186,6 @@ private JToolBar statusToolbar() { toolbar.add(statusFast); toolbar.addSeparator(); toolbar.add(statusOptions); - toolbar.add(Box.createHorizontalGlue()); - final JButton statusHelp = GuiUtils.helpButton(null); - statusHelp.addActionListener(e -> showHelpMsg()); - toolbar.add(statusHelp); return toolbar; } diff --git a/src/main/java/org/scijava/ui/swing/script/GuiUtils.java b/src/main/java/org/scijava/ui/swing/script/GuiUtils.java index 76d627af..9e1b0619 100644 --- a/src/main/java/org/scijava/ui/swing/script/GuiUtils.java +++ b/src/main/java/org/scijava/ui/swing/script/GuiUtils.java @@ -29,15 +29,7 @@ package org.scijava.ui.swing.script; -import java.awt.Color; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.RenderingHints; -import java.awt.Insets; -import java.awt.Graphics2D; -import java.awt.Graphics; -import java.awt.FontMetrics; -import java.awt.Point; +import java.awt.*; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; @@ -474,7 +466,7 @@ static Color accentColor() { try { Color c = UIManager.getColor("Component.accentColor"); if (c == null) c = UIManager.getColor("Component.focusColor"); - return (c == null) ? new Color(0x3E73B9) : new Color(c.getRGB()); // plain color: UIResource ones are reset + return (c == null) ? new Color(0x3E73B9) : new Color(c.getRGB()); // plain color: UIResource ones are reset!? } catch (final Exception ignored) { // do nothing } @@ -490,13 +482,43 @@ static boolean isDark(final Color c) { return (c.getRed() * 0.299 + c.getGreen() * 0.587 + c.getBlue() * 0.114) < 186; } - /** Small "+" button for the trailing area of a tabbed pane */ - static JButton newTabButton(final Runnable action) { - final JButton b = new JButton("+"); - b.setToolTipText("New file"); - b.setFocusable(false); - b.putClientProperty(FlatClientProperties.BUTTON_TYPE, FlatClientProperties.BUTTON_TYPE_TOOLBAR_BUTTON); - b.addActionListener(e -> action.run()); + /** Small toggle button that looks like a tree selection when selected */ + static JToggleButton smallToggleButton(final String text) { + return smallToggleButton(text, null); + } + + /** + * As {@link #smallToggleButton(String)}. + * + * @param extraStyle Optional. FlatLaf style properties to add to the ones set here. NB: Setting the + * style property of the button later would replace them + */ + static JToggleButton smallToggleButton(final String text, final String extraStyle) { + return smallToggleButton(text, extraStyle, true); + } + + /** + * As {@link #smallToggleButton(String, String)}. + * + * @param secondary If true, the text of the unselected button is in secondary color. If false, in + * the default (primary) color of buttons + */ + static JToggleButton smallToggleButton(final String text, final String extraStyle, final boolean secondary) { + final JToggleButton b = new JToggleButton(text); + b.putClientProperty(FlatClientProperties.STYLE_CLASS, "small"); + // NB: setBackground() would not do, as FlatLaf darkens it + b.putClientProperty(FlatClientProperties.STYLE, + "selectedBackground: $Tree.selectionBackground; toolbar.selectedBackground: $Tree.selectionBackground" + + (extraStyle == null || extraStyle.isEmpty() ? "" : "; " + extraStyle)); + // NB: Foregrounds must be set after the style: applying it resets them + final Runnable updateForeground = () -> { + final Color sel = UIManager.getColor("Tree.selectionForeground"); + final Color rest = secondary ? secondaryColor() : UIManager.getColor("Button.foreground"); + final Color fGrnd = (b.isSelected() && sel != null) ? sel : rest; + if (fGrnd != null) b.setForeground(fGrnd); + }; + updateForeground.run(); + b.addItemListener(e -> updateForeground.run()); return b; } @@ -505,27 +527,27 @@ static JButton ellipsisButton(final Runnable action) { b.setFocusable(false); b.putClientProperty(FlatClientProperties.BUTTON_TYPE, FlatClientProperties.BUTTON_TYPE_TOOLBAR_BUTTON); if (action != null) b.addActionListener(e -> action.run()); - b.setForeground(secondaryColor()); // the icon follows the foreground. Set last: style updates reset UI foregrounds + // NBL he icon follows the foreground. To change its caller setForground() needs to be Set last return b; } - - /** Small round "?" button, in the style of the editor's other help buttons */ - static JButton helpButton(final Runnable action) { - return helpButton(action, .75f, true); - } - - private static JButton helpButton(final Runnable action, final float scale, final boolean borderless) { + /** + * Round help "?" button + * + * @param sizeToComponent Optional. If not null, the icon will be scaled to height of this component. + */ + static JButton helpButton(final Runnable action, final Component sizeToComponent) { final FlatHelpButtonIcon icon = new FlatHelpButtonIcon(); - icon.setScale(scale); icon.applyStyleProperty("questionMarkColor", secondaryColor()); icon.applyStyleProperty("background", UIManager.getColor("Panel.background")); final JButton b = new JButton(icon); b.setFocusable(false); b.putClientProperty(FlatClientProperties.BUTTON_TYPE, FlatClientProperties.BUTTON_TYPE_TOOLBAR_BUTTON); - if (borderless) { - b.putClientProperty("JButton.buttonType", "borderless"); + if (sizeToComponent != null) { + b.setMargin(null); b.setBorder(null); + b.putClientProperty("JButton.buttonType", "borderless"); // probably not needed? + icon.setScale(Icons.scaleToFont(icon, sizeToComponent)); } if (action != null) b.addActionListener(e -> action.run()); return b; @@ -581,15 +603,7 @@ static void installSplitHandle(final JComponent handle, final JSplitPane split) split.setDividerSize(active ? 0 : regularSize); handle.setCursor(active ? java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.N_RESIZE_CURSOR) : null); }; - // children must not inherit the resize cursor - final java.util.function.Consumer[] resetCursors = new java.util.function.Consumer[1]; - resetCursors[0] = parent -> { - for (final java.awt.Component child : parent.getComponents()) { - if (!child.isCursorSet()) child.setCursor(java.awt.Cursor.getDefaultCursor()); - if (child instanceof java.awt.Container) resetCursors[0].accept((java.awt.Container) child); - } - }; - resetCursors[0].accept(handle); + defaultCursorForInteractive(handle); update.run(); split.addPropertyChangeListener(JSplitPane.ORIENTATION_PROPERTY, evt -> update.run()); final int[] grab = new int[1]; @@ -611,6 +625,20 @@ public void mouseDragged(final java.awt.event.MouseEvent e) { }); } + /** + * Components that handle mouse events themselves must not inherit the resize cursor of a + * split handle. Labels, glue and gaps do (they move the split) + */ + private static void defaultCursorForInteractive(final java.awt.Container parent) { + for (final java.awt.Component child : parent.getComponents()) { + final boolean interactive = child instanceof AbstractButton + || child instanceof javax.swing.text.JTextComponent || child instanceof JComboBox + || child instanceof JSpinner || child instanceof JList || child instanceof JSlider; + if (interactive && !child.isCursorSet()) child.setCursor(java.awt.Cursor.getDefaultCursor()); + if (child instanceof java.awt.Container) defaultCursorForInteractive((java.awt.Container) child); + } + } + static void collapseAllTreeNodes(final JTree tree) { final int row1 = (tree.isRootVisible()) ? 1 : 0; for (int i = row1; i < tree.getRowCount(); i++) @@ -631,6 +659,8 @@ static JTabbedPane getJTabbedPane() { static JTabbedPane getJTabbedPane(final int initialPlacement) { final JTabbedPane tabbed = new JTabbedPane(); tabbed.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT); + tabbed.putClientProperty(FlatClientProperties.TABBED_PANE_TAB_AREA_ALIGNMENT, + FlatClientProperties.TABBED_PANE_ALIGN_LEADING); tabbed.putClientProperty(FlatClientProperties.TABBED_PANE_TABS_POPUP_POLICY, "asNeeded"); // overflow dropdown tabbed.putClientProperty(FlatClientProperties.TABBED_PANE_SCROLL_BUTTONS_POLICY, "never"); // do not show arrows tabbed.putClientProperty(FlatClientProperties.TABBED_PANE_TAB_ROTATION, @@ -693,6 +723,24 @@ static JTabbedPane getJTabbedPane(final int initialPlacement) { return tabbed; } + /** + * Assembles a secondary pane heading + * @param text the header text + * @param help optional An action to be attached to an option help button to the right of the heading + * @return a small header in secondary color + */ + static JComponent getHeader(final String text, final Runnable help) { + final JLabel label = new JLabel(text); + label.putClientProperty(FlatClientProperties.STYLE_CLASS, "small"); + label.setForeground(GuiUtils.secondaryColor()); + final JPanel panel = new JPanel(new BorderLayout()); + panel.setBorder(BorderFactory.createEmptyBorder(0, 2, 0, 0)); + panel.setOpaque(false); + panel.add(label, BorderLayout.CENTER); + if (help != null) panel.add(helpButton(help, label), BorderLayout.EAST); + return panel; + } + private static String placementName(final int placement) { switch (placement) { case JTabbedPane.LEFT: return "Left"; diff --git a/src/main/java/org/scijava/ui/swing/script/Icons.java b/src/main/java/org/scijava/ui/swing/script/Icons.java index 327f4026..d4798eba 100644 --- a/src/main/java/org/scijava/ui/swing/script/Icons.java +++ b/src/main/java/org/scijava/ui/swing/script/Icons.java @@ -77,11 +77,22 @@ static Icon ellipsisVertical() { return new GlyphIcon(ELLIPSIS_VERTICAL, null, null, false, 0, 0, 640, 640, 18); } - /** Small error icon for status messages */ - static Icon error() { - final FlatAbstractIcon icon = new FlatOptionPaneErrorIcon(); - icon.setScale(.35f); - return icon; + /** + * Error icon + * @param sizeToComponent Optional. If not null, the icon will be scaled to height of this component. + */ + static Icon error(final Component sizeToComponent) { + final FlatAbstractIcon errorIcon = new FlatOptionPaneErrorIcon(); + if (sizeToComponent != null) + errorIcon.setScale(scaleToFont(errorIcon, sizeToComponent)); + return errorIcon; + } + + /** Scale that makes the icon as tall as the text of the given component */ + static float scaleToFont(final FlatAbstractIcon icon, final Component ref) { + assert(icon != null && ref != null); + final FontMetrics fm = ref.getFontMetrics(ref.getFont()); + return fm.getHeight() / (float) icon.getIconHeight(); // icon created at scale 1 } /** Folder icon for the Files side tab (follows the component foreground) */ @@ -137,7 +148,7 @@ static Icon stop(final boolean disabled) { static Icon trash(final boolean disabled) { return new GlyphIcon( "M232.7 69.9C237.1 56.8 249.3 48 263.1 48L377 48C390.8 48 403 56.8 407.4 69.9L416 96L512 96C529.7 96 544 110.3 544 128C544 145.7 529.7 160 512 160L128 160C110.3 160 96 145.7 96 128C96 110.3 110.3 96 128 96L224 96L232.7 69.9zM128 208L512 208L512 512C512 547.3 483.3 576 448 576L192 576C156.7 576 128 547.3 128 512L128 208zM216 272C202.7 272 192 282.7 192 296L192 488C192 501.3 202.7 512 216 512C229.3 512 240 501.3 240 488L240 296C240 282.7 229.3 272 216 272zM320 272C306.7 272 296 282.7 296 296L296 488C296 501.3 306.7 512 320 512C333.3 512 344 501.3 344 488L344 296C344 282.7 333.3 272 320 272zM424 272C410.7 272 400 282.7 400 296L400 488C400 501.3 410.7 512 424 512C437.3 512 448 501.3 448 488L448 296C448 282.7 437.3 272 424 272z", - new Color(0x6E6E6E), new Color(0xA9A9A9), disabled); + null, null, disabled); } /** diff --git a/src/main/java/org/scijava/ui/swing/script/NotesPanel.java b/src/main/java/org/scijava/ui/swing/script/NotesPanel.java index d0ae9512..19fe2e9c 100644 --- a/src/main/java/org/scijava/ui/swing/script/NotesPanel.java +++ b/src/main/java/org/scijava/ui/swing/script/NotesPanel.java @@ -46,7 +46,6 @@ import javax.swing.event.DocumentListener; import javax.swing.text.JTextComponent; -import com.formdev.flatlaf.FlatClientProperties; import org.fife.ui.rtextarea.ClipboardHistory; import org.scijava.prefs.PrefService; @@ -109,8 +108,8 @@ protected void paintComponent(final java.awt.Graphics g) { @Override protected void paintComponent(final java.awt.Graphics g) { super.paintComponent(g); - if (getDocument().getLength() == 0) GuiUtils.paintEmptyHint(g, this, "Jot down snippets", - "They are saved between sessions"); + if (getDocument().getLength() == 0) GuiUtils.paintEmptyHint(g, this, "Jot down notes or snippets", + "Saved between sessions"); } }; scratch.setLineWrap(prefs.getBoolean(prefsOwner, PREFS_WRAP, true)); @@ -121,7 +120,7 @@ protected void paintComponent(final java.awt.Graphics g) { // Scratchpad final JPanel pane1 = new JPanel(new BorderLayout()); - final JLabel scratchHeader = header("Scratchpad"); + final JComponent scratchHeader = GuiUtils.getHeader("Scratchpad", null); pane1.add(scratchHeader, BorderLayout.NORTH); pane1.add(scratchPane, BorderLayout.CENTER); @@ -131,7 +130,7 @@ protected void paintComponent(final java.awt.Graphics g) { final JScrollPane listPane = new JScrollPane(list); GuiUtils.flattenScrollBars(listPane); final JPanel pane2 = new JPanel(new BorderLayout()); - final JLabel clipboardHeader = header("Clipboard History"); + final JComponent clipboardHeader = GuiUtils.getHeader("Clipboard History", null); pane2.add(clipboardHeader, BorderLayout.NORTH); pane2.add(listPane, BorderLayout.CENTER); @@ -281,14 +280,6 @@ void refresh() { list.setSelectedValue(selected, true); } - private JLabel header(final String text) { - final JLabel label = new JLabel(text); - label.setBorder(BorderFactory.createEmptyBorder(2, 2,0,0)); - label.putClientProperty(FlatClientProperties.STYLE_CLASS, "small"); - label.setForeground(GuiUtils.secondaryColor()); - return label; - } - private void maybePopup(final MouseEvent e) { if (!e.isPopupTrigger()) return; final int idx = list.locationToIndex(e.getPoint()); diff --git a/src/main/java/org/scijava/ui/swing/script/TextEditor.java b/src/main/java/org/scijava/ui/swing/script/TextEditor.java index fadbfa06..95305818 100644 --- a/src/main/java/org/scijava/ui/swing/script/TextEditor.java +++ b/src/main/java/org/scijava/ui/swing/script/TextEditor.java @@ -71,7 +71,6 @@ import java.io.StringReader; import java.io.Writer; import java.net.URL; -import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; @@ -303,6 +302,11 @@ public class TextEditor extends JFrame implements ActionListener, /** Share of the window given to the side panel by default */ private static final double SIDE_SHARE = .20d; private JCheckBoxMenuItem vimMode; + // Zen mode: what was visible before (null if not active) + private java.util.Map zenConsoles; + private boolean zenSide; + private boolean zenBusy; // true while Zen mode itself is changing the panes + private final JCheckBoxMenuItem zenItem; private JCheckBoxMenuItem sidePaneItem, consoleItem; // Window menu: kept in sync with the status bar private boolean syncingPanes; private boolean disposed; // see dispose() @@ -398,8 +402,6 @@ public TextEditor(final Context context) { // NB: All panes must be initialized before menus are assembled! tabbed = GuiUtils.getJTabbedPane(); - tabbed.putClientProperty(FlatClientProperties.TABBED_PANE_TAB_AREA_ALIGNMENT, - FlatClientProperties.TABBED_PANE_ALIGN_LEADING); tabbed.putClientProperty(FlatClientProperties.TABBED_PANE_TAB_CLOSABLE, true); tabbed.putClientProperty(FlatClientProperties.TABBED_PANE_TAB_CLOSE_TOOLTIPTEXT, "Close"); tabbed.putClientProperty(FlatClientProperties.TABBED_PANE_TAB_CLOSE_CALLBACK, @@ -411,8 +413,6 @@ public TextEditor(final Context context) { tree = new FileSystemTree(log); sideTabs = GuiUtils.getJTabbedPane(JTabbedPane.LEFT); - sideTabs.putClientProperty(FlatClientProperties.TABBED_PANE_TAB_AREA_ALIGNMENT, - FlatClientProperties.TABBED_PANE_ALIGN_FILL); // Icon-only tabs: only the selected tab shows its title, keeping the pane narrow sideTabs.putClientProperty(FlatClientProperties.TABBED_PANE_TAB_WIDTH_MODE, FlatClientProperties.TABBED_PANE_TAB_WIDTH_MODE_COMPACT); @@ -432,18 +432,17 @@ public TextEditor(final Context context) { // Outline final JPanel pane1 = new JPanel(new BorderLayout()); - final JLabel outlineHeader = header("Structure"); - pane1.add(outlineHeader, BorderLayout.NORTH); + pane1.add(GuiUtils.getHeader("Structure", null), BorderLayout.NORTH); pane1.add(sourceTreePanel, BorderLayout.CENTER); addSideTab("Outline", Icons.outline(), pane1); // Markers: bookmarks and tasks of all open tabs final JPanel pane2 = new JPanel(new BorderLayout()); - pane2.add(header("Bookmarks", this::showBookmarksHelp), BorderLayout.NORTH); + pane2.add(GuiUtils.getHeader("Bookmarks", this::showBookmarksHelp), BorderLayout.NORTH); pane2.add(bookmarksPanel, BorderLayout.CENTER); final JPanel pane3 = new JPanel(new BorderLayout()); - final JComponent tasksHeader = header("Tasks", this::showTasksHelp); + final JComponent tasksHeader = GuiUtils.getHeader("Tasks", this::showTasksHelp); pane3.add(tasksHeader, BorderLayout.NORTH); pane3.add(tasksPanel, BorderLayout.CENTER); markersSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT, pane2, pane3); @@ -719,9 +718,21 @@ public TextEditor(final Context context) { final JCheckBoxMenuItem jcmi2 = consoleItem = new JCheckBoxMenuItem("Console", prefService.getInt(getClass(), TAB_DIV_LOCATION, 1) > 0); jcmi2.addItemListener(e -> { - if (!syncingPanes) getTab().setBottomVisible(jcmi2.isSelected()); + if (syncingPanes) return; + if (jcmi2.isSelected()) endZenMode(); + getTab().setBottomVisible(jcmi2.isSelected()); }); tabsMenu.add(jcmi2); + zenItem = new JCheckBoxMenuItem("Zen Mode"); + zenItem.setToolTipText("Hides the side pane and the console, restoring them when turned off"); + zenItem.addItemListener(e -> { + if (!syncingPanes) setZenMode(zenItem.isSelected()); + }); + tabsMenu.add(zenItem); + // Tabs shown (or created) while in Zen mode get the same treatment + tabbed.addChangeListener(e -> { + if (zenConsoles != null) SwingUtilities.invokeLater(this::zenHideNewTabs); + }); final JMenuItem mi = new JMenuItem("Reset Layout..."); mi.addActionListener(e -> { if (confirm("Reset Location of Console and Files pane?", "Reset Layout?", "Reset")) { @@ -1000,6 +1011,8 @@ public void componentResized(final ComponentEvent e) { private void resetLayout() { body.setDividerLocation(SIDE_SHARE); getTab().resetLayout(); + // pack() honors the preferred size, which holds the last saved window size + setPreferredSize(new Dimension(DEFAULT_WINDOW_WIDTH, DEFAULT_WINDOW_HEIGHT)); pack(); } @@ -1008,26 +1021,6 @@ private void addSideTab(final String title, final Icon icon, final Component c) sideTabs.setToolTipTextAt(sideTabs.getTabCount() - 1, title); } - private JLabel header(final String text) { - final JLabel label = new JLabel(text); - label.setBorder(BorderFactory.createEmptyBorder(2, 2,0,0)); - label.putClientProperty(FlatClientProperties.STYLE_CLASS, "small"); - label.setForeground(GuiUtils.secondaryColor()); - return label; - } - - /** A header with a help button on its right, which is also a split handle */ - private JComponent header(final String text, final Runnable help) { - final JLabel label = header(text); - // installSplitHandle() leaves explicitly set cursors of children alone - label.setCursor(Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR)); - final JPanel panel = new JPanel(new BorderLayout()); - panel.setOpaque(false); - panel.add(label, BorderLayout.CENTER); - panel.add(GuiUtils.helpButton(help), BorderLayout.EAST); - return panel; - } - private static String tagHtml(final String tag) { return String.format("%s", TasksPanel.tagColor(tag).getRGB() & 0xFFFFFF, tag); } @@ -1514,10 +1507,11 @@ public void saveWindowSizeToPrefs() { prefService.put(getClass(), WINDOW_HEIGHT, dim.height); prefService.put(getClass(), WINDOW_WIDTH, dim.width); - prefService.put(getClass(), MAIN_DIV_LOCATION, body.getDividerLocation()); - final TextEditorTab tab = getTab(); - prefService.put(getClass(), TAB_DIV_LOCATION, tab.getDividerLocation()); + if (zenConsoles == null) { // in Zen mode the panes are hidden only temporarily + prefService.put(getClass(), MAIN_DIV_LOCATION, body.getDividerLocation()); + prefService.put(getClass(), TAB_DIV_LOCATION, tab.getDividerLocation()); + } prefService.put(getClass(), TAB_DIV_ORIENTATION, tab.getOrientation()); prefService.put(getClass(), REPL_DIV_LOCATION, tab.getScreenAndPromptSplit().getDividerLocation()); } @@ -1826,7 +1820,7 @@ public void loadTemplate(final URL url) { } public void loadTemplate(final URL url, final ScriptLanguage language) { - createNewDocument(); + open(null); // reuses an empty new document in front: the template fills it try { // Load the template. NB: setText() keeps the document (and its @@ -1851,8 +1845,9 @@ public void loadTemplate(final URL url, final ScriptLanguage language) { } } + /** Opens a new tab, even if the one in front is an empty new document */ public void createNewDocument() { - open(null); + open(null, false); } public void createNewDocument(final String title, final String text) { @@ -2161,6 +2156,7 @@ public Dimension getPreferredSize() { // fixed width: neighbors do not move as t body.addPropertyChangeListener("dividerLocation", evt -> { final int loc = body.getDividerLocation(); if (loc > 50 && !body.isSettling()) sideLastLocation = loc; + if (loc > 5) endZenMode(); statusSide.setSelected(loc > 5); syncPaneItems(loc > 5, null); }); @@ -2194,8 +2190,7 @@ public Dimension getPreferredSize() { // fixed width: neighbors do not move as t getTab().setREPLEnabled(statusRepl.isSelected()); syncStatusBar(); // e.g., no language: the request was refused }); - statusVimToggle = new JToggleButton("Vim"); - statusVimToggle.setFont(statusVimToggle.getFont().deriveFont(statusVimToggle.getFont().getSize2D() * .9f)); + statusVimToggle = GuiUtils.smallToggleButton("Vim", null, false); // as the other buttons of the bar statusVimToggle.setToolTipText(vimMode.getToolTipText()); statusVimToggle.setFocusable(false); statusVimToggle.addActionListener(e -> setVimMode(statusVimToggle.isSelected())); @@ -2379,6 +2374,8 @@ void syncStatusBar() { if (statusBelow != null) { final TextEditorTab tab = getTab(); final boolean shown = tab.isBottomVisible(); + // A tab Zen mode has not handled yet (new) is hidden by zenHideNewTabs() + if (shown && zenConsoles != null && zenConsoles.containsKey(tab)) endZenMode(); syncPaneItems(null, shown); statusBelow.setSelected(shown && tab.isLayoutBelow()); statusRight.setSelected(shown && !tab.isLayoutBelow()); @@ -2497,12 +2494,31 @@ private void installCloseTabsPopup() { final int sel = tabbed.getSelectedIndex(); closeTabs(i -> i > sel, true); }); + final JMenuItem copyPath = new JMenuItem("Copy Path"); + copyPath.addActionListener(e -> { + final File f = getEditorPane().getFile(); + if (f == null) return; + Toolkit.getDefaultToolkit().getSystemClipboard().setContents( + new java.awt.datatransfer.StringSelection(f.getAbsolutePath()), null); + statusText.setText("Copied: " + f.getAbsolutePath()); + }); + final JMenuItem reveal = new JMenuItem("Reveal in Files Pane"); + reveal.addActionListener(e -> { + final File f = getEditorPane().getFile(); + if (f == null) return; + if (!statusSide.isSelected()) setSidePanelVisible(true); + sideTabs.setSelectedComponent(filesPanel); + tree.reveal(f); + }); final JMenuItem unmodified = new JMenuItem("Close Unmodified"); unmodified.addActionListener(e -> closeTabs(i -> !getEditorPane(i).fileChanged(), false)); final JMenuItem all = new JMenuItem("Close All"); all.addActionListener(e -> closeTabs(i -> true, true)); for (final JMenuItem mi : new JMenuItem[] { others, right, unmodified, all }) tmp.add(mi); + GuiUtils.addPopupMenuSeparator(tmp, "File:"); + tmp.add(copyPath); + tmp.add(reveal); final java.awt.Component[] items = tmp.getComponents(); for (int i = 0; i < items.length; i++) popup.insert(items[i], i); @@ -2514,6 +2530,9 @@ public void popupMenuWillBecomeVisible(final PopupMenuEvent e) { final int n = tabbed.getTabCount(); others.setEnabled(n > 1); right.setEnabled(tabbed.getSelectedIndex() < n - 1); + final boolean saved = getEditorPane().getFile() != null; + copyPath.setEnabled(saved); + reveal.setEnabled(saved); } @Override @@ -2582,6 +2601,67 @@ boolean handleVimCommand(final String command) { } } + /** Hides the console of tabs not yet handled while in Zen mode */ + private void zenHideNewTabs() { + if (zenConsoles == null) return; + final boolean wasBusy = zenBusy; + zenBusy = true; + try { + for (int i = 0; i < tabbed.getTabCount(); i++) { + final TextEditorTab tab = getTab(i); + if (zenConsoles.containsKey(tab)) continue; + zenConsoles.put(tab, tab.isBottomVisible()); + tab.setBottomVisible(false); + } + } finally { + zenBusy = wasBusy; + } + syncStatusBar(); + } + + /** Hides the side pane and the consoles, or restores them as they were. The status bar stays */ + private void setZenMode(final boolean on) { + if (on == (zenConsoles != null)) return; + zenBusy = true; + try { + if (on) { + zenSide = statusSide == null || statusSide.isSelected(); + zenConsoles = new java.util.IdentityHashMap<>(); + setSidePanelVisible(false); + zenHideNewTabs(); + } else { + final java.util.Map saved = zenConsoles; + zenConsoles = null; + saved.forEach((tab, visible) -> { + if (visible && tabbed.indexOfComponent(tab) >= 0) tab.setBottomVisible(true); + }); + if (zenSide) setSidePanelVisible(true); + } + } finally { + zenBusy = false; + } + syncStatusBar(); + getEditorPane().requestFocusInWindow(); + } + + /** + * Leaves Zen mode without restoring anything: called when the user brings back a + * pane by hand. Does nothing if Zen mode itself is changing the panes + */ + private void endZenMode() { + if (zenConsoles == null || zenBusy) return; + zenConsoles = null; + if (zenItem != null && zenItem.isSelected()) { + final boolean was = syncingPanes; + syncingPanes = true; + try { + zenItem.setSelected(false); + } finally { + syncingPanes = was; + } + } + } + /** Shows/hides the side panel (Files, Outline, Notes), restoring its last width */ private void setSidePanelVisible(final boolean visible) { if (visible) body.setDividerLocation(sideLastLocation > 50 ? sideLastLocation : (int) (body.getWidth() * SIDE_SHARE)); @@ -2976,6 +3056,14 @@ public TextEditorTab newTab(final String content, final String languageExtension } public TextEditorTab open(final File file) { + return open(file, true); + } + + /** + * @param reuseEmpty if true, an empty and unmodified new document in front is reused, i.e., + * it takes the file (or is reset, if file is null) instead of opening another tab + */ + private TextEditorTab open(final File file, final boolean reuseEmpty) { if (isBinary(file)) { try { uiService.show(ioService.open(file.getAbsolutePath())); @@ -2988,7 +3076,7 @@ public TextEditorTab open(final File file) { try { TextEditorTab tab = (tabbed.getTabCount() == 0) ? null : getTab(); final TextEditorTab prior = tab; - final boolean wasNew = tab != null && tab.editorPane.isNew(); + final boolean wasNew = reuseEmpty && tab != null && tab.editorPane.isNew(); float font_size = 0; // to set the new editor's font like the last active one, if any if (!wasNew) { if (tabbed.getTabCount() > 0) font_size = getTab().getEditorPane().getFont().getSize2D(); @@ -4828,6 +4916,35 @@ else if (getTab().showingErrors) popup.add(jmi); jmi.addActionListener(e -> textArea.getHighlighter().removeAllHighlights()); cmdPalette.register(jmi, scope); + popup.addSeparator(); + jmi = new JMenuItem("Save " + ((textArea == errorScreen) ? "Errors" : "Output") + " to File..."); + popup.add(jmi); + jmi.addActionListener(e -> saveConsole(textArea)); + cmdPalette.register(jmi, scope); + } + + /** Saves the contents of a console to a text file chosen by the user */ + private void saveConsole(final JTextArea textArea) { + final String text = textArea.getText(); + if (text == null || text.isEmpty()) { + UIManager.getLookAndFeel().provideErrorFeedback(textArea); + statusText.setText("The console is empty"); + return; + } + final File script = getEditorPane().getFile(); + final File dir = (script != null) ? script.getParentFile() : appService.getApp().getBaseDirectory(); + String base = (script != null) ? script.getName() : "console"; + final int dot = base.lastIndexOf('.'); + if (dot > 0) base = base.substring(0, dot); + final String suffix = (textArea == errorScreen) ? "_errors.txt" : "_output.txt"; + final File file = GuiUtils.chooseSaveFile(this, new File(dir, base + suffix), "Save Console to File"); + if (file == null) return; + try { + Files.write(file.toPath(), text.getBytes(StandardCharsets.UTF_8)); + statusText.setText("Saved: " + file.getAbsolutePath()); + } catch (final IOException ex) { + error("Could not save to\n" + file.getAbsolutePath() + "\n" + ex.getMessage()); + } } private static Collection assembleFlatFileCollection(final Collection collection, final File[] files) { diff --git a/src/main/java/org/scijava/ui/swing/script/TextEditorTab.java b/src/main/java/org/scijava/ui/swing/script/TextEditorTab.java index 2e555ad0..f215cf46 100644 --- a/src/main/java/org/scijava/ui/swing/script/TextEditorTab.java +++ b/src/main/java/org/scijava/ui/swing/script/TextEditorTab.java @@ -93,7 +93,7 @@ public String toString() { private final ConsoleArea combinedScreen = new ConsoleArea(ConsoleArea.Content.MIXED); protected final JTextArea prompt = new JTextArea(); /** Status line for vim mode: the mode, partial command or message. */ - protected final JToggleButton updownarrows = new JToggleButton(); + protected final JToggleButton updownarrows; protected final JScrollPane scroll; /** True iff the console is showing errors only. */ protected boolean showingErrors; @@ -289,11 +289,12 @@ public Dimension getMinimumSize() { label.setIcon(Icons.repl()); promptBar.add(label); promptBar.add(Box.createHorizontalGlue()); - updownarrows.setText("Arrow Keys"); - updownarrows.putClientProperty(FlatClientProperties.STYLE_CLASS, "small"); + // Compact bar: drop the vertical padding FlatLaf adds to toolbar buttons (margin 3 + spacing 1) + final String tight = "toolbar.margin: 0,3,0,3; toolbar.spacingInsets: 0,0,0,0"; + updownarrows = GuiUtils.smallToggleButton("Arrow keys", tight); promptBar.add(Box.createHorizontalGlue()); promptBar.add(updownarrows); - final JButton statusHelp = GuiUtils.helpButton(null); + final JButton statusHelp = GuiUtils.helpButton(null, updownarrows); statusHelp.addActionListener(a -> { final int shift = InputEvent.SHIFT_DOWN_MASK; final int ctrl = InputEvent.CTRL_DOWN_MASK; @@ -317,10 +318,6 @@ public Dimension getMinimumSize() { promptBar.add(statusHelp); - // Compact bar: drop the vertical padding FlatLaf adds to toolbar buttons (margin 3 + spacing 1) - final String tight = "toolbar.margin: 0,3,0,3; toolbar.spacingInsets: 0,0,0,0"; - updownarrows.putClientProperty(FlatClientProperties.STYLE, tight); - updownarrows.setForeground(GuiUtils.secondaryColor()); // Must come after the style properties: applying them resets UIResource foregrounds statusHelp.putClientProperty(FlatClientProperties.STYLE, tight); screenAndPromptSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT, bottom, prompt_panel); screenAndPromptSplit.setResizeWeight(1d); // output takes the changes in height, the prompt keeps its size From edd19c7442a3e90346aa57739eaf577f0d4c247a Mon Sep 17 00:00:00 2001 From: Tiago Ferreira Date: Mon, 16 Nov 2026 22:01:41 -0500 Subject: [PATCH 2/3] Fix menu separators not rendering on macOS native menu bar --- .../java/org/scijava/ui/swing/script/GuiUtils.java | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/main/java/org/scijava/ui/swing/script/GuiUtils.java b/src/main/java/org/scijava/ui/swing/script/GuiUtils.java index 9e1b0619..b59cc9aa 100644 --- a/src/main/java/org/scijava/ui/swing/script/GuiUtils.java +++ b/src/main/java/org/scijava/ui/swing/script/GuiUtils.java @@ -319,6 +319,13 @@ static void addMenubarSeparator(final JMenu menu, final String header) { menu.addSeparator(); } try { + if (usesScreenMenuBar()) { + // The native macOS menu bar only translates menu items, not arbitrary components + final JMenuItem item = new JMenuItem(header); + item.setEnabled(false); + menu.add(item); + return; + } final JLabel label = new JLabel(" "+ header); label.setEnabled(false); label.setForeground(getDisabledComponentColor()); @@ -328,6 +335,11 @@ static void addMenubarSeparator(final JMenu menu, final String header) { } } + /** Whether menu bars are displayed in the native macOS menu bar (at the top of the screen) */ + private static boolean usesScreenMenuBar() { + return PlatformUtils.isMac() && Boolean.parseBoolean(System.getProperty("apple.laf.useScreenMenuBar")); + } + static void addPopupMenuSeparator(final JPopupMenu menu, final String header) { if (menu.getComponentCount() > 1) { menu.addSeparator(); From d81e38d5cbad96525f35788a2fde41c22a2b089f Mon Sep 17 00:00:00 2001 From: Tiago Ferreira Date: Mon, 16 Nov 2026 22:03:40 -0500 Subject: [PATCH 3/3] Report run time and acknowledge completion when running scripts --- .../scijava/ui/swing/script/TextEditor.java | 126 +++++++++++++++++- 1 file changed, 122 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/scijava/ui/swing/script/TextEditor.java b/src/main/java/org/scijava/ui/swing/script/TextEditor.java index d1dd2780..f765fc98 100644 --- a/src/main/java/org/scijava/ui/swing/script/TextEditor.java +++ b/src/main/java/org/scijava/ui/swing/script/TextEditor.java @@ -81,6 +81,7 @@ import java.util.Arrays; import java.util.Collection; import java.util.Collections; +import java.util.ConcurrentModificationException; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.Date; @@ -286,6 +287,9 @@ public class TextEditor extends JFrame implements ActionListener, private int sideLastLocation = -1; private final JMenu languageMenu; private JLabel statusText; + private JLabel statusRun; // run timer: elapsed time of the running script + private boolean headerWritten; // whether the last markCompileStart() wrote a "Started" line + private final Timer runTimer = new Timer(1000, e -> refreshRunStatus()); private JLabel statusVim; private final FileSystemTreePanel filesPanel; private final JCheckBoxMenuItem autoSave; @@ -2206,6 +2210,13 @@ public Dimension getPreferredSize() { // fixed width: neighbors do not move as t bar.add(statusVim); bar.add(statusText); bar.add(Box.createHorizontalGlue()); + statusRun = new JLabel(); + statusRun.setFont(statusText.getFont()); + statusRun.setForeground(GuiUtils.secondaryColor()); + statusRun.setToolTipText("Time elapsed since the running script started"); + statusRun.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 8)); + statusRun.setVisible(false); + bar.add(statusRun); bar.addSeparator(); bar.add(Box.createHorizontalStrut(gap)); bar.add(statusVimToggle); @@ -3321,6 +3332,7 @@ public void dispose() { disposed = true; layoutSaveTimer.stop(); titleTimer.stop(); + runTimer.stop(); UIManager.removePropertyChangeListener(lookAndFeelListener); tree.destroy(); if (dragSource != null) { // necessary to prevent memory leaks @@ -3520,6 +3532,73 @@ public void setTitle(final String title) { private final ArrayList executingTasks = new ArrayList<>(); + /** + * Called once when a task ends: writes the matching "Finished" (or "Stopped") line to the consoles + * of its tab, if the run had a "Started" line, and updates the run timer + */ + private void reportRun(final Executer task, final boolean stopped) { + if (!task.reported.compareAndSet(false, true)) return; + final long ms = (System.nanoTime() - task.startNanos) / 1_000_000; + final Date end = new Date(); // the lambda below runs a bit later + SwingUtilities.invokeLater(() -> { + // Failed: a caught exception, or what makes the error console pop up (see markCompileEnd()) + final boolean failed = !stopped && (task.failed || (task.unverifiedLang == null + && task.runParser.isLogDetailed() + && errorScreen.getDocument().getLength() != task.startOffset)); + final String note = (stopped || failed || task.unverifiedLang == null) ? "" + : " (success not verified for " + task.unverifiedLang + ")"; + final String footer = (stopped ? "Stopped " + task.runName + " after " + : failed ? "Failed " + task.runName + " after " : "Finished " + task.runName + " in ") + + formatElapsed(ms, false) + note + " at " + end + "\n"; + if (task.marked) { // same layout as the header: the errors view gets it too, the combined view once + task.runTab.withoutMirroringErrors(() -> append(errorScreen, footer)); + append(task.runTab.screen, footer); + } + refreshRunStatus(); + }); + } + + /** Name of the language if its failures cannot be detected (see ErrorParser), null otherwise */ + private static String unverifiedLanguage(final ScriptLanguage lang) { + if (lang == null) return null; + final String name = lang.getLanguageName(); + if ("ImageJ Macro".equals(name) || "IJ1 Macro".equals(name) || "Scala".equals(name) || "R".equals(name)) + return name; + return null; + } + + /** Updates the run timer of the status bar. Invoke in the context of the event dispatch thread */ + private void refreshRunStatus() { + if (statusRun == null) return; + final List running; + try { + running = new ArrayList<>(executingTasks); + } catch (final ConcurrentModificationException ex) { + return; // the next tick will get it + } + String text = null; + if (running.isEmpty()) { + runTimer.stop(); + } else { + runTimer.start(); // no-op if already running + final Executer newest = Collections.max(running, java.util.Comparator.comparingLong(x -> x.startNanos)); + final long ms = (System.nanoTime() - newest.startNanos) / 1_000_000; + // short runs do not flash the label + if (ms >= 900) text = "Running " + formatElapsed(ms, true) + (running.size() > 1 ? " (+" + (running.size() - 1) + ")" : ""); + } + statusRun.setText(text == null ? "" : text); + statusRun.setVisible(text != null); + } + + /** Elapsed time as "3.4 s" (finished runs under a minute), "12 s", "2:05" or "1:02:05" */ + private static String formatElapsed(final long ms, final boolean running) { + if (ms < 60_000) return running ? (ms / 1000) + " s" : String.format(java.util.Locale.ROOT, "%.1f s", ms / 1000d); + final long totalSeconds = ms / 1000; + final long h = totalSeconds / 3600, m = (totalSeconds % 3600) / 60, sec = totalSeconds % 60; + return h > 0 ? String.format(java.util.Locale.ROOT, "%d:%02d:%02d", h, m, sec) + : String.format(java.util.Locale.ROOT, "%d:%02d", m, sec); + } + /** * Generic Thread that keeps a starting time stamp, sets the priority to * normal and starts itself. @@ -3527,6 +3606,18 @@ public void setTitle(final String title) { public abstract class Executer extends ThreadGroup { JTextAreaWriter output, errors; + private final long startNanos = System.nanoTime(); + private final java.util.concurrent.atomic.AtomicBoolean reported = new java.util.concurrent.atomic.AtomicBoolean(); + // What the "Finished" line needs, recorded when the run starts (the tab may change or close later) + private final boolean marked = headerWritten; + private final String runName = getEditorPane().getFileName(); + private final TextEditorTab runTab = getTab(); + private final ErrorParser runParser = getEditorPane().getErrorHighlighter(); + // Languages whose errors we cannot detect: ErrorParser skips them (and macros report errors in a dialog) + private final String unverifiedLang = unverifiedLanguage(getCurrentLanguage()); + private volatile boolean failed; // an exception or compile error was caught + // length of the error console once the header (written by markCompileStart) is in + private final int startOffset = errorScreen.getDocument().getLength(); Executer(final JTextAreaWriter output, final JTextAreaWriter errors) { super("Script Editor Run :: " + new Date().toString()); @@ -3534,6 +3625,7 @@ public abstract class Executer extends ThreadGroup { this.errors = errors; // Store itself for later executingTasks.add(this); + SwingUtilities.invokeLater(TextEditor.this::refreshRunStatus); setTitle(); // Enable kill menu kill.setEnabled(true); @@ -3588,6 +3680,7 @@ public void run() { catch (final Exception e) { handleException(e); } + reportRun(Executer.this, false); // after the writers flushed: the last line of the run // Leave kill menu item enabled if other tasks are running kill.setEnabled(!executingTasks.isEmpty()); setTitle(); @@ -3667,6 +3760,7 @@ void obliterate() { } } executingTasks.remove(this); + reportRun(this, true); // The wrapper thread may survive (no Thread.stop()): refresh the state it would have SwingUtilities.invokeLater(() -> kill.setEnabled(!executingTasks.isEmpty())); setTitle(); @@ -3691,7 +3785,7 @@ private void reportSurvivors() { errorScreen.append("\n[Kill] " + names.size() + " thread(s) of " + script + " still running 1s after Kill: " + String.join(", ", names) + "\n"); showTemporaryStatus(names.size() + " thread(s) of " + script + " still running after Kill. " - + "See Errors", 15000, Icons.error()); + + "See Errors", 15000, Icons.error(statusText)); }); timer.setRepeats(false); timer.start(); @@ -3707,17 +3801,17 @@ static boolean isScriptOwnedThread(final Thread thread, final ThreadGroup runGroup, final ThreadService threadService) { if (thread == null || runGroup == null) return false; - if (threadService == null) return isInThreadGroup(thread, runGroup); + if (threadService == null) return isInThreadGroup(thread, runGroup) && !isIdleDaemon(thread); final ThreadService.ThreadContext threadContext; try { threadContext = threadService.getThreadContext(thread); } catch (final RuntimeException e) { - return isInThreadGroup(thread, runGroup); + return isInThreadGroup(thread, runGroup) && !isIdleDaemon(thread); } if (threadContext == null || threadContext == ThreadService.ThreadContext.NONE) { - return isInThreadGroup(thread, runGroup); + return isInThreadGroup(thread, runGroup) && !isIdleDaemon(thread); } final Set seenParents = new HashSet<>(); @@ -3729,6 +3823,17 @@ static boolean isScriptOwnedThread(final Thread thread, return isInThreadGroup(thread, runGroup) && !isIdleThreadServiceWorker(thread); } + /** + * Some scripts may launch Daemon threads parked in a wait. E.g., This happens when using SNT to connect to + * remote databases which causes Okio Watchdog or OkHttp TaskRunner to linger 1-5 minutes after the HTTP request. + * These should be filtered and not hold the run. + */ + private static boolean isIdleDaemon(final Thread thread) { + if (!thread.isDaemon()) return false; + final Thread.State state = thread.getState(); + return state == Thread.State.WAITING || state == Thread.State.TIMED_WAITING; + } + private static boolean isIdleThreadServiceWorker(final Thread thread) { final Thread.State state = thread.getState(); if (state != Thread.State.WAITING && state != Thread.State.TIMED_WAITING) { @@ -4105,6 +4210,7 @@ public void markCompileStart() { } public void markCompileStart(final boolean with_timestamp) { + headerWritten = with_timestamp; // the run that follows gets a matching "Finished" line errorHandler = null; // Errors flagged by a previous run are outdated getEditorPane().getErrorHighlighter().reset(); @@ -4463,7 +4569,18 @@ void showHTMLDialog(final String title, final String htmlContents) { GuiUtils.showHTMLDialog(this, title, htmlContents); } + /** Flags the run (if any) that the calling thread belongs to as failed */ + private void flagFailedRun() { + for (ThreadGroup g = Thread.currentThread().getThreadGroup(); g != null; g = g.getParent()) { + if (g instanceof Executer) { + ((Executer) g).failed = true; + return; + } + } + } + public void handleException(final Throwable e) { + flagFailedRun(); handleException(e, errorScreen); getEditorPane().getErrorHighlighter().parse(e); getTab().showErrors(); @@ -4589,6 +4706,7 @@ private Reader evalScript(final String filename, Reader reader, } catch (final ExecutionException e) { log.error(e); + flagFailedRun(); getEditorPane().getErrorHighlighter().parse(e); } finally { getEditorPane().getErrorHighlighter().parse();