From f4b9a528c95ec3fedc41c9e27142fa0e78cfa7b3 Mon Sep 17 00:00:00 2001
From: Tiago Ferreira
Date: Wed, 11 Nov 2026 21:55:00 -0500
Subject: [PATCH 01/41] Improve FilePane
- Searching an hierarchy with an n5/Zarr folder no longer halts the EDT
- Fast mode option: Only act on listed paths, not their children
- Fast mode automatically activates if search slower than 1 sec
- Option to toggle live updates
- Improve drag and drop
- Improve layout with FlatLaft
- Add icons to file list
---
.gitignore | 2 +
.../scijava/ui/swing/script/EditorPane.java | 5 +-
.../org/scijava/ui/swing/script/FileDrop.java | 1217 +++++------------
.../ui/swing/script/FileFunctions.java | 4 +-
.../ui/swing/script/FileSystemTree.java | 1202 ++++++++++------
.../ui/swing/script/FileSystemTreePanel.java | 874 ++++++++----
.../scijava/ui/swing/script/PromptPane.java | 2 +-
.../scijava/ui/swing/script/TextEditor.java | 519 ++++++-
.../ui/swing/script/TextEditorTab.java | 3 +
9 files changed, 2240 insertions(+), 1588 deletions(-)
diff --git a/.gitignore b/.gitignore
index 3b41a45d..dde63c6c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -6,3 +6,5 @@
/.idea/
/.serena
/script-editor.iml
+
+.DS_Store
diff --git a/src/main/java/org/scijava/ui/swing/script/EditorPane.java b/src/main/java/org/scijava/ui/swing/script/EditorPane.java
index a81ec716..bcc4ec88 100644
--- a/src/main/java/org/scijava/ui/swing/script/EditorPane.java
+++ b/src/main/java/org/scijava/ui/swing/script/EditorPane.java
@@ -383,6 +383,7 @@ public RTextScrollPane wrappedInScrollbars() {
final RTextScrollPane sp = new RTextScrollPane(this);
sp.setPreferredSize(new Dimension(600, 350));
sp.setIconRowHeaderEnabled(true);
+ TextEditor.GuiUtils.flattenScrollBars(sp);
gutter = sp.getGutter();
gutter.setBookmarkingEnabled(true);
gutter.setShowCollapsedRegionToolTips(true);
@@ -1142,13 +1143,13 @@ private void applyTheme(final Theme th) throws IllegalArgumentException {
}
public String loadFolders() {
- return prefService.get(getClass(), FOLDERS_PREFS, System.getProperty("user.home"));
+ return prefService.get(getClass(), FOLDERS_PREFS, "");
}
/**
* Retrieves and saves the preferences to the persistent store.
*
- * @param top_folders the File Explorer's pane top folder paths (":" separated list)
+ * @param top_folders the Files pane top folder paths (":" separated list)
* @param theme the Script Editor's theme
*/
public void savePreferences(final String top_folders, final String theme) {
diff --git a/src/main/java/org/scijava/ui/swing/script/FileDrop.java b/src/main/java/org/scijava/ui/swing/script/FileDrop.java
index 547dc74f..0544410e 100644
--- a/src/main/java/org/scijava/ui/swing/script/FileDrop.java
+++ b/src/main/java/org/scijava/ui/swing/script/FileDrop.java
@@ -29,962 +29,417 @@
package org.scijava.ui.swing.script;
+import java.awt.Color;
+import java.awt.Component;
+import java.awt.Container;
+import java.awt.FontMetrics;
+import java.awt.Graphics2D;
+import java.awt.Graphics;
+import java.awt.GraphicsEnvironment;
+import java.awt.Point;
+import java.awt.RenderingHints;
+import java.awt.BasicStroke;
+import java.awt.geom.RoundRectangle2D;
import java.awt.datatransfer.DataFlavor;
+import java.awt.datatransfer.Transferable;
+import java.awt.datatransfer.UnsupportedFlavorException;
+import java.awt.dnd.DnDConstants;
+import java.awt.dnd.DropTarget;
+import java.awt.dnd.DropTargetAdapter;
+import java.awt.dnd.DropTargetDragEvent;
+import java.awt.dnd.DropTargetDropEvent;
+import java.awt.dnd.DropTargetEvent;
+import java.awt.dnd.DropTargetListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
-import java.io.PrintStream;
-import java.io.Reader;
-
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import javax.swing.JComponent;
+import javax.swing.JLayeredPane;
+import javax.swing.JRootPane;
+import javax.swing.SwingUtilities;
import javax.swing.UIManager;
-
/**
- * This class makes it easy to drag and drop files from the operating system to
- * a Java program. Any {@code java.awt.Component} can be dropped onto, but only
- * {@code javax.swing.JComponent}s will indicate the drop event with a changed
- * border.
+ * Makes it easy to drag and drop files from the operating system to a Java
+ * program. Any {@link java.awt.Component} displayed in a Swing window can be
+ * dropped onto. While dragging, a frame is painted over the target without
+ * affecting its border or layout.
*
* To use this class, construct a new {@code FileDrop} by passing it the target
- * component and a {@code Listener} to receive notification when file(s) have
- * been dropped. Here is an example:
+ * component and a {@link Listener} to receive notification when file(s) have
+ * been dropped. Dropped files are delivered on the Event Dispatch Thread, after
+ * the drop operation has been completed, so listeners are free to display
+ * dialogs or start long running tasks. Example:
*
- *
+ *
*
- * JPanel myPanel = new JPanel();
- * new FileDrop( myPanel, new FileDrop.Listener()
- * { public void filesDropped( java.io.File[] files )
- * {
- * // handle file drop
- * ...
- * } // end filesDropped
- * }); // end FileDrop.Listener
+ * new FileDrop(myPanel, files -> {
+ * // handle file drop
+ * });
*
*
- * You can specify the border that will appear when files are being dragged by
- * calling the constructor with a {@code javax.swing.border.Border}. Only
- * {@code JComponent}s will show any indication with a border.
- *
- *
- * You can turn on some debugging features by passing a {@code PrintStream}
- * object (such as {@code System.out}) into the full constructor. A
- * {@code null} value will result in no extra debugging information being
- * output.
- *
- *
- *
- * I'm releasing this code into the Public Domain. Enjoy.
- *
- *
- * Original author: Robert Harder, rob@iharder.net
+ * Released into the Public Domain by the original author, Robert Harder
+ * (rob@iharder.net).
*
*
* Additional support:
*
*
- * - September 2007, Nathan Blomquist -- Linux (KDE/Gnome) support added.
+ * - September 2007, Nathan Blomquist: Linux (KDE/Gnome) support
* - December 2010, Joshua Gerth
- * - June 2019, TF, Adjust defaultBorderColor. Code cleanup. Added the ability
- * to abort drop operation using Esc
+ *
- June 2019, TF: Adjusted default border color, code cleanup
+ * - 2026, TF: Modernization (single drop handler, headless awareness,
+ * uri-list parsing, asynchronous listener dispatch, uninstall support, layout
+ * neutral drag highlight)
*
*
* @author Robert Harder
- * @version 1.1.1
+ * @author rharder@users.sf.net
*/
public class FileDrop {
- private transient javax.swing.border.Border normalBorder;
- private transient java.awt.dnd.DropTargetListener dropListener;
- /** Discover if the running JVM is modern enough to have drag and drop. */
- private static Boolean supportsDnD;
+ private static final Logger LOGGER = Logger.getLogger(FileDrop.class
+ .getName());
+ private static final String URI_LIST_MIME = "text/uri-list";
- // Default border color
- private static java.awt.Color defaultBorderColor = UIManager.getColor("Tree.selectionBackground");
- static {
- if (defaultBorderColor == null) defaultBorderColor = new java.awt.Color(0f,0f, 1f, 0.25f);
- }
+ private final Component target;
+ private final Listener listener;
+ private final DropTargetListener dropListener = new Handler();
+ private final List installed = new ArrayList<>();
- /**
- * Constructs a {@link FileDrop} with a default light-blue border and, if
- * c is a {@link java.awt.Container}, recursively sets all
- * elements contained within as drop targets, though only the top level
- * container will change borders.
- *
- * @param c
- * Component on which files will be dropped.
- * @param listener
- * Listens for {@code filesDropped}.
- * @since 1.0
- */
- public FileDrop(final java.awt.Component c, final Listener listener) {
- this(null, // Logging stream
- c, // Drop target
- javax.swing.BorderFactory.createMatteBorder(2, 2, 2, 2,
- defaultBorderColor), // Drag border
- true, // Recursive
- listener);
- } // end constructor
-
- /**
- * Constructor with a default border and the option to recursively set drop
- * targets. If your component is a {@code java.awt.Container}, then each of
- * its children components will also listen for drops, though only the
- * parent will change borders.
- *
- * @param c
- * Component on which files will be dropped.
- * @param recursive
- * Recursively set children as drop targets.
- * @param listener
- * Listens for {@code filesDropped}.
- * @since 1.0
- */
- protected FileDrop(final java.awt.Component c, final boolean recursive,
- final Listener listener) {
- this(null, // Logging stream
- c, // Drop target
- javax.swing.BorderFactory.createMatteBorder(2, 2, 2, 2,
- defaultBorderColor), // Drag border
- recursive, // Recursive
- listener);
- } // end constructor
+ // Frame painted over the target while a drag is active
+ private Highlight highlight;
/**
- * Constructor with a default border and debugging optionally turned on.
- * With Debugging turned on, more status messages will be displayed to
- * {@code out}. A common way to use this constructor is with
- * {@code System.out} or {@code System.err}. A {@code null} value for the
- * parameter {@code out} will result in no debugging output.
+ * Constructs a {@link FileDrop} that recursively sets all the components
+ * contained in c as drop targets, though only c is
+ * highlighted while dragging.
*
- * @param out
- * PrintStream to record debugging info or null for no debugging.
- * @param c
- * Component on which files will be dropped.
- * @param listener
- * Listens for {@code filesDropped}.
- * @since 1.0
+ * @param c the component on which files will be dropped
+ * @param listener notified when files are dropped
*/
- protected FileDrop(final java.io.PrintStream out, final java.awt.Component c,
- final Listener listener) {
- this(out, // Logging stream
- c, // Drop target
- javax.swing.BorderFactory.createMatteBorder(2, 2, 2, 2,
- defaultBorderColor), false, // Recursive
- listener);
- } // end constructor
-
- /**
- * Constructor with a default border, debugging optionally turned on and the
- * option to recursively set drop targets. If your component is a
- * {@code java.awt.Container}, then each of its children components will
- * also listen for drops, though only the parent will change borders. With
- * Debugging turned on, more status messages will be displayed to
- * {@code out}. A common way to use this constructor is with
- * {@code System.out} or {@code System.err}. A {@code null} value for the
- * parameter {@code out} will result in no debugging output.
- *
- * @param out
- * PrintStream to record debugging info or null for no debugging.
- * @param c
- * Component on which files will be dropped.
- * @param recursive
- * Recursively set children as drop targets.
- * @param listener
- * Listens for {@code filesDropped}.
- * @since 1.0
- */
- protected FileDrop(final java.io.PrintStream out, final java.awt.Component c,
- final boolean recursive, final Listener listener) {
- this(out, // Logging stream
- c, // Drop target
- javax.swing.BorderFactory.createMatteBorder(2, 2, 2, 2,
- defaultBorderColor), // Drag border
- recursive, // Recursive
- listener);
- } // end constructor
+ public FileDrop(final Component c, final Listener listener) {
+ this(c, true, listener);
+ }
/**
- * Constructor with a specified border
+ * Constructs a {@link FileDrop}. In headless mode this constructor is a
+ * no-op.
*
- * @param c
- * Component on which files will be dropped.
- * @param dragBorder
- * Border to use on {@code JComponent} when dragging occurs.
- * @param listener
- * Listens for {@code filesDropped}.
- * @since 1.0
+ * @param c the component on which files will be dropped
+ * @param recursive if {@code true}, and c is a
+ * {@link java.awt.Container}, its children will also be set as drop
+ * targets, though only c is highlighted while dragging
+ * @param listener notified when files are dropped
*/
- protected FileDrop(final java.awt.Component c,
- final javax.swing.border.Border dragBorder, final Listener listener) {
- this(null, // Logging stream
- c, // Drop target
- dragBorder, // Drag border
- false, // Recursive
- listener);
- } // end constructor
+ public FileDrop(final Component c, final boolean recursive,
+ final Listener listener)
+ {
+ this.target = Objects.requireNonNull(c);
+ this.listener = Objects.requireNonNull(listener);
+ if (GraphicsEnvironment.isHeadless()) {
+ LOGGER.fine("Headless mode, drag and drop is disabled");
+ return;
+ }
+ install(c, recursive);
+ }
/**
- * Constructor with a specified border and the option to recursively set
- * drop targets. If your component is a {@code java.awt.Container}, then
- * each of its children components will also listen for drops, though only
- * the parent will change borders.
- *
- * @param c
- * Component on which files will be dropped.
- * @param dragBorder
- * Border to use on {@code JComponent} when dragging occurs.
- * @param recursive
- * Recursively set children as drop targets.
- * @param listener
- * Listens for {@code filesDropped}.
- * @since 1.0
+ * Removes the drag-and-drop hooks installed by this instance, restoring any
+ * drop target the components had before. Call this if you add and remove
+ * components after you've set up the drag-and-drop.
*/
- protected FileDrop(final java.awt.Component c,
- final javax.swing.border.Border dragBorder,
- final boolean recursive, final Listener listener) {
- this(null, c, dragBorder, recursive, listener);
- } // end constructor
+ public void uninstall() {
+ for (final Installed i : installed) {
+ if (i.component.getDropTarget() == i.ours) i.component.setDropTarget(
+ i.previous);
+ }
+ installed.clear();
+ hideHighlight();
+ }
- /**
- * Constructor with a specified border and debugging optionally turned on.
- * With Debugging turned on, more status messages will be displayed to
- * {@code out}. A common way to use this constructor is with
- * {@code System.out} or {@code System.err}. A {@code null} value for the
- * parameter {@code out} will result in no debugging output.
- *
- * @param out
- * PrintStream to record debugging info or null for no debugging.
- * @param c
- * Component on which files will be dropped.
- * @param dragBorder
- * Border to use on {@code JComponent} when dragging occurs.
- * @param listener
- * Listens for {@code filesDropped}.
- * @since 1.0
- */
- protected FileDrop(final java.io.PrintStream out, final java.awt.Component c,
- final javax.swing.border.Border dragBorder, final Listener listener) {
- this(out, // Logging stream
- c, // Drop target
- dragBorder, // Drag border
- false, // Recursive
- listener);
- } // end constructor
+ private void install(final Component c, final boolean recursive) {
+ final DropTarget previous = c.getDropTarget();
+ // The DropTarget is attached to the component by its constructor
+ final DropTarget ours = new DropTarget(c, DnDConstants.ACTION_COPY,
+ dropListener, true);
+ installed.add(new Installed(c, previous, ours));
+ if (recursive && c instanceof Container) {
+ for (final Component child : ((Container) c).getComponents())
+ install(child, true);
+ }
+ }
/**
- * Full constructor with a specified border and debugging optionally turned
- * on. With Debugging turned on, more status messages will be displayed to
- * {@code out}. A common way to use this constructor is with
- * {@code System.out} or {@code System.err}. A {@code null} value for the
- * parameter {@code out} will result in no debugging output.
+ * Paints a dashed box with a short message at the center of a component, to
+ * advertise that it accepts dropped files. Meant to be called from
+ * {@code paintComponent()} while the component is empty. Nothing is painted
+ * if the component is too small to fit the hint.
*
- * @param out
- * PrintStream to record debugging info or null for no debugging.
- * @param c
- * Component on which files will be dropped.
- * @param dragBorder
- * Border to use on {@code JComponent} when dragging occurs.
- * @param recursive
- * Recursively set children as drop targets.
- * @param listener
- * Listens for {@code filesDropped}.
- * @since 1.0
+ * @param component the component being painted
+ * @param g the graphics context of the component. Left untouched (a copy is
+ * used)
+ * @param text the message, e.g., "Drag folders here"
*/
- protected FileDrop(final java.io.PrintStream out, final java.awt.Component c,
- final javax.swing.border.Border dragBorder,
- final boolean recursive, final Listener listener) {
-
- if (supportsDnD()) { // Make a drop listener
- dropListener = new java.awt.dnd.DropTargetListener() {
- @Override
- public void dragEnter(final java.awt.dnd.DropTargetDragEvent evt) {
- log(out, "FileDrop: dragEnter event.");
-
- // Is this an acceptable drag event?
- if (isDragOk(out, evt) && c.isEnabled()) {
- // If it's a Swing component, set its border
- if (c instanceof javax.swing.JComponent) {
- final javax.swing.JComponent jc = (javax.swing.JComponent) c;
- if (normalBorder == null) {
- normalBorder = jc.getBorder();
- } // end if: border not yet saved
- log(out, "FileDrop: normal border saved.");
- jc.setBorder(dragBorder);
- log(out, "FileDrop: drag border set.");
- } // end if: JComponent
-
- // Acknowledge that it's okay to enter
- // evt.acceptDrag(
- // java.awt.dnd.DnDConstants.ACTION_COPY_OR_MOVE );
- evt.acceptDrag(java.awt.dnd.DnDConstants.ACTION_COPY);
- log(out, "FileDrop: event accepted.");
- } // end if: drag ok
- else { // Reject the drag event
- evt.rejectDrag();
- log(out, "FileDrop: event rejected.");
- } // end else: drag not ok
- } // end dragEnter
-
- @Override
- public void dragOver(final java.awt.dnd.DropTargetDragEvent evt) { // This
- // is
- // called
- // continually
- // as
- // long
- // as
- // the
- // mouse
- // is
- // over
- // the
- // drag
- // target.
- } // end dragOver
-
- @Override
- public void drop(final java.awt.dnd.DropTargetDropEvent evt) {
- log(out, "FileDrop: drop event.");
- try { // Get whatever was dropped
- final java.awt.datatransfer.Transferable tr = evt
- .getTransferable();
-
- // Is it a file list?
- if (tr.isDataFlavorSupported(java.awt.datatransfer.DataFlavor.javaFileListFlavor)) {
- // Say we'll take it.
- // evt.acceptDrop (
- // java.awt.dnd.DnDConstants.ACTION_COPY_OR_MOVE );
- evt.acceptDrop(java.awt.dnd.DnDConstants.ACTION_COPY);
- log(out, "FileDrop: file list accepted.");
-
- // Get a useful list
- final java.util.List> fileList = (java.util.List>) tr
- .getTransferData(java.awt.datatransfer.DataFlavor.javaFileListFlavor);
- //final java.util.Iterator> iterator = fileList.iterator();
-
- // Convert list to array
- final java.io.File[] filesTemp = new java.io.File[fileList
- .size()];
- fileList.toArray(filesTemp);
- final java.io.File[] files = filesTemp;
-
- // Alert listener to drop.
- if (listener != null)
- listener.filesDropped(files);
-
- // Mark that drop is completed.
- evt.getDropTargetContext().dropComplete(true);
- log(out, "FileDrop: drop complete.");
- } // end if: file list
- else // this section will check for a reader flavor.
- {
- // Thanks, Nathan!
- // BEGIN 2007-09-12 Nathan Blomquist -- Linux
- // (KDE/Gnome) support added.
- final DataFlavor[] flavors = tr.getTransferDataFlavors();
- boolean handled = false;
- for (int zz = 0; zz < flavors.length; zz++) {
- if (flavors[zz].isRepresentationClassReader()) {
- // Say we'll take it.
- // evt.acceptDrop (
- // java.awt.dnd.DnDConstants.ACTION_COPY_OR_MOVE
- // );
- evt.acceptDrop(java.awt.dnd.DnDConstants.ACTION_COPY);
- log(out, "FileDrop: reader accepted.");
-
- final Reader reader = flavors[zz]
- .getReaderForText(tr);
-
- final BufferedReader br = new BufferedReader(
- reader);
-
- if (listener != null)
- listener.filesDropped(createFileArray(
- br, out));
-
- // Mark that drop is completed.
- evt.getDropTargetContext().dropComplete(
- true);
- log(out, "FileDrop: drop complete.");
- handled = true;
- break;
- }
- }
- if (!handled) {
- log(out,
- "FileDrop: not a file list or reader - abort.");
- evt.rejectDrop();
- }
- // END 2007-09-12 Nathan Blomquist -- Linux
- // (KDE/Gnome) support added.
- } // end else: not a file list
- } // end try
- catch (final java.io.IOException io) {
- log(out, "FileDrop: IOException - abort:");
- io.printStackTrace(out);
- evt.rejectDrop();
- } // end catch IOException
- catch (final java.awt.datatransfer.UnsupportedFlavorException ufe) {
- log(out,
- "FileDrop: UnsupportedFlavorException - abort:");
- ufe.printStackTrace(out);
- evt.rejectDrop();
- } // end catch: UnsupportedFlavorException
- finally {
- // If it's a Swing component, reset its border
- if (c instanceof javax.swing.JComponent) {
- final javax.swing.JComponent jc = (javax.swing.JComponent) c;
- jc.setBorder(normalBorder);
- log(out, "FileDrop: normal border restored.");
- } // end if: JComponent
- } // end finally
- } // end drop
-
- @Override
- public void dragExit(final java.awt.dnd.DropTargetEvent evt) {
- log(out, "FileDrop: dragExit event.");
- // If it's a Swing component, reset its border
- if (c instanceof javax.swing.JComponent) {
- final javax.swing.JComponent jc = (javax.swing.JComponent) c;
- jc.setBorder(normalBorder);
- log(out, "FileDrop: normal border restored.");
- } // end if: JComponent
- } // end dragExit
-
- @Override
- public void dropActionChanged(
- final java.awt.dnd.DropTargetDragEvent evt) {
- log(out, "FileDrop: dropActionChanged event.");
- // Is this an acceptable drag event?
- if (isDragOk(out, evt)) { // evt.acceptDrag(
- // java.awt.dnd.DnDConstants.ACTION_COPY_OR_MOVE
- // );
- evt.acceptDrag(java.awt.dnd.DnDConstants.ACTION_COPY);
- log(out, "FileDrop: event accepted.");
- } // end if: drag ok
- else {
- evt.rejectDrag();
- log(out, "FileDrop: event rejected.");
- } // end else: drag not ok
- } // end dropActionChanged
- }; // end DropTargetListener
-
- // Make the component (and possibly children) drop targets
- makeDropTarget(out, c, recursive);
- } // end if: supports dnd
- else {
- log(out, "FileDrop: Drag and drop is not supported with this JVM");
- } // end else: does not support DnD
- } // end constructor
-
- private static boolean supportsDnD() { // Static Boolean
- if (supportsDnD == null) {
- boolean support = false;
- try {
- Class.forName("java.awt.dnd.DnDConstants");
- support = true;
- } // end try
- catch (final Exception e) {
- support = false;
- } // end catch
- supportsDnD = Boolean.valueOf(support);
- } // end if: first time through
- return supportsDnD.booleanValue();
- } // end supportsDnD
-
- // BEGIN 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support added.
- private static String ZERO_CHAR_STRING = "" + (char) 0;
-
- private static File[] createFileArray(final BufferedReader bReader,
- final PrintStream out) {
+ public static void paintHint(final Component component, final Graphics g,
+ final String text)
+ {
+ final Graphics2D g2 = (Graphics2D) g.create();
try {
- final java.util.List list = new java.util.ArrayList();
- java.lang.String line = null;
- while ((line = bReader.readLine()) != null) {
- try {
- // kde seems to append a 0 char to the end of the reader
- if (ZERO_CHAR_STRING.equals(line))
- continue;
-
- final java.io.File file = new java.io.File(new java.net.URI(line));
- list.add(file);
- } catch (final Exception ex) {
- log(out, "Error with " + line + ": " + ex.getMessage());
- }
- }
+ final FontMetrics fm = g2.getFontMetrics();
+ final int gap = fm.stringWidth("W");
+ final int w = fm.stringWidth(text) + 4 * gap;
+ final int h = fm.getHeight() * 3;
+ if (component.getWidth() < w + 2 * gap || component
+ .getHeight() < h + 2 * gap) return;
+ Color c = UIManager.getColor("Label.disabledForeground");
+ if (c == null) c = Color.GRAY;
+ g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
+ RenderingHints.VALUE_ANTIALIAS_ON);
+ g2.setColor(c);
+ g2.setStroke(new BasicStroke(1f, BasicStroke.CAP_BUTT,
+ BasicStroke.JOIN_MITER, gap / 2.5f, new float[] { gap / 2.5f }, 0f));
+ final double x = (component.getWidth() - w) / 2d;
+ final double y = (component.getHeight() - h) / 2d;
+ g2.draw(new RoundRectangle2D.Double(x, y, w, h, gap * 2, gap * 2));
+ g2.drawString(text, (int) (x + 2 * gap), (int) (y + (h - fm
+ .getHeight()) / 2d + fm.getAscent()));
+ } finally {
+ g2.dispose();
+ }
+ }
- return list.toArray(new File[list.size()]);
- } catch (final IOException ex) {
- log(out, "FileDrop: IOException");
+ private void showHighlight() {
+ if (highlight != null) return;
+ final JRootPane root = SwingUtilities.getRootPane(target);
+ if (root == null || !target.isShowing()) return;
+ // The layered pane has no layout manager: adding the highlight to it
+ // leaves the layout and the border of the target untouched
+ final JLayeredPane layers = root.getLayeredPane();
+ final Point p = SwingUtilities.convertPoint(target, 0, 0, layers);
+ highlight = new Highlight(highlightColor());
+ highlight.setBounds(p.x, p.y, target.getWidth(), target.getHeight());
+ layers.add(highlight, JLayeredPane.DRAG_LAYER);
+ }
+
+ private void hideHighlight() {
+ if (highlight == null) return;
+ final Container parent = highlight.getParent();
+ if (parent != null) {
+ parent.remove(highlight);
+ parent.repaint(highlight.getX(), highlight.getY(), highlight
+ .getWidth(), highlight.getHeight());
}
- return new File[0];
+ highlight = null;
}
- // END 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support added.
+ private static Color highlightColor() {
+ final String[] keys = { "Component.focusColor", "List.selectionBackground",
+ "Tree.selectionBackground" };
+ for (final String key : keys) {
+ final Color c = UIManager.getColor(key);
+ if (c != null) return c;
+ }
+ return new Color(75, 110, 175);
+ }
- private void makeDropTarget(final java.io.PrintStream out,
- final java.awt.Component c, final boolean recursive) {
- // Make drop target
- final java.awt.dnd.DropTarget dt = new java.awt.dnd.DropTarget();
+ private void notifyListener(final File[] files) {
try {
- dt.addDropTargetListener(dropListener);
- } // end try
- catch (final java.util.TooManyListenersException e) {
- e.printStackTrace();
- log(out,
- "FileDrop: Drop will not work due to previous error. Do you have another listener attached?");
- } // end catch
-
- // Listen for hierarchy changes and remove the drop target when the
- // parent gets cleared out.
- c.addHierarchyListener(new java.awt.event.HierarchyListener() {
- @Override
- public void hierarchyChanged(final java.awt.event.HierarchyEvent evt) {
- log(out, "FileDrop: Hierarchy changed.");
- final java.awt.Component parent = c.getParent();
- if (parent == null) {
- c.setDropTarget(null);
- log(out, "FileDrop: Drop target cleared from component.");
- } // end if: null parent
- else {
- new java.awt.dnd.DropTarget(c, dropListener);
- log(out, "FileDrop: Drop target added to component.");
- } // end else: parent not null
- } // end hierarchyChanged
- }); // end hierarchy listener
- if (c.getParent() != null)
- new java.awt.dnd.DropTarget(c, dropListener);
-
- if (recursive && (c instanceof java.awt.Container)) {
- // Get the container
- final java.awt.Container cont = (java.awt.Container) c;
-
- // Get it's components
- final java.awt.Component[] comps = cont.getComponents();
-
- // Set it's components as listeners also
- for (int i = 0; i < comps.length; i++)
- makeDropTarget(out, comps[i], recursive);
- } // end if: recursively set components as listener
- } // end dropListener
-
- /** Determine if the dragged data is a file list. */
- private boolean isDragOk(final java.io.PrintStream out,
- final java.awt.dnd.DropTargetDragEvent evt) {
- boolean ok = false;
-
- // Get data flavors being dragged
- final java.awt.datatransfer.DataFlavor[] flavors = evt
- .getCurrentDataFlavors();
-
- // See if any of the flavors are a file list
- int i = 0;
- while (!ok && i < flavors.length) {
- // BEGIN 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support
- // added.
- // Is the flavor a file list?
- final DataFlavor curFlavor = flavors[i];
- if (curFlavor
- .equals(java.awt.datatransfer.DataFlavor.javaFileListFlavor)
- || curFlavor.isRepresentationClassReader()) {
- ok = true;
- }
- // END 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support
- // added.
- i++;
- } // end while: through flavors
-
- // If logging is enabled, show data flavors
- if (out != null) {
- if (flavors.length == 0)
- log(out, "FileDrop: no data flavors.");
- for (i = 0; i < flavors.length; i++)
- log(out, flavors[i].toString());
- } // end if: logging enabled
-
- return ok;
- } // end isDragOk
-
- /** Outputs {@code message} to {@code out} if it's not null. */
- private static void log(final java.io.PrintStream out, final String message) { // Log
- // message
- // if
- // requested
- if (out != null)
- out.println(message);
- } // end log
-
- /**
- * Removes the drag-and-drop hooks from the component and optionally from
- * the all children. You should call this if you add and remove components
- * after you've set up the drag-and-drop. This will recursively unregister
- * all components contained within c if c is a
- * {@link java.awt.Container}.
- *
- * @param c The component to unregister as a drop target
- * @return true, if successful
- * @since 1.0
- */
- public static boolean remove(final java.awt.Component c) {
- return remove(null, c, true);
- } // end remove
+ listener.filesDropped(files);
+ } catch (final RuntimeException ex) {
+ LOGGER.log(Level.WARNING, "Listener failed", ex);
+ }
+ }
- /**
- * Removes the drag-and-drop hooks from the component and optionally from
- * the all children. You should call this if you add and remove components
- * after you've set up the drag-and-drop.
- *
- * @param out Optional {@link java.io.PrintStream} for logging drag and drop
- * messages
- * @param c The component to unregister
- * @param recursive Recursively unregister components within a container
- * @return true, if successful
- * @since 1.0
- */
- protected static boolean remove(final java.io.PrintStream out, final java.awt.Component c,
- final boolean recursive) { // Make sure we support dnd.
- if (supportsDnD()) {
- log(out, "FileDrop: Removing drag-and-drop hooks.");
- c.setDropTarget(null);
- if (recursive && (c instanceof java.awt.Container)) {
- final java.awt.Component[] comps = ((java.awt.Container) c)
- .getComponents();
- for (int i = 0; i < comps.length; i++)
- remove(out, comps[i], recursive);
- return true;
- } // end if: recursive
- else
- return false;
- } // end if: supports DnD
- else
- return false;
- } // end remove
+ private static boolean isUriList(final DataFlavor flavor) {
+ return flavor.isRepresentationClassReader() && flavor.isMimeTypeEqual(
+ URI_LIST_MIME);
+ }
- /* ******** I N N E R I N T E R F A C E L I S T E N E R ******** */
+ private static boolean isDragOk(final DataFlavor[] flavors) {
+ for (final DataFlavor f : flavors) {
+ if (DataFlavor.javaFileListFlavor.equals(f) || isUriList(f)) return true;
+ }
+ return false;
+ }
- /**
- * Implement this inner interface to listen for when files are dropped. For
- * example your class declaration may begin like this:
- *
- * public class MyClass implements FileDrop.Listener
- * ...
- * public void filesDropped( java.io.File[] files )
- * {
- * ...
- * } // end filesDropped
- * ...
- *
- *
- * @since 1.1
- */
- public static interface Listener {
+ private static DataFlavor findUriListFlavor(final Transferable tr) {
+ for (final DataFlavor f : tr.getTransferDataFlavors()) {
+ if (isUriList(f)) return f;
+ }
+ return null;
+ }
- /**
- * This method is called when files have been successfully dropped.
- *
- * @param files
- * An array of {@code File}s that were dropped.
- * @since 1.0
- */
- public abstract void filesDropped(java.io.File[] files);
+ private static File[] readFileList(final Transferable tr)
+ throws IOException, UnsupportedFlavorException
+ {
+ final Object data = tr.getTransferData(DataFlavor.javaFileListFlavor);
+ if (!(data instanceof List)) return new File[0];
+ final List files = new ArrayList<>();
+ for (final Object o : (List>) data) {
+ if (o instanceof File) files.add((File) o);
+ }
+ return files.toArray(new File[0]);
+ }
- } // end inner-interface Listener
+ private static File[] readUriList(final DataFlavor flavor,
+ final Transferable tr) throws IOException, UnsupportedFlavorException
+ {
+ final List lines = new ArrayList<>();
+ try (BufferedReader br = new BufferedReader(flavor.getReaderForText(
+ tr)))
+ {
+ String line;
+ while ((line = br.readLine()) != null)
+ lines.add(line);
+ }
+ return parseUriList(lines);
+ }
- /* ******** I N N E R C L A S S ******** */
+ private static File[] parseUriList(final List lines) {
+ final List files = new ArrayList<>();
+ for (final String raw : lines) {
+ // KDE may append NUL chars, and uri-lists (RFC 2483) may hold comments
+ final String line = raw.replace("\0", "").trim();
+ if (line.isEmpty() || line.startsWith("#")) continue;
+ try {
+ final URI uri = new URI(line);
+ if ("file".equalsIgnoreCase(uri.getScheme())) files.add(new File(
+ uri));
+ else LOGGER.fine("Ignoring non-file URI: " + line);
+ } catch (final URISyntaxException | RuntimeException ex) {
+ LOGGER.fine("Could not parse " + line + ": " + ex.getMessage());
+ }
+ }
+ return files.toArray(new File[0]);
+ }
- /**
- * This is the event that is passed to the
- * {@link FileDrop.Listener#filesDropped filesDropped(...)} method in your
- * {@link FileDrop.Listener} when files are dropped onto a registered drop
- * target.
- *
- *
- * I'm releasing this code into the Public Domain. Enjoy.
- *
- *
- * @author Robert Harder
- * @author rob@iharder.net
- * @version 1.2
- */
@SuppressWarnings("serial")
- static class Event extends java.util.EventObject {
-
- private final java.io.File[] files;
-
- /**
- * Constructs an {@link Event} with the array of files that were dropped
- * and the {@link FileDrop} that initiated the event.
- *
- * @param files
- * The array of files that were dropped
- * @param source
- * The event source
- * @since 1.1
- */
- public Event(final java.io.File[] files, final Object source) {
- super(source);
- this.files = files;
- } // end constructor
+ private static final class Highlight extends JComponent {
- /**
- * Returns an array of files that were dropped on a registered drop
- * target.
- *
- * @return array of files that were dropped
- * @since 1.1
- */
- public java.io.File[] getFiles() {
- return files;
- } // end getFiles
+ private static final int THICKNESS = 2;
+ private final Color color;
- } // end inner class Event
-
- /* ******** I N N E R C L A S S ******** */
-
- /**
- * At last an easy way to encapsulate your custom objects for dragging and
- * dropping in your Java programs! When you need to create a
- * {@link java.awt.datatransfer.Transferable} object, use this class to wrap
- * your object. For example:
- *
- *
- * ...
- * MyCoolClass myObj = new MyCoolClass();
- * Transferable xfer = new TransferableObject( myObj );
- * ...
- *
- *
- * Or if you need to know when the data was actually dropped, like when
- * you're moving data out of a list, say, you can use the
- * {@link TransferableObject.Fetcher} inner class to return your object Just
- * in Time. For example:
- *
- *
- * ...
- * final MyCoolClass myObj = new MyCoolClass();
- *
- * TransferableObject.Fetcher fetcher = new TransferableObject.Fetcher()
- * { public Object getObject(){ return myObj; }
- * }; // end fetcher
- *
- * Transferable xfer = new TransferableObject( fetcher );
- * ...
- *
- *
- * The {@link java.awt.datatransfer.DataFlavor} associated with
- * {@link TransferableObject} has the representation class
- * {@code net.iharder.dnd.TransferableObject.class} and MIME type
- * {@code application/x-net.iharder.dnd.TransferableObject}. This data
- * flavor is accessible via the static {@link #DATA_FLAVOR} property.
- *
- *
- *
- * I'm releasing this code into the Public Domain. Enjoy.
- *
- *
- * @author Robert Harder
- * @author rob@iharder.net
- * @version 1.2
- */
- static class TransferableObject implements
- java.awt.datatransfer.Transferable {
- /**
- * The MIME type for {@link #DATA_FLAVOR} is
- * {@code application/x-net.iharder.dnd.TransferableObject}.
- *
- * @since 1.1
- */
- public final static String MIME_TYPE = "application/x-net.iharder.dnd.TransferableObject";
-
- /**
- * The default {@link java.awt.datatransfer.DataFlavor} for
- * {@link TransferableObject} has the representation class
- * {@code net.iharder.dnd.TransferableObject.class} and the MIME type
- * {@code application/x-net.iharder.dnd.TransferableObject}.
- *
- * @since 1.1
- */
- public final static java.awt.datatransfer.DataFlavor DATA_FLAVOR = new java.awt.datatransfer.DataFlavor(
- FileDrop.TransferableObject.class, MIME_TYPE);
+ Highlight(final Color color) {
+ this.color = color;
+ setOpaque(false);
+ setFocusable(false);
+ }
- private Fetcher fetcher;
- private Object data;
+ // Let mouse events (and drop target lookups) go through
+ @Override
+ public boolean contains(final int x, final int y) {
+ return false;
+ }
- private java.awt.datatransfer.DataFlavor customFlavor;
+ @Override
+ protected void paintComponent(final Graphics g) {
+ final int w = getWidth();
+ final int h = getHeight();
+ g.setColor(color);
+ g.fillRect(0, 0, w, THICKNESS);
+ g.fillRect(0, h - THICKNESS, w, THICKNESS);
+ g.fillRect(0, THICKNESS, THICKNESS, h - 2 * THICKNESS);
+ g.fillRect(w - THICKNESS, THICKNESS, THICKNESS, h - 2 * THICKNESS);
+ }
+ }
- /**
- * Creates a new {@link TransferableObject} that wraps data.
- * Along with the {@link #DATA_FLAVOR} associated with this class, this
- * creates a custom data flavor with a representation class determined
- * from data.getClass() and the MIME type
- * {@code application/x-net.iharder.dnd.TransferableObject}.
- *
- * @param data
- * The data to transfer
- * @since 1.1
- */
- public TransferableObject(final Object data) {
- this.data = data;
- this.customFlavor = new java.awt.datatransfer.DataFlavor(
- data.getClass(), MIME_TYPE);
- } // end constructor
+ private static final class Installed {
- /**
- * Creates a new {@link TransferableObject} that will return the object
- * that is returned by fetcher. No custom data flavor is set
- * other than the default {@link #DATA_FLAVOR}.
- *
- * @see Fetcher
- * @param fetcher
- * The {@link Fetcher} that will return the data object
- * @since 1.1
- */
- public TransferableObject(final Fetcher fetcher) {
- this.fetcher = fetcher;
- } // end constructor
+ final Component component;
+ final DropTarget previous;
+ final DropTarget ours;
- /**
- * Creates a new {@link TransferableObject} that will return the object
- * that is returned by fetcher. Along with the
- * {@link #DATA_FLAVOR} associated with this class, this creates a
- * custom data flavor with a representation class dataClass
- * and the MIME type
- * {@code application/x-net.iharder.dnd.TransferableObject}.
- *
- * @see Fetcher
- * @param dataClass
- * The {@link java.lang.Class} to use in the custom data
- * flavor
- * @param fetcher
- * The {@link Fetcher} that will return the data object
- * @since 1.1
- */
- public TransferableObject(final Class> dataClass, final Fetcher fetcher) {
- this.fetcher = fetcher;
- this.customFlavor = new java.awt.datatransfer.DataFlavor(dataClass,
- MIME_TYPE);
- } // end constructor
-
- /**
- * Returns the custom {@link java.awt.datatransfer.DataFlavor}
- * associated with the encapsulated object or {@code null} if the
- * {@link Fetcher} constructor was used without passing a
- * {@link java.lang.Class}.
- *
- * @return The custom data flavor for the encapsulated object
- * @since 1.1
- */
- public java.awt.datatransfer.DataFlavor getCustomDataFlavor() {
- return customFlavor;
- } // end getCustomDataFlavor
+ Installed(final Component component, final DropTarget previous,
+ final DropTarget ours)
+ {
+ this.component = component;
+ this.previous = previous;
+ this.ours = ours;
+ }
+ }
- /* ******** T R A N S F E R A B L E M E T H O D S ******** */
+ private final class Handler extends DropTargetAdapter {
- /**
- * Returns a two- or three-element array containing first the custom
- * data flavor, if one was created in the constructors, second the
- * default {@link #DATA_FLAVOR} associated with
- * {@link TransferableObject}, and third the
- * {@link java.awt.datatransfer.DataFlavor#stringFlavor}.
- *
- * @return An array of supported data flavors
- * @since 1.1
- */
@Override
- public java.awt.datatransfer.DataFlavor[] getTransferDataFlavors() {
- if (customFlavor != null)
- return new java.awt.datatransfer.DataFlavor[] { customFlavor,
- DATA_FLAVOR,
- java.awt.datatransfer.DataFlavor.stringFlavor }; // end
- // flavors
- // array
- else
- return new java.awt.datatransfer.DataFlavor[] { DATA_FLAVOR,
- java.awt.datatransfer.DataFlavor.stringFlavor }; // end
- // flavors
- // array
- } // end getTransferDataFlavors
+ public void dragEnter(final DropTargetDragEvent evt) {
+ if (target.isEnabled() && isDragOk(evt.getCurrentDataFlavors())) {
+ showHighlight();
+ evt.acceptDrag(DnDConstants.ACTION_COPY);
+ }
+ else {
+ evt.rejectDrag();
+ }
+ }
- /**
- * Returns the data encapsulated in this {@link TransferableObject}. If
- * the {@link Fetcher} constructor was used, then this is when the
- * {@link Fetcher#getObject getObject()} method will be called. If the
- * requested data flavor is not supported, then the
- * {@link Fetcher#getObject getObject()} method will not be called.
- *
- * @param flavor
- * The data flavor for the data to return
- * @return The dropped data
- * @since 1.1
- */
@Override
- public Object getTransferData(final java.awt.datatransfer.DataFlavor flavor)
- throws java.awt.datatransfer.UnsupportedFlavorException,
- java.io.IOException {
- // Native object
- if (flavor.equals(DATA_FLAVOR))
- return fetcher == null ? data : fetcher.getObject();
-
- // String
- if (flavor.equals(java.awt.datatransfer.DataFlavor.stringFlavor))
- return fetcher == null ? data.toString() : fetcher.getObject()
- .toString();
-
- // We can't do anything else
- throw new java.awt.datatransfer.UnsupportedFlavorException(flavor);
- } // end getTransferData
+ public void dropActionChanged(final DropTargetDragEvent evt) {
+ if (target.isEnabled() && isDragOk(evt.getCurrentDataFlavors())) evt
+ .acceptDrag(DnDConstants.ACTION_COPY);
+ else evt.rejectDrag();
+ }
- /**
- * Returns {@code true} if flavor is one of the supported
- * flavors. Flavors are supported using the equals(...)
- * method.
- *
- * @param flavor
- * The data flavor to check
- * @return Whether or not the flavor is supported
- * @since 1.1
- */
@Override
- public boolean isDataFlavorSupported(
- final java.awt.datatransfer.DataFlavor flavor) {
- // Native object
- if (flavor.equals(DATA_FLAVOR))
- return true;
-
- // String
- if (flavor.equals(java.awt.datatransfer.DataFlavor.stringFlavor))
- return true;
+ public void dragExit(final DropTargetEvent evt) {
+ hideHighlight();
+ }
- // We can't do anything else
- return false;
- } // end isDataFlavorSupported
+ @Override
+ public void drop(final DropTargetDropEvent evt) {
+ boolean accepted = false;
+ try {
+ final Transferable tr = evt.getTransferable();
+ final boolean fileList = tr.isDataFlavorSupported(
+ DataFlavor.javaFileListFlavor);
+ final DataFlavor uriFlavor = fileList ? null : findUriListFlavor(tr);
+ if (!fileList && uriFlavor == null) {
+ LOGGER.fine("Not a file list or uri list, aborting");
+ evt.rejectDrop();
+ return;
+ }
+ evt.acceptDrop(DnDConstants.ACTION_COPY);
+ accepted = true;
+ final File[] files = fileList ? readFileList(tr) : readUriList(
+ uriFlavor, tr);
+ evt.dropComplete(files.length > 0);
+ // Dispatch after the drop completes so that the drag source (e.g.,
+ // the OS file browser) is not blocked by dialogs or long tasks
+ if (files.length > 0) SwingUtilities.invokeLater(() -> notifyListener(
+ files));
+ } catch (final IOException | UnsupportedFlavorException
+ | RuntimeException ex)
+ {
+ LOGGER.log(Level.WARNING, "Drop aborted", ex);
+ if (accepted) evt.dropComplete(false);
+ else evt.rejectDrop();
+ } finally {
+ hideHighlight();
+ }
+ }
+ }
- /* ******** I N N E R I N T E R F A C E F E T C H E R ******** */
+ /**
+ * Implement this interface to listen for when files are dropped.
+ */
+ @FunctionalInterface
+ public interface Listener {
/**
- * Instead of passing your data directly to the
- * {@link TransferableObject} constructor, you may want to know exactly
- * when your data was received in case you need to remove it from its
- * source (or do anyting else to it). When the {@link #getTransferData
- * getTransferData(...)} method is called on the
- * {@link TransferableObject}, the {@link Fetcher}'s {@link #getObject
- * getObject()} method will be called.
+ * Called on the Event Dispatch Thread when files have been successfully
+ * dropped.
*
- * @author Robert Harder
- * @version 1.1
- * @since 1.1
+ * @param files the (non-empty) array of files that were dropped
*/
- public static interface Fetcher {
- /**
- * Return the object being encapsulated in the
- * {@link TransferableObject}.
- *
- * @return The dropped object
- * @since 1.1
- */
- public abstract Object getObject();
- } // end inner interface Fetcher
-
- } // end class TransferableObject
-
-} // end class FileDrop
+ void filesDropped(File[] files);
+
+ }
+
+}
\ No newline at end of file
diff --git a/src/main/java/org/scijava/ui/swing/script/FileFunctions.java b/src/main/java/org/scijava/ui/swing/script/FileFunctions.java
index e8d4fbb8..5978d4a0 100644
--- a/src/main/java/org/scijava/ui/swing/script/FileFunctions.java
+++ b/src/main/java/org/scijava/ui/swing/script/FileFunctions.java
@@ -372,7 +372,7 @@ public String firstNLines(final String text, int maxLineCount) {
" more line" + (count > 1 ? "s" : "") + ")...\n";
}
- public class LengthWarner implements DocumentListener {
+ public static class LengthWarner implements DocumentListener {
protected int width;
protected JTextComponent component;
@@ -404,7 +404,7 @@ public void updateColor() {
}
}
- public class TextWrapper implements DocumentListener {
+ public static class TextWrapper implements DocumentListener {
protected int width;
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 119101bb..275cc646 100644
--- a/src/main/java/org/scijava/ui/swing/script/FileSystemTree.java
+++ b/src/main/java/org/scijava/ui/swing/script/FileSystemTree.java
@@ -28,579 +28,967 @@
*/
package org.scijava.ui.swing.script;
-import java.awt.Component;
-import java.awt.event.KeyAdapter;
-import java.awt.event.KeyEvent;
+import com.formdev.flatlaf.icons.FlatAbstractIcon;
+import com.formdev.flatlaf.icons.FlatOptionPaneErrorIcon;
+import org.scijava.log.Logger;
+
+import javax.swing.*;
+import javax.swing.event.TreeExpansionEvent;
+import javax.swing.event.TreeWillExpandListener;
+import javax.swing.tree.*;
+import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
-import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
-import java.nio.file.FileSystems;
-import java.nio.file.Path;
-import java.nio.file.StandardWatchEventKinds;
-import java.nio.file.WatchEvent;
-import java.nio.file.WatchKey;
-import java.nio.file.WatchService;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.Map;
-import java.util.regex.Pattern;
-
-import javax.swing.Icon;
-import javax.swing.ImageIcon;
-import javax.swing.JTree;
-import javax.swing.SwingUtilities;
-import javax.swing.event.TreeExpansionEvent;
-import javax.swing.event.TreeWillExpandListener;
-import javax.swing.tree.DefaultMutableTreeNode;
-import javax.swing.tree.DefaultTreeCellRenderer;
-import javax.swing.tree.DefaultTreeModel;
-import javax.swing.tree.ExpandVetoException;
-import javax.swing.tree.TreePath;
-import javax.swing.tree.TreeSelectionModel;
-
-import org.scijava.log.Logger;
+import java.nio.file.*;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.*;
+import java.util.List;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.CopyOnWriteArraySet;
+import java.util.function.BooleanSupplier;
+import java.util.function.Consumer;
/**
- *
- * @author Albert Cardona
+ * A tree listing the contents of one or more top-level folders. Folders are
+ * listed when expanded, and kept in sync with the file system while expanded.
+ * Folder and file icons are the ones defined by the look and feel (
+ * {@code Tree.openIcon}, {@code Tree.closedIcon}, {@code Tree.leafIcon}).
*
+ * @author Albert Cardona
*/
-public class FileSystemTree extends JTree
-{
- static private String withSlash(String path) {
- path = path.replace('\\', '/'); // compatible with Windows
- return '/' == path.charAt(path.length()-1) ? path : path + "/";
- }
-
- static private final Icon makeErrorIcon() {
- final int[] pixels = new int[]{16777215, 16777215, 16777215, 16777215, 16777215, 16776958, 16772075, 16761281, 16751001, 16744833, 16744833,
- 16751001, 16761281, 16772075, 16776958, 16777215, 16777215, 16777215, 16777215, 16777215, 16777215, 16777215, 16777215, 16777215,
- 16772075, 16749973, 16728128, 16726586, 16734553, 16742520, 16742520, 16734553, 16726586, 16728128, 16749973, 16772075, 16777215,
- 16777215, 16777215, 16777215, 16777215, 16777215, 16776958, 16764365, 16731212, 16728385, 16754599, 16770790, 16774902, 16774131,
- 16774131, 16774131, 16770790, 16754599, 16728385, 16731212, 16764365, 16776958, 16777215, 16777215, 16777215, 16777215, 16764365,
- 16726072, 16739436, 16770276, 16777215, 16777215, 16757169, 16727871, 16727614, 16747660, 16776958, 16777215, 16770276, 16739436,
- 16726072, 16764365, 16777215, 16777215, 16777215, 16772075, 16731212, 16739436, 16773874, 16777215, 16777215, 16777215, 16750744,
- 16711937, 16711680, 16738151, 16776958, 16777215, 16777215, 16773874, 16739436, 16731212, 16772075, 16777215, 16776958, 16749973,
- 16728385, 16770276, 16777215, 16777215, 16777215, 16777215, 16750744, 16711937, 16711680, 16738151, 16776958, 16777215, 16777215,
- 16777215, 16770276, 16728385, 16749973, 16776958, 16772075, 16728128, 16754599, 16777215, 16777215, 16777215, 16777215, 16777215,
- 16750744, 16711937, 16711680, 16738151, 16776958, 16777215, 16777215, 16777215, 16777215, 16754599, 16728128, 16772075, 16761281,
- 16726586, 16770790, 16777215, 16777215, 16777215, 16777215, 16777215, 16750744, 16711937, 16711680, 16738151, 16776958, 16777215,
- 16777215, 16777215, 16777215, 16770790, 16726586, 16761281, 16751001, 16734553, 16775930, 16777215, 16777215, 16777215, 16777215,
- 16777215, 16750744, 16711937, 16711680, 16738151, 16776958, 16777215, 16777215, 16777215, 16777215, 16775930, 16734553, 16751001,
- 16744833, 16742520, 16777215, 16777215, 16777215, 16777215, 16777215, 16777215, 16750744, 16711937, 16711680, 16738151, 16776958,
- 16777215, 16777215, 16777215, 16777215, 16777215, 16742520, 16744833, 16744833, 16742520, 16777215, 16777215, 16777215, 16777215,
- 16777215, 16777215, 16750744, 16711937, 16711680, 16738151, 16776958, 16777215, 16777215, 16777215, 16777215, 16777215, 16742520,
- 16744833, 16751001, 16734553, 16775930, 16777215, 16777215, 16777215, 16777215, 16777215, 16750744, 16711937, 16711680, 16738151,
- 16776958, 16777215, 16777215, 16777215, 16777215, 16775930, 16734553, 16751001, 16761281, 16726586, 16770790, 16777215, 16777215,
- 16777215, 16777215, 16777215, 16751772, 16715021, 16714507, 16739950, 16776958, 16777215, 16777215, 16777215, 16777215, 16770790,
- 16726586, 16761281, 16772075, 16728128, 16754599, 16777215, 16777215, 16777215, 16777215, 16777215, 16770790, 16760767, 16760510,
- 16767706, 16777215, 16777215, 16777215, 16777215, 16777215, 16754599, 16728128, 16772075, 16776958, 16749973, 16728385, 16770276,
- 16777215, 16777215, 16777215, 16777215, 16773360, 16745604, 16738665, 16767192, 16777215, 16777215, 16777215, 16777215, 16770276,
- 16728385, 16749973, 16776958, 16777215, 16772075, 16731212, 16739436, 16773874, 16777215, 16777215, 16777215, 16759996, 16714764,
- 16711937, 16743291, 16776958, 16777215, 16777215, 16773874, 16739436, 16731212, 16772075, 16777215, 16777215, 16777215, 16764365,
- 16726072, 16739436, 16770276, 16777215, 16777215, 16766164, 16723502, 16717848, 16753571, 16777215, 16777215, 16770276, 16739436,
- 16726072, 16764365, 16777215, 16777215, 16777215, 16777215, 16776958, 16764365, 16731212, 16728385, 16754599, 16770790, 16775416,
- 16767963, 16764879, 16774131, 16770790, 16754599, 16728385, 16731212, 16764365, 16776958, 16777215, 16777215, 16777215, 16777215,
- 16777215, 16777215, 16772075, 16749973, 16728128, 16726586, 16734553, 16742520, 16742520, 16734553, 16726586, 16728128, 16749973,
- 16772075, 16777215, 16777215, 16777215, 16777215, 16777215, 16777215, 16777215, 16777215, 16777215, 16776958, 16772075, 16761281,
- 16751001, 16744833, 16744833, 16751001, 16761281, 16772075, 16776958, 16777215, 16777215, 16777215, 16777215, 16777215};
- final BufferedImage image = new BufferedImage(20, 20, BufferedImage.TYPE_INT_ARGB);
- image.setRGB(0, 0, 20, 20, pixels, 0, 20);
- return new ImageIcon(image);
- }
-
- static public final Icon ICON_ERROR = makeErrorIcon();
-
- public class Node extends DefaultMutableTreeNode
- {
- final private String path;
- private Icon icon = null;
+public class FileSystemTree extends JTree {
+
+ private static final int MAX_SCANNED = 200_000;
+ /** Searches stop at this many matches: more cannot be digested by the tree (or the user) */
+ private static final int MAX_HITS = 1000;
+ /** Max. no. of folders expanded automatically to reveal hits (each expansion lists a folder on the EDT) */
+ private static final int MAX_AUTO_EXPAND = 100;
+ private int expand_budget;
+ /** Max. no. of entries listed for a single folder (the rest is reported, not listed) */
+ private static final int MAX_LISTED = 1000;
+
+ /**
+ * Folders (matched by the end of their name, case-insensitively) that hold huge numbers of
+ * files, e.g., chunked image volumes. Searches match them by name but never look inside.
+ * Editable through {@link #setOpaqueFolders(Collection)}
+ */
+ private final Set opaque_folders = new CopyOnWriteArraySet<>(List.of(".zarr", ".n5", "node_modules"));
+ private Consumer notice_listener;
+ private int last_skipped; // opaque folders left out of the last search
+ private boolean expanded_only; // search expanded folders only, regardless of search_collapsed
+ private boolean last_hit_cap; // last search stopped at MAX_HITS
+ private boolean last_capped; // last search revealed more folders than were expanded
+
+ /**
+ * Whether a file or folder is hidden. Besides names starting with a dot, folders
+ * can be flagged as hidden by the OS (e.g., ~/Library on macOS, AppData on Windows).
+ * Top-level folders are never subject to this check: hidden folders can still be
+ * listed if chosen/dragged manually.
+ */
+ private static boolean isHidden(final File f) {
+ if (f.isHidden()) return true;
+ if (!f.isDirectory()) return false;
+ try {
+ return Files.isHidden(f.toPath());
+ } catch (final IOException | RuntimeException ignored) {
+ return false;
+ }
+ }
+
+ private static String withSlash(final String path) {
+ final String p = path.replace('\\', '/'); // compatible with Windows
+ return p.endsWith("/") ? p : p + "/";
+ }
+
+ public class Node extends DefaultMutableTreeNode {
+
+ private final String path;
+ private final boolean directory;
+ private boolean failed;
+ // True if this node lists everything (it is in, or below, a folder matching the filter)
+ private boolean showAll;
+ private int omitted; // entries not listed because the folder is too large
public Node(final String path) {
this.path = withSlash(path);
+ this.directory = new File(this.path).isDirectory();
}
public boolean isDirectory() {
- return new File(this.path).isDirectory();
+ return directory;
}
/**
- * @param sort whether result should be sorted
- * @param file_filter Applies to leafs, not to directories.
- * @return the array denoting children files
+ * Lists the visible children. Unless pruning (see
+ * {@link FileSystemTree#setFileFilter(FileFilter, boolean)}), directories are
+ * not subject to filtering
*/
- public File[] updatedChildrenFiles(final boolean sort, final FileFilter file_filter) {
- final File file = new File(this.path);
- if (!file.isDirectory()) {
- return new File[0];
- }
- final File[] files = file.listFiles(new FileFilter() {
- @Override
- public boolean accept(final File f) {
- return !f.isHidden() && !f.getName().endsWith("~")
- && !re_ignored_extensions.matcher(f.getName()).matches()
- && (f.isDirectory() || file_filter.accept(f));
- }
+ private File[] listChildren() {
+ final Prune p = prune;
+ final boolean all = p != null && listsAll(p);
+ File[] files = new File(path).listFiles(f -> {
+ if (isHidden(f) || f.getName().endsWith("~") || isIgnored(f.getName())) return false;
+ if (p == null) return f.isDirectory() || file_filter.accept(f);
+ if (all) return true;
+ return f.isDirectory() ? p.keep.contains(withSlash(f.getAbsolutePath())) : file_filter.accept(f);
});
- if (sort) Arrays.sort(files);
+ if (files != null) Arrays.sort(files);
+ omitted = (files != null && files.length > MAX_LISTED) ? files.length - MAX_LISTED : 0;
+ if (omitted > 0) files = Arrays.copyOf(files, MAX_LISTED);
return files;
}
- /**
- * If it's a directory, add a Node for each of its visible files.
- *
- * @param model the tree model
- * @param file_filter Applies to leafs, not to directories.
- */
- public synchronized void populateChildren(final DefaultTreeModel model, final FileFilter file_filter) {
- try {
- if (isLeaf()) return;
- int index = 0;
- for (final File file : updatedChildrenFiles(true, file_filter)) {
- // Can't use add: would try to insert at getChildCount(), which is the wrong value here
- model.insertNodeInto(new Node(file.getAbsolutePath()), this, index++);
- }
- icon = null;
- } catch (Throwable t) {
- icon = ICON_ERROR;
- log.error("Failed to populate folder " + this.path, t);
- }
+ private boolean listsAll(final Prune p) {
+ return showAll || p.full.contains(path);
}
- /**
- * Recursive expansion until opening the final element of the path
- * @param path The absolute file path.
- * @param full A single-slot array containing the full path, if any.
- */
- public void expandTo(final String path, final TreePath[] full) {
- if (path.startsWith(this.path)) {
- final LinkedList stack = new LinkedList<>();
- stack.add(this);
- while (true) {
- final Node node = stack.removeFirst();
- if (path.startsWith(node.path)) {
- for (int i=0, count=node.getChildCount(); i 0 && notice_listener != null) notice_listener
+ .accept("Showing the first " + MAX_LISTED + " of " + (MAX_LISTED + omitted) + " items in "
+ + new File(path).getName());
+ final int first = getChildCount();
+ final int[] indices = new int[files.length];
+ final boolean all = prune != null && listsAll(prune);
+ for (int i = 0; i < files.length; i++) {
+ final Node child = new Node(files[i].getAbsolutePath());
+ child.showAll = all;
+ add(child);
+ indices[i] = first + i;
}
+ getModel().nodesWereInserted(this, indices);
}
- @Override
- public String toString() {
- return this.path;
+ private void clear() {
+ final int n = getChildCount();
+ if (n == 0) return;
+ final int[] indices = new int[n];
+ final Object[] removed = new Object[n];
+ for (int i = 0; i < n; i++) {
+ indices[i] = i;
+ removed[i] = getChildAt(i);
+ }
+ removeAllChildren();
+ getModel().nodesWereRemoved(this, indices, removed);
}
@Override
- public synchronized int getChildCount() {
- return super.getChildCount();
+ public String toString() {
+ return path;
}
@Override
- public synchronized Node getChildAt(final int index) {
- if (0 == getChildCount()) return null;
- try {
- return (Node) super.getChildAt(index);
- } catch (ArrayIndexOutOfBoundsException ae) {
- log.error("FileSystemTree: no child at index " + index + " for file at " + this.path, ae);
- return null;
- }
- }
-
- public Icon getIcon() {
- return this.icon;
+ public Node getChildAt(final int index) {
+ return (Node) super.getChildAt(index);
}
@Override
public Object getUserObject() {
- return this.path;
+ return path;
}
@Override
public boolean isLeaf() {
- return !isRoot() && !this.isDirectory();
+ return !isRoot() && !directory;
}
+ }
- public synchronized void removeAllChildren(final DefaultTreeModel model) {
- for (int i=super.getChildCount() -1; i>-1; --i) {
- // Can't use DefaultMutableTreeNode.removeAllChildren or .remove(int): the model is not notified
- model.removeNodeFromParent((Node)super.getChildAt(i));
- }
+ /** Paths found by a scan of the top-level folders for files/folders accepted by a filter */
+ private static final class Prune {
+
+ final Set keep = new HashSet<>(); // folders to display
+ final Set full = new HashSet<>(); // folders whose name matches: display their whole content
+ int hits;
+ int skipped; // opaque folders not searched
+ boolean hitCap; // stopped at MAX_HITS
+ boolean truncated;
+
+ Prune copy() {
+ final Prune c = new Prune();
+ c.keep.addAll(keep);
+ c.full.addAll(full);
+ c.hits = hits;
+ c.skipped = skipped;
+ c.hitCap = hitCap;
+ c.truncated = truncated;
+ return c;
}
+ }
- public synchronized void updateChildrenList(final DefaultTreeModel model, final FileFilter file_filter) {
- removeAllChildren(model);
- populateChildren(model, file_filter);
- }
+ /** Notified when a filter has been applied */
+ public interface FilterListener {
+
+ /**
+ * @param hits the number of matches so far, or -1 if folders are not being hidden
+ * @param truncated whether the search stopped before covering all folders
+ * @param done false while the search is still running (results are streamed)
+ */
+ void filterApplied(int hits, boolean truncated, boolean done);
}
public interface LeafListener {
- public void leafDoubleClicked(final File file);
+
+ void leafDoubleClicked(final File file);
}
final Logger log;
-
- private ArrayList leaf_listeners = new ArrayList<>();
-
- private final DirectoryWatcher dir_watcher = new DirectoryWatcher();
-
- private final HashSet ignored_extensions = new HashSet<>();
- private Pattern re_ignored_extensions = Pattern.compile("^.*$", Pattern.CASE_INSENSITIVE); // match all
- private FileFilter file_filter = ((f) -> true);
-
- public FileSystemTree(final Logger log)
- {
+ private final List leaf_listeners = new CopyOnWriteArrayList<>();
+ private final DirectoryWatcher dir_watcher;
+ private final Set ignored_extensions = new HashSet<>(); // lower case
+ private FileFilter file_filter = f -> true;
+ // Filtering that hides folders without hits: state of the last completed scan
+ private boolean prune_active;
+ private Prune prune;
+ private Set saved_expansion; // expanded folders before pruning started
+ private final TreeMap hidden_tops = new TreeMap<>(); // top-level folders without hits
+ private SwingWorker scanner;
+ private boolean scanning;
+ private boolean search_collapsed = true;
+ private boolean live_updates = true;
+ private volatile long publish_interval_nanos = 300_000_000L;
+ private FilterListener filter_listener;
+ // Set by FileSystemTreePanel, released in destroy()
+ FileDrop fileDrop;
+
+ public FileSystemTree(final Logger log) {
this.log = log;
+ dir_watcher = new DirectoryWatcher();
setModel(new DefaultTreeModel(new Node("#root#")));
setRootVisible(false);
+ setShowsRootHandles(true);
getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
- setAutoscrolls(true);
- setScrollsOnExpand(true);
- setExpandsSelectedPaths(true);
+ ToolTipManager.sharedInstance().registerComponent(this);
+ final FlatAbstractIcon errorIcon = new FlatOptionPaneErrorIcon();
+ errorIcon.setScale(.35f);
+ // FlatLaf does not assign node icons by default, but defines them
+ setCellRenderer(new DefaultTreeCellRenderer() {
+
+ @Override
+ public Component getTreeCellRendererComponent(final JTree tree, final Object value, final boolean selected,
+ final boolean expanded, final boolean leaf, final int row, final boolean hasFocus) {
+ super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
+ final String key = leaf ? "Tree.leafIcon" : (expanded ? "Tree.openIcon" : "Tree.closedIcon");
+ setIcon(((Node) value).failed ? errorIcon : UIManager.getIcon(key));
+ return this;
+ }
+ });
addTreeWillExpandListener(new TreeWillExpandListener() {
+
@Override
- public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException {
- final Node node = ((Node)event.getPath().getLastPathComponent());
- node.populateChildren(getModel(), file_filter);
- dir_watcher.register(node);
+ public void treeWillExpand(final TreeExpansionEvent event) {
+ final Node node = (Node) event.getPath().getLastPathComponent();
+ node.populate();
+ if (live_updates && !prune_active) dir_watcher.register(node); // no watchers for transient, filtered listings
}
@Override
- public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException {
- final Node node = ((Node)event.getPath().getLastPathComponent());
- node.removeAllChildren(getModel());
- dir_watcher.unregister(node);
+ public void treeWillCollapse(final TreeExpansionEvent event) {
+ final Node node = (Node) event.getPath().getLastPathComponent();
+ for (final Enumeration> e = node.depthFirstEnumeration(); e.hasMoreElements();)
+ dir_watcher.unregister((Node) e.nextElement());
+ node.clear();
}
});
addMouseListener(new MouseAdapter() {
+
@Override
public void mousePressed(final MouseEvent me) {
+ if (me.getClickCount() != 2) return;
final TreePath path = getPathForLocation(me.getX(), me.getY());
- if (null == path) return;
+ if (path == null) return;
final Node node = (Node) path.getLastPathComponent();
- if (2 == me.getClickCount()) {
- if (node.isLeaf() && !node.isDirectory()) { // do not accept empty directories as leafs
- for (final LeafListener l : leaf_listeners) l.leafDoubleClicked(new File(node.path));
- }
- }
- }
- });
- addKeyListener(new KeyAdapter() {
- @Override
- public void keyPressed(final KeyEvent ke) {
- if (KeyEvent.VK_DELETE == ke.getKeyCode()) {
- removeSelectionPaths(getSelectionPaths());
+ if (!node.isDirectory()) {
+ final File file = new File(node.path);
+ leaf_listeners.forEach(l -> l.leafDoubleClicked(file));
}
}
});
- setCellRenderer(new DefaultTreeCellRenderer() {
- @Override
- public Component getTreeCellRendererComponent(final JTree tree, final Object value, final boolean selected,
- final boolean expanded, final boolean leaf, final int row, final boolean hasFocus) {
- super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
- final Node node = (Node) value;
- setText(new File(node.path).getName());
- if (node.isDirectory()) {
- setToolTipText(node.path);
- if (null != node.icon) setIcon(node.icon);
- else if (expanded) setIcon(openIcon);
- else setIcon(closedIcon);
- } else {
- setIcon(leafIcon);
- }
- return this;
+ }
+
+ /**
+ * Folders are emptied when collapsed (and listed again when expanded). The
+ * default implementation would remember that a collapsed folder was expanded
+ * before, and since it has no children, would not paint its expand handle.
+ */
+ @Override
+ public boolean hasBeenExpanded(final TreePath path) {
+ return isExpanded(path);
+ }
+
+ @Override
+ public DefaultTreeModel getModel() {
+ return (DefaultTreeModel) super.getModel();
+ }
+
+ private Node root() {
+ return (Node) getModel().getRoot();
+ }
+
+ @Override
+ public String convertValueToText(final Object value, final boolean selected, final boolean expanded,
+ final boolean leaf, final int row, final boolean hasFocus) {
+ // NB: the JTree constructor calls this with its default model
+ if (!(value instanceof Node)) return super.convertValueToText(value, selected, expanded, leaf, row, hasFocus);
+ return new File(((Node) value).path).getName();
+ }
+
+ @Override
+ public String getToolTipText(final MouseEvent e) {
+ final TreePath path = getPathForLocation(e.getX(), e.getY());
+ return (path == null) ? null : ((Node) path.getLastPathComponent()).path;
+ }
+
+ @Override
+ protected void paintComponent(final Graphics g) {
+ super.paintComponent(g);
+ // Plain hints while the tree is empty (no content, or all folders hidden by the filter)
+ if (root().getChildCount() > 0) return;
+ final String[] lines = hidden_tops.isEmpty() ? new String[] { "Drag folders here", "or right-click for options" }
+ : new String[] { scanning ? "Searching..." : "No matches" };
+ final java.awt.Graphics2D g2 = (java.awt.Graphics2D) g.create();
+ try {
+ g2.setRenderingHint(java.awt.RenderingHints.KEY_TEXT_ANTIALIASING,
+ java.awt.RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
+ g2.setColor(TextEditor.GuiUtils.secondaryColor());
+ final java.awt.FontMetrics fm = g2.getFontMetrics();
+ int y = (getHeight() - fm.getHeight() * lines.length) / 2 + fm.getAscent();
+ for (final String line : lines) {
+ g2.drawString(line, (getWidth() - fm.stringWidth(line)) / 2, y);
+ y += fm.getHeight();
}
- });
- setVisible(true);
+ } finally {
+ g2.dispose();
+ }
}
/**
* Add a file name extension to ignore, without the dot, for example "class".
- * Files whose name have this extension will not be listed as leaves in the tree.
- *
+ * Files whose name have this extension will not be listed.
+ *
* @param extension The file name extension to ignore, e.g. "class".
* @return true if the extension wasn't there already.
*/
public boolean ignoreExtension(final String extension) {
- if (this.ignored_extensions.add(extension)) {
- updateIgnoreExtensionPattern();
- return true;
- }
- return false;
+ return ignored_extensions.add(extension.toLowerCase());
}
- /** Opposite of {@link #ignoreExtension(String)}.
- *
+ /**
+ * Opposite of {@link #ignoreExtension(String)}.
+ *
* @param extension The file name extension to stop ignoring, e.g. "class".
- * @return true if the extension wasn't there already.
+ * @return true if the extension was being ignored.
*/
public boolean showExtension(final String extension) {
- if (this.ignored_extensions.remove(extension)) {
- updateIgnoreExtensionPattern();
- return true;
- }
- return false;
+ return ignored_extensions.remove(extension.toLowerCase());
}
- private void updateIgnoreExtensionPattern() {
- if (this.ignored_extensions.isEmpty()) {
- this.re_ignored_extensions = Pattern.compile("^.*$", Pattern.CASE_INSENSITIVE);
- } else {
- StringBuilder s = new StringBuilder("^.*\\.(");
- s.append(String.join("|", this.ignored_extensions.toArray(new String[this.ignored_extensions.size()])));
- s.append(")$");
- this.re_ignored_extensions = Pattern.compile(s.toString(), Pattern.CASE_INSENSITIVE);
- }
+ private boolean isIgnored(final String name) {
+ final int dot = name.lastIndexOf('.');
+ return dot >= 0 && ignored_extensions.contains(name.substring(dot + 1).toLowerCase());
}
-
+
+ /**
+ * Sets the filter applied to files (not folders). Expanded folders are
+ * re-listed
+ *
+ * @param file_filter the filter
+ */
public void setFileFilter(final FileFilter file_filter) {
+ setFileFilter(file_filter, false);
+ }
+
+ /**
+ * Sets the filter applied to files. If {@code pruneFolders} is true, folders
+ * are filtered too: all folders are searched in the background and only
+ * those leading to files accepted by the filter are listed (and expanded).
+ * Folders accepted by the filter are listed with all of their content.
+ * Top-level folders without hits are hidden, and restored once the filter is
+ * lifted.
+ *
+ * @param file_filter the filter
+ * @param pruneFolders whether folders without hits should be hidden
+ * @see #setFilterListener(FilterListener)
+ */
+ public void setFileFilter(final FileFilter file_filter, final boolean pruneFolders) {
+ cancelFilterScan();
this.file_filter = file_filter;
- updateRecursively(file_filter);
- }
-
- private void updateRecursively(final FileFilter file_filter) {
- // Find expanded directories
- final ArrayList stack = new ArrayList<>();
- final Node root = (Node) this.getModel().getRoot();
- for (int i=root.getChildCount() -1; i>-1; --i) {
- stack.add((Node)root.getChildAt(i));
- }
- final ArrayList stack2 = new ArrayList<>(stack); // copy for second phase
- final HashSet expanded = new HashSet<>();
- while (!stack.isEmpty()) {
- final Node node = stack.remove(0);
- if (this.isExpanded(new TreePath(node.getPath()))) {
- expanded.add(node.path);
- for (int i=node.getChildCount() -1; i>-1; --i) {
- final Node child = node.getChildAt(i);
- if (child.isDirectory()) stack.add(child);
+ if (!pruneFolders) {
+ if (prune_active) {
+ prune_active = false;
+ rebuild(null);
+ } else {
+ final Node root = root();
+ for (int i = 0; i < root.getChildCount(); i++) {
+ final Node top = root.getChildAt(i);
+ if (isExpanded(new TreePath(top.getPath()))) refresh(top);
}
}
+ if (filter_listener != null) filter_listener.filterApplied(-1, false, true);
+ return;
}
- // Re-list all files, filtering
- while (!stack2.isEmpty()) {
- final Node node = stack2.remove(0);
- if (expanded.contains(node.path)) {
- node.removeAllChildren(this.getModel());
- node.populateChildren(this.getModel(), file_filter);
- final int count = node.getChildCount();
- if (count > 0) expandPath(new TreePath(node.getChildAt(0).getPath())); // awkward way to ensure parent is expanded
- for (int i=0; i tops = new ArrayList<>();
+ for (final Node top : allTops())
+ tops.add(top.path);
+ final Set onlyIn = (search_collapsed && !expanded_only) ? null : new HashSet<>(saved_expansion);
+ if (onlyIn != null) onlyIn.addAll(tops); // top-level folders are always searched, expanded or not
+ if (filter_listener != null) filter_listener.filterApplied(0, false, false);
+ scanner = new SwingWorker() {
+
+ @Override
+ protected Prune doInBackground() {
+ final Prune p = new Prune();
+ final long[] state = { 0, System.nanoTime() };
+ for (final String top : tops) {
+ if (isCancelled() || p.truncated || p.hitCap) break;
+ walk(Paths.get(top), file_filter, p, onlyIn, state, this::isCancelled, this::publish);
}
+ return p;
}
+
+ @Override
+ protected void process(final List chunks) {
+ if (!isCancelled() && scanner == this) rebuild(chunks.get(chunks.size() - 1), false);
+ }
+
+ @Override
+ protected void done() {
+ if (isCancelled() || scanner != this) return;
+ try {
+ scanning = false;
+ rebuild(get(), true);
+ } catch (final Exception e) {
+ log.error(e);
+ }
+ }
+ };
+ scanner.execute();
+ }
+
+ /**
+ * Whether the filter also searches folders that are not expanded (the default).
+ * If false, only folders that are currently expanded are searched, which is
+ * much faster for very large top-level folders.
+ */
+ public void setSearchCollapsedFolders(final boolean search) {
+ search_collapsed = search;
+ }
+
+ public boolean isSearchCollapsedFolders() {
+ return search_collapsed;
+ }
+
+ /** Stops a search triggered by {@link #setFileFilter(FileFilter, boolean)} that is still running */
+ public void cancelFilterScan() {
+ if (scanner != null) scanner.cancel(true);
+ scanner = null;
+ scanning = false;
+ }
+
+ /** The folders that searches do not look into (see {@link #setOpaqueFolders(Collection)}) */
+ public List getOpaqueFolders() {
+ return new ArrayList<>(opaque_folders);
+ }
+
+ /** Sets the folders that searches do not look into: endings of folder names, e.g., ".zarr" */
+ public void setOpaqueFolders(final Collection endings) {
+ opaque_folders.clear();
+ for (final String e : endings)
+ if (e != null && !e.trim().isEmpty()) opaque_folders.add(e.trim());
+ }
+
+ private boolean isOpaque(final Path dir) {
+ final Path name = dir.getFileName();
+ if (name == null) return false;
+ final String n = name.toString().toLowerCase();
+ for (final String e : opaque_folders)
+ if (n.endsWith(e.toLowerCase())) return true;
+ return false;
+ }
+
+ /** Whether the last search stopped at the maximum number of matches */
+ boolean isHitCapped() {
+ return last_hit_cap;
+ }
+
+ /**
+ * Restricts the next searches to expanded folders only (e.g., for very short queries),
+ * regardless of {@link #setSearchCollapsedFolders(boolean)}
+ */
+ void setExpandedOnly(final boolean expandedOnly) {
+ expanded_only = expandedOnly;
+ }
+
+ /** Number of folders left out of the last search because they are opaque */
+ int getSkippedFolderCount() {
+ return last_skipped;
+ }
+
+ /** Whether the last search found more folders to expand than the limit for automatic expansion */
+ boolean isExpansionCapped() {
+ return last_capped;
+ }
+
+ /** Sets the listener for messages such as folders listed partially (called on the EDT) */
+ void setNoticeListener(final Consumer listener) {
+ notice_listener = listener;
+ }
+
+ public void setFilterListener(final FilterListener listener) {
+ filter_listener = listener;
+ }
+
+ /** A folder being walked by {@link #walk} */
+ private static final class Frame {
+
+ final String path;
+ boolean found;
+
+ Frame(final String path) {
+ this.path = path;
+ }
+ }
+
+ /**
+ * Searches {@code top} recursively for files/folders accepted by the filter,
+ * recording the folders to display. Uses the attributes provided by the walk
+ * (no additional file system calls per entry). Periodically hands a snapshot of
+ * the findings to {@code publisher}, so that they can be displayed while the
+ * search is running.
+ *
+ * @param onlyIn if not null, only these folders are descended into
+ */
+ private void walk(final Path top, final FileFilter filter, final Prune p, final Set onlyIn, final long[] state,
+ final BooleanSupplier cancelled, final Consumer publisher) {
+ final boolean windows = File.separatorChar == '\\';
+ final List stack = new ArrayList<>();
+ try {
+ Files.walkFileTree(top, EnumSet.noneOf(FileVisitOption.class), Integer.MAX_VALUE,
+ new SimpleFileVisitor<>() {
+
+ private boolean first = true;
+
+ private boolean skipped(final Path path, final boolean dir) {
+ final Path name = path.getFileName();
+ if (name == null) return false;
+ final String n = name.toString();
+ if (n.endsWith("~") || isIgnored(n) || n.startsWith(".")) return true;
+ if (!dir && !windows) return false;
+ try {
+ return Files.isHidden(path);
+ } catch (final IOException ignored) {
+ return false;
+ }
+ }
+
+ private FileVisitResult tick() {
+ if (cancelled.getAsBoolean() || p.hitCap) return FileVisitResult.TERMINATE;
+ if (++state[0] > MAX_SCANNED) {
+ p.truncated = true;
+ return FileVisitResult.TERMINATE;
+ }
+ final long now = System.nanoTime();
+ if (now - state[1] > publish_interval_nanos) {
+ state[1] = now;
+ publisher.accept(p.copy());
+ }
+ return FileVisitResult.CONTINUE;
+ }
+
+ private void hit() {
+ if (++p.hits >= MAX_HITS) p.hitCap = true;
+ for (int i = stack.size() - 1; i >= 0 && !stack.get(i).found; i--) {
+ stack.get(i).found = true;
+ p.keep.add(stack.get(i).path);
+ }
+ }
+
+ @Override
+ public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) {
+ final FileVisitResult result = tick();
+ if (result != FileVisitResult.CONTINUE) return result;
+ final boolean isTop = first;
+ first = false;
+ final String path = withSlash(dir.toAbsolutePath().toString());
+ if (!isTop) {
+ if (skipped(dir, true)) return FileVisitResult.SKIP_SUBTREE;
+ if (filter.accept(dir.toFile())) { // list it, with all its content
+ p.full.add(path);
+ p.keep.add(path);
+ hit();
+ return FileVisitResult.SKIP_SUBTREE;
+ }
+ }
+ if (!isTop && isOpaque(dir)) { // never search inside chunk stores and similar
+ p.skipped++;
+ return FileVisitResult.SKIP_SUBTREE;
+ }
+ if (onlyIn != null && !onlyIn.contains(path)) return FileVisitResult.SKIP_SUBTREE;
+ stack.add(new Frame(path));
+ return FileVisitResult.CONTINUE;
+ }
+
+ @Override
+ public FileVisitResult postVisitDirectory(final Path dir, final IOException exc) {
+ if (!stack.isEmpty()) stack.remove(stack.size() - 1);
+ return FileVisitResult.CONTINUE;
+ }
+
+ @Override
+ public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) {
+ final FileVisitResult result = tick();
+ if (result != FileVisitResult.CONTINUE) return result;
+ if (!skipped(file, false) && filter.accept(file.toFile())) hit();
+ return FileVisitResult.CONTINUE;
+ }
+
+ @Override
+ public FileVisitResult visitFileFailed(final Path file, final IOException exc) {
+ return FileVisitResult.CONTINUE; // e.g., no permission
+ }
+ });
+ } catch (final IOException | RuntimeException e) {
+ // A folder that cannot be searched: ignore it
}
}
- synchronized public void addLeafListener(final LeafListener l) {
- this.leaf_listeners.add(l);
+ /** Lists the top-level folders, including those hidden by the filter, in their original order */
+ private List allTops() {
+ final Node root = root();
+ final List tops = new ArrayList<>();
+ for (int i = 0; i < root.getChildCount(); i++)
+ tops.add(root.getChildAt(i));
+ hidden_tops.forEach((index, node) -> tops.add(Math.min(index, tops.size()), node));
+ return tops;
}
- synchronized public void removeLeafListener(final LeafListener l) {
- this.leaf_listeners.remove(l);
+ private void restoreHiddenTops() {
+ hidden_tops.forEach((index, node) -> getModel().insertNodeInto(node, root(), Math.min(index, root().getChildCount())));
+ hidden_tops.clear();
}
- synchronized public ArrayList getLeafListeners() {
- return new ArrayList<>(this.leaf_listeners);
+ private Set expandedFolders() {
+ final Set expanded = new HashSet<>();
+ final Node root = root();
+ for (int i = 0; i < root.getChildCount(); i++) {
+ final Enumeration e = getExpandedDescendants(new TreePath(root.getChildAt(i).getPath()));
+ while (e != null && e.hasMoreElements())
+ expanded.add(((Node) e.nextElement().getLastPathComponent()).path);
+ }
+ return expanded;
+ }
+
+ /**
+ * Re-lists all folders according to the outcome of a scan, expanding the paths to
+ * the hits. A null scan lifts the filtering, restoring the previous expansion
+ */
+ private void rebuild(final Prune p) {
+ rebuild(p, true);
+ }
+
+ /** @param done false if the scan is still running: the tree is updated with partial results */
+ private void rebuild(final Prune p, final boolean done) {
+ final long start = System.nanoTime();
+ restoreHiddenTops();
+ prune = p;
+ final Node root = root();
+ for (int i = 0; i < root.getChildCount(); i++) {
+ final Node top = root.getChildAt(i);
+ collapsePath(new TreePath(top.getPath())); // releases the content
+ top.showAll = false;
+ }
+ if (p == null) {
+ final Set saved = saved_expansion;
+ saved_expansion = null;
+ for (int i = 0; saved != null && i < root.getChildCount(); i++) {
+ final Node top = root.getChildAt(i);
+ if (saved.contains(top.path)) {
+ expandPath(new TreePath(top.getPath()));
+ restoreExpansion(top, saved);
+ }
+ }
+ return;
+ }
+ for (int i = root.getChildCount() - 1; i >= 0; i--) {
+ final Node top = root.getChildAt(i);
+ if (!p.keep.contains(top.path)) {
+ hidden_tops.put(i, top);
+ getModel().removeNodeFromParent(top);
+ }
+ }
+ expand_budget = MAX_AUTO_EXPAND;
+ for (int i = 0; i < root.getChildCount(); i++) {
+ final Node top = root.getChildAt(i);
+ expandPath(new TreePath(top.getPath()));
+ expandHits(top, p);
+ }
+ if (done) scrollRowToVisible(0);
+ last_skipped = p.skipped;
+ last_hit_cap = p.hitCap;
+ last_capped = expand_budget < 0;
+ // Do not let updating the tree dominate the search
+ publish_interval_nanos = Math.max(300_000_000L, 5 * (System.nanoTime() - start));
+ if (filter_listener != null) filter_listener.filterApplied(p.hits, p.truncated, done);
+ }
+
+ /** Expands the (listed) folders leading to hits. Folders that match are not expanded further */
+ private void expandHits(final Node node, final Prune p) {
+ if (node.listsAll(p)) return;
+ for (int i = 0; i < node.getChildCount(); i++) {
+ final Node child = node.getChildAt(i);
+ if (child.isDirectory() && p.keep.contains(child.path)) {
+ if (expand_budget-- <= 0) return; // too many: remaining folders can be expanded manually
+ expandPath(new TreePath(child.getPath()));
+ expandHits(child, p);
+ }
+ }
+ }
+
+ /**
+ * Whether listed folders are kept in sync with the file system (the default).
+ * Turn it off for network or cloud folders, where file system events are
+ * unreliable or expensive. Use {@link #refresh()} to update the listing on demand.
+ */
+ public void setLiveUpdates(final boolean live) {
+ if (live == live_updates) return;
+ live_updates = live;
+ final Node root = root();
+ if (live) {
+ for (final Enumeration> e = root.depthFirstEnumeration(); e.hasMoreElements();) {
+ final Node n = (Node) e.nextElement();
+ if (n.isDirectory() && isExpanded(new TreePath(n.getPath()))) dir_watcher.register(n);
+ }
+ refresh(); // catch up with changes made meanwhile
+ } else {
+ for (final Enumeration> e = root.depthFirstEnumeration(); e.hasMoreElements();)
+ dir_watcher.unregister((Node) e.nextElement());
+ }
+ }
+
+ public boolean isLiveUpdates() {
+ return live_updates;
+ }
+
+ /** Re-lists all expanded folders, preserving their expansion */
+ public void refresh() {
+ if (prune_active) {
+ setFileFilter(file_filter, true); // search again
+ return;
+ }
+ final Node root = root();
+ for (int i = 0; i < root.getChildCount(); i++) {
+ final Node top = root.getChildAt(i);
+ if (isExpanded(new TreePath(top.getPath()))) refresh(top);
+ }
+ }
+
+ /** Removes all top-level folders */
+ public void clearTopLevelFolders() {
+ cancelFilterScan();
+ final Node root = root();
+ for (final Enumeration> e = root.depthFirstEnumeration(); e.hasMoreElements();)
+ dir_watcher.unregister((Node) e.nextElement());
+ hidden_tops.clear();
+ root.clear();
+ }
+
+ /** Removes a top-level folder */
+ public void removeTopLevelFolder(final Node top) {
+ for (final Enumeration> e = top.depthFirstEnumeration(); e.hasMoreElements();)
+ dir_watcher.unregister((Node) e.nextElement());
+ getModel().removeNodeFromParent(top);
+ }
+
+ /** Re-lists the children of a node, preserving the expansion of its subfolders */
+ private void refresh(final Node node) {
+ if (node.getRoot() != root()) { // removed from the tree
+ dir_watcher.unregister(node);
+ return;
+ }
+ // A folder collapsed after the file system event was queued must remain empty
+ if (!isExpanded(new TreePath(node.getPath()))) return;
+ final Set expanded = new HashSet<>();
+ final Enumeration e = getExpandedDescendants(new TreePath(node.getPath()));
+ while (e != null && e.hasMoreElements())
+ expanded.add(((Node) e.nextElement().getLastPathComponent()).path);
+ node.clear();
+ node.populate();
+ restoreExpansion(node, expanded);
+ }
+
+ private void restoreExpansion(final Node node, final Set expanded) {
+ for (int i = 0; i < node.getChildCount(); i++) {
+ final Node child = node.getChildAt(i);
+ if (expanded.contains(child.path)) {
+ expandPath(new TreePath(child.getPath())); // lists the child (see treeWillExpand)
+ restoreExpansion(child, expanded);
+ }
+ }
+ }
+
+ public void addLeafListener(final LeafListener l) {
+ leaf_listeners.add(l);
+ }
+
+ public void removeLeafListener(final LeafListener l) {
+ leaf_listeners.remove(l);
+ }
+
+ public ArrayList getLeafListeners() {
+ return new ArrayList<>(leaf_listeners);
}
/**
* Add a directory as a top-level root.
- *
+ *
* @param dir The directory to add as a top-level root
* @param checkIfChild If true, and the {@code dir} is a child of an existing root,
* then merely expand it and don't add it as a root.
*/
public void addRootDirectory(final String dir, final boolean checkIfChild) {
+ restoreHiddenTops();
+ addRoot(dir, checkIfChild);
+ if (prune_active) setFileFilter(file_filter, true); // search again
+ }
+
+ private void addRoot(final String dir, final boolean checkIfChild) {
final File file = new File(dir);
if (!file.isDirectory()) return;
final String dirPath = withSlash(file.getAbsolutePath());
- final Node root = (Node) getModel().getRoot();
-
+ final Node root = root();
if (checkIfChild) {
- // If dir is a subdirectory of an existing root, expand recursively to show it
- for (int i=0; i FileSystemTree.this.updateUI());
+ /** Expands nodes downwards until reaching dirPath. Returns null if not found */
+ private TreePath pathTo(Node node, final String dirPath) {
+ while (dirPath.startsWith(node.path)) {
+ if (dirPath.equals(node.path)) return new TreePath(node.getPath());
+ expandPath(new TreePath(node.getPath())); // lists the node (see treeWillExpand)
+ Node next = null;
+ for (int i = 0; i < node.getChildCount() && next == null; i++) {
+ if (dirPath.startsWith(node.getChildAt(i).path)) next = node.getChildAt(i);
+ }
+ if (next == null) return null;
+ node = next;
+ }
+ return null;
}
/**
* For persistence.
+ *
* @return A String with the absolute file paths of all top-level folders
- * concatenated with a ':' character as separator.
+ * concatenated with {@link File#pathSeparator}.
*/
public String getTopLevelFoldersString() {
- final Node root = (Node) getModel().getRoot();
- if (0 == root.getChildCount()) return "";
- final StringBuilder sb = new StringBuilder(root.getChildAt(0).path);
- for (int i=1, l=root.getChildCount(); i paths = new ArrayList<>();
+ for (final Node top : allTops())
+ paths.add(top.path);
+ return String.join(File.pathSeparator, paths);
}
/**
* For restoring state. Only those paths that are directories and exist will be added.
+ *
* @param folders A String generated from {@code FileSystemTree#getTopLevelFoldersString()}.
*/
public void addTopLevelFoldersFrom(final String folders) {
- for (final String path : folders.split(":")) {
- final File file = new File(path);
- if (file.exists() && file.isDirectory()) {
- addRootDirectory(file.getAbsolutePath(), false);
- }
+ for (final String path : folders.split(File.pathSeparator)) {
+ addRootDirectory(path, false);
}
}
public void destroy() {
+ cancelFilterScan();
dir_watcher.interrupt();
- FileDrop.remove(this);
+ if (fileDrop != null) fileDrop.uninstall();
}
+ /** Watches expanded folders, re-listing them when their content changes */
private class DirectoryWatcher extends Thread {
+ private final Map keys = new ConcurrentHashMap<>();
+ private final Map byNode = new ConcurrentHashMap<>();
private WatchService watcher;
- private final HashMap keys = new HashMap<>();
- private final HashMap map = new HashMap<>();
DirectoryWatcher() {
+ super("FileSystemTree watcher");
setDaemon(true);
try {
- this.watcher = FileSystems.getDefault().newWatchService();
- this.start();
- } catch (IOException e) {
+ watcher = FileSystems.getDefault().newWatchService();
+ start();
+ } catch (final IOException e) {
log.error("Failed to start filesystem watching.", e);
}
}
void register(final Node node) {
- if (null == watcher) {
- log.error("Filesystem watching is not running.");
- return;
- }
- synchronized (keys) {
- try {
- final Path path = new File(node.path).toPath();
- final WatchKey key = path.register(watcher,
- StandardWatchEventKinds.ENTRY_CREATE,
- StandardWatchEventKinds.ENTRY_MODIFY,
+ if (watcher == null || node.failed) return; // unreadable folders cannot be watched
+ try {
+ final WatchKey key = new File(node.path).toPath().register(watcher, StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE);
- keys.put(key, path);
- map.put(path, node);
- } catch (IOException e) {
- log.error(e);
- }
+ final Node previous = keys.put(key, node); // same key if the folder was already registered
+ if (previous != null && previous != node) byNode.remove(previous);
+ byNode.put(node, key);
+ } catch (final IOException e) {
+ log.debug("Could not watch folder " + node.path + ": " + e.getMessage());
}
}
void unregister(final Node node) {
- synchronized (keys) {
- final Iterator> it = map.entrySet().iterator();
- Path path = null;
- while (it.hasNext()) {
- final Map.Entry e = it.next();
- if ( e.getValue() == node ) {
- path = e.getKey();
- it.remove();
- break;
- }
- }
- if (null == path) return;
- final Iterator itp = keys.values().iterator();
- while (itp.hasNext()) {
- if (itp.next().equals(path)) {
- itp.remove();
- return;
- }
- }
+ final WatchKey key = byNode.remove(node);
+ // The key may have been taken over by another node listing the same folder
+ if (key != null && keys.get(key) == node) {
+ key.cancel();
+ keys.remove(key);
}
}
@Override
public void run() {
- while (true) {
- if (isInterrupted()) return;
- WatchKey key;
- try {
- key = watcher.take();
- } catch (InterruptedException x) {
- return;
- }
-
- final Path dir = keys.get(key);
- if (null == dir) {
- log.error("Unrecognized WatchKey: " + key);
- continue;
- }
-
- final HashSet nodes = new HashSet<>();
-
- for (final WatchEvent> event: key.pollEvents()) {
- final WatchEvent.Kind> kind = event.kind();
- if (StandardWatchEventKinds.OVERFLOW == kind
- || StandardWatchEventKinds.ENTRY_MODIFY == kind) { // ignore e.g. files getting larger or smaller
- continue;
+ try {
+ while (!isInterrupted()) {
+ final WatchKey key = watcher.take();
+ final Node node = keys.get(key);
+ if (node != null && !key.pollEvents().isEmpty()) SwingUtilities.invokeLater(() -> refresh(node));
+ if (!key.reset()) {
+ final Node gone = keys.remove(key);
+ if (gone != null) byNode.remove(gone);
}
-
- @SuppressWarnings("unchecked")
- final Path child = dir.resolve(((WatchEvent) event).context());
- final Node node = map.get(child.getParent());
- if (null != node) nodes.add(node);
}
-
- SwingUtilities.invokeLater(() -> {
- for (final Node node : nodes) {
- node.updateChildrenList(FileSystemTree.this.getModel(), file_filter);
- FileSystemTree.this.expandPath(new TreePath(node.getPath()));
- }
- });
-
- boolean valid = key.reset();
- if (!valid) {
- final Path path = keys.remove(key);
- if (null != path) map.remove(path);
+ } catch (final InterruptedException | ClosedWatchServiceException ignored) {
+ // we are done
+ } finally {
+ try {
+ watcher.close();
+ } catch (final IOException ignored) {
+ // nothing to do
}
}
}
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 8ded11f6..8ec0a82f 100644
--- a/src/main/java/org/scijava/ui/swing/script/FileSystemTreePanel.java
+++ b/src/main/java/org/scijava/ui/swing/script/FileSystemTreePanel.java
@@ -29,38 +29,27 @@
package org.scijava.ui.swing.script;
-import java.awt.Color;
-import java.awt.Desktop;
-import java.awt.Dimension;
-import java.awt.FontMetrics;
-import java.awt.GridBagConstraints;
-import java.awt.GridBagLayout;
-import java.awt.Insets;
-import java.awt.event.FocusAdapter;
-import java.awt.event.FocusEvent;
-import java.awt.event.KeyAdapter;
-import java.awt.event.KeyEvent;
-import java.awt.font.FontRenderContext;
-import java.awt.geom.Rectangle2D;
+import java.awt.*;
import java.io.File;
+import java.io.FileFilter;
+import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import java.util.stream.Collectors;
-
-import javax.swing.BorderFactory;
-import javax.swing.JButton;
-import javax.swing.JCheckBoxMenuItem;
-import javax.swing.JFileChooser;
-import javax.swing.JMenuItem;
-import javax.swing.JPanel;
-import javax.swing.JPopupMenu;
-import javax.swing.JScrollPane;
-import javax.swing.UIManager;
+import javax.swing.*;
+import javax.swing.event.DocumentEvent;
+import javax.swing.event.DocumentListener;
+import javax.swing.event.PopupMenuEvent;
+import javax.swing.event.PopupMenuListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
+import com.formdev.flatlaf.FlatClientProperties;
+import com.formdev.flatlaf.icons.*;
+import com.formdev.flatlaf.ui.FlatRoundBorder;
+import com.formdev.flatlaf.util.UIScale;
import org.scijava.Context;
import org.scijava.app.AppService;
import org.scijava.plugin.Parameter;
@@ -77,9 +66,23 @@ class FileSystemTreePanel extends JPanel {
private static final long serialVersionUID = -710040159139542578L;
private final FileSystemTree tree;
private final SearchField searchField;
+ private static final int SEARCH_DELAY_MS = 250;
+ private static final int MAX_HISTORY = 10;
+ private final List history = new ArrayList<>(MAX_HISTORY + 1);
private boolean regex;
private boolean caseSensitive;
+ private java.util.function.Supplier activeScript = () -> null;
+ private java.util.function.Consumer statusListener = t -> {};
+ private String status = "";
+ private boolean userChoice; // user explicitly changed fast mode options: never auto-enable
+ private boolean autoFast; // fast mode was auto-enabled already (once per session)
+ private boolean autoNotice; // report the auto-enabling once the repeated search completes
+ private final Timer searchingTimer = new Timer(400, e -> setStatus("Searching..."));
+ private static final long SLOW_SCAN_NANOS = 1_000_000_000L;
+ private static final int MIN_CHARS_COLLAPSED = 2; // shorter queries only search expanded folders
+ private long scanStart; // when the last filter was applied (0 if not being timed)
+
@Parameter
private AppService appService;
@@ -87,139 +90,246 @@ class FileSystemTreePanel extends JPanel {
this.tree = tree;
context.inject(this);
searchField = initializedField();
+ tree.setFilterListener(this::filterStatus);
+ tree.setNoticeListener(this::setStatus);
+
+ // assign contextual menu early on
+ addContextualMenuToTree();
+
setLayout(new GridBagLayout());
final GridBagConstraints bc = new GridBagConstraints();
bc.gridx = 0;
bc.gridy = 0;
- bc.weightx = 0;
- bc.weighty = 0;
- bc.anchor = GridBagConstraints.CENTER;
- bc.fill = GridBagConstraints.HORIZONTAL;
- add(addDirectoryButton(), bc);
- bc.gridx = 1;
- add(removeDirectoryButton(), bc);
- bc.gridx = 2;
bc.fill = GridBagConstraints.BOTH;
bc.weightx = 1;
+ bc.weighty = 0;
add(searchField, bc);
- bc.fill = GridBagConstraints.NONE;
- bc.weightx = 0;
- bc.gridx = 3;
- add(searchOptionsButton(), bc);
- bc.gridx = 0;
- bc.gridwidth = 4;
bc.gridy = 1;
bc.weightx = 1.0;
bc.weighty = 1.0;
bc.fill = GridBagConstraints.BOTH;
final JScrollPane treePane = new JScrollPane(tree);
+ TextEditor.GuiUtils.flattenScrollBars(treePane);
add(treePane, bc);
- new FileDrop(treePane, files -> {
- final List dirs = Arrays.asList(files).stream().filter(f -> f.isDirectory())
- .collect(Collectors.toList());
- if (dirs.isEmpty()) {
- TextEditor.GuiUtils.warn(this, "Only folders can be dropped into the file tree.");
- return;
- }
- if (TextEditor.GuiUtils.confirm(this, "Confirm loading of " + dirs.size() + " folders?", "Confirm?",
- "Confirm")) {
- dirs.forEach(dir -> tree.addRootDirectory(dir.getAbsolutePath(), true));
+ bc.gridy = 2;
+ bc.weightx = 0;
+ bc.weighty = 0;
+ add(statusToolbar(), bc);
+ tree.fileDrop = new FileDrop(treePane, files -> {
+ try {
+ final List dirs = Arrays.stream(files).filter(File::isDirectory).collect(Collectors.toList());
+ if (dirs.isEmpty()) { // Only files dropped without directories
+ addRootFromFile(files[0]);
+ } else if (dirs.size() == 1) { // A single folder dropped
+ addRootFromFile(dirs.get(0));
+ } else if (TextEditor.GuiUtils.confirm(this,
+ "Replace contents with the " + dirs.size() + " dropped folders?",
+ "Replace Contents?", "Confirm")) {
+ tree.clearTopLevelFolders(); // Blank out the entire tree
+ dirs.forEach(dir -> tree.addRootDirectory(dir.getAbsolutePath(), true));
+ }
+
+ } catch (final Throwable ignored) {
+ TextEditor.GuiUtils.warn(this, "Could not retrieve location of dropped file(s).");
}
});
- addContextualMenuToTree();
+ }
+
+ private JToolBar statusToolbar() {
+ final JToolBar toolbar = new JToolBar();
+ toolbar.setBackground(tree.getBackground());
+ final JToggleButton statusFast = new JToggleButton("Fast Mode");
+ statusFast.putClientProperty(FlatClientProperties.STYLE_CLASS, "small");
+ statusFast.setForeground(TextEditor.GuiUtils.secondaryColor());
+ 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") : TextEditor.GuiUtils.secondaryColor();
+ final Color bGrnd = (selected) ? UIManager.getColor("Tree.selectionBackground") : toolbar.getBackground();
+ if (fGrnd!=null) statusFast.setForeground(fGrnd);
+ if (bGrnd!=null) statusFast.setBackground(bGrnd);
+ });
+ final JButton statusOptions = new JButton("Options");
+ final FlatFileChooserDetailsViewIcon optionsIcon = new FlatFileChooserDetailsViewIcon();
+ optionsIcon.setScale(.8f); // matches the font size set by the "small" style
+ statusOptions.putClientProperty(FlatClientProperties.STYLE_CLASS, "small");
+ statusOptions.setForeground(TextEditor.GuiUtils.secondaryColor());
+ statusOptions.addActionListener(e -> tree.getComponentPopupMenu().show(statusOptions, 0, 0));
+ statusOptions.setIcon(optionsIcon);
+ toolbar.add(statusFast);
+ toolbar.addSeparator();
+ toolbar.add(statusOptions);
+ toolbar.add(Box.createHorizontalGlue());
+ final FlatHelpButtonIcon helpIcon = new FlatHelpButtonIcon();
+ helpIcon.setScale(.8f); // matches the font size set by the "small" style
+ helpIcon.applyStyleProperty("questionMarkColor", TextEditor.GuiUtils.secondaryColor());
+ helpIcon.applyStyleProperty("background", toolbar.getBackground());
+ final JButton statusHelp = new JButton(helpIcon);
+ statusHelp.addActionListener(e -> showHelpMsg());
+ toolbar.add(statusHelp);
+ return toolbar;
+ }
+
+ private void addRootFromFile(final File file) {
+ if (file.isDirectory())
+ tree.addRootDirectory(file.getAbsolutePath(), true);
+ else
+ tree.addRootDirectory(file.getParentFile().getAbsolutePath(), true);
}
private SearchField initializedField() {
final SearchField field = new SearchField();
- field.addFocusListener(new FocusAdapter() {
+ // Live search: apply the filter once typing pauses
+ final Timer liveSearch = new Timer(SEARCH_DELAY_MS, e -> applyFilter());
+ liveSearch.setRepeats(false);
+ field.getDocument().addDocumentListener(new DocumentListener() {
+
@Override
- public void focusLost(final FocusEvent e) {
- if (0 == field.getText().length()) {
- tree.setFileFilter(((f) -> true)); // any // no need to press enter
- }
+ public void insertUpdate(final DocumentEvent e) {
+ liveSearch.restart();
}
- });
- field.addKeyListener(new KeyAdapter() {
- Pattern pattern = null;
@Override
- public void keyPressed(final KeyEvent ke) {
- if (ke.getKeyCode() == KeyEvent.VK_ENTER) {
- final String text = field.getText();
- if (0 == text.length()) {
- tree.setFileFilter(((f) -> true)); // any
- return;
- }
-
- if (isRegexEnabled()) { // if ('/' == text.charAt(0)) {
- // Interpret as a regular expression
- // Attempt to compile the pattern
- try {
- String regex = text; // text.substring(1);
- if ('^' != regex.charAt(1))
- regex = "^.*" + regex;
- if ('$' != regex.charAt(regex.length() - 1))
- regex += ".*$";
- pattern = Pattern.compile(regex);
- field.setForeground(tree.getForeground());
- } catch (final PatternSyntaxException | StringIndexOutOfBoundsException pse) {
- // regex is too short to be parseable or is invalid
- tree.log.warn(pse.getLocalizedMessage());
- field.setForeground(Color.RED);
- pattern = null;
- return;
- }
- if (null != pattern) {
- tree.setFileFilter((f) -> pattern.matcher(f.getName()).matches());
- }
- } else {
- // Interpret as a literal match
- if (isCaseSensitive())
- tree.setFileFilter((f) -> -1 != f.getName().indexOf(text));
- else
- tree.setFileFilter((f) -> -1 != f.getName().toLowerCase().indexOf(text.toLowerCase()));
- }
- } else {
- // Upon re-typing something
- if (field.getForeground() == Color.RED) {
- field.setForeground(tree.getForeground());
- }
- }
+ public void removeUpdate(final DocumentEvent e) {
+ liveSearch.restart();
+ }
+
+ @Override
+ public void changedUpdate(final DocumentEvent e) {
+ liveSearch.restart();
}
});
+ // Enter: apply immediately and remember the term
+ field.addActionListener(e -> {
+ liveSearch.stop();
+ if (applyFilter()) addToHistory(field.getText());
+ });
return field;
}
- private JButton thinButton(final String label, final float factor) {
- final JButton b = new JButton(label);
- try {
- if ("com.apple.laf.AquaLookAndFeel".equals(UIManager.getLookAndFeel().getClass().getName())) {
- b.setOpaque(true);
- b.setBackground(new JPanel().getBackground());
- b.setBorderPainted(false);
- b.setBorder(BorderFactory.createEmptyBorder());
- b.setMargin(new Insets(0, 2, 0, 2));
- } else {
- final Insets insets = b.getMargin();
- b.setMargin(new Insets((int) (insets.top * factor), (int) (insets.left * factor),
- (int) (insets.bottom * factor), (int) (insets.right * factor)));
+ /** Sets the listener notified of status messages (empty string clears the message) */
+ void setStatusListener(final java.util.function.Consumer l) {
+ statusListener = (l == null) ? t -> {} : l;
+ statusListener.accept(status);
+ }
+
+ /** Fast mode: no live updates and no search of collapsed folders */
+ boolean isFastMode() {
+ return !tree.isLiveUpdates() && !tree.isSearchCollapsedFolders();
+ }
+
+ /** Sets fast mode on behalf of the user (disables any automatic switching) */
+ void setFastMode(final boolean fast) {
+ userChoice = true;
+ applyFastMode(fast);
+ }
+
+ private void applyFastMode(final boolean fast) {
+ tree.setLiveUpdates(!fast);
+ tree.setSearchCollapsedFolders(!fast);
+ searchField.setCollapsedSelected(!fast);
+ if (!searchField.getText().isEmpty()) applyFilter();
+ }
+
+ private void setStatus(final String text) {
+ status = (text == null) ? "" : text;
+ statusListener.accept(status);
+ }
+
+ /** Called by the tree as results of the filter are found (on the EDT) */
+ private void filterStatus(final int hits, final boolean truncated, final boolean done) {
+ if (!done) { // Only mention the search if it takes a while
+ searchingTimer.setRepeats(false);
+ if (!searchingTimer.isRunning() && status.isEmpty()) searchingTimer.restart();
+ // A long search of a huge tree: switch to fast mode and search again, restricted to expanded folders
+ if (scanStart != 0 && System.nanoTime() - scanStart > SLOW_SCAN_NANOS && !isFastMode() && !userChoice
+ && !autoFast) {
+ autoFast = true;
+ autoNotice = true;
+ applyFastMode(true);
}
- } catch (final Exception ignored) {
- // do nothing
+ return;
+ }
+ searchingTimer.stop();
+ searchField.setInvalid(hits == 0);
+ setStatus(resultSummary(hits, truncated));
+ if (autoNotice) {
+ autoNotice = false;
+ setStatus("Large folders: Fast mode enabled. " + status);
+ }
+ final long elapsed = (scanStart == 0) ? 0 : System.nanoTime() - scanStart;
+ scanStart = 0;
+ final boolean slow = hits >= 0 && (truncated || elapsed > SLOW_SCAN_NANOS);
+ if (slow && !isFastMode() && !userChoice && !autoFast) {
+ autoFast = true;
+ autoNotice = true;
+ applyFastMode(true); // repeats the search, now faster
+ } else if (slow && !isFastMode()) {
+ setStatus("Searching too many files..: Enable Fast mode");
+ }
+ }
+
+ /** One-line outcome of a finished search: the status stays until the next search */
+ private String resultSummary(final int hits, final boolean truncated) {
+ if (hits < 0) return ""; // filter lifted
+ final StringBuilder sb = new StringBuilder();
+ sb.append(hits == 0 ? "No matches" : hits + (tree.isHitCapped() ? "+ matches" : (hits == 1 ? " match" : " matches")));
+ final List notes = new ArrayList<>();
+ if (tree.isHitCapped()) notes.add("refine your search");
+ else if (truncated) notes.add("search limited: results incomplete");
+ if (searchField.getText().length() < MIN_CHARS_COLLAPSED && tree.isSearchCollapsedFolders())
+ notes.add("type " + MIN_CHARS_COLLAPSED + "+ characters to search collapsed folders");
+ if (tree.isExpansionCapped()) notes.add("not all folders expanded");
+ if (tree.getSkippedFolderCount() > 0) notes.add(tree.getSkippedFolderCount() + " chunk stores not searched");
+ if (!notes.isEmpty()) sb.append(" (").append(String.join("; ", notes)).append(")");
+ return sb.toString();
+ }
+
+ /** Applies the filter defined by the search field. Returns false if it is not valid */
+ private boolean applyFilter() {
+ final String text = searchField.getText();
+ try {
+ final FileFilter filter = filterFor(text);
+ searchField.setInvalid(false);
+ tree.setExpandedOnly(text.length() < MIN_CHARS_COLLAPSED);
+ setStatus(""); // drop the outcome of the previous search; "Searching..." follows if this one is slow
+ scanStart = text.isEmpty() ? 0 : System.nanoTime();
+ tree.setFileFilter(filter, !text.isEmpty()); // hides folders without hits
+ return !text.isEmpty();
+ } catch (final PatternSyntaxException ignored) {
+ tree.cancelFilterScan();
+ searchField.setInvalid(true);
+ return false;
}
- // b.setBorder(null);
- // set height to that of searchField. Do not allow vertical resizing
- b.setPreferredSize(new Dimension(b.getPreferredSize().width, (int) searchField.getPreferredSize().getHeight()));
- b.setMaximumSize(new Dimension(b.getMaximumSize().width, (int) searchField.getPreferredSize().getHeight()));
- return b;
}
- private JButton addDirectoryButton() {
- final JButton add_directory = thinButton("+", .25f);
- add_directory.setToolTipText("Add a directory");
+ private FileFilter filterFor(final String text) throws PatternSyntaxException {
+ if (text.isEmpty()) return f -> true;
+ if (isRegexEnabled()) {
+ String expr = text;
+ if (!expr.startsWith("^")) expr = "^.*" + expr;
+ if (!expr.endsWith("$")) expr += ".*$";
+ final Pattern pattern = Pattern.compile(expr, isCaseSensitive() ? 0 : Pattern.CASE_INSENSITIVE);
+ return f -> pattern.matcher(f.getName()).matches();
+ }
+ if (isCaseSensitive()) return f -> f.getName().contains(text);
+ final String lowerCase = text.toLowerCase();
+ return f -> f.getName().toLowerCase().contains(lowerCase);
+ }
+
+ private void addToHistory(final String term) {
+ history.remove(term);
+ history.add(term);
+ if (history.size() > MAX_HISTORY) history.remove(0);
+ }
+
+ private JMenuItem addDirectoryMenuItem() {
+ final JMenuItem add_directory = new JMenuItem("Other...", new FlatFileChooserNewFolderIcon());
+ add_directory.setToolTipText("List a different location");
add_directory.addActionListener(e -> {
final String folders = tree.getTopLevelFoldersString();
- final String lastFolder = folders.substring(folders.lastIndexOf(":") + 1);
+ final String lastFolder = folders.substring(folders.lastIndexOf(File.pathSeparatorChar) + 1);
final JFileChooser c = new JFileChooser();
c.setDialogTitle("Choose Top-Level Folder");
c.setCurrentDirectory(new File(lastFolder));
@@ -229,74 +339,87 @@ private JButton addDirectoryButton() {
c.setApproveButtonText("Choose Folder");
c.setMultiSelectionEnabled(false);
c.setDragEnabled(true);
- new FileDrop(c, files -> {
- if (files.length == 0)
- return;
- final File firstFile = files[0];
- c.setCurrentDirectory((firstFile.isDirectory()) ? firstFile : firstFile.getParentFile());
- c.rescanCurrentDirectory();
+ final FileDrop fileDrop = new FileDrop(c, files -> {
+ if (files == null || files.length == 0 || files[0] == null) return;
+ try {
+ final File ref = files[0].getAbsoluteFile();
+ c.setCurrentDirectory((ref.isDirectory()) ? ref : ref.getParentFile());
+ } catch (final Throwable ignored) {
+ TextEditor.GuiUtils.warn(this, "Could not retrieve location of dropped file(s).");
+ }
});
if (JFileChooser.APPROVE_OPTION == c.showOpenDialog(this)) {
final File f = c.getSelectedFile();
if (f.isDirectory())
tree.addRootDirectory(f.getAbsolutePath(), false);
}
- FileDrop.remove(c);
+ fileDrop.uninstall();
});
return add_directory;
}
- private JButton removeDirectoryButton() {
- final JButton remove_directory = thinButton("−", .25f);
- remove_directory.setToolTipText("Remove a top-level directory");
+ private JMenuItem removeDirectoryMenuItem() {
+ final JMenuItem remove_directory = new JMenuItem("Remove Last");
+ remove_directory.setToolTipText("Remove last top-level directory");
remove_directory.addActionListener(e -> {
- final TreePath p = tree.getSelectionPath();
- if (null == p) {
- TextEditor.GuiUtils.error(this, "Select a top-level folder first.");
- return;
- }
- if (2 == p.getPathCount()) {
- // Is a child of the root, so it's a top-level folder
- tree.getModel().removeNodeFromParent(//
- (FileSystemTree.Node) p.getLastPathComponent());
- } else {
- TextEditor.GuiUtils.error(this, "Can only remove top-level folders.");
- }
+ try {
+ final DefaultMutableTreeNode root = (DefaultMutableTreeNode) tree.getModel().getRoot();
+ if (root != null && root.getChildCount() > 0) {
+ DefaultMutableTreeNode lastLevel1Node = (DefaultMutableTreeNode) root.getLastChild();
+ if (lastLevel1Node != null)
+ tree.removeTopLevelFolder((FileSystemTree.Node) lastLevel1Node);
+ }
+
+ } catch (Exception ex) {
+ TextEditor.GuiUtils.error(this, "Could not remove top-level folders.");
+ }
});
return remove_directory;
}
- private JButton searchOptionsButton() {
- final JButton options = thinButton("⋮", .05f);
- options.setToolTipText("Filtering options");
+ private JPopupMenu searchOptionsMenu() {
final JPopupMenu popup = new JPopupMenu();
- final JCheckBoxMenuItem jcbmi1 = new JCheckBoxMenuItem("Case Sensitive", isCaseSensitive());
- jcbmi1.addItemListener(e -> {
- setCaseSensitive(jcbmi1.isSelected());
- });
- popup.add(jcbmi1);
- final JCheckBoxMenuItem jcbmi2 = new JCheckBoxMenuItem("Enable Regex", isCaseSensitive());
- jcbmi2.addItemListener(e -> {
- setRegexEnabled(jcbmi2.isSelected());
- });
- popup.add(jcbmi2);
+ final JMenu historyMenu = new JMenu("Search History");
+ historyMenu.setToolTipText("Press Enter on a typed term to store it in this menu");
+ popup.add(historyMenu);
popup.addSeparator();
- JMenuItem jmi = new JMenuItem("Reset Filter");
+ JMenuItem jmi = new JMenuItem("Reset Filter(s)");
jmi.addActionListener(e -> {
- jcbmi1.setSelected(false);
- setCaseSensitive(false);
- jcbmi2.setSelected(false);
- setRegexEnabled(false);
+ searchField.resetOptions();
searchField.setText("");
- tree.setFileFilter(((f) -> true));
+ applyFilter();
});
popup.add(jmi);
- popup.addSeparator();
- jmi = new JMenuItem("About File Explorer...");
- jmi.addActionListener(e -> showHelpMsg());
- popup.add(jmi);
- options.addActionListener(e -> popup.show(options, options.getWidth() / 2, options.getHeight() / 2));
- return options;
+ popup.addPopupMenuListener(new PopupMenuListener() {
+
+ @Override
+ public void popupMenuWillBecomeVisible(final PopupMenuEvent e) {
+ historyMenu.removeAll();
+ for (int i = history.size() - 1; i >= 0; i--) {
+ final String term = history.get(i);
+ final JMenuItem item = new JMenuItem(term);
+ item.addActionListener(ev -> {
+ searchField.setText(term);
+ applyFilter();
+ });
+ historyMenu.add(item);
+ }
+ historyMenu.setEnabled(!history.isEmpty());
+ if (!history.isEmpty()) {
+ historyMenu.addSeparator();
+ final JMenuItem clear = new JMenuItem("Clear History");
+ clear.addActionListener(ev -> history.clear());
+ historyMenu.add(clear);
+ }
+ }
+
+ @Override
+ public void popupMenuWillBecomeInvisible(final PopupMenuEvent e) {}
+
+ @Override
+ public void popupMenuCanceled(final PopupMenuEvent e) {}
+ });
+ return popup;
}
@SuppressWarnings("unused")
@@ -309,14 +432,36 @@ private boolean allTreeNodesCollapsed() {
private void addContextualMenuToTree() {
final JPopupMenu popup = new JPopupMenu();
- JMenuItem jmi = new JMenuItem("Collapse All");
- jmi.addActionListener(e -> TextEditor.GuiUtils.collapseAllTreeNodes(tree));
- popup.add(jmi);
- jmi = new JMenuItem("Expand Folders");
- jmi.addActionListener(e -> expandImmediateNodes());
+
+ TextEditor.GuiUtils.addPopupMenuSeparator(popup, "List:");
+ final JMenuItem selected = new JMenuItem("Selected Folder", new FlatFileViewDirectoryIcon());
+ selected.setToolTipText("Makes the selected folder (or the folder of the selected file) the only top-level folder");
+ selected.addActionListener(e -> {
+ final File dir = selectedDirectory();
+ if (dir != null) changeRootPath(dir.getAbsolutePath());
+ });
+ popup.add(selected);
+ final JMenuItem parent = new JMenuItem("Parent Folder", new FlatFileChooserUpFolderIcon());
+ parent.setToolTipText("Lists the parent of the current top-level folder");
+ parent.addActionListener(e -> {
+ final File dir = parentDirectory();
+ if (dir != null) changeRootPath(dir.getAbsolutePath());
+ });
+ popup.add(parent);
+ final JMenuItem active = new JMenuItem("Folder of Active Script", new FlatFileViewFileIcon());
+ active.addActionListener(e -> {
+ final File dir = activeScriptDirectory();
+ if (dir != null) changeRootPath(dir.getAbsolutePath());
+ });
+ popup.add(active);
+ JMenuItem jmi = new JMenuItem(appService.getApp().getTitle() + " Folder", new FlatFileChooserHomeFolderIcon());
+ jmi.addActionListener(e -> changeRootPath(appService.getApp().getBaseDirectory().getAbsolutePath()));
popup.add(jmi);
- popup.addSeparator();
- jmi = new JMenuItem("Open in System Explorer");
+ popup.add(addDirectoryMenuItem());
+
+ TextEditor.GuiUtils.addPopupMenuSeparator(popup, "Open In:");
+ final JMenuItem fileSystem = new JMenuItem("File System", new FlatFileViewComputerIcon());
+ jmi = fileSystem;
jmi.addActionListener(e -> {
final TreePath path = tree.getSelectionPath();
if (path == null) {
@@ -327,12 +472,13 @@ private void addContextualMenuToTree() {
final String filepath = (String) ((FileSystemTree.Node) path.getLastPathComponent()).getUserObject();
final File f = new File(filepath);
Desktop.getDesktop().open((f.isDirectory()) ? f : f.getParentFile());
- } catch (final Exception | Error ignored) {
+ } catch (final Throwable ignored) {
TextEditor.GuiUtils.error(this, "Folder of selected item does not seem to be accessible.");
}
});
popup.add(jmi);
- jmi = new JMenuItem("Open in Terminal");
+ final JMenuItem terminal = new JMenuItem("Terminal", new FlatMenuArrowIcon());
+ jmi = terminal;
jmi.addActionListener(e -> {
final TreePath path = tree.getSelectionPath();
if (path == null) {
@@ -342,26 +488,136 @@ private void addContextualMenuToTree() {
try {
final String filepath = (String) ((FileSystemTree.Node) path.getLastPathComponent()).getUserObject();
TextEditor.GuiUtils.openTerminal(new File(filepath));
- } catch (final Exception ignored) {
+ } catch (final Throwable ignored) {
TextEditor.GuiUtils.error(this, "Could not open path in Terminal.");
}
});
popup.add(jmi);
-
- popup.addSeparator();
- jmi = new JMenuItem("Reset to Home Folder");
- jmi.addActionListener(e -> changeRootPath(System.getProperty("user.home")));
+
+ TextEditor.GuiUtils.addPopupMenuSeparator(popup, "Contents:");
+ final JMenuItem collapseAll = new JMenuItem("Collapse All");
+ jmi = collapseAll;
+ jmi.addActionListener(e -> TextEditor.GuiUtils.collapseAllTreeNodes(tree));
popup.add(jmi);
- jmi = new JMenuItem("Reset to Fiji.app/");
- jmi.addActionListener(e -> changeRootPath(appService.getApp().getBaseDirectory().getAbsolutePath()));
+ final JMenuItem expandLevel = new JMenuItem("Expand One Level");
+ jmi = expandLevel;
+ jmi.setToolTipText("Expands the listed folders (repeat to go deeper)");
+ jmi.addActionListener(e -> expandImmediateNodes());
popup.add(jmi);
+ final JMenuItem refresh = new JMenuItem("Refresh");
+ refresh.setToolTipText("Re-lists the expanded folders");
+ refresh.addActionListener(e -> tree.refresh());
+ popup.add(refresh);
+ final javax.swing.JCheckBoxMenuItem live = new javax.swing.JCheckBoxMenuItem("Live Updates", tree.isLiveUpdates());
+ live.setToolTipText("Keeps listed folders in sync with the file system. Turn off for network or cloud folders");
+ live.addActionListener(e -> {
+ userChoice = true;
+ tree.setLiveUpdates(live.isSelected());
+ });
+ popup.add(live);
+
+ TextEditor.GuiUtils.addPopupMenuSeparator(popup, "Reset:");
+ final JMenuItem removeLast = removeDirectoryMenuItem();
+ popup.add(removeLast);
+ final JMenuItem wipe = new JMenuItem("Clear All");
+ wipe.addActionListener(e -> tree.clearTopLevelFolders());
+ popup.add(wipe);
+ popup.addPopupMenuListener(new PopupMenuListener() {
+
+ @Override
+ public void popupMenuWillBecomeVisible(final PopupMenuEvent e) {
+ selected.setEnabled(selectedDirectory() != null);
+ final File dir = activeScriptDirectory();
+ active.setEnabled(dir != null);
+ active.setToolTipText(dir == null ? "The active script has not been saved" : dir.getAbsolutePath());
+ parent.setEnabled(parentDirectory() != null);
+ final boolean hasSelection = tree.getSelectionPath() != null;
+ fileSystem.setEnabled(hasSelection);
+ terminal.setEnabled(hasSelection);
+ final boolean hasRows = tree.getRowCount() > 0;
+ collapseAll.setEnabled(hasRows);
+ expandLevel.setEnabled(hasRows);
+ refresh.setEnabled(hasRows);
+ live.setSelected(tree.isLiveUpdates());
+ final boolean hasFolders = !tree.getTopLevelFoldersString().isEmpty();
+ removeLast.setEnabled(hasFolders);
+ wipe.setEnabled(hasFolders);
+ }
+
+ @Override
+ public void popupMenuWillBecomeInvisible(final PopupMenuEvent e) {}
+
+ @Override
+ public void popupMenuCanceled(final PopupMenuEvent e) {}
+ });
+ // Right-click selects the item under the cursor
+ tree.addMouseListener(new java.awt.event.MouseAdapter() {
+
+ @Override
+ public void mousePressed(final java.awt.event.MouseEvent e) {
+ select(e);
+ }
+
+ @Override
+ public void mouseReleased(final java.awt.event.MouseEvent e) {
+ select(e);
+ }
+
+ private void select(final java.awt.event.MouseEvent e) {
+ if (!e.isPopupTrigger()) return;
+ final int row = tree.getRowForLocation(e.getX(), e.getY());
+ if (row >= 0) tree.setSelectionRow(row);
+ else tree.clearSelection();
+ }
+ });
tree.setComponentPopupMenu(popup);
}
+ /** The selected folder, or the parent of the selected file. Null if nothing is selected */
+ private File selectedDirectory() {
+ final TreePath path = tree.getSelectionPath();
+ if (path == null) return null;
+ final File f = new File((String) ((FileSystemTree.Node) path.getLastPathComponent()).getUserObject());
+ final File dir = f.isDirectory() ? f : f.getParentFile();
+ return (dir != null && dir.isDirectory()) ? dir : null;
+ }
+
+ /** The parent of the top-level folder holding the selection (or of the first one). Null if there is none */
+ private File parentDirectory() {
+ final String top = tree.getTopLevelFoldersString();
+ if (top.isEmpty()) return null;
+ final String[] tops = top.split(File.pathSeparator);
+ String chosen = tops[0];
+ final TreePath path = tree.getSelectionPath();
+ if (path != null) {
+ final String sel = ((FileSystemTree.Node) path.getLastPathComponent()).getUserObject().toString();
+ for (final String t : tops) {
+ if (sel.startsWith(t)) chosen = t;
+ }
+ }
+ final File parent = new File(chosen).getAbsoluteFile().getParentFile();
+ return (parent != null && parent.isDirectory()) ? parent : null;
+ }
+
+ /** The folder of the active script. Null if the script has not been saved */
+ private File activeScriptDirectory() {
+ try {
+ final File f = activeScript.get();
+ final File dir = (f == null) ? null : f.getAbsoluteFile().getParentFile();
+ return (dir != null && dir.isDirectory()) ? dir : null;
+ } catch (final RuntimeException ignored) {
+ return null;
+ }
+ }
+
+ /** Sets how to retrieve the file of the active script (null if not saved) */
+ void setActiveScriptSupplier(final java.util.function.Supplier supplier) {
+ activeScript = (supplier == null) ? () -> null : supplier;
+ }
+
void changeRootPath(final String path) {
- ((DefaultMutableTreeNode) tree.getModel().getRoot()).removeAllChildren();
- tree.addTopLevelFoldersFrom(path);
- tree.getModel().reload(); // this will collapse all nodes
+ tree.clearTopLevelFolders();
+ tree.addRootDirectory(path, false); // NB: not addTopLevelFoldersFrom(), as paths may contain separators
expandImmediateNodes();
}
@@ -371,36 +627,36 @@ private void expandImmediateNodes() {
}
private void showHelpMsg() {
- final String msg = "" //
- + "Overview
" //
- + "The File Explorer pane provides a direct view of selected folders. Changes in " //
- + "the native file system are synchronized in real time.
" //
- + "
Add/Remove Folders
" //
- + "To add a folder, use the [+] button, or drag & drop folders from the native " //
- + "System Explorer. To remove a folder: select it, then use the [-] button. To reset "
- + "or reveal items: use the commands in the contextual popup menu.
" //
- + "
Accessing Files & Paths
" //
- + "Double-click on a file to open it. Drag & drop items into the editor pane "
- + "to paste their paths into the active script.
" //
- + "
Filtering Files
" //
- + "Filters affect filenames (not folders) and are applied by typing a filtering "//
- + "string + [Enter]. Filters act only on files being listed in expanded directories, " //
- + "and ignore the content of collapsed folders. Examples of regex usage:
" //
- + "
" //
- + " " //
- + " | Pattern | " //
- + " Result | " //
- + "
" //
- + " " //
- + " | py$ | " //
- + " Display filenames ending with py | " //
- + "
" //
- + " " //
- + " | ^Demo | " //
- + " Display filenames starting with Demo | " //
- + "
" //
- + "
";
- TextEditor.GuiUtils.showHTMLDialog(this.getRootPane(), "File Explorer Pane", msg);
+ final String msg = "" //
+ + "The Files pane provides a direct view of selected folders. Changes in " //
+ + "the native file system are synchronized in real time (turn
Live Updates off in the " //
+ + "contextual menu for network or cloud folders, and use
Refresh to update on demand). " //
+ + "Hidden files and folders are not listed." //
+ + "
Add/Remove Folders
" //
+ + "To add a folder, drag & drop it from the native System Explorer, or use " //
+ + "
Other... in the contextual menu (right-click). The same menu " //
+ + "lists the selected folder, its parent, or the folder of the active script, and " //
+ + "removes the last folder or all folders." //
+ + "
Accessing Files & Paths
" //
+ + "Double-click on a file to open it. Drag & drop items into the editor pane " //
+ + "to paste their paths into the active script." //
+ + "
Filtering
" //
+ + "Filtering is applied as you type. Only files and folders with matching names are " //
+ + "listed: folders without matches are hidden, and the folders leading to matches are " //
+ + "expanded. A folder whose name matches is listed with all of its content. " //
+ + "Press [Enter] to store a term in the search history (magnifier icon). Options:" //
+ + "
" //
+ + "- <⌄<
" //
+ + "- Also search collapsed folders (default). If deselected, only " //
+ + "expanded folders are searched, which is faster in very large folders
" //
+ + "- Cc
" //
+ + "- Match case
" //
+ + "- .*<
" //
+ + "- Regular expressions. Examples: py$ (names ending with py), " //
+ + "^Demo (names starting with Demo)
" //
+ + "
";
+
+ TextEditor.GuiUtils.showHTMLDialog(this.getRootPane(), "Files Pane", msg);
}
private boolean isCaseSensitive() {
@@ -413,47 +669,185 @@ private boolean isRegexEnabled() {
private void setCaseSensitive(final boolean b) {
caseSensitive = b;
- searchField.update();
+ applyFilter();
}
private void setRegexEnabled(final boolean b) {
regex = b;
- searchField.update();
+ applyFilter();
+ }
+
+ private void setCollapsedEnabled(final boolean b) {
+ userChoice = true;
+ tree.setSearchCollapsedFolders(b);
+ applyFilter();
}
private class SearchField extends TextEditor.TextFieldWithPlaceholder {
private static final long serialVersionUID = 7004232238240585434L;
- private static final String REGEX_HOLDER = "[?*]";
- private static final String CASE_HOLDER = "[Aa]";
- private static final String DEF_HOLDER = "File filter... ";
+ private static final String DEF_HOLDER = "File filter...";
+ private final JToggleButton caseToggle;
+ private final JToggleButton regexToggle;
+ private final JToggleButton collapsedToggle;
SearchField() {
+ setPlaceholder(DEF_HOLDER);
+ // Filtering options (and history) are accessed from the search icon
+ final JButton options = new JButton(new FlatSearchWithHistoryIcon(true));
+ options.setToolTipText("Filtering options");
+ options.setFocusable(false);
+ options.putClientProperty(FlatClientProperties.BUTTON_TYPE, FlatClientProperties.BUTTON_TYPE_TOOLBAR_BUTTON);
+ final JPopupMenu menu = searchOptionsMenu();
+ options.addActionListener(e -> menu.show(options, 0, options.getHeight()));
+ putClientProperty(FlatClientProperties.TEXT_FIELD_LEADING_COMPONENT, options);
+ // Case and regex toggles live inside the field (FlatLaf)
+ caseToggle = optionToggle("Cc", "Match case", FileSystemTreePanel.this::setCaseSensitive);
+ regexToggle = optionToggle(".*", "Use regular expressions", FileSystemTreePanel.this::setRegexEnabled);
+ regexToggle.setFont(regexToggle.getFont().deriveFont(Font.BOLD));
+ collapsedToggle = optionToggle(null, "Include collapsed folders in searches (slower)", FileSystemTreePanel.this::setCollapsedEnabled);
+ collapsedToggle.setSelected(tree.isSearchCollapsedFolders()); // reflect the default
+ // Tree chevrons (collapsed/expanded) instead of text
+ collapsedToggle.setIcon(new ChevronIcon(false));
+ collapsedToggle.setSelectedIcon(new ChevronIcon(true));
+
+ final JToolBar tb = new JToolBar();
+ tb.setMargin(new Insets(0, 0, 0, 2));
+ tb.add(collapsedToggle);
+ tb.add(caseToggle);
+ tb.add(regexToggle);
+ putClientProperty(FlatClientProperties.TEXT_FIELD_TRAILING_COMPONENT, tb);
+ enlarge(1.1f);
+ }
+
+ /** Slightly larger text, with padding proportional to the font */
+ private void enlarge(final float enlargeFactor) {
+ // Normalize by the OS scale so the enlargement is consistent across platforms
+ final float factor = 1f + (enlargeFactor - 1f) / osScale();
+ setFont(getFont().deriveFont(getFont().getSize() * factor));
+ for (final JToggleButton b : Arrays.asList(collapsedToggle, caseToggle, regexToggle))
+ b.setFont(b.getFont().deriveFont(b.getFont().getSize() * factor));
+ equalizeToggles();
+ final int padding = getFontMetrics(getFont()).getDescent();
+ setBorder(BorderFactory.createCompoundBorder(new FlatRoundBorder(),
+ BorderFactory.createEmptyBorder(padding, padding, padding, padding)));
+ }
+
+ /**
+ * Gives all toggles the size of the largest one. Must be called once their
+ * fonts are final (the toolbar layout ignores minimum sizes)
+ */
+ private void equalizeToggles() {
+ final List toggles = Arrays.asList(collapsedToggle, caseToggle, regexToggle);
+ int w = 0;
+ int h = 0;
+ for (final JToggleButton b : toggles) {
+ b.setPreferredSize(null); // measure the natural size
+ final Dimension d = b.getPreferredSize();
+ w = Math.max(w, d.width);
+ h = Math.max(h, d.height);
+ }
+ final Dimension size = new Dimension(w, h);
+ for (final JToggleButton b : toggles) {
+ b.setPreferredSize(size);
+ b.setMinimumSize(size);
+ b.setMaximumSize(size);
+ }
+ }
+
+ /** Ratio between FlatLaf's UI scale and the display's scale */
+ private float osScale() {
try {
- // make sure pane is large enough to display placeholders
- final FontMetrics fm = getFontMetrics(getFont());
- final FontRenderContext frc = fm.getFontRenderContext();
- final String buf = CASE_HOLDER + REGEX_HOLDER + DEF_HOLDER;
- final Rectangle2D rect = getFont().getStringBounds(buf, frc);
- final int prefWidth = (int) rect.getWidth();
- setColumns(prefWidth / getColumnWidth());
+ final GraphicsConfiguration gc = getGraphicsConfiguration();
+ final double device = (gc == null)
+ ? GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()
+ .getDefaultConfiguration().getDefaultTransform().getScaleX()
+ : gc.getDefaultTransform().getScaleX();
+ return (float) (Math.max(1.0, UIScale.getUserScaleFactor()) / Math.max(1.0, device));
} catch (final Exception ignored) {
- // do nothing
+ return 1f;
}
}
- void update() {
- update(getGraphics());
+ private JToggleButton optionToggle(final String label, final String tooltip, final java.util.function.Consumer setter) {
+ // Same tint as the search icon (it follows the look and feel)
+ final JToggleButton b = new JToggleButton(label) {
+
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public Color getForeground() {
+ final Color c = TextEditor.GuiUtils.secondaryColor();
+ return (c != null) ? c : super.getForeground();
+ }
+ };
+ b.setToolTipText(tooltip);
+ b.setFocusable(false);
+ b.setFont(b.getFont().deriveFont(b.getFont().getSize() * .85f));
+ b.addActionListener(e -> setter.accept(b.isSelected()));
+ return b;
+ }
+
+ void setInvalid(final boolean invalid) {
+ putClientProperty(FlatClientProperties.OUTLINE, invalid ? FlatClientProperties.OUTLINE_ERROR : null);
+ }
+
+ void setCollapsedSelected(final boolean selected) {
+ collapsedToggle.setSelected(selected);
+ }
+
+ void resetOptions() {
+ caseToggle.setSelected(false);
+ regexToggle.setSelected(false);
+ collapsedToggle.setSelected(true); // default: also search collapsed folders
+ tree.setSearchCollapsedFolders(true);
+ caseSensitive = false;
+ regex = false;
+ }
+ }
+ /** A chevron pointing right (collapsed) or down (expanded), painted with the foreground of its button */
+ private static final class ChevronIcon implements Icon {
+
+ private final boolean down;
+
+ ChevronIcon(final boolean down) {
+ this.down = down;
}
@Override
- String getPlaceholder() {
- final StringBuilder sb = new StringBuilder(DEF_HOLDER);
- if (isCaseSensitive())
- sb.append(CASE_HOLDER);
- if (isRegexEnabled())
- sb.append(REGEX_HOLDER);
- return sb.toString();
+ public int getIconWidth() {
+ return UIScale.scale(10);
+ }
+
+ @Override
+ public int getIconHeight() {
+ return UIScale.scale(10);
+ }
+
+ @Override
+ public void paintIcon(final Component c, final Graphics g, final int x, final int y) {
+ final Graphics2D g2 = (Graphics2D) g.create();
+ try {
+ g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
+ g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
+ g2.setColor(c.getForeground());
+ g2.setStroke(new BasicStroke(UIScale.scale(1.3f), BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
+ final float s = getIconWidth();
+ final float a = s * .3f; // inset
+ final java.awt.geom.Path2D.Float p = new java.awt.geom.Path2D.Float();
+ if (down) {
+ p.moveTo(x + a * .5f, y + s * .35f);
+ p.lineTo(x + s / 2, y + s * .65f);
+ p.lineTo(x + s - a * .5f, y + s * .35f);
+ } else {
+ p.moveTo(x + s * .35f, y + a * .5f);
+ p.lineTo(x + s * .65f, y + s / 2);
+ p.lineTo(x + s * .35f, y + s - a * .5f);
+ }
+ g2.draw(p);
+ } finally {
+ g2.dispose();
+ }
}
}
}
diff --git a/src/main/java/org/scijava/ui/swing/script/PromptPane.java b/src/main/java/org/scijava/ui/swing/script/PromptPane.java
index 42d1a2c6..4ffd2554 100644
--- a/src/main/java/org/scijava/ui/swing/script/PromptPane.java
+++ b/src/main/java/org/scijava/ui/swing/script/PromptPane.java
@@ -191,7 +191,7 @@ private ThreadService threadService() {
* Trivial extension of {@link JTextArea} to expose its {@code getRowHeight()}
* method.
*/
- public class TextArea extends JTextArea {
+ public static class TextArea extends JTextArea {
public TextArea(int rows, int columns) {
super(rows, columns);
}
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 65713ca5..ddfeacd4 100644
--- a/src/main/java/org/scijava/ui/swing/script/TextEditor.java
+++ b/src/main/java/org/scijava/ui/swing/script/TextEditor.java
@@ -29,17 +29,7 @@
package org.scijava.ui.swing.script;
-import java.awt.Color;
-import java.awt.Component;
-import java.awt.Cursor;
-import java.awt.Desktop;
-import java.awt.Dimension;
-import java.awt.Font;
-import java.awt.Graphics2D;
-import java.awt.GridBagConstraints;
-import java.awt.GridBagLayout;
-import java.awt.RenderingHints;
-import java.awt.Toolkit;
+import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
@@ -97,6 +87,7 @@
import java.util.Map;
import java.util.Objects;
import java.util.Set;
+import java.util.function.BiConsumer;
import java.util.TreeMap;
import java.util.Vector;
import java.util.concurrent.ExecutionException;
@@ -110,7 +101,11 @@
import javax.script.ScriptException;
import javax.swing.AbstractAction;
import javax.swing.AbstractButton;
+import javax.swing.Icon;
+import javax.swing.Box;
import javax.swing.BoxLayout;
+import javax.swing.JComponent;
+import javax.swing.JToggleButton;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
@@ -128,6 +123,7 @@
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
+import javax.swing.JToolBar;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.JTree;
@@ -144,6 +140,7 @@
import javax.swing.text.Position;
import javax.swing.tree.TreePath;
+import com.formdev.flatlaf.icons.FlatSearchIcon;
import org.fife.ui.rsyntaxtextarea.AbstractTokenMakerFactory;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import org.fife.ui.rsyntaxtextarea.Theme;
@@ -191,6 +188,7 @@
import org.scijava.util.Types;
import org.scijava.widget.FileWidget;
+import com.formdev.flatlaf.FlatClientProperties;
import com.formdev.flatlaf.FlatLaf;
/**
@@ -236,6 +234,10 @@ public class TextEditor extends JFrame implements ActionListener,
private static AbstractTokenMakerFactory tokenMakerFactory = null;
private JTabbedPane tabbed;
+ private JTabbedPane sideTabs;
+ private NotesPanel notesPanel;
+ private BookmarksPanel bookmarksPanel;
+ private JSplitPane outlineSplit;
private JMenuItem newFile, open, save, saveas, compileAndRun, compile,
close, undo, redo, cut, copy, paste, find, selectAll, kill,
gotoLine, makeJar, makeJarWithSource, removeUnusedImports, sortImports,
@@ -252,6 +254,16 @@ public class TextEditor extends JFrame implements ActionListener,
private int tabsMenuTabsStart;
private Set tabsMenuItems;
private FindAndReplaceDialog findDialog;
+ private JToggleButton statusFast;
+ private JButton statusTab;
+ private FlatSearchIcon statusFastIcon;
+ private JToggleButton statusWrap;
+ private JButton statusPos, statusLang;
+ private JToggleButton statusSide;
+ private int sideLastLocation = -1;
+ private JMenu languageMenu;
+ private JLabel statusText;
+ private FileSystemTreePanel filesPanel;
private JCheckBoxMenuItem autoSave, wrapLines, tabsEmulated, autoImport,
autocompletion, fallbackAutocompletion, keylessAutocompletion,
markOccurences, paintTabs, whiteSpace, marginLine, lockPane, vimMode;
@@ -325,12 +337,45 @@ public TextEditor(final Context context) {
// NB: All panes must be initialized before menus are assembled!
tabbed = GuiUtils.getJTabbedPane();
+ 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,
+ (BiConsumer) (pane, index) -> {
+ pane.setSelectedIndex(index);
+ closeTab(true);
+ });
+ tabbed.putClientProperty(FlatClientProperties.TABBED_PANE_TRAILING_COMPONENT,
+ GuiUtils.newTabButton(() -> newFile.doClick()));
tree = new FileSystemTree(log);
- final JTabbedPane sideTabs = GuiUtils.getJTabbedPane();
- sideTabs.addTab("File Explorer", new FileSystemTreePanel(tree, context));
- sideTabs.addTab("Outline", sourceTreePanel = new OutlineTreePanel());
- body = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, sideTabs, tabbed);
+ sideTabs = GuiUtils.getJTabbedPane();
+ sideTabs.putClientProperty(FlatClientProperties.TABBED_PANE_TAB_AREA_ALIGNMENT,
+ FlatClientProperties.TABBED_PANE_ALIGN_FILL);
+ filesPanel = new FileSystemTreePanel(tree, context);
+ filesPanel.setActiveScriptSupplier(() -> {
+ try {
+ return getEditorPane().getFile();
+ } catch (final RuntimeException ignored) {
+ return null;
+ }
+ });
+ sideTabs.addTab("Files", filesPanel);
+ sourceTreePanel = new OutlineTreePanel();
+ bookmarksPanel = new BookmarksPanel(this::collectBookmarks, this::goToBookmark);
+ outlineSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT, sourceTreePanel, bookmarksPanel);
+ outlineSplit.setResizeWeight(.75);
+ outlineSplit.setContinuousLayout(true);
+ GuiUtils.flattenSplitPane(outlineSplit);
+ sideTabs.addTab("Outline", outlineSplit);
+ notesPanel = new NotesPanel(() -> {
+ try {
+ return getEditorPane();
+ } catch (final RuntimeException ignored) {
+ return null;
+ }
+ }, prefService, getClass());
+ sideTabs.addTab("Notes", notesPanel);
+ body = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, sideTabs, tabbed);
// These items are dynamic and need to be initialized before EditorPane creation
initializeDynamicMenuComponents();
@@ -373,6 +418,7 @@ public TextEditor(final Context context) {
} else {
new SetWritableAction().actionPerformedImpl(e, getEditorPane());
}
+ syncStatusBar();
});
JMenuItem jmi = new JMenuItem("Revert...");
jmi.addActionListener(e -> {
@@ -418,6 +464,7 @@ public TextEditor(final Context context) {
languageMenuItems = new LinkedHashMap<>();
final Set usedShortcuts = new HashSet<>();
final JMenu languages = new JMenu("Language");
+ languageMenu = languages;
languages.setMnemonic(KeyEvent.VK_L);
final ButtonGroup group = new ButtonGroup();
@@ -574,7 +621,7 @@ public TextEditor(final Context context) {
tabsMenu.add(jcmi2);
final JMenuItem mi = new JMenuItem("Reset Layout...");
mi.addActionListener(e -> {
- if (confirm("Reset Location of Console and File Explorer?", "Reset Layout?", "Reset")) {
+ if (confirm("Reset Location of Console and Files pane?", "Reset Layout?", "Reset")) {
resetLayout();
jcmi1.setSelected(true);
jcmi2.setSelected(true);
@@ -635,7 +682,10 @@ public TextEditor(final Context context) {
GuiUtils.addMenubarSeparator(options, "Indentation:");
tabsEmulated = new JCheckBoxMenuItem("Indent Using Spaces");
tabsEmulated.setMnemonic(KeyEvent.VK_S);
- tabsEmulated.addItemListener(e -> setTabsEmulated(tabsEmulated.getState()));
+ tabsEmulated.addItemListener(e -> {
+ setTabsEmulated(tabsEmulated.getState());
+ syncStatusBar();
+ });
options.add(tabsEmulated);
tabSizeMenu = new JMenu("Tab Width");
tabSizeMenu.setMnemonic(KeyEvent.VK_T);
@@ -645,6 +695,7 @@ public TextEditor(final Context context) {
item.addActionListener(event -> {
getEditorPane().setTabSize(size);
updateTabAndFontSize(false);
+ syncStatusBar();
});
item.setMnemonic(KeyEvent.VK_0 + (size % 10));
bg.add(item);
@@ -706,7 +757,8 @@ public TextEditor(final Context context) {
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
// Tweaks for JSplitPane
- body.setOneTouchExpandable(true);
+ body.setOneTouchExpandable(false); // the side panel is collapsed from the status bar
+ GuiUtils.flattenSplitPane(body);
body.addPropertyChangeListener(evt -> {
if ("dividerLocation".equals(evt.getPropertyName())) saveWindowSizeToPrefs();
});
@@ -743,11 +795,10 @@ public TextEditor(final Context context) {
}
}
// Ask:
- if (confirm("Really try to open file " + name + " in a tab?", "Confirm", "Open")) {
- open(f);
- }
+ open(f);
});
getContentPane().add(body);
+ getContentPane().add(assembleStatusBar());
// for Eclipse and MS Visual Studio lovers
addAccelerator(compileAndRun, KeyEvent.VK_F11, 0, true);
@@ -861,6 +912,12 @@ private void assembleEditMenu() {
addMappedActionToMenu(editMenu, "Copy as Styled Text", EditorPaneActions.rstaCopyAsStyledTextAction, false);
paste = addToMenu(editMenu, "Paste", KeyEvent.VK_V, ctrl);
addMappedActionToMenu(editMenu, "Paste History...", EditorPaneActions.clipboardHistoryAction, true);
+ final JMenuItem notesItem = new JMenuItem("Notes & Clipboard History");
+ notesItem.addActionListener(e -> {
+ sideTabs.setSelectedComponent(notesPanel);
+ notesPanel.refresh();
+ });
+ editMenu.add(notesItem);
GuiUtils.addMenubarSeparator(editMenu, "Find:");
find = addToMenu(editMenu, "Find/Replace...", KeyEvent.VK_F, ctrl);
find.setMnemonic(KeyEvent.VK_F);
@@ -894,7 +951,7 @@ private void assembleEditMenu() {
final JMenuItem toggB = addMappedActionToMenu(editMenu, "Toggle Bookmark",
EditorPaneActions.rtaToggleBookmarkAction, false);
toggB.setToolTipText("Alternatively, click on left bookmark gutter near the line number");
- final JMenuItem listBookmarks = addToMenu(editMenu, "List Bookmarks...", 0, 0);
+ final JMenuItem listBookmarks = addToMenu(editMenu, "Show Bookmarks", 0, 0);
listBookmarks.setMnemonic(KeyEvent.VK_L);
listBookmarks.addActionListener(e -> listBookmarks());
final JMenuItem clearBookmarks = addToMenu(editMenu, "Clear Bookmarks...", 0, 0);
@@ -1137,7 +1194,10 @@ private void initializeDynamicMenuComponents() {
marginLine = new JCheckBoxMenuItem("Show Margin Line", false);
marginLine.setToolTipText("Displays right margin at column 80");
marginLine.addItemListener(e -> setMarginLineEnabled(marginLine.getState()));
- wrapLines.addItemListener(e -> setWrapLines(wrapLines.getState()));
+ wrapLines.addItemListener(e -> {
+ setWrapLines(wrapLines.getState());
+ syncStatusBar();
+ });
markOccurences = new JCheckBoxMenuItem("Mark Occurences", false);
markOccurences.setToolTipText("Allows for all occurrences of a double-clicked string to be"
+ " highlighted.\nLines with hits are marked on the Editor's notification strip");
@@ -1255,6 +1315,7 @@ public void loadWindowSizePreferences() {
* @see #loadWindowSizePreferences()
*/
public void saveWindowSizeToPrefs() {
+ if (notesPanel != null) notesPanel.flush();
if (layoutLoading) return;
final Dimension dim = getSize();
@@ -1792,6 +1853,284 @@ private void setAutoCompletionEnabled(final boolean enabled) {
fallbackAutocompletion.setEnabled(enabled);
}
+ /** Builds the permanent, full-width status bar: Fast | status text | glue | GoTo | Tab | Lock */
+ private JComponent assembleStatusBar() {
+ statusFast = statusButton("Fast Mode", "Fast mode for large folders: turns off live updates and the search of collapsed folders", true);
+ statusFastIcon = new FlatSearchIcon(true);
+ statusFast.setIcon(statusFastIcon);
+ statusFast.addActionListener(e -> {
+ filesPanel.setFastMode(statusFast.isSelected());
+ updateFastLook();
+ });
+ statusText = new JLabel(" ");
+ statusText.setFont(statusText.getFont().deriveFont(statusText.getFont().getSize2D() * .9f));
+ statusText.setForeground(GuiUtils.secondaryColor());
+ //statusText.setMinimumSize(new Dimension(0, 0));
+ statusPos = new JButton("Ln 1, Col 1") {
+
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public Dimension getPreferredSize() { // fixed width: neighbors do not move as the caret does
+ final Dimension d = super.getPreferredSize();
+ d.width = Math.max(d.width, getFontMetrics(getFont()).stringWidth("Ln 99999, Col 999") + 16);
+ return d;
+ }
+ };
+ statusPos.setToolTipText("Caret position. Click to go to line...");
+ statusPos.setFocusable(false);
+ statusPos.putClientProperty(FlatClientProperties.BUTTON_TYPE, FlatClientProperties.BUTTON_TYPE_TOOLBAR_BUTTON);
+ statusPos.setFont(statusPos.getFont().deriveFont(statusPos.getFont().getSize2D() * .9f));
+ statusPos.addActionListener(e -> gotoLine());
+ statusLang = new JButton("None");
+ statusLang.setToolTipText("Language of the active script. Click to change");
+ statusLang.setFocusable(false);
+ statusLang.putClientProperty(FlatClientProperties.BUTTON_TYPE, FlatClientProperties.BUTTON_TYPE_TOOLBAR_BUTTON);
+ statusLang.setFont(statusLang.getFont().deriveFont(statusLang.getFont().getSize2D() * .9f));
+ statusLang.addActionListener(e -> {
+ final JPopupMenu menu = languageMenu.getPopupMenu();
+ menu.show(statusLang, 0, -menu.getPreferredSize().height); // opens upwards: the bar is at the bottom
+ });
+ statusWrap = statusButton("Wrap", "Wraps long lines", true);
+ statusWrap.addActionListener(e -> {
+ wrapLines.setState(statusWrap.isSelected());
+ syncStatusBar();
+ });
+ statusTab = new JButton("Spaces: 4");
+ statusTab.setToolTipText("Indentation. Click for options");
+ statusTab.setFocusable(false);
+ statusTab.putClientProperty(FlatClientProperties.BUTTON_TYPE, FlatClientProperties.BUTTON_TYPE_TOOLBAR_BUTTON);
+ statusTab.setFont(statusTab.getFont().deriveFont(statusTab.getFont().getSize2D() * .9f));
+ statusTab.addActionListener(e -> {
+ final JPopupMenu menu = indentationMenu();
+ menu.show(statusTab, 0, -menu.getPreferredSize().height); // opens upwards: the bar is at the bottom
+ });
+ filesPanel.setStatusListener(t -> statusText.setText(t == null || t.isEmpty() ? " " : t));
+ filesPanel.setFastModeListener(b -> {
+ statusFast.setSelected(b);
+ updateFastLook();
+ });
+ filesPanel.setFastModeSuggestionListener(() -> setFastColor(GuiUtils.accentColor()));
+ statusFast.setSelected(filesPanel.isFastMode());
+ updateFastLook();
+ statusSide = new JToggleButton(new SidebarIcon());
+ statusSide.setToolTipText("Shows/hides the side panel (Files, Outline, Notes)");
+ statusSide.setFocusable(false);
+ statusSide.setSelected(true);
+ statusSide.putClientProperty(FlatClientProperties.BUTTON_TYPE, FlatClientProperties.BUTTON_TYPE_TOOLBAR_BUTTON);
+ statusSide.addActionListener(e -> {
+ if (statusSide.isSelected()) { // restore
+ body.setDividerLocation(sideLastLocation > 50 ? sideLastLocation : (int) (body.getWidth() * .2));
+ } else { // collapse (the location is remembered by the divider listener)
+ body.setDividerLocation(0);
+ }
+ });
+ body.addPropertyChangeListener("dividerLocation", evt -> {
+ final int loc = body.getDividerLocation();
+ if (loc > 50) sideLastLocation = loc;
+ statusSide.setSelected(loc > 5);
+ statusFast.setVisible(loc > 5); // Fast mode only concerns the Files pane
+ });
+ final JToolBar bar = new JToolBar();
+ bar.add(statusSide);
+ bar.add(Box.createHorizontalStrut(4));
+ bar.add(statusFast);
+ bar.add(Box.createHorizontalStrut(8));
+ bar.add(statusText);
+ bar.add(Box.createHorizontalGlue());
+ bar.add(statusPos);
+ bar.add(statusLang);
+ bar.add(statusWrap);
+ bar.add(statusTab);
+ bar.add(Box.createHorizontalStrut(10));
+ bar.setBorder(null);
+ bar.setAlignmentX(Component.LEFT_ALIGNMENT); // same as body (JSplitPane), or BoxLayout shifts the body
+ syncStatusBar();
+ return bar;
+ }
+
+ private JToggleButton statusButton(final String label, final String tooltip, final boolean toolbarStyle) {
+ final JToggleButton b = new JToggleButton(label);
+ b.setToolTipText(tooltip);
+ b.setFocusable(false);
+ if (toolbarStyle) b.putClientProperty(FlatClientProperties.BUTTON_TYPE, FlatClientProperties.BUTTON_TYPE_TOOLBAR_BUTTON);
+ b.setFont(b.getFont().deriveFont(b.getFont().getSize2D() * .9f));
+ return b;
+ }
+
+ /** Fast button: accent color while on, secondary otherwise (whatever changed the state: button, menu, auto-switch) */
+ private void updateFastLook() {
+ setFastColor(statusFast.isSelected() ? GuiUtils.accentColor() : GuiUtils.secondaryColor());
+ }
+
+ /** Colors the label and the (search) icon of the Fast button */
+ private void setFastColor(final Color c) {
+ statusFast.setForeground(c);
+ if (c != null) statusFastIcon.applyStyleProperty("searchIconColor", c);
+ statusFast.repaint();
+ }
+
+ /** Menu of the indentation button: what the Tab key inserts, tab width, and conversion of existing indentation */
+ private JPopupMenu indentationMenu() {
+ final JPopupMenu menu = new JPopupMenu();
+ final boolean spaces = getEditorPane().getTabsEmulated();
+ final ButtonGroup kind = new ButtonGroup();
+ final JRadioButtonMenuItem useTabs = new JRadioButtonMenuItem("Indent Using Tabs", !spaces);
+ final JRadioButtonMenuItem useSpaces = new JRadioButtonMenuItem("Indent Using Spaces", spaces);
+ useTabs.addActionListener(e -> tabsEmulated.setState(false));
+ useSpaces.addActionListener(e -> tabsEmulated.setState(true));
+ kind.add(useTabs);
+ kind.add(useSpaces);
+ menu.add(useTabs);
+ menu.add(useSpaces);
+ final JMenu width = new JMenu("Tab Width");
+ final ButtonGroup sizes = new ButtonGroup();
+ final int current = getEditorPane().getTabSize();
+ for (final int size : new int[] { 2, 4, 8 }) {
+ final JRadioButtonMenuItem item = new JRadioButtonMenuItem("" + size, size == current);
+ item.addActionListener(e -> {
+ getEditorPane().setTabSize(size);
+ updateTabAndFontSize(false);
+ });
+ sizes.add(item);
+ width.add(item);
+ }
+ menu.add(width);
+ menu.addSeparator();
+ final JMenuItem toSpaces = new JMenuItem("Convert Indentation to Spaces...");
+ toSpaces.addActionListener(e -> convertIndentation(true));
+ final JMenuItem toTabs = new JMenuItem("Convert Indentation to Tabs...");
+ toTabs.addActionListener(e -> convertIndentation(false));
+ menu.add(toSpaces);
+ menu.add(toTabs);
+ return menu;
+ }
+
+ /**
+ * Converts the leading whitespace of the lines of the selection (or of the whole
+ * file, if nothing is selected). Whitespace inside lines is never touched. This is
+ * a single edit, so it can be undone in one step
+ */
+ private void convertIndentation(final boolean toSpaces) {
+ final RSyntaxTextArea ta = getTextArea();
+ if (getEditorPane().isLocked()) {
+ error("File is currently locked.");
+ return;
+ }
+ final boolean selection = ta.getSelectionStart() != ta.getSelectionEnd();
+ final String scope = selection ? "the selected lines" : "the whole file";
+ if (!GuiUtils.confirm(this, "Convert the indentation of " + scope + " to " + (toSpaces ? "spaces" : "tabs") + "?",
+ "Convert Indentation?", "Convert")) return;
+ try {
+ final int length = ta.getDocument().getLength();
+ int start = 0;
+ int end = length;
+ if (selection) {
+ start = ta.getLineStartOffset(ta.getLineOfOffset(ta.getSelectionStart()));
+ end = Math.min(length, ta.getLineEndOffset(ta.getLineOfOffset(Math.max(ta.getSelectionStart(),
+ ta.getSelectionEnd() - 1))));
+ }
+ final int tabSize = ta.getTabSize();
+ final String text = ta.getText(start, end - start);
+ final StringBuilder out = new StringBuilder(text.length());
+ int changed = 0;
+ int i = 0;
+ while (i < text.length()) {
+ int eol = text.indexOf('\n', i);
+ eol = (eol < 0) ? text.length() : eol + 1;
+ int j = i;
+ int col = 0;
+ while (j < eol && (text.charAt(j) == ' ' || text.charAt(j) == '\t')) {
+ col += (text.charAt(j) == '\t') ? tabSize - (col % tabSize) : 1;
+ j++;
+ }
+ final StringBuilder lead = new StringBuilder();
+ if (toSpaces) {
+ for (int k = 0; k < col; k++)
+ lead.append(' ');
+ } else {
+ for (int k = 0; k < col / tabSize; k++)
+ lead.append('\t');
+ for (int k = 0; k < col % tabSize; k++)
+ lead.append(' ');
+ }
+ if (!lead.toString().equals(text.substring(i, j))) changed++;
+ out.append(lead).append(text, j, eol);
+ i = eol;
+ }
+ if (changed == 0) {
+ statusText.setText("Indentation already uses " + (toSpaces ? "spaces" : "tabs"));
+ return;
+ }
+ ta.replaceRange(out.toString(), start, end);
+ statusText.setText("Converted the indentation of " + changed + (changed == 1 ? " line" : " lines"));
+ } catch (final BadLocationException | RuntimeException ex) {
+ error("Could not convert the indentation: " + ex.getMessage());
+ }
+ }
+
+ /** Side panel icon: a window with a left pane, filled when the pane is shown. Painted with the foreground of its button */
+ private static final class SidebarIcon implements Icon {
+
+ @Override
+ public void paintIcon(final Component c, final Graphics g, final int x, final int y) {
+ final Graphics2D g2 = (Graphics2D) g.create();
+ try {
+ g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
+ g2.setColor(c.getForeground());
+ g2.drawRoundRect(x + 1, y + 2, 13, 11, 3, 3);
+ if (c instanceof AbstractButton && ((AbstractButton) c).isSelected()) g2.fillRect(x + 2, y + 3, 4, 10);
+ else g2.drawLine(x + 6, y + 3, x + 6, y + 12);
+ } finally {
+ g2.dispose();
+ }
+ }
+
+ @Override
+ public int getIconWidth() {
+ return 16;
+ }
+
+ @Override
+ public int getIconHeight() {
+ return 16;
+ }
+ }
+
+ private String languageLabel(final ScriptLanguage language) {
+ return language == null ? "None" : languageDisplayName(language);
+ }
+
+ /** Updates the caret position of the status bar (cheap: no scanning of the text) */
+ private void updateCaretStatus() {
+ if (statusPos == null) return;
+ try {
+ final RSyntaxTextArea ta = getTextArea();
+ final int pos = ta.getCaretPosition();
+ final int line = ta.getLineOfOffset(pos);
+ final String text = "Ln " + (line + 1) + ", Col " + (pos - ta.getLineStartOffset(line) + 1);
+ if (!text.equals(statusPos.getText())) statusPos.setText(text);
+ } catch (final BadLocationException | RuntimeException ignored) {
+ // no editor yet, or document changing
+ }
+ }
+
+ /** Updates the toggles of the status bar from the state of the active editor */
+ private void syncStatusBar() {
+ if (statusTab == null || statusWrap == null) return;
+ try {
+ final EditorPane pane = getEditorPane();
+ statusWrap.setSelected(pane.getLineWrap());
+ statusLang.setText(languageLabel(pane.getCurrentLanguage()));
+ updateCaretStatus();
+ statusTab.setText((pane.getTabsEmulated() ? "Spaces: " : "Tab: ") + pane.getTabSize());
+ statusFast.setSelected(filesPanel.isFastMode());
+ updateFastLook();
+ } catch (final RuntimeException ignored) {
+ // no editor yet
+ }
+ }
+
private void setTabsEmulated(final boolean emulated) {
for (int i = 0; i < tabbed.getTabCount(); i++)
getEditorPane(i).setTabsEmulated(emulated);
@@ -2036,6 +2375,7 @@ public void stateChanged(final ChangeEvent e) {
}
final EditorPane editorPane = getEditorPane(index);
lockPane.setSelected(editorPane.isLocked());
+ syncStatusBar();
editorPane.requestFocus();
checkForOutsideChanges();
@@ -2085,12 +2425,17 @@ public void toggleBookmark() {
getEditorPane().toggleBookmark();
}
- private Vector getAllBookmarks() {
+ private Vector collectBookmarks() {
final Vector bookmarks = new Vector<>();
for (int i = 0; i < tabbed.getTabCount(); i++) {
final TextEditorTab tab = (TextEditorTab) tabbed.getComponentAt(i);
tab.editorPane.getBookmarks(tab, bookmarks);
}
+ return bookmarks;
+ }
+
+ private Vector getAllBookmarks() {
+ final Vector bookmarks = collectBookmarks();
if (bookmarks.isEmpty()) {
info("No Bookmarks currently exist.\nYou can bookmark lines by clicking next to their line number.",
"No Bookmarks");
@@ -2098,11 +2443,17 @@ private Vector getAllBookmarks() {
return bookmarks;
}
+ private void goToBookmark(final Bookmark bookmark) {
+ final int index = tabbed.indexOfComponent(bookmark.tab);
+ if (index < 0) return;
+ switchTo(index);
+ bookmark.setCaret();
+ }
+
+ /** Shows the bookmarks side panel, listing bookmarks of all open tabs. */
public void listBookmarks() {
- final Vector bookmarks = getAllBookmarks();
- if (!bookmarks.isEmpty()) {
- new BookmarkDialog(this, bookmarks).setVisible(true);
- }
+ sideTabs.setSelectedComponent(outlineSplit);
+ bookmarksPanel.refresh();
}
void clearAllBookmarks() {
@@ -2268,7 +2619,11 @@ public TextEditorTab open(final File file) {
updateLanguageMenu(tab.editorPane.getCurrentLanguage());
tab.editorPane.getDocument().addDocumentListener(this);
- tab.editorPane.requestFocusInWindow();
+ final EditorPane pane = tab.editorPane;
+ pane.addCaretListener(e -> {
+ if (pane == getEditorPane()) updateCaretStatus();
+ });
+ pane.requestFocusInWindow();
return tab;
}
catch (final FileNotFoundException e) {
@@ -2344,7 +2699,7 @@ public boolean makeJar(final boolean includeSources) {
String name = getEditorPane().getFileName();
final String ext = FileUtils.getExtension(name);
- if (!"".equals(ext)) name = name.substring(0, name.length() - ext.length());
+ if (!ext.isEmpty()) name = name.substring(0, name.length() - ext.length());
if (name.indexOf('_') < 0) name += "_";
name += ".jar";
@@ -2398,7 +2753,7 @@ static void getClasses(final File directory, final List paths,
{
String prefix = inPrefix;
- if (!prefix.equals("")) prefix += "/";
+ if (!prefix.isEmpty()) prefix += "/";
for (final File file : directory.listFiles())
if (file.isDirectory()) getClasses(file, paths, names, prefix +
file.getName());
@@ -2457,6 +2812,7 @@ void setLanguage(final ScriptLanguage language, final boolean addHeader) {
private String lastSupportStatus = null;
void updateLanguageMenu(final ScriptLanguage language) {
+ if (statusLang != null) statusLang.setText(languageLabel(language));
JMenuItem item = languageMenuItems.get(language);
if (item == null) {
// is none
@@ -2568,6 +2924,7 @@ else if (tabSize == Integer.parseInt(item.getText())) {
wrapLines.setState(pane.getLineWrap());
marginLine.setState(pane.isMarginLineEnabled());
tabsEmulated.setState(pane.getTabsEmulated());
+ syncStatusBar();
paintTabs.setState(pane.getPaintTabLines());
whiteSpace.setState(pane.isWhitespaceVisible());
autocompletion.setState(pane.isAutoCompletionEnabled());
@@ -4125,6 +4482,22 @@ static Color getDisabledComponentColor() {
}
}
+ public static Color secondaryColor() {
+ try {
+ return UIManager.getColor("SearchField.searchIconColor");
+ } catch (final Exception ignored) {
+ return getDisabledComponentColor();
+ }
+ }
+
+ public static Color accentColor() {
+ try {
+ return UIManager.getColor("Component.accentColor");
+ } catch (final Exception ignored) {
+ return Color.ORANGE.darker();
+ }
+ }
+
static boolean isDarkLaF() {
return FlatLaf.isLafDark() || isDark(new JLabel().getBackground());
}
@@ -4134,6 +4507,39 @@ 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());
+ return b;
+ }
+
+ static JButton ellipsisButton(final Runnable action) {
+ final JButton b = new JButton("⋮");
+ b.setFont(b.getFont().deriveFont(Font.BOLD));
+ b.setFocusable(false);
+ b.putClientProperty(FlatClientProperties.BUTTON_TYPE, FlatClientProperties.BUTTON_TYPE_TOOLBAR_BUTTON);
+ b.addActionListener(e -> action.run());
+ return b;
+ }
+
+
+ /** Rounded scrollbar thumbs without arrow buttons (FlatLaf only) */
+ static void flattenScrollBars(final JScrollPane scrollPane) {
+ final String style = "showButtons: false; trackArc: 999; thumbArc: 999; "
+ + "trackInsets: 2,2,2,2; thumbInsets: 2,2,2,2";
+ scrollPane.getVerticalScrollBar().putClientProperty(FlatClientProperties.STYLE, style);
+ scrollPane.getHorizontalScrollBar().putClientProperty(FlatClientProperties.STYLE, style);
+ }
+
+ /** Plain divider with triangular one-touch arrows (FlatLaf only) */
+ static void flattenSplitPane(final JSplitPane splitPane) {
+ splitPane.putClientProperty(FlatClientProperties.STYLE, "style: plain; arrowType: triangle");
+ }
+
static void collapseAllTreeNodes(final JTree tree) {
final int row1 = (tree.isRootVisible()) ? 1 : 0;
for (int i = row1; i < tree.getRowCount(); i++)
@@ -4148,11 +4554,23 @@ static void expandAllTreeNodes(final JTree tree) {
/* Tweaks for tabbed pane */
static JTabbedPane getJTabbedPane() {
final JTabbedPane tabbed = new JTabbedPane();
+ tabbed.putClientProperty(FlatClientProperties.TABBED_PANE_TAB_ROTATION,
+ FlatClientProperties.TABBED_PANE_TAB_ROTATION_AUTO);
final JPopupMenu popup = new JPopupMenu();
tabbed.setComponentPopupMenu(popup);
- final ButtonGroup bGroup = new ButtonGroup();
+ GuiUtils.addPopupMenuSeparator(popup, "Tab Style:");
+ ButtonGroup bGroup = new ButtonGroup();
+ for (final String option : new String[]{"Card", "Underlined"}) {
+ final JCheckBoxMenuItem jcbmi = new JCheckBoxMenuItem(option, "Underlined".equals(option));
+ jcbmi.addItemListener(e -> tabbed.putClientProperty(FlatClientProperties.TABBED_PANE_TAB_TYPE,
+ option.toLowerCase()));
+ bGroup.add(jcbmi);
+ popup.add(jcbmi);
+ }
+ GuiUtils.addPopupMenuSeparator(popup, "Tab Placement:");
+ bGroup = new ButtonGroup();
for (final String pos : new String[] { "Top", "Left", "Bottom", "Right" }) {
- final JMenuItem jcbmi = new JCheckBoxMenuItem("Place on " + pos, "Top".equals(pos));
+ final JMenuItem jcbmi = new JCheckBoxMenuItem(pos, "Top".equals(pos));
jcbmi.addItemListener(e -> {
switch (pos) {
case "Top":
@@ -4172,49 +4590,40 @@ static JTabbedPane getJTabbedPane() {
bGroup.add(jcbmi);
popup.add(jcbmi);
}
- tabbed.addMouseWheelListener(e -> {
- // https://stackoverflow.com/a/38463104
- final JTabbedPane pane = (JTabbedPane) e.getSource();
- final int units = e.getWheelRotation();
- final int oldIndex = pane.getSelectedIndex();
- final int newIndex = oldIndex + units;
- if (newIndex < 0)
- pane.setSelectedIndex(0);
- else if (newIndex >= pane.getTabCount())
- pane.setSelectedIndex(pane.getTabCount() - 1);
- else
- pane.setSelectedIndex(newIndex);
- });
return tabbed;
}
}
+ /**
+ * Text field displaying a hint while empty. Relies on FlatLaf's placeholder
+ * support, falling back to manual painting under other look and feels.
+ */
static class TextFieldWithPlaceholder extends JTextField {
private static final long serialVersionUID = 1L;
- private String placeholder;
- void setPlaceholder(final String placeholder) {
- this.placeholder = placeholder;
- update(getGraphics());
+ TextFieldWithPlaceholder() {
+ putClientProperty(FlatClientProperties.TEXT_FIELD_SHOW_CLEAR_BUTTON, true);
}
- Font getPlaceholderFont() {
- return getFont().deriveFont(Font.ITALIC);
+ void setPlaceholder(final String placeholder) {
+ putClientProperty(FlatClientProperties.PLACEHOLDER_TEXT, placeholder);
+ repaint();
}
String getPlaceholder() {
- return placeholder;
+ final Object p = getClientProperty(FlatClientProperties.PLACEHOLDER_TEXT);
+ return (p == null) ? "" : p.toString();
}
@Override
protected void paintComponent(final java.awt.Graphics g) {
super.paintComponent(g);
- if (getText().isEmpty()) {
+ if (getText().isEmpty() && !(UIManager.getLookAndFeel() instanceof FlatLaf)) {
final Graphics2D g2 = (Graphics2D) g.create();
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2.setColor(getDisabledTextColor());
- g2.setFont(getPlaceholderFont());
+ g2.setFont(getFont().deriveFont(Font.ITALIC));
g2.drawString(getPlaceholder(), getInsets().left,
g2.getFontMetrics().getHeight() + getInsets().top - getInsets().bottom);
g2.dispose();
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 c353e906..31228d52 100644
--- a/src/main/java/org/scijava/ui/swing/script/TextEditorTab.java
+++ b/src/main/java/org/scijava/ui/swing/script/TextEditorTab.java
@@ -124,6 +124,7 @@ public TextEditorTab(final TextEditor textEditor) {
super(JSplitPane.VERTICAL_SPLIT);
super.setResizeWeight(350.0 / 430.0);
setOneTouchExpandable(true);
+ TextEditor.GuiUtils.flattenSplitPane(this);
this.textEditor = textEditor;
editorPane = new EditorPane();
@@ -281,6 +282,7 @@ public void actionPerformed(final ActionEvent e) {
bc.weighty = 1;
bc.gridwidth = 8;
scroll = new JScrollPane(screen);
+ TextEditor.GuiUtils.flattenScrollBars(scroll);
bottom.add(scroll, bc);
prompt.setEnabled(false);
@@ -354,6 +356,7 @@ public void actionPerformed(final ActionEvent e) {
});
screenAndPromptSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT, bottom, prompt_panel);
+ TextEditor.GuiUtils.flattenSplitPane(screenAndPromptSplit);
// Enable ErrorSrip à la Eclipse. This will keep track of lines with 'Mark All'
// occurrences as well as lines associated with ParserNotice.Level.WARNING and
From 9da8aea17c428b1dc5f241b0d1f8af42890307e2 Mon Sep 17 00:00:00 2001
From: Tiago Ferreira
Date: Sat, 14 Nov 2026 08:15:13 -0500
Subject: [PATCH 02/41] Implement scratchpad and clipboard history pane
---
.../scijava/ui/swing/script/NotesPanel.java | 369 ++++++++++++++++++
1 file changed, 369 insertions(+)
create mode 100644 src/main/java/org/scijava/ui/swing/script/NotesPanel.java
diff --git a/src/main/java/org/scijava/ui/swing/script/NotesPanel.java b/src/main/java/org/scijava/ui/swing/script/NotesPanel.java
new file mode 100644
index 00000000..83b57cc5
--- /dev/null
+++ b/src/main/java/org/scijava/ui/swing/script/NotesPanel.java
@@ -0,0 +1,369 @@
+/*
+ * #%L
+ * Script Editor and Interpreter for SciJava script languages.
+ * %%
+ * Copyright (C) 2009 - 2026 SciJava developers.
+ * %%
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ * #L%
+ */
+
+package org.scijava.ui.swing.script;
+
+import java.awt.BorderLayout;
+import java.awt.Color;
+import java.awt.Component;
+import java.awt.event.KeyAdapter;
+import java.awt.event.KeyEvent;
+import java.awt.event.MouseAdapter;
+import java.awt.event.MouseEvent;
+import java.awt.datatransfer.StringSelection;
+import java.awt.Toolkit;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.function.Supplier;
+import javax.swing.*;
+import javax.swing.border.CompoundBorder;
+import javax.swing.border.EmptyBorder;
+import javax.swing.border.MatteBorder;
+import javax.swing.event.DocumentEvent;
+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;
+
+/**
+ * A "Notes" side panel: a persistent scratchpad (top) and a view of the
+ * editor's clipboard history (bottom). Double-clicking (or pressing Enter on)
+ * a clipboard entry inserts it at the caret of the active editor.
+ *
+ * Clipboard history is the one maintained by RSyntaxTextArea, i.e., it records
+ * what is copied or cut inside the editor. It is not persisted. The scratchpad
+ * is saved to the preferences (in chunks, since preference values are size
+ * limited).
+ *
+ */
+class NotesPanel extends JPanel {
+
+ private static final long serialVersionUID = 1L;
+ private static final String PREFS_COUNT = "script.editor.notes.chunks";
+ private static final String PREFS_CHUNK = "script.editor.notes.chunk";
+ private static final int CHUNK_SIZE = 4000;
+ private static final int MAX_CHARS = 200000;
+ private static final int SAVE_DELAY_MS = 1000;
+ private static final int REFRESH_DELAY_MS = 750;
+ private static final int ROW_MAX_CHARS = 120;
+
+ private final Supplier extends JTextComponent> activeEditor;
+ private final PrefService prefs;
+ private final Class> prefsOwner;
+ private final JTextArea scratch;
+ private final DefaultListModel model = new DefaultListModel<>();
+ private final JList list = new JList<>(model);
+ private final Timer saveTimer;
+ private boolean loading;
+
+ NotesPanel(final Supplier extends JTextComponent> activeEditor,
+ final PrefService prefs, final Class> prefsOwner)
+ {
+ super(new BorderLayout());
+ this.activeEditor = activeEditor;
+ this.prefs = prefs;
+ this.prefsOwner = prefsOwner;
+
+ // Scratchpad
+ scratch = new JTextArea();
+ scratch.setLineWrap(true);
+ scratch.setWrapStyleWord(true);
+ scratch.setBorder(new EmptyBorder(4, 4, 4, 4));
+ scratch.setToolTipText("Scratchpad: free text, saved between sessions");
+ final JScrollPane scratchPane = new JScrollPane(scratch);
+ TextEditor.GuiUtils.flattenScrollBars(scratchPane);
+
+ // Scratchpad
+ final JPanel pane1 = new JPanel(new BorderLayout());
+ final JLabel scratchHeader = header("Scratchpad");
+ pane1.add(scratchHeader, BorderLayout.NORTH);
+ pane1.add(scratchPane, BorderLayout.CENTER);
+
+ // Clipboard history
+ list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
+ list.setCellRenderer(new Renderer());
+ final JScrollPane listPane = new JScrollPane(list);
+ TextEditor.GuiUtils.flattenScrollBars(listPane);
+ final JPanel pane2 = new JPanel(new BorderLayout());
+ final JLabel clipboardHeader = header("Clipboard History (Double-click to Insert)");
+ pane2.add(clipboardHeader, BorderLayout.NORTH);
+ pane2.add(listPane, BorderLayout.CENTER);
+
+ final JSplitPane split = new JSplitPane(JSplitPane.VERTICAL_SPLIT, pane1, pane2);
+ split.setResizeWeight(.75);
+ // No divider: the Scratchpad header (with a hairline on top) is the drag handle
+ TextEditor.GuiUtils.installSplitHandle(clipboardHeader, split);
+ add(split, BorderLayout.CENTER);
+
+ // List interaction
+ list.addMouseListener(new MouseAdapter() {
+
+ @Override
+ public void mouseClicked(final MouseEvent e) {
+ if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 2) {
+ final int idx = list.locationToIndex(e.getPoint());
+ if (idx >= 0 && list.getCellBounds(idx, idx).contains(e.getPoint()))
+ insert(model.get(idx));
+ }
+ }
+
+ @Override
+ public void mousePressed(final MouseEvent e) {
+ maybePopup(e);
+ }
+
+ @Override
+ public void mouseReleased(final MouseEvent e) {
+ maybePopup(e);
+ }
+ });
+ list.addKeyListener(new KeyAdapter() {
+
+ @Override
+ public void keyPressed(final KeyEvent e) {
+ final String sel = list.getSelectedValue();
+ if (sel == null) return;
+ if (e.getKeyCode() == KeyEvent.VK_ENTER) {
+ insert(sel);
+ e.consume();
+ }
+ else if (e.getKeyCode() == KeyEvent.VK_DELETE) {
+ remove(sel);
+ e.consume();
+ }
+ }
+ });
+
+ // Persistence of scratchpad
+ load();
+ saveTimer = new Timer(SAVE_DELAY_MS, e -> save());
+ saveTimer.setRepeats(false);
+ scratch.getDocument().addDocumentListener(new DocumentListener() {
+
+ @Override
+ public void insertUpdate(final DocumentEvent e) {
+ changed();
+ }
+
+ @Override
+ public void removeUpdate(final DocumentEvent e) {
+ changed();
+ }
+
+ @Override
+ public void changedUpdate(final DocumentEvent e) {
+ changed();
+ }
+ });
+
+ // Cheap polling, only while visible. RSyntaxTextArea provides no listener
+ refresh();
+ final Timer poll = new Timer(REFRESH_DELAY_MS, e -> {
+ if (isShowing()) refresh();
+ });
+ poll.start();
+ }
+
+ /** Flushes pending scratchpad changes to the preferences. */
+ void flush() {
+ if (saveTimer.isRunning()) {
+ saveTimer.stop();
+ save();
+ }
+ }
+
+ /** Brings the clipboard list up to date (cheap if nothing changed). */
+ void refresh() {
+ final List history = new ArrayList<>(ClipboardHistory.get()
+ .getHistory());
+ boolean same = history.size() == model.size();
+ for (int i = 0; same && i < history.size(); i++)
+ same = history.get(i).equals(model.get(i));
+ if (same) return;
+ final String selected = list.getSelectedValue();
+ model.clear();
+ for (final String s : history)
+ model.addElement(s);
+ if (selected != null && model.contains(selected))
+ 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(TextEditor.GuiUtils.secondaryColor());
+ return label;
+ }
+
+ private void maybePopup(final MouseEvent e) {
+ if (!e.isPopupTrigger()) return;
+ final int idx = list.locationToIndex(e.getPoint());
+ if (idx >= 0 && list.getCellBounds(idx, idx).contains(e.getPoint()))
+ list.setSelectedIndex(idx);
+ final String sel = list.getSelectedValue();
+ final JPopupMenu menu = new JPopupMenu();
+ JMenuItem mi = new JMenuItem("Insert at Caret");
+ mi.setEnabled(sel != null);
+ mi.addActionListener(a -> insert(sel));
+ menu.add(mi);
+ mi = new JMenuItem("Copy");
+ mi.setEnabled(sel != null);
+ mi.addActionListener(a -> Toolkit.getDefaultToolkit().getSystemClipboard()
+ .setContents(new StringSelection(sel), null));
+ menu.add(mi);
+ mi = new JMenuItem("Send to Scratchpad");
+ mi.setEnabled(sel != null);
+ mi.addActionListener(a -> appendToScratchpad(sel));
+ menu.add(mi);
+ menu.addSeparator();
+ mi = new JMenuItem("Remove Entry");
+ mi.setEnabled(sel != null);
+ mi.addActionListener(a -> remove(sel));
+ menu.add(mi);
+ mi = new JMenuItem("Clear History");
+ mi.setEnabled(!model.isEmpty());
+ mi.addActionListener(a -> clearHistory());
+ menu.add(mi);
+ menu.show(list, e.getX(), e.getY());
+ }
+
+ private void insert(final String text) {
+ final JTextComponent ta = activeEditor.get();
+ if (ta == null || !ta.isEditable() || !ta.isEnabled()) {
+ UIManager.getLookAndFeel().provideErrorFeedback(list);
+ return;
+ }
+ ta.replaceSelection(text);
+ ta.requestFocusInWindow();
+ }
+
+ private void appendToScratchpad(final String text) {
+ final String current = scratch.getText();
+ scratch.append((current.isEmpty() || current.endsWith("\n") ? "" : "\n") +
+ text + "\n");
+ scratch.setCaretPosition(scratch.getDocument().getLength());
+ }
+
+ private void remove(final String text) {
+ final List live = liveHistory();
+ if (live != null) live.remove(text);
+ refresh();
+ }
+
+ private void clearHistory() {
+ final List live = liveHistory();
+ if (live != null) live.clear();
+ refresh();
+ }
+
+ /**
+ * ClipboardHistory#getHistory() returns a copy, and the API offers no way
+ * to remove entries. Access the backing list (best effort).
+ */
+ @SuppressWarnings("unchecked")
+ private static List liveHistory() {
+ try {
+ final java.lang.reflect.Field f = ClipboardHistory.class
+ .getDeclaredField("history");
+ f.setAccessible(true);
+ return (List) f.get(ClipboardHistory.get());
+ }
+ catch (final Exception | LinkageError ignored) {
+ return null;
+ }
+ }
+
+ private void changed() {
+ if (!loading) saveTimer.restart();
+ }
+
+ private void load() {
+ loading = true;
+ try {
+ final int n = prefs.getInt(prefsOwner, PREFS_COUNT, 0);
+ final StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < n; i++)
+ sb.append(prefs.get(prefsOwner, PREFS_CHUNK + i, ""));
+ scratch.setText(sb.toString());
+ scratch.setCaretPosition(0);
+ }
+ catch (final RuntimeException ignored) {
+ // preferences are best effort
+ }
+ finally {
+ loading = false;
+ }
+ }
+
+ private void save() {
+ try {
+ String text = scratch.getText();
+ if (text.length() > MAX_CHARS) text = text.substring(0, MAX_CHARS);
+ final int oldCount = prefs.getInt(prefsOwner, PREFS_COUNT, 0);
+ final int n = (text.length() + CHUNK_SIZE - 1) / CHUNK_SIZE;
+ for (int i = 0; i < n; i++)
+ prefs.put(prefsOwner, PREFS_CHUNK + i, text.substring(i * CHUNK_SIZE,
+ Math.min(text.length(), (i + 1) * CHUNK_SIZE)));
+ for (int i = n; i < oldCount; i++)
+ prefs.remove(prefsOwner, PREFS_CHUNK + i);
+ prefs.put(prefsOwner, PREFS_COUNT, n);
+ }
+ catch (final RuntimeException ignored) {
+ // preferences are best effort
+ }
+ }
+
+ private static String escape(final String s) {
+ return s.replace("&", "&").replace("<", "<").replace(">", ">");
+ }
+
+ private static class Renderer extends DefaultListCellRenderer {
+
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public Component getListCellRendererComponent(final JList> l,
+ final Object value, final int index, final boolean selected,
+ final boolean focus)
+ {
+ final String s = String.valueOf(value);
+ String oneLine = s.trim().replaceAll("\\s+", " ");
+ if (oneLine.length() > ROW_MAX_CHARS) oneLine = oneLine.substring(0,
+ ROW_MAX_CHARS) + "...";
+ super.getListCellRendererComponent(l, oneLine, index, selected, focus);
+ setBorder(new EmptyBorder(2, 6, 2, 6));
+ String tip = s.length() > 1500 ? s.substring(0, 1500) + "\n..." : s;
+ setToolTipText("" + escape(tip) + "
");
+ return this;
+ }
+ }
+}
From 27c2aeb53631079e4b23cf682ac628332abc66c0 Mon Sep 17 00:00:00 2001
From: Tiago Ferreira
Date: Sat, 14 Nov 2026 08:15:30 -0500
Subject: [PATCH 03/41] Implement Bookmarks panel
---
.../ui/swing/script/BookmarksPanel.java | 261 ++++++++++++++++++
1 file changed, 261 insertions(+)
create mode 100644 src/main/java/org/scijava/ui/swing/script/BookmarksPanel.java
diff --git a/src/main/java/org/scijava/ui/swing/script/BookmarksPanel.java b/src/main/java/org/scijava/ui/swing/script/BookmarksPanel.java
new file mode 100644
index 00000000..4e875152
--- /dev/null
+++ b/src/main/java/org/scijava/ui/swing/script/BookmarksPanel.java
@@ -0,0 +1,261 @@
+/*
+ * #%L
+ * Script Editor and Interpreter for SciJava script languages.
+ * %%
+ * Copyright (C) 2009 - 2026 SciJava developers.
+ * %%
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ * #L%
+ */
+
+
+package org.scijava.ui.swing.script;
+
+import java.awt.BorderLayout;
+import java.awt.Component;
+import java.awt.Graphics;
+import java.awt.event.KeyAdapter;
+import java.awt.event.KeyEvent;
+import java.awt.event.MouseAdapter;
+import java.awt.event.MouseEvent;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.function.Consumer;
+import java.util.function.Supplier;
+
+import javax.swing.DefaultListCellRenderer;
+import javax.swing.DefaultListModel;
+import javax.swing.JLabel;
+import javax.swing.JList;
+import javax.swing.JMenuItem;
+import javax.swing.JPanel;
+import javax.swing.JPopupMenu;
+import javax.swing.JScrollPane;
+import javax.swing.ListSelectionModel;
+import javax.swing.SwingUtilities;
+import javax.swing.Timer;
+import javax.swing.border.EmptyBorder;
+import javax.swing.text.BadLocationException;
+
+/**
+ * A "Bookmarks" side panel listing the bookmarks of all open editor tabs.
+ * Double-clicking (or pressing Enter on) an entry jumps to it. Bookmarks are
+ * toggled in the editor gutter, so the list is kept up to date by a cheap check
+ * that only runs while the panel is visible.
+ */
+class BookmarksPanel extends JPanel {
+
+ private static final long serialVersionUID = 1L;
+ private static final int REFRESH_DELAY_MS = 750;
+ private static final int TEXT_MAX_CHARS = 100;
+
+ private final Supplier> source;
+ private final Consumer jumper;
+ private final DefaultListModel model = new DefaultListModel<>();
+ private final List signature = new ArrayList<>();
+ private final JList list;
+
+ /**
+ * @param source supplies the current bookmarks of all tabs (in display order)
+ * @param jumper moves the editor to the given bookmark
+ */
+ BookmarksPanel(final Supplier> source,
+ final Consumer jumper)
+ {
+ super(new BorderLayout());
+ this.source = source;
+ this.jumper = jumper;
+
+ list = new JList<>(model) {
+
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ protected void paintComponent(final Graphics g) {
+ super.paintComponent(g);
+ if (model.isEmpty()) paintEmptyHint((java.awt.Graphics2D) g.create(),
+ this, "No bookmarks", "Click next to a line number", "to bookmark it");
+ }
+ };
+ list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
+ list.setCellRenderer(new Renderer());
+ final JScrollPane pane = new JScrollPane(list);
+ TextEditor.GuiUtils.flattenScrollBars(pane);
+ add(pane, BorderLayout.CENTER);
+
+ list.addMouseListener(new MouseAdapter() {
+
+ @Override
+ public void mouseClicked(final MouseEvent e) {
+ if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 2) {
+ final int idx = list.locationToIndex(e.getPoint());
+ if (idx >= 0 && list.getCellBounds(idx, idx).contains(e.getPoint()))
+ jumper.accept(model.get(idx));
+ }
+ }
+
+ @Override
+ public void mousePressed(final MouseEvent e) {
+ maybePopup(e);
+ }
+
+ @Override
+ public void mouseReleased(final MouseEvent e) {
+ maybePopup(e);
+ }
+ });
+ list.addKeyListener(new KeyAdapter() {
+
+ @Override
+ public void keyPressed(final KeyEvent e) {
+ final Bookmark sel = list.getSelectedValue();
+ if (sel == null) return;
+ if (e.getKeyCode() == KeyEvent.VK_ENTER) {
+ jumper.accept(sel);
+ e.consume();
+ }
+ else if (e.getKeyCode() == KeyEvent.VK_DELETE) {
+ remove(sel);
+ e.consume();
+ }
+ }
+ });
+
+ refresh();
+ final Timer poll = new Timer(REFRESH_DELAY_MS, e -> {
+ if (isShowing()) refresh();
+ });
+ poll.start();
+ }
+
+ private static void paintEmptyHint(final java.awt.Graphics2D g2,
+ final Component c, final String... lines)
+ {
+ try {
+ g2.setRenderingHint(java.awt.RenderingHints.KEY_TEXT_ANTIALIASING,
+ java.awt.RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
+ g2.setColor(TextEditor.GuiUtils.secondaryColor());
+ final java.awt.FontMetrics fm = g2.getFontMetrics();
+ int y = (c.getHeight() - fm.getHeight() * lines.length) / 2 + fm
+ .getAscent();
+ for (final String line : lines) {
+ g2.drawString(line, (c.getWidth() - fm.stringWidth(line)) / 2, y);
+ y += fm.getHeight();
+ }
+ }
+ finally {
+ g2.dispose();
+ }
+ }
+
+ /** Brings the list up to date (cheap if nothing changed). */
+ void refresh() {
+ final List current = source.get();
+ final List sig = new ArrayList<>(current.size());
+ for (final Bookmark bk : current)
+ sig.add(System.identityHashCode(bk.tab) + ":" + bk.getLineNumber() + ":" +
+ lineText(bk));
+ if (sig.equals(signature)) return;
+ signature.clear();
+ signature.addAll(sig);
+ final int selectedLine = list.getSelectedValue() == null ? -1 : list
+ .getSelectedIndex();
+ model.clear();
+ for (final Bookmark bk : current)
+ model.addElement(bk);
+ if (selectedLine >= 0 && selectedLine < model.size()) list
+ .setSelectedIndex(selectedLine);
+ }
+
+ private void remove(final Bookmark bk) {
+ bk.tab.editorPane.toggleBookmark(bk.getLineNumber());
+ refresh();
+ }
+
+ private void clearAll() {
+ for (final Bookmark bk : new ArrayList<>(source.get()))
+ bk.tab.editorPane.toggleBookmark(bk.getLineNumber());
+ refresh();
+ }
+
+ private void maybePopup(final MouseEvent e) {
+ if (!e.isPopupTrigger()) return;
+ final int idx = list.locationToIndex(e.getPoint());
+ if (idx >= 0 && list.getCellBounds(idx, idx).contains(e.getPoint()))
+ list.setSelectedIndex(idx);
+ final Bookmark sel = list.getSelectedValue();
+ final JPopupMenu menu = new JPopupMenu();
+ JMenuItem mi = new JMenuItem("Go to Bookmark");
+ mi.setEnabled(sel != null);
+ mi.addActionListener(a -> jumper.accept(sel));
+ menu.add(mi);
+ mi = new JMenuItem("Remove Bookmark");
+ mi.setEnabled(sel != null);
+ mi.addActionListener(a -> remove(sel));
+ menu.add(mi);
+ menu.addSeparator();
+ mi = new JMenuItem("Clear All Bookmarks");
+ mi.setEnabled(!model.isEmpty());
+ mi.addActionListener(a -> clearAll());
+ menu.add(mi);
+ menu.show(list, e.getX(), e.getY());
+ }
+
+ /** The (trimmed) text of the bookmarked line, or an empty string. */
+ private static String lineText(final Bookmark bk) {
+ try {
+ final int line = bk.getLineNumber();
+ if (line < 0) return "";
+ final int start = bk.tab.editorPane.getLineStartOffset(line);
+ final int end = bk.tab.editorPane.getLineEndOffset(line);
+ String s = bk.tab.editorPane.getText(start, end - start).trim()
+ .replaceAll("\\s+", " ");
+ if (s.length() > TEXT_MAX_CHARS) s = s.substring(0, TEXT_MAX_CHARS) +
+ "...";
+ return s;
+ }
+ catch (final BadLocationException | RuntimeException ignored) {
+ return "";
+ }
+ }
+
+ private static class Renderer extends DefaultListCellRenderer {
+
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public Component getListCellRendererComponent(final JList> l,
+ final Object value, final int index, final boolean selected,
+ final boolean focus)
+ {
+ final Bookmark bk = (Bookmark) value;
+ final String name = bk.tab.editorPane.getFileName();
+ final String text = lineText(bk);
+ super.getListCellRendererComponent(l, (name == null ? "Untitled"
+ : name) + ":" + (bk.getLineNumber() + 1) + (text.isEmpty() ? ""
+ : " " + text), index, selected, focus);
+ setBorder(new EmptyBorder(2, 6, 2, 6));
+ setToolTipText(text.isEmpty() ? null : text);
+ return this;
+ }
+ }
+}
From 4261a51a21b744282f7335e1c4d7f5dcac5ea764 Mon Sep 17 00:00:00 2001
From: Tiago Ferreira
Date: Sat, 14 Nov 2026 08:26:22 -0500
Subject: [PATCH 04/41] Organize layout with status bar
---
pom.xml | 1 +
.../scijava/ui/swing/script/TextEditor.java | 274 +++++++++---
.../ui/swing/script/TextEditorTab.java | 421 +++++++++++-------
3 files changed, 472 insertions(+), 224 deletions(-)
diff --git a/pom.xml b/pom.xml
index 06ff8814..72de36d2 100644
--- a/pom.xml
+++ b/pom.xml
@@ -206,6 +206,7 @@
com.formdev
flatlaf
+ 3.8
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 ddfeacd4..6be99adf 100644
--- a/src/main/java/org/scijava/ui/swing/script/TextEditor.java
+++ b/src/main/java/org/scijava/ui/swing/script/TextEditor.java
@@ -99,37 +99,7 @@
import javax.script.ScriptEngine;
import javax.script.ScriptException;
-import javax.swing.AbstractAction;
-import javax.swing.AbstractButton;
-import javax.swing.Icon;
-import javax.swing.Box;
-import javax.swing.BoxLayout;
-import javax.swing.JComponent;
-import javax.swing.JToggleButton;
-import javax.swing.ButtonGroup;
-import javax.swing.JButton;
-import javax.swing.JCheckBoxMenuItem;
-import javax.swing.JDialog;
-import javax.swing.JFrame;
-import javax.swing.JLabel;
-import javax.swing.JMenu;
-import javax.swing.JMenuBar;
-import javax.swing.JMenuItem;
-import javax.swing.JOptionPane;
-import javax.swing.JPanel;
-import javax.swing.JPopupMenu;
-import javax.swing.JRadioButtonMenuItem;
-import javax.swing.JScrollPane;
-import javax.swing.JSplitPane;
-import javax.swing.JTabbedPane;
-import javax.swing.JTextArea;
-import javax.swing.JToolBar;
-import javax.swing.JTextField;
-import javax.swing.JTextPane;
-import javax.swing.JTree;
-import javax.swing.KeyStroke;
-import javax.swing.SwingUtilities;
-import javax.swing.UIManager;
+import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentEvent;
@@ -254,12 +224,11 @@ public class TextEditor extends JFrame implements ActionListener,
private int tabsMenuTabsStart;
private Set tabsMenuItems;
private FindAndReplaceDialog findDialog;
- private JToggleButton statusFast;
private JButton statusTab;
private FlatSearchIcon statusFastIcon;
private JToggleButton statusWrap;
private JButton statusPos, statusLang;
- private JToggleButton statusSide;
+ private JToggleButton statusSide, statusBelow, statusRight, statusRepl;
private int sideLastLocation = -1;
private JMenu languageMenu;
private JLabel statusText;
@@ -360,12 +329,27 @@ public TextEditor(final Context context) {
}
});
sideTabs.addTab("Files", filesPanel);
+
sourceTreePanel = new OutlineTreePanel();
bookmarksPanel = new BookmarksPanel(this::collectBookmarks, this::goToBookmark);
- outlineSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT, sourceTreePanel, bookmarksPanel);
+
+ // Scratchpad
+ final JPanel pane1 = new JPanel(new BorderLayout());
+ final JLabel outlineHeader = header("Structure");
+ pane1.add(outlineHeader, BorderLayout.NORTH);
+ pane1.add(sourceTreePanel, BorderLayout.CENTER);
+
+ // Clipboard history
+ final JPanel pane2 = new JPanel(new BorderLayout());
+ final JLabel bookmarkHeader = header("Bookmarks");
+ pane2.add(bookmarkHeader, BorderLayout.NORTH);
+ pane2.add(bookmarksPanel, BorderLayout.CENTER);
+
+ outlineSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT, pane1, pane2);
outlineSplit.setResizeWeight(.75);
- outlineSplit.setContinuousLayout(true);
- GuiUtils.flattenSplitPane(outlineSplit);
+ // No divider: the Scratchpad header (with a hairline on top) is the drag handle
+ TextEditor.GuiUtils.installSplitHandle(bookmarkHeader, outlineSplit);
+
sideTabs.addTab("Outline", outlineSplit);
notesPanel = new NotesPanel(() -> {
try {
@@ -376,6 +360,7 @@ public TextEditor(final Context context) {
}, prefService, getClass());
sideTabs.addTab("Notes", notesPanel);
body = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, sideTabs, tabbed);
+ GuiUtils.installSplitHandle(null, body);
// These items are dynamic and need to be initialized before EditorPane creation
initializeDynamicMenuComponents();
@@ -757,8 +742,6 @@ public TextEditor(final Context context) {
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
// Tweaks for JSplitPane
- body.setOneTouchExpandable(false); // the side panel is collapsed from the status bar
- GuiUtils.flattenSplitPane(body);
body.addPropertyChangeListener(evt -> {
if ("dividerLocation".equals(evt.getPropertyName())) saveWindowSizeToPrefs();
});
@@ -899,6 +882,14 @@ private void resetLayout() {
pack();
}
+ 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(TextEditor.GuiUtils.secondaryColor());
+ return label;
+ }
+
private void assembleEditMenu() {
// requires an existing instance of an EditorPane
final int ctrl = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
@@ -1855,13 +1846,6 @@ private void setAutoCompletionEnabled(final boolean enabled) {
/** Builds the permanent, full-width status bar: Fast | status text | glue | GoTo | Tab | Lock */
private JComponent assembleStatusBar() {
- statusFast = statusButton("Fast Mode", "Fast mode for large folders: turns off live updates and the search of collapsed folders", true);
- statusFastIcon = new FlatSearchIcon(true);
- statusFast.setIcon(statusFastIcon);
- statusFast.addActionListener(e -> {
- filesPanel.setFastMode(statusFast.isSelected());
- updateFastLook();
- });
statusText = new JLabel(" ");
statusText.setFont(statusText.getFont().deriveFont(statusText.getFont().getSize2D() * .9f));
statusText.setForeground(GuiUtils.secondaryColor());
@@ -1906,13 +1890,6 @@ public Dimension getPreferredSize() { // fixed width: neighbors do not move as t
menu.show(statusTab, 0, -menu.getPreferredSize().height); // opens upwards: the bar is at the bottom
});
filesPanel.setStatusListener(t -> statusText.setText(t == null || t.isEmpty() ? " " : t));
- filesPanel.setFastModeListener(b -> {
- statusFast.setSelected(b);
- updateFastLook();
- });
- filesPanel.setFastModeSuggestionListener(() -> setFastColor(GuiUtils.accentColor()));
- statusFast.setSelected(filesPanel.isFastMode());
- updateFastLook();
statusSide = new JToggleButton(new SidebarIcon());
statusSide.setToolTipText("Shows/hides the side panel (Files, Outline, Notes)");
statusSide.setFocusable(false);
@@ -1929,20 +1906,48 @@ public Dimension getPreferredSize() { // fixed width: neighbors do not move as t
final int loc = body.getDividerLocation();
if (loc > 50) sideLastLocation = loc;
statusSide.setSelected(loc > 5);
- statusFast.setVisible(loc > 5); // Fast mode only concerns the Files pane
+ });
+ // Layout of the console: below or beside the editor. Clicking the active one collapses/restores it
+ statusBelow = new JToggleButton(new BottomPaneIcon());
+ statusBelow.setToolTipText("Console below the editor (click again to hide/show it)");
+ statusRight = new JToggleButton(new RightPaneIcon());
+ statusRight.setToolTipText("Console beside the editor (click again to hide/show it)");
+ for (final JToggleButton b : new JToggleButton[] { statusBelow, statusRight }) {
+ b.setFocusable(false);
+ b.putClientProperty(FlatClientProperties.BUTTON_TYPE, FlatClientProperties.BUTTON_TYPE_TOOLBAR_BUTTON);
+ }
+ statusBelow.setSelected(true);
+ statusBelow.addActionListener(e -> {
+ getTab().toggleLayout(true);
+ syncStatusBar();
+ });
+ statusRight.addActionListener(e -> {
+ getTab().toggleLayout(false);
+ syncStatusBar();
+ });
+ statusRepl = new JToggleButton("REPL", new ReplIcon());
+ cmdPalette.register(statusRepl, "Interpreter");
+ statusRepl.setFont(statusRepl.getFont().deriveFont(statusRepl.getFont().getSize2D() * .9f));
+ statusRepl.setToolTipText("Turns the REPL prompt on/off (of the active tab). Requires a language");
+ statusRepl.setFocusable(false);
+ statusRepl.addActionListener(e -> {
+ getTab().setREPLEnabled(statusRepl.isSelected());
+ syncStatusBar(); // e.g., no language: the request was refused
});
final JToolBar bar = new JToolBar();
bar.add(statusSide);
- bar.add(Box.createHorizontalStrut(4));
- bar.add(statusFast);
+ bar.add(statusBelow);
+ bar.add(statusRight);
bar.add(Box.createHorizontalStrut(8));
bar.add(statusText);
bar.add(Box.createHorizontalGlue());
+ bar.add(statusRepl);
+ //bar.add(Box.createHorizontalStrut(8));
bar.add(statusPos);
bar.add(statusLang);
bar.add(statusWrap);
bar.add(statusTab);
- bar.add(Box.createHorizontalStrut(10));
+ bar.add(Box.createHorizontalStrut(8));
bar.setBorder(null);
bar.setAlignmentX(Component.LEFT_ALIGNMENT); // same as body (JSplitPane), or BoxLayout shifts the body
syncStatusBar();
@@ -1958,18 +1963,6 @@ private JToggleButton statusButton(final String label, final String tooltip, fin
return b;
}
- /** Fast button: accent color while on, secondary otherwise (whatever changed the state: button, menu, auto-switch) */
- private void updateFastLook() {
- setFastColor(statusFast.isSelected() ? GuiUtils.accentColor() : GuiUtils.secondaryColor());
- }
-
- /** Colors the label and the (search) icon of the Fast button */
- private void setFastColor(final Color c) {
- statusFast.setForeground(c);
- if (c != null) statusFastIcon.applyStyleProperty("searchIconColor", c);
- statusFast.repaint();
- }
-
/** Menu of the indentation button: what the Tab key inserts, tab width, and conversion of existing indentation */
private JPopupMenu indentationMenu() {
final JPopupMenu menu = new JPopupMenu();
@@ -2069,6 +2062,91 @@ private void convertIndentation(final boolean toSpaces) {
}
}
+ /** REPL icon: a prompt (>_) inside a window. Painted with the foreground of its button */
+ static final class ReplIcon implements Icon {
+
+ @Override
+ public void paintIcon(final Component c, final Graphics g, final int x, final int y) {
+ final Graphics2D g2 = (Graphics2D) g.create();
+ try {
+ g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
+ g2.setColor(c.getForeground());
+ g2.drawRoundRect(x + 1, y + 2, 13, 11, 3, 3);
+ g2.drawLine(x + 4, y + 5, x + 6, y + 7); // chevron
+ g2.drawLine(x + 6, y + 7, x + 4, y + 9);
+ g2.drawLine(x + 8, y + 10, x + 11, y + 10); // cursor
+ } finally {
+ g2.dispose();
+ }
+ }
+
+ @Override
+ public int getIconWidth() {
+ return 16;
+ }
+
+ @Override
+ public int getIconHeight() {
+ return 16;
+ }
+ }
+
+ /** Right pane icon: a window with a pane on its right side, filled when the pane is shown */
+ private static final class RightPaneIcon implements Icon {
+
+ @Override
+ public void paintIcon(final Component c, final Graphics g, final int x, final int y) {
+ final Graphics2D g2 = (Graphics2D) g.create();
+ try {
+ g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
+ g2.setColor(c.getForeground());
+ g2.drawRoundRect(x + 1, y + 2, 13, 11, 3, 3);
+ if (c instanceof AbstractButton && ((AbstractButton) c).isSelected()) g2.fillRect(x + 9, y + 3, 4, 10);
+ else g2.drawLine(x + 9, y + 3, x + 9, y + 12);
+ } finally {
+ g2.dispose();
+ }
+ }
+
+ @Override
+ public int getIconWidth() {
+ return 16;
+ }
+
+ @Override
+ public int getIconHeight() {
+ return 16;
+ }
+ }
+
+ /** Bottom pane icon: a window with a pane below, filled when the pane is shown */
+ private static final class BottomPaneIcon implements Icon {
+
+ @Override
+ public void paintIcon(final Component c, final Graphics g, final int x, final int y) {
+ final Graphics2D g2 = (Graphics2D) g.create();
+ try {
+ g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
+ g2.setColor(c.getForeground());
+ g2.drawRoundRect(x + 1, y + 2, 13, 11, 3, 3);
+ if (c instanceof AbstractButton && ((AbstractButton) c).isSelected()) g2.fillRect(x + 2, y + 8, 12, 4);
+ else g2.drawLine(x + 2, y + 8, x + 13, y + 8);
+ } finally {
+ g2.dispose();
+ }
+ }
+
+ @Override
+ public int getIconWidth() {
+ return 16;
+ }
+
+ @Override
+ public int getIconHeight() {
+ return 16;
+ }
+ }
+
/** Side panel icon: a window with a left pane, filled when the pane is shown. Painted with the foreground of its button */
private static final class SidebarIcon implements Icon {
@@ -2116,16 +2194,21 @@ private void updateCaretStatus() {
}
/** Updates the toggles of the status bar from the state of the active editor */
- private void syncStatusBar() {
+ void syncStatusBar() {
if (statusTab == null || statusWrap == null) return;
try {
final EditorPane pane = getEditorPane();
statusWrap.setSelected(pane.getLineWrap());
+ if (statusBelow != null) {
+ final TextEditorTab tab = getTab();
+ final boolean shown = tab.isBottomVisible();
+ statusBelow.setSelected(shown && tab.isLayoutBelow());
+ statusRight.setSelected(shown && !tab.isLayoutBelow());
+ }
+ if (statusRepl != null) statusRepl.setSelected(getTab().isREPLEnabled());
statusLang.setText(languageLabel(pane.getCurrentLanguage()));
updateCaretStatus();
statusTab.setText((pane.getTabsEmulated() ? "Spaces: " : "Tab: ") + pane.getTabSize());
- statusFast.setSelected(filesPanel.isFastMode());
- updateFastLook();
} catch (final RuntimeException ignored) {
// no editor yet
}
@@ -4535,9 +4618,52 @@ static void flattenScrollBars(final JScrollPane scrollPane) {
scrollPane.getHorizontalScrollBar().putClientProperty(FlatClientProperties.STYLE, style);
}
- /** Plain divider with triangular one-touch arrows (FlatLaf only) */
- static void flattenSplitPane(final JSplitPane splitPane) {
- splitPane.putClientProperty(FlatClientProperties.STYLE, "style: plain; arrowType: triangle");
+ /**
+ * Removes the divider of a vertical (top/bottom) split pane and lets {@code handle} act as
+ * the divider instead. {@code handle} must sit at the top edge of the lower component, e.g.,
+ * a header label or a toolbar. Dragging any part of it that does not handle mouse events
+ * itself (labels, glue, gaps) moves the split. If the split pane is later switched to a
+ * horizontal (left/right) orientation, its regular divider is restored.
+ */
+ static void installSplitHandle(final JComponent handle, final JSplitPane split) {
+ split.setContinuousLayout(true);
+ split.setOneTouchExpandable(false);
+ split.putClientProperty(FlatClientProperties.STYLE, "style: plain;");
+ if (handle == null) return;
+ final int regularSize = split.getDividerSize();
+ final Runnable update = () -> {
+ final boolean active = split.getOrientation() == JSplitPane.VERTICAL_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);
+ update.run();
+ split.addPropertyChangeListener(JSplitPane.ORIENTATION_PROPERTY, evt -> update.run());
+ final int[] grab = new int[1];
+ handle.addMouseListener(new java.awt.event.MouseAdapter() {
+
+ @Override
+ public void mousePressed(final java.awt.event.MouseEvent e) {
+ grab[0] = e.getY();
+ }
+ });
+ handle.addMouseMotionListener(new java.awt.event.MouseAdapter() {
+
+ @Override
+ public void mouseDragged(final java.awt.event.MouseEvent e) {
+ if (split.getOrientation() != JSplitPane.VERTICAL_SPLIT) return;
+ final int y = SwingUtilities.convertPoint(handle, e.getPoint(), split).y;
+ split.setDividerLocation(Math.max(0, y - grab[0]));
+ }
+ });
}
static void collapseAllTreeNodes(final JTree tree) {
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 31228d52..e99394a5 100644
--- a/src/main/java/org/scijava/ui/swing/script/TextEditorTab.java
+++ b/src/main/java/org/scijava/ui/swing/script/TextEditorTab.java
@@ -32,9 +32,12 @@
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
+import java.awt.Component;
import java.awt.Font;
-import java.awt.GridBagConstraints;
-import java.awt.GridBagLayout;
+import java.awt.Graphics2D;
+import java.awt.geom.Path2D;
+import java.awt.geom.RoundRectangle2D;
+import java.awt.FlowLayout;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.dnd.DnDConstants;
@@ -47,22 +50,16 @@
import java.awt.event.ActionListener;
import java.io.File;
import java.util.List;
-
-import javax.swing.BorderFactory;
-import javax.swing.JButton;
-import javax.swing.JCheckBox;
-import javax.swing.JComboBox;
-import javax.swing.JLabel;
-import javax.swing.JPanel;
-import javax.swing.JScrollPane;
-import javax.swing.JSplitPane;
-import javax.swing.JTextArea;
-import javax.swing.SwingUtilities;
+import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.JTextComponent;
+import com.formdev.flatlaf.FlatClientProperties;
+import com.formdev.flatlaf.icons.FlatAbstractIcon;
+import com.formdev.flatlaf.icons.FlatFileChooserDetailsViewIcon;
+import com.formdev.flatlaf.icons.FlatHelpButtonIcon;
import org.fife.ui.rsyntaxtextarea.ErrorStrip;
import org.fife.ui.rsyntaxtextarea.Style;
import org.fife.ui.rsyntaxtextarea.Token;
@@ -75,9 +72,6 @@
*/
public class TextEditorTab extends JSplitPane {
- private static final String DOWN_ARROW = "\u25BC";
- private static final String RIGHT_ARROW = "\u25B6";
-
/** Which console stream(s) to display. */
private enum ConsoleView {
BOTH("Output+Errors"), OUTPUT("Output"), ERRORS("Errors");
@@ -99,10 +93,9 @@ public String toString() {
/** Output and errors interleaved, in the order they were written. */
private final ConsoleArea combinedScreen = new ConsoleArea(ConsoleArea.Content.MIXED);
protected final JTextArea prompt = new JTextArea();
- private final JLabel prompt_title = new JLabel();
/** Status line for vim mode: the mode, partial command or message. */
private final JLabel vimStatus = new JLabel(" ");
- protected final JCheckBox updownarrows = new JCheckBox("Use arrow keys");
+ protected final JToggleButton updownarrows = new JToggleButton();
protected final JScrollPane scroll;
/** True iff the console is showing errors only. */
protected boolean showingErrors;
@@ -110,11 +103,14 @@ public String toString() {
private boolean updatingViewChooser;
private volatile boolean skipErrorMirroring;
private Executer executer;
- private final JButton runit, batchit, killit, switchSplit;
+ private final JButton runit, batchit, killit;
private final JComboBox viewChooser;
- private final JCheckBox incremental;
+ private boolean replOn; // the REPL is on (prompt shown)
+ private JPanel promptPanel;
+ private int promptDividerSize; // thickness of the divider above the prompt (hidden while the REPL is off)
private final JSplitPane screenAndPromptSplit;
private int screenAndPromptSplitDividerLocation;
+ private int bottomLastLocation = -1; // divider location while the bottom part was last shown
private final TextEditor textEditor;
private DropTarget dropTarget;
@@ -123,8 +119,6 @@ public String toString() {
public TextEditorTab(final TextEditor textEditor) {
super(JSplitPane.VERTICAL_SPLIT);
super.setResizeWeight(350.0 / 430.0);
- setOneTouchExpandable(true);
- TextEditor.GuiUtils.flattenSplitPane(this);
this.textEditor = textEditor;
editorPane = new EditorPane();
@@ -187,103 +181,63 @@ public void dragEnter(final DropTargetDragEvent e) {
mirrorInto(combinedScreen, screen, false);
mirrorInto(combinedScreen, textEditor.getErrorScreen(), true);
- final JPanel bottom = new JPanel();
- bottom.setLayout(new GridBagLayout());
- final GridBagConstraints bc = new GridBagConstraints();
-
- bc.gridx = 0;
- bc.gridy = 0;
- bc.weightx = 0;
- bc.weighty = 0;
- bc.anchor = GridBagConstraints.CENTER;
- bc.fill = GridBagConstraints.HORIZONTAL;
- runit = new JButton("Run");
+ final JPanel bottom = new JPanel(new BorderLayout());
+ final JToolBar bar = new JToolBar();
+ bar.setFloatable(false);
+ bar.setBorder(BorderFactory.createEmptyBorder(1, 2, 1, 2));
+
+ runit = new JButton("Run", new PlayIcon(false));
+ runit.setDisabledIcon(new PlayIcon(true));
runit.setToolTipText("Control+R, F5, or F11");
textEditor.cmdPalette.register(runit, "Interpreter");
runit.addActionListener(ae -> textEditor.runText());
- bottom.add(runit, bc);
+ bar.add(runit);
- bc.gridx = 1;
- batchit = new JButton("Batch");
+ batchit = new JButton("Batch", new FastForwardIcon(false));
+ batchit.putClientProperty("JButton.buttonType", "borderless");
+
+ batchit.setDisabledIcon(new FastForwardIcon(true));
batchit.setToolTipText("Requires at least one @File SciJava parameter to be declared");
batchit.addActionListener(e -> textEditor.runBatch());
- bottom.add(batchit, bc);
+ bar.add(batchit);
- bc.gridx = 2;
- killit = new JButton("Kill");
+ killit = new JButton("Stop", new StopIcon(false));
+ killit.setDisabledIcon(new StopIcon(true));
+ killit.setToolTipText("Stop the running script (interrupts its thread)");
killit.setEnabled(false);
killit.addActionListener(ae -> kill());
- bottom.add(killit, bc);
-
- bc.gridx = 3;
- incremental = new JCheckBox("REPL");
- textEditor.cmdPalette.register(incremental, "Interpreter");
- incremental.setEnabled(true);
- incremental.setSelected(false);
- bottom.add(incremental, bc);
-
- bc.gridx = 4;
- bc.fill = GridBagConstraints.HORIZONTAL;
- bc.weightx = 1;
- bottom.add(new JPanel(), bc);
-
- bc.gridx = 5;
- bc.fill = GridBagConstraints.NONE;
- bc.weightx = 0;
- bc.anchor = GridBagConstraints.NORTHEAST;
+ bar.add(killit);
+
+ bar.add(Box.createHorizontalGlue());
+
viewChooser = new JComboBox<>(ConsoleView.values());
viewChooser.setToolTipText("Which console streams to show");
viewChooser.addActionListener(e -> {
if (!updatingViewChooser) setView((ConsoleView) viewChooser.getSelectedItem());
});
- final JPanel viewPanel = new JPanel(new BorderLayout(4, 0));
- viewPanel.add(new JLabel("Show:"), BorderLayout.LINE_START);
- viewPanel.add(viewChooser, BorderLayout.CENTER);
- bottom.add(viewPanel, bc);
-
- bc.gridx = 6;
- bc.fill = GridBagConstraints.NONE;
- bc.weightx = 0;
- bc.anchor = GridBagConstraints.NORTHEAST;
- final JButton clear = new JButton("Clear");
+ final JPanel viewPanel = new JPanel();
+ viewPanel.setOpaque(false);
+ viewPanel.add(new JLabel("Show:"));
+ viewPanel.add(viewChooser);
+ viewPanel.setMaximumSize(viewPanel.getPreferredSize()); // do not stretch
+ bar.add(viewPanel);
+ bar.add(Box.createHorizontalStrut(4));
+
+ final JButton clear = new JButton("Clear", new TrashIcon(false));
+ clear.setDisabledIcon(new TrashIcon(true));
clear.addActionListener(ae -> {
screen.setText("");
textEditor.getErrorScreen().setText("");
combinedScreen.setText("");
if (view != ConsoleView.OUTPUT) editorPane.getErrorHighlighter().reset();
});
- bottom.add(clear, bc);
+ bar.add(clear);
textEditor.cmdPalette.register(clear, "Console");
- bc.gridx = 7;
- switchSplit = new JButton(RIGHT_ARROW);
- switchSplit.setToolTipText("Switch location");
- switchSplit.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(final ActionEvent e) {
- if (DOWN_ARROW.equals(switchSplit.getText())) {
- TextEditorTab.this.setOrientation(JSplitPane.VERTICAL_SPLIT);
- } else {
- TextEditorTab.this.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
- }
- // Keep prompt collapsed if not in use
- if (!incremental.isSelected()) {
- setREPLVisible(false);
- }
- }
- });
- bottom.add(switchSplit, bc);
-
- bc.gridx = 0;
- bc.gridy = 1;
- bc.anchor = GridBagConstraints.NORTHWEST;
- bc.fill = GridBagConstraints.BOTH;
- bc.weightx = 1;
- bc.weighty = 1;
- bc.gridwidth = 8;
scroll = new JScrollPane(screen);
TextEditor.GuiUtils.flattenScrollBars(scroll);
- bottom.add(scroll, bc);
+ bottom.add(bar, BorderLayout.PAGE_START);
+ bottom.add(scroll, BorderLayout.CENTER);
prompt.setEnabled(false);
prompt.setFont(getEditorPane().getFont());
@@ -292,32 +246,30 @@ public void actionPerformed(final ActionEvent e) {
final JPanel prompt_panel = new JPanel();
prompt_panel.setMinimumSize(new Dimension(0, 0));
prompt_panel.setVisible(false);
- prompt_panel.setLayout(new GridBagLayout());
-
- bc.gridx = 0;
- bc.gridy = 0;
- bc.anchor = GridBagConstraints.NORTHWEST;
- bc.fill = GridBagConstraints.NONE;
- bc.weightx = 0;
- bc.weighty = 0;
- bc.gridwidth = 1;
- bc.gridheight = 1;
- prompt_panel.add(prompt_title, bc);
-
- bc.gridx = 1;
- bc.fill = GridBagConstraints.HORIZONTAL;
- bc.weightx = 1;
- prompt_panel.add(new JPanel(), bc);
-
- bc.gridx = 2;
- bc.anchor = GridBagConstraints.NORTHEAST;
- bc.weightx = 0;
- bc.fill = GridBagConstraints.NONE;
- prompt_panel.add(updownarrows, bc);
-
- bc.gridx = 3;
- final JButton prompt_help = new JButton("?");
- prompt_help.addActionListener(a -> {
+ promptPanel = prompt_panel;
+ prompt_panel.setLayout(new BorderLayout());
+
+ final JToolBar promptBar = new JToolBar();
+ promptBar.putClientProperty(FlatClientProperties.STYLE_CLASS, "small");
+ promptBar.setBorder(null);
+ promptBar.setMargin(null);
+ prompt_panel.add(promptBar, BorderLayout.PAGE_START);
+ prompt_panel.add(prompt, BorderLayout.CENTER);
+ final JLabel label = new JLabel();
+ label.setForeground(TextEditor.GuiUtils.secondaryColor());
+ label.setIcon(new TextEditor.ReplIcon());
+ promptBar.add(label);
+ promptBar.add(Box.createHorizontalGlue());
+ updownarrows.setText("Arrow Keys");
+ updownarrows.putClientProperty(FlatClientProperties.STYLE_CLASS, "small");
+ promptBar.add(Box.createHorizontalGlue());
+ promptBar.add(updownarrows);
+ final FlatHelpButtonIcon helpIcon = new FlatHelpButtonIcon();
+ helpIcon.setScale(.8f); // matches the font size set by the "small" style
+ helpIcon.applyStyleProperty("questionMarkColor", TextEditor.GuiUtils.secondaryColor());
+ helpIcon.applyStyleProperty("background", promptBar.getBackground());
+ final JButton statusHelp = new JButton(helpIcon);
+ statusHelp.addActionListener(a -> {
final String msg = "This REPL (Read-Evaluate-Print-Loop) parses " + textEditor.getCurrentLanguage().getLanguageName() + " code.\n\n"
+ "Key bindings:\n"
+ " [Enter]: Evaluate code\n"
@@ -331,32 +283,18 @@ public void actionPerformed(final ActionEvent e) {
;
textEditor.info(msg, "REPL Help");
});
- prompt_panel.add(prompt_help, bc);
-
- bc.gridx = 0;
- bc.gridy = 1;
- bc.anchor = GridBagConstraints.NORTHWEST;
- bc.fill = GridBagConstraints.BOTH;
- bc.weightx = 1;
- bc.weighty = 1;
- bc.gridwidth = 4;
- prompt_panel.add(prompt, bc);
-
- incremental.addActionListener(ae -> {
- if (incremental.isSelected() && null == textEditor.getCurrentLanguage()) {
- incremental.setSelected(false);
- textEditor.error("Select a language first!");
- return;
- }
- textEditor.setIncremental(incremental.isSelected());
- prompt_title.setText(incremental.isSelected() ? //
- "REPL: " + textEditor.getCurrentLanguage().getLanguageName() : "");
- prompt.setEnabled(incremental.isSelected());
- prompt_panel.setVisible(incremental.isSelected());
- });
+ 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);
+ statusHelp.putClientProperty(FlatClientProperties.STYLE, tight);
screenAndPromptSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT, bottom, prompt_panel);
- TextEditor.GuiUtils.flattenSplitPane(screenAndPromptSplit);
+ // No divider: the prompt bar is the handle. Keep promptDividerSize at 0 so toggling the REPL
+ // never brings the divider back
+ TextEditor.GuiUtils.installSplitHandle(promptBar, screenAndPromptSplit);
+ promptDividerSize = 0;
// Enable ErrorSrip à la Eclipse. This will keep track of lines with 'Mark All'
// occurrences as well as lines associated with ParserNotice.Level.WARNING and
@@ -381,6 +319,7 @@ public void actionPerformed(final ActionEvent e) {
editorPane.getVimHandler().setExHandler(textEditor::handleVimCommand);
super.setLeftComponent(holder);
super.setRightComponent(screenAndPromptSplit);
+ TextEditor.GuiUtils.installSplitHandle(bar, this); // no divider in the "below" layout: the toolbar is the handle
screenAndPromptSplit.setDividerLocation(1.0);
setView(view); // sync the console and chooser with the initial view
@@ -388,11 +327,165 @@ public void actionPerformed(final ActionEvent e) {
// Persist Script Editor layout whenever split pane divider is adjusted.
addPropertyChangeListener(evt -> {
- if ("dividerLocation".equals(evt.getPropertyName()))
+ if ("dividerLocation".equals(evt.getPropertyName())) {
+ if (isBottomVisible() && getDividerLocation() > 50) bottomLastLocation = getDividerLocation();
textEditor.saveWindowSizeToPrefs();
+ textEditor.syncStatusBar();
+ }
});
}
+ /** Whether the REPL is on */
+ boolean isREPLEnabled() {
+ return replOn;
+ }
+
+ /** Turns the REPL on/off (turning it on requires a language) */
+ void setREPLEnabled(final boolean enable) {
+ if (enable == replOn) return;
+ if (enable && null == textEditor.getCurrentLanguage()) {
+ textEditor.error("Select a language first!");
+ return;
+ }
+ if (enable) setBottomVisible(true); // the prompt lives in the bottom part
+ replOn = enable;
+ screenAndPromptSplit.setDividerSize(enable ? promptDividerSize : 0);
+ textEditor.setIncremental(enable);
+ prompt.setEnabled(enable);
+ promptPanel.setVisible(enable);
+ textEditor.syncStatusBar();
+ }
+
+ /** Whether the bottom part (output and prompt) is showing, i.e., not collapsed */
+ boolean isBottomVisible() {
+ if (axisSize() <= 0) return true; // not laid out yet
+ return getDividerLocation() < getMaximumDividerLocation() - 5;
+ }
+
+ /** Collapses the bottom part (output and prompt), or restores it to its last height */
+ void setBottomVisible(final boolean visible) {
+ if (visible == isBottomVisible()) return;
+ if (visible) {
+ final int max = getMaximumDividerLocation();
+ setDividerLocation(bottomLastLocation > 50 && bottomLastLocation < max - 5 ? bottomLastLocation
+ : (int) (axisSize() * .7));
+ } else {
+ setDividerLocation(1d); // all the way down
+ }
+ }
+
+ /**
+ * Icon painted from SVG path data (absolute M, L, C and Z commands, 640x640 view box). Glyphs by
+ * Font Awesome Free (https://fontawesome.com), licensed CC BY 4.0. Colors adapt to light/dark themes
+ */
+ private static class GlyphIcon extends FlatAbstractIcon {
+
+ private final Path2D path;
+ private final boolean disabled;
+ private final Color light, dark;
+
+ GlyphIcon(final String svgPath, final Color light, final Color dark, final boolean disabled) {
+ super(16, 16, null);
+ this.path = parse(svgPath);
+ this.light = light;
+ this.dark = dark;
+ this.disabled = disabled;
+ }
+
+ @Override
+ protected void paintIcon(final Component c, final Graphics2D g) {
+ Color color = com.formdev.flatlaf.FlatLaf.isLafDark() ? dark : light;
+ if (disabled) {
+ final Color d = UIManager.getColor("Button.disabledText");
+ color = (d != null) ? d : Color.GRAY;
+ }
+ g.setColor(color);
+ g.fill(path);
+ }
+
+ /** Parses the path, scaling it from the 640 unit view box to the 16 unit icon */
+ private static Path2D parse(final String d) {
+ final double k = 16d / 640d;
+ final java.util.regex.Matcher m = java.util.regex.Pattern.compile("[MLCZz]|-?\\d*\\.?\\d+").matcher(d);
+ final List tokens = new java.util.ArrayList<>();
+ while (m.find())
+ tokens.add(m.group());
+ final Path2D.Double p = new Path2D.Double();
+ char cmd = 'M';
+ int i = 0;
+ while (i < tokens.size()) {
+ final String t = tokens.get(i);
+ if (Character.isLetter(t.charAt(0))) {
+ cmd = t.charAt(0);
+ i++;
+ if (cmd == 'Z' || cmd == 'z') {
+ p.closePath();
+ continue;
+ }
+ }
+ switch (cmd) {
+ case 'M':
+ p.moveTo(k * Double.parseDouble(tokens.get(i)), k * Double.parseDouble(tokens.get(i + 1)));
+ i += 2;
+ cmd = 'L'; // further pairs are line segments
+ break;
+ case 'L':
+ p.lineTo(k * Double.parseDouble(tokens.get(i)), k * Double.parseDouble(tokens.get(i + 1)));
+ i += 2;
+ break;
+ case 'C':
+ p.curveTo(k * Double.parseDouble(tokens.get(i)), k * Double.parseDouble(tokens.get(i + 1)),
+ k * Double.parseDouble(tokens.get(i + 2)), k * Double.parseDouble(tokens.get(i + 3)),
+ k * Double.parseDouble(tokens.get(i + 4)), k * Double.parseDouble(tokens.get(i + 5)));
+ i += 6;
+ break;
+ default:
+ throw new IllegalArgumentException("Unsupported path command: " + cmd);
+ }
+ }
+ return p;
+ }
+ }
+
+ private static final Color GREEN = new Color(0x44774E), GREEN_DARK = new Color(0x446E4B);
+ private static final Color RED = new Color(0xDF5663), RED_DARK = new Color(0xB45355);
+
+ /** Green "play" triangle (Font Awesome) */
+ private static final class PlayIcon extends GlyphIcon {
+
+ PlayIcon(final boolean disabled) {
+ super("M187.2 100.9C174.8 94.1 159.8 94.4 147.6 101.6C135.4 108.8 128 121.9 128 136L128 504C128 518.1 135.5 531.2 147.6 538.4C159.7 545.6 174.8 545.9 187.2 539.1L523.2 355.1C536 348.1 544 334.6 544 320C544 305.4 536 291.9 523.2 284.9L187.2 100.9z",
+ GREEN_DARK, GREEN, disabled);
+ }
+ }
+
+ /** Green "fast forward" (double play) icon (Font Awesome), for batch runs */
+ private static final class FastForwardIcon extends GlyphIcon {
+
+ FastForwardIcon(final boolean disabled) {
+ super("M403.7 107.1C392.1 96 375 92.9 360.3 99.2C345.6 105.5 336 120 336 136L336 272.3L163.7 107.2C152.1 96 135 92.9 120.3 99.2C105.6 105.5 96 120 96 136L96 504C96 520 105.6 534.5 120.3 540.8C135 547.1 152.1 544 163.7 532.9L336 367.7L336 504C336 520 345.6 534.5 360.3 540.8C375 547.1 392.1 544 403.7 532.9L595.7 348.9C603.6 341.4 608 330.9 608 320C608 309.1 603.5 298.7 595.7 291.1L403.7 107.1z",
+ GREEN, GREEN_DARK, disabled);
+ }
+ }
+
+ /** Red "stop" rounded square (Font Awesome) */
+ private static final class StopIcon extends GlyphIcon {
+
+ StopIcon(final boolean disabled) {
+ super("M160 96L480 96C515.3 96 544 124.7 544 160L544 480C544 515.3 515.3 544 480 544L160 544C124.7 544 96 515.3 96 480L96 160C96 124.7 124.7 96 160 96z",
+ RED, RED_DARK, disabled);
+ }
+ }
+
+ /** Neutral "trash can" icon (Font Awesome), for the Clear button */
+ private static final class TrashIcon extends GlyphIcon {
+
+ TrashIcon(final boolean disabled) {
+ super("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);
+ }
+ }
+
// Package-private
JSplitPane getScreenAndPromptSplit() {
return screenAndPromptSplit;
@@ -400,6 +493,7 @@ JSplitPane getScreenAndPromptSplit() {
void setREPLVisible(final boolean visible) {
SwingUtilities.invokeLater(() -> {
+ screenAndPromptSplit.setDividerSize(visible ? promptDividerSize : 0); // before moving the divider
if (visible) {
// If stashed location of divider is invalid, set divider to half of panel's height and re-stash
if (screenAndPromptSplitDividerLocation <= 0
@@ -414,15 +508,40 @@ void setREPLVisible(final boolean visible) {
screenAndPromptSplitDividerLocation = getScreenAndPromptSplit().getDividerLocation();
getScreenAndPromptSplit().setDividerLocation(1f);
}
- incremental.setSelected(visible);
+ replOn = visible;
+ textEditor.syncStatusBar();
});
}
@Override
public void setOrientation(final int orientation) {
super.setOrientation(orientation);
- switchSplit.setText(orientation == JSplitPane.VERTICAL_SPLIT ? //
- RIGHT_ARROW : DOWN_ARROW);
+ bottomLastLocation = -1; // locations of the other layout do not apply
+ if (textEditor != null) textEditor.syncStatusBar();
+ }
+
+ /** Whether the console is (or would be) below the editor, as opposed to on its right side */
+ boolean isLayoutBelow() {
+ return getOrientation() == JSplitPane.VERTICAL_SPLIT;
+ }
+
+ /** Size of the tab along the axis of the divider */
+ private int axisSize() {
+ return isLayoutBelow() ? getHeight() : getWidth();
+ }
+
+ /**
+ * Status bar behavior: clicking the layout that is active collapses/restores the console,
+ * clicking the other layout switches to it (showing the console)
+ */
+ void toggleLayout(final boolean below) {
+ if (isLayoutBelow() == below) {
+ setBottomVisible(!isBottomVisible());
+ return;
+ }
+ setOrientation(below ? JSplitPane.VERTICAL_SPLIT : JSplitPane.HORIZONTAL_SPLIT);
+ if (!replOn) setREPLVisible(false); // keep the prompt collapsed if not in use
+ setDividerLocation(.7d);
}
// Package private
@@ -434,6 +553,7 @@ void destroy() {
/** Invoke in the context of the event dispatch thread. */
public void prepare() {
+ setBottomVisible(true); // a script that runs must be able to show its output
editorPane.setEditable(false);
runit.setEnabled(false);
killit.setEnabled(true);
@@ -445,7 +565,7 @@ public void restore() {
runit.setEnabled(true);
killit.setEnabled(false);
setExecutor(null);
- if(incremental.isSelected())
+ if (replOn)
prompt.requestFocusInWindow();
});
}
@@ -456,6 +576,7 @@ public void toggleErrors() {
/** Shows errors, unless errors are already shown (alone or with output). */
public void showErrors() {
+ setBottomVisible(true);
if (view == ConsoleView.OUTPUT) setView(ConsoleView.ERRORS);
else if (scroll.getViewport().getView() == null) setView(view);
}
From 10150798ebd3ffa65d52fab7ec2b3f40a0811100 Mon Sep 17 00:00:00 2001
From: Tiago Ferreira
Date: Sat, 14 Nov 2026 12:05:02 -0500
Subject: [PATCH 05/41] Improve command palette and bump java version to 21
---
pom.xml | 1 +
.../ui/swing/script/CommandPalette.java | 1231 +++++++++++++----
2 files changed, 939 insertions(+), 293 deletions(-)
diff --git a/pom.xml b/pom.xml
index 72de36d2..de1f8c50 100644
--- a/pom.xml
+++ b/pom.xml
@@ -140,6 +140,7 @@
+ 21
org.scijava.ui.swing.script.Main
org.scijava.ui.swing.script
bsd_2
diff --git a/src/main/java/org/scijava/ui/swing/script/CommandPalette.java b/src/main/java/org/scijava/ui/swing/script/CommandPalette.java
index 29c9d03f..c1a22cac 100644
--- a/src/main/java/org/scijava/ui/swing/script/CommandPalette.java
+++ b/src/main/java/org/scijava/ui/swing/script/CommandPalette.java
@@ -29,46 +29,71 @@
package org.scijava.ui.swing.script;
+import java.awt.AlphaComposite;
+import java.awt.BasicStroke;
import java.awt.BorderLayout;
+import java.awt.Color;
import java.awt.Component;
-import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
+import java.awt.Graphics;
+import java.awt.Graphics2D;
+import java.awt.GraphicsConfiguration;
+import java.awt.GraphicsDevice;
+import java.awt.GraphicsEnvironment;
import java.awt.Insets;
+import java.awt.Point;
import java.awt.Rectangle;
+import java.awt.RenderingHints;
+import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
+import java.awt.event.MouseMotionAdapter;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
+import java.awt.geom.Ellipse2D;
+import java.awt.geom.Line2D;
+import java.awt.geom.Path2D;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
+import java.util.function.Consumer;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
import javax.swing.AbstractAction;
import javax.swing.AbstractButton;
import javax.swing.Action;
import javax.swing.ActionMap;
+import javax.swing.Box;
+import javax.swing.BorderFactory;
+import javax.swing.Icon;
import javax.swing.InputMap;
+import javax.swing.JButton;
import javax.swing.JComponent;
-import javax.swing.JFrame;
+import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
+import javax.swing.JPanel;
import javax.swing.JPopupMenu;
-import javax.swing.JRootPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
+import javax.swing.JToggleButton;
+import javax.swing.JToolBar;
+import javax.swing.JViewport;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.MenuElement;
import javax.swing.SwingUtilities;
+import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
@@ -78,24 +103,45 @@
import org.fife.ui.rtextarea.RecordableTextAction;
import org.scijava.util.PlatformUtils;
+import com.formdev.flatlaf.FlatClientProperties;
+import com.formdev.flatlaf.icons.FlatSearchWithHistoryIcon;
+import com.formdev.flatlaf.util.Animator;
+import com.formdev.flatlaf.util.CubicBezierEasing;
+import com.formdev.flatlaf.util.UIScale;
+
class CommandPalette {
private static final String NAME = "Command Palette...";
/** Settings. Ought to become adjustable some day */
private static final KeyStroke ACCELERATOR = KeyStroke.getKeyStroke(KeyEvent.VK_P,
- java.awt.Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() | KeyEvent.SHIFT_DOWN_MASK);
+ Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx() | KeyEvent.SHIFT_DOWN_MASK);
private static final int TABLE_ROWS = 6; // no. of commands to be displayed
- private static final float OPACITY = 1f; // 0-1 range
- private static final boolean IGNORE_WHITESPACE = true; // Ignore white spaces while matching?
- private static Palette frame;
+ private static final int MAX_PATH = 2; // no. of menu levels in the path column
+ private static final Pattern QUERY_TOKEN_SPLIT = Pattern.compile("\\s+");
+ private static final Pattern ID_TOKEN_SPLIT = Pattern.compile("\\W+");
+ private static final Font REF_FONT = refFont();
+ private static final Color WARNING_COLOR = new Color(254, 210, 132);
- private SearchField searchField;
- private CmdTable table;
private final TextEditor textEditor;
private final CmdAction noHitsCmd;
private final CmdScrapper cmdScrapper;
+ private Palette frame;
+ private SearchField searchField;
+ private CmdTable table;
+ private boolean alwaysOnTop; // Always on top of other windows?
+ private boolean autoHide = true; // Hide after command is executed?
+ private boolean caseSensitive; // Case-sensitive matching?
+ private boolean ignoreWhiteSpace = true; // Ignore white spaces while matching?
+ private Point lastLocation; // last on-screen position, restored on re-open
+ // Bumped whenever caseSensitive or ignoreWhiteSpace changes: CmdAction caches
+ // pre-normalized haystacks keyed to this generation
+ private int normGeneration;
+ private Timer msgTimer;
+ // Guards setText() calls in displayTempMsg() so that they do not trigger a search
+ private boolean suppressDocListener;
+
public CommandPalette(final TextEditor textEditor) {
this.textEditor = textEditor;
noHitsCmd = new SearchWebCmd();
@@ -117,6 +163,28 @@ public void actionPerformed(final ActionEvent e) {
toolsMenu.add(new JMenuItem(action));
}
+ /** Menu bar button that toggles the palette, for the right end of the menu bar */
+ JButton getMenuButton() {
+ final JButton button = new JButton(new AbstractAction(null, new MagnifierIcon()) {
+
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public void actionPerformed(final ActionEvent e) {
+ toggleVisibility();
+ }
+
+ });
+ button.setToolTipText("Command Palette (" + getAcceleratorString() + ")");
+ button.setFocusable(false);
+ button.putClientProperty(FlatClientProperties.BUTTON_TYPE, FlatClientProperties.BUTTON_TYPE_TOOLBAR_BUTTON);
+ return button;
+ }
+
+ String getAcceleratorString() {
+ return noHitsCmd.prettifiedKey(ACCELERATOR).trim();
+ }
+
Map getShortcuts() {
if (!cmdScrapper.scrapeSuccessful())
cmdScrapper.scrape();
@@ -142,25 +210,36 @@ Map getRecordableActions() {
}
void register(final AbstractButton button, final String description) {
- cmdScrapper.registerOther(button, description);
+ cmdScrapper.registerOther(button, List.of(description));
}
void dispose() {
- if (frame != null) frame.dispose();
+ if (msgTimer != null)
+ msgTimer.stop();
+ if (frame != null)
+ frame.dispose();
frame = null;
}
private void hideWindow() {
- if (frame != null) frame.setVisible(false);
+ if (frame != null) {
+ if (frame.isVisible())
+ lastLocation = frame.getLocation(); // remember for next open
+ frame.setVisible(false);
+ }
+ }
+
+ private void autoHide() {
+ if (autoHide)
+ hideWindow();
}
private void assemblePalette() {
- if (frame != null)
- return;
frame = new Palette();
- frame.setLayout(new BorderLayout());
- searchField = new SearchField();
- frame.add(searchField, BorderLayout.NORTH);
+ initSearchField();
+ final JToolBar titleBar = new TitleBar().getToolBar();
+ frame.add(titleBar, BorderLayout.NORTH);
+ frame.add(searchField, BorderLayout.CENTER);
searchField.getDocument().addDocumentListener(new PromptDocumentListener());
final InternalKeyListener keyListener = new InternalKeyListener();
searchField.addKeyListener(keyListener);
@@ -175,62 +254,198 @@ public void mouseClicked(final MouseEvent e) {
}
});
populateList("");
- frame.add(table.getScrollPane());
+ frame.add(table.getScrollPane(), BorderLayout.SOUTH);
frame.pack();
+ enableDrag(frame.getRootPane());
+ enableDrag(titleBar);
}
- private String[] makeRow(final CmdAction ca) {
- return new String[] {ca.id, ca.description()};
+ private static void enableDrag(final JComponent component) {
+ final Point[] dragStart = { null };
+ component.addMouseListener(new MouseAdapter() {
+ @Override
+ public void mousePressed(final MouseEvent e) {
+ dragStart[0] = e.getPoint();
+ }
+
+ @Override
+ public void mouseReleased(final MouseEvent e) {
+ dragStart[0] = null;
+ }
+ });
+ component.addMouseMotionListener(new MouseMotionAdapter() {
+ @Override
+ public void mouseDragged(final MouseEvent e) {
+ if (dragStart[0] != null) {
+ final java.awt.Window w = SwingUtilities.getWindowAncestor(component);
+ if (w == null)
+ return;
+ final Point loc = w.getLocation();
+ w.setLocation(loc.x + e.getX() - dragStart[0].x, loc.y + e.getY() - dragStart[0].y);
+ }
+ }
+ });
}
- private void populateList(final String matchingSubstring) {
- final ArrayList list = new ArrayList<>();
- if (!cmdScrapper.scrapeSuccessful())
- cmdScrapper.scrape();
- cmdScrapper.getCmdMap().forEach((id, cmd) -> {
- if (cmd.matches(matchingSubstring)) {
- list.add(makeRow(cmd));
+ private void initSearchField() {
+ searchField = new SearchField(" Search for commands and actions (e.g., Theme)");
+ final JMenuItem rebuildIndex = new JMenuItem("Rebuild Index...");
+ rebuildIndex.addActionListener(e -> rebuildIndex());
+ searchField.optionsMenu.add(rebuildIndex);
+ searchField.caseButton.setSelected(caseSensitive);
+ searchField.caseButton.addItemListener(e -> {
+ caseSensitive = searchField.caseButton.isSelected();
+ normGeneration++; // invalidate cached haystacks
+ populateList(currentQuery()); // avoid setText(): it fires the document listener twice
+ });
+ searchField.whitespaceButton.setSelected(!ignoreWhiteSpace);
+ searchField.whitespaceButton.addItemListener(e -> {
+ ignoreWhiteSpace = !searchField.whitespaceButton.isSelected();
+ normGeneration++;
+ populateList(currentQuery());
+ });
+ }
+
+ // Case-adjusted but space-preserved: matches() does its own normalization so
+ // that fuzzyMatches() always sees the original tokens
+ private String currentQuery() {
+ final String text = searchField.getText();
+ if (text == null)
+ return "";
+ return (caseSensitive) ? text : text.toLowerCase();
+ }
+
+ private void rebuildIndex() {
+ cmdScrapper.scrape();
+ populateList(currentQuery());
+ displayTempMsg(String.format("Index rebuilt: %d commands/actions available...",
+ cmdScrapper.getCmdMap().size()), false);
+ }
+
+ private void displayTempMsg(final String msg, final boolean warning) {
+ if (msgTimer != null)
+ msgTimer.stop(); // restore whatever a still-pending message left behind, first
+ final String existingPlaceholder = searchField.getPlaceholder();
+ final String existingText = searchField.getText();
+ searchField.setPlaceholder(msg);
+ suppressDocListener = true;
+ searchField.setText(null);
+ suppressDocListener = false;
+ if (warning)
+ setWarningModeEnabled(true);
+ msgTimer = new Timer((warning) ? 3000 : 6000, null) {
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public void stop() {
+ super.stop();
+ searchField.setPlaceholder(existingPlaceholder);
+ suppressDocListener = true;
+ searchField.setText(existingText);
+ suppressDocListener = false;
+ if (warning)
+ setWarningModeEnabled(false);
}
+ };
+ msgTimer.addActionListener(e -> msgTimer.stop()); // same restore path on timeout
+ SwingUtilities.invokeLater(() -> {
+ if (frame != null)
+ frame.setVisible(true); // dispose() may have cleared it in the meantime
+ msgTimer.start();
});
- if (list.isEmpty()) {
- list.add(makeRow(noHitsCmd));
- }
+ }
+
+ private void populateList(final String query) {
+ if (!cmdScrapper.scrapeSuccessful())
+ cmdScrapper.scrape();
+ final List list = getSortedListByQuery(query);
+ final boolean noHits = list.isEmpty();
+ if (noHits)
+ list.add(noHitsCmd);
table.getInternalModel().setData(list);
- if (searchField != null)
+ if (searchField != null) {
+ setWarningModeEnabled(noHits);
searchField.requestFocus();
+ }
+ }
+
+ /** Pairing of a hit with its rank tier, computed once per hit */
+ private record Scored(CmdAction cmd, int score) {
+ }
+
+ private List getSortedListByQuery(final String query) {
+ // Query normalization and tokenizing depend only on the settings and query,
+ // so they are computed once per keystroke rather than once per command
+ final String normalizedQuery = normalize(query);
+ final String[] queryTokens = (query.trim().length() < 2) ? new String[0]
+ : QUERY_TOKEN_SPLIT.split(query.trim().toLowerCase());
+ final List hits = new ArrayList<>();
+ for (final CmdAction cmd : cmdScrapper.getCmdMap().values()) {
+ if (cmd.matches(normalizedQuery, queryTokens))
+ hits.add(new Scored(cmd, getMatchScore(cmd, normalizedQuery)));
+ }
+ hits.sort((a, b) -> {
+ if (a.score() != b.score())
+ return Integer.compare(a.score(), b.score());
+ final int alphaCompare = String.CASE_INSENSITIVE_ORDER.compare(a.cmd().id, b.cmd().id);
+ return (alphaCompare != 0) ? alphaCompare : a.cmd().id.compareTo(b.cmd().id);
+ });
+ final List sorted = new ArrayList<>(hits.size());
+ for (final Scored s : hits)
+ sorted.add(s.cmd());
+ return sorted;
+ }
+
+ private int getMatchScore(final CmdAction cmd, final String normalizedQuery) {
+ // cmd.matches() has already triggered ensureNormalized()
+ if (normalizedQuery.isEmpty())
+ return 1; // no query: alphabetical order takes over
+ if (cmd.normId.startsWith(normalizedQuery))
+ return 1; // id starts with query
+ if (cmd.normId.contains(normalizedQuery))
+ return 2; // id contains query
+ if (cmd.normTooltip.contains(normalizedQuery) || cmd.normPath.contains(normalizedQuery))
+ return 3; // matched through metadata only
+ return 4; // fuzzy-only hit
+ }
+
+ // Normalizes a haystack/query string per the current case/whitespace settings
+ private String normalize(final String s) {
+ if (s == null || s.isEmpty())
+ return "";
+ final String r = caseSensitive ? s : s.toLowerCase();
+ return ignoreWhiteSpace ? r.replace(" ", "") : r;
+ }
+
+ private void setWarningModeEnabled(final boolean enable) {
+ searchField.setBackground((enable) ? WARNING_COLOR : defaultFieldBackground());
+ searchField.setForeground((enable) ? Color.BLACK : defaultFieldForeground());
}
- private void runCmd(final String command) {
+ private static Color defaultFieldBackground() {
+ final Color c = UIManager.getColor("TextField.background");
+ return (c != null) ? c : Color.WHITE;
+ }
+
+ private static Color defaultFieldForeground() {
+ final Color c = UIManager.getColor("TextField.foreground");
+ return (c != null) ? c : Color.BLACK;
+ }
+
+ private void runCmd(final CmdAction cmd) {
+ if (cmd == null)
+ return;
SwingUtilities.invokeLater(() -> {
- if (CmdScrapper.REBUILD_ID.equals(command)) {
- cmdScrapper.scrape();
- table.clearSelection();
- searchField.setText("");
- searchField.requestFocus();
- frame.setVisible(true);
+ if (cmd.isDisabled()) {
+ displayTempMsg("Command is currently disabled: unmet requirements or unsupported by language", true);
return;
}
- CmdAction cmd;
- if (noHitsCmd != null && command.equals(noHitsCmd.id)) {
- cmd = noHitsCmd;
- } else {
- cmd = cmdScrapper.getCmdMap().get(command);
- }
- if (cmd != null) {
- final boolean hasButton = cmd.button != null;
- if (hasButton && !cmd.button.isEnabled()) {
- textEditor.error("Command is currently disabled. Either execution requirements "
- + "are unmet or it is not supported by current language.");
- frame.setVisible(true);
- return;
- }
- hideWindow(); // hide before running, in case command opens a dialog
- if (hasButton) {
- cmd.button.doClick();
- } else if (cmd.action != null) {
- cmd.action.actionPerformed(
- new ActionEvent(textEditor.getTextArea(), ActionEvent.ACTION_PERFORMED, cmd.id));
- }
+ autoHide(); // hide before running, in case command opens a dialog
+ if (cmd.button != null) {
+ cmd.button.doClick();
+ } else if (cmd.action != null) {
+ cmd.action.actionPerformed(
+ new ActionEvent(textEditor.getTextArea(), ActionEvent.ACTION_PERFORMED, cmd.id));
}
});
}
@@ -242,57 +457,429 @@ private void toggleVisibility() {
if (frame.isVisible()) {
hideWindow();
} else {
- frame.center(textEditor);
- table.clearSelection();
+ if (searchField.getText().isBlank())
+ table.clearSelection();
+ else
+ searchField.selectAll();
+ restoreOrCenterLocation();
frame.setVisible(true);
searchField.requestFocus();
}
}
+ private void restoreOrCenterLocation() {
+ // Restore the last user position, if the screen is still reachable
+ if (lastLocation != null && isOnScreen(lastLocation)) {
+ frame.setLocation(lastLocation);
+ return;
+ }
+ frame.setLocationRelativeTo(textEditor);
+ // Keep the palette clear of docks and taskbars
+ final GraphicsConfiguration gc = textEditor.getGraphicsConfiguration();
+ if (gc == null)
+ return;
+ final Rectangle b = gc.getBounds();
+ final Insets in = Toolkit.getDefaultToolkit().getScreenInsets(gc);
+ final int minX = b.x + in.left;
+ final int minY = b.y + in.top;
+ final int maxX = Math.max(minX, b.x + b.width - in.right - frame.getWidth());
+ final int maxY = Math.max(minY, b.y + b.height - in.bottom - frame.getHeight());
+ frame.setLocation(Math.clamp(frame.getX(), minX, maxX), Math.clamp(frame.getY(), minY, maxY));
+ }
+
+ private static boolean isOnScreen(final Point p) {
+ for (final GraphicsDevice gd : GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()) {
+ if (gd.getDefaultConfiguration().getBounds().contains(p))
+ return true;
+ }
+ return false;
+ }
+
+ /* Theme helpers. Computed on demand so that they follow the Look and Feel */
+
+ private static Font refFont() {
+ try {
+ return UIManager.getFont("TextField.font");
+ } catch (final Exception ignored) {
+ return new JTextField().getFont();
+ }
+ }
+
+ private static Color background() {
+ Color c = UIManager.getColor("Popup.background");
+ if (c == null)
+ c = UIManager.getColor("Panel.background");
+ return (c != null) ? c : Color.LIGHT_GRAY;
+ }
+
+ private static Color iconColor() {
+ final Color c = TextEditor.GuiUtils.secondaryColor();
+ return (c != null) ? c : Color.GRAY;
+ }
+
+ /**
+ * Toggle painted with the LAF's secondary color. The color is returned as a plain
+ * Color because FlatLaf ignores foregrounds that are UIResources, and resolved on
+ * every paint so that it follows Look and Feel changes
+ */
+ private static JToggleButton secondaryToggle(final String text, final String tooltip) {
+ final JToggleButton b = new JToggleButton(text) {
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public Color getForeground() {
+ final Color c = TextEditor.GuiUtils.secondaryColor();
+ return (c != null) ? new Color(c.getRGB()) : super.getForeground();
+ }
+ };
+ b.setToolTipText(tooltip);
+ b.setFocusable(false);
+ return b;
+ }
+
+ private static Color selectionColor() {
+ Color c = UIManager.getColor("Table.selectionBackground");
+ if (c == null)
+ c = UIManager.getColor("List.selectionBackground");
+ return (c != null) ? c : new Color(75, 110, 175);
+ }
+
+ private static Color alpha(final Color c, final int percent) {
+ return new Color(c.getRed(), c.getGreen(), c.getBlue(), Math.round(percent / 100f * 255));
+ }
+
+ /** Returns a color that is weight of a plus (1 - weight) of b */
+ private static Color mix(final Color a, final Color b, final double weight) {
+ final double w = Math.clamp(weight, 0d, 1d);
+ return new Color((int) Math.round(a.getRed() * w + b.getRed() * (1 - w)),
+ (int) Math.round(a.getGreen() * w + b.getGreen() * (1 - w)),
+ (int) Math.round(a.getBlue() * w + b.getBlue() * (1 - w)));
+ }
+
+ private static void recolorTracks(final JScrollPane scrollPane, final Color color) {
+ Component corner = scrollPane.getCorner(JScrollPane.LOWER_TRAILING_CORNER);
+ if (corner == null) {
+ corner = new JPanel();
+ scrollPane.setCorner(JScrollPane.LOWER_TRAILING_CORNER, corner);
+ }
+ corner.setBackground(color);
+ final Map style = Map.of("track", color, "hoverTrackColor", color);
+ scrollPane.getHorizontalScrollBar().putClientProperty(FlatClientProperties.STYLE, style);
+ scrollPane.getVerticalScrollBar().putClientProperty(FlatClientProperties.STYLE, style);
+ }
+
+ /** The search field, with options menu, and case and whitespace toggles */
private static class SearchField extends TextEditor.TextFieldWithPlaceholder {
private static final long serialVersionUID = 1L;
- private static final int PADDING = 4;
- static final Font REF_FONT = refFont();
+ private static final float ENLARGE_FACTOR = 1.1f;
+ final JPopupMenu optionsMenu = new JPopupMenu();
+ final JToggleButton caseButton;
+ final JToggleButton whitespaceButton;
+
+ SearchField(final String placeholder) {
+ setPlaceholder(placeholder);
+ final JButton options = new JButton(new FlatSearchWithHistoryIcon(true));
+ options.setToolTipText("Options");
+ options.setFocusable(false);
+ options.putClientProperty(FlatClientProperties.BUTTON_TYPE, FlatClientProperties.BUTTON_TYPE_TOOLBAR_BUTTON);
+ options.addActionListener(e -> optionsMenu.show(options, 0, options.getHeight()));
+ putClientProperty(FlatClientProperties.TEXT_FIELD_LEADING_COMPONENT, options);
+ caseButton = secondaryToggle("Cc", "Match case");
+ whitespaceButton = secondaryToggle("\u2423", "Match whitespace");
+ final JToolBar tb = new JToolBar();
+ tb.setFloatable(false);
+ tb.setMargin(new Insets(0, 0, 0, 2));
+ tb.add(caseButton);
+ tb.add(whitespaceButton);
+ putClientProperty(FlatClientProperties.TEXT_FIELD_TRAILING_COMPONENT, tb);
+ enlarge(options);
+ styleBorder();
+ }
- SearchField() {
- setPlaceholder(" Search for commands and actions (e.g., Theme)");
- setMargin(new Insets(PADDING, PADDING, 0, 0));
- setFont(REF_FONT.deriveFont(REF_FONT.getSize() * 1.5f));
+ private void enlarge(final JButton options) {
+ // Normalize by the OS scale so that the enlargement is consistent across platforms
+ final float factor = 1f + (ENLARGE_FACTOR - 1f) / osScale();
+ setFont(getFont().deriveFont(getFont().getSize2D() * factor));
+ options.setFont(options.getFont().deriveFont(options.getFont().getSize2D() * factor));
+ int w = 0;
+ int h = 0;
+ for (final JToggleButton b : List.of(caseButton, whitespaceButton)) {
+ b.setFont(b.getFont().deriveFont(b.getFont().getSize2D() * factor * .85f));
+ b.setPreferredSize(null);
+ final Dimension d = b.getPreferredSize();
+ w = Math.max(w, d.width);
+ h = Math.max(h, d.height);
+ }
+ final Dimension size = new Dimension(w, h);
+ for (final JToggleButton b : List.of(caseButton, whitespaceButton)) {
+ b.setPreferredSize(size);
+ b.setMinimumSize(size);
+ b.setMaximumSize(size);
+ }
+ }
+
+ private void styleBorder() {
+ final int padding = (int) (getFont().getSize2D() * .8);
+ setBorder(BorderFactory.createCompoundBorder(
+ BorderFactory.createMatteBorder(1, 0, 1, 0, alpha(iconColor(), 40)),
+ BorderFactory.createEmptyBorder(padding, padding, padding, padding)));
}
@Override
- Font getPlaceholderFont() {
- return REF_FONT.deriveFont(Font.ITALIC);
+ public void updateUI() {
+ super.updateUI(); // resets the border to the Look and Feel default
+ if (caseButton != null)
+ styleBorder();
}
- static Font refFont() {
+ /** Ratio between FlatLaf's UI scale and the display's scale */
+ private float osScale() {
try {
- return UIManager.getFont("TextField.font");
+ final GraphicsConfiguration gc = getGraphicsConfiguration();
+ final double device = (gc == null)
+ ? GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()
+ .getDefaultConfiguration().getDefaultTransform().getScaleX()
+ : gc.getDefaultTransform().getScaleX();
+ return (float) (Math.max(1.0, UIScale.getUserScaleFactor()) / Math.max(1.0, device));
} catch (final Exception ignored) {
- return new JTextField().getFont();
+ return 1f;
}
}
}
+ /** Magnifier icon, painted with the foreground of its component */
+ private static final class MagnifierIcon implements Icon {
+
+ @Override
+ public void paintIcon(final Component c, final Graphics g, final int x, final int y) {
+ final Graphics2D g2 = (Graphics2D) g.create();
+ try {
+ g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
+ g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
+ g2.setColor(c.getForeground());
+ g2.setStroke(new BasicStroke(UIScale.scale(1.6f), BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
+ final float s = getIconWidth();
+ g2.draw(new Ellipse2D.Float(x + .1f * s, y + .1f * s, .6f * s, .6f * s));
+ g2.draw(new Line2D.Float(x + .62f * s, y + .62f * s, x + .88f * s, y + .88f * s));
+ } finally {
+ g2.dispose();
+ }
+ }
+
+ @Override
+ public int getIconWidth() {
+ return UIScale.scale(16);
+ }
+
+ @Override
+ public int getIconHeight() {
+ return UIScale.scale(16);
+ }
+ }
+
+ /** Light bulb icon (Font Awesome Free 7.3.1). Painted with the foreground of its component */
+ private static final class BulbIcon implements Icon {
+ private static final String PATH = "M424.5 355.1C449 329.2 464 294.4 464 256C464 176.5 399.5 112 320 112"
+ + "C240.5 112 176 176.5 176 256C176 294.4 191 329.2 215.5 355.1C236.8 377.5 260.4 409.1 268.8 448"
+ + "L371.2 448C379.6 409 403.2 377.5 424.5 355.1z"
+ + "M459.3 388.1C435.7 413 416 443.4 416 477.7L416 496C416 540.2 380.2 576 336 576L304 576"
+ + "C259.8 576 224 540.2 224 496L224 477.7C224 443.4 204.3 413 180.7 388.1C148 353.7 128 307.2 128 256"
+ + "C128 150 214 64 320 64C426 64 512 150 512 256C512 307.2 492 353.7 459.3 388.1z"
+ + "M272 248C272 261.3 261.3 272 248 272C234.7 272 224 261.3 224 248C224 199.4 263.4 160 312 160"
+ + "C325.3 160 336 170.7 336 184C336 197.3 325.3 208 312 208C289.9 208 272 225.9 272 248z";
+ // Glyph bounds within the 640x640 view box
+ private static final double X0 = 128;
+ private static final double Y0 = 64;
+ private static final double GLYPH_W = 384;
+ private static final double GLYPH_H = 512;
+ private static final Path2D SHAPE = parse(PATH);
+ private final int height;
+
+ BulbIcon(final int height) {
+ this.height = height;
+ }
+
+ /** Parses absolute M, L, C and z commands, the only ones in PATH */
+ private static Path2D parse(final String d) {
+ final Path2D.Double p = new Path2D.Double(Path2D.WIND_NON_ZERO);
+ final Matcher m = Pattern.compile("([MLCz])([^MLCz]*)").matcher(d);
+ while (m.find()) {
+ final String args = m.group(2).trim();
+ final String[] n = args.isEmpty() ? new String[0] : args.split("[ ,]+");
+ switch (m.group(1).charAt(0)) {
+ case 'M' -> p.moveTo(Double.parseDouble(n[0]), Double.parseDouble(n[1]));
+ case 'L' -> p.lineTo(Double.parseDouble(n[0]), Double.parseDouble(n[1]));
+ case 'C' -> p.curveTo(Double.parseDouble(n[0]), Double.parseDouble(n[1]), Double.parseDouble(n[2]),
+ Double.parseDouble(n[3]), Double.parseDouble(n[4]), Double.parseDouble(n[5]));
+ default -> p.closePath();
+ }
+ }
+ return p;
+ }
+
+ @Override
+ public void paintIcon(final Component c, final Graphics g, final int x, final int y) {
+ final Graphics2D g2 = (Graphics2D) g.create();
+ try {
+ g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
+ g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
+ g2.setColor(c.getForeground());
+ final double s = height / GLYPH_H;
+ g2.translate(x, y);
+ g2.scale(s, s);
+ g2.translate(-X0, -Y0);
+ g2.fill(SHAPE);
+ } finally {
+ g2.dispose();
+ }
+ }
+
+ @Override
+ public int getIconWidth() {
+ return (int) Math.round(height * GLYPH_W / GLYPH_H);
+ }
+
+ @Override
+ public int getIconHeight() {
+ return height;
+ }
+ }
+
+ /** A {@link JLabel} that fades and slides in/out through a FlatLaf {@link Animator} */
+ private static class FadableHintLabel extends JLabel {
+ private static final long serialVersionUID = 1L;
+ private static final int DURATION_MS = 300;
+ private float alpha = 1f; // 0f (fully hidden) to 1f (fully shown)
+ private float offset; // horizontal paint offset in px: 0f is the resting position
+ private Animator animator;
+
+ FadableHintLabel(final String text) {
+ super(text);
+ }
+
+ void animateVisibility(final boolean show) {
+ if (animator != null && animator.isRunning())
+ animator.stop();
+ final float startAlpha = alpha;
+ final float endAlpha = show ? 1f : 0f;
+ // Reveals move left-to-right, hides exit past the right edge
+ final float travel = Math.max(getWidth(), getPreferredSize().width);
+ final float startOffset = offset;
+ final float endOffset = show ? 0f : travel;
+ if (show)
+ setVisible(true); // must be visible for the transition to be seen
+ if (startAlpha == endAlpha && startOffset == endOffset) {
+ if (!show)
+ setVisible(false);
+ return;
+ }
+ animator = new Animator(DURATION_MS, new Animator.TimingTarget() {
+ @Override
+ public void timingEvent(final float fraction) {
+ alpha = startAlpha + (endAlpha - startAlpha) * fraction;
+ offset = startOffset + (endOffset - startOffset) * fraction;
+ repaint();
+ }
+
+ @Override
+ public void end() {
+ alpha = endAlpha;
+ offset = endOffset;
+ if (!show)
+ setVisible(false); // hide only once fully faded out
+ repaint();
+ }
+ });
+ animator.setInterpolator(CubicBezierEasing.EASE_IN_OUT);
+ animator.start();
+ }
+
+ @Override
+ protected void paintComponent(final Graphics g) {
+ if (alpha >= 1f && offset == 0f) {
+ super.paintComponent(g);
+ return;
+ }
+ final Graphics2D g2d = (Graphics2D) g.create();
+ // Clip to own bounds so that the slide never paints over neighboring buttons
+ g2d.clipRect(0, 0, getWidth(), getHeight());
+ g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, Math.clamp(alpha, 0f, 1f)));
+ g2d.translate(offset, 0);
+ super.paintComponent(g2d);
+ g2d.dispose();
+ }
+ }
+
+ private class TitleBar {
+
+ private static final float FONT_SCALE = .9f;
+
+ JToolBar getToolBar() {
+ final JToolBar toolbar = new JToolBar();
+ toolbar.setOpaque(false);
+ toolbar.setFocusable(false);
+ toolbar.setFloatable(false);
+ toolbar.add(toggle("Auto-Hide", "Dismiss palette after running a command", autoHide,
+ selected -> autoHide = selected));
+ toolbar.add(toggle("Pin", "Display palette above all other windows", alwaysOnTop,
+ selected -> frame.setAlwaysOnTop(alwaysOnTop = selected)));
+ toolbar.add(Box.createHorizontalGlue());
+ addHint(toolbar);
+ return toolbar;
+ }
+
+ JToggleButton toggle(final String text, final String tooltip, final boolean initialState,
+ final Consumer setter) {
+ final JToggleButton button = secondaryToggle(text, tooltip);
+ button.setSelected(initialState);
+ button.setFont(button.getFont().deriveFont(button.getFont().getSize2D() * FONT_SCALE));
+ button.addItemListener(e -> setter.accept(button.isSelected()));
+ return button;
+ }
+
+ void addHint(final JToolBar parent) {
+ final FadableHintLabel label = new FadableHintLabel(
+ "HINT: Up/Down to navigate, Enter to run, Esc to close ");
+ label.setFont(label.getFont().deriveFont(label.getFont().getSize2D() * FONT_SCALE));
+ label.setForeground(iconColor());
+ label.setFocusable(false);
+ enableDrag(label);
+ parent.add(label);
+ final JButton button = new JButton(new BulbIcon((int) Math.round(label.getFont().getSize2D() * 1.2)));
+ button.setToolTipText("Search hints");
+ button.setForeground(iconColor());
+ button.setFocusable(false);
+ parent.add(button);
+ // Tracked separately from label.isVisible(), which lags behind while fading
+ final boolean[] shown = { true };
+ button.addActionListener(e -> {
+ shown[0] = !shown[0];
+ label.animateVisibility(shown[0]);
+ });
+ final Timer timer = new Timer(5000, e -> {
+ shown[0] = false;
+ label.animateVisibility(false);
+ ((Timer) e.getSource()).stop();
+ });
+ timer.setRepeats(false);
+ timer.start();
+ }
+ }
+
private class PromptDocumentListener implements DocumentListener {
public void insertUpdate(final DocumentEvent e) {
- populateList(getQueryFromSearchField());
+ if (!suppressDocListener)
+ populateList(currentQuery());
}
public void removeUpdate(final DocumentEvent e) {
- populateList(getQueryFromSearchField());
+ if (!suppressDocListener)
+ populateList(currentQuery());
}
public void changedUpdate(final DocumentEvent e) {
- populateList(getQueryFromSearchField());
- }
-
- String getQueryFromSearchField() {
- final String text = searchField.getText();
- if (text == null)
- return "";
- final String query = text.toLowerCase();
- return (IGNORE_WHITESPACE) ? query.replaceAll("\\s+", "") : query;
+ if (!suppressDocListener)
+ populateList(currentQuery());
}
}
@@ -308,13 +895,9 @@ public void keyPressed(final KeyEvent ke) {
if (key == KeyEvent.VK_ESCAPE || (key == KeyEvent.VK_W && meta) || (key == KeyEvent.VK_P && meta)) {
hideWindow();
} else if (source == searchField) {
- /*
- * If you hit enter in the text field, and there's only one command that
- * matches, run that:
- */
+ /* Enter in the text field runs the selected row, or the first one */
if (key == KeyEvent.VK_ENTER) {
- if (1 == items)
- runCmd(table.getInternalModel().getCommand(0));
+ runCmd(table.getInternalModel().getCommand(Math.max(table.getSelectedRow(), 0)));
}
/*
* If you hit the up or down arrows in the text field, move the focus to the
@@ -332,7 +915,6 @@ public void keyPressed(final KeyEvent ke) {
}
if (index >= 0) {
table.requestFocus();
- // completions.ensureIndexIsVisible(index);
table.setRowSelectionInterval(index, index);
}
} else if (key == KeyEvent.VK_BACK_SPACE || key == KeyEvent.VK_DELETE) {
@@ -360,17 +942,30 @@ public void keyPressed(final KeyEvent ke) {
}
}
- private class Palette extends JFrame {
+ /** Content pane that follows the Look and Feel */
+ private static class PalettePanel extends JPanel {
+ private static final long serialVersionUID = 1L;
+
+ PalettePanel() {
+ super(new BorderLayout());
+ }
+
+ @Override
+ public void updateUI() {
+ super.updateUI();
+ setBackground(background());
+ }
+ }
+
+ private class Palette extends JDialog {
private static final long serialVersionUID = 1L;
Palette() {
- super("Command Palette");
+ super(textEditor, "Command Palette", false);
+ setResizable(false);
+ setAlwaysOnTop(alwaysOnTop);
setUndecorated(true);
- setAlwaysOnTop(true);
- setOpacity(OPACITY);
- getRootPane().setWindowDecorationStyle(JRootPane.NONE);
- // it should NOT be possible to minimize this frame, but just to
- // be safe, we'll ensure the frame is never in an awkward state
+ setContentPane(new PalettePanel());
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(final WindowEvent e) {
@@ -379,27 +974,15 @@ public void windowClosing(final WindowEvent e) {
@Override
public void windowIconified(final WindowEvent e) {
- hideWindow();
+ autoHide();
}
@Override
public void windowDeactivated(final WindowEvent e) {
- hideWindow();
+ autoHide();
}
});
}
-
- void center(final Container component) {
- final Rectangle bounds = component.getBounds();
- final Dimension w = getSize();
- int x = bounds.x + (bounds.width - w.width) / 2;
- int y = bounds.y + (bounds.height - w.height) / 2;
- if (x < 0)
- x = 0;
- if (y < 0)
- y = 0;
- setLocation(x, y);
- }
}
private class CmdTable extends JTable {
@@ -415,8 +998,8 @@ private class CmdTable extends JTable {
setTableHeader(null);
setAutoResizeMode(AUTO_RESIZE_LAST_COLUMN);
final CmdTableRenderer renderer = new CmdTableRenderer();
- final int col0Width = renderer.maxWidh(0);
- final int col1Width = renderer.maxWidh(1);
+ final int col0Width = renderer.maxWidth(0);
+ final int col1Width = renderer.maxWidth(1);
setDefaultRenderer(Object.class, renderer);
getColumnModel().getColumn(0).setMaxWidth(col0Width);
getColumnModel().getColumn(1).setMaxWidth(col1Width);
@@ -428,10 +1011,27 @@ private class CmdTable extends JTable {
setFillsViewportHeight(true);
}
+ @Override
+ public void updateUI() {
+ super.updateUI();
+ setBackground(background());
+ if (getParent() instanceof JViewport viewport)
+ viewport.setBackground(background());
+ }
+
private JScrollPane getScrollPane() {
final JScrollPane scrollPane = new JScrollPane(this, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
- JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
+ JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED) {
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public void updateUI() {
+ recolorTracks(this, background());
+ super.updateUI();
+ }
+ };
scrollPane.setWheelScrollingEnabled(true);
+ scrollPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 0, 0));
return scrollPane;
}
@@ -444,31 +1044,36 @@ CmdTableModel getInternalModel() {
private class CmdTableRenderer extends DefaultTableCellRenderer {
private static final long serialVersionUID = 1L;
- final Font col0Font = SearchField.REF_FONT.deriveFont(SearchField.REF_FONT.getSize() * 1.2f);
- final Font col1Font = SearchField.REF_FONT.deriveFont(SearchField.REF_FONT.getSize() * 1.2f);
-
- public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected,
- final boolean hasFocus, final int row, final int column) {
- final Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
- if (column == 1) {
- setHorizontalAlignment(JLabel.RIGHT);
- setEnabled(false);
- setFont(col1Font);
- } else {
- setHorizontalAlignment(JLabel.LEFT);
- setEnabled(true);
- setFont(col0Font);
- }
- return c;
+ final Font col0Font = REF_FONT.deriveFont(REF_FONT.getSize2D() * 1.1f);
+ final Font col1Font = REF_FONT;
+
+ @Override
+ public Component getTableCellRendererComponent(final JTable table, final Object value,
+ final boolean isSelected, final boolean hasFocus, final int row, final int column) {
+ final CmdAction cmd = (CmdAction) value; // see CmdTableModel#getValueAt
+ final String text = (cmd == null) ? "" : (column == 0) ? cmd.id : cmd.description();
+ super.getTableCellRendererComponent(table, text, false, false, row, column);
+ final Color bg = table.getBackground();
+ final Color fg = table.getForeground();
+ setBackground((isSelected) ? mix(selectionColor(), bg, .35) : bg);
+ if (cmd != null && cmd.isDisabled())
+ setForeground(mix(fg, bg, .45));
+ else
+ setForeground((column == 0) ? fg : mix(fg, bg, .6));
+ setHorizontalAlignment((column == 0) ? JLabel.LEFT : JLabel.RIGHT);
+ setFont((column == 0) ? col0Font : col1Font);
+ setBorder(BorderFactory.createEmptyBorder(0, 6, 0, 6));
+ return this;
}
int rowHeight() {
- return (int) (col0Font.getSize() * 1.75f);
+ return (int) (col0Font.getSize2D() * 1.85f);
}
- int maxWidh(final int columnIndex) {
+ int maxWidth(final int columnIndex) {
if (columnIndex == 1)
- return SwingUtilities.computeStringWidth(getFontMetrics(col1Font), "Really+Huge+Key+Combo");
+ return SwingUtilities.computeStringWidth(getFontMetrics(col1Font),
+ "A really long menu › With long submenus ");
return SwingUtilities.computeStringWidth(getFontMetrics(col0Font),
"A large filename from the Recents menu.groovy");
}
@@ -477,21 +1082,16 @@ int maxWidh(final int columnIndex) {
private class CmdTableModel extends AbstractTableModel {
private static final long serialVersionUID = 1L;
- private final static int COLUMNS = 2;
- List list;
+ private static final int COLUMNS = 2;
+ private List list = new ArrayList<>();
- void setData(final ArrayList list) {
+ void setData(final List list) {
this.list = list;
fireTableDataChanged();
}
- String getCommand(final int row) {
- if (list.size() == 1)
- return (String) getValueAt(row, 0);
- else if (row < 0 || row >= list.size())
- return "";
- else
- return (String) getValueAt(row, 0);
+ CmdAction getCommand(final int row) {
+ return (row < 0 || row >= list.size()) ? null : list.get(row);
}
@Override
@@ -501,10 +1101,8 @@ public int getColumnCount() {
@Override
public Object getValueAt(final int row, final int column) {
- if (row >= list.size() || column >= COLUMNS)
- return null;
- final String[] strings = (String[]) list.get(row);
- return strings[column];
+ // Both columns are rendered from the command itself
+ return getCommand(row);
}
@Override
@@ -517,14 +1115,21 @@ public int getRowCount() {
private class CmdAction {
final String id;
- String menuLocation;
+ List path;
String hotkey;
AbstractButton button;
Action action;
+ private String pathDescription;
+ private String tooltipCache;
+ private String[] idTokensCache;
+ // Pre-normalized haystacks, valid for normGen == normGeneration
+ private String normId, normPath, normTooltip;
+ private int normGen = -1;
+
CmdAction(final String cmdName) {
this.id = capitalize(cmdName);
- this.menuLocation = "";
+ this.path = new ArrayList<>();
this.hotkey = "";
}
@@ -544,22 +1149,93 @@ private class CmdAction {
boolean recordable() {
return action != null && action instanceof RecordableTextAction;
}
-
+
+ /** True if backed by a button, menu item or action that is currently disabled */
+ boolean isDisabled() {
+ if (button != null) {
+ return !button.isEnabled() || (button instanceof JMenuItem && button.getParent() != null
+ && !button.getParent().isEnabled());
+ }
+ return action != null && !action.isEnabled();
+ }
+
+ String pathDescription() {
+ if (pathDescription == null) {
+ final List tail = path.subList(Math.max(path.size() - MAX_PATH, 0), path.size());
+ pathDescription = String.join(" \u203A ", tail);
+ }
+ return pathDescription;
+ }
+
String description() {
- final String rec = (recordable()) ?" \u29BF" :"";
+ final String rec = (recordable()) ? " \u29BF" : "";
if (!hotkey.isEmpty())
return hotkey + rec;
- if (!menuLocation.isEmpty())
- return "|" + menuLocation + "|" + rec;
+ if (!path.isEmpty())
+ return pathDescription() + rec;
return rec;
}
- boolean matches(final String lowercaseQuery) {
- if (IGNORE_WHITESPACE) {
- return id.toLowerCase().replaceAll("\\s+", "").contains(lowercaseQuery)
- || menuLocation.toLowerCase().contains(lowercaseQuery);
+ String tooltip() {
+ if (tooltipCache == null) {
+ String t = null;
+ if (button != null)
+ t = button.getToolTipText();
+ else if (action != null && action.getValue(Action.SHORT_DESCRIPTION) instanceof String s)
+ t = s;
+ tooltipCache = (t == null) ? "" : t.replaceAll("<[^>]*>", ""); // strip HTML once
}
- return id.toLowerCase().contains(lowercaseQuery) || menuLocation.toLowerCase().contains(lowercaseQuery);
+ return tooltipCache;
+ }
+
+ // normalizedQuery and queryTokens are computed once per keystroke by the
+ // caller (getSortedListByQuery), not per command
+ boolean matches(final String normalizedQuery, final String[] queryTokens) {
+ ensureNormalized();
+ return normId.contains(normalizedQuery) || normTooltip.contains(normalizedQuery)
+ || normPath.contains(normalizedQuery) || fuzzyMatches(queryTokens);
+ }
+
+ // Fuzzy fallback: each query token must fuzzy-match at least one id token.
+ // The threshold is computed per word (1 error per 3 chars), so that a typo
+ // in a single word of a multi-word query is tolerated. Matching is always
+ // case-insensitive and tokens shorter than 2 chars are skipped
+ private boolean fuzzyMatches(final String[] queryTokens) {
+ if (queryTokens.length == 0)
+ return false;
+ final String[] idTokens = idTokens();
+ for (final String qt : queryTokens) {
+ if (qt.length() < 2)
+ continue;
+ final int threshold = Math.max(1, qt.length() / 3);
+ boolean matched = false;
+ for (final String it : idTokens) {
+ if (it.length() < qt.length() - threshold)
+ continue; // too short to match
+ if (it.contains(qt) || withinEditDistance(qt, it, threshold)) {
+ matched = true;
+ break;
+ }
+ }
+ if (!matched)
+ return false; // all query tokens must match
+ }
+ return true;
+ }
+
+ private String[] idTokens() {
+ if (idTokensCache == null)
+ idTokensCache = ID_TOKEN_SPLIT.split(id.toLowerCase());
+ return idTokensCache;
+ }
+
+ private void ensureNormalized() {
+ if (normGen == normGeneration)
+ return;
+ normId = normalize(id);
+ normPath = normalize(pathDescription());
+ normTooltip = normalize(tooltip());
+ normGen = normGeneration;
}
void setkeyString(final KeyStroke key) {
@@ -623,116 +1299,91 @@ String getKeyText(final int keyCode) {
|| keyCode >= KeyEvent.VK_A && keyCode <= KeyEvent.VK_Z) {
return String.valueOf((char) keyCode);
}
- switch (keyCode) {
- case KeyEvent.VK_COMMA:
- return ",";
- case KeyEvent.VK_PERIOD:
- return ".";
- case KeyEvent.VK_SLASH:
- return "/";
- case KeyEvent.VK_SEMICOLON:
- return ";";
- case KeyEvent.VK_EQUALS:
- return "=";
- case KeyEvent.VK_OPEN_BRACKET:
- return "[";
- case KeyEvent.VK_BACK_SLASH:
- return "\\";
- case KeyEvent.VK_CLOSE_BRACKET:
- return "]";
- case KeyEvent.VK_ENTER:
- return "↵";
- case KeyEvent.VK_BACK_SPACE:
- return "⌫";
- case KeyEvent.VK_TAB:
- return "↹";
- case KeyEvent.VK_CANCEL:
- return "Cancel";
- case KeyEvent.VK_CLEAR:
- return "Clear";
- case KeyEvent.VK_PAUSE:
- return "Pause";
- case KeyEvent.VK_CAPS_LOCK:
- return "Caps Lock";
- case KeyEvent.VK_ESCAPE:
- return "Esc";
- case KeyEvent.VK_SPACE:
- return "Space";
- case KeyEvent.VK_PAGE_UP:
- return "⇞";
- case KeyEvent.VK_PAGE_DOWN:
- return "⇟";
- case KeyEvent.VK_END:
- return "END";
- case KeyEvent.VK_HOME:
- return "Home"; // "⌂";
- case KeyEvent.VK_LEFT:
- return "←";
- case KeyEvent.VK_UP:
- return "↑";
- case KeyEvent.VK_RIGHT:
- return "→";
- case KeyEvent.VK_DOWN:
- return "↓";
- case KeyEvent.VK_MULTIPLY:
- return "[Num ×]";
- case KeyEvent.VK_ADD:
- return "[Num +]";
- case KeyEvent.VK_SUBTRACT:
- return "[Num −]";
- case KeyEvent.VK_DIVIDE:
- return "[Num /]";
- case KeyEvent.VK_DELETE:
- return "⌦";
- case KeyEvent.VK_INSERT:
- return "Ins";
- case KeyEvent.VK_BACK_QUOTE:
- return "`";
- case KeyEvent.VK_QUOTE:
- return "'";
- case KeyEvent.VK_AMPERSAND:
- return "&";
- case KeyEvent.VK_ASTERISK:
- return "*";
- case KeyEvent.VK_QUOTEDBL:
- return "\"";
- case KeyEvent.VK_LESS:
- return "<";
- case KeyEvent.VK_GREATER:
- return ">";
- case KeyEvent.VK_BRACELEFT:
- return "{";
- case KeyEvent.VK_BRACERIGHT:
- return "}";
- case KeyEvent.VK_COLON:
- return ",";
- case KeyEvent.VK_CIRCUMFLEX:
- return "^";
- case KeyEvent.VK_DEAD_TILDE:
- return "~";
- case KeyEvent.VK_DOLLAR:
- return "$";
- case KeyEvent.VK_EXCLAMATION_MARK:
- return "!";
- case KeyEvent.VK_LEFT_PARENTHESIS:
- return "(";
- case KeyEvent.VK_MINUS:
- return "-";
- case KeyEvent.VK_PLUS:
- return "+";
- case KeyEvent.VK_RIGHT_PARENTHESIS:
- return ")";
- case KeyEvent.VK_UNDERSCORE:
- return "_";
- default:
- return KeyEvent.getKeyText(keyCode);
+ return switch (keyCode) {
+ case KeyEvent.VK_COMMA -> ",";
+ case KeyEvent.VK_PERIOD -> ".";
+ case KeyEvent.VK_SLASH -> "/";
+ case KeyEvent.VK_SEMICOLON -> ";";
+ case KeyEvent.VK_EQUALS -> "=";
+ case KeyEvent.VK_OPEN_BRACKET -> "[";
+ case KeyEvent.VK_BACK_SLASH -> "\\";
+ case KeyEvent.VK_CLOSE_BRACKET -> "]";
+ case KeyEvent.VK_ENTER -> "↵";
+ case KeyEvent.VK_BACK_SPACE -> "⌫";
+ case KeyEvent.VK_TAB -> "↹";
+ case KeyEvent.VK_CANCEL -> "Cancel";
+ case KeyEvent.VK_CLEAR -> "Clear";
+ case KeyEvent.VK_PAUSE -> "Pause";
+ case KeyEvent.VK_CAPS_LOCK -> "Caps Lock";
+ case KeyEvent.VK_ESCAPE -> "Esc";
+ case KeyEvent.VK_SPACE -> "Space";
+ case KeyEvent.VK_PAGE_UP -> "⇞";
+ case KeyEvent.VK_PAGE_DOWN -> "⇟";
+ case KeyEvent.VK_END -> "END";
+ case KeyEvent.VK_HOME -> "Home"; // "⌂";
+ case KeyEvent.VK_LEFT -> "←";
+ case KeyEvent.VK_UP -> "↑";
+ case KeyEvent.VK_RIGHT -> "→";
+ case KeyEvent.VK_DOWN -> "↓";
+ case KeyEvent.VK_MULTIPLY -> "[Num ×]";
+ case KeyEvent.VK_ADD -> "[Num +]";
+ case KeyEvent.VK_SUBTRACT -> "[Num −]";
+ case KeyEvent.VK_DIVIDE -> "[Num /]";
+ case KeyEvent.VK_DELETE -> "⌦";
+ case KeyEvent.VK_INSERT -> "Ins";
+ case KeyEvent.VK_BACK_QUOTE -> "`";
+ case KeyEvent.VK_QUOTE -> "'";
+ case KeyEvent.VK_AMPERSAND -> "&";
+ case KeyEvent.VK_ASTERISK -> "*";
+ case KeyEvent.VK_QUOTEDBL -> "\"";
+ case KeyEvent.VK_LESS -> "<";
+ case KeyEvent.VK_GREATER -> ">";
+ case KeyEvent.VK_BRACELEFT -> "{";
+ case KeyEvent.VK_BRACERIGHT -> "}";
+ case KeyEvent.VK_COLON -> ":";
+ case KeyEvent.VK_CIRCUMFLEX -> "^";
+ case KeyEvent.VK_DEAD_TILDE -> "~";
+ case KeyEvent.VK_DOLLAR -> "$";
+ case KeyEvent.VK_EXCLAMATION_MARK -> "!";
+ case KeyEvent.VK_LEFT_PARENTHESIS -> "(";
+ case KeyEvent.VK_MINUS -> "-";
+ case KeyEvent.VK_PLUS -> "+";
+ case KeyEvent.VK_RIGHT_PARENTHESIS -> ")";
+ case KeyEvent.VK_UNDERSCORE -> "_";
+ default -> KeyEvent.getKeyText(keyCode);
+ };
+ }
+ }
+
+ /** Levenshtein test that bails out once the distance is known to exceed max */
+ private static boolean withinEditDistance(final String a, final String b, final int max) {
+ final int n = a.length();
+ final int m = b.length();
+ if (Math.abs(n - m) > max)
+ return false;
+ int[] prev = new int[m + 1];
+ int[] curr = new int[m + 1];
+ for (int j = 0; j <= m; j++)
+ prev[j] = j;
+ for (int i = 1; i <= n; i++) {
+ curr[0] = i;
+ int rowMin = curr[0];
+ for (int j = 1; j <= m; j++) {
+ final int cost = (a.charAt(i - 1) == b.charAt(j - 1)) ? 0 : 1;
+ curr[j] = Math.min(Math.min(curr[j - 1] + 1, prev[j] + 1), prev[j - 1] + cost);
+ rowMin = Math.min(rowMin, curr[j]);
}
+ if (rowMin > max)
+ return false;
+ final int[] tmp = prev;
+ prev = curr;
+ curr = tmp;
}
+ return prev[m] <= max;
}
private class CmdScrapper {
final TextEditor textEditor;
- static final String REBUILD_ID = "Rebuild Actions Index";
private final TreeMap cmdMap;
private TreeMap otherMap;
@@ -756,21 +1407,18 @@ boolean scrapeSuccessful() {
void scrape() {
cmdMap.clear();
- cmdMap.put(REBUILD_ID, new CmdAction(REBUILD_ID));
parseActionAndInputMaps();
final JMenuBar menuBar = textEditor.getJMenuBar();
final int topLevelMenus = menuBar.getMenuCount();
for (int i = 0; i < topLevelMenus; ++i) {
final JMenu topLevelMenu = menuBar.getMenu(i);
if (topLevelMenu != null && topLevelMenu.getText() != null) {
- parseMenu(topLevelMenu.getText(), topLevelMenu);
+ parseMenu(List.of(topLevelMenu.getText()), topLevelMenu);
}
}
final JPopupMenu popup = textEditor.getEditorPane().getPopupMenu();
if (popup != null) {
- getMenuItems(popup).forEach(mi -> {
- registerMenuItem(mi, "Popup Menu");
- });
+ getMenuItems(popup).forEach(mi -> registerMenuItem(mi, List.of("Popup Menu")));
}
}
@@ -809,27 +1457,23 @@ private void parseActionAndInputMaps() {
}
}
- private void parseMenu(final String componentHostingMenu, final JMenu menu) {
+ private void parseMenu(final List path, final JMenu menu) {
final int n = menu.getItemCount();
for (int i = 0; i < n; ++i) {
- registerMenuItem(menu.getItem(i), componentHostingMenu);
+ registerMenuItem(menu.getItem(i), path);
}
}
- private void registerMenuItem(final JMenuItem m, final String hostingComponent) {
- if (m != null) {
- String label = m.getActionCommand();
- if (label == null)
- label = m.getText();
- if (m instanceof JMenu) {
- final JMenu subMenu = (JMenu) m;
- String hostDesc = subMenu.getText();
- if (hostDesc == null)
- hostDesc = hostingComponent;
- parseMenu(hostDesc, subMenu);
- } else {
- registerMain(m, hostingComponent);
- }
+ private void registerMenuItem(final JMenuItem m, final List path) {
+ if (m == null)
+ return;
+ if (m instanceof JMenu subMenu) {
+ final List subPath = new ArrayList<>(path);
+ if (subMenu.getText() != null)
+ subPath.add(subMenu.getText());
+ parseMenu(subPath, subMenu);
+ } else {
+ registerMain(m, path);
}
}
@@ -865,22 +1509,22 @@ private boolean irrelevantCommand(final String label) {
return label == null || label.endsWith(" pt") || label.length() < 2;
}
- void registerMain(final AbstractButton button, final String description) {
- register(cmdMap, button, description);
+ void registerMain(final AbstractButton button, final List path) {
+ register(cmdMap, button, path);
}
- void registerOther(final AbstractButton button, final String description) {
+ void registerOther(final AbstractButton button, final List path) {
if (otherMap == null)
otherMap = new TreeMap<>();
- register(otherMap, button, description);
+ register(otherMap, button, path);
}
private void register(final TreeMap map, final AbstractButton button,
- final String descriptionOfComponentHostingButton) {
+ final List path) {
String label = button.getActionCommand();
if (NAME.equals(label))
return; // do not register command palette
- if (label == null)
+ if (label == null && button.getText() != null)
label = button.getText().trim();
if (irrelevantCommand(label))
return;
@@ -888,14 +1532,15 @@ private void register(final TreeMap map, final AbstractButton
label = label.substring(0, label.length() - 3);
// If a command has already been registered, we'll include its accelerator
final boolean isMenuItem = button instanceof JMenuItem;
- final CmdAction registeredAction = (CmdAction) map.get(label);
+ final CmdAction registeredAction = map.get(label);
final KeyStroke accelerator = (isMenuItem) ? ((JMenuItem) button).getAccelerator() : null;
if (registeredAction != null && accelerator != null) {
registeredAction.setkeyString(accelerator);
} else {
final CmdAction ca = new CmdAction(label, button);
- ca.menuLocation = descriptionOfComponentHostingButton;
- if (accelerator != null) ca.setkeyString(accelerator);
+ ca.path = new ArrayList<>(path);
+ if (accelerator != null)
+ ca.setkeyString(accelerator);
map.put(ca.id, ca);
}
}
@@ -929,7 +1574,7 @@ public void actionPerformed(final ActionEvent e) {
@Override
String description() {
- return "|Unmatched action|";
+ return "Unmatched action";
}
}
}
From e0d04fa8c4d432778af822dbdeef93449a4db39a Mon Sep 17 00:00:00 2001
From: Tiago Ferreira
Date: Sat, 14 Nov 2026 14:27:55 -0500
Subject: [PATCH 06/41] Implement temporary status messages
---
.../scijava/ui/swing/script/TextEditor.java | 29 +++++++++++++++++++
1 file changed, 29 insertions(+)
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 6be99adf..ca0b1581 100644
--- a/src/main/java/org/scijava/ui/swing/script/TextEditor.java
+++ b/src/main/java/org/scijava/ui/swing/script/TextEditor.java
@@ -715,6 +715,8 @@ public TextEditor(final Context context) {
appendPreferences(options);
mbar.add(options);
mbar.add(helpMenu());
+ mbar.add(Box.createHorizontalGlue());
+ mbar.add(cmdPalette.getMenuButton());
// -- END MENUS --
@@ -793,6 +795,12 @@ public TextEditor(final Context context) {
// make sure that the window is not closed by accident
addWindowListener(new WindowAdapter() {
+ @Override
+ public void windowOpened(final WindowEvent e) {
+ showTemporaryStatus("Tip: press " + cmdPalette.getAcceleratorString()
+ + " to search all commands and actions", 10000);
+ }
+
@Override
public void windowClosing(final WindowEvent e) {
if (!confirmClose()) return;
@@ -1844,6 +1852,27 @@ private void setAutoCompletionEnabled(final boolean enabled) {
fallbackAutocompletion.setEnabled(enabled);
}
+ private Timer statusRestoreTimer;
+ private String statusRestoreText;
+
+ /**
+ * Shows a message in the status bar and restores the previous text after the
+ * given delay. Text set by other means in the meantime is left untouched
+ */
+ void showTemporaryStatus(final String message, final int millis) {
+ if (statusRestoreTimer != null && statusRestoreTimer.isRunning())
+ statusRestoreTimer.stop(); // keep the text saved by the pending message
+ else
+ statusRestoreText = statusText.getText();
+ statusText.setText(message);
+ statusRestoreTimer = new Timer(millis, e -> {
+ if (message.equals(statusText.getText()))
+ statusText.setText(statusRestoreText);
+ });
+ statusRestoreTimer.setRepeats(false);
+ statusRestoreTimer.start();
+ }
+
/** Builds the permanent, full-width status bar: Fast | status text | glue | GoTo | Tab | Lock */
private JComponent assembleStatusBar() {
statusText = new JLabel(" ");
From 5978d1c3631c2af01683203947c43c8b5b5fdabb Mon Sep 17 00:00:00 2001
From: Tiago Ferreira
Date: Sat, 14 Nov 2026 15:45:42 -0500
Subject: [PATCH 07/41] Layout fixes
- Do not allow palette to outlive the TextEditor closure
- Layout/border adjustments
- Fix landscape mode toggle failing when window too narrow
---
.../ui/swing/script/CommandPalette.java | 21 +++++++++---
.../ui/swing/script/FileSystemTreePanel.java | 32 +++++++++++++++++++
.../scijava/ui/swing/script/TextEditor.java | 22 ++++++-------
.../ui/swing/script/TextEditorTab.java | 22 +++++++++++--
4 files changed, 77 insertions(+), 20 deletions(-)
diff --git a/src/main/java/org/scijava/ui/swing/script/CommandPalette.java b/src/main/java/org/scijava/ui/swing/script/CommandPalette.java
index c1a22cac..d694bb80 100644
--- a/src/main/java/org/scijava/ui/swing/script/CommandPalette.java
+++ b/src/main/java/org/scijava/ui/swing/script/CommandPalette.java
@@ -146,6 +146,13 @@ public CommandPalette(final TextEditor textEditor) {
this.textEditor = textEditor;
noHitsCmd = new SearchWebCmd();
cmdScrapper = new CmdScrapper(textEditor);
+ // The palette must not outlive its parent, whatever way the latter is closed
+ textEditor.addWindowListener(new WindowAdapter() {
+ @Override
+ public void windowClosed(final WindowEvent e) {
+ dispose();
+ }
+ });
}
void install(final JMenu toolsMenu) {
@@ -349,7 +356,7 @@ public void stop() {
};
msgTimer.addActionListener(e -> msgTimer.stop()); // same restore path on timeout
SwingUtilities.invokeLater(() -> {
- if (frame != null)
+ if (frame != null && textEditor.isDisplayable())
frame.setVisible(true); // dispose() may have cleared it in the meantime
msgTimer.start();
});
@@ -451,7 +458,11 @@ private void runCmd(final CmdAction cmd) {
}
private void toggleVisibility() {
- if (frame == null) {
+ if (!textEditor.isDisplayable()) { // parent is gone: do not resurrect the palette
+ dispose();
+ return;
+ }
+ if (frame == null || !frame.isDisplayable()) {
assemblePalette();
}
if (frame.isVisible()) {
@@ -1282,11 +1293,11 @@ private String prettifiedKey(final KeyStroke key) {
}
switch (key.getKeyEventType()) {
case KeyEvent.KEY_TYPED:
- s.append(key.getKeyChar() + " ");
+ s.append(key.getKeyChar()).append(" ");
break;
case KeyEvent.KEY_PRESSED:
case KeyEvent.KEY_RELEASED:
- s.append(getKeyText(key.getKeyCode()) + " ");
+ s.append(getKeyText(key.getKeyCode())).append(" ");
break;
default:
break;
@@ -1418,7 +1429,7 @@ void scrape() {
}
final JPopupMenu popup = textEditor.getEditorPane().getPopupMenu();
if (popup != null) {
- getMenuItems(popup).forEach(mi -> registerMenuItem(mi, List.of("Popup Menu")));
+ getMenuItems(popup).forEach(mi -> registerMenuItem(mi, List.of("Context Menu")));
}
}
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 8ec0a82f..c5e89774 100644
--- a/src/main/java/org/scijava/ui/swing/script/FileSystemTreePanel.java
+++ b/src/main/java/org/scijava/ui/swing/script/FileSystemTreePanel.java
@@ -39,6 +39,7 @@
import java.util.regex.PatternSyntaxException;
import java.util.stream.Collectors;
import javax.swing.*;
+import javax.swing.border.AbstractBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.PopupMenuEvent;
@@ -135,9 +136,40 @@ class FileSystemTreePanel extends JPanel {
});
}
+ /** Border with the color of scroll pane outlines, drawn on the left, right and bottom edges only */
+ private static final class SideBorder extends AbstractBorder {
+
+ private static final long serialVersionUID = 1L;
+
+ private static int thickness() {
+ return Math.max(1, Math.round(UIScale.scale(1f)));
+ }
+
+ @Override
+ public void paintBorder(final Component c, final Graphics g, final int x, final int y, final int w,
+ final int h) {
+ final Color color = UIManager.getColor("Component.borderColor"); // resolved on paint: follows the LAF
+ if (color == null)
+ return;
+ final int t = thickness();
+ g.setColor(color);
+ g.fillRect(x, y, t, h);
+ g.fillRect(x + w - t, y, t, h);
+ g.fillRect(x, y + h - t, w, t);
+ }
+
+ @Override
+ public Insets getBorderInsets(final Component c) {
+ final int t = thickness();
+ return new Insets(0, t, t, t);
+ }
+ }
+
private JToolBar statusToolbar() {
final JToolBar toolbar = new JToolBar();
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(TextEditor.GuiUtils.secondaryColor());
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 ca0b1581..eeedf7e4 100644
--- a/src/main/java/org/scijava/ui/swing/script/TextEditor.java
+++ b/src/main/java/org/scijava/ui/swing/script/TextEditor.java
@@ -1877,7 +1877,6 @@ void showTemporaryStatus(final String message, final int millis) {
private JComponent assembleStatusBar() {
statusText = new JLabel(" ");
statusText.setFont(statusText.getFont().deriveFont(statusText.getFont().getSize2D() * .9f));
- statusText.setForeground(GuiUtils.secondaryColor());
//statusText.setMinimumSize(new Dimension(0, 0));
statusPos = new JButton("Ln 1, Col 1") {
@@ -1886,19 +1885,17 @@ private JComponent assembleStatusBar() {
@Override
public Dimension getPreferredSize() { // fixed width: neighbors do not move as the caret does
final Dimension d = super.getPreferredSize();
- d.width = Math.max(d.width, getFontMetrics(getFont()).stringWidth("Ln 99999, Col 999") + 16);
+ d.width = Math.max(d.width, getFontMetrics(getFont()).stringWidth("Ln 9999, Col 999"));
return d;
}
};
statusPos.setToolTipText("Caret position. Click to go to line...");
statusPos.setFocusable(false);
- statusPos.putClientProperty(FlatClientProperties.BUTTON_TYPE, FlatClientProperties.BUTTON_TYPE_TOOLBAR_BUTTON);
statusPos.setFont(statusPos.getFont().deriveFont(statusPos.getFont().getSize2D() * .9f));
statusPos.addActionListener(e -> gotoLine());
statusLang = new JButton("None");
statusLang.setToolTipText("Language of the active script. Click to change");
statusLang.setFocusable(false);
- statusLang.putClientProperty(FlatClientProperties.BUTTON_TYPE, FlatClientProperties.BUTTON_TYPE_TOOLBAR_BUTTON);
statusLang.setFont(statusLang.getFont().deriveFont(statusLang.getFont().getSize2D() * .9f));
statusLang.addActionListener(e -> {
final JPopupMenu menu = languageMenu.getPopupMenu();
@@ -1912,7 +1909,6 @@ public Dimension getPreferredSize() { // fixed width: neighbors do not move as t
statusTab = new JButton("Spaces: 4");
statusTab.setToolTipText("Indentation. Click for options");
statusTab.setFocusable(false);
- statusTab.putClientProperty(FlatClientProperties.BUTTON_TYPE, FlatClientProperties.BUTTON_TYPE_TOOLBAR_BUTTON);
statusTab.setFont(statusTab.getFont().deriveFont(statusTab.getFont().getSize2D() * .9f));
statusTab.addActionListener(e -> {
final JPopupMenu menu = indentationMenu();
@@ -1923,7 +1919,6 @@ public Dimension getPreferredSize() { // fixed width: neighbors do not move as t
statusSide.setToolTipText("Shows/hides the side panel (Files, Outline, Notes)");
statusSide.setFocusable(false);
statusSide.setSelected(true);
- statusSide.putClientProperty(FlatClientProperties.BUTTON_TYPE, FlatClientProperties.BUTTON_TYPE_TOOLBAR_BUTTON);
statusSide.addActionListener(e -> {
if (statusSide.isSelected()) { // restore
body.setDividerLocation(sideLastLocation > 50 ? sideLastLocation : (int) (body.getWidth() * .2));
@@ -1938,12 +1933,11 @@ public Dimension getPreferredSize() { // fixed width: neighbors do not move as t
});
// Layout of the console: below or beside the editor. Clicking the active one collapses/restores it
statusBelow = new JToggleButton(new BottomPaneIcon());
- statusBelow.setToolTipText("Console below the editor (click again to hide/show it)");
+ statusBelow.setToolTipText("Vertical Layout: Console below the editor.
Click again to hide/show it");
statusRight = new JToggleButton(new RightPaneIcon());
- statusRight.setToolTipText("Console beside the editor (click again to hide/show it)");
+ statusRight.setToolTipText("Horizontal Layout: Console beside the editor.
Click again to hide/show it");
for (final JToggleButton b : new JToggleButton[] { statusBelow, statusRight }) {
b.setFocusable(false);
- b.putClientProperty(FlatClientProperties.BUTTON_TYPE, FlatClientProperties.BUTTON_TYPE_TOOLBAR_BUTTON);
}
statusBelow.setSelected(true);
statusBelow.addActionListener(e -> {
@@ -1964,20 +1958,24 @@ public Dimension getPreferredSize() { // fixed width: neighbors do not move as t
syncStatusBar(); // e.g., no language: the request was refused
});
final JToolBar bar = new JToolBar();
+ final int gap = 4;
+ bar.setBorder(BorderFactory.createEmptyBorder(0, gap, 0, gap));
bar.add(statusSide);
bar.add(statusBelow);
bar.add(statusRight);
- bar.add(Box.createHorizontalStrut(8));
+ bar.add(Box.createHorizontalStrut(gap));
+ bar.addSeparator();
+ bar.add(Box.createHorizontalStrut(gap));
bar.add(statusText);
bar.add(Box.createHorizontalGlue());
+ bar.addSeparator();
+ bar.add(Box.createHorizontalStrut(gap));
bar.add(statusRepl);
//bar.add(Box.createHorizontalStrut(8));
bar.add(statusPos);
bar.add(statusLang);
bar.add(statusWrap);
bar.add(statusTab);
- bar.add(Box.createHorizontalStrut(8));
- bar.setBorder(null);
bar.setAlignmentX(Component.LEFT_ALIGNMENT); // same as body (JSplitPane), or BoxLayout shifts the body
syncStatusBar();
return bar;
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 e99394a5..7acd7133 100644
--- a/src/main/java/org/scijava/ui/swing/script/TextEditorTab.java
+++ b/src/main/java/org/scijava/ui/swing/script/TextEditorTab.java
@@ -34,6 +34,7 @@
import java.awt.Dimension;
import java.awt.Component;
import java.awt.Font;
+import java.awt.Insets;
import java.awt.Graphics2D;
import java.awt.geom.Path2D;
import java.awt.geom.RoundRectangle2D;
@@ -254,7 +255,10 @@ public void dragEnter(final DropTargetDragEvent e) {
promptBar.setBorder(null);
promptBar.setMargin(null);
prompt_panel.add(promptBar, BorderLayout.PAGE_START);
- prompt_panel.add(prompt, BorderLayout.CENTER);
+ // Same scroll pane (and thus border) as the console
+ final JScrollPane promptScroll = new JScrollPane(prompt);
+ TextEditor.GuiUtils.flattenScrollBars(promptScroll);
+ prompt_panel.add(promptScroll, BorderLayout.CENTER);
final JLabel label = new JLabel();
label.setForeground(TextEditor.GuiUtils.secondaryColor());
label.setIcon(new TextEditor.ReplIcon());
@@ -289,6 +293,7 @@ public void dragEnter(final DropTargetDragEvent e) {
// 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(TextEditor.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);
// No divider: the prompt bar is the handle. Keep promptDividerSize at 0 so toggling the REPL
@@ -359,14 +364,25 @@ void setREPLEnabled(final boolean enable) {
/** Whether the bottom part (output and prompt) is showing, i.e., not collapsed */
boolean isBottomVisible() {
if (axisSize() <= 0) return true; // not laid out yet
- return getDividerLocation() < getMaximumDividerLocation() - 5;
+ return getDividerLocation() < collapsedLocation() - 5;
+ }
+
+ /**
+ * Divider location at which the bottom part is fully collapsed. Unlike
+ * getMaximumDividerLocation() this ignores the minimum size of the bottom part: in a window
+ * too narrow (or short) to honor it, the part is shown truncated and would wrongly count as
+ * collapsed, so that it could not be collapsed again
+ */
+ private int collapsedLocation() {
+ final Insets in = getInsets();
+ return axisSize() - getDividerSize() - (isLayoutBelow() ? in.top + in.bottom : in.left + in.right);
}
/** Collapses the bottom part (output and prompt), or restores it to its last height */
void setBottomVisible(final boolean visible) {
if (visible == isBottomVisible()) return;
if (visible) {
- final int max = getMaximumDividerLocation();
+ final int max = collapsedLocation();
setDividerLocation(bottomLastLocation > 50 && bottomLastLocation < max - 5 ? bottomLastLocation
: (int) (axisSize() * .7));
} else {
From 17e4ee9da2d1f1dfd4983bdadaa9e60d6481dd95 Mon Sep 17 00:00:00 2001
From: Tiago Ferreira
Date: Sat, 14 Nov 2026 16:59:03 -0500
Subject: [PATCH 08/41] Organize GUI related code into dedicated classes
---
.../ui/swing/script/BookmarksPanel.java | 4 +-
.../ui/swing/script/CommandPalette.java | 299 +---------
.../scijava/ui/swing/script/ConsoleArea.java | 2 +-
.../scijava/ui/swing/script/EditorPane.java | 20 +-
.../ui/swing/script/FileSystemTree.java | 2 +-
.../ui/swing/script/FileSystemTreePanel.java | 93 +---
.../org/scijava/ui/swing/script/GuiUtils.java | 523 ++++++++++++++++++
.../scijava/ui/swing/script/GutterUtils.java | 65 ---
.../org/scijava/ui/swing/script/Icons.java | 345 ++++++++++++
.../scijava/ui/swing/script/NotesPanel.java | 8 +-
.../ui/swing/script/OutlineTreePanel.java | 6 +-
.../scijava/ui/swing/script/TextEditor.java | 456 +--------------
.../ui/swing/script/TextEditorTab.java | 185 ++-----
.../script/TextFieldWithPlaceholder.java | 79 +++
14 files changed, 1059 insertions(+), 1028 deletions(-)
create mode 100644 src/main/java/org/scijava/ui/swing/script/GuiUtils.java
create mode 100644 src/main/java/org/scijava/ui/swing/script/Icons.java
create mode 100644 src/main/java/org/scijava/ui/swing/script/TextFieldWithPlaceholder.java
diff --git a/src/main/java/org/scijava/ui/swing/script/BookmarksPanel.java b/src/main/java/org/scijava/ui/swing/script/BookmarksPanel.java
index 4e875152..b5358ff6 100644
--- a/src/main/java/org/scijava/ui/swing/script/BookmarksPanel.java
+++ b/src/main/java/org/scijava/ui/swing/script/BookmarksPanel.java
@@ -99,7 +99,7 @@ protected void paintComponent(final Graphics g) {
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setCellRenderer(new Renderer());
final JScrollPane pane = new JScrollPane(list);
- TextEditor.GuiUtils.flattenScrollBars(pane);
+ GuiUtils.flattenScrollBars(pane);
add(pane, BorderLayout.CENTER);
list.addMouseListener(new MouseAdapter() {
@@ -153,7 +153,7 @@ private static void paintEmptyHint(final java.awt.Graphics2D g2,
try {
g2.setRenderingHint(java.awt.RenderingHints.KEY_TEXT_ANTIALIASING,
java.awt.RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
- g2.setColor(TextEditor.GuiUtils.secondaryColor());
+ g2.setColor(GuiUtils.secondaryColor());
final java.awt.FontMetrics fm = g2.getFontMetrics();
int y = (c.getHeight() - fm.getHeight() * lines.length) / 2 + fm
.getAscent();
diff --git a/src/main/java/org/scijava/ui/swing/script/CommandPalette.java b/src/main/java/org/scijava/ui/swing/script/CommandPalette.java
index d694bb80..6d895eb9 100644
--- a/src/main/java/org/scijava/ui/swing/script/CommandPalette.java
+++ b/src/main/java/org/scijava/ui/swing/script/CommandPalette.java
@@ -30,7 +30,6 @@
package org.scijava.ui.swing.script;
import java.awt.AlphaComposite;
-import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
@@ -44,26 +43,19 @@
import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
-import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
-import java.awt.event.InputEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
-import java.awt.event.MouseMotionAdapter;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
-import java.awt.geom.Ellipse2D;
-import java.awt.geom.Line2D;
-import java.awt.geom.Path2D;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.function.Consumer;
-import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.AbstractAction;
@@ -72,7 +64,6 @@
import javax.swing.ActionMap;
import javax.swing.Box;
import javax.swing.BorderFactory;
-import javax.swing.Icon;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JComponent;
@@ -101,7 +92,6 @@
import javax.swing.table.DefaultTableCellRenderer;
import org.fife.ui.rtextarea.RecordableTextAction;
-import org.scijava.util.PlatformUtils;
import com.formdev.flatlaf.FlatClientProperties;
import com.formdev.flatlaf.icons.FlatSearchWithHistoryIcon;
@@ -172,7 +162,7 @@ public void actionPerformed(final ActionEvent e) {
/** Menu bar button that toggles the palette, for the right end of the menu bar */
JButton getMenuButton() {
- final JButton button = new JButton(new AbstractAction(null, new MagnifierIcon()) {
+ final JButton button = new JButton(new AbstractAction(null, Icons.magnifier()) {
private static final long serialVersionUID = 1L;
@@ -189,7 +179,7 @@ public void actionPerformed(final ActionEvent e) {
}
String getAcceleratorString() {
- return noHitsCmd.prettifiedKey(ACCELERATOR).trim();
+ return GuiUtils.prettifiedKey(ACCELERATOR).trim();
}
Map getShortcuts() {
@@ -263,35 +253,8 @@ public void mouseClicked(final MouseEvent e) {
populateList("");
frame.add(table.getScrollPane(), BorderLayout.SOUTH);
frame.pack();
- enableDrag(frame.getRootPane());
- enableDrag(titleBar);
- }
-
- private static void enableDrag(final JComponent component) {
- final Point[] dragStart = { null };
- component.addMouseListener(new MouseAdapter() {
- @Override
- public void mousePressed(final MouseEvent e) {
- dragStart[0] = e.getPoint();
- }
-
- @Override
- public void mouseReleased(final MouseEvent e) {
- dragStart[0] = null;
- }
- });
- component.addMouseMotionListener(new MouseMotionAdapter() {
- @Override
- public void mouseDragged(final MouseEvent e) {
- if (dragStart[0] != null) {
- final java.awt.Window w = SwingUtilities.getWindowAncestor(component);
- if (w == null)
- return;
- final Point loc = w.getLocation();
- w.setLocation(loc.x + e.getX() - dragStart[0].x, loc.y + e.getY() - dragStart[0].y);
- }
- }
- });
+ GuiUtils.enableDrag(frame.getRootPane());
+ GuiUtils.enableDrag(titleBar);
}
private void initSearchField() {
@@ -524,14 +487,13 @@ private static Color background() {
}
private static Color iconColor() {
- final Color c = TextEditor.GuiUtils.secondaryColor();
+ final Color c = GuiUtils.secondaryColor();
return (c != null) ? c : Color.GRAY;
}
/**
- * Toggle painted with the LAF's secondary color. The color is returned as a plain
- * Color because FlatLaf ignores foregrounds that are UIResources, and resolved on
- * every paint so that it follows Look and Feel changes
+ * Toggle painted with the LAF's secondary color, resolved on every paint so that
+ * it follows Look and Feel changes
*/
private static JToggleButton secondaryToggle(final String text, final String tooltip) {
final JToggleButton b = new JToggleButton(text) {
@@ -539,8 +501,8 @@ private static JToggleButton secondaryToggle(final String text, final String too
@Override
public Color getForeground() {
- final Color c = TextEditor.GuiUtils.secondaryColor();
- return (c != null) ? new Color(c.getRGB()) : super.getForeground();
+ final Color c = GuiUtils.secondaryColor();
+ return (c != null) ? c : super.getForeground();
}
};
b.setToolTipText(tooltip);
@@ -555,32 +517,8 @@ private static Color selectionColor() {
return (c != null) ? c : new Color(75, 110, 175);
}
- private static Color alpha(final Color c, final int percent) {
- return new Color(c.getRed(), c.getGreen(), c.getBlue(), Math.round(percent / 100f * 255));
- }
-
- /** Returns a color that is weight of a plus (1 - weight) of b */
- private static Color mix(final Color a, final Color b, final double weight) {
- final double w = Math.clamp(weight, 0d, 1d);
- return new Color((int) Math.round(a.getRed() * w + b.getRed() * (1 - w)),
- (int) Math.round(a.getGreen() * w + b.getGreen() * (1 - w)),
- (int) Math.round(a.getBlue() * w + b.getBlue() * (1 - w)));
- }
-
- private static void recolorTracks(final JScrollPane scrollPane, final Color color) {
- Component corner = scrollPane.getCorner(JScrollPane.LOWER_TRAILING_CORNER);
- if (corner == null) {
- corner = new JPanel();
- scrollPane.setCorner(JScrollPane.LOWER_TRAILING_CORNER, corner);
- }
- corner.setBackground(color);
- final Map style = Map.of("track", color, "hoverTrackColor", color);
- scrollPane.getHorizontalScrollBar().putClientProperty(FlatClientProperties.STYLE, style);
- scrollPane.getVerticalScrollBar().putClientProperty(FlatClientProperties.STYLE, style);
- }
-
/** The search field, with options menu, and case and whitespace toggles */
- private static class SearchField extends TextEditor.TextFieldWithPlaceholder {
+ private static class SearchField extends TextFieldWithPlaceholder {
private static final long serialVersionUID = 1L;
private static final float ENLARGE_FACTOR = 1.1f;
final JPopupMenu optionsMenu = new JPopupMenu();
@@ -632,7 +570,7 @@ private void enlarge(final JButton options) {
private void styleBorder() {
final int padding = (int) (getFont().getSize2D() * .8);
setBorder(BorderFactory.createCompoundBorder(
- BorderFactory.createMatteBorder(1, 0, 1, 0, alpha(iconColor(), 40)),
+ BorderFactory.createMatteBorder(1, 0, 1, 0, GuiUtils.alpha(iconColor(), 40)),
BorderFactory.createEmptyBorder(padding, padding, padding, padding)));
}
@@ -658,104 +596,6 @@ private float osScale() {
}
}
- /** Magnifier icon, painted with the foreground of its component */
- private static final class MagnifierIcon implements Icon {
-
- @Override
- public void paintIcon(final Component c, final Graphics g, final int x, final int y) {
- final Graphics2D g2 = (Graphics2D) g.create();
- try {
- g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
- g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
- g2.setColor(c.getForeground());
- g2.setStroke(new BasicStroke(UIScale.scale(1.6f), BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
- final float s = getIconWidth();
- g2.draw(new Ellipse2D.Float(x + .1f * s, y + .1f * s, .6f * s, .6f * s));
- g2.draw(new Line2D.Float(x + .62f * s, y + .62f * s, x + .88f * s, y + .88f * s));
- } finally {
- g2.dispose();
- }
- }
-
- @Override
- public int getIconWidth() {
- return UIScale.scale(16);
- }
-
- @Override
- public int getIconHeight() {
- return UIScale.scale(16);
- }
- }
-
- /** Light bulb icon (Font Awesome Free 7.3.1). Painted with the foreground of its component */
- private static final class BulbIcon implements Icon {
- private static final String PATH = "M424.5 355.1C449 329.2 464 294.4 464 256C464 176.5 399.5 112 320 112"
- + "C240.5 112 176 176.5 176 256C176 294.4 191 329.2 215.5 355.1C236.8 377.5 260.4 409.1 268.8 448"
- + "L371.2 448C379.6 409 403.2 377.5 424.5 355.1z"
- + "M459.3 388.1C435.7 413 416 443.4 416 477.7L416 496C416 540.2 380.2 576 336 576L304 576"
- + "C259.8 576 224 540.2 224 496L224 477.7C224 443.4 204.3 413 180.7 388.1C148 353.7 128 307.2 128 256"
- + "C128 150 214 64 320 64C426 64 512 150 512 256C512 307.2 492 353.7 459.3 388.1z"
- + "M272 248C272 261.3 261.3 272 248 272C234.7 272 224 261.3 224 248C224 199.4 263.4 160 312 160"
- + "C325.3 160 336 170.7 336 184C336 197.3 325.3 208 312 208C289.9 208 272 225.9 272 248z";
- // Glyph bounds within the 640x640 view box
- private static final double X0 = 128;
- private static final double Y0 = 64;
- private static final double GLYPH_W = 384;
- private static final double GLYPH_H = 512;
- private static final Path2D SHAPE = parse(PATH);
- private final int height;
-
- BulbIcon(final int height) {
- this.height = height;
- }
-
- /** Parses absolute M, L, C and z commands, the only ones in PATH */
- private static Path2D parse(final String d) {
- final Path2D.Double p = new Path2D.Double(Path2D.WIND_NON_ZERO);
- final Matcher m = Pattern.compile("([MLCz])([^MLCz]*)").matcher(d);
- while (m.find()) {
- final String args = m.group(2).trim();
- final String[] n = args.isEmpty() ? new String[0] : args.split("[ ,]+");
- switch (m.group(1).charAt(0)) {
- case 'M' -> p.moveTo(Double.parseDouble(n[0]), Double.parseDouble(n[1]));
- case 'L' -> p.lineTo(Double.parseDouble(n[0]), Double.parseDouble(n[1]));
- case 'C' -> p.curveTo(Double.parseDouble(n[0]), Double.parseDouble(n[1]), Double.parseDouble(n[2]),
- Double.parseDouble(n[3]), Double.parseDouble(n[4]), Double.parseDouble(n[5]));
- default -> p.closePath();
- }
- }
- return p;
- }
-
- @Override
- public void paintIcon(final Component c, final Graphics g, final int x, final int y) {
- final Graphics2D g2 = (Graphics2D) g.create();
- try {
- g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
- g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
- g2.setColor(c.getForeground());
- final double s = height / GLYPH_H;
- g2.translate(x, y);
- g2.scale(s, s);
- g2.translate(-X0, -Y0);
- g2.fill(SHAPE);
- } finally {
- g2.dispose();
- }
- }
-
- @Override
- public int getIconWidth() {
- return (int) Math.round(height * GLYPH_W / GLYPH_H);
- }
-
- @Override
- public int getIconHeight() {
- return height;
- }
- }
-
/** A {@link JLabel} that fades and slides in/out through a FlatLaf {@link Animator} */
private static class FadableHintLabel extends JLabel {
private static final long serialVersionUID = 1L;
@@ -854,9 +694,9 @@ void addHint(final JToolBar parent) {
label.setFont(label.getFont().deriveFont(label.getFont().getSize2D() * FONT_SCALE));
label.setForeground(iconColor());
label.setFocusable(false);
- enableDrag(label);
+ GuiUtils.enableDrag(label);
parent.add(label);
- final JButton button = new JButton(new BulbIcon((int) Math.round(label.getFont().getSize2D() * 1.2)));
+ final JButton button = new JButton(Icons.bulb(Math.round(UIScale.unscale(label.getFont().getSize2D() * 1.2f))));
button.setToolTipText("Search hints");
button.setForeground(iconColor());
button.setFocusable(false);
@@ -1037,7 +877,7 @@ private JScrollPane getScrollPane() {
@Override
public void updateUI() {
- recolorTracks(this, background());
+ GuiUtils.recolorTracks(this, background());
super.updateUI();
}
};
@@ -1066,11 +906,11 @@ public Component getTableCellRendererComponent(final JTable table, final Object
super.getTableCellRendererComponent(table, text, false, false, row, column);
final Color bg = table.getBackground();
final Color fg = table.getForeground();
- setBackground((isSelected) ? mix(selectionColor(), bg, .35) : bg);
+ setBackground((isSelected) ? GuiUtils.mix(selectionColor(), bg, .35) : bg);
if (cmd != null && cmd.isDisabled())
- setForeground(mix(fg, bg, .45));
+ setForeground(GuiUtils.mix(fg, bg, .45));
else
- setForeground((column == 0) ? fg : mix(fg, bg, .6));
+ setForeground((column == 0) ? fg : GuiUtils.mix(fg, bg, .6));
setHorizontalAlignment((column == 0) ? JLabel.LEFT : JLabel.RIGHT);
setFont((column == 0) ? col0Font : col1Font);
setBorder(BorderFactory.createEmptyBorder(0, 6, 0, 6));
@@ -1251,10 +1091,10 @@ private void ensureNormalized() {
void setkeyString(final KeyStroke key) {
if (hotkey.isEmpty()) {
- hotkey = prettifiedKey(key);
+ hotkey = GuiUtils.prettifiedKey(key);
} else {
final String oldHotkey = hotkey;
- final String newHotKey = prettifiedKey(key);
+ final String newHotKey = GuiUtils.prettifiedKey(key);
if (!oldHotkey.contains(newHotKey)) {
hotkey = oldHotkey + " or " + newHotKey;
}
@@ -1265,105 +1105,6 @@ private String capitalize(final String string) {
return string.substring(0, 1).toUpperCase() + string.substring(1);
}
- private String prettifiedKey(final KeyStroke key) {
- if (key == null)
- return "";
- final StringBuilder s = new StringBuilder();
- final int m = key.getModifiers();
- if ((m & InputEvent.CTRL_DOWN_MASK) != 0) {
- s.append((PlatformUtils.isMac()) ? "⌃ " : "Ctrl ");
- }
- if ((m & InputEvent.META_DOWN_MASK) != 0) {
- s.append((PlatformUtils.isMac()) ? "⌘ " : "Ctrl ");
- }
- if ((m & InputEvent.ALT_DOWN_MASK) != 0) {
- s.append((PlatformUtils.isMac()) ? "⎇ " : "Alt ");
- }
- if ((m & InputEvent.SHIFT_DOWN_MASK) != 0) {
- s.append("⇧ ");
- }
- if ((m & InputEvent.BUTTON1_DOWN_MASK) != 0) {
- s.append("L-click ");
- }
- if ((m & InputEvent.BUTTON2_DOWN_MASK) != 0) {
- s.append("R-click ");
- }
- if ((m & InputEvent.BUTTON3_DOWN_MASK) != 0) {
- s.append("M-click ");
- }
- switch (key.getKeyEventType()) {
- case KeyEvent.KEY_TYPED:
- s.append(key.getKeyChar()).append(" ");
- break;
- case KeyEvent.KEY_PRESSED:
- case KeyEvent.KEY_RELEASED:
- s.append(getKeyText(key.getKeyCode())).append(" ");
- break;
- default:
- break;
- }
- return s.toString();
- }
-
- String getKeyText(final int keyCode) {
- if (keyCode >= KeyEvent.VK_0 && keyCode <= KeyEvent.VK_9
- || keyCode >= KeyEvent.VK_A && keyCode <= KeyEvent.VK_Z) {
- return String.valueOf((char) keyCode);
- }
- return switch (keyCode) {
- case KeyEvent.VK_COMMA -> ",";
- case KeyEvent.VK_PERIOD -> ".";
- case KeyEvent.VK_SLASH -> "/";
- case KeyEvent.VK_SEMICOLON -> ";";
- case KeyEvent.VK_EQUALS -> "=";
- case KeyEvent.VK_OPEN_BRACKET -> "[";
- case KeyEvent.VK_BACK_SLASH -> "\\";
- case KeyEvent.VK_CLOSE_BRACKET -> "]";
- case KeyEvent.VK_ENTER -> "↵";
- case KeyEvent.VK_BACK_SPACE -> "⌫";
- case KeyEvent.VK_TAB -> "↹";
- case KeyEvent.VK_CANCEL -> "Cancel";
- case KeyEvent.VK_CLEAR -> "Clear";
- case KeyEvent.VK_PAUSE -> "Pause";
- case KeyEvent.VK_CAPS_LOCK -> "Caps Lock";
- case KeyEvent.VK_ESCAPE -> "Esc";
- case KeyEvent.VK_SPACE -> "Space";
- case KeyEvent.VK_PAGE_UP -> "⇞";
- case KeyEvent.VK_PAGE_DOWN -> "⇟";
- case KeyEvent.VK_END -> "END";
- case KeyEvent.VK_HOME -> "Home"; // "⌂";
- case KeyEvent.VK_LEFT -> "←";
- case KeyEvent.VK_UP -> "↑";
- case KeyEvent.VK_RIGHT -> "→";
- case KeyEvent.VK_DOWN -> "↓";
- case KeyEvent.VK_MULTIPLY -> "[Num ×]";
- case KeyEvent.VK_ADD -> "[Num +]";
- case KeyEvent.VK_SUBTRACT -> "[Num −]";
- case KeyEvent.VK_DIVIDE -> "[Num /]";
- case KeyEvent.VK_DELETE -> "⌦";
- case KeyEvent.VK_INSERT -> "Ins";
- case KeyEvent.VK_BACK_QUOTE -> "`";
- case KeyEvent.VK_QUOTE -> "'";
- case KeyEvent.VK_AMPERSAND -> "&";
- case KeyEvent.VK_ASTERISK -> "*";
- case KeyEvent.VK_QUOTEDBL -> "\"";
- case KeyEvent.VK_LESS -> "<";
- case KeyEvent.VK_GREATER -> ">";
- case KeyEvent.VK_BRACELEFT -> "{";
- case KeyEvent.VK_BRACERIGHT -> "}";
- case KeyEvent.VK_COLON -> ":";
- case KeyEvent.VK_CIRCUMFLEX -> "^";
- case KeyEvent.VK_DEAD_TILDE -> "~";
- case KeyEvent.VK_DOLLAR -> "$";
- case KeyEvent.VK_EXCLAMATION_MARK -> "!";
- case KeyEvent.VK_LEFT_PARENTHESIS -> "(";
- case KeyEvent.VK_MINUS -> "-";
- case KeyEvent.VK_PLUS -> "+";
- case KeyEvent.VK_RIGHT_PARENTHESIS -> ")";
- case KeyEvent.VK_UNDERSCORE -> "_";
- default -> KeyEvent.getKeyText(keyCode);
- };
- }
}
/** Levenshtein test that bails out once the distance is known to exceed max */
@@ -1577,7 +1318,7 @@ private class SearchWebCmd extends CmdAction {
@Override
public void actionPerformed(final ActionEvent e) {
- TextEditor.GuiUtils.runSearchQueryInBrowser(textEditor, textEditor.getPlatformService(),
+ GuiUtils.runSearchQueryInBrowser(textEditor, textEditor.getPlatformService(),
searchField.getText());
}
});
diff --git a/src/main/java/org/scijava/ui/swing/script/ConsoleArea.java b/src/main/java/org/scijava/ui/swing/script/ConsoleArea.java
index 389601de..78534d58 100644
--- a/src/main/java/org/scijava/ui/swing/script/ConsoleArea.java
+++ b/src/main/java/org/scijava/ui/swing/script/ConsoleArea.java
@@ -184,7 +184,7 @@ private boolean isError(final int pos) {
private Color colorAt(final int pos) {
final Color fg = getForeground(), bg = getBackground();
- final boolean dark = TextEditor.GuiUtils.isDark(bg);
+ final boolean dark = GuiUtils.isDark(bg);
final Color base = isError(pos) ? (dark ? new Color(255, 95, 95) : new Color(200, 0, 0)) : fg;
return pos < runStart.offset ? blend(base, bg, 0.5) : base;
}
diff --git a/src/main/java/org/scijava/ui/swing/script/EditorPane.java b/src/main/java/org/scijava/ui/swing/script/EditorPane.java
index bcc4ec88..75800c9b 100644
--- a/src/main/java/org/scijava/ui/swing/script/EditorPane.java
+++ b/src/main/java/org/scijava/ui/swing/script/EditorPane.java
@@ -248,24 +248,24 @@ private void installCustomPopupMenu() {
// this is the only access point in the GUI for these
// see #createPopupMenu(); #appendFoldingMenu();
final JPopupMenu popup = new JPopupMenu();
- TextEditor.GuiUtils.addPopupMenuSeparator(popup, "Code Editing:");
+ GuiUtils.addPopupMenuSeparator(popup, "Code Editing:");
popup.add(getMenuItem("Copy", EditorPaneActions.copyAction, false));
popup.add(getMenuItem("Cut", EditorPaneActions.cutAction, true));
popup.add(getMenuItem("Paste", EditorPaneActions.pasteAction, true));
popup.add(getMenuItem("Delete Line", EditorPaneActions.rtaDeleteLineAction, true));
popup.add(getMenuItem("Delete Rest of Line", EditorPaneActions.rtaDeleteRestOfLineAction, true));
- TextEditor.GuiUtils.addPopupMenuSeparator(popup, "Code Selection:");
+ GuiUtils.addPopupMenuSeparator(popup, "Code Selection:");
popup.add(getMenuItem("Select All", EditorPaneActions.selectAllAction, false));
popup.add(getMenuItem("Select Line", EditorPaneActions.selectLineAction, false));
popup.add(getMenuItem("Select Paragraph", EditorPaneActions.selectParagraphAction, false));
- TextEditor.GuiUtils.addPopupMenuSeparator(popup, "Code Folding:");
+ GuiUtils.addPopupMenuSeparator(popup, "Code Folding:");
popup.add(getMenuItem("Collapse Fold", EditorPaneActions.rstaCollapseFoldAction, false));
popup.add(getMenuItem("Expand Fold", EditorPaneActions.rstaExpandFoldAction, false));
popup.add(getMenuItem("Toggle Current Fold", EditorPaneActions.rstaToggleCurrentFoldAction, false));
popup.add(getMenuItem("Collapse All Folds", EditorPaneActions.rstaCollapseAllFoldsAction, false));
popup.add(getMenuItem("Expand All Folds", EditorPaneActions.rstaExpandAllFoldsAction, false));
popup.add(getMenuItem("Collapse All Comments", EditorPaneActions.rstaCollapseAllCommentFoldsAction, false));
- TextEditor.GuiUtils.addPopupMenuSeparator(popup, "Code Formatting:");
+ GuiUtils.addPopupMenuSeparator(popup, "Code Formatting:");
popup.add(getMenuItem("Indent Right", EditorPaneActions.epaIncreaseIndentAction, true));
popup.add(getMenuItem("Indent Left", EditorPaneActions.rstaDecreaseIndentAction, true));
popup.add(getMenuItem("Move Up", EditorPaneActions.rtaLineUpAction, true));
@@ -280,10 +280,10 @@ private void installCustomPopupMenu() {
menu.add(getMenuItem("Lower Case ('_' Sep.)", EditorPaneActions.epaLowerCaseUndAction, true));
menu.add(getMenuItem("Title Case", EditorPaneActions.epaTitleCaseAction, true));
menu.add(getMenuItem("Upper Case", EditorPaneActions.rtaUpperSelectionCaseAction, true));
- TextEditor.GuiUtils.addPopupMenuSeparator(popup, "Ocurrences:");
+ GuiUtils.addPopupMenuSeparator(popup, "Ocurrences:");
popup.add(getMenuItem("Next Occurrence", EditorPaneActions.rtaNextOccurrenceAction, false));
popup.add(getMenuItem("Previous Occurrence", EditorPaneActions.rtaPrevOccurrenceAction, false));
- TextEditor.GuiUtils.addPopupMenuSeparator(popup, "Utilities:");
+ GuiUtils.addPopupMenuSeparator(popup, "Utilities:");
popup.add(new OpenLinkUnderCursor().getMenuItem());
popup.add(new SearchWebOnSelectedText().getMenuItem());
popup.add(noneLangSyntaxMenu);
@@ -335,7 +335,7 @@ private JMenuItem getSyntaxItem(final ButtonGroup bg, final String label, final
}
void error(final String message) {
- TextEditor.GuiUtils.error(this, message);
+ GuiUtils.error(this, message);
}
private void updateNoneLangSyntaxMenu(final ScriptLanguage language) {
@@ -383,7 +383,7 @@ public RTextScrollPane wrappedInScrollbars() {
final RTextScrollPane sp = new RTextScrollPane(this);
sp.setPreferredSize(new Dimension(600, 350));
sp.setIconRowHeaderEnabled(true);
- TextEditor.GuiUtils.flattenScrollBars(sp);
+ GuiUtils.flattenScrollBars(sp);
gutter = sp.getGutter();
gutter.setBookmarkingEnabled(true);
gutter.setShowCollapsedRegionToolTips(true);
@@ -1123,7 +1123,7 @@ public void loadPreferences() {
public void applyTheme(final String theme) throws IllegalArgumentException {
try {
// If dark L&F and using the default theme, assume 'dark' theme
- final boolean dark = DEFAULT_THEME.equals(theme) && TextEditor.GuiUtils.isDarkLaF();
+ final boolean dark = DEFAULT_THEME.equals(theme) && GuiUtils.isDarkLaF();
applyTheme(TextEditor.getTheme(dark ? "dark" : theme));
} catch (final Exception ex) {
throw new IllegalArgumentException(ex);
@@ -1212,7 +1212,7 @@ public void actionPerformedImpl(final ActionEvent e, final RTextArea textArea) {
if (selection == null) {
UIManager.getLookAndFeel().provideErrorFeedback(textArea);
} else {
- TextEditor.GuiUtils.runSearchQueryInBrowser(EditorPane.this, platformService, selection.trim());
+ GuiUtils.runSearchQueryInBrowser(EditorPane.this, platformService, selection.trim());
}
textArea.requestFocusInWindow();
}
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 275cc646..f513866b 100644
--- a/src/main/java/org/scijava/ui/swing/script/FileSystemTree.java
+++ b/src/main/java/org/scijava/ui/swing/script/FileSystemTree.java
@@ -362,7 +362,7 @@ protected void paintComponent(final Graphics g) {
try {
g2.setRenderingHint(java.awt.RenderingHints.KEY_TEXT_ANTIALIASING,
java.awt.RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
- g2.setColor(TextEditor.GuiUtils.secondaryColor());
+ g2.setColor(GuiUtils.secondaryColor());
final java.awt.FontMetrics fm = g2.getFontMetrics();
int y = (getHeight() - fm.getHeight() * lines.length) / 2 + fm.getAscent();
for (final String line : lines) {
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 c5e89774..e2157074 100644
--- a/src/main/java/org/scijava/ui/swing/script/FileSystemTreePanel.java
+++ b/src/main/java/org/scijava/ui/swing/script/FileSystemTreePanel.java
@@ -110,7 +110,7 @@ class FileSystemTreePanel extends JPanel {
bc.weighty = 1.0;
bc.fill = GridBagConstraints.BOTH;
final JScrollPane treePane = new JScrollPane(tree);
- TextEditor.GuiUtils.flattenScrollBars(treePane);
+ GuiUtils.flattenScrollBars(treePane);
add(treePane, bc);
bc.gridy = 2;
bc.weightx = 0;
@@ -123,7 +123,7 @@ class FileSystemTreePanel extends JPanel {
addRootFromFile(files[0]);
} else if (dirs.size() == 1) { // A single folder dropped
addRootFromFile(dirs.get(0));
- } else if (TextEditor.GuiUtils.confirm(this,
+ } else if (GuiUtils.confirm(this,
"Replace contents with the " + dirs.size() + " dropped folders?",
"Replace Contents?", "Confirm")) {
tree.clearTopLevelFolders(); // Blank out the entire tree
@@ -131,7 +131,7 @@ class FileSystemTreePanel extends JPanel {
}
} catch (final Throwable ignored) {
- TextEditor.GuiUtils.warn(this, "Could not retrieve location of dropped file(s).");
+ GuiUtils.warn(this, "Could not retrieve location of dropped file(s).");
}
});
}
@@ -172,12 +172,12 @@ private JToolBar statusToolbar() {
toolbar.setBorder(BorderFactory.createCompoundBorder(new SideBorder(), toolbar.getBorder()));
final JToggleButton statusFast = new JToggleButton("Fast Mode");
statusFast.putClientProperty(FlatClientProperties.STYLE_CLASS, "small");
- statusFast.setForeground(TextEditor.GuiUtils.secondaryColor());
+ statusFast.setForeground(GuiUtils.secondaryColor());
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") : TextEditor.GuiUtils.secondaryColor();
+ 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);
@@ -186,7 +186,7 @@ private JToolBar statusToolbar() {
final FlatFileChooserDetailsViewIcon optionsIcon = new FlatFileChooserDetailsViewIcon();
optionsIcon.setScale(.8f); // matches the font size set by the "small" style
statusOptions.putClientProperty(FlatClientProperties.STYLE_CLASS, "small");
- statusOptions.setForeground(TextEditor.GuiUtils.secondaryColor());
+ statusOptions.setForeground(GuiUtils.secondaryColor());
statusOptions.addActionListener(e -> tree.getComponentPopupMenu().show(statusOptions, 0, 0));
statusOptions.setIcon(optionsIcon);
toolbar.add(statusFast);
@@ -195,7 +195,7 @@ private JToolBar statusToolbar() {
toolbar.add(Box.createHorizontalGlue());
final FlatHelpButtonIcon helpIcon = new FlatHelpButtonIcon();
helpIcon.setScale(.8f); // matches the font size set by the "small" style
- helpIcon.applyStyleProperty("questionMarkColor", TextEditor.GuiUtils.secondaryColor());
+ helpIcon.applyStyleProperty("questionMarkColor", GuiUtils.secondaryColor());
helpIcon.applyStyleProperty("background", toolbar.getBackground());
final JButton statusHelp = new JButton(helpIcon);
statusHelp.addActionListener(e -> showHelpMsg());
@@ -377,7 +377,7 @@ private JMenuItem addDirectoryMenuItem() {
final File ref = files[0].getAbsoluteFile();
c.setCurrentDirectory((ref.isDirectory()) ? ref : ref.getParentFile());
} catch (final Throwable ignored) {
- TextEditor.GuiUtils.warn(this, "Could not retrieve location of dropped file(s).");
+ GuiUtils.warn(this, "Could not retrieve location of dropped file(s).");
}
});
if (JFileChooser.APPROVE_OPTION == c.showOpenDialog(this)) {
@@ -403,7 +403,7 @@ private JMenuItem removeDirectoryMenuItem() {
}
} catch (Exception ex) {
- TextEditor.GuiUtils.error(this, "Could not remove top-level folders.");
+ GuiUtils.error(this, "Could not remove top-level folders.");
}
});
return remove_directory;
@@ -465,7 +465,7 @@ private boolean allTreeNodesCollapsed() {
private void addContextualMenuToTree() {
final JPopupMenu popup = new JPopupMenu();
- TextEditor.GuiUtils.addPopupMenuSeparator(popup, "List:");
+ GuiUtils.addPopupMenuSeparator(popup, "List:");
final JMenuItem selected = new JMenuItem("Selected Folder", new FlatFileViewDirectoryIcon());
selected.setToolTipText("Makes the selected folder (or the folder of the selected file) the only top-level folder");
selected.addActionListener(e -> {
@@ -491,13 +491,13 @@ private void addContextualMenuToTree() {
popup.add(jmi);
popup.add(addDirectoryMenuItem());
- TextEditor.GuiUtils.addPopupMenuSeparator(popup, "Open In:");
+ GuiUtils.addPopupMenuSeparator(popup, "Open In:");
final JMenuItem fileSystem = new JMenuItem("File System", new FlatFileViewComputerIcon());
jmi = fileSystem;
jmi.addActionListener(e -> {
final TreePath path = tree.getSelectionPath();
if (path == null) {
- TextEditor.GuiUtils.info(this, "No items are currently selected.", "Invalid Selection");
+ GuiUtils.info(this, "No items are currently selected.", "Invalid Selection");
return;
}
try {
@@ -505,7 +505,7 @@ private void addContextualMenuToTree() {
final File f = new File(filepath);
Desktop.getDesktop().open((f.isDirectory()) ? f : f.getParentFile());
} catch (final Throwable ignored) {
- TextEditor.GuiUtils.error(this, "Folder of selected item does not seem to be accessible.");
+ GuiUtils.error(this, "Folder of selected item does not seem to be accessible.");
}
});
popup.add(jmi);
@@ -514,22 +514,22 @@ private void addContextualMenuToTree() {
jmi.addActionListener(e -> {
final TreePath path = tree.getSelectionPath();
if (path == null) {
- TextEditor.GuiUtils.info(this, "No items are currently selected.", "Invalid Selection");
+ GuiUtils.info(this, "No items are currently selected.", "Invalid Selection");
return;
}
try {
final String filepath = (String) ((FileSystemTree.Node) path.getLastPathComponent()).getUserObject();
- TextEditor.GuiUtils.openTerminal(new File(filepath));
+ GuiUtils.openTerminal(new File(filepath));
} catch (final Throwable ignored) {
- TextEditor.GuiUtils.error(this, "Could not open path in Terminal.");
+ GuiUtils.error(this, "Could not open path in Terminal.");
}
});
popup.add(jmi);
- TextEditor.GuiUtils.addPopupMenuSeparator(popup, "Contents:");
+ GuiUtils.addPopupMenuSeparator(popup, "Contents:");
final JMenuItem collapseAll = new JMenuItem("Collapse All");
jmi = collapseAll;
- jmi.addActionListener(e -> TextEditor.GuiUtils.collapseAllTreeNodes(tree));
+ jmi.addActionListener(e -> GuiUtils.collapseAllTreeNodes(tree));
popup.add(jmi);
final JMenuItem expandLevel = new JMenuItem("Expand One Level");
jmi = expandLevel;
@@ -548,7 +548,7 @@ private void addContextualMenuToTree() {
});
popup.add(live);
- TextEditor.GuiUtils.addPopupMenuSeparator(popup, "Reset:");
+ GuiUtils.addPopupMenuSeparator(popup, "Reset:");
final JMenuItem removeLast = removeDirectoryMenuItem();
popup.add(removeLast);
final JMenuItem wipe = new JMenuItem("Clear All");
@@ -688,7 +688,7 @@ private void showHelpMsg() {
+ "^Demo (names starting with Demo)" //
+ "";
- TextEditor.GuiUtils.showHTMLDialog(this.getRootPane(), "Files Pane", msg);
+ GuiUtils.showHTMLDialog(this.getRootPane(), "Files Pane", msg);
}
private boolean isCaseSensitive() {
@@ -715,7 +715,7 @@ private void setCollapsedEnabled(final boolean b) {
applyFilter();
}
- private class SearchField extends TextEditor.TextFieldWithPlaceholder {
+ private class SearchField extends TextFieldWithPlaceholder {
private static final long serialVersionUID = 7004232238240585434L;
private static final String DEF_HOLDER = "File filter...";
@@ -740,8 +740,8 @@ private class SearchField extends TextEditor.TextFieldWithPlaceholder {
collapsedToggle = optionToggle(null, "Include collapsed folders in searches (slower)", FileSystemTreePanel.this::setCollapsedEnabled);
collapsedToggle.setSelected(tree.isSearchCollapsedFolders()); // reflect the default
// Tree chevrons (collapsed/expanded) instead of text
- collapsedToggle.setIcon(new ChevronIcon(false));
- collapsedToggle.setSelectedIcon(new ChevronIcon(true));
+ collapsedToggle.setIcon(Icons.chevron(false));
+ collapsedToggle.setSelectedIcon(Icons.chevron(true));
final JToolBar tb = new JToolBar();
tb.setMargin(new Insets(0, 0, 0, 2));
@@ -809,7 +809,7 @@ private JToggleButton optionToggle(final String label, final String tooltip, fin
@Override
public Color getForeground() {
- final Color c = TextEditor.GuiUtils.secondaryColor();
+ final Color c = GuiUtils.secondaryColor();
return (c != null) ? c : super.getForeground();
}
};
@@ -837,49 +837,4 @@ void resetOptions() {
regex = false;
}
}
- /** A chevron pointing right (collapsed) or down (expanded), painted with the foreground of its button */
- private static final class ChevronIcon implements Icon {
-
- private final boolean down;
-
- ChevronIcon(final boolean down) {
- this.down = down;
- }
-
- @Override
- public int getIconWidth() {
- return UIScale.scale(10);
- }
-
- @Override
- public int getIconHeight() {
- return UIScale.scale(10);
- }
-
- @Override
- public void paintIcon(final Component c, final Graphics g, final int x, final int y) {
- final Graphics2D g2 = (Graphics2D) g.create();
- try {
- g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
- g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
- g2.setColor(c.getForeground());
- g2.setStroke(new BasicStroke(UIScale.scale(1.3f), BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
- final float s = getIconWidth();
- final float a = s * .3f; // inset
- final java.awt.geom.Path2D.Float p = new java.awt.geom.Path2D.Float();
- if (down) {
- p.moveTo(x + a * .5f, y + s * .35f);
- p.lineTo(x + s / 2, y + s * .65f);
- p.lineTo(x + s - a * .5f, y + s * .35f);
- } else {
- p.moveTo(x + s * .35f, y + a * .5f);
- p.lineTo(x + s * .65f, y + s / 2);
- p.lineTo(x + s * .35f, y + s - a * .5f);
- }
- g2.draw(p);
- } finally {
- g2.dispose();
- }
- }
- }
}
diff --git a/src/main/java/org/scijava/ui/swing/script/GuiUtils.java b/src/main/java/org/scijava/ui/swing/script/GuiUtils.java
new file mode 100644
index 00000000..01e746a1
--- /dev/null
+++ b/src/main/java/org/scijava/ui/swing/script/GuiUtils.java
@@ -0,0 +1,523 @@
+/*
+ * #%L
+ * Script Editor and Interpreter for SciJava script languages.
+ * %%
+ * Copyright (C) 2009 - 2026 SciJava developers.
+ * %%
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ * #L%
+ */
+
+package org.scijava.ui.swing.script;
+
+import java.awt.Color;
+import java.awt.Component;
+import java.awt.Dimension;
+import java.awt.Font;
+import java.awt.Point;
+import java.awt.event.InputEvent;
+import java.awt.event.KeyEvent;
+import java.awt.event.MouseAdapter;
+import java.awt.event.MouseEvent;
+import java.awt.event.MouseMotionAdapter;
+import java.io.File;
+import java.io.IOException;
+import java.net.URL;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.util.Map;
+
+import javax.swing.ButtonGroup;
+import javax.swing.JButton;
+import javax.swing.JCheckBoxMenuItem;
+import javax.swing.JComponent;
+import javax.swing.JDialog;
+import javax.swing.JLabel;
+import javax.swing.JMenu;
+import javax.swing.JMenuItem;
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+import javax.swing.JPopupMenu;
+import javax.swing.JScrollPane;
+import javax.swing.JSplitPane;
+import javax.swing.JTabbedPane;
+import javax.swing.JTextPane;
+import javax.swing.JTree;
+import javax.swing.KeyStroke;
+import javax.swing.SwingUtilities;
+import javax.swing.UIManager;
+
+import org.scijava.platform.PlatformService;
+import org.scijava.util.PlatformUtils;
+
+import com.formdev.flatlaf.FlatClientProperties;
+import com.formdev.flatlaf.FlatLaf;
+
+/** Static helpers for dialogs, menus and widgets shared by the script editor */
+final class GuiUtils {
+
+ private GuiUtils() {
+ }
+
+ static void error(final Component parent, final String message) {
+ JOptionPane.showMessageDialog(parent, message, "Error", JOptionPane.ERROR_MESSAGE);
+ }
+
+ static void warn(final Component parent, final String message) {
+ JOptionPane.showMessageDialog(parent, message, "Warning", JOptionPane.WARNING_MESSAGE);
+ }
+
+ static void info(final Component parent, final String message, final String title) {
+ JOptionPane.showMessageDialog(parent, message, title, JOptionPane.INFORMATION_MESSAGE);
+ }
+
+ static boolean confirm(final Component parent, final String message, final String title,
+ final String yesButtonLabel) {
+ return JOptionPane.showConfirmDialog(parent, message, title, JOptionPane.YES_NO_OPTION) ==
+ JOptionPane.YES_OPTION;
+ }
+
+ static void showHTMLDialog(final Component parent, final String title, final String htmlContents) {
+ final JTextPane f = new JTextPane();
+ f.setContentType("text/html");
+ f.setEditable(false);
+ f.setBackground(null);
+ f.setBorder(null);
+ f.setText(htmlContents);
+ f.setCaretPosition(0);
+ final JScrollPane sp = new JScrollPane(f);
+ final JOptionPane pane = new JOptionPane(sp);
+ final JDialog dialog = pane.createDialog(parent, title);
+ dialog.setResizable(true);
+ dialog.pack();
+ dialog.setPreferredSize(
+ new Dimension(
+ (int) Math.min(parent.getWidth() * .5, pane.getPreferredSize().getWidth() + (3 * sp.getVerticalScrollBar().getWidth())),
+ (int) Math.min(parent.getHeight() * .8, pane.getPreferredSize().getHeight())));
+ dialog.pack();
+ pane.addPropertyChangeListener(JOptionPane.VALUE_PROPERTY, ignored -> {
+ dialog.dispose();
+ });
+ dialog.setModal(false);
+ dialog.setLocationRelativeTo(parent);
+ dialog.setVisible(true);
+ }
+
+ static String getString(final Component parent, final String message, final String title) {
+ return (String) JOptionPane.showInputDialog(parent, message, title, JOptionPane.QUESTION_MESSAGE);
+ }
+
+ static void runSearchQueryInBrowser(final Component parentComponent, final PlatformService platformService,
+ final String query) {
+ String url;
+ try {
+ url = "https://forum.image.sc/search?q=" + URLEncoder.encode(query, StandardCharsets.UTF_8.toString());
+ } catch (final Exception ignored) {
+ url = query.trim().replace(" ", "%20");
+ }
+ openURL(parentComponent, platformService, url);
+ }
+
+ static void openURL(final Component parentComponent, final PlatformService platformService, final String url) {
+ try {
+ platformService.open(new URL(url));
+ } catch (final Exception ignored) {
+ // Error message with selectable text
+ final JTextPane f = new JTextPane();
+ f.setContentType("text/html");
+ f.setText("Web page could not be open. Please visit
" + url + "
using your web browser.");
+ f.setEditable(false);
+ f.setBackground(null);
+ f.setBorder(null);
+ JOptionPane.showMessageDialog(parentComponent, f, "Error", JOptionPane.ERROR_MESSAGE);
+ }
+ }
+
+ static void openTerminal(final File pwd) throws IOException, InterruptedException {
+ final String[] wrappedCommand;
+ final File dir = (pwd.isDirectory()) ? pwd : pwd.getParentFile();
+ if (PlatformUtils.isWindows()) {
+ // this should probably be replaced with powershell!?
+ wrappedCommand = new String[] { "cmd", "/c", "start", "/wait", "cmd.exe", "/K" };
+ } else if (PlatformUtils.isLinux()) {
+ // this will likely only work on debian-based distros
+ wrappedCommand = new String[] { "/usr/bin/x-terminal-emulator" };
+ } else if (PlatformUtils.isMac()) {
+ // On MacOS ProcessBuilder#directory() fails!? so we'll use applescript :)
+ wrappedCommand = new String[] { "osascript", "-e", //
+ "tell application \"Terminal\" to (do script \"cd '" + dir.getAbsolutePath() + "';clear\")" };
+ } else {
+ throw new IllegalArgumentException("Unsupported OS");
+ }
+ final ProcessBuilder pb = new ProcessBuilder(wrappedCommand);
+ pb.directory(dir); // does nothing on macOS !?
+ pb.start();
+ }
+
+ static void addMenubarSeparator(final JMenu menu, final String header) {
+ if (menu.getMenuComponentCount() > 0) {
+ menu.addSeparator();
+ }
+ try {
+ final JLabel label = new JLabel(" "+ header);
+ label.setEnabled(false);
+ label.setForeground(getDisabledComponentColor());
+ menu.add(label);
+ } catch (final Exception ignored) {
+ // do nothing
+ }
+ }
+
+ static void addPopupMenuSeparator(final JPopupMenu menu, final String header) {
+ if (menu.getComponentCount() > 1) {
+ menu.addSeparator();
+ }
+ final JLabel label = new JLabel(header);
+ // label.setHorizontalAlignment(SwingConstants.LEFT);
+ label.setEnabled(false);
+ label.setForeground(getDisabledComponentColor());
+ menu.add(label);
+
+ }
+
+ static Color getDisabledComponentColor() {
+ try {
+ return UIManager.getColor("MenuItem.disabledForeground");
+ } catch (final Exception ignored) {
+ return Color.GRAY;
+ }
+ }
+
+ /** Readable form of a key stroke, e.g., "Ctrl Shift P", using glyphs on macOS */
+ static String prettifiedKey(final KeyStroke key) {
+ if (key == null)
+ return "";
+ final StringBuilder s = new StringBuilder();
+ final int m = key.getModifiers();
+ if ((m & InputEvent.CTRL_DOWN_MASK) != 0) {
+ s.append((PlatformUtils.isMac()) ? "\u2303 " : "Ctrl ");
+ }
+ if ((m & InputEvent.META_DOWN_MASK) != 0) {
+ s.append((PlatformUtils.isMac()) ? "\u2318 " : "Ctrl ");
+ }
+ if ((m & InputEvent.ALT_DOWN_MASK) != 0) {
+ s.append((PlatformUtils.isMac()) ? "\u2387 " : "Alt ");
+ }
+ if ((m & InputEvent.SHIFT_DOWN_MASK) != 0) {
+ s.append("\u21e7 ");
+ }
+ if ((m & InputEvent.BUTTON1_DOWN_MASK) != 0) {
+ s.append("L-click ");
+ }
+ if ((m & InputEvent.BUTTON2_DOWN_MASK) != 0) {
+ s.append("R-click ");
+ }
+ if ((m & InputEvent.BUTTON3_DOWN_MASK) != 0) {
+ s.append("M-click ");
+ }
+ switch (key.getKeyEventType()) {
+ case KeyEvent.KEY_TYPED:
+ s.append(key.getKeyChar()).append(" ");
+ break;
+ case KeyEvent.KEY_PRESSED:
+ case KeyEvent.KEY_RELEASED:
+ s.append(getKeyText(key.getKeyCode())).append(" ");
+ break;
+ default:
+ break;
+ }
+ return s.toString();
+ }
+
+ private static String getKeyText(final int keyCode) {
+ if (keyCode >= KeyEvent.VK_0 && keyCode <= KeyEvent.VK_9
+ || keyCode >= KeyEvent.VK_A && keyCode <= KeyEvent.VK_Z) {
+ return String.valueOf((char) keyCode);
+ }
+ return switch (keyCode) {
+ case KeyEvent.VK_COMMA -> ",";
+ case KeyEvent.VK_PERIOD -> ".";
+ case KeyEvent.VK_SLASH -> "/";
+ case KeyEvent.VK_SEMICOLON -> ";";
+ case KeyEvent.VK_EQUALS -> "=";
+ case KeyEvent.VK_OPEN_BRACKET -> "[";
+ case KeyEvent.VK_BACK_SLASH -> "\\";
+ case KeyEvent.VK_CLOSE_BRACKET -> "]";
+ case KeyEvent.VK_ENTER -> "\u21b5";
+ case KeyEvent.VK_BACK_SPACE -> "\u232b";
+ case KeyEvent.VK_TAB -> "\u21b9";
+ case KeyEvent.VK_CANCEL -> "Cancel";
+ case KeyEvent.VK_CLEAR -> "Clear";
+ case KeyEvent.VK_PAUSE -> "Pause";
+ case KeyEvent.VK_CAPS_LOCK -> "Caps Lock";
+ case KeyEvent.VK_ESCAPE -> "Esc";
+ case KeyEvent.VK_SPACE -> "Space";
+ case KeyEvent.VK_PAGE_UP -> "\u21de";
+ case KeyEvent.VK_PAGE_DOWN -> "\u21df";
+ case KeyEvent.VK_END -> "END";
+ case KeyEvent.VK_HOME -> "Home";
+ case KeyEvent.VK_LEFT -> "\u2190";
+ case KeyEvent.VK_UP -> "\u2191";
+ case KeyEvent.VK_RIGHT -> "\u2192";
+ case KeyEvent.VK_DOWN -> "\u2193";
+ case KeyEvent.VK_MULTIPLY -> "[Num \u00d7]";
+ case KeyEvent.VK_ADD -> "[Num +]";
+ case KeyEvent.VK_SUBTRACT -> "[Num \u2212]";
+ case KeyEvent.VK_DIVIDE -> "[Num /]";
+ case KeyEvent.VK_DELETE -> "\u2326";
+ case KeyEvent.VK_INSERT -> "Ins";
+ case KeyEvent.VK_BACK_QUOTE -> "`";
+ case KeyEvent.VK_QUOTE -> "'";
+ case KeyEvent.VK_AMPERSAND -> "&";
+ case KeyEvent.VK_ASTERISK -> "*";
+ case KeyEvent.VK_QUOTEDBL -> "\"";
+ case KeyEvent.VK_LESS -> "<";
+ case KeyEvent.VK_GREATER -> ">";
+ case KeyEvent.VK_BRACELEFT -> "{";
+ case KeyEvent.VK_BRACERIGHT -> "}";
+ case KeyEvent.VK_COLON -> ":";
+ case KeyEvent.VK_CIRCUMFLEX -> "^";
+ case KeyEvent.VK_DEAD_TILDE -> "~";
+ case KeyEvent.VK_DOLLAR -> "$";
+ case KeyEvent.VK_EXCLAMATION_MARK -> "!";
+ case KeyEvent.VK_LEFT_PARENTHESIS -> "(";
+ case KeyEvent.VK_MINUS -> "-";
+ case KeyEvent.VK_PLUS -> "+";
+ case KeyEvent.VK_RIGHT_PARENTHESIS -> ")";
+ case KeyEvent.VK_UNDERSCORE -> "_";
+ default -> KeyEvent.getKeyText(keyCode);
+ };
+ }
+
+ /**
+ * The LAF's secondary color, as a plain Color: FlatLaf ignores or resets
+ * foregrounds that are UIResources
+ */
+ static Color secondaryColor() {
+ try {
+ final Color c = UIManager.getColor("SearchField.searchIconColor");
+ return (c != null) ? new Color(c.getRGB(), true) : getDisabledComponentColor();
+ } catch (final Exception ignored) {
+ return getDisabledComponentColor();
+ }
+ }
+
+ static Color accentColor() {
+ try {
+ return UIManager.getColor("Component.accentColor");
+ } catch (final Exception ignored) {
+ return Color.ORANGE.darker();
+ }
+ }
+
+ static boolean isDarkLaF() {
+ return FlatLaf.isLafDark() || isDark(new JLabel().getBackground());
+ }
+
+ static boolean isDark(final Color c) {
+ // see https://stackoverflow.com/a/3943023
+ 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());
+ return b;
+ }
+
+ static JButton ellipsisButton(final Runnable action) {
+ final JButton b = new JButton("\u22ee");
+ b.setFont(b.getFont().deriveFont(Font.BOLD));
+ b.setFocusable(false);
+ b.putClientProperty(FlatClientProperties.BUTTON_TYPE, FlatClientProperties.BUTTON_TYPE_TOOLBAR_BUTTON);
+ b.addActionListener(e -> action.run());
+ return b;
+ }
+
+
+ /** Rounded scrollbar thumbs without arrow buttons (FlatLaf only) */
+ static void flattenScrollBars(final JScrollPane scrollPane) {
+ final String style = "showButtons: false; trackArc: 999; thumbArc: 999; "
+ + "trackInsets: 2,2,2,2; thumbInsets: 2,2,2,2";
+ scrollPane.getVerticalScrollBar().putClientProperty(FlatClientProperties.STYLE, style);
+ scrollPane.getHorizontalScrollBar().putClientProperty(FlatClientProperties.STYLE, style);
+ }
+
+ /**
+ * Removes the divider of a vertical (top/bottom) split pane and lets {@code handle} act as
+ * the divider instead. {@code handle} must sit at the top edge of the lower component, e.g.,
+ * a header label or a toolbar. Dragging any part of it that does not handle mouse events
+ * itself (labels, glue, gaps) moves the split. If the split pane is later switched to a
+ * horizontal (left/right) orientation, its regular divider is restored.
+ */
+ static void installSplitHandle(final JComponent handle, final JSplitPane split) {
+ split.setContinuousLayout(true);
+ split.setOneTouchExpandable(false);
+ split.putClientProperty(FlatClientProperties.STYLE, "style: plain;");
+ if (handle == null) return;
+ final int regularSize = split.getDividerSize();
+ final Runnable update = () -> {
+ final boolean active = split.getOrientation() == JSplitPane.VERTICAL_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);
+ update.run();
+ split.addPropertyChangeListener(JSplitPane.ORIENTATION_PROPERTY, evt -> update.run());
+ final int[] grab = new int[1];
+ handle.addMouseListener(new java.awt.event.MouseAdapter() {
+
+ @Override
+ public void mousePressed(final java.awt.event.MouseEvent e) {
+ grab[0] = e.getY();
+ }
+ });
+ handle.addMouseMotionListener(new java.awt.event.MouseAdapter() {
+
+ @Override
+ public void mouseDragged(final java.awt.event.MouseEvent e) {
+ if (split.getOrientation() != JSplitPane.VERTICAL_SPLIT) return;
+ final int y = SwingUtilities.convertPoint(handle, e.getPoint(), split).y;
+ split.setDividerLocation(Math.max(0, y - grab[0]));
+ }
+ });
+ }
+
+ static void collapseAllTreeNodes(final JTree tree) {
+ final int row1 = (tree.isRootVisible()) ? 1 : 0;
+ for (int i = row1; i < tree.getRowCount(); i++)
+ tree.collapseRow(i);
+ }
+
+ static void expandAllTreeNodes(final JTree tree) {
+ for (int i = 0; i < tree.getRowCount(); i++)
+ tree.expandRow(i);
+ }
+
+ /* Tweaks for tabbed pane */
+ static JTabbedPane getJTabbedPane() {
+ final JTabbedPane tabbed = new JTabbedPane();
+ tabbed.putClientProperty(FlatClientProperties.TABBED_PANE_TAB_ROTATION,
+ FlatClientProperties.TABBED_PANE_TAB_ROTATION_AUTO);
+ final JPopupMenu popup = new JPopupMenu();
+ tabbed.setComponentPopupMenu(popup);
+ GuiUtils.addPopupMenuSeparator(popup, "Tab Style:");
+ ButtonGroup bGroup = new ButtonGroup();
+ for (final String option : new String[]{"Card", "Underlined"}) {
+ final JCheckBoxMenuItem jcbmi = new JCheckBoxMenuItem(option, "Underlined".equals(option));
+ jcbmi.addItemListener(e -> tabbed.putClientProperty(FlatClientProperties.TABBED_PANE_TAB_TYPE,
+ option.toLowerCase()));
+ bGroup.add(jcbmi);
+ popup.add(jcbmi);
+ }
+ GuiUtils.addPopupMenuSeparator(popup, "Tab Placement:");
+ bGroup = new ButtonGroup();
+ for (final String pos : new String[] { "Top", "Left", "Bottom", "Right" }) {
+ final JMenuItem jcbmi = new JCheckBoxMenuItem(pos, "Top".equals(pos));
+ jcbmi.addItemListener(e -> {
+ switch (pos) {
+ case "Top":
+ tabbed.setTabPlacement(JTabbedPane.TOP);
+ break;
+ case "Bottom":
+ tabbed.setTabPlacement(JTabbedPane.BOTTOM);
+ break;
+ case "Left":
+ tabbed.setTabPlacement(JTabbedPane.LEFT);
+ break;
+ case "Right":
+ tabbed.setTabPlacement(JTabbedPane.RIGHT);
+ break;
+ }
+ });
+ bGroup.add(jcbmi);
+ popup.add(jcbmi);
+ }
+ return tabbed;
+ }
+
+ /** Returns the color with the given opacity (0-100) */
+ static Color alpha(final Color c, final int percent) {
+ return new Color(c.getRed(), c.getGreen(), c.getBlue(), Math.round(percent / 100f * 255));
+ }
+
+ /** Returns a color that is weight of a plus (1 - weight) of b */
+ static Color mix(final Color a, final Color b, final double weight) {
+ final double w = Math.clamp(weight, 0d, 1d);
+ return new Color((int) Math.round(a.getRed() * w + b.getRed() * (1 - w)),
+ (int) Math.round(a.getGreen() * w + b.getGreen() * (1 - w)),
+ (int) Math.round(a.getBlue() * w + b.getBlue() * (1 - w)));
+ }
+
+ /** Paints the scroll bar tracks and corner of the scroll pane with the given color */
+ static void recolorTracks(final JScrollPane scrollPane, final Color color) {
+ Component corner = scrollPane.getCorner(JScrollPane.LOWER_TRAILING_CORNER);
+ if (corner == null) {
+ corner = new JPanel();
+ scrollPane.setCorner(JScrollPane.LOWER_TRAILING_CORNER, corner);
+ }
+ corner.setBackground(color);
+ final Map style = Map.of("track", color, "hoverTrackColor", color);
+ scrollPane.getHorizontalScrollBar().putClientProperty(FlatClientProperties.STYLE, style);
+ scrollPane.getVerticalScrollBar().putClientProperty(FlatClientProperties.STYLE, style);
+ }
+
+ /** Makes the window containing the component draggable by it */
+ static void enableDrag(final JComponent component) {
+ final Point[] dragStart = { null };
+ component.addMouseListener(new MouseAdapter() {
+ @Override
+ public void mousePressed(final MouseEvent e) {
+ dragStart[0] = e.getPoint();
+ }
+
+ @Override
+ public void mouseReleased(final MouseEvent e) {
+ dragStart[0] = null;
+ }
+ });
+ component.addMouseMotionListener(new MouseMotionAdapter() {
+ @Override
+ public void mouseDragged(final MouseEvent e) {
+ if (dragStart[0] != null) {
+ final java.awt.Window w = SwingUtilities.getWindowAncestor(component);
+ if (w == null)
+ return;
+ final Point loc = w.getLocation();
+ w.setLocation(loc.x + e.getX() - dragStart[0].x, loc.y + e.getY() - dragStart[0].y);
+ }
+ }
+ });
+ }
+}
diff --git a/src/main/java/org/scijava/ui/swing/script/GutterUtils.java b/src/main/java/org/scijava/ui/swing/script/GutterUtils.java
index 7e684a1e..5e640a20 100644
--- a/src/main/java/org/scijava/ui/swing/script/GutterUtils.java
+++ b/src/main/java/org/scijava/ui/swing/script/GutterUtils.java
@@ -28,17 +28,12 @@
*/
package org.scijava.ui.swing.script;
-import java.awt.Color;
-import java.awt.Component;
-import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
-import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.text.BadLocationException;
-import org.fife.ui.rtextarea.FoldIndicator;
import org.fife.ui.rtextarea.Gutter;
import org.fife.ui.rtextarea.GutterIconInfo;
@@ -53,22 +48,6 @@ public class GutterUtils {
gutter.setShowCollapsedRegionToolTips(true);
}
- @SuppressWarnings("unused")
- private void updateFoldIcons() { // no longer needed since v3.3.0
- int size;
- try {
- size = (int) new FoldIndicator(null).getPreferredSize().getWidth();
- } catch (final Exception | Error ignored) {
- size = 12; // FoldIndicator#WIDTH
- }
- if (size < 8)
- size = 8; // the default foldicon size in FoldIndicator
- final int fontSize = gutter.getLineNumberFont().getSize();
- if (size > fontSize)
- size = fontSize;
- //gutter.setFoldIcons(new FoldIcon(true, size), new FoldIcon(false, size));
- }
-
private ImageIcon getBookmarkIcon() {
final int size = gutter.getLineNumberFont().getSize();
final BufferedImage image = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB);
@@ -97,50 +76,6 @@ private void updateBookmarkIcon() {
public static void updateIcons(final Gutter gutter) {
final GutterUtils utils = new GutterUtils(gutter);
- //utils.updateFoldIcons();
utils.updateBookmarkIcon();
}
-
- @SuppressWarnings("unused")
- private class FoldIcon implements Icon {
-
- private final boolean collapsed;
- private final Color background;
- private final Color foreground;
- private final int size;
-
- FoldIcon(final boolean collapsed, final int size) {
- this.collapsed = collapsed;
- this.background = gutter.getBorderColor();
- this.foreground = gutter.getActiveLineRangeColor();
- this.size = size;
- }
-
- @Override
- public int getIconHeight() {
- return size;
- }
-
- @Override
- public int getIconWidth() {
- return size;
- }
-
- @Override
- public void paintIcon(final Component c, final Graphics g, final int x, final int y) {
- // the default '+'/'-' symbols are to small with scaled fonts, and we don't
- // have an easy way to resize the space allocated for the icon in the gutter
- if (collapsed) {
- g.setColor(foreground);
- g.fillRect(x, y, size, size);
- g.setColor(background);
- g.drawRect(x, y, size-2, size-1); // no idea why the extra pixel is needed
- } else {
- g.setColor(background);
- g.fillRect(x, y, size, size);
- g.setColor(foreground);
- g.drawRect(x, y, size-2, size-1);
- }
- }
- }
}
diff --git a/src/main/java/org/scijava/ui/swing/script/Icons.java b/src/main/java/org/scijava/ui/swing/script/Icons.java
new file mode 100644
index 00000000..fd7814f9
--- /dev/null
+++ b/src/main/java/org/scijava/ui/swing/script/Icons.java
@@ -0,0 +1,345 @@
+/*
+ * #%L
+ * Script Editor and Interpreter for SciJava script languages.
+ * %%
+ * Copyright (C) 2009 - 2026 SciJava developers.
+ * %%
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ * #L%
+ */
+
+package org.scijava.ui.swing.script;
+
+import com.formdev.flatlaf.FlatLaf;
+import com.formdev.flatlaf.icons.FlatAbstractIcon;
+import com.formdev.flatlaf.ui.FlatUIUtils;
+import com.formdev.flatlaf.util.UIScale;
+
+import javax.swing.*;
+import java.awt.*;
+import java.awt.geom.Ellipse2D;
+import java.awt.geom.Line2D;
+import java.awt.geom.Path2D;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * Factory of the hand-made icons of the script editor. Glyph icons are
+ * painted from SVG path data of Font Awesome Free (...),
+ * licensed CC BY 4.0. Remaining icons are painted with the foreground of the
+ * component they are assigned to.
+ */
+final class Icons {
+
+ private static final Color GREEN = new Color(0x629B70), GREEN_DARK = new Color(0x44774E);
+ private static final Color RED = new Color(0xD46D71), RED_DARK = new Color(0xDF5663);
+
+ private Icons() {
+ }
+
+ /**
+ * Green "play" triangle
+ */
+ static Icon play(final boolean disabled) {
+ return new GlyphIcon(
+ "M187.2 100.9C174.8 94.1 159.8 94.4 147.6 101.6C135.4 108.8 128 121.9 128 136L128 504C128 518.1 135.5 531.2 147.6 538.4C159.7 545.6 174.8 545.9 187.2 539.1L523.2 355.1C536 348.1 544 334.6 544 320C544 305.4 536 291.9 523.2 284.9L187.2 100.9z",
+ GREEN, GREEN_DARK, disabled);
+ }
+
+ /**
+ * Green "fast-forward" (double play) icon, for batch runs
+ */
+ static Icon fastForward(final boolean disabled) {
+ return new GlyphIcon(
+ "M403.7 107.1C392.1 96 375 92.9 360.3 99.2C345.6 105.5 336 120 336 136L336 272.3L163.7 107.2C152.1 96 135 92.9 120.3 99.2C105.6 105.5 96 120 96 136L96 504C96 520 105.6 534.5 120.3 540.8C135 547.1 152.1 544 163.7 532.9L336 367.7L336 504C336 520 345.6 534.5 360.3 540.8C375 547.1 392.1 544 403.7 532.9L595.7 348.9C603.6 341.4 608 330.9 608 320C608 309.1 603.5 298.7 595.7 291.1L403.7 107.1z",
+ GREEN, GREEN_DARK, disabled);
+ }
+
+ /**
+ * Red "stop" rounded square
+ */
+ static Icon stop(final boolean disabled) {
+ return new GlyphIcon(
+ "M160 96L480 96C515.3 96 544 124.7 544 160L544 480C544 515.3 515.3 544 480 544L160 544C124.7 544 96 515.3 96 480L96 160C96 124.7 124.7 96 160 96z",
+ RED, RED_DARK, disabled);
+ }
+
+ /**
+ * Neutral "trash can" icon, for the Clear button
+ */
+ 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);
+ }
+
+ /**
+ * Light bulb icon.
+ *
+ * @param height the height in unscaled pixels
+ */
+ static Icon bulb(final int height) {
+ final Color c = GuiUtils.secondaryColor();
+ return new GlyphIcon(
+ "M424.5 355.1C449 329.2 464 294.4 464 256C464 176.5 399.5 112 320 112"
+ + "C240.5 112 176 176.5 176 256C176 294.4 191 329.2 215.5 355.1C236.8 377.5 260.4 409.1 268.8 448"
+ + "L371.2 448C379.6 409 403.2 377.5 424.5 355.1z"
+ + "M459.3 388.1C435.7 413 416 443.4 416 477.7L416 496C416 540.2 380.2 576 336 576L304 576"
+ + "C259.8 576 224 540.2 224 496L224 477.7C224 443.4 204.3 413 180.7 388.1C148 353.7 128 307.2 128 256"
+ + "C128 150 214 64 320 64C426 64 512 150 512 256C512 307.2 492 353.7 459.3 388.1z"
+ + "M272 248C272 261.3 261.3 272 248 272C234.7 272 224 261.3 224 248C224 199.4 263.4 160 312 160"
+ + "C325.3 160 336 170.7 336 184C336 197.3 325.3 208 312 208C289.9 208 272 225.9 272 248z",
+ c, c, false, 128, 64, 384, 512, height);
+ }
+
+ /**
+ * REPL icon: a prompt (>_) inside a window
+ */
+ static Icon repl() {
+ return new WindowIcon() {
+ @Override
+ void paintContent(final Graphics2D g, final boolean selected) {
+ g.drawLine(4, 5, 6, 7); // chevron
+ g.drawLine(6, 7, 4, 9);
+ g.drawLine(8, 10, 11, 10); // cursor
+ }
+ };
+ }
+
+ /**
+ * Window with a pane on its right side, filled when the button is selected
+ */
+ static Icon rightPane() {
+ return new WindowIcon() {
+ @Override
+ void paintContent(final Graphics2D g, final boolean selected) {
+ if (selected) g.fillRect(10, 3, 4, 10);
+ else g.drawLine(9, 3, 9, 12);
+ }
+ };
+ }
+
+ /**
+ * Window with a pane below, filled when the button is selected
+ */
+ static Icon bottomPane() {
+ return new WindowIcon() {
+ @Override
+ void paintContent(final Graphics2D g, final boolean selected) {
+ if (selected) g.fillRect(2, 9, 12, 4);
+ else g.drawLine(2, 8, 13, 8);
+ }
+ };
+ }
+
+ /**
+ * Window with a left pane, filled when the button is selected
+ */
+ static Icon sidebar() {
+ return new WindowIcon() {
+ @Override
+ void paintContent(final Graphics2D g, final boolean selected) {
+ if (selected) g.fillRect(2, 3, 4, 10);
+ else g.drawLine(6, 3, 6, 12);
+ }
+ };
+ }
+
+ /**
+ * Chevron pointing right (collapsed) or down (expanded)
+ */
+ static Icon chevron(final boolean down) {
+ return new ChevronIcon(down);
+ }
+
+ /**
+ * Magnifier icon
+ */
+ static Icon magnifier() {
+ return new MagnifierIcon();
+ }
+
+ /**
+ * Icon painted from SVG path data (absolute M, L, C and Z commands)
+ */
+ private static class GlyphIcon extends FlatAbstractIcon {
+
+ private final Path2D path;
+ private final boolean disabled;
+ private final Color light, dark;
+
+ /**
+ * Square 16 pixel icon from a 640x640 view box
+ */
+ GlyphIcon(final String svgPath, final Color light, final Color dark, final boolean disabled) {
+ this(svgPath, light, dark, disabled, 0, 0, 640, 640, 16);
+ }
+
+ /**
+ * Icon of the given height showing the (x, y, w, h) region of the view box
+ */
+ GlyphIcon(final String svgPath, final Color light, final Color dark, final boolean disabled,
+ final double x, final double y, final double w, final double h, final int height) {
+ super((int) Math.round(height * w / h), height, null);
+ this.path = parse(svgPath, height / h, x, y);
+ this.light = light;
+ this.dark = dark;
+ this.disabled = disabled;
+ }
+
+ @Override
+ protected void paintIcon(final Component c, final Graphics2D g) {
+ Color color = FlatLaf.isLafDark() ? dark : light;
+ if (disabled) {
+ final Color d = UIManager.getColor("Button.disabledText");
+ color = (d != null) ? d : Color.GRAY;
+ }
+ g.setColor(color);
+ g.fill(path);
+ }
+
+ private static Path2D parse(final String d, final double k, final double x0, final double y0) {
+ final Matcher m = Pattern.compile("[MLCZz]|-?\\d*\\.?\\d+").matcher(d);
+ final List tokens = new ArrayList<>();
+ while (m.find())
+ tokens.add(m.group());
+ final Path2D.Double p = new Path2D.Double();
+ char cmd = 'M';
+ int i = 0;
+ while (i < tokens.size()) {
+ final String t = tokens.get(i);
+ if (Character.isLetter(t.charAt(0))) {
+ cmd = t.charAt(0);
+ i++;
+ if (cmd == 'Z' || cmd == 'z') {
+ p.closePath();
+ continue;
+ }
+ }
+ final double[] v = new double[cmd == 'C' ? 6 : 2];
+ for (int j = 0; j < v.length; j++)
+ v[j] = k * (Double.parseDouble(tokens.get(i + j)) - ((j % 2 == 0) ? x0 : y0));
+ i += v.length;
+ switch (cmd) {
+ case 'M' -> {
+ p.moveTo(v[0], v[1]);
+ cmd = 'L'; // further pairs are line segments
+ }
+ case 'L' -> p.lineTo(v[0], v[1]);
+ case 'C' -> p.curveTo(v[0], v[1], v[2], v[3], v[4], v[5]);
+ default -> throw new IllegalArgumentException("Unsupported path command: " + cmd);
+ }
+ }
+ return p;
+ }
+ }
+
+ /**
+ * Rounded window outline (16x16), painted with the foreground of its component
+ */
+ private abstract static class WindowIcon extends FlatAbstractIcon {
+
+ WindowIcon() {
+ super(16, 16, null);
+ }
+
+ /**
+ * Paints the inner details. The component being selected means "pane shown"
+ */
+ abstract void paintContent(Graphics2D g, boolean selected);
+
+ @Override
+ protected void paintIcon(final Component c, final Graphics2D g) {
+ g.setColor(c.getForeground());
+ g.drawRoundRect(1, 2, 13, 11, 3, 3);
+ paintContent(g, c instanceof AbstractButton b && b.isSelected());
+ }
+ }
+
+ private record ChevronIcon(boolean down) implements Icon {
+
+ @Override
+ public int getIconWidth() {
+ return UIScale.scale(10);
+ }
+
+ @Override
+ public int getIconHeight() {
+ return UIScale.scale(10);
+ }
+
+ @Override
+ public void paintIcon(final Component c, final Graphics g, final int x, final int y) {
+ final Graphics2D g2 = (Graphics2D) g.create();
+ try {
+ FlatUIUtils.setRenderingHints(g2);
+ g2.setColor(c.getForeground());
+ g2.setStroke(new BasicStroke(UIScale.scale(1.3f), BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
+ final float s = getIconWidth();
+ final float a = s * .3f; // inset
+ final Path2D.Float p = new Path2D.Float();
+ if (down) {
+ p.moveTo(x + a * .5f, y + s * .35f);
+ p.lineTo(x + s / 2, y + s * .65f);
+ p.lineTo(x + s - a * .5f, y + s * .35f);
+ } else {
+ p.moveTo(x + s * .35f, y + a * .5f);
+ p.lineTo(x + s * .65f, y + s / 2);
+ p.lineTo(x + s * .35f, y + s - a * .5f);
+ }
+ FlatUIUtils.drawShapePure(g2, p);
+ } finally {
+ g2.dispose();
+ }
+ }
+ }
+
+ private static final class MagnifierIcon implements Icon {
+
+ @Override
+ public void paintIcon(final Component c, final Graphics g, final int x, final int y) {
+ final Graphics2D g2 = (Graphics2D) g.create();
+ try {
+ FlatUIUtils.setRenderingHints(g2);
+ g2.setColor(c.getForeground());
+ g2.setStroke(new BasicStroke(UIScale.scale(1.6f), BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
+ final float s = getIconWidth();
+ FlatUIUtils.drawShapePure(g2, new Ellipse2D.Float(x + .1f * s, y + .1f * s, .6f * s, .6f * s));
+ FlatUIUtils.drawShapePure(g2, new Line2D.Float(x + .62f * s, y + .62f * s, x + .88f * s, y + .88f * s));
+ } finally {
+ g2.dispose();
+ }
+ }
+
+ @Override
+ public int getIconWidth() {
+ return UIScale.scale(16);
+ }
+
+ @Override
+ public int getIconHeight() {
+ return UIScale.scale(16);
+ }
+ }
+}
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 83b57cc5..476da3e0 100644
--- a/src/main/java/org/scijava/ui/swing/script/NotesPanel.java
+++ b/src/main/java/org/scijava/ui/swing/script/NotesPanel.java
@@ -99,7 +99,7 @@ class NotesPanel extends JPanel {
scratch.setBorder(new EmptyBorder(4, 4, 4, 4));
scratch.setToolTipText("Scratchpad: free text, saved between sessions");
final JScrollPane scratchPane = new JScrollPane(scratch);
- TextEditor.GuiUtils.flattenScrollBars(scratchPane);
+ GuiUtils.flattenScrollBars(scratchPane);
// Scratchpad
final JPanel pane1 = new JPanel(new BorderLayout());
@@ -111,7 +111,7 @@ class NotesPanel extends JPanel {
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setCellRenderer(new Renderer());
final JScrollPane listPane = new JScrollPane(list);
- TextEditor.GuiUtils.flattenScrollBars(listPane);
+ GuiUtils.flattenScrollBars(listPane);
final JPanel pane2 = new JPanel(new BorderLayout());
final JLabel clipboardHeader = header("Clipboard History (Double-click to Insert)");
pane2.add(clipboardHeader, BorderLayout.NORTH);
@@ -120,7 +120,7 @@ class NotesPanel extends JPanel {
final JSplitPane split = new JSplitPane(JSplitPane.VERTICAL_SPLIT, pane1, pane2);
split.setResizeWeight(.75);
// No divider: the Scratchpad header (with a hairline on top) is the drag handle
- TextEditor.GuiUtils.installSplitHandle(clipboardHeader, split);
+ GuiUtils.installSplitHandle(clipboardHeader, split);
add(split, BorderLayout.CENTER);
// List interaction
@@ -220,7 +220,7 @@ 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(TextEditor.GuiUtils.secondaryColor());
+ label.setForeground(GuiUtils.secondaryColor());
return label;
}
diff --git a/src/main/java/org/scijava/ui/swing/script/OutlineTreePanel.java b/src/main/java/org/scijava/ui/swing/script/OutlineTreePanel.java
index dcb9889f..8da663c0 100644
--- a/src/main/java/org/scijava/ui/swing/script/OutlineTreePanel.java
+++ b/src/main/java/org/scijava/ui/swing/script/OutlineTreePanel.java
@@ -71,7 +71,7 @@ class OutlineTreePanel extends JScrollPane {
super();
fontSize = getFont().getSize();
setViewportView(new UnsupportedLangTree());
- placeholdColor = TextEditor.GuiUtils.getDisabledComponentColor();
+ placeholdColor = GuiUtils.getDisabledComponentColor();
}
protected void rebuildSourceTree(final EditorPane pane) {
@@ -115,10 +115,10 @@ private void setPopupMenu(final JTree tree, final EditorPane pane) {
JMenuItem jmi;
if (tree instanceof AbstractSourceTree) {
jmi = new JMenuItem("Collapse All");
- jmi.addActionListener(e -> TextEditor.GuiUtils.collapseAllTreeNodes(tree));
+ jmi.addActionListener(e -> GuiUtils.collapseAllTreeNodes(tree));
popup.add(jmi);
jmi = new JMenuItem("Expand All");
- jmi.addActionListener(e -> TextEditor.GuiUtils.expandAllTreeNodes(tree));
+ jmi.addActionListener(e -> GuiUtils.expandAllTreeNodes(tree));
popup.add(jmi);
popup.addSeparator();
final JCheckBoxMenuItem jcmi1 = new JCheckBoxMenuItem("Hide 'Minor' Elements", major);
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 eeedf7e4..6fe16b30 100644
--- a/src/main/java/org/scijava/ui/swing/script/TextEditor.java
+++ b/src/main/java/org/scijava/ui/swing/script/TextEditor.java
@@ -68,7 +68,6 @@
import java.io.StringReader;
import java.io.Writer;
import java.net.URL;
-import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
@@ -154,12 +153,10 @@
import org.scijava.util.FileUtils;
import org.scijava.util.MiscUtils;
import org.scijava.util.POM;
-import org.scijava.util.PlatformUtils;
import org.scijava.util.Types;
import org.scijava.widget.FileWidget;
import com.formdev.flatlaf.FlatClientProperties;
-import com.formdev.flatlaf.FlatLaf;
/**
* A versatile script editor for SciJava applications.
@@ -348,7 +345,7 @@ public TextEditor(final Context context) {
outlineSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT, pane1, pane2);
outlineSplit.setResizeWeight(.75);
// No divider: the Scratchpad header (with a hairline on top) is the drag handle
- TextEditor.GuiUtils.installSplitHandle(bookmarkHeader, outlineSplit);
+ GuiUtils.installSplitHandle(bookmarkHeader, outlineSplit);
sideTabs.addTab("Outline", outlineSplit);
notesPanel = new NotesPanel(() -> {
@@ -894,7 +891,7 @@ 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(TextEditor.GuiUtils.secondaryColor());
+ label.setForeground(GuiUtils.secondaryColor());
return label;
}
@@ -1915,7 +1912,7 @@ public Dimension getPreferredSize() { // fixed width: neighbors do not move as t
menu.show(statusTab, 0, -menu.getPreferredSize().height); // opens upwards: the bar is at the bottom
});
filesPanel.setStatusListener(t -> statusText.setText(t == null || t.isEmpty() ? " " : t));
- statusSide = new JToggleButton(new SidebarIcon());
+ statusSide = new JToggleButton(Icons.sidebar());
statusSide.setToolTipText("Shows/hides the side panel (Files, Outline, Notes)");
statusSide.setFocusable(false);
statusSide.setSelected(true);
@@ -1932,9 +1929,9 @@ public Dimension getPreferredSize() { // fixed width: neighbors do not move as t
statusSide.setSelected(loc > 5);
});
// Layout of the console: below or beside the editor. Clicking the active one collapses/restores it
- statusBelow = new JToggleButton(new BottomPaneIcon());
+ statusBelow = new JToggleButton(Icons.bottomPane());
statusBelow.setToolTipText("Vertical Layout: Console below the editor.
Click again to hide/show it");
- statusRight = new JToggleButton(new RightPaneIcon());
+ statusRight = new JToggleButton(Icons.rightPane());
statusRight.setToolTipText("Horizontal Layout: Console beside the editor.
Click again to hide/show it");
for (final JToggleButton b : new JToggleButton[] { statusBelow, statusRight }) {
b.setFocusable(false);
@@ -1948,7 +1945,7 @@ public Dimension getPreferredSize() { // fixed width: neighbors do not move as t
getTab().toggleLayout(false);
syncStatusBar();
});
- statusRepl = new JToggleButton("REPL", new ReplIcon());
+ statusRepl = new JToggleButton("REPL", Icons.repl());
cmdPalette.register(statusRepl, "Interpreter");
statusRepl.setFont(statusRepl.getFont().deriveFont(statusRepl.getFont().getSize2D() * .9f));
statusRepl.setToolTipText("Turns the REPL prompt on/off (of the active tab). Requires a language");
@@ -2089,119 +2086,6 @@ private void convertIndentation(final boolean toSpaces) {
}
}
- /** REPL icon: a prompt (>_) inside a window. Painted with the foreground of its button */
- static final class ReplIcon implements Icon {
-
- @Override
- public void paintIcon(final Component c, final Graphics g, final int x, final int y) {
- final Graphics2D g2 = (Graphics2D) g.create();
- try {
- g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
- g2.setColor(c.getForeground());
- g2.drawRoundRect(x + 1, y + 2, 13, 11, 3, 3);
- g2.drawLine(x + 4, y + 5, x + 6, y + 7); // chevron
- g2.drawLine(x + 6, y + 7, x + 4, y + 9);
- g2.drawLine(x + 8, y + 10, x + 11, y + 10); // cursor
- } finally {
- g2.dispose();
- }
- }
-
- @Override
- public int getIconWidth() {
- return 16;
- }
-
- @Override
- public int getIconHeight() {
- return 16;
- }
- }
-
- /** Right pane icon: a window with a pane on its right side, filled when the pane is shown */
- private static final class RightPaneIcon implements Icon {
-
- @Override
- public void paintIcon(final Component c, final Graphics g, final int x, final int y) {
- final Graphics2D g2 = (Graphics2D) g.create();
- try {
- g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
- g2.setColor(c.getForeground());
- g2.drawRoundRect(x + 1, y + 2, 13, 11, 3, 3);
- if (c instanceof AbstractButton && ((AbstractButton) c).isSelected()) g2.fillRect(x + 9, y + 3, 4, 10);
- else g2.drawLine(x + 9, y + 3, x + 9, y + 12);
- } finally {
- g2.dispose();
- }
- }
-
- @Override
- public int getIconWidth() {
- return 16;
- }
-
- @Override
- public int getIconHeight() {
- return 16;
- }
- }
-
- /** Bottom pane icon: a window with a pane below, filled when the pane is shown */
- private static final class BottomPaneIcon implements Icon {
-
- @Override
- public void paintIcon(final Component c, final Graphics g, final int x, final int y) {
- final Graphics2D g2 = (Graphics2D) g.create();
- try {
- g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
- g2.setColor(c.getForeground());
- g2.drawRoundRect(x + 1, y + 2, 13, 11, 3, 3);
- if (c instanceof AbstractButton && ((AbstractButton) c).isSelected()) g2.fillRect(x + 2, y + 8, 12, 4);
- else g2.drawLine(x + 2, y + 8, x + 13, y + 8);
- } finally {
- g2.dispose();
- }
- }
-
- @Override
- public int getIconWidth() {
- return 16;
- }
-
- @Override
- public int getIconHeight() {
- return 16;
- }
- }
-
- /** Side panel icon: a window with a left pane, filled when the pane is shown. Painted with the foreground of its button */
- private static final class SidebarIcon implements Icon {
-
- @Override
- public void paintIcon(final Component c, final Graphics g, final int x, final int y) {
- final Graphics2D g2 = (Graphics2D) g.create();
- try {
- g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
- g2.setColor(c.getForeground());
- g2.drawRoundRect(x + 1, y + 2, 13, 11, 3, 3);
- if (c instanceof AbstractButton && ((AbstractButton) c).isSelected()) g2.fillRect(x + 2, y + 3, 4, 10);
- else g2.drawLine(x + 6, y + 3, x + 6, y + 12);
- } finally {
- g2.dispose();
- }
- }
-
- @Override
- public int getIconWidth() {
- return 16;
- }
-
- @Override
- public int getIconHeight() {
- return 16;
- }
- }
-
private String languageLabel(final ScriptLanguage language) {
return language == null ? "None" : languageDisplayName(language);
}
@@ -4457,332 +4341,4 @@ else if (file.isDirectory())
}
return collection;
}
-
- protected static class GuiUtils {
-
- private GuiUtils() {
- }
-
- static void error(final Component parent, final String message) {
- JOptionPane.showMessageDialog(parent, message, "Error", JOptionPane.ERROR_MESSAGE);
- }
-
- static void warn(final Component parent, final String message) {
- JOptionPane.showMessageDialog(parent, message, "Warning", JOptionPane.WARNING_MESSAGE);
- }
-
- static void info(final Component parent, final String message, final String title) {
- JOptionPane.showMessageDialog(parent, message, title, JOptionPane.INFORMATION_MESSAGE);
- }
-
- static boolean confirm(final Component parent, final String message, final String title,
- final String yesButtonLabel) {
- return JOptionPane.showConfirmDialog(parent, message, title, JOptionPane.YES_NO_OPTION) ==
- JOptionPane.YES_OPTION;
- }
-
- static void showHTMLDialog(final Component parent, final String title, final String htmlContents) {
- final JTextPane f = new JTextPane();
- f.setContentType("text/html");
- f.setEditable(false);
- f.setBackground(null);
- f.setBorder(null);
- f.setText(htmlContents);
- f.setCaretPosition(0);
- final JScrollPane sp = new JScrollPane(f);
- final JOptionPane pane = new JOptionPane(sp);
- final JDialog dialog = pane.createDialog(parent, title);
- dialog.setResizable(true);
- dialog.pack();
- dialog.setPreferredSize(
- new Dimension(
- (int) Math.min(parent.getWidth() * .5, pane.getPreferredSize().getWidth() + (3 * sp.getVerticalScrollBar().getWidth())),
- (int) Math.min(parent.getHeight() * .8, pane.getPreferredSize().getHeight())));
- dialog.pack();
- pane.addPropertyChangeListener(JOptionPane.VALUE_PROPERTY, ignored -> {
- dialog.dispose();
- });
- dialog.setModal(false);
- dialog.setLocationRelativeTo(parent);
- dialog.setVisible(true);
- }
-
- static String getString(final Component parent, final String message, final String title) {
- return (String) JOptionPane.showInputDialog(parent, message, title, JOptionPane.QUESTION_MESSAGE);
- }
-
- static void runSearchQueryInBrowser(final Component parentComponent, final PlatformService platformService,
- final String query) {
- String url;
- try {
- url = "https://forum.image.sc/search?q=" + URLEncoder.encode(query, StandardCharsets.UTF_8.toString());
- } catch (final Exception ignored) {
- url = query.trim().replace(" ", "%20");
- }
- openURL(parentComponent, platformService, url);
- }
-
- static void openURL(final Component parentComponent, final PlatformService platformService, final String url) {
- try {
- platformService.open(new URL(url));
- } catch (final Exception ignored) {
- // Error message with selectable text
- final JTextPane f = new JTextPane();
- f.setContentType("text/html");
- f.setText("Web page could not be open. Please visit
" + url + "
using your web browser.");
- f.setEditable(false);
- f.setBackground(null);
- f.setBorder(null);
- JOptionPane.showMessageDialog(parentComponent, f, "Error", JOptionPane.ERROR_MESSAGE);
- }
- }
-
- static void openTerminal(final File pwd) throws IOException, InterruptedException {
- final String[] wrappedCommand;
- final File dir = (pwd.isDirectory()) ? pwd : pwd.getParentFile();
- if (PlatformUtils.isWindows()) {
- // this should probably be replaced with powershell!?
- wrappedCommand = new String[] { "cmd", "/c", "start", "/wait", "cmd.exe", "/K" };
- } else if (PlatformUtils.isLinux()) {
- // this will likely only work on debian-based distros
- wrappedCommand = new String[] { "/usr/bin/x-terminal-emulator" };
- } else if (PlatformUtils.isMac()) {
- // On MacOS ProcessBuilder#directory() fails!? so we'll use applescript :)
- wrappedCommand = new String[] { "osascript", "-e", //
- "tell application \"Terminal\" to (do script \"cd '" + dir.getAbsolutePath() + "';clear\")" };
- } else {
- throw new IllegalArgumentException("Unsupported OS");
- }
- final ProcessBuilder pb = new ProcessBuilder(wrappedCommand);
- pb.directory(dir); // does nothing on macOS !?
- pb.start();
- }
-
- static void addMenubarSeparator(final JMenu menu, final String header) {
- if (menu.getMenuComponentCount() > 0) {
- menu.addSeparator();
- }
- try {
- final JLabel label = new JLabel(" "+ header);
- label.setEnabled(false);
- label.setForeground(getDisabledComponentColor());
- menu.add(label);
- } catch (final Exception ignored) {
- // do nothing
- }
- }
-
- static void addPopupMenuSeparator(final JPopupMenu menu, final String header) {
- if (menu.getComponentCount() > 1) {
- menu.addSeparator();
- }
- final JLabel label = new JLabel(header);
- // label.setHorizontalAlignment(SwingConstants.LEFT);
- label.setEnabled(false);
- label.setForeground(getDisabledComponentColor());
- menu.add(label);
-
- }
-
- static Color getDisabledComponentColor() {
- try {
- return UIManager.getColor("MenuItem.disabledForeground");
- } catch (final Exception ignored) {
- return Color.GRAY;
- }
- }
-
- public static Color secondaryColor() {
- try {
- return UIManager.getColor("SearchField.searchIconColor");
- } catch (final Exception ignored) {
- return getDisabledComponentColor();
- }
- }
-
- public static Color accentColor() {
- try {
- return UIManager.getColor("Component.accentColor");
- } catch (final Exception ignored) {
- return Color.ORANGE.darker();
- }
- }
-
- static boolean isDarkLaF() {
- return FlatLaf.isLafDark() || isDark(new JLabel().getBackground());
- }
-
- static boolean isDark(final Color c) {
- // see https://stackoverflow.com/a/3943023
- 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());
- return b;
- }
-
- static JButton ellipsisButton(final Runnable action) {
- final JButton b = new JButton("⋮");
- b.setFont(b.getFont().deriveFont(Font.BOLD));
- b.setFocusable(false);
- b.putClientProperty(FlatClientProperties.BUTTON_TYPE, FlatClientProperties.BUTTON_TYPE_TOOLBAR_BUTTON);
- b.addActionListener(e -> action.run());
- return b;
- }
-
-
- /** Rounded scrollbar thumbs without arrow buttons (FlatLaf only) */
- static void flattenScrollBars(final JScrollPane scrollPane) {
- final String style = "showButtons: false; trackArc: 999; thumbArc: 999; "
- + "trackInsets: 2,2,2,2; thumbInsets: 2,2,2,2";
- scrollPane.getVerticalScrollBar().putClientProperty(FlatClientProperties.STYLE, style);
- scrollPane.getHorizontalScrollBar().putClientProperty(FlatClientProperties.STYLE, style);
- }
-
- /**
- * Removes the divider of a vertical (top/bottom) split pane and lets {@code handle} act as
- * the divider instead. {@code handle} must sit at the top edge of the lower component, e.g.,
- * a header label or a toolbar. Dragging any part of it that does not handle mouse events
- * itself (labels, glue, gaps) moves the split. If the split pane is later switched to a
- * horizontal (left/right) orientation, its regular divider is restored.
- */
- static void installSplitHandle(final JComponent handle, final JSplitPane split) {
- split.setContinuousLayout(true);
- split.setOneTouchExpandable(false);
- split.putClientProperty(FlatClientProperties.STYLE, "style: plain;");
- if (handle == null) return;
- final int regularSize = split.getDividerSize();
- final Runnable update = () -> {
- final boolean active = split.getOrientation() == JSplitPane.VERTICAL_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);
- update.run();
- split.addPropertyChangeListener(JSplitPane.ORIENTATION_PROPERTY, evt -> update.run());
- final int[] grab = new int[1];
- handle.addMouseListener(new java.awt.event.MouseAdapter() {
-
- @Override
- public void mousePressed(final java.awt.event.MouseEvent e) {
- grab[0] = e.getY();
- }
- });
- handle.addMouseMotionListener(new java.awt.event.MouseAdapter() {
-
- @Override
- public void mouseDragged(final java.awt.event.MouseEvent e) {
- if (split.getOrientation() != JSplitPane.VERTICAL_SPLIT) return;
- final int y = SwingUtilities.convertPoint(handle, e.getPoint(), split).y;
- split.setDividerLocation(Math.max(0, y - grab[0]));
- }
- });
- }
-
- static void collapseAllTreeNodes(final JTree tree) {
- final int row1 = (tree.isRootVisible()) ? 1 : 0;
- for (int i = row1; i < tree.getRowCount(); i++)
- tree.collapseRow(i);
- }
-
- static void expandAllTreeNodes(final JTree tree) {
- for (int i = 0; i < tree.getRowCount(); i++)
- tree.expandRow(i);
- }
-
- /* Tweaks for tabbed pane */
- static JTabbedPane getJTabbedPane() {
- final JTabbedPane tabbed = new JTabbedPane();
- tabbed.putClientProperty(FlatClientProperties.TABBED_PANE_TAB_ROTATION,
- FlatClientProperties.TABBED_PANE_TAB_ROTATION_AUTO);
- final JPopupMenu popup = new JPopupMenu();
- tabbed.setComponentPopupMenu(popup);
- GuiUtils.addPopupMenuSeparator(popup, "Tab Style:");
- ButtonGroup bGroup = new ButtonGroup();
- for (final String option : new String[]{"Card", "Underlined"}) {
- final JCheckBoxMenuItem jcbmi = new JCheckBoxMenuItem(option, "Underlined".equals(option));
- jcbmi.addItemListener(e -> tabbed.putClientProperty(FlatClientProperties.TABBED_PANE_TAB_TYPE,
- option.toLowerCase()));
- bGroup.add(jcbmi);
- popup.add(jcbmi);
- }
- GuiUtils.addPopupMenuSeparator(popup, "Tab Placement:");
- bGroup = new ButtonGroup();
- for (final String pos : new String[] { "Top", "Left", "Bottom", "Right" }) {
- final JMenuItem jcbmi = new JCheckBoxMenuItem(pos, "Top".equals(pos));
- jcbmi.addItemListener(e -> {
- switch (pos) {
- case "Top":
- tabbed.setTabPlacement(JTabbedPane.TOP);
- break;
- case "Bottom":
- tabbed.setTabPlacement(JTabbedPane.BOTTOM);
- break;
- case "Left":
- tabbed.setTabPlacement(JTabbedPane.LEFT);
- break;
- case "Right":
- tabbed.setTabPlacement(JTabbedPane.RIGHT);
- break;
- }
- });
- bGroup.add(jcbmi);
- popup.add(jcbmi);
- }
- return tabbed;
- }
- }
-
- /**
- * Text field displaying a hint while empty. Relies on FlatLaf's placeholder
- * support, falling back to manual painting under other look and feels.
- */
- static class TextFieldWithPlaceholder extends JTextField {
-
- private static final long serialVersionUID = 1L;
-
- TextFieldWithPlaceholder() {
- putClientProperty(FlatClientProperties.TEXT_FIELD_SHOW_CLEAR_BUTTON, true);
- }
-
- void setPlaceholder(final String placeholder) {
- putClientProperty(FlatClientProperties.PLACEHOLDER_TEXT, placeholder);
- repaint();
- }
-
- String getPlaceholder() {
- final Object p = getClientProperty(FlatClientProperties.PLACEHOLDER_TEXT);
- return (p == null) ? "" : p.toString();
- }
-
- @Override
- protected void paintComponent(final java.awt.Graphics g) {
- super.paintComponent(g);
- if (getText().isEmpty() && !(UIManager.getLookAndFeel() instanceof FlatLaf)) {
- final Graphics2D g2 = (Graphics2D) g.create();
- g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
- g2.setColor(getDisabledTextColor());
- g2.setFont(getFont().deriveFont(Font.ITALIC));
- g2.drawString(getPlaceholder(), getInsets().left,
- g2.getFontMetrics().getHeight() + getInsets().top - getInsets().bottom);
- g2.dispose();
- }
- }
-
- }
-
}
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 7acd7133..5fa3fc16 100644
--- a/src/main/java/org/scijava/ui/swing/script/TextEditorTab.java
+++ b/src/main/java/org/scijava/ui/swing/script/TextEditorTab.java
@@ -32,11 +32,8 @@
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
-import java.awt.Component;
import java.awt.Font;
import java.awt.Insets;
-import java.awt.Graphics2D;
-import java.awt.geom.Path2D;
import java.awt.geom.RoundRectangle2D;
import java.awt.FlowLayout;
import java.awt.datatransfer.DataFlavor;
@@ -49,6 +46,8 @@
import java.awt.dnd.DropTargetListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
+import java.awt.event.InputEvent;
+import java.awt.event.KeyEvent;
import java.io.File;
import java.util.List;
import javax.swing.*;
@@ -58,7 +57,6 @@
import javax.swing.text.JTextComponent;
import com.formdev.flatlaf.FlatClientProperties;
-import com.formdev.flatlaf.icons.FlatAbstractIcon;
import com.formdev.flatlaf.icons.FlatFileChooserDetailsViewIcon;
import com.formdev.flatlaf.icons.FlatHelpButtonIcon;
import org.fife.ui.rsyntaxtextarea.ErrorStrip;
@@ -187,23 +185,23 @@ public void dragEnter(final DropTargetDragEvent e) {
bar.setFloatable(false);
bar.setBorder(BorderFactory.createEmptyBorder(1, 2, 1, 2));
- runit = new JButton("Run", new PlayIcon(false));
- runit.setDisabledIcon(new PlayIcon(true));
+ runit = new JButton("Run", Icons.play(false));
+ runit.setDisabledIcon(Icons.play(true));
runit.setToolTipText("Control+R, F5, or F11");
textEditor.cmdPalette.register(runit, "Interpreter");
runit.addActionListener(ae -> textEditor.runText());
bar.add(runit);
- batchit = new JButton("Batch", new FastForwardIcon(false));
+ batchit = new JButton("Batch", Icons.fastForward(false));
batchit.putClientProperty("JButton.buttonType", "borderless");
- batchit.setDisabledIcon(new FastForwardIcon(true));
+ batchit.setDisabledIcon(Icons.fastForward(true));
batchit.setToolTipText("Requires at least one @File SciJava parameter to be declared");
batchit.addActionListener(e -> textEditor.runBatch());
bar.add(batchit);
- killit = new JButton("Stop", new StopIcon(false));
- killit.setDisabledIcon(new StopIcon(true));
+ killit = new JButton("Stop", Icons.stop(false));
+ killit.setDisabledIcon(Icons.stop(true));
killit.setToolTipText("Stop the running script (interrupts its thread)");
killit.setEnabled(false);
killit.addActionListener(ae -> kill());
@@ -224,8 +222,8 @@ public void dragEnter(final DropTargetDragEvent e) {
bar.add(viewPanel);
bar.add(Box.createHorizontalStrut(4));
- final JButton clear = new JButton("Clear", new TrashIcon(false));
- clear.setDisabledIcon(new TrashIcon(true));
+ final JButton clear = new JButton("Clear", Icons.trash(false));
+ clear.setDisabledIcon(Icons.trash(true));
clear.addActionListener(ae -> {
screen.setText("");
textEditor.getErrorScreen().setText("");
@@ -236,7 +234,7 @@ public void dragEnter(final DropTargetDragEvent e) {
textEditor.cmdPalette.register(clear, "Console");
scroll = new JScrollPane(screen);
- TextEditor.GuiUtils.flattenScrollBars(scroll);
+ GuiUtils.flattenScrollBars(scroll);
bottom.add(bar, BorderLayout.PAGE_START);
bottom.add(scroll, BorderLayout.CENTER);
@@ -257,11 +255,11 @@ public void dragEnter(final DropTargetDragEvent e) {
prompt_panel.add(promptBar, BorderLayout.PAGE_START);
// Same scroll pane (and thus border) as the console
final JScrollPane promptScroll = new JScrollPane(prompt);
- TextEditor.GuiUtils.flattenScrollBars(promptScroll);
+ GuiUtils.flattenScrollBars(promptScroll);
prompt_panel.add(promptScroll, BorderLayout.CENTER);
final JLabel label = new JLabel();
- label.setForeground(TextEditor.GuiUtils.secondaryColor());
- label.setIcon(new TextEditor.ReplIcon());
+ label.setForeground(GuiUtils.secondaryColor());
+ label.setIcon(Icons.repl());
promptBar.add(label);
promptBar.add(Box.createHorizontalGlue());
updownarrows.setText("Arrow Keys");
@@ -270,22 +268,28 @@ public void dragEnter(final DropTargetDragEvent e) {
promptBar.add(updownarrows);
final FlatHelpButtonIcon helpIcon = new FlatHelpButtonIcon();
helpIcon.setScale(.8f); // matches the font size set by the "small" style
- helpIcon.applyStyleProperty("questionMarkColor", TextEditor.GuiUtils.secondaryColor());
+ helpIcon.applyStyleProperty("questionMarkColor", GuiUtils.secondaryColor());
helpIcon.applyStyleProperty("background", promptBar.getBackground());
final JButton statusHelp = new JButton(helpIcon);
statusHelp.addActionListener(a -> {
- final String msg = "This REPL (Read-Evaluate-Print-Loop) parses " + textEditor.getCurrentLanguage().getLanguageName() + " code.\n\n"
- + "Key bindings:\n"
- + " [Enter]: Evaluate code\n"
- + " [Shift+Enter]: Add line break (also alt-enter and meta-enter)\n"
- + " [Page UP] or [Ctrl+P]: Show previous entry in the history\n"
- + " [Page DOWN] or [Ctrl+N]: Show next entry in the history\n"
- + "\n"
- + "If 'Use arrow keys' is checked, then up/down arrows work like\n"
- + "Page UP/DOWN, and Shift+up/down arrows work like arrow\n"
- + "keys before for caret movement within a multi-line prompt."
- ;
- textEditor.info(msg, "REPL Help");
+ final int shift = InputEvent.SHIFT_DOWN_MASK;
+ final int ctrl = InputEvent.CTRL_DOWN_MASK;
+ final String html = """
+
+
+ | %s | Evaluate code |
+ | %s | Add line break (also with Ctrl, Alt or Meta) |
+ | %s or %s | Previous entry in the history |
+ | %s or %s | Next entry in the history |
+
+ With Arrow Keys on, %s and %s also navigate the history. Combined
+ with a modifier (e.g., %s) they move the caret within a multi-line prompt.
+ """
+ .formatted(keyHtml(KeyEvent.VK_ENTER, 0), keyHtml(KeyEvent.VK_ENTER, shift),
+ keyHtml(KeyEvent.VK_PAGE_UP, 0), keyHtml(KeyEvent.VK_P, ctrl),
+ keyHtml(KeyEvent.VK_PAGE_DOWN, 0), keyHtml(KeyEvent.VK_N, ctrl),
+ keyHtml(KeyEvent.VK_UP, 0), keyHtml(KeyEvent.VK_DOWN, 0), keyHtml(KeyEvent.VK_UP, shift));
+ textEditor.showHTMLDialog("REPL (Read-Evaluate-Print-Loop)", html);
});
promptBar.add(statusHelp);
@@ -293,12 +297,12 @@ public void dragEnter(final DropTargetDragEvent e) {
// 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(TextEditor.GuiUtils.secondaryColor()); // Must come after the style properties: applying them resets UIResource foregrounds
+ 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);
// No divider: the prompt bar is the handle. Keep promptDividerSize at 0 so toggling the REPL
// never brings the divider back
- TextEditor.GuiUtils.installSplitHandle(promptBar, screenAndPromptSplit);
+ GuiUtils.installSplitHandle(promptBar, screenAndPromptSplit);
promptDividerSize = 0;
// Enable ErrorSrip à la Eclipse. This will keep track of lines with 'Mark All'
@@ -324,7 +328,7 @@ public void dragEnter(final DropTargetDragEvent e) {
editorPane.getVimHandler().setExHandler(textEditor::handleVimCommand);
super.setLeftComponent(holder);
super.setRightComponent(screenAndPromptSplit);
- TextEditor.GuiUtils.installSplitHandle(bar, this); // no divider in the "below" layout: the toolbar is the handle
+ GuiUtils.installSplitHandle(bar, this); // no divider in the "below" layout: the toolbar is the handle
screenAndPromptSplit.setDividerLocation(1.0);
setView(view); // sync the console and chooser with the initial view
@@ -390,118 +394,6 @@ void setBottomVisible(final boolean visible) {
}
}
- /**
- * Icon painted from SVG path data (absolute M, L, C and Z commands, 640x640 view box). Glyphs by
- * Font Awesome Free (https://fontawesome.com), licensed CC BY 4.0. Colors adapt to light/dark themes
- */
- private static class GlyphIcon extends FlatAbstractIcon {
-
- private final Path2D path;
- private final boolean disabled;
- private final Color light, dark;
-
- GlyphIcon(final String svgPath, final Color light, final Color dark, final boolean disabled) {
- super(16, 16, null);
- this.path = parse(svgPath);
- this.light = light;
- this.dark = dark;
- this.disabled = disabled;
- }
-
- @Override
- protected void paintIcon(final Component c, final Graphics2D g) {
- Color color = com.formdev.flatlaf.FlatLaf.isLafDark() ? dark : light;
- if (disabled) {
- final Color d = UIManager.getColor("Button.disabledText");
- color = (d != null) ? d : Color.GRAY;
- }
- g.setColor(color);
- g.fill(path);
- }
-
- /** Parses the path, scaling it from the 640 unit view box to the 16 unit icon */
- private static Path2D parse(final String d) {
- final double k = 16d / 640d;
- final java.util.regex.Matcher m = java.util.regex.Pattern.compile("[MLCZz]|-?\\d*\\.?\\d+").matcher(d);
- final List tokens = new java.util.ArrayList<>();
- while (m.find())
- tokens.add(m.group());
- final Path2D.Double p = new Path2D.Double();
- char cmd = 'M';
- int i = 0;
- while (i < tokens.size()) {
- final String t = tokens.get(i);
- if (Character.isLetter(t.charAt(0))) {
- cmd = t.charAt(0);
- i++;
- if (cmd == 'Z' || cmd == 'z') {
- p.closePath();
- continue;
- }
- }
- switch (cmd) {
- case 'M':
- p.moveTo(k * Double.parseDouble(tokens.get(i)), k * Double.parseDouble(tokens.get(i + 1)));
- i += 2;
- cmd = 'L'; // further pairs are line segments
- break;
- case 'L':
- p.lineTo(k * Double.parseDouble(tokens.get(i)), k * Double.parseDouble(tokens.get(i + 1)));
- i += 2;
- break;
- case 'C':
- p.curveTo(k * Double.parseDouble(tokens.get(i)), k * Double.parseDouble(tokens.get(i + 1)),
- k * Double.parseDouble(tokens.get(i + 2)), k * Double.parseDouble(tokens.get(i + 3)),
- k * Double.parseDouble(tokens.get(i + 4)), k * Double.parseDouble(tokens.get(i + 5)));
- i += 6;
- break;
- default:
- throw new IllegalArgumentException("Unsupported path command: " + cmd);
- }
- }
- return p;
- }
- }
-
- private static final Color GREEN = new Color(0x44774E), GREEN_DARK = new Color(0x446E4B);
- private static final Color RED = new Color(0xDF5663), RED_DARK = new Color(0xB45355);
-
- /** Green "play" triangle (Font Awesome) */
- private static final class PlayIcon extends GlyphIcon {
-
- PlayIcon(final boolean disabled) {
- super("M187.2 100.9C174.8 94.1 159.8 94.4 147.6 101.6C135.4 108.8 128 121.9 128 136L128 504C128 518.1 135.5 531.2 147.6 538.4C159.7 545.6 174.8 545.9 187.2 539.1L523.2 355.1C536 348.1 544 334.6 544 320C544 305.4 536 291.9 523.2 284.9L187.2 100.9z",
- GREEN_DARK, GREEN, disabled);
- }
- }
-
- /** Green "fast forward" (double play) icon (Font Awesome), for batch runs */
- private static final class FastForwardIcon extends GlyphIcon {
-
- FastForwardIcon(final boolean disabled) {
- super("M403.7 107.1C392.1 96 375 92.9 360.3 99.2C345.6 105.5 336 120 336 136L336 272.3L163.7 107.2C152.1 96 135 92.9 120.3 99.2C105.6 105.5 96 120 96 136L96 504C96 520 105.6 534.5 120.3 540.8C135 547.1 152.1 544 163.7 532.9L336 367.7L336 504C336 520 345.6 534.5 360.3 540.8C375 547.1 392.1 544 403.7 532.9L595.7 348.9C603.6 341.4 608 330.9 608 320C608 309.1 603.5 298.7 595.7 291.1L403.7 107.1z",
- GREEN, GREEN_DARK, disabled);
- }
- }
-
- /** Red "stop" rounded square (Font Awesome) */
- private static final class StopIcon extends GlyphIcon {
-
- StopIcon(final boolean disabled) {
- super("M160 96L480 96C515.3 96 544 124.7 544 160L544 480C544 515.3 515.3 544 480 544L160 544C124.7 544 96 515.3 96 480L96 160C96 124.7 124.7 96 160 96z",
- RED, RED_DARK, disabled);
- }
- }
-
- /** Neutral "trash can" icon (Font Awesome), for the Clear button */
- private static final class TrashIcon extends GlyphIcon {
-
- TrashIcon(final boolean disabled) {
- super("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);
- }
- }
-
// Package-private
JSplitPane getScreenAndPromptSplit() {
return screenAndPromptSplit;
@@ -637,6 +529,11 @@ void startNewRun() {
if (errors instanceof ConsoleArea) ((ConsoleArea) errors).startNewRun();
}
+ /** HTML for a key stroke, e.g., for help dialogs */
+ private static String keyHtml(final int keyCode, final int modifiers) {
+ return "" + GuiUtils.prettifiedKey(KeyStroke.getKeyStroke(keyCode, modifiers)).trim() + "";
+ }
+
/** Makes the consoles and REPL prompt use the editor pane's colors. */
void applyConsoleColors() {
// Note: themes set the text color via the syntax scheme, not the component foreground.
diff --git a/src/main/java/org/scijava/ui/swing/script/TextFieldWithPlaceholder.java b/src/main/java/org/scijava/ui/swing/script/TextFieldWithPlaceholder.java
new file mode 100644
index 00000000..68ec00ad
--- /dev/null
+++ b/src/main/java/org/scijava/ui/swing/script/TextFieldWithPlaceholder.java
@@ -0,0 +1,79 @@
+/*
+ * #%L
+ * Script Editor and Interpreter for SciJava script languages.
+ * %%
+ * Copyright (C) 2009 - 2026 SciJava developers.
+ * %%
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ * #L%
+ */
+
+package org.scijava.ui.swing.script;
+
+import java.awt.Font;
+import java.awt.Graphics;
+import java.awt.Graphics2D;
+import java.awt.RenderingHints;
+
+import javax.swing.JTextField;
+import javax.swing.UIManager;
+
+import com.formdev.flatlaf.FlatClientProperties;
+import com.formdev.flatlaf.FlatLaf;
+
+/**
+ * Text field displaying a hint while empty. Relies on FlatLaf's placeholder
+ * support, falling back to manual painting under other look and feels.
+ */
+class TextFieldWithPlaceholder extends JTextField {
+
+ private static final long serialVersionUID = 1L;
+
+ TextFieldWithPlaceholder() {
+ putClientProperty(FlatClientProperties.TEXT_FIELD_SHOW_CLEAR_BUTTON, true);
+ }
+
+ void setPlaceholder(final String placeholder) {
+ putClientProperty(FlatClientProperties.PLACEHOLDER_TEXT, placeholder);
+ repaint();
+ }
+
+ String getPlaceholder() {
+ final Object p = getClientProperty(FlatClientProperties.PLACEHOLDER_TEXT);
+ return (p == null) ? "" : p.toString();
+ }
+
+ @Override
+ protected void paintComponent(final Graphics g) {
+ super.paintComponent(g);
+ if (getText().isEmpty() && !(UIManager.getLookAndFeel() instanceof FlatLaf)) {
+ final Graphics2D g2 = (Graphics2D) g.create();
+ g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
+ g2.setColor(getDisabledTextColor());
+ g2.setFont(getFont().deriveFont(Font.ITALIC));
+ g2.drawString(getPlaceholder(), getInsets().left,
+ g2.getFontMetrics().getHeight() + getInsets().top - getInsets().bottom);
+ g2.dispose();
+ }
+ }
+
+}
From 9afe282b63422f4ce83a3d487ca0f7f0e684f8e5 Mon Sep 17 00:00:00 2001
From: Tiago Ferreira
Date: Sat, 14 Nov 2026 21:27:49 -0500
Subject: [PATCH 09/41] Organize menu entries. Adopt "Code" menu as used by
VSCode/IntelliJ
---
.../ui/swing/script/CommandPalette.java | 4 +-
.../scijava/ui/swing/script/EditorPane.java | 12 +-
.../ui/swing/script/EditorPaneActions.java | 1 -
.../ui/swing/script/FileSystemTreePanel.java | 4 +-
.../scijava/ui/swing/script/TextEditor.java | 152 ++++++++++++------
.../ui/swing/script/TextEditorTab.java | 7 +-
6 files changed, 115 insertions(+), 65 deletions(-)
diff --git a/src/main/java/org/scijava/ui/swing/script/CommandPalette.java b/src/main/java/org/scijava/ui/swing/script/CommandPalette.java
index 6d895eb9..cf897a25 100644
--- a/src/main/java/org/scijava/ui/swing/script/CommandPalette.java
+++ b/src/main/java/org/scijava/ui/swing/script/CommandPalette.java
@@ -145,7 +145,7 @@ public void windowClosed(final WindowEvent e) {
});
}
- void install(final JMenu toolsMenu) {
+ void install(final JMenu menu) {
final Action action = new AbstractAction(NAME) {
private static final long serialVersionUID = -7030359886427866104L;
@@ -157,7 +157,7 @@ public void actionPerformed(final ActionEvent e) {
};
action.putValue(Action.ACCELERATOR_KEY, ACCELERATOR);
- toolsMenu.add(new JMenuItem(action));
+ menu.add(new JMenuItem(action));
}
/** Menu bar button that toggles the palette, for the right end of the menu bar */
diff --git a/src/main/java/org/scijava/ui/swing/script/EditorPane.java b/src/main/java/org/scijava/ui/swing/script/EditorPane.java
index 75800c9b..846ebbdd 100644
--- a/src/main/java/org/scijava/ui/swing/script/EditorPane.java
+++ b/src/main/java/org/scijava/ui/swing/script/EditorPane.java
@@ -248,24 +248,24 @@ private void installCustomPopupMenu() {
// this is the only access point in the GUI for these
// see #createPopupMenu(); #appendFoldingMenu();
final JPopupMenu popup = new JPopupMenu();
- GuiUtils.addPopupMenuSeparator(popup, "Code Editing:");
+ GuiUtils.addPopupMenuSeparator(popup, "Edit:");
popup.add(getMenuItem("Copy", EditorPaneActions.copyAction, false));
popup.add(getMenuItem("Cut", EditorPaneActions.cutAction, true));
popup.add(getMenuItem("Paste", EditorPaneActions.pasteAction, true));
popup.add(getMenuItem("Delete Line", EditorPaneActions.rtaDeleteLineAction, true));
popup.add(getMenuItem("Delete Rest of Line", EditorPaneActions.rtaDeleteRestOfLineAction, true));
- GuiUtils.addPopupMenuSeparator(popup, "Code Selection:");
+ GuiUtils.addPopupMenuSeparator(popup, "Select:");
popup.add(getMenuItem("Select All", EditorPaneActions.selectAllAction, false));
popup.add(getMenuItem("Select Line", EditorPaneActions.selectLineAction, false));
popup.add(getMenuItem("Select Paragraph", EditorPaneActions.selectParagraphAction, false));
- GuiUtils.addPopupMenuSeparator(popup, "Code Folding:");
+ GuiUtils.addPopupMenuSeparator(popup, "Folding:");
popup.add(getMenuItem("Collapse Fold", EditorPaneActions.rstaCollapseFoldAction, false));
popup.add(getMenuItem("Expand Fold", EditorPaneActions.rstaExpandFoldAction, false));
popup.add(getMenuItem("Toggle Current Fold", EditorPaneActions.rstaToggleCurrentFoldAction, false));
popup.add(getMenuItem("Collapse All Folds", EditorPaneActions.rstaCollapseAllFoldsAction, false));
popup.add(getMenuItem("Expand All Folds", EditorPaneActions.rstaExpandAllFoldsAction, false));
popup.add(getMenuItem("Collapse All Comments", EditorPaneActions.rstaCollapseAllCommentFoldsAction, false));
- GuiUtils.addPopupMenuSeparator(popup, "Code Formatting:");
+ GuiUtils.addPopupMenuSeparator(popup, "Format:");
popup.add(getMenuItem("Indent Right", EditorPaneActions.epaIncreaseIndentAction, true));
popup.add(getMenuItem("Indent Left", EditorPaneActions.rstaDecreaseIndentAction, true));
popup.add(getMenuItem("Move Up", EditorPaneActions.rtaLineUpAction, true));
@@ -280,10 +280,10 @@ private void installCustomPopupMenu() {
menu.add(getMenuItem("Lower Case ('_' Sep.)", EditorPaneActions.epaLowerCaseUndAction, true));
menu.add(getMenuItem("Title Case", EditorPaneActions.epaTitleCaseAction, true));
menu.add(getMenuItem("Upper Case", EditorPaneActions.rtaUpperSelectionCaseAction, true));
- GuiUtils.addPopupMenuSeparator(popup, "Ocurrences:");
+ GuiUtils.addPopupMenuSeparator(popup, "Occurrences:");
popup.add(getMenuItem("Next Occurrence", EditorPaneActions.rtaNextOccurrenceAction, false));
popup.add(getMenuItem("Previous Occurrence", EditorPaneActions.rtaPrevOccurrenceAction, false));
- GuiUtils.addPopupMenuSeparator(popup, "Utilities:");
+ GuiUtils.addPopupMenuSeparator(popup, "Links & Syntax:");
popup.add(new OpenLinkUnderCursor().getMenuItem());
popup.add(new SearchWebOnSelectedText().getMenuItem());
popup.add(noneLangSyntaxMenu);
diff --git a/src/main/java/org/scijava/ui/swing/script/EditorPaneActions.java b/src/main/java/org/scijava/ui/swing/script/EditorPaneActions.java
index 8524b37a..841b6553 100644
--- a/src/main/java/org/scijava/ui/swing/script/EditorPaneActions.java
+++ b/src/main/java/org/scijava/ui/swing/script/EditorPaneActions.java
@@ -130,7 +130,6 @@ private void installCustomActions() {
map.put(rtaLineDownAction, new LineMoveAction(rtaLineUpAction, 1));
// actions that are not registered by default
- map.put(rtaTimeDateAction, new TimeDateAction());
map.put(clipboardHistoryAction, new ClipboardHistoryActionImpl());
// NB: This action is present in rsyntaxtextarea 3.1.1, but not 3.1.6.
// So we disable it for the time being.
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 e2157074..08bf1093 100644
--- a/src/main/java/org/scijava/ui/swing/script/FileSystemTreePanel.java
+++ b/src/main/java/org/scijava/ui/swing/script/FileSystemTreePanel.java
@@ -167,6 +167,7 @@ public Insets getBorderInsets(final Component c) {
private JToolBar statusToolbar() {
final JToolBar toolbar = new JToolBar();
+ toolbar.setFloatable(false);
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()));
@@ -465,7 +466,7 @@ private boolean allTreeNodesCollapsed() {
private void addContextualMenuToTree() {
final JPopupMenu popup = new JPopupMenu();
- GuiUtils.addPopupMenuSeparator(popup, "List:");
+ GuiUtils.addPopupMenuSeparator(popup, "List Folder:");
final JMenuItem selected = new JMenuItem("Selected Folder", new FlatFileViewDirectoryIcon());
selected.setToolTipText("Makes the selected folder (or the folder of the selected file) the only top-level folder");
selected.addActionListener(e -> {
@@ -744,6 +745,7 @@ private class SearchField extends TextFieldWithPlaceholder {
collapsedToggle.setSelectedIcon(Icons.chevron(true));
final JToolBar tb = new JToolBar();
+ tb.setFloatable(false);
tb.setMargin(new Insets(0, 0, 0, 2));
tb.add(collapsedToggle);
tb.add(caseToggle);
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 6fe16b30..c7a2e035 100644
--- a/src/main/java/org/scijava/ui/swing/script/TextEditor.java
+++ b/src/main/java/org/scijava/ui/swing/script/TextEditor.java
@@ -77,6 +77,8 @@
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
+import java.time.LocalDateTime;
+import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
@@ -111,6 +113,7 @@
import com.formdev.flatlaf.icons.FlatSearchIcon;
import org.fife.ui.rsyntaxtextarea.AbstractTokenMakerFactory;
+import org.fife.ui.rsyntaxtextarea.RSyntaxDocument;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import org.fife.ui.rsyntaxtextarea.Theme;
import org.fife.ui.rsyntaxtextarea.TokenMakerFactory;
@@ -216,8 +219,9 @@ public class TextEditor extends JFrame implements ActionListener,
chooseTabSize, gitGrep, replaceTabsWithSpaces,
replaceSpacesWithTabs, zapGremlins,openClassOrPackageHelp;
private RecentFilesMenuItem openRecent;
- private JMenu editMenu, gitMenu, tabsMenu, fontSizeMenu, tabSizeMenu, toolsMenu,
+ private JMenu editMenu, gitMenu, tabsMenu, fontSizeMenu, tabSizeMenu, codeMenu,
runMenu;
+ private int codeMenuCommentsIndex;
private int tabsMenuTabsStart;
private Set tabsMenuItems;
private FindAndReplaceDialog findDialog;
@@ -385,6 +389,20 @@ public TextEditor(final Context context) {
save.setMnemonic(KeyEvent.VK_S);
saveas = addToMenu(file, "Save As...", KeyEvent.VK_S, ctrl + shift);
saveas.setMnemonic(KeyEvent.VK_A);
+ JMenuItem jmi = new JMenuItem("Revert...");
+ jmi.addActionListener(e -> {
+ if (getEditorPane().isLocked()) {
+ error("File is currently locked.");
+ return;
+ }
+ final File f = getEditorPane().getFile();
+ if (f == null || !f.exists()) {
+ error(getEditorPane().getFileName() + "\nhas not been saved or its file is not available.");
+ } else {
+ reloadRevert("Revert to Saved File? Any unsaved changes will be lost.", "Revert");
+ }
+ });
+ file.add(jmi);
file.addSeparator();
makeJar = addToMenu(file, "Export as JAR...", 0, 0);
makeJar.setMnemonic(KeyEvent.VK_E);
@@ -402,21 +420,6 @@ public TextEditor(final Context context) {
}
syncStatusBar();
});
- JMenuItem jmi = new JMenuItem("Revert...");
- jmi.addActionListener(e -> {
- if (getEditorPane().isLocked()) {
- error("File is currently locked.");
- return;
- }
- final File f = getEditorPane().getFile();
- if (f == null || !f.exists()) {
- error(getEditorPane().getFileName() + "\nhas not been saved or its file is not available.");
- } else {
- reloadRevert("Revert to Saved File? Any unsaved changes will be lost.", "Revert");
- }
- });
- file.add(jmi);
- file.addSeparator();
jmi = new JMenuItem("Show in System Explorer");
jmi.addActionListener(e -> {
final File f = getEditorPane().getFile();
@@ -531,15 +534,14 @@ public TextEditor(final Context context) {
mbar.add(runMenu);
- // -- Tools menu --
+ // -- Code menu --
- toolsMenu = new JMenu("Tools");
- toolsMenu.setMnemonic(KeyEvent.VK_O);
+ codeMenu = new JMenu("Code");
+ codeMenu.setMnemonic(KeyEvent.VK_D);
cmdPalette = new CommandPalette(this);
- cmdPalette.install(toolsMenu);
-
- GuiUtils.addMenubarSeparator(toolsMenu, "Imports:");
- addImport = addToMenu(toolsMenu, "Add Import...", 0, 0);
+
+ GuiUtils.addMenubarSeparator(codeMenu, "Imports:");
+ addImport = addToMenu(codeMenu, "Add Import...", 0, 0);
addImport.setMnemonic(KeyEvent.VK_I);
respectAutoImports = prefService.getBoolean(getClass(), AUTO_IMPORT_PREFS, false);
autoImport =
@@ -553,22 +555,37 @@ public TextEditor(final Context context) {
else
write("Auto-imports off. Lines associated with execution errors can be marked");
});
- toolsMenu.add(autoImport);
- removeUnusedImports = addToMenu(toolsMenu, "Remove Unused Imports", 0, 0);
+ codeMenu.add(autoImport);
+ removeUnusedImports = addToMenu(codeMenu, "Remove Unused Imports", 0, 0);
removeUnusedImports.setMnemonic(KeyEvent.VK_U);
- sortImports = addToMenu(toolsMenu, "Sort Imports", 0, 0);
+ sortImports = addToMenu(codeMenu, "Sort Imports", 0, 0);
sortImports.setMnemonic(KeyEvent.VK_S);
- GuiUtils.addMenubarSeparator(toolsMenu, "Source & APIs:");
- extractSourceJar = addToMenu(toolsMenu, "Extract Source Jar...", 0, 0);
+ GuiUtils.addMenubarSeparator(codeMenu, "Comments:");
+ // "Toggle Comment" is inserted here by assembleEditMenu(): it needs an editor pane
+ codeMenuCommentsIndex = codeMenu.getMenuComponentCount();
+ final JMenuItem timeStamp = new JMenuItem("Insert Time Stamp Comment");
+ timeStamp.setToolTipText("Inserts the current date and time as a comment");
+ timeStamp.addActionListener(e -> insertTimeStampComment());
+ codeMenu.add(timeStamp);
+
+ GuiUtils.addMenubarSeparator(codeMenu, "Format:");
+ removeTrailingWhitespace = addToMenu(codeMenu, "Remove Trailing Whitespace", 0, 0);
+ replaceSpacesWithTabs = addToMenu(codeMenu, "Replace Spaces With Tabs", 0, 0);
+ replaceTabsWithSpaces = addToMenu(codeMenu, "Replace Tabs With Spaces", 0, 0);
+ zapGremlins = addToMenu(codeMenu, "Zap Gremlins", 0, 0);
+ zapGremlins.setToolTipText("Removes invalid (non-printable) ASCII characters");
+
+ GuiUtils.addMenubarSeparator(codeMenu, "Source & APIs:");
+ extractSourceJar = addToMenu(codeMenu, "Extract Source Jar...", 0, 0);
extractSourceJar.setMnemonic(KeyEvent.VK_E);
- openSourceForClass = addToMenu(toolsMenu, "Open Java File for Class...", 0, 0);
+ openSourceForClass = addToMenu(codeMenu, "Open Java File for Class...", 0, 0);
openSourceForClass.setMnemonic(KeyEvent.VK_J);
- //openSourceForMenuItem = addToMenu(toolsMenu, "Open Java File for Menu Item...", 0, 0);
+ //openSourceForMenuItem = addToMenu(codeMenu, "Open Java File for Menu Item...", 0, 0);
//openSourceForMenuItem.setMnemonic(KeyEvent.VK_M);
- addScritpEditorMacroCommands(toolsMenu);
- mbar.add(toolsMenu);
+ addScritpEditorMacroCommands(codeMenu);
+ mbar.add(codeMenu);
// -- Git menu --
@@ -689,10 +706,8 @@ public TextEditor(final Context context) {
bg.add(chooseTabSize);
tabSizeMenu.add(chooseTabSize);
options.add(tabSizeMenu);
- replaceSpacesWithTabs = addToMenu(options, "Replace Spaces With Tabs", 0, 0);
- replaceTabsWithSpaces = addToMenu(options, "Replace Tabs With Spaces", 0, 0);
- GuiUtils.addMenubarSeparator(options, "View:");
+ GuiUtils.addMenubarSeparator(options, "Appearance:");
options.add(markOccurences);
options.add(paintTabs);
options.add(marginLine);
@@ -912,6 +927,7 @@ private void assembleEditMenu() {
notesItem.addActionListener(e -> {
sideTabs.setSelectedComponent(notesPanel);
notesPanel.refresh();
+ if (!statusSide.isSelected()) statusSide.doClick();
});
editMenu.add(notesItem);
GuiUtils.addMenubarSeparator(editMenu, "Find:");
@@ -953,20 +969,35 @@ private void assembleEditMenu() {
final JMenuItem clearBookmarks = addToMenu(editMenu, "Clear Bookmarks...", 0, 0);
clearBookmarks.addActionListener(e -> clearAllBookmarks());
- GuiUtils.addMenubarSeparator(editMenu, "Utilities:");
- final JMenuItem commentJMI = addMappedActionToMenu(editMenu, "Toggle Comment",
- EditorPaneActions.rstaToggleCommentAction, true);
+ final JMenuItem commentJMI = addMappedActionToMenu(codeMenu, "Toggle Comment",
+ EditorPaneActions.rstaToggleCommentAction, true, codeMenuCommentsIndex);
commentJMI.setToolTipText("Alternative shortcut: "
+ getEditorPane().getPaneActions().getAcceleratorLabel(EditorPaneActions.epaToggleCommentAltAction));
- addMappedActionToMenu(editMenu, "Insert Time Stamp", EditorPaneActions.rtaTimeDateAction, true);
- removeTrailingWhitespace = addToMenu(editMenu, "Remove Trailing Whitespace", 0, 0);
- zapGremlins = addToMenu(editMenu, "Zap Gremlins", 0, 0);
- zapGremlins.setToolTipText("Removes invalid (non-printable) ASCII characters");
+ }
+
+ /** Inserts the current date and time at the caret, as a comment in the current language */
+ private void insertTimeStampComment() {
+ final EditorPane pane = getEditorPane();
+ if (pane.isLocked()) {
+ warn("File is currently locked.");
+ return;
+ }
+ String text = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
+ try {
+ // {start, end}: end is null for line comments. Both are null if the language has no comments
+ final String[] c = ((RSyntaxDocument) pane.getDocument()).getLineCommentStartAndEnd(0);
+ if (c != null && c[0] != null) text = c[0] + " " + text + (c[1] != null ? " " + c[1] : "");
+ } catch (final RuntimeException ignored) {
+ // no comment syntax: insert plain text
+ }
+ pane.requestFocusInWindow();
+ pane.replaceSelection(text);
}
private void addScritpEditorMacroCommands(final JMenu menu) {
- GuiUtils.addMenubarSeparator(menu, "Script Editor Macros:");
- final JMenuItem startMacro = new JMenuItem("Start/Resume Macro Recording");
+ GuiUtils.addMenubarSeparator(menu, "Action Recorder:");
+ final JMenuItem startMacro = new JMenuItem("Start/Resume Recording");
+ startMacro.setToolTipText("Starts (or resumes) recording a macro of editor actions");
startMacro.addActionListener(e -> {
if (getEditorPane().isLocked()) {
error("File is currently locked.");
@@ -977,7 +1008,8 @@ private void addScritpEditorMacroCommands(final JMenu menu) {
RTextArea.beginRecordingMacro();
});
menu.add(startMacro);
- final JMenuItem pauseMacro = new JMenuItem("Pause Macro Recording...");
+ final JMenuItem pauseMacro = new JMenuItem("Pause Recording...");
+ pauseMacro.setToolTipText("Pauses the macro recording");
pauseMacro.addActionListener(e -> {
if (!RTextArea.isRecordingMacro() || RTextArea.getCurrentMacro() == null) {
warn("No Script Editor Macro recording exists.");
@@ -992,6 +1024,7 @@ private void addScritpEditorMacroCommands(final JMenu menu) {
});
menu.add(pauseMacro);
final JMenuItem endMacro = new JMenuItem("Stop/Save Recording...");
+ endMacro.setToolTipText("Stops the macro recording and saves it to a file");
endMacro.addActionListener(e -> {
pauseMacro.doClick();
if (RTextArea.getCurrentMacro() != null) {
@@ -1007,7 +1040,8 @@ private void addScritpEditorMacroCommands(final JMenu menu) {
}
});
menu.add(endMacro);
- final JMenuItem clearMacro = new JMenuItem("Clear Recorded Macro...");
+ final JMenuItem clearMacro = new JMenuItem("Clear Recording...");
+ clearMacro.setToolTipText("Discards the current macro recording");
clearMacro.addActionListener(e -> {
if (RTextArea.getCurrentMacro() == null) {
warn("Nothing to clear: No macro has been recorded.");
@@ -1019,8 +1053,8 @@ private void addScritpEditorMacroCommands(final JMenu menu) {
}
});
menu.add(clearMacro);
- final JMenuItem playMacro = new JMenuItem("Run Recorded Macro");
- playMacro.setToolTipText("Runs current recordings. Prompts for\nrecordings file if no recordings exist");
+ final JMenuItem playMacro = new JMenuItem("Run Recording");
+ playMacro.setToolTipText("Runs the current macro recording. Prompts for\nrecordings file if no recordings exist");
playMacro.addActionListener(e -> {
if (getEditorPane().isLocked()) {
error("File is currently locked.");
@@ -1194,7 +1228,7 @@ private void initializeDynamicMenuComponents() {
setWrapLines(wrapLines.getState());
syncStatusBar();
});
- markOccurences = new JCheckBoxMenuItem("Mark Occurences", false);
+ markOccurences = new JCheckBoxMenuItem("Mark Occurrences", false);
markOccurences.setToolTipText("Allows for all occurrences of a double-clicked string to be"
+ " highlighted.\nLines with hits are marked on the Editor's notification strip");
markOccurences.addItemListener(e -> setMarkOccurrences(markOccurences.getState()));
@@ -1390,6 +1424,12 @@ public JMenuItem addToMenu(final JMenu menu, final String menuEntry,
}
private JMenuItem addMappedActionToMenu(final JMenu menu, String label, String actionID, final boolean editingAction) {
+ return addMappedActionToMenu(menu, label, actionID, editingAction, -1);
+ }
+
+ /** Same as above, adding the item at the specified position of the menu (-1 appends it) */
+ private JMenuItem addMappedActionToMenu(final JMenu menu, String label, String actionID, final boolean editingAction,
+ final int index) {
final JMenuItem jmi = new JMenuItem(label);
jmi.addActionListener(e -> {
try {
@@ -1409,7 +1449,8 @@ private JMenuItem addMappedActionToMenu(final JMenu menu, String label, String a
}
});
jmi.setAccelerator(getEditorPane().getPaneActions().getAccelerator(actionID));
- menu.add(jmi);
+ if (index < 0) menu.add(jmi);
+ else menu.insert(jmi, index);
return jmi;
}
@@ -1955,6 +1996,7 @@ public Dimension getPreferredSize() { // fixed width: neighbors do not move as t
syncStatusBar(); // e.g., no language: the request was refused
});
final JToolBar bar = new JToolBar();
+ bar.setFloatable(false);
final int gap = 4;
bar.setBorder(BorderFactory.createEmptyBorder(0, gap, 0, gap));
bar.add(statusSide);
@@ -2446,8 +2488,13 @@ private void goToBookmark(final Bookmark bookmark) {
/** Shows the bookmarks side panel, listing bookmarks of all open tabs. */
public void listBookmarks() {
+ if (!SwingUtilities.isEventDispatchThread()) {
+ SwingUtilities.invokeLater(this::listBookmarks);
+ return;
+ }
sideTabs.setSelectedComponent(outlineSplit);
bookmarksPanel.refresh();
+ if (!statusSide.isSelected()) statusSide.doClick();
}
void clearAllBookmarks() {
@@ -4205,6 +4252,7 @@ private void appendPreferences(final JMenu menu) {
private JMenu helpMenu() {
final JMenu menu = new JMenu("Help");
+ cmdPalette.install(menu);
GuiUtils.addMenubarSeparator(menu, "Offline Help:");
JMenuItem item = new JMenuItem("List Shortcuts...");
item.addActionListener(e -> displayKeyMap());
@@ -4241,14 +4289,12 @@ private JMenu helpMenu() {
//menu.addSeparator();
menu.add(helpMenuItem("SciJava Javadoc Portal", "https://javadoc.scijava.org/"));
menu.add(helpMenuItem("SciJava Maven Repository", "https://maven.scijava.org/"));
- menu.addSeparator();
menu.add(helpMenuItem("Fiji on GitHub", "https://github.com/fiji"));
menu.add(helpMenuItem("SciJava on GitHub", "https://github.com/scijava/"));
- menu.addSeparator();
+ GuiUtils.addMenubarSeparator(menu, "Documentation:");
menu.add(helpMenuItem("ImageJ Macro Functions", "https://imagej.nih.gov/ij/developer/macro/functions.html"));
menu.add(helpMenuItem("ImageJ Docs: Development", "https://imagej.net/develop/"));
menu.add(helpMenuItem("ImageJ Docs: Scripting", "https://imagej.net/scripting/"));
- menu.addSeparator();
menu.add(helpMenuItem("ImageJ Notebook Tutorials", "https://github.com/imagej/tutorials#readme"));
return menu;
}
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 5fa3fc16..03bd8dac 100644
--- a/src/main/java/org/scijava/ui/swing/script/TextEditorTab.java
+++ b/src/main/java/org/scijava/ui/swing/script/TextEditorTab.java
@@ -216,7 +216,9 @@ public void dragEnter(final DropTargetDragEvent e) {
});
final JPanel viewPanel = new JPanel();
viewPanel.setOpaque(false);
- viewPanel.add(new JLabel("Show:"));
+ final JLabel showLabel = new JLabel("Show:");
+ showLabel.setEnabled(false);
+ viewPanel.add(showLabel);
viewPanel.add(viewChooser);
viewPanel.setMaximumSize(viewPanel.getPreferredSize()); // do not stretch
bar.add(viewPanel);
@@ -249,6 +251,7 @@ public void dragEnter(final DropTargetDragEvent e) {
prompt_panel.setLayout(new BorderLayout());
final JToolBar promptBar = new JToolBar();
+ promptBar.setFloatable(false);
promptBar.putClientProperty(FlatClientProperties.STYLE_CLASS, "small");
promptBar.setBorder(null);
promptBar.setMargin(null);
@@ -289,7 +292,7 @@ with a modifier (e.g., %s) they move the caret within a multi-line prompt.
keyHtml(KeyEvent.VK_PAGE_UP, 0), keyHtml(KeyEvent.VK_P, ctrl),
keyHtml(KeyEvent.VK_PAGE_DOWN, 0), keyHtml(KeyEvent.VK_N, ctrl),
keyHtml(KeyEvent.VK_UP, 0), keyHtml(KeyEvent.VK_DOWN, 0), keyHtml(KeyEvent.VK_UP, shift));
- textEditor.showHTMLDialog("REPL (Read-Evaluate-Print-Loop)", html);
+ textEditor.showHTMLDialog("REPL (Read-Evaluate-Print-Loop) Key Bindings", html);
});
promptBar.add(statusHelp);
From 8dbaa36e1b3a68d55b07359b14b9665c4b1b6b41 Mon Sep 17 00:00:00 2001
From: Tiago Ferreira
Date: Sat, 14 Nov 2026 21:46:29 -0500
Subject: [PATCH 10/41] Improve convertion between spaces <> tabs
- Only touch leading whitespace
- Respect a selection, or apply to whole file if none exists
- Ask for confirmation
- Checks for a locked file
- Report how many lines changed
---
.../scijava/ui/swing/script/TextEditor.java | 30 ++++++++++++-------
1 file changed, 20 insertions(+), 10 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 c7a2e035..05d81265 100644
--- a/src/main/java/org/scijava/ui/swing/script/TextEditor.java
+++ b/src/main/java/org/scijava/ui/swing/script/TextEditor.java
@@ -216,8 +216,8 @@ public class TextEditor extends JFrame implements ActionListener,
previousTab, runSelection, extractSourceJar, openSourceForClass,
//openSourceForMenuItem, // this never had an actionListener!??
openMacroFunctions, decreaseFontSize, increaseFontSize, chooseFontSize,
- chooseTabSize, gitGrep, replaceTabsWithSpaces,
- replaceSpacesWithTabs, zapGremlins,openClassOrPackageHelp;
+ chooseTabSize, gitGrep, convertToSpaces,
+ convertToTabs, zapGremlins,openClassOrPackageHelp;
private RecentFilesMenuItem openRecent;
private JMenu editMenu, gitMenu, tabsMenu, fontSizeMenu, tabSizeMenu, codeMenu,
runMenu;
@@ -571,8 +571,10 @@ public TextEditor(final Context context) {
GuiUtils.addMenubarSeparator(codeMenu, "Format:");
removeTrailingWhitespace = addToMenu(codeMenu, "Remove Trailing Whitespace", 0, 0);
- replaceSpacesWithTabs = addToMenu(codeMenu, "Replace Spaces With Tabs", 0, 0);
- replaceTabsWithSpaces = addToMenu(codeMenu, "Replace Tabs With Spaces", 0, 0);
+ convertToSpaces = addToMenu(codeMenu, "Convert Indentation to Spaces...", 0, 0);
+ convertToSpaces.setToolTipText("Converts the leading tabs of the selected lines (or of the whole file) to spaces");
+ convertToTabs = addToMenu(codeMenu, "Convert Indentation to Tabs...", 0, 0);
+ convertToTabs.setToolTipText("Converts the leading spaces of the selected lines (or of the whole file) to tabs");
zapGremlins = addToMenu(codeMenu, "Zap Gremlins", 0, 0);
zapGremlins.setToolTipText("Removes invalid (non-printable) ASCII characters");
@@ -1874,10 +1876,10 @@ else if (source == sortImports)
new TokenFunctions(getTextArea()).sortImports();
else if (source == removeTrailingWhitespace)
new TokenFunctions(getTextArea()).removeTrailingWhitespace();
- else if (source == replaceTabsWithSpaces)
- getTextArea().convertTabsToSpaces();
- else if (source == replaceSpacesWithTabs)
- getTextArea().convertSpacesToTabs();
+ else if (source == convertToSpaces)
+ convertIndentation(true);
+ else if (source == convertToTabs)
+ convertIndentation(false);
else if (source == zapGremlins)
zapGremlins();
}
@@ -2045,15 +2047,21 @@ private JPopupMenu indentationMenu() {
final JMenu width = new JMenu("Tab Width");
final ButtonGroup sizes = new ButtonGroup();
final int current = getEditorPane().getTabSize();
+ boolean custom = true;
for (final int size : new int[] { 2, 4, 8 }) {
final JRadioButtonMenuItem item = new JRadioButtonMenuItem("" + size, size == current);
item.addActionListener(e -> {
getEditorPane().setTabSize(size);
updateTabAndFontSize(false);
});
+ if (size == current) custom = false;
sizes.add(item);
width.add(item);
}
+ final JRadioButtonMenuItem other = new JRadioButtonMenuItem(chooseTabSize.getText(), custom);
+ other.addActionListener(e -> chooseTabSize.doClick());
+ sizes.add(other);
+ width.add(other);
menu.add(width);
menu.addSeparator();
final JMenuItem toSpaces = new JMenuItem("Convert Indentation to Spaces...");
@@ -2078,8 +2086,6 @@ private void convertIndentation(final boolean toSpaces) {
}
final boolean selection = ta.getSelectionStart() != ta.getSelectionEnd();
final String scope = selection ? "the selected lines" : "the whole file";
- if (!GuiUtils.confirm(this, "Convert the indentation of " + scope + " to " + (toSpaces ? "spaces" : "tabs") + "?",
- "Convert Indentation?", "Convert")) return;
try {
final int length = ta.getDocument().getLength();
int start = 0;
@@ -2121,6 +2127,10 @@ private void convertIndentation(final boolean toSpaces) {
statusText.setText("Indentation already uses " + (toSpaces ? "spaces" : "tabs"));
return;
}
+ final String rule = toSpaces ? "1 tab = " + tabSize + " spaces" : tabSize + " spaces = 1 tab";
+ if (!GuiUtils.confirm(this, "Convert the indentation of " + scope + " to " + (toSpaces ? "spaces" : "tabs")
+ + " (" + rule + ")?\n\n" + changed + (changed == 1 ? " line" : " lines") + " will change.",
+ "Convert Indentation?", "Convert")) return;
ta.replaceRange(out.toString(), start, end);
statusText.setText("Converted the indentation of " + changed + (changed == 1 ? " line" : " lines"));
} catch (final BadLocationException | RuntimeException ex) {
From 3f8a648d56e903ae45ccfe3dad270953d8b925b4 Mon Sep 17 00:00:00 2001
From: Tiago Ferreira
Date: Sat, 14 Nov 2026 22:06:23 -0500
Subject: [PATCH 11/41] Improved controls for line wrapping
---
.../ui/swing/script/CommandPalette.java | 1 +
.../scijava/ui/swing/script/TextEditor.java | 66 +++++++++++++++----
.../ui/swing/script/TextEditorTab.java | 14 +++-
3 files changed, 68 insertions(+), 13 deletions(-)
diff --git a/src/main/java/org/scijava/ui/swing/script/CommandPalette.java b/src/main/java/org/scijava/ui/swing/script/CommandPalette.java
index cf897a25..d7c56bfa 100644
--- a/src/main/java/org/scijava/ui/swing/script/CommandPalette.java
+++ b/src/main/java/org/scijava/ui/swing/script/CommandPalette.java
@@ -157,6 +157,7 @@ public void actionPerformed(final ActionEvent e) {
};
action.putValue(Action.ACCELERATOR_KEY, ACCELERATOR);
+ action.putValue(Action.SMALL_ICON, Icons.magnifier());
menu.add(new JMenuItem(action));
}
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 05d81265..c02d7b21 100644
--- a/src/main/java/org/scijava/ui/swing/script/TextEditor.java
+++ b/src/main/java/org/scijava/ui/swing/script/TextEditor.java
@@ -227,7 +227,11 @@ public class TextEditor extends JFrame implements ActionListener,
private FindAndReplaceDialog findDialog;
private JButton statusTab;
private FlatSearchIcon statusFastIcon;
- private JToggleButton statusWrap;
+ private JButton statusWrap;
+ private JCheckBoxMenuItem wrapEditorItem;
+ private boolean consoleWrap, replWrap;
+ private static final String CONSOLE_WRAP_PREFS = "script.editor.ConsoleWrap";
+ private static final String REPL_WRAP_PREFS = "script.editor.ReplWrap";
private JButton statusPos, statusLang;
private JToggleButton statusSide, statusBelow, statusRight, statusRepl;
private int sideLastLocation = -1;
@@ -304,6 +308,8 @@ public TextEditor(final Context context) {
contexts.add(context);
context.inject(this);
initializeTokenMakers();
+ consoleWrap = prefService.getBoolean(getClass(), CONSOLE_WRAP_PREFS, false);
+ replWrap = prefService.getBoolean(getClass(), REPL_WRAP_PREFS, false);
// NB: All panes must be initialized before menus are assembled!
tabbed = GuiUtils.getJTabbedPane();
@@ -841,7 +847,7 @@ public void windowGainedFocus(final WindowEvent e) {
// Tweaks for Console
errorScreen.setFont(getEditorPane().getFont());
errorScreen.setEditable(false);
- errorScreen.setLineWrap(false);
+ errorScreen.setLineWrap(consoleWrap);
applyConsolePopupMenu(errorScreen);
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
@@ -1941,11 +1947,30 @@ public Dimension getPreferredSize() { // fixed width: neighbors do not move as t
final JPopupMenu menu = languageMenu.getPopupMenu();
menu.show(statusLang, 0, -menu.getPreferredSize().height); // opens upwards: the bar is at the bottom
});
- statusWrap = statusButton("Wrap", "Wraps long lines", true);
- statusWrap.addActionListener(e -> {
- wrapLines.setState(statusWrap.isSelected());
+ statusWrap = new JButton("Wrap: Off");
+ statusWrap.setToolTipText("Line wrapping. Click for options");
+ statusWrap.setFocusable(false);
+ statusWrap.setFont(statusWrap.getFont().deriveFont(statusWrap.getFont().getSize2D() * .9f));
+ final JPopupMenu wrapMenu = new JPopupMenu();
+ wrapEditorItem = new JCheckBoxMenuItem("Wrap Editor Lines", wrapLines.getState());
+ wrapEditorItem.addActionListener(e -> {
+ wrapLines.setState(wrapEditorItem.isSelected());
syncStatusBar();
});
+ final JCheckBoxMenuItem wrapConsoleItem = new JCheckBoxMenuItem("Wrap Console Lines", consoleWrap);
+ wrapConsoleItem.addActionListener(e -> setConsoleWrap(wrapConsoleItem.isSelected()));
+ final JCheckBoxMenuItem wrapReplItem = new JCheckBoxMenuItem("Wrap REPL Prompt Lines", replWrap);
+ wrapReplItem.addActionListener(e -> setReplWrap(wrapReplItem.isSelected()));
+ wrapMenu.add(wrapEditorItem);
+ wrapMenu.addSeparator();
+ wrapMenu.add(wrapConsoleItem);
+ wrapMenu.add(wrapReplItem);
+ statusWrap.addActionListener(e -> {
+ wrapEditorItem.setSelected(getEditorPane().getLineWrap());
+ wrapMenu.show(statusWrap, 0, -wrapMenu.getPreferredSize().height); // opens upwards: the bar is at the bottom
+ });
+ cmdPalette.register(wrapConsoleItem, "Status Bar");
+ cmdPalette.register(wrapReplItem, "Status Bar");
statusTab = new JButton("Spaces: 4");
statusTab.setToolTipText("Indentation. Click for options");
statusTab.setFocusable(false);
@@ -2161,7 +2186,8 @@ void syncStatusBar() {
if (statusTab == null || statusWrap == null) return;
try {
final EditorPane pane = getEditorPane();
- statusWrap.setSelected(pane.getLineWrap());
+ statusWrap.setText("Wrap: " + (pane.getLineWrap() ? "On" : "Off"));
+ if (wrapEditorItem != null) wrapEditorItem.setSelected(pane.getLineWrap());
if (statusBelow != null) {
final TextEditorTab tab = getTab();
final boolean shown = tab.isBottomVisible();
@@ -2219,6 +2245,29 @@ private void setWrapLines(final boolean wrap) {
getEditorPane().requestFocusInWindow();
}
+ boolean isConsoleWrap() {
+ return consoleWrap;
+ }
+
+ boolean isReplWrap() {
+ return replWrap;
+ }
+
+ private void setConsoleWrap(final boolean wrap) {
+ consoleWrap = wrap;
+ prefService.put(getClass(), CONSOLE_WRAP_PREFS, wrap);
+ errorScreen.setLineWrap(wrap);
+ for (int i = 0; i < tabbed.getTabCount(); i++)
+ getTab(i).setConsoleWrap(wrap);
+ }
+
+ private void setReplWrap(final boolean wrap) {
+ replWrap = wrap;
+ prefService.put(getClass(), REPL_WRAP_PREFS, wrap);
+ for (int i = 0; i < tabbed.getTabCount(); i++)
+ getTab(i).setPromptWrap(wrap);
+ }
+
private void setMarginLineEnabled(final boolean enabled) {
for (int i = 0; i < tabbed.getTabCount(); i++)
getEditorPane(i).setMarginLineEnabled(enabled);
@@ -4378,11 +4427,6 @@ else if (getTab().showingErrors)
popup.add(jmi);
jmi.addActionListener(e -> textArea.getHighlighter().removeAllHighlights());
cmdPalette.register(jmi, scope);
- popup.addSeparator();
- final JCheckBoxMenuItem jmc = new JCheckBoxMenuItem("Wrap Lines");
- popup.add(jmc);
- jmc.addActionListener( e -> textArea.setLineWrap(jmc.isSelected()));
- cmdPalette.register(jmc, scope);
}
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 03bd8dac..08a1a328 100644
--- a/src/main/java/org/scijava/ui/swing/script/TextEditorTab.java
+++ b/src/main/java/org/scijava/ui/swing/script/TextEditorTab.java
@@ -170,10 +170,10 @@ public void dragEnter(final DropTargetDragEvent e) {
// tweaks for console
screen.setEditable(false);
- screen.setLineWrap(false);
+ screen.setLineWrap(textEditor.isConsoleWrap());
screen.setFont(getEditorPane().getFont());
combinedScreen.setEditable(false);
- combinedScreen.setLineWrap(false);
+ combinedScreen.setLineWrap(textEditor.isConsoleWrap());
combinedScreen.setFont(getEditorPane().getFont());
textEditor.applyConsolePopupMenu(screen);
textEditor.applyConsolePopupMenu(combinedScreen);
@@ -243,6 +243,7 @@ public void dragEnter(final DropTargetDragEvent e) {
prompt.setEnabled(false);
prompt.setFont(getEditorPane().getFont());
prompt.setTabSize(editorPane.getTabSize());
+ prompt.setLineWrap(textEditor.isReplWrap());
final JPanel prompt_panel = new JPanel();
prompt_panel.setMinimumSize(new Dimension(0, 0));
@@ -595,6 +596,15 @@ public JTextArea getScreen() {
}
}
+ void setConsoleWrap(final boolean wrap) {
+ screen.setLineWrap(wrap);
+ combinedScreen.setLineWrap(wrap);
+ }
+
+ void setPromptWrap(final boolean wrap) {
+ prompt.setLineWrap(wrap);
+ }
+
public JTextArea getPrompt() {
return prompt;
}
From b5f1dbc726bfeb0c563cd326bcaf6ac622f5bbb7 Mon Sep 17 00:00:00 2001
From: Tiago Ferreira
Date: Sat, 14 Nov 2026 22:22:29 -0500
Subject: [PATCH 12/41] Organize/improve empty-panel hints
---
.../ui/swing/script/BookmarksPanel.java | 24 +--------
.../ui/swing/script/FileSystemTree.java | 17 +------
.../org/scijava/ui/swing/script/GuiUtils.java | 51 +++++++++++++++++++
.../scijava/ui/swing/script/NotesPanel.java | 26 ++++++++--
.../ui/swing/script/OutlineTreePanel.java | 39 ++------------
5 files changed, 81 insertions(+), 76 deletions(-)
diff --git a/src/main/java/org/scijava/ui/swing/script/BookmarksPanel.java b/src/main/java/org/scijava/ui/swing/script/BookmarksPanel.java
index b5358ff6..616249f1 100644
--- a/src/main/java/org/scijava/ui/swing/script/BookmarksPanel.java
+++ b/src/main/java/org/scijava/ui/swing/script/BookmarksPanel.java
@@ -92,8 +92,8 @@ class BookmarksPanel extends JPanel {
@Override
protected void paintComponent(final Graphics g) {
super.paintComponent(g);
- if (model.isEmpty()) paintEmptyHint((java.awt.Graphics2D) g.create(),
- this, "No bookmarks", "Click next to a line number", "to bookmark it");
+ if (model.isEmpty()) GuiUtils.paintEmptyHint(g, this, "No bookmarks",
+ "Click next to a line number to bookmark it");
}
};
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
@@ -147,26 +147,6 @@ else if (e.getKeyCode() == KeyEvent.VK_DELETE) {
poll.start();
}
- private static void paintEmptyHint(final java.awt.Graphics2D g2,
- final Component c, final String... lines)
- {
- try {
- g2.setRenderingHint(java.awt.RenderingHints.KEY_TEXT_ANTIALIASING,
- java.awt.RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
- g2.setColor(GuiUtils.secondaryColor());
- final java.awt.FontMetrics fm = g2.getFontMetrics();
- int y = (c.getHeight() - fm.getHeight() * lines.length) / 2 + fm
- .getAscent();
- for (final String line : lines) {
- g2.drawString(line, (c.getWidth() - fm.stringWidth(line)) / 2, y);
- y += fm.getHeight();
- }
- }
- finally {
- g2.dispose();
- }
- }
-
/** Brings the list up to date (cheap if nothing changed). */
void refresh() {
final List current = source.get();
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 f513866b..25bf098a 100644
--- a/src/main/java/org/scijava/ui/swing/script/FileSystemTree.java
+++ b/src/main/java/org/scijava/ui/swing/script/FileSystemTree.java
@@ -356,22 +356,9 @@ protected void paintComponent(final Graphics g) {
super.paintComponent(g);
// Plain hints while the tree is empty (no content, or all folders hidden by the filter)
if (root().getChildCount() > 0) return;
- final String[] lines = hidden_tops.isEmpty() ? new String[] { "Drag folders here", "or right-click for options" }
+ final String[] lines = hidden_tops.isEmpty() ? new String[] { "Drag folders here", "Or right-click for options" }
: new String[] { scanning ? "Searching..." : "No matches" };
- final java.awt.Graphics2D g2 = (java.awt.Graphics2D) g.create();
- try {
- g2.setRenderingHint(java.awt.RenderingHints.KEY_TEXT_ANTIALIASING,
- java.awt.RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
- g2.setColor(GuiUtils.secondaryColor());
- final java.awt.FontMetrics fm = g2.getFontMetrics();
- int y = (getHeight() - fm.getHeight() * lines.length) / 2 + fm.getAscent();
- for (final String line : lines) {
- g2.drawString(line, (getWidth() - fm.stringWidth(line)) / 2, y);
- y += fm.getHeight();
- }
- } finally {
- g2.dispose();
- }
+ GuiUtils.paintEmptyHint(g, this, lines);
}
/**
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 01e746a1..4389e6f0 100644
--- a/src/main/java/org/scijava/ui/swing/script/GuiUtils.java
+++ b/src/main/java/org/scijava/ui/swing/script/GuiUtils.java
@@ -33,6 +33,11 @@
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
+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.event.InputEvent;
import java.awt.event.KeyEvent;
@@ -45,6 +50,8 @@
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;
+import java.util.List;
+import java.util.ArrayList;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
@@ -493,6 +500,50 @@ static void recolorTracks(final JScrollPane scrollPane, final Color color) {
scrollPane.getVerticalScrollBar().putClientProperty(FlatClientProperties.STYLE, style);
}
+ /**
+ * Paints centered, word-wrapped hint text over an empty component (e.g., a list or a text area), in the
+ * secondary color. To be called from paintComponent(), after the superclass has painted. Each argument is
+ * a paragraph.
+ */
+ static void paintEmptyHint(final Graphics g, final JComponent c, final String... paragraphs) {
+ final Graphics2D g2 = (Graphics2D) g.create();
+ try {
+ g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
+ g2.setFont(c.getFont());
+ g2.setColor(secondaryColor());
+ final FontMetrics fm = g2.getFontMetrics();
+ final Insets in = c.getInsets();
+ final int maxWidth = Math.max(20, c.getWidth() - in.left - in.right - 2 * fm.getHeight());
+ final List lines = new ArrayList<>();
+ final List paragraphStart = new ArrayList<>();
+ for (final String paragraph : paragraphs) {
+ final StringBuilder line = new StringBuilder();
+ boolean first = true;
+ for (final String word : paragraph.split(" ")) {
+ if (line.length() > 0 && fm.stringWidth(line + " " + word) > maxWidth) {
+ lines.add(line.toString());
+ paragraphStart.add(first);
+ first = false;
+ line.setLength(0);
+ }
+ line.append(line.length() > 0 ? " " : "").append(word);
+ }
+ lines.add(line.toString());
+ paragraphStart.add(first);
+ }
+ final int gap = fm.getHeight() / 3;
+ final int height = fm.getHeight() * lines.size() + gap * (paragraphs.length - 1);
+ int y = (c.getHeight() - height) / 2 + fm.getAscent();
+ for (int i = 0; i < lines.size(); i++) {
+ if (i > 0 && paragraphStart.get(i)) y += gap;
+ g2.drawString(lines.get(i), (c.getWidth() - fm.stringWidth(lines.get(i))) / 2, y);
+ y += fm.getHeight();
+ }
+ } finally {
+ g2.dispose();
+ }
+ }
+
/** Makes the window containing the component draggable by it */
static void enableDrag(final JComponent component) {
final Point[] dragStart = { null };
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 476da3e0..3ba4ddf2 100644
--- a/src/main/java/org/scijava/ui/swing/script/NotesPanel.java
+++ b/src/main/java/org/scijava/ui/swing/script/NotesPanel.java
@@ -80,7 +80,17 @@ class NotesPanel extends JPanel {
private final Class> prefsOwner;
private final JTextArea scratch;
private final DefaultListModel model = new DefaultListModel<>();
- private final JList list = new JList<>(model);
+ private final JList list = new JList<>(model) {
+
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ protected void paintComponent(final java.awt.Graphics g) {
+ super.paintComponent(g);
+ if (model.isEmpty()) GuiUtils.paintEmptyHint(g, this, "Paste history will appear here",
+ "Double-click an entry to insert it");
+ }
+ };
private final Timer saveTimer;
private boolean loading;
@@ -93,7 +103,17 @@ class NotesPanel extends JPanel {
this.prefsOwner = prefsOwner;
// Scratchpad
- scratch = new JTextArea();
+ scratch = new JTextArea() {
+
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ protected void paintComponent(final java.awt.Graphics g) {
+ super.paintComponent(g);
+ if (getDocument().getLength() == 0) GuiUtils.paintEmptyHint(g, this, "Jot down notes",
+ "They are saved between sessions");
+ }
+ };
scratch.setLineWrap(true);
scratch.setWrapStyleWord(true);
scratch.setBorder(new EmptyBorder(4, 4, 4, 4));
@@ -113,7 +133,7 @@ class NotesPanel extends JPanel {
final JScrollPane listPane = new JScrollPane(list);
GuiUtils.flattenScrollBars(listPane);
final JPanel pane2 = new JPanel(new BorderLayout());
- final JLabel clipboardHeader = header("Clipboard History (Double-click to Insert)");
+ final JLabel clipboardHeader = header("Clipboard History");
pane2.add(clipboardHeader, BorderLayout.NORTH);
pane2.add(listPane, BorderLayout.CENTER);
diff --git a/src/main/java/org/scijava/ui/swing/script/OutlineTreePanel.java b/src/main/java/org/scijava/ui/swing/script/OutlineTreePanel.java
index 8da663c0..6a6209b7 100644
--- a/src/main/java/org/scijava/ui/swing/script/OutlineTreePanel.java
+++ b/src/main/java/org/scijava/ui/swing/script/OutlineTreePanel.java
@@ -29,16 +29,6 @@
package org.scijava.ui.swing.script;
-import java.awt.Color;
-import java.awt.Graphics2D;
-import java.awt.Insets;
-import java.awt.RenderingHints;
-import java.awt.font.FontRenderContext;
-import java.awt.font.LineBreakMeasurer;
-import java.awt.font.TextAttribute;
-import java.awt.font.TextLayout;
-import java.text.AttributedCharacterIterator;
-import java.text.AttributedString;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JMenuItem;
@@ -62,7 +52,6 @@ class OutlineTreePanel extends JScrollPane {
private static final long serialVersionUID = -710040159139542578L;
private AbstractSourceTree sourceTree;
- private final Color placeholdColor;
private float fontSize;
private boolean sorted;
private boolean major;
@@ -71,7 +60,6 @@ class OutlineTreePanel extends JScrollPane {
super();
fontSize = getFont().getSize();
setViewportView(new UnsupportedLangTree());
- placeholdColor = GuiUtils.getDisabledComponentColor();
}
protected void rebuildSourceTree(final EditorPane pane) {
@@ -146,11 +134,10 @@ private void setPopupMenu(final JTree tree, final EditorPane pane) {
private class UnsupportedLangTree extends JTree {
private static final long serialVersionUID = 1L;
- private static final String HOLDER = "Outline not available... "
- + "(Currently, only Java, JS, & XML are supported)";
public UnsupportedLangTree() {
super((TreeNode) null);
+ setFont(getFont().deriveFont(fontSize));
}
public UnsupportedLangTree(final EditorPane pane) {
@@ -161,28 +148,8 @@ public UnsupportedLangTree(final EditorPane pane) {
@Override
protected void paintComponent(final java.awt.Graphics g) {
super.paintComponent(g);
- final Graphics2D g2 = (Graphics2D) g.create();
- g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
- g2.setColor(placeholdColor);
- final Insets i = getInsets();
- float yTop = i.top;
- final int w = getWidth() - i.left - i.right;
- final int lastIndex = HOLDER.length();
- final AttributedString ac = new AttributedString(HOLDER);
- ac.addAttribute(TextAttribute.SIZE, fontSize, 0, lastIndex);
- ac.addAttribute(TextAttribute.POSTURE, TextAttribute.POSTURE_OBLIQUE, 0, lastIndex);
- final AttributedCharacterIterator aci = ac.getIterator();
- final FontRenderContext frc = g2.getFontRenderContext();
- final LineBreakMeasurer lbm = new LineBreakMeasurer(aci, frc);
- while (lbm.getPosition() < aci.getEndIndex()) {
- // see https://stackoverflow.com/a/41118280s
- final TextLayout tl = lbm.nextLayout(w);
- final float xPos = (float) (i.left + ((getWidth() - tl.getBounds().getWidth()) / 2));
- final float yPos = (float) (yTop + ((getHeight() - tl.getBounds().getHeight()) / 2));
- tl.draw(g2, xPos, yPos + tl.getAscent());
- yTop += tl.getDescent() + tl.getLeading() + tl.getAscent();
- }
- g2.dispose();
+ GuiUtils.paintEmptyHint(g, this, "Outline not available",
+ "Currently, only Java, JS, and XML are supported");
}
}
From 4a72158e8eac2ca5d3ed0a07f0c919d70b0062bf Mon Sep 17 00:00:00 2001
From: Tiago Ferreira
Date: Sat, 14 Nov 2026 22:59:19 -0500
Subject: [PATCH 13/41] Add tab controls
---
.../org/scijava/ui/swing/script/GuiUtils.java | 12 ++-
.../scijava/ui/swing/script/NotesPanel.java | 2 +-
.../scijava/ui/swing/script/TextEditor.java | 86 ++++++++++++++++++-
3 files changed, 94 insertions(+), 6 deletions(-)
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 4389e6f0..e44fd173 100644
--- a/src/main/java/org/scijava/ui/swing/script/GuiUtils.java
+++ b/src/main/java/org/scijava/ui/swing/script/GuiUtils.java
@@ -356,11 +356,12 @@ static JButton newTabButton(final Runnable action) {
}
static JButton ellipsisButton(final Runnable action) {
- final JButton b = new JButton("\u22ee");
+ final JButton b = new JButton("⋮");
+ b.setFont(b.getFont().deriveFont(b.getFont().getSize()*1.2f));
b.setFont(b.getFont().deriveFont(Font.BOLD));
b.setFocusable(false);
b.putClientProperty(FlatClientProperties.BUTTON_TYPE, FlatClientProperties.BUTTON_TYPE_TOOLBAR_BUTTON);
- b.addActionListener(e -> action.run());
+ if (action != null) b.addActionListener(e -> action.run());
return b;
}
@@ -435,6 +436,9 @@ static void expandAllTreeNodes(final JTree tree) {
/* Tweaks for tabbed pane */
static JTabbedPane getJTabbedPane() {
final JTabbedPane tabbed = new JTabbedPane();
+ tabbed.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
+ 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,
FlatClientProperties.TABBED_PANE_TAB_ROTATION_AUTO);
final JPopupMenu popup = new JPopupMenu();
@@ -471,6 +475,10 @@ static JTabbedPane getJTabbedPane() {
bGroup.add(jcbmi);
popup.add(jcbmi);
}
+ final JButton triggerButton = ellipsisButton(null);
+ triggerButton.addActionListener( e -> popup.show(triggerButton,
+ triggerButton.getWidth() /2, triggerButton.getHeight() /2));
+ tabbed.putClientProperty(FlatClientProperties.TABBED_PANE_TRAILING_COMPONENT, triggerButton);
return tabbed;
}
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 3ba4ddf2..735e28f6 100644
--- a/src/main/java/org/scijava/ui/swing/script/NotesPanel.java
+++ b/src/main/java/org/scijava/ui/swing/script/NotesPanel.java
@@ -110,7 +110,7 @@ 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 notes",
+ if (getDocument().getLength() == 0) GuiUtils.paintEmptyHint(g, this, "Jot down snippets",
"They are saved between sessions");
}
};
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 c02d7b21..f743f419 100644
--- a/src/main/java/org/scijava/ui/swing/script/TextEditor.java
+++ b/src/main/java/org/scijava/ui/swing/script/TextEditor.java
@@ -49,6 +49,8 @@
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
+import java.awt.event.MouseAdapter;
+import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
@@ -89,6 +91,7 @@
import java.util.Objects;
import java.util.Set;
import java.util.function.BiConsumer;
+import java.util.function.IntPredicate;
import java.util.TreeMap;
import java.util.Vector;
import java.util.concurrent.ExecutionException;
@@ -105,6 +108,8 @@
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
+import javax.swing.event.PopupMenuEvent;
+import javax.swing.event.PopupMenuListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.DefaultHighlighter.DefaultHighlightPainter;
@@ -313,6 +318,8 @@ 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_FILL);
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,
@@ -320,13 +327,12 @@ public TextEditor(final Context context) {
pane.setSelectedIndex(index);
closeTab(true);
});
- tabbed.putClientProperty(FlatClientProperties.TABBED_PANE_TRAILING_COMPONENT,
- GuiUtils.newTabButton(() -> newFile.doClick()));
+ installCloseTabsPopup();
+
tree = new FileSystemTree(log);
sideTabs = GuiUtils.getJTabbedPane();
sideTabs.putClientProperty(FlatClientProperties.TABBED_PANE_TAB_AREA_ALIGNMENT,
FlatClientProperties.TABBED_PANE_ALIGN_FILL);
-
filesPanel = new FileSystemTreePanel(tree, context);
filesPanel.setActiveScriptSupplier(() -> {
try {
@@ -2291,6 +2297,80 @@ private void closeTab(final boolean confirm) {
switchTo(index);
}
+ /** Adds the "Close:" section to the top of the tab popup menu */
+ private void installCloseTabsPopup() {
+ final JPopupMenu popup = tabbed.getComponentPopupMenu();
+ final JPopupMenu tmp = new JPopupMenu();
+ GuiUtils.addPopupMenuSeparator(tmp, "Close:");
+ final JMenuItem others = new JMenuItem("Close Others");
+ others.addActionListener(e -> {
+ final int sel = tabbed.getSelectedIndex();
+ closeTabs(i -> i != sel, true);
+ });
+ final JMenuItem right = new JMenuItem("Close Tabs to the Right");
+ right.addActionListener(e -> {
+ final int sel = tabbed.getSelectedIndex();
+ closeTabs(i -> i > sel, true);
+ });
+ 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);
+ final java.awt.Component[] items = tmp.getComponents();
+ for (int i = 0; i < items.length; i++)
+ popup.insert(items[i], i);
+ popup.insert(new JPopupMenu.Separator(), items.length);
+ popup.addPopupMenuListener(new PopupMenuListener() {
+
+ @Override
+ public void popupMenuWillBecomeVisible(final PopupMenuEvent e) {
+ final int n = tabbed.getTabCount();
+ others.setEnabled(n > 1);
+ right.setEnabled(tabbed.getSelectedIndex() < n - 1);
+ }
+
+ @Override
+ public void popupMenuWillBecomeInvisible(final PopupMenuEvent e) {}
+
+ @Override
+ public void popupMenuCanceled(final PopupMenuEvent e) {}
+ });
+ // Right-click acts on the tab under the pointer
+ tabbed.addMouseListener(new MouseAdapter() {
+
+ @Override
+ public void mousePressed(final MouseEvent e) {
+ if (!SwingUtilities.isRightMouseButton(e) && !e.isPopupTrigger()) return;
+ final int i = tabbed.indexAtLocation(e.getX(), e.getY());
+ if (i >= 0) tabbed.setSelectedIndex(i);
+ }
+ });
+ }
+
+ /**
+ * Closes the tabs whose index (evaluated up front) matches the filter. Stops
+ * if the user cancels a save prompt. Never closes the window: a new
+ * document is opened if no tab is left.
+ */
+ private void closeTabs(final IntPredicate filter, final boolean prompt) {
+ final TextEditorTab current = getTab();
+ final List targets = new ArrayList<>();
+ for (int i = 0; i < tabbed.getTabCount(); i++) {
+ if (filter.test(i)) targets.add(getTab(i));
+ }
+ for (final TextEditorTab tab : targets) {
+ final int index = tabbed.indexOfComponent(tab);
+ if (index < 0) continue;
+ tabbed.setSelectedIndex(index);
+ if (prompt && !handleUnsavedChanges()) return;
+ removeTab(index);
+ }
+ if (tabbed.getTabCount() == 0) createNewDocument();
+ else if (tabbed.indexOfComponent(current) >= 0) tabbed.setSelectedComponent(current);
+ }
+
/**
* Handles a vim ex command (typed after ':') which the editor pane does not
* handle itself.
From 29b707989e0bc5e1479565f798f0227a288820a1 Mon Sep 17 00:00:00 2001
From: Tiago Ferreira
Date: Sat, 14 Nov 2026 23:19:19 -0500
Subject: [PATCH 14/41] Integrate vim mode in new statusbar
---
.../org/scijava/ui/swing/script/GuiUtils.java | 7 +++--
.../scijava/ui/swing/script/TextEditor.java | 30 ++++++++++++++++++-
.../ui/swing/script/TextEditorTab.java | 12 +-------
.../ui/swing/script/vim/VimHandler.java | 22 +++++---------
4 files changed, 42 insertions(+), 29 deletions(-)
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 e44fd173..a75b6527 100644
--- a/src/main/java/org/scijava/ui/swing/script/GuiUtils.java
+++ b/src/main/java/org/scijava/ui/swing/script/GuiUtils.java
@@ -330,10 +330,13 @@ static Color secondaryColor() {
static Color accentColor() {
try {
- return UIManager.getColor("Component.accentColor");
+ 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
} catch (final Exception ignored) {
- return Color.ORANGE.darker();
+ // do nothing
}
+ return new Color(0x3E73B9);
}
static boolean isDarkLaF() {
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 f743f419..528a47bd 100644
--- a/src/main/java/org/scijava/ui/swing/script/TextEditor.java
+++ b/src/main/java/org/scijava/ui/swing/script/TextEditor.java
@@ -238,10 +238,11 @@ public class TextEditor extends JFrame implements ActionListener,
private static final String CONSOLE_WRAP_PREFS = "script.editor.ConsoleWrap";
private static final String REPL_WRAP_PREFS = "script.editor.ReplWrap";
private JButton statusPos, statusLang;
- private JToggleButton statusSide, statusBelow, statusRight, statusRepl;
+ private JToggleButton statusSide, statusBelow, statusRight, statusRepl, statusVimToggle;
private int sideLastLocation = -1;
private JMenu languageMenu;
private JLabel statusText;
+ private JLabel statusVim;
private FileSystemTreePanel filesPanel;
private JCheckBoxMenuItem autoSave, wrapLines, tabsEmulated, autoImport,
autocompletion, fallbackAutocompletion, keylessAutocompletion,
@@ -1930,6 +1931,10 @@ private JComponent assembleStatusBar() {
statusText = new JLabel(" ");
statusText.setFont(statusText.getFont().deriveFont(statusText.getFont().getSize2D() * .9f));
//statusText.setMinimumSize(new Dimension(0, 0));
+ statusVim = new JLabel();
+ statusVim.setFont(new Font(Font.MONOSPACED, Font.PLAIN, statusText.getFont().getSize()));
+ statusVim.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 12));
+ statusVim.setVisible(false);
statusPos = new JButton("Ln 1, Col 1") {
private static final long serialVersionUID = 1L;
@@ -2028,6 +2033,11 @@ 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.setToolTipText(vimMode.getToolTipText());
+ statusVimToggle.setFocusable(false);
+ statusVimToggle.addActionListener(e -> vimMode.setState(statusVimToggle.isSelected()));
final JToolBar bar = new JToolBar();
bar.setFloatable(false);
final int gap = 4;
@@ -2038,10 +2048,12 @@ public Dimension getPreferredSize() { // fixed width: neighbors do not move as t
bar.add(Box.createHorizontalStrut(gap));
bar.addSeparator();
bar.add(Box.createHorizontalStrut(gap));
+ bar.add(statusVim);
bar.add(statusText);
bar.add(Box.createHorizontalGlue());
bar.addSeparator();
bar.add(Box.createHorizontalStrut(gap));
+ bar.add(statusVimToggle);
bar.add(statusRepl);
//bar.add(Box.createHorizontalStrut(8));
bar.add(statusPos);
@@ -2187,6 +2199,19 @@ private void updateCaretStatus() {
}
}
+ /** Shows the Vim status of the given tab, if it is the active one */
+ void setVimStatus(final TextEditorTab tab, final String status) {
+ if (statusVim == null || tabbed.getSelectedComponent() != tab) return;
+ statusVim.setText(status == null ? "" : status);
+ statusVim.setVisible(status != null && !status.isEmpty());
+ // Mode text ("-- INSERT --") stands out, command line and messages stay plain
+ final boolean mode = status != null && status.startsWith("-- ");
+ final int style = mode ? Font.BOLD : Font.PLAIN;
+ if (statusVim.getFont().getStyle() != style) statusVim.setFont(statusVim.getFont().deriveFont(style));
+ final Color c = mode ? GuiUtils.accentColor() : UIManager.getColor("Label.foreground");
+ if (c != null) statusVim.setForeground(c);
+ }
+
/** Updates the toggles of the status bar from the state of the active editor */
void syncStatusBar() {
if (statusTab == null || statusWrap == null) return;
@@ -2201,8 +2226,10 @@ void syncStatusBar() {
statusRight.setSelected(shown && !tab.isLayoutBelow());
}
if (statusRepl != null) statusRepl.setSelected(getTab().isREPLEnabled());
+ if (statusVimToggle != null) statusVimToggle.setSelected(pane.isVimEnabled());
statusLang.setText(languageLabel(pane.getCurrentLanguage()));
updateCaretStatus();
+ setVimStatus(getTab(), pane.getVimHandler().getStatus());
statusTab.setText((pane.getTabsEmulated() ? "Spaces: " : "Tab: ") + pane.getTabSize());
} catch (final RuntimeException ignored) {
// no editor yet
@@ -2759,6 +2786,7 @@ public TextEditorTab open(final File file) {
tab.editorPane.loadPreferences();
tab.applyConsoleColors(); // the theme was just applied to the editor pane
addDefaultAccelerators(tab.editorPane);
+ if (vimMode != null) tab.editorPane.setVimEnabled(vimMode.getState()); // global setting
} else {
// the Edit menu can only be populated after an editor pane exists, as it reads
// actions from its input map. We will built it here, if it has not been assembled
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 08a1a328..fdaa4c2e 100644
--- a/src/main/java/org/scijava/ui/swing/script/TextEditorTab.java
+++ b/src/main/java/org/scijava/ui/swing/script/TextEditorTab.java
@@ -32,7 +32,6 @@
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
-import java.awt.Font;
import java.awt.Insets;
import java.awt.geom.RoundRectangle2D;
import java.awt.FlowLayout;
@@ -93,7 +92,6 @@ 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. */
- private final JLabel vimStatus = new JLabel(" ");
protected final JToggleButton updownarrows = new JToggleButton();
protected final JScrollPane scroll;
/** True iff the console is showing errors only. */
@@ -320,15 +318,7 @@ with a modifier (e.g., %s) they move the caret within a multi-line prompt.
final JPanel holder = new JPanel(new BorderLayout());
holder.add(editorPane.wrappedInScrollbars());
holder.add(es, BorderLayout.LINE_END);
- holder.add(vimStatus, BorderLayout.PAGE_END);
- vimStatus.setFont(new Font(Font.MONOSPACED, Font.PLAIN, vimStatus.getFont().getSize()));
- vimStatus.setBorder(BorderFactory.createEmptyBorder(2, 4, 2, 4));
- vimStatus.setVisible(false);
- editorPane.getVimHandler().setStatusListener(status -> {
- vimStatus.setVisible(status != null);
- // Note: a blank keeps the line from collapsing.
- vimStatus.setText(status == null || status.isEmpty() ? " " : status);
- });
+ editorPane.getVimHandler().setStatusListener(status -> textEditor.setVimStatus(this, status));
editorPane.getVimHandler().setExHandler(textEditor::handleVimCommand);
super.setLeftComponent(holder);
super.setRightComponent(screenAndPromptSplit);
diff --git a/src/main/java/org/scijava/ui/swing/script/vim/VimHandler.java b/src/main/java/org/scijava/ui/swing/script/vim/VimHandler.java
index 218ca738..5431a07a 100644
--- a/src/main/java/org/scijava/ui/swing/script/vim/VimHandler.java
+++ b/src/main/java/org/scijava/ui/swing/script/vim/VimHandler.java
@@ -241,21 +241,13 @@ public String getStatus() {
private String modeStatus() {
if (mode == Mode.COMMAND_LINE) return cmdLineType + cmdLine.toString();
if (message != null) return message;
- final String modeText;
- switch (mode) {
- case INSERT:
- modeText = "-- INSERT --";
- break;
- case VISUAL:
- modeText = "-- VISUAL --";
- break;
- case VISUAL_LINE:
- modeText = "-- VISUAL LINE --";
- break;
- default:
- modeText = "";
- }
- if (pending.length() == 0) return modeText;
+ final String modeText = switch (mode) {
+ case INSERT -> "-- INSERT --";
+ case VISUAL -> "-- VISUAL --";
+ case VISUAL_LINE -> "-- VISUAL LINE --";
+ default -> "";
+ };
+ if (pending.isEmpty()) return modeText;
return modeText + (modeText.isEmpty() ? "" : " ") + printable(pending);
}
From c777a7669e77a3d236b9f1e264dcb9ea0533dec8 Mon Sep 17 00:00:00 2001
From: Tiago Ferreira
Date: Sun, 15 Nov 2026 00:05:20 -0500
Subject: [PATCH 15/41] Bugfix: Template scripts being opened as modified
---
.../java/org/scijava/ui/swing/script/EditorPane.java | 9 +++++++++
.../java/org/scijava/ui/swing/script/TextEditor.java | 2 ++
2 files changed, 11 insertions(+)
diff --git a/src/main/java/org/scijava/ui/swing/script/EditorPane.java b/src/main/java/org/scijava/ui/swing/script/EditorPane.java
index 846ebbdd..82305402 100644
--- a/src/main/java/org/scijava/ui/swing/script/EditorPane.java
+++ b/src/main/java/org/scijava/ui/swing/script/EditorPane.java
@@ -481,6 +481,15 @@ public boolean fileChanged() {
return modifyCount != 0;
}
+ /**
+ * Marks the current content as the unmodified baseline and clears the undo
+ * history. For content loaded after the pane was created (e.g., templates)
+ */
+ void resetModified() {
+ discardAllEdits();
+ modifyCount = 0;
+ }
+
@Override
public void insertUpdate(final DocumentEvent e) {
modified();
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 528a47bd..483ae2c0 100644
--- a/src/main/java/org/scijava/ui/swing/script/TextEditor.java
+++ b/src/main/java/org/scijava/ui/swing/script/TextEditor.java
@@ -1691,6 +1691,7 @@ public void loadTemplate(final URL url, final ScriptLanguage language) {
}
final String path = url.getPath();
setEditorPaneFileName(path.substring(path.lastIndexOf('/') + 1));
+ getEditorPane().resetModified();
}
catch (final Exception e) {
log.error(e);
@@ -1707,6 +1708,7 @@ public void createNewDocument(final String title, final String text) {
final EditorPane editorPane = getEditorPane();
editorPane.setText(text);
setNewDocumentLanguageAndFileName(editorPane, title);
+ editorPane.resetModified();
updateLanguageMenu(editorPane.getCurrentLanguage());
}
From 4b6c0f7c433e80d060277ed8b50eac90f2b5338b Mon Sep 17 00:00:00 2001
From: Tiago Ferreira
Date: Sun, 15 Nov 2026 09:49:41 -0500
Subject: [PATCH 16/41] Adopt new modernized themes and auto-synchronize theme
on L&F changes
---
pom.xml | 9 +--
.../scijava/ui/swing/script/EditorPane.java | 8 +-
.../ui/swing/script/OutlineTreePanel.java | 9 ++-
.../scijava/ui/swing/script/TextEditor.java | 64 +++++++++++----
.../ui/swing/script/themes/scijava-dark.xml | 78 +++++++++++++++++++
.../ui/swing/script/themes/scijava-light.xml | 76 ++++++++++++++++++
.../swing/script/ScriptEditorTestDrive.java | 4 +
7 files changed, 222 insertions(+), 26 deletions(-)
create mode 100644 src/main/resources/org/scijava/ui/swing/script/themes/scijava-dark.xml
create mode 100644 src/main/resources/org/scijava/ui/swing/script/themes/scijava-light.xml
diff --git a/pom.xml b/pom.xml
index de1f8c50..90afafff 100644
--- a/pom.xml
+++ b/pom.xml
@@ -164,6 +164,10 @@
org.scijava
scripting-java
+
+ org.scijava
+ scijava-ui-swing
+
@@ -194,11 +198,6 @@
parsington
test
-
- org.scijava
- scijava-ui-swing
- test
-
org.scijava
scripting-groovy
diff --git a/src/main/java/org/scijava/ui/swing/script/EditorPane.java b/src/main/java/org/scijava/ui/swing/script/EditorPane.java
index 82305402..bb50394e 100644
--- a/src/main/java/org/scijava/ui/swing/script/EditorPane.java
+++ b/src/main/java/org/scijava/ui/swing/script/EditorPane.java
@@ -1124,16 +1124,14 @@ public void loadPreferences() {
/**
* Applies a theme to this pane.
*
- * @param theme either "default", "dark", "druid", "eclipse", "idea", "monokai",
- * "vs"
+ * @param theme either "default", "scijava-light", "scijava-dark", "druid",
+ * "eclipse", "idea", "monokai", "vs"
* @throws IllegalArgumentException If {@code theme} is not a valid option, or
* the resource could not be loaded
*/
public void applyTheme(final String theme) throws IllegalArgumentException {
try {
- // If dark L&F and using the default theme, assume 'dark' theme
- final boolean dark = DEFAULT_THEME.equals(theme) && GuiUtils.isDarkLaF();
- applyTheme(TextEditor.getTheme(dark ? "dark" : theme));
+ applyTheme(TextEditor.getTheme(theme)); // aliases such as "default" are resolved there
} catch (final Exception ex) {
throw new IllegalArgumentException(ex);
}
diff --git a/src/main/java/org/scijava/ui/swing/script/OutlineTreePanel.java b/src/main/java/org/scijava/ui/swing/script/OutlineTreePanel.java
index 6a6209b7..e2a00eb9 100644
--- a/src/main/java/org/scijava/ui/swing/script/OutlineTreePanel.java
+++ b/src/main/java/org/scijava/ui/swing/script/OutlineTreePanel.java
@@ -119,8 +119,13 @@ private void setPopupMenu(final JTree tree, final EditorPane pane) {
popup.add(jcmi1);
final JCheckBoxMenuItem jcmi2 = new JCheckBoxMenuItem("Sort Elements", sorted);
jcmi2.addItemListener(e -> {
- sorted = jcmi2.isSelected();
- ((AbstractSourceTree) tree).setSorted(sorted); // will refresh
+ try {
+ sorted = jcmi2.isSelected();
+ ((AbstractSourceTree) tree).setSorted(sorted); // will refresh
+ } catch (final Throwable throwable) {
+ GuiUtils.error(OutlineTreePanel.this, "Outline could not be sorted.");
+ jcmi2.setSelected(sorted = false);
+ }
});
popup.add(jcmi2);
popup.addSeparator();
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 483ae2c0..95ed807d 100644
--- a/src/main/java/org/scijava/ui/swing/script/TextEditor.java
+++ b/src/main/java/org/scijava/ui/swing/script/TextEditor.java
@@ -53,6 +53,7 @@
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
+import java.beans.PropertyChangeListener;
import java.io.BufferedReader;
import java.io.CharArrayWriter;
import java.io.File;
@@ -153,6 +154,7 @@
import org.scijava.thread.ThreadService;
import org.scijava.ui.CloseConfirmable;
import org.scijava.ui.UIService;
+import org.scijava.ui.swing.laf.OptionsLookAndFeel;
import org.scijava.ui.swing.script.autocompletion.ClassUtil;
import org.scijava.ui.swing.script.commands.ChooseFontSize;
import org.scijava.ui.swing.script.commands.ChooseTabSize;
@@ -185,8 +187,11 @@ public class TextEditor extends JFrame implements ActionListener,
ChangeListener, CloseConfirmable, DocumentListener
{
+ /* default themes */
+ private static final String SCIJAVA_LIGHT = "scijava-light";
+ private static final String SCIJAVA_DARK = "scijava-dark";
+
private static final Set TEMPLATE_PATHS = new HashSet<>();
-// private static final int BORDER_SIZE = 4;
public static final String AUTO_IMPORT_PREFS = "script.editor.AutoImport";
public static final String WINDOW_HEIGHT = "script.editor.height";
public static final String WINDOW_WIDTH = "script.editor.width";
@@ -259,6 +264,17 @@ public class TextEditor extends JFrame implements ActionListener,
private boolean respectAutoImports;
private String activeTheme;
+ // Re-resolves the automatic theme when the application switches between light and dark
+ private final PropertyChangeListener lookAndFeelListener = evt -> {
+ if (!"lookAndFeel".equals(evt.getPropertyName()) || !"default".equals(activeTheme)) return;
+ SwingUtilities.invokeLater(() -> {
+ try {
+ applyTheme("default", false);
+ } catch (final IllegalArgumentException ignored) {
+ // keep the current colors
+ }
+ });
+ };
private int[] panePositions;
@@ -824,6 +840,7 @@ public TextEditor(final Context context) {
addWindowListener(new WindowAdapter() {
@Override
public void windowOpened(final WindowEvent e) {
+ UIManager.addPropertyChangeListener(lookAndFeelListener);
showTemporaryStatus("Tip: press " + cmdPalette.getAcceleratorString()
+ " to search all commands and actions", 10000);
}
@@ -831,6 +848,7 @@ public void windowOpened(final WindowEvent e) {
@Override
public void windowClosing(final WindowEvent e) {
if (!confirmClose()) return;
+ UIManager.removePropertyChangeListener(lookAndFeelListener);
tree.destroy();
// Necessary to prevent memory leaks
for (final DragSourceListener l : dragSource.getDragSourceListeners()) {
@@ -894,9 +912,7 @@ public void componentResized(final ComponentEvent e) {
open(null);
final EditorPane editorPane = getEditorPane();
- // If dark L&F and using the default theme, assume 'dark' theme
- applyTheme((GuiUtils.isDarkLaF() && "default".equals(editorPane.themeName())) ? "dark" : editorPane.themeName(),
- true);
+ applyTheme(editorPane.themeName(), true);
// Ensure font sizes are consistent across all panels
setFontSize(getEditorPane().getFontSize());
@@ -2434,11 +2450,12 @@ private void setVimMode(final boolean enabled) {
private JMenu applyThemeMenu() {
final LinkedHashMap map = new LinkedHashMap<>();
- map.put("Default", "default");
- map.put("-", "-");
- map.put("Dark", "dark");
- map.put("Druid", "druid");
- map.put("Monokai", "monokai");
+ map.put("Automatic (Light or Dark)", "default");
+ map.put("SciJava Light", SCIJAVA_LIGHT);
+ map.put("SciJava Dark", SCIJAVA_DARK);
+ map.put("-", "Legacy:");
+ map.put("Druid (Dark)", "druid");
+ map.put("Monokai (Dark)", "monokai");
map.put("Eclipse (Light)", "eclipse");
map.put("IntelliJ (Light)", "idea");
map.put("Visual Studio (Light)", "vs");
@@ -2446,7 +2463,7 @@ private JMenu applyThemeMenu() {
final JMenu menu = new JMenu("Theme");
map.forEach((k, v) -> {
if ("-".equals(k)) {
- menu.addSeparator();
+ GuiUtils.addMenubarSeparator(menu, v);
return;
}
final JRadioButtonMenuItem item = new JRadioButtonMenuItem(k);
@@ -2457,6 +2474,9 @@ private JMenu applyThemeMenu() {
applyTheme(v, false);
// make the choice available for the next tab
prefService.put(EditorPane.class, EditorPane.THEME_PREFS, v);
+ if (!"default".equals(v) && GuiUtils.isDark(getEditorPane().getBackground()) != GuiUtils.isDarkLaF())
+ showTemporaryStatus("Editor theme differs from the application's. "
+ + "Use Theme > Application Look & Feel... to match", 8000);
} catch (final IllegalArgumentException ex) {
error("Theme could not be loaded. See Console for details.");
ex.printStackTrace();
@@ -2464,14 +2484,21 @@ private JMenu applyThemeMenu() {
});
menu.add(item);
});
+ GuiUtils.addMenubarSeparator(menu, "Application:");
+ final JMenuItem laf = new JMenuItem("Application Look & Feel...");
+ laf.setToolTipText("Opens the options for the look and feel (light/dark) of the application");
+ laf.addActionListener(e -> commandService.run(OptionsLookAndFeel.class, true));
+ menu.add(laf);
return menu;
}
/**
* Applies a theme to all the panes of this editor.
*
- * @param theme either "default", "dark", "druid", "eclipse", "idea", "monokai",
- * "vs"
+ * @param theme either "default" (SciJava light or dark, matching the look and
+ * feel), "scijava-light", "scijava-dark", "druid", "eclipse",
+ * "idea", "monokai", "vs". The legacy "dark" is an alias of
+ * "scijava-dark"
* @throws IllegalArgumentException If {@code theme} is not a valid option, or
* the resource could not be loaded
*/
@@ -2503,10 +2530,19 @@ private void applyTheme(final String theme, final boolean updateMenus) throws Il
if (updateMenus) updateThemeControls(theme);
}
+ /** Resolves aliases: "default" follows the look and feel, "dark" is the legacy name */
+ private static String resolveTheme(final String theme) {
+ if ("dark".equals(theme)) return SCIJAVA_DARK;
+ if ("default".equals(theme)) return GuiUtils.isDarkLaF() ? SCIJAVA_DARK : SCIJAVA_LIGHT;
+ return theme;
+ }
+
static Theme getTheme(final String theme) throws IllegalArgumentException {
try {
- return Theme
- .load(TextEditor.class.getResourceAsStream("/org/fife/ui/rsyntaxtextarea/themes/" + theme + ".xml"));
+ final String name = resolveTheme(theme);
+ final InputStream in = name.startsWith("scijava-") ? TextEditor.class.getResourceAsStream("themes/" + name + ".xml")
+ : TextEditor.class.getResourceAsStream("/org/fife/ui/rsyntaxtextarea/themes/" + name + ".xml");
+ return Theme.load(in);
} catch (final Exception ex) {
throw new IllegalArgumentException(ex);
}
diff --git a/src/main/resources/org/scijava/ui/swing/script/themes/scijava-dark.xml b/src/main/resources/org/scijava/ui/swing/script/themes/scijava-dark.xml
new file mode 100644
index 00000000..6c41341e
--- /dev/null
+++ b/src/main/resources/org/scijava/ui/swing/script/themes/scijava-dark.xml
@@ -0,0 +1,78 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/main/resources/org/scijava/ui/swing/script/themes/scijava-light.xml b/src/main/resources/org/scijava/ui/swing/script/themes/scijava-light.xml
new file mode 100644
index 00000000..84916219
--- /dev/null
+++ b/src/main/resources/org/scijava/ui/swing/script/themes/scijava-light.xml
@@ -0,0 +1,76 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/test/java/org/scijava/ui/swing/script/ScriptEditorTestDrive.java b/src/test/java/org/scijava/ui/swing/script/ScriptEditorTestDrive.java
index 97e13778..ae2f1c0d 100644
--- a/src/test/java/org/scijava/ui/swing/script/ScriptEditorTestDrive.java
+++ b/src/test/java/org/scijava/ui/swing/script/ScriptEditorTestDrive.java
@@ -29,6 +29,9 @@
package org.scijava.ui.swing.script;
+import com.formdev.flatlaf.FlatDarkLaf;
+import com.formdev.flatlaf.FlatLightLaf;
+
/**
* Interactive test for the script editor.
*
@@ -41,6 +44,7 @@
*/
public class ScriptEditorTestDrive {
public static void main(String[] args) throws Exception {
+ FlatDarkLaf.setup();
Main.launch("Groovy");
}
}
From 6baf9c537e694f128767dd7d701c8da9d43074dd Mon Sep 17 00:00:00 2001
From: Tiago Ferreira
Date: Sun, 15 Nov 2026 10:56:34 -0500
Subject: [PATCH 17/41] Update to latest Rsyntaxtextarea version
---
pom.xml | 5 +++++
.../java/org/scijava/ui/swing/script/EditorPaneActions.java | 4 ++--
.../java/org/scijava/ui/swing/script/vim/VimHandler.java | 3 ++-
3 files changed, 9 insertions(+), 3 deletions(-)
diff --git a/pom.xml b/pom.xml
index 90afafff..ac1ebdea 100644
--- a/pom.xml
+++ b/pom.xml
@@ -148,6 +148,10 @@
sign,deploy-to-scijava
+
+
+ 3.8
+ 4.0.1
@@ -173,6 +177,7 @@
com.fifesoft
rsyntaxtextarea
+ ${rsyntaxtextarea.version}
com.fifesoft
diff --git a/src/main/java/org/scijava/ui/swing/script/EditorPaneActions.java b/src/main/java/org/scijava/ui/swing/script/EditorPaneActions.java
index 841b6553..ef40f275 100644
--- a/src/main/java/org/scijava/ui/swing/script/EditorPaneActions.java
+++ b/src/main/java/org/scijava/ui/swing/script/EditorPaneActions.java
@@ -44,8 +44,8 @@
import javax.swing.text.Element;
import javax.swing.text.Segment;
+import org.fife.ui.rsyntaxtextarea.OS;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextAreaEditorKit;
-import org.fife.ui.rsyntaxtextarea.RSyntaxUtilities;
import org.fife.ui.rtextarea.RTextArea;
import org.fife.ui.rtextarea.RecordableTextAction;
@@ -79,7 +79,7 @@ public EditorPaneActions(final EditorPane editorPane) {
*/
// toggle comments
- if (RSyntaxUtilities.OS_LINUX == RSyntaxUtilities.getOS()) {
+ if (OS.get() == OS.LINUX) {
// See note on RSyntaxTextAreaDefaultInputMap: Ctrl+/ types '/' on linux!
map.put(KeyStroke.getKeyStroke(KeyEvent.VK_SLASH, defaultMod + shift), rstaToggleCommentAction);
}
diff --git a/src/main/java/org/scijava/ui/swing/script/vim/VimHandler.java b/src/main/java/org/scijava/ui/swing/script/vim/VimHandler.java
index 5431a07a..a6bc32f6 100644
--- a/src/main/java/org/scijava/ui/swing/script/vim/VimHandler.java
+++ b/src/main/java/org/scijava/ui/swing/script/vim/VimHandler.java
@@ -58,6 +58,7 @@
import org.fife.ui.rtextarea.CaretStyle;
import org.fife.ui.rtextarea.ConfigurableCaret;
import org.fife.ui.rtextarea.RTextArea;
+import org.fife.ui.rtextarea.TextMode;
/**
* Modal, vim-style key handling for an {@link RTextArea}.
@@ -2010,7 +2011,7 @@ private void updateCaretStyle() {
final boolean block = enabled && mode != Mode.INSERT;
final CaretStyle style = block ? CaretStyle.BLOCK_STYLE
: originalCaretStyle;
- if (style != null) area.setCaretStyle(RTextArea.INSERT_MODE, style);
+ if (style != null) area.setCaretStyle(TextMode.INSERT, style);
}
private boolean areCtrlKeysFree() {
From d0a4ffca5d13ff22e6dd735dd5dbee3c71141f09 Mon Sep 17 00:00:00 2001
From: Tiago Ferreira
Date: Sun, 15 Nov 2026 11:04:43 -0500
Subject: [PATCH 18/41] Catch-up with new RSyntaxTextArea API
- Some of our gutter customizations/hacks are no longer needed
- Use the new RowListener to monitor bookmarks
- It seems MatlabTokenMaker now needs declared bracket pairs
- Our themes can now use fold indicator background
- Our hacks for non-executable syntax (markdown, etc.) are no longer needed
are now all handled by FileTypeUtil
- Fix a bug: Files whose extension has no SciJava language (data.json, notes.md)
were being renamed to .txt without reason
- Trade-off:
A "New_" tab w/ "None" language can no longer be given a syntax by hand. T
The workaround is to savein or naming (e.g. x.json): it will trigger the new fallback
---
.../ui/swing/script/BookmarksPanel.java | 2 +-
.../scijava/ui/swing/script/EditorPane.java | 130 ++++++++----------
.../scijava/ui/swing/script/GutterUtils.java | 2 -
.../scijava/ui/swing/script/TextEditor.java | 5 +
.../ui/swing/script/TextEditorTab.java | 1 +
.../script/highliters/MatlabTokenMaker.java | 5 +
.../ui/swing/script/themes/scijava-dark.xml | 2 +-
.../ui/swing/script/themes/scijava-light.xml | 2 +-
8 files changed, 69 insertions(+), 80 deletions(-)
diff --git a/src/main/java/org/scijava/ui/swing/script/BookmarksPanel.java b/src/main/java/org/scijava/ui/swing/script/BookmarksPanel.java
index 616249f1..90440575 100644
--- a/src/main/java/org/scijava/ui/swing/script/BookmarksPanel.java
+++ b/src/main/java/org/scijava/ui/swing/script/BookmarksPanel.java
@@ -65,7 +65,7 @@
class BookmarksPanel extends JPanel {
private static final long serialVersionUID = 1L;
- private static final int REFRESH_DELAY_MS = 750;
+ private static final int REFRESH_DELAY_MS = 1500;
private static final int TEXT_MAX_CHARS = 100;
private final Supplier> source;
diff --git a/src/main/java/org/scijava/ui/swing/script/EditorPane.java b/src/main/java/org/scijava/ui/swing/script/EditorPane.java
index bb50394e..9ce08581 100644
--- a/src/main/java/org/scijava/ui/swing/script/EditorPane.java
+++ b/src/main/java/org/scijava/ui/swing/script/EditorPane.java
@@ -54,14 +54,11 @@
import java.util.regex.Pattern;
import javax.swing.Action;
-import javax.swing.ButtonGroup;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
-import javax.swing.JRadioButtonMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JViewport;
-import javax.swing.MenuElement;
import javax.swing.ToolTipManager;
import javax.swing.UIManager;
import javax.swing.event.DocumentEvent;
@@ -72,6 +69,7 @@
import org.fife.rsta.ac.LanguageSupport;
import org.fife.rsta.ac.LanguageSupportFactory;
+import org.fife.ui.rsyntaxtextarea.FileTypeUtil;
import org.fife.ui.rsyntaxtextarea.RSyntaxDocument;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import org.fife.ui.rsyntaxtextarea.Style;
@@ -80,6 +78,8 @@
import org.fife.ui.rsyntaxtextarea.parser.TaskTagParser;
import org.fife.ui.rtextarea.Gutter;
import org.fife.ui.rtextarea.GutterIconInfo;
+import org.fife.ui.rtextarea.IconRowEvent;
+import org.fife.ui.rtextarea.IconRowListener;
import org.fife.ui.rtextarea.RTextArea;
import org.fife.ui.rtextarea.RTextScrollPane;
import org.fife.ui.rtextarea.RecordableTextAction;
@@ -112,6 +112,8 @@ public class EditorPane extends RSyntaxTextArea implements DocumentListener {
private long fileLastModified;
private ScriptLanguage currentLanguage;
private Gutter gutter;
+ private Runnable bookmarkListener;
+ private boolean quietBookmarks;
private int modifyCount;
private boolean undoInProgress;
@@ -121,7 +123,6 @@ public class EditorPane extends RSyntaxTextArea implements DocumentListener {
private boolean autoCompletionWithoutKey;
private String supportStatus;
private final ErrorParser errorHighlighter;
- private final JMenu noneLangSyntaxMenu;
private final EditorPaneActions actions;
private final VimHandler vim = new VimHandler(this);
@@ -189,7 +190,6 @@ public void hyperlinkUpdate(final HyperlinkEvent hle) {
getActionMap().put(EditorPaneActions.selectionPreviousWordAction,
wordMovement("Prev-Word-Select-Action", -1, true));
- noneLangSyntaxMenu = geSyntaxForNoneLang();
installCustomPopupMenu();
ToolTipManager.sharedInstance().registerComponent(this);
@@ -283,10 +283,9 @@ private void installCustomPopupMenu() {
GuiUtils.addPopupMenuSeparator(popup, "Occurrences:");
popup.add(getMenuItem("Next Occurrence", EditorPaneActions.rtaNextOccurrenceAction, false));
popup.add(getMenuItem("Previous Occurrence", EditorPaneActions.rtaPrevOccurrenceAction, false));
- GuiUtils.addPopupMenuSeparator(popup, "Links & Syntax:");
+ GuiUtils.addPopupMenuSeparator(popup, "Links:");
popup.add(new OpenLinkUnderCursor().getMenuItem());
popup.add(new SearchWebOnSelectedText().getMenuItem());
- popup.add(noneLangSyntaxMenu);
super.setPopupMenu(popup);
}
@@ -298,70 +297,10 @@ private JMenuItem getMenuItem(final String label, final String actionID, final b
return jmi;
}
- private JMenu geSyntaxForNoneLang() {
- final JMenu menu = new JMenu("Non-Executable Syntax");
- menu.setToolTipText("Markup languages when scripting language is none");
- final ButtonGroup bg = new ButtonGroup();
- menu.add(getSyntaxItem(bg, "None", SYNTAX_STYLE_NONE));
- bg.getElements().nextElement().setSelected(true); //select none
- menu.addSeparator();
- menu.add(getSyntaxItem(bg, "BAT", SYNTAX_STYLE_WINDOWS_BATCH));
- menu.add(getSyntaxItem(bg, "CSS", SYNTAX_STYLE_CSS));
- menu.add(getSyntaxItem(bg, "Dockerfile", SYNTAX_STYLE_DOCKERFILE));
- menu.add(getSyntaxItem(bg, "HTML", SYNTAX_STYLE_HTML));
- menu.add(getSyntaxItem(bg, "JSON", SYNTAX_STYLE_JSON));
- menu.add(getSyntaxItem(bg, "Kotlin", SYNTAX_STYLE_KOTLIN));
- menu.add(getSyntaxItem(bg, "Makefile", SYNTAX_STYLE_MAKEFILE));
- menu.add(getSyntaxItem(bg, "Markdown", SYNTAX_STYLE_MARKDOWN));
- menu.add(getSyntaxItem(bg, "SH", SYNTAX_STYLE_UNIX_SHELL));
- menu.add(getSyntaxItem(bg, "XML", SYNTAX_STYLE_XML));
- menu.add(getSyntaxItem(bg, "YAML", SYNTAX_STYLE_YAML));
- return menu;
- }
-
- private JMenuItem getSyntaxItem(final ButtonGroup bg, final String label, final String syntaxId) {
- final JRadioButtonMenuItem item = new JRadioButtonMenuItem(label);
- bg.add(item);
- item.addActionListener(e -> {
- if (getCurrentLanguage() == null) {
- setSyntaxEditingStyle(syntaxId);
- } else {
- error("Non-executable syntaxes can only be applied when scripting language is 'None'.");
- bg.getElements().nextElement().setSelected(true); //select none
- setSyntaxEditingStyle(SYNTAX_STYLE_NONE);
- }
- });
- return item;
- }
-
void error(final String message) {
GuiUtils.error(this, message);
}
- private void updateNoneLangSyntaxMenu(final ScriptLanguage language) {
- noneLangSyntaxMenu.setEnabled(language == null);
- if (language == null) {
- JRadioButtonMenuItem defaultChoice = null;
- try {
- for (final MenuElement me : noneLangSyntaxMenu.getSubElements()) {
- if (me instanceof JRadioButtonMenuItem) {
- final JRadioButtonMenuItem rb = ((JRadioButtonMenuItem) me);
- final String choice = rb.getActionCommand();
- if (getSyntaxEditingStyle().equals(choice)) {
- rb.setSelected(true);
- return;
- }
- if (SYNTAX_STYLE_NONE.equals(choice))
- defaultChoice = rb;
- }
- }
- defaultChoice.setSelected(true);
- } catch (final Exception ignored) {
- // do nothing
- }
- }
- }
-
@Override
public void setTabSize(final int width) {
if (getTabSize() != width) super.setTabSize(width);
@@ -386,12 +325,42 @@ public RTextScrollPane wrappedInScrollbars() {
GuiUtils.flattenScrollBars(sp);
gutter = sp.getGutter();
gutter.setBookmarkingEnabled(true);
- gutter.setShowCollapsedRegionToolTips(true);
gutter.setFoldIndicatorEnabled(true);
- GutterUtils.updateIcons(gutter);
+ updateGutterIcons();
+ gutter.addIconRowListener(new IconRowListener() {
+
+ @Override
+ public void bookmarkAdded(final IconRowEvent e) {
+ bookmarksChanged();
+ }
+
+ @Override
+ public void bookmarkRemoved(final IconRowEvent e) {
+ bookmarksChanged();
+ }
+ });
return sp;
}
+ /** Sets the action to run when a bookmark is added or removed */
+ void setBookmarkListener(final Runnable listener) {
+ bookmarkListener = listener;
+ }
+
+ private void bookmarksChanged() {
+ if (!quietBookmarks && bookmarkListener != null) bookmarkListener.run();
+ }
+
+ // Re-creating the icons toggles existing bookmarks, which is not a change
+ private void updateGutterIcons() {
+ quietBookmarks = true;
+ try {
+ GutterUtils.updateIcons(gutter);
+ } finally {
+ quietBookmarks = false;
+ }
+ }
+
RecordableTextAction wordMovement(final String id, final int direction, final boolean select) {
return new RecordableTextAction(id) {
private static final long serialVersionUID = 1L;
@@ -718,8 +687,14 @@ protected String getFileName() {
* @see #setLanguage(ScriptLanguage, boolean)
*/
protected void setLanguageByFileName(final String name) {
- setLanguage(scriptService.getLanguageByExtension(FileUtils
- .getExtension(name)));
+ final ScriptLanguage language = scriptService.getLanguageByExtension(FileUtils
+ .getExtension(name));
+ setLanguage(language, false, language != null);
+ if (language == null) {
+ // Not executable: highlight only, and keep the file name as is
+ final String style = FileTypeUtil.get().guessContentType(new File(name));
+ if (style != null && !SYNTAX_STYLE_NONE.equals(style)) setSyntaxEditingStyle(style);
+ }
}
/**
@@ -744,6 +719,12 @@ protected void setLanguage(final ScriptLanguage language) {
*/
protected void setLanguage(final ScriptLanguage language,
final boolean addHeader)
+ {
+ setLanguage(language, addHeader, true);
+ }
+
+ private void setLanguage(final ScriptLanguage language,
+ final boolean addHeader, final boolean renameFile)
{
// uninstall existing language support.
LanguageSupport support =
@@ -767,7 +748,7 @@ protected void setLanguage(final ScriptLanguage language,
}
if (fallBackBaseName != null && fallBackBaseName.endsWith(".txt")) fallBackBaseName =
fallBackBaseName.substring(0, fallBackBaseName.length() - 4);
- if (curFile != null) {
+ if (renameFile && curFile != null) {
String name = curFile.getName();
final String ext = "." + FileUtils.getExtension(name);
if (!defaultExtension.equals(ext)) {
@@ -800,7 +781,6 @@ protected void setLanguage(final ScriptLanguage language,
setText(header += getText());
}
- updateNoneLangSyntaxMenu(language);
if ("None".equals(languageName) ) {
supportStatus = "Active language: None";
return; // no need to update console any further
@@ -941,7 +921,7 @@ public void increaseFontSize(final float factor) {
if (gutter != null) {
final float lnSize = size * 0.8f;
gutter.setLineNumberFont(font.deriveFont(lnSize));
- GutterUtils.updateIcons(gutter);
+ updateGutterIcons();
}
Component parent = getParent();
if (parent instanceof JViewport) {
@@ -1146,7 +1126,7 @@ private void applyTheme(final Theme th) throws IllegalArgumentException {
final float existingFontSize = getFontSize();
th.apply(this);
setFontSize(existingFontSize);
- GutterUtils.updateIcons(gutter);
+ updateGutterIcons();
}
public String loadFolders() {
diff --git a/src/main/java/org/scijava/ui/swing/script/GutterUtils.java b/src/main/java/org/scijava/ui/swing/script/GutterUtils.java
index 5e640a20..32e2450d 100644
--- a/src/main/java/org/scijava/ui/swing/script/GutterUtils.java
+++ b/src/main/java/org/scijava/ui/swing/script/GutterUtils.java
@@ -43,9 +43,7 @@ public class GutterUtils {
GutterUtils(final Gutter gutter) {
this.gutter = gutter;
- gutter.setSpacingBetweenLineNumbersAndFoldIndicator(0);
//gutter.setFoldIndicatorStyle(org.fife.ui.rtextarea.FoldIndicatorStyle.MODERN); // DEFAULT
- gutter.setShowCollapsedRegionToolTips(true);
}
private ImageIcon getBookmarkIcon() {
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 95ed807d..f9d02adc 100644
--- a/src/main/java/org/scijava/ui/swing/script/TextEditor.java
+++ b/src/main/java/org/scijava/ui/swing/script/TextEditor.java
@@ -2690,6 +2690,11 @@ private void goToBookmark(final Bookmark bookmark) {
bookmark.setCaret();
}
+ /** Brings the Bookmarks panel up to date after a bookmark was added or removed */
+ void bookmarksChanged() {
+ if (bookmarksPanel != null) bookmarksPanel.refresh();
+ }
+
/** Shows the bookmarks side panel, listing bookmarks of all open tabs. */
public void listBookmarks() {
if (!SwingUtilities.isEventDispatchThread()) {
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 fdaa4c2e..57b1e3a3 100644
--- a/src/main/java/org/scijava/ui/swing/script/TextEditorTab.java
+++ b/src/main/java/org/scijava/ui/swing/script/TextEditorTab.java
@@ -320,6 +320,7 @@ with a modifier (e.g., %s) they move the caret within a multi-line prompt.
holder.add(es, BorderLayout.LINE_END);
editorPane.getVimHandler().setStatusListener(status -> textEditor.setVimStatus(this, status));
editorPane.getVimHandler().setExHandler(textEditor::handleVimCommand);
+ editorPane.setBookmarkListener(textEditor::bookmarksChanged);
super.setLeftComponent(holder);
super.setRightComponent(screenAndPromptSplit);
GuiUtils.installSplitHandle(bar, this); // no divider in the "below" layout: the toolbar is the handle
diff --git a/src/main/java/org/scijava/ui/swing/script/highliters/MatlabTokenMaker.java b/src/main/java/org/scijava/ui/swing/script/highliters/MatlabTokenMaker.java
index 9bae015b..0b0c41a0 100644
--- a/src/main/java/org/scijava/ui/swing/script/highliters/MatlabTokenMaker.java
+++ b/src/main/java/org/scijava/ui/swing/script/highliters/MatlabTokenMaker.java
@@ -77,6 +77,11 @@
*/
public class MatlabTokenMaker extends AbstractJFlexTokenMaker {
+ @Override
+ public String getBracketPairs() {
+ return "()[]{}";
+ }
+
/** This character denotes the end of file */
public static final int YYEOF = -1;
diff --git a/src/main/resources/org/scijava/ui/swing/script/themes/scijava-dark.xml b/src/main/resources/org/scijava/ui/swing/script/themes/scijava-dark.xml
index 6c41341e..de260f1c 100644
--- a/src/main/resources/org/scijava/ui/swing/script/themes/scijava-dark.xml
+++ b/src/main/resources/org/scijava/ui/swing/script/themes/scijava-dark.xml
@@ -30,7 +30,7 @@
-
+
diff --git a/src/main/resources/org/scijava/ui/swing/script/themes/scijava-light.xml b/src/main/resources/org/scijava/ui/swing/script/themes/scijava-light.xml
index 84916219..9183d173 100644
--- a/src/main/resources/org/scijava/ui/swing/script/themes/scijava-light.xml
+++ b/src/main/resources/org/scijava/ui/swing/script/themes/scijava-light.xml
@@ -29,7 +29,7 @@
-
+
From 32af0042114959bc97bb0ad938336f7f7d7fc925 Mon Sep 17 00:00:00 2001
From: Tiago Ferreira
Date: Sun, 15 Nov 2026 12:45:55 -0500
Subject: [PATCH 19/41] Improve bookmark icons in left gutter
---
.../scijava/ui/swing/script/EditorPane.java | 2 +-
.../scijava/ui/swing/script/GutterUtils.java | 39 +++++++++----------
.../org/scijava/ui/swing/script/Icons.java | 15 +++++++
3 files changed, 35 insertions(+), 21 deletions(-)
diff --git a/src/main/java/org/scijava/ui/swing/script/EditorPane.java b/src/main/java/org/scijava/ui/swing/script/EditorPane.java
index 9ce08581..1cc2b9c8 100644
--- a/src/main/java/org/scijava/ui/swing/script/EditorPane.java
+++ b/src/main/java/org/scijava/ui/swing/script/EditorPane.java
@@ -355,7 +355,7 @@ private void bookmarksChanged() {
private void updateGutterIcons() {
quietBookmarks = true;
try {
- GutterUtils.updateIcons(gutter);
+ GutterUtils.updateIcons(gutter, this);
} finally {
quietBookmarks = false;
}
diff --git a/src/main/java/org/scijava/ui/swing/script/GutterUtils.java b/src/main/java/org/scijava/ui/swing/script/GutterUtils.java
index 32e2450d..645bde5e 100644
--- a/src/main/java/org/scijava/ui/swing/script/GutterUtils.java
+++ b/src/main/java/org/scijava/ui/swing/script/GutterUtils.java
@@ -28,52 +28,51 @@
*/
package org.scijava.ui.swing.script;
-import java.awt.Graphics2D;
-import java.awt.image.BufferedImage;
+import java.awt.Color;
-import javax.swing.ImageIcon;
import javax.swing.text.BadLocationException;
import org.fife.ui.rtextarea.Gutter;
import org.fife.ui.rtextarea.GutterIconInfo;
+import org.fife.ui.rtextarea.RTextArea;
+
+import com.formdev.flatlaf.util.UIScale;
public class GutterUtils {
+ private static final String CACHE_KEY = "scijava.bookmarkIcon";
private final Gutter gutter;
+ private final RTextArea textArea;
- GutterUtils(final Gutter gutter) {
+ GutterUtils(final Gutter gutter, final RTextArea textArea) {
this.gutter = gutter;
+ this.textArea = textArea;
//gutter.setFoldIndicatorStyle(org.fife.ui.rtextarea.FoldIndicatorStyle.MODERN); // DEFAULT
}
- private ImageIcon getBookmarkIcon() {
- final int size = gutter.getLineNumberFont().getSize();
- final BufferedImage image = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB);
- final Graphics2D graphics = image.createGraphics();
- graphics.setColor(gutter.getLineNumberColor());
- graphics.fillRect(0, 0, size, size);
- graphics.setXORMode(gutter.getBorderColor());
- graphics.drawRect(0, 0, size - 1, size - 1);
- image.flush();
- return new ImageIcon(image);
- }
-
private void updateBookmarkIcon() {
+ final int height = gutter.getLineNumberFont().getSize();
+ final Color color = GuiUtils.accentColor();
+ // The icon only depends on these: skip the rebuild (and the bookmark restore) if unchanged
+ final String key = height + ":" + color.getRGB();
+ if (key.equals(gutter.getClientProperty(CACHE_KEY)) && gutter.getBookmarkIcon() != null) return;
+ gutter.putClientProperty(CACHE_KEY, key);
+
// this will clear existing bookmarks, so we'll need restore existing ones
final GutterIconInfo[] stash = gutter.getBookmarks();
- gutter.setBookmarkIcon(getBookmarkIcon());
+ gutter.setBookmarkIcon(Icons.bookmark(color, UIScale.unscale(height)));
for (final GutterIconInfo info : stash) {
try {
- gutter.toggleBookmark(info.getMarkedOffset());
+ gutter.toggleBookmark(textArea.getLineOfOffset(info.getMarkedOffset()));
} catch (final BadLocationException ignored) {
// do nothing
}
}
}
- public static void updateIcons(final Gutter gutter) {
- final GutterUtils utils = new GutterUtils(gutter);
+ public static void updateIcons(final Gutter gutter, final RTextArea textArea) {
+ final GutterUtils utils = new GutterUtils(gutter, textArea);
utils.updateBookmarkIcon();
}
}
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 fd7814f9..b30cb6ec 100644
--- a/src/main/java/org/scijava/ui/swing/script/Icons.java
+++ b/src/main/java/org/scijava/ui/swing/script/Icons.java
@@ -94,6 +94,21 @@ static Icon trash(final boolean disabled) {
new Color(0x6E6E6E), new Color(0xA9A9A9), disabled);
}
+ /**
+ * Bookmark ribbon, for the gutter
+ *
+ * @param color the fill color
+ * @param height the height in unscaled pixels
+ */
+ static Icon bookmark(final Color color, final int height) {
+ return new GlyphIcon(
+ "M192 64C156.7 64 128 92.7 128 128L128 544C128 555.5 134.2 566.2 144.2 571.8"
+ + "C154.2 577.4 166.5 577.3 176.4 571.4L320 485.3L463.5 571.4"
+ + "C473.4 577.3 485.7 577.5 495.7 571.8C505.7 566.1 512 555.5 512 544L512 128"
+ + "C512 92.7 483.3 64 448 64L192 64z",
+ color, color, false, 128, 64, 384, 512, height);
+ }
+
/**
* Light bulb icon.
*
From 9c5e839a7809b727e157575490a95af396f064d7 Mon Sep 17 00:00:00 2001
From: Tiago Ferreira
Date: Sun, 15 Nov 2026 13:05:44 -0500
Subject: [PATCH 20/41] Modernize right Errorstrip w/ scalable markers
---
.../ui/swing/script/ScalableErrorStrip.java | 88 +++++++++++++++++++
.../ui/swing/script/TextEditorTab.java | 2 +-
2 files changed, 89 insertions(+), 1 deletion(-)
create mode 100644 src/main/java/org/scijava/ui/swing/script/ScalableErrorStrip.java
diff --git a/src/main/java/org/scijava/ui/swing/script/ScalableErrorStrip.java b/src/main/java/org/scijava/ui/swing/script/ScalableErrorStrip.java
new file mode 100644
index 00000000..28144be8
--- /dev/null
+++ b/src/main/java/org/scijava/ui/swing/script/ScalableErrorStrip.java
@@ -0,0 +1,88 @@
+/*
+ * #%L
+ * Script Editor and Interpreter for SciJava script languages.
+ * %%
+ * Copyright (C) 2009 - 2026 SciJava developers.
+ * %%
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ * #L%
+ */
+
+package org.scijava.ui.swing.script;
+
+import java.awt.Component;
+import java.awt.Dimension;
+import java.awt.Color;
+import java.awt.Graphics2D;
+
+import com.formdev.flatlaf.ui.FlatUIUtils;
+import org.fife.ui.rsyntaxtextarea.ErrorStrip;
+import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
+import org.fife.ui.rsyntaxtextarea.parser.ParserNotice;
+
+import com.formdev.flatlaf.util.UIScale;
+
+/**
+ * An {@link ErrorStrip} that follows the UI scale factor. The stock strip uses
+ * hard-coded pixel sizes (width, marker size and caret line thickness)
+ */
+class ScalableErrorStrip extends ErrorStrip {
+
+ // Sizes of the stock strip, in unscaled pixels
+ private static final int WIDTH = 14, MARKER_WIDTH = 10, MARKER_HEIGHT = 5, CARET_THICKNESS = 2;
+
+ ScalableErrorStrip(final RSyntaxTextArea textArea) {
+ super(textArea);
+ // The stock strip repaints a region sized for unscaled markers
+ textArea.addCaretListener(e -> {
+ if (UIScale.getUserScaleFactor() > 1f) repaint();
+ });
+ }
+
+ @Override
+ public Dimension getPreferredSize() {
+ return new Dimension(UIScale.scale(WIDTH), super.getPreferredSize().height);
+ }
+
+ @Override
+ protected void addImpl(final Component comp, final Object constraints, final int index) {
+ super.addImpl(comp, constraints, index);
+ comp.setSize(UIScale.scale(MARKER_WIDTH), UIScale.scale(MARKER_HEIGHT)); // layout is null
+ }
+
+ @Override
+ protected void paintCaretMarker(final Graphics2D g, final int width, final int height) {
+ final int thickness = UIScale.scale(CARET_THICKNESS);
+ final int center = height / 2 + (height & 1) + 1;
+ g.fillRect(0, center - thickness / 2, width, thickness);
+ }
+
+ // Flat rounded markers without the stock beveled border
+ @Override
+ protected void paintParserNoticeMarker(final Graphics2D g, final ParserNotice notice, final int width,
+ final int height) {
+ final Color c = notice.getColor();
+ FlatUIUtils.setRenderingHints(g);
+ g.setColor(c == null ? Color.GRAY : c);
+ g.fillRect(0, 0, width, height);
+ }
+}
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 57b1e3a3..747bd642 100644
--- a/src/main/java/org/scijava/ui/swing/script/TextEditorTab.java
+++ b/src/main/java/org/scijava/ui/swing/script/TextEditorTab.java
@@ -312,7 +312,7 @@ with a modifier (e.g., %s) they move the caret within a multi-line prompt.
// ParserNotice.Level.ERROR. NB: As is, the end of the strip corresponds to the
// last line of text in the text area: E.g., for a text area with just 3 lines,
// line 2 will be marked at the strip's half height
- final ErrorStrip es = new ErrorStrip(editorPane);
+ final ErrorStrip es = new ScalableErrorStrip(editorPane);
es.setShowMarkAll(true);
es.setShowMarkedOccurrences(true);
final JPanel holder = new JPanel(new BorderLayout());
From 94f6d0d30c81671f94c0fde7ca698502eb2a1d4c Mon Sep 17 00:00:00 2001
From: Tiago Ferreira
Date: Sun, 15 Nov 2026 17:09:37 -0500
Subject: [PATCH 21/41] Add tasks pane.
---
.../org/scijava/ui/swing/script/Icons.java | 32 +++-
.../scijava/ui/swing/script/TasksPanel.java | 167 ++++++++++++++++++
.../scijava/ui/swing/script/TextEditor.java | 81 +++++++--
3 files changed, 257 insertions(+), 23 deletions(-)
create mode 100644 src/main/java/org/scijava/ui/swing/script/TasksPanel.java
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 b30cb6ec..a832c6eb 100644
--- a/src/main/java/org/scijava/ui/swing/script/Icons.java
+++ b/src/main/java/org/scijava/ui/swing/script/Icons.java
@@ -55,9 +55,34 @@ final class Icons {
private static final Color GREEN = new Color(0x629B70), GREEN_DARK = new Color(0x44774E);
private static final Color RED = new Color(0xD46D71), RED_DARK = new Color(0xDF5663);
+ private static final String BOOKMARK = "M128 128C128 92.7 156.7 64 192 64L448 64C483.3 64 512 92.7 512 128L512 545.1C512 570.7 483.5 585.9 462.2 571.7L320 476.8L177.8 571.7C156.5 585.9 128 570.6 128 545.1L128 128zM192 112C183.2 112 176 119.2 176 128L176 515.2L293.4 437C309.5 426.3 330.5 426.3 346.6 437L464 515.2L464 128C464 119.2 456.8 112 448 112L192 112z";
+ private static final String FOLDER = "M128 464L512 464C520.8 464 528 456.8 528 448L528 208C528 199.2 520.8 192 512 192L362.7 192C345.4 192 328.5 186.4 314.7 176L276.3 147.2C273.5 145.1 270.2 144 266.7 144L128 144C119.2 144 112 151.2 112 160L112 448C112 456.8 119.2 464 128 464zM512 512L128 512C92.7 512 64 483.3 64 448L64 160C64 124.7 92.7 96 128 96L266.7 96C280.5 96 294 100.5 305.1 108.8L343.5 137.6C349 141.8 355.8 144 362.7 144L512 144C547.3 144 576 172.7 576 208L576 448C576 483.3 547.3 512 512 512z";
+ private static final String OUTLINE = "M104 112C90.7 112 80 122.7 80 136L80 184C80 197.3 90.7 208 104 208L152 208C165.3 208 176 197.3 176 184L176 136C176 122.7 165.3 112 152 112L104 112zM256 128C238.3 128 224 142.3 224 160C224 177.7 238.3 192 256 192L544 192C561.7 192 576 177.7 576 160C576 142.3 561.7 128 544 128L256 128zM256 288C238.3 288 224 302.3 224 320C224 337.7 238.3 352 256 352L544 352C561.7 352 576 337.7 576 320C576 302.3 561.7 288 544 288L256 288zM256 448C238.3 448 224 462.3 224 480C224 497.7 238.3 512 256 512L544 512C561.7 512 576 497.7 576 480C576 462.3 561.7 448 544 448L256 448zM80 296L80 344C80 357.3 90.7 368 104 368L152 368C165.3 368 176 357.3 176 344L176 296C176 282.7 165.3 272 152 272L104 272C90.7 272 80 282.7 80 296zM104 432C90.7 432 80 442.7 80 456L80 504C80 517.3 90.7 528 104 528L152 528C165.3 528 176 517.3 176 504L176 456C176 442.7 165.3 432 152 432L104 432z";
+ private static final String CLIPBOARD = "M360 160L280 160C266.7 160 256 149.3 256 136C256 122.7 266.7 112 280 112L360 112C373.3 112 384 122.7 384 136C384 149.3 373.3 160 360 160zM360 208C397.1 208 427.6 180 431.6 144L448 144C456.8 144 464 151.2 464 160L464 512C464 520.8 456.8 528 448 528L192 528C183.2 528 176 520.8 176 512L176 160C176 151.2 183.2 144 192 144L208.4 144C212.4 180 242.9 208 280 208L360 208zM419.9 96C407 76.7 385 64 360 64L280 64C255 64 233 76.7 220.1 96L192 96C156.7 96 128 124.7 128 160L128 512C128 547.3 156.7 576 192 576L448 576C483.3 576 512 547.3 512 512L512 160C512 124.7 483.3 96 448 96L419.9 96z";
+
private Icons() {
}
+ /** Folder icon for the Files side tab (follows the component foreground) */
+ static Icon folder() {
+ return new GlyphIcon(FOLDER, null, null, false, 0, 0, 640, 640, 18);
+ }
+
+ /** Rectangle-with-list icon for the Outline side tab */
+ static Icon outline() {
+ return new GlyphIcon(OUTLINE, null, null, false, 0, 0, 640, 640, 18);
+ }
+
+ /** Bookmark icon for the Markers side tab */
+ static Icon markers() {
+ return new GlyphIcon(BOOKMARK, null, null, false, 0, 0, 640, 640, 18);
+ }
+
+ /** Clipboard icon for the Notes side tab */
+ static Icon clipboard() {
+ return new GlyphIcon(CLIPBOARD, null, null, false, 0, 0, 640, 640, 18);
+ }
+
/**
* Green "play" triangle
*/
@@ -102,10 +127,7 @@ static Icon trash(final boolean disabled) {
*/
static Icon bookmark(final Color color, final int height) {
return new GlyphIcon(
- "M192 64C156.7 64 128 92.7 128 128L128 544C128 555.5 134.2 566.2 144.2 571.8"
- + "C154.2 577.4 166.5 577.3 176.4 571.4L320 485.3L463.5 571.4"
- + "C473.4 577.3 485.7 577.5 495.7 571.8C505.7 566.1 512 555.5 512 544L512 128"
- + "C512 92.7 483.3 64 448 64L192 64z",
+ BOOKMARK,
color, color, false, 128, 64, 384, 512, height);
}
@@ -225,7 +247,7 @@ private static class GlyphIcon extends FlatAbstractIcon {
@Override
protected void paintIcon(final Component c, final Graphics2D g) {
- Color color = FlatLaf.isLafDark() ? dark : light;
+ Color color = light == null ? c.getForeground() : FlatLaf.isLafDark() ? dark : light;
if (disabled) {
final Color d = UIManager.getColor("Button.disabledText");
color = (d != null) ? d : Color.GRAY;
diff --git a/src/main/java/org/scijava/ui/swing/script/TasksPanel.java b/src/main/java/org/scijava/ui/swing/script/TasksPanel.java
new file mode 100644
index 00000000..d1193890
--- /dev/null
+++ b/src/main/java/org/scijava/ui/swing/script/TasksPanel.java
@@ -0,0 +1,167 @@
+/*
+ * #%L
+ * Script Editor and Interpreter for SciJava script languages.
+ * %%
+ * Copyright (C) 2009 - 2026 SciJava developers.
+ * %%
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ * #L%
+ */
+
+package org.scijava.ui.swing.script;
+
+import java.awt.BorderLayout;
+import java.awt.Component;
+import java.awt.Graphics;
+import java.awt.event.KeyAdapter;
+import java.awt.event.KeyEvent;
+import java.awt.event.MouseAdapter;
+import java.awt.event.MouseEvent;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.function.Consumer;
+import java.util.function.Supplier;
+
+import javax.swing.DefaultListCellRenderer;
+import javax.swing.DefaultListModel;
+import javax.swing.JList;
+import javax.swing.JPanel;
+import javax.swing.JScrollPane;
+import javax.swing.ListSelectionModel;
+import javax.swing.SwingUtilities;
+import javax.swing.Timer;
+import javax.swing.border.EmptyBorder;
+
+/**
+ * A "Tasks" side panel listing the TODO, FIXME and HACK comments of all open editor tabs that are detected by the
+ * editor's task tag parser. Double-clicking (or pressing Enter on) an entry jumps to it. Tasks are discovered
+ * while typing, so the list is kept up to date by a check that only runs while the panel is visible.
+ */
+class TasksPanel extends JPanel {
+
+ /** A task comment: its tab, 1-based line, document offset and text */
+ record Task(TextEditorTab tab, int line, int offset, String text) {}
+
+ private static final long serialVersionUID = 1L;
+ private static final int REFRESH_DELAY_MS = 1500;
+ private static final int TEXT_MAX_CHARS = 100;
+
+ private final Supplier> source;
+ private final DefaultListModel model = new DefaultListModel<>();
+ private final List signature = new ArrayList<>();
+ private final JList list;
+
+ /**
+ * @param source supplies the current tasks of all tabs (in display order)
+ * @param jumper moves the editor to the given task
+ */
+ TasksPanel(final Supplier> source, final Consumer jumper) {
+ super(new BorderLayout());
+ this.source = source;
+
+ list = new JList<>(model) {
+
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ protected void paintComponent(final Graphics g) {
+ super.paintComponent(g);
+ if (model.isEmpty()) GuiUtils.paintEmptyHint(g, this, "No tasks",
+ "Comments with TODO, FIXME or HACK show up here");
+ }
+ };
+ list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
+ list.setCellRenderer(new Renderer());
+ final JScrollPane pane = new JScrollPane(list);
+ GuiUtils.flattenScrollBars(pane);
+ add(pane, BorderLayout.CENTER);
+
+ list.addMouseListener(new MouseAdapter() {
+
+ @Override
+ public void mouseClicked(final MouseEvent e) {
+ if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 2) {
+ final int idx = list.locationToIndex(e.getPoint());
+ if (idx >= 0 && list.getCellBounds(idx, idx).contains(e.getPoint()))
+ jumper.accept(model.get(idx));
+ }
+ }
+ });
+ list.addKeyListener(new KeyAdapter() {
+
+ @Override
+ public void keyPressed(final KeyEvent e) {
+ final Task sel = list.getSelectedValue();
+ if (sel != null && e.getKeyCode() == KeyEvent.VK_ENTER) {
+ jumper.accept(sel);
+ e.consume();
+ }
+ }
+ });
+
+ refresh();
+ final Timer poll = new Timer(REFRESH_DELAY_MS, e -> {
+ if (isShowing()) refresh();
+ });
+ poll.start();
+ }
+
+ /** Brings the list up to date (cheap if nothing changed). */
+ void refresh() {
+ final List current = source.get();
+ final List sig = new ArrayList<>(current.size());
+ for (final Task t : current)
+ sig.add(System.identityHashCode(t.tab()) + ":" + t.line() + ":" + t
+ .text());
+ if (sig.equals(signature)) return;
+ signature.clear();
+ signature.addAll(sig);
+ final int selected = list.getSelectedIndex();
+ model.clear();
+ for (final Task t : current)
+ model.addElement(t);
+ if (selected >= 0 && selected < model.size()) list.setSelectedIndex(
+ selected);
+ }
+
+ private static class Renderer extends DefaultListCellRenderer {
+
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public Component getListCellRendererComponent(final JList> l,
+ final Object value, final int index, final boolean selected,
+ final boolean focus)
+ {
+ final Task t = (Task) value;
+ final String name = t.tab().editorPane.getFileName();
+ String text = t.text();
+ if (text.length() > TEXT_MAX_CHARS) text = text.substring(0,
+ TEXT_MAX_CHARS) + "...";
+ super.getListCellRendererComponent(l, (name == null ? "Untitled" : name) +
+ ":" + t.line() + " " + text, index, selected, focus);
+ setBorder(new EmptyBorder(2, 6, 2, 6));
+ setToolTipText(t.text());
+ return this;
+ }
+ }
+}
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 f9d02adc..6ba6731e 100644
--- a/src/main/java/org/scijava/ui/swing/script/TextEditor.java
+++ b/src/main/java/org/scijava/ui/swing/script/TextEditor.java
@@ -122,6 +122,8 @@
import org.fife.ui.rsyntaxtextarea.RSyntaxDocument;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import org.fife.ui.rsyntaxtextarea.Theme;
+import org.fife.ui.rsyntaxtextarea.parser.ParserNotice;
+import org.fife.ui.rsyntaxtextarea.parser.TaskTagParser;
import org.fife.ui.rsyntaxtextarea.TokenMakerFactory;
import org.fife.ui.rtextarea.ClipboardHistory;
import org.fife.ui.rtextarea.Macro;
@@ -217,7 +219,8 @@ public class TextEditor extends JFrame implements ActionListener,
private JTabbedPane sideTabs;
private NotesPanel notesPanel;
private BookmarksPanel bookmarksPanel;
- private JSplitPane outlineSplit;
+ private JSplitPane markersSplit;
+ private TasksPanel tasksPanel;
private JMenuItem newFile, open, save, saveas, compileAndRun, compile,
close, undo, redo, cut, copy, paste, find, selectAll, kill,
gotoLine, makeJar, makeJarWithSource, removeUnusedImports, sortImports,
@@ -350,6 +353,9 @@ public TextEditor(final Context context) {
sideTabs = GuiUtils.getJTabbedPane();
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);
filesPanel = new FileSystemTreePanel(tree, context);
filesPanel.setActiveScriptSupplier(() -> {
try {
@@ -358,29 +364,33 @@ public TextEditor(final Context context) {
return null;
}
});
- sideTabs.addTab("Files", filesPanel);
+ addSideTab("Files", Icons.folder(), filesPanel);
sourceTreePanel = new OutlineTreePanel();
bookmarksPanel = new BookmarksPanel(this::collectBookmarks, this::goToBookmark);
+ tasksPanel = new TasksPanel(this::collectTasks, this::goToTask);
- // Scratchpad
+ // Outline
final JPanel pane1 = new JPanel(new BorderLayout());
final JLabel outlineHeader = header("Structure");
pane1.add(outlineHeader, BorderLayout.NORTH);
pane1.add(sourceTreePanel, BorderLayout.CENTER);
- // Clipboard history
+ addSideTab("Outline", Icons.outline(), pane1);
+
+ // Markers: bookmarks and tasks of all open tabs
final JPanel pane2 = new JPanel(new BorderLayout());
- final JLabel bookmarkHeader = header("Bookmarks");
- pane2.add(bookmarkHeader, BorderLayout.NORTH);
+ pane2.add(header("Bookmarks"), BorderLayout.NORTH);
pane2.add(bookmarksPanel, BorderLayout.CENTER);
-
- outlineSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT, pane1, pane2);
- outlineSplit.setResizeWeight(.75);
- // No divider: the Scratchpad header (with a hairline on top) is the drag handle
- GuiUtils.installSplitHandle(bookmarkHeader, outlineSplit);
-
- sideTabs.addTab("Outline", outlineSplit);
+ final JPanel pane3 = new JPanel(new BorderLayout());
+ final JLabel tasksHeader = header("Tasks");
+ pane3.add(tasksHeader, BorderLayout.NORTH);
+ pane3.add(tasksPanel, BorderLayout.CENTER);
+ markersSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT, pane2, pane3);
+ markersSplit.setResizeWeight(.5);
+ // No divider: the Tasks header (with a hairline on top) is the drag handle
+ GuiUtils.installSplitHandle(tasksHeader, markersSplit);
+ addSideTab("Markers", Icons.markers(), markersSplit);
notesPanel = new NotesPanel(() -> {
try {
return getEditorPane();
@@ -388,7 +398,7 @@ public TextEditor(final Context context) {
return null;
}
}, prefService, getClass());
- sideTabs.addTab("Notes", notesPanel);
+ addSideTab("Notes", Icons.clipboard(), notesPanel);
body = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, sideTabs, tabbed);
GuiUtils.installSplitHandle(null, body);
// These items are dynamic and need to be initialized before EditorPane creation
@@ -880,7 +890,7 @@ public void windowGainedFocus(final WindowEvent e) {
try {
threadService.invoke(() -> {
pack();
- body.setDividerLocation(0.2); // Important!: will be read as prefs. default
+ body.setDividerLocation(0.25); // Important!: will be read as prefs. default
getTab().setREPLVisible(false);
loadWindowSizePreferences();
pack();
@@ -924,7 +934,7 @@ public void componentResized(final ComponentEvent e) {
}
private void resetLayout() {
- body.setDividerLocation(.2d);
+ body.setDividerLocation(.25d);
getTab().setOrientation(JSplitPane.VERTICAL_SPLIT);
getTab().setDividerLocation((incremental) ? .7d : .75d);
if (incremental)
@@ -933,6 +943,11 @@ private void resetLayout() {
pack();
}
+ private void addSideTab(final String title, final Icon icon, final Component c) {
+ sideTabs.addTab(title, icon, 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));
@@ -2015,7 +2030,7 @@ public Dimension getPreferredSize() { // fixed width: neighbors do not move as t
statusSide.setSelected(true);
statusSide.addActionListener(e -> {
if (statusSide.isSelected()) { // restore
- body.setDividerLocation(sideLastLocation > 50 ? sideLastLocation : (int) (body.getWidth() * .2));
+ body.setDividerLocation(sideLastLocation > 50 ? sideLastLocation : (int) (body.getWidth() * .25));
} else { // collapse (the location is remembered by the divider listener)
body.setDividerLocation(0);
}
@@ -2690,6 +2705,35 @@ private void goToBookmark(final Bookmark bookmark) {
bookmark.setCaret();
}
+ private List collectTasks() {
+ final List tasks = new ArrayList<>();
+ for (int i = 0; i < tabbed.getTabCount(); i++) {
+ final TextEditorTab tab = (TextEditorTab) tabbed.getComponentAt(i);
+ for (final ParserNotice n : tab.editorPane.getParserNotices()) {
+ if (!(n instanceof TaskTagParser.TaskNotice)) continue;
+ // Multi-line comments may carry their closing delimiter
+ final String text = n.getMessage().replaceAll("\\s*\\*/\\s*$", "").trim();
+ tasks.add(new TasksPanel.Task(tab, n.getLine(), n.getOffset(), text));
+ }
+ }
+ return tasks;
+ }
+
+ private void goToTask(final TasksPanel.Task task) {
+ final int index = tabbed.indexOfComponent(task.tab());
+ if (index < 0) return;
+ switchTo(index);
+ task.tab().requestFocus();
+ final RSyntaxTextArea area = task.tab().editorPane;
+ try {
+ final int offs = task.offset() >= 0 && task.offset() <= area.getDocument().getLength() ? task.offset()
+ : area.getLineStartOffset(task.line() - 1);
+ area.setCaretPosition(offs);
+ } catch (final BadLocationException | RuntimeException ignored) {
+ // Stale task; the list refreshes shortly
+ }
+ }
+
/** Brings the Bookmarks panel up to date after a bookmark was added or removed */
void bookmarksChanged() {
if (bookmarksPanel != null) bookmarksPanel.refresh();
@@ -2701,8 +2745,9 @@ public void listBookmarks() {
SwingUtilities.invokeLater(this::listBookmarks);
return;
}
- sideTabs.setSelectedComponent(outlineSplit);
+ sideTabs.setSelectedComponent(markersSplit);
bookmarksPanel.refresh();
+ tasksPanel.refresh();
if (!statusSide.isSelected()) statusSide.doClick();
}
From 33e8c9cc79b9df533de682722e8a970db8e57f12 Mon Sep 17 00:00:00 2001
From: Tiago Ferreira
Date: Sun, 15 Nov 2026 17:11:10 -0500
Subject: [PATCH 22/41] Wip: adjust the REPL cursor
---
.../ui/swing/script/TextEditorTab.java | 41 +++++++++++++++++++
1 file changed, 41 insertions(+)
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 747bd642..bcbc4c22 100644
--- a/src/main/java/org/scijava/ui/swing/script/TextEditorTab.java
+++ b/src/main/java/org/scijava/ui/swing/script/TextEditorTab.java
@@ -32,7 +32,10 @@
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
+import java.awt.FontMetrics;
+import java.awt.Graphics;
import java.awt.Insets;
+import java.awt.Rectangle;
import java.awt.geom.RoundRectangle2D;
import java.awt.FlowLayout;
import java.awt.datatransfer.DataFlavor;
@@ -53,11 +56,13 @@
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
+import javax.swing.text.DefaultCaret;
import javax.swing.text.JTextComponent;
import com.formdev.flatlaf.FlatClientProperties;
import com.formdev.flatlaf.icons.FlatFileChooserDetailsViewIcon;
import com.formdev.flatlaf.icons.FlatHelpButtonIcon;
+import com.formdev.flatlaf.util.UIScale;
import org.fife.ui.rsyntaxtextarea.ErrorStrip;
import org.fife.ui.rsyntaxtextarea.Style;
import org.fife.ui.rsyntaxtextarea.Token;
@@ -242,6 +247,10 @@ public void dragEnter(final DropTargetDragEvent e) {
prompt.setFont(getEditorPane().getFont());
prompt.setTabSize(editorPane.getTabSize());
prompt.setLineWrap(textEditor.isReplWrap());
+ // Underscore caret: console look, distinct from the editor (and Vim block) caret
+ final UnderscoreCaret caret = new UnderscoreCaret();
+ caret.setBlinkRate(prompt.getCaret().getBlinkRate());
+ prompt.setCaret(caret);
final JPanel prompt_panel = new JPanel();
prompt_panel.setMinimumSize(new Dimension(0, 0));
@@ -652,4 +661,36 @@ public void setExecutor(final Executer executer) {
public JTextComponent getEditorPane() {
return editorPane;
}
+
+ /** A caret drawn as an underscore below the current character cell */
+ private static class UnderscoreCaret extends DefaultCaret {
+
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ protected synchronized void damage(final Rectangle r) {
+ if (r == null) return;
+ final JTextComponent c = getComponent();
+ x = r.x;
+ y = r.y;
+ width = c.getFontMetrics(c.getFont()).charWidth('m') + 1;
+ height = r.height;
+ repaint();
+ }
+
+ @Override
+ public void paint(final Graphics g) {
+ if (!isVisible()) return;
+ final JTextComponent c = getComponent();
+ try {
+ final Rectangle r = c.modelToView2D(getDot()).getBounds();
+ final FontMetrics fm = c.getFontMetrics(c.getFont());
+ final int thickness = Math.max(2, UIScale.scale(2));
+ g.setColor(c.getCaretColor());
+ g.fillRect(r.x, r.y + fm.getAscent() + fm.getDescent() - thickness, fm.charWidth('m'), thickness);
+ } catch (final BadLocationException ignored) {
+ // Caret outside of the document: nothing to paint
+ }
+ }
+ }
}
From b68090c098f4f7b40be058dd2d5736c499472d48 Mon Sep 17 00:00:00 2001
From: Tiago Ferreira
Date: Sun, 15 Nov 2026 17:49:57 -0500
Subject: [PATCH 23/41] Improve detection of batch service submission failure
---
.../java/org/scijava/ui/swing/script/TextEditor.java | 10 +++++++++-
1 file changed, 9 insertions(+), 1 deletion(-)
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 6ba6731e..c34c1737 100644
--- a/src/main/java/org/scijava/ui/swing/script/TextEditor.java
+++ b/src/main/java/org/scijava/ui/swing/script/TextEditor.java
@@ -140,6 +140,7 @@
import org.scijava.io.IOService;
import org.scijava.log.LogService;
import org.scijava.module.ModuleException;
+import org.scijava.module.ModuleItem;
import org.scijava.module.ModuleService;
import org.scijava.options.OptionsService;
import org.scijava.platform.PlatformService;
@@ -3552,8 +3553,15 @@ public void runBatch() {
return;
}
final ScriptInfo info = new ScriptInfo(context, //
- "dummy." + getCurrentLanguage().getExtensions().get(0), //
+ "batch_submission." + getCurrentLanguage().getExtensions().getFirst(), //
new StringReader(script));
+ boolean hasFileInput = false;
+ for (final ModuleItem> input : info.inputs())
+ hasFileInput |= File.class.isAssignableFrom(input.getType());
+ if (!hasFileInput) {
+ error("This option requires at least one @File parameter to be declared in the script.");
+ return;
+ }
batchService.run(info);
}
From 88e07d660d7599e04e7779088e5069ca91e3faf1 Mon Sep 17 00:00:00 2001
From: Tiago Ferreira
Date: Sun, 15 Nov 2026 18:57:15 -0500
Subject: [PATCH 24/41] Improve/Fix ErrorParser
- Fix: After every full-script run wrong lines were highlighted the wrong lines due to offset accumulation
- Fix Parser leak. ew ErrorStripNotifyingParser were added without removing the previous one
- Fix inverted logic in gotoPreviousError
- Fix: Highlights being re-added on every reparse
- Improve fragile parsing: we now walk the exception chain instead of scraping text
- Improve persistence of errors after editing text
- Reset all errors flagged by a previous run before each run
- Drop support for scala and R: The handbaked hacks are just too fragile
- Add proper test
---
.../scijava/ui/swing/script/ErrorParser.java | 489 +++++++++++-------
.../scijava/ui/swing/script/TextEditor.java | 7 +
.../ui/swing/script/ErrorParserTest.java | 113 ++++
3 files changed, 418 insertions(+), 191 deletions(-)
create mode 100644 src/test/java/org/scijava/ui/swing/script/ErrorParserTest.java
diff --git a/src/main/java/org/scijava/ui/swing/script/ErrorParser.java b/src/main/java/org/scijava/ui/swing/script/ErrorParser.java
index 292cb0d4..12526c8c 100644
--- a/src/main/java/org/scijava/ui/swing/script/ErrorParser.java
+++ b/src/main/java/org/scijava/ui/swing/script/ErrorParser.java
@@ -35,16 +35,24 @@
import java.awt.Window;
import java.io.PrintWriter;
import java.io.StringWriter;
-import java.util.Arrays;
import java.util.Collection;
-import java.util.StringTokenizer;
+import java.util.List;
+import java.util.Objects;
import java.util.TreeSet;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
+import javax.script.ScriptException;
+import javax.swing.SwingUtilities;
import javax.swing.UIManager;
+import javax.swing.event.DocumentEvent;
+import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
+import javax.swing.text.Document;
import javax.swing.text.Element;
+import javax.swing.text.Position;
import org.fife.ui.rsyntaxtextarea.RSyntaxDocument;
import org.fife.ui.rsyntaxtextarea.SyntaxConstants;
@@ -55,53 +63,144 @@
import org.fife.ui.rsyntaxtextarea.parser.Parser;
import org.scijava.script.ScriptLanguage;
+/**
+ * Detects the lines of the editor that caused a script error and flags them
+ * (line highlight and error strip). Lines are taken from the exception when
+ * possible (see {@link #parse(Throwable)}), and otherwise scraped from the
+ * error console (see {@link #parse()}).
+ */
public class ErrorParser {
/* Color for ErrorStrip marks and fallback taint for line highlights */
private static final Color COLOR = Color.RED;
- /* 0-base indices of Editor's lines that have errored */
- private TreeSet errorLines;
- /* When running selected code errored lines map to Editor through this offset */
- private int lineOffset;
- private boolean enabled;
+ private static final int UNKNOWN = -1;
+ /* Stack frames of the runtimes themselves, never script lines */
+ private static final Pattern IGNORED = Pattern.compile(
+ ":classloader:|\\.org\\.python\\.|\\.codehaus\\.groovy\\.|\\.tools\\.nsc\\.|at bsh\\.|\\$Recompilation\\$");
+ /* "line 51", "Line: 51", "line number 51" */
+ private static final Pattern LINE_WORD = Pattern.compile(
+ "\\bline(?:\\s+number)?\\s*:?\\s*(\\d+)", Pattern.CASE_INSENSITIVE);
+
+ /**
+ * An errored line: its position tracks edits in the document, and its text
+ * at the time of the run tells whether the error is still about that line
+ */
+ private record FlaggedLine(Position position, String text, Object highlight) {}
+
+ private final List errors = new CopyOnWriteArrayList<>();
+ private final AtomicBoolean prunePending = new AtomicBoolean();
+ private final DocumentListener editListener = new DocumentListener() {
+
+ @Override
+ public void insertUpdate(final DocumentEvent e) {
+ schedulePrune();
+ }
+
+ @Override
+ public void removeUpdate(final DocumentEvent e) {
+ schedulePrune();
+ }
+
+ @Override
+ public void changedUpdate(final DocumentEvent e) {
+ // attributes only
+ }
+ };
+ private Document listenedDocument;
+ private final ErrorStripNotifyingParser notifyingParser = new ErrorStripNotifyingParser();
private final EditorPane editorPane;
+ private boolean parserRegistered;
+ /* 0-base editor line of the executed selection (0: whole script) */
+ private volatile int lineOffset;
+ /* Prompt commands do not map to editor lines */
+ private volatile boolean promptRun;
+ private volatile boolean enabled;
private JTextAreaWriter writer;
private int lengthOfJTextAreaWriter;
- private ErrorStripNotifyingParser notifyingParser;
- private boolean parsingSucceeded;
+ private volatile boolean parsingSucceeded;
+ /* Whether the console was told why errors are not flagged in this run */
+ private boolean noticeShown;
public ErrorParser(final EditorPane editorPane) {
this.editorPane = editorPane;
- lineOffset = 0;
}
public void gotoPreviousError() {
- if (!isCaretMovable()) {
- try {
- final int caretLine = editorPane.getCaretLineNumber();
- gotoLine(errorLines.lower(caretLine));
- } catch (final NullPointerException ignored) {
- gotoLine(errorLines.last());
- }
- }
+ gotoError(false);
}
public void gotoNextError() {
- if (isCaretMovable()) {
- try {
- final int caretLine = editorPane.getCaretLineNumber();
- gotoLine(errorLines.higher(caretLine));
- } catch (final NullPointerException ignored) {
- gotoLine(errorLines.first());
- }
+ gotoError(true);
+ }
+
+ private void gotoError(final boolean forward) {
+ final TreeSet lines = currentLines();
+ if (lines.isEmpty()) {
+ UIManager.getLookAndFeel().provideErrorFeedback(editorPane);
+ return;
}
+ final int caretLine = editorPane.getCaretLineNumber();
+ Integer target = forward ? lines.higher(caretLine) : lines.lower(caretLine);
+ if (target == null) target = forward ? lines.first() : lines.last(); // wrap around
+ gotoLine(target);
}
+ /** Removes the flagged lines of the previous run */
public void reset() {
- if (notifyingParser != null) {
+ final List flagged = List.copyOf(errors);
+ errors.clear();
+ parsingSucceeded = false;
+ noticeShown = false;
+ runOnEdt(() -> {
+ if (parserRegistered) {
+ editorPane.removeParser(notifyingParser);
+ parserRegistered = false;
+ }
+ flagged.forEach(e -> editorPane.removeLineHighlight(e.highlight()));
+ });
+ }
+
+ private void schedulePrune() {
+ if (!errors.isEmpty() && prunePending.compareAndSet(false, true)) {
+ SwingUtilities.invokeLater(() -> {
+ prunePending.set(false);
+ prune();
+ });
+ }
+ }
+
+ /** Drops the errors whose line is no longer the one that failed. On the EDT */
+ private void prune() {
+ boolean dropped = false;
+ for (final FlaggedLine e : errors) {
+ if (Objects.equals(lineText(lineOf(e.position())), e.text())) continue;
+ errors.remove(e);
+ editorPane.removeLineHighlight(e.highlight());
+ dropped = true;
+ }
+ if (!dropped) return;
+ if (errors.isEmpty() && parserRegistered) {
editorPane.removeParser(notifyingParser);
- if (notifyingParser.highlightAbnoxiously)
- editorPane.removeAllLineHighlights();
+ parserRegistered = false;
+ } else {
+ editorPane.forceReparsing(notifyingParser);
+ }
+ }
+
+ private int lineOf(final Position p) {
+ try {
+ return editorPane.getLineOfOffset(p.getOffset());
+ } catch (final BadLocationException ignored) {
+ return -1;
+ }
+ }
+
+ private String lineText(final int line) {
+ try {
+ final int start = editorPane.getLineStartOffset(line);
+ return editorPane.getText(start, editorPane.getLineEndOffset(line) - start).stripTrailing();
+ } catch (final BadLocationException ignored) {
+ return null;
}
}
@@ -113,42 +212,59 @@ public void setLineOffset(final int zeroBasedlineOffset) {
this.lineOffset = zeroBasedlineOffset;
}
+ /**
+ * Sets whether the next run executes the current selection, in which case
+ * errored lines map to the editor through the line at which it starts.
+ * Must be called for every run, since the offset is kept until changed.
+ */
public void setSelectedCodeExecution(final boolean selectedExecution) {
- if (selectedExecution) {
- final int p0 = Math.min(editorPane.getCaret().getDot(), editorPane.getCaret().getMark());
- final int p1 = Math.max(editorPane.getCaret().getDot(), editorPane.getCaret().getMark());
- if (p0 != p1) {
- try {
- lineOffset = editorPane.getLineOfOffset(p0);
- } catch (final BadLocationException ignored) {
- lineOffset = -1;
- }
- } else {
- lineOffset = -1;
+ promptRun = false;
+ lineOffset = 0;
+ if (!selectedExecution) return;
+ final int p0 = Math.min(editorPane.getCaret().getDot(), editorPane.getCaret().getMark());
+ final int p1 = Math.max(editorPane.getCaret().getDot(), editorPane.getCaret().getMark());
+ lineOffset = UNKNOWN;
+ if (p0 != p1) {
+ try {
+ lineOffset = editorPane.getLineOfOffset(p0);
+ } catch (final BadLocationException ignored) {
+ // unknown
}
- } else {
- lineOffset = 0;
}
}
+ /** Declares that the next run is a prompt command, with no lines in the editor */
+ public void setPromptExecution() {
+ promptRun = true;
+ }
+
public void setWriter(final JTextAreaWriter writer) {
this.writer = writer;
lengthOfJTextAreaWriter = writer.textArea.getText().length();
+ noticeShown = false;
}
+ /** Flags the lines reported in the error console since {@link #setWriter} */
public void parse() {
if (writer == null)
throw new IllegalArgumentException("Writer is null");
- parse(writer.textArea.getText().substring(lengthOfJTextAreaWriter));
+ final String text = writer.textArea.getText();
+ // The console may have been cleared since the run started
+ final int start = (text.length() < lengthOfJTextAreaWriter) ? 0 : lengthOfJTextAreaWriter;
+ parse(text.substring(start), null);
}
+ /**
+ * Flags the lines reported by an exception: the line numbers of script
+ * exceptions and the stack frames of the script. If it holds none, its stack
+ * trace is scraped like the console.
+ */
public void parse(final Throwable t) {
if (!enabled)
return;
final StringWriter sw = new StringWriter();
- final PrintWriter pw = new PrintWriter(sw);
- t.printStackTrace(pw);
- parse(sw.toString());
+ t.printStackTrace(new PrintWriter(sw));
+ parse(sw.toString(), t);
}
private boolean isImageJMacro() {
@@ -158,6 +274,7 @@ private boolean isImageJMacro() {
return name.equals("ImageJ Macro") || name.equals("IJ1 Macro");
}
+ /** Whether lines were found in the log, i.e., it has details of the error */
public boolean isLogDetailed() {
if (!isImageJMacro()) return parsingSucceeded;
for (final Window win : Window.getWindows()) {
@@ -168,19 +285,21 @@ public boolean isLogDetailed() {
return parsingSucceeded;
}
- private boolean isCaretMovable() {
- if (errorLines == null || errorLines.isEmpty()) {
- UIManager.getLookAndFeel().provideErrorFeedback(editorPane);
- return false;
+ /** The 0-based editor lines currently flagged, following any edits */
+ private TreeSet currentLines() {
+ final TreeSet lines = new TreeSet<>();
+ for (final FlaggedLine e : errors) {
+ final int line = lineOf(e.position());
+ if (line >= 0) lines.add(line);
}
- return true;
+ return lines;
}
private void gotoLine(final int lineNumber) {
try {
editorPane.setCaretPosition(editorPane.getLineStartOffset(lineNumber));
// ensure line is visible. Probably not needed!?
- final Rectangle rect = editorPane.modelToView(editorPane.getCaretPosition());
+ final Rectangle rect = editorPane.modelToView2D(editorPane.getCaretPosition()).getBounds();
editorPane.scrollRectToVisible(rect);
} catch (final BadLocationException ignored) {
// do nothing
@@ -189,140 +308,148 @@ private void gotoLine(final int lineNumber) {
}
}
- private void parse(final String errorLog) {
+ private static void runOnEdt(final Runnable r) {
+ if (SwingUtilities.isEventDispatchThread()) r.run();
+ else SwingUtilities.invokeLater(r);
+ }
+
+ private void parse(final String errorLog, final Throwable t) {
final ScriptLanguage lang = editorPane.getCurrentLanguage();
- if (lang == null) {
+ if (lang == null || promptRun) {
abort();
return;
}
- final boolean isIJM = isImageJMacro();
- if (isIJM) {
+ if (isImageJMacro()) {
abort("Execution errors handled by the Macro Interpreter. Use the Interpreter's Debug option for error tracking", false);
return;
}
+ // Reported lines of these runtimes do not map reliably to the editor
+ final String name = lang.getLanguageName();
+ if ("Scala".equals(name) || "R".equals(name)) {
+ abort("Execution errors are not highlighted for " + name, false);
+ return;
+ }
// Do nothing if disabled, or if only selected text was evaluated in the
// script but we don't know where in the document such selection occurred
if (!enabled) {
abort("Execution errors are not highlighted when auto-imports are active", true);
return;
}
- if (lineOffset == -1) {
- abort("Code selection unknown: Erros are not highlighted in the Editor", true);
- return;
- }
-
- final boolean isJava = "Java".equals(lang.getLanguageName());
- final String fileName = editorPane.getFileName();
- if (isJava && fileName == null) {
- abort();
+ if (lineOffset == UNKNOWN) {
+ abort("Code selection unknown: Errors are not highlighted in the Editor", true);
return;
}
- // HACK scala code seems to always be pre-pended by some 10 lines of code(!?).
- if ("Scala".equals(lang.getLanguageName()))
- lineOffset += 10;
- // HACK and R by one (!?)
- else if ("R".equals(lang.getLanguageName()))
- lineOffset += 1;
-
- errorLines = new TreeSet<>();
- final StringTokenizer tokenizer = new StringTokenizer(errorLog, "\n");
- if (isJava) {
- while (tokenizer.hasMoreTokens()) {
- parseJava(fileName, tokenizer.nextToken(), errorLines);
- }
- } else {
- while (tokenizer.hasMoreTokens()) {
- parseNonJava(tokenizer.nextToken(), errorLines);
- }
- }
- if (!errorLines.isEmpty()) {
- notifyingParser = new ErrorStripNotifyingParser();
- editorPane.addParser(notifyingParser);
- editorPane.forceReparsing(notifyingParser);
- gotoLine(errorLines.first());
+ final String fileName = editorPane.getFileName();
+ final TreeSet reported = new TreeSet<>(); // 1-based, as reported
+ if (t != null) fromThrowable(t, fileName, reported);
+ if (reported.isEmpty()) {
+ reported.addAll(scrape(errorLog, fileName, lang.getExtensions(),
+ "Java".equals(lang.getLanguageName())));
}
+ if (reported.isEmpty()) return;
parsingSucceeded = true;
- }
-
- private void parseNonJava(final String lineText, final Collection errorLines) {
-
- if ( // Elimination of some false positives. TODO: Make this Regex
- lineText.indexOf(":classloader:") > -1 // ruby
- || lineText.indexOf(".org.python.") > -1 // python
- || lineText.indexOf(".codehaus.groovy.") > -1 // groovy
- || lineText.indexOf(".tools.nsc.") > -1 // scala
- || lineText.indexOf("at bsh.") > -1 // beanshel
- || lineText.indexOf("$Recompilation$") > -1 // javascript
- ) {//
- return;
- }
-
- final int extensionIdx = extensionIdx(lineText);
- final int lineIdx = lineText.toLowerCase().indexOf("line");
- if (lineIdx < 0 && extensionIdx < 0 && filenameIdx(lineText) < 0)
- return;
- extractLineIndicesFromFilteredTextLines(lineText, errorLines);
+ final int shift = lineOffset;
+ runOnEdt(() -> flag(reported, shift));
}
- private void extractLineIndicesFromFilteredTextLines(final String lineText, final Collection errorLines) {
-// System.out.println("Section being matched: " + lineText);
- final Pattern pattern = Pattern.compile(":(\\d+)|line\\D*(\\d+)", Pattern.CASE_INSENSITIVE);
- final Matcher matcher = pattern.matcher(lineText);
-
- if (matcher.find()) {
+ /** Flags the (1-based) reported lines, shifted to editor lines. On the EDT */
+ private void flag(final Collection reported, final int shift) {
+ final TreeSet flagged = currentLines();
+ final Color c = highlightColor();
+ for (final int number : reported) {
+ final int line = number - 1 + shift;
+ if (line < 0 || line >= editorPane.getLineCount() || !flagged.add(line)) continue;
try {
- final String firstGroup = matcher.group(1);
- final String lastGroup = matcher.group(matcher.groupCount());
- final String group = (firstGroup == null) ? lastGroup : firstGroup;
-// System.out.println("firstGroup: " + firstGroup);
-// System.out.println("lastGroup: " + lastGroup);
-
- final int lineNumber = Integer.valueOf(group.trim());
- if (lineNumber > 0)
- errorLines.add(lineNumber - 1 + lineOffset); // store 0-based indices
- } catch (final NumberFormatException e) {
- e.printStackTrace();
+ errors.add(new FlaggedLine(editorPane.getDocument().createPosition(editorPane.getLineStartOffset(line)),
+ lineText(line), editorPane.addLineHighlight(line, c)));
+ } catch (final BadLocationException ignored) {
+ // do nothing
}
}
+ if (errors.isEmpty()) return;
+ if (listenedDocument != editorPane.getDocument()) {
+ listenedDocument = editorPane.getDocument();
+ listenedDocument.addDocumentListener(editListener);
+ }
+ if (!parserRegistered) {
+ editorPane.addParser(notifyingParser);
+ parserRegistered = true;
+ }
+ editorPane.forceReparsing(notifyingParser);
+ final TreeSet now = currentLines();
+ if (!now.isEmpty()) gotoLine(now.first());
}
- private int extensionIdx(final String line) {
- int dotIndex = -1;
- for (final String extension : editorPane.getCurrentLanguage().getExtensions()) {
- dotIndex = line.indexOf("." + extension);
- if (dotIndex > -1)
- return dotIndex;
+ /** Collects the 1-based lines of the script in an exception and its causes */
+ static void fromThrowable(final Throwable t, final String fileName, final Collection lines) {
+ int depth = 0;
+ for (Throwable c = t; c != null && depth++ < 20; c = c.getCause()) {
+ if (c instanceof ScriptException se && se.getLineNumber() > 0 && sameFile(se.getFileName(), fileName, true))
+ lines.add(se.getLineNumber());
+ for (final StackTraceElement e : c.getStackTrace()) {
+ if (e.getLineNumber() > 0 && sameFile(e.getFileName(), fileName, false))
+ lines.add(e.getLineNumber());
+ }
}
- return -1;
}
- private int filenameIdx(final String line) {
- int index = line.indexOf(editorPane.getFileName());
- if (index == -1)
- index = (line.indexOf(" Script")); // unsaved file, etc.
- return index;
+ private static boolean sameFile(final String reported, final String fileName, final boolean unknownIsSame) {
+ if (reported == null || reported.isEmpty()) return unknownIsSame;
+ final String base = reported.substring(Math.max(reported.lastIndexOf('/'), reported.lastIndexOf('\\')) + 1);
+ return base.equalsIgnoreCase(fileName);
}
- private void parseJava(final String filename, final String line, final Collection errorLines) {
- int colon = line.indexOf(filename);
- if (colon <= 0)
- return;
-// System.out.println("Parsing candidate: " + line);
- colon += filename.length();
- final int next = line.indexOf(':', colon + 1);
- if (next < colon + 2)
- return;
- try {
- final int lineNumber = Integer.parseInt(line.substring(colon + 1, next));
- if (lineNumber > 0)
- errorLines.add(lineNumber - 1 + lineOffset); // store 0-based indices
-// System.out.println("line Np: " + (lineNumber - 1));
- } catch (final NumberFormatException e) {
- // ignore
+ /**
+ * Scrapes the 1-based lines of the script from a log: frames such as
+ * {@code Script.groovy:51} or {@code Script.java:51:}, and statements such as
+ * {@code line 51}.
+ *
+ * @param extensions the extensions of the script language
+ * @param fileName the name of the script, used for Java sources
+ */
+ static TreeSet scrape(final String log, final String fileName, final Collection extensions,
+ final boolean isJava)
+ {
+ final Pattern frame;
+ if (isJava) {
+ // Compiler messages (Foo.java:12: error) and runtime frames (Foo.java:12)
+ frame = Pattern.compile("(? own = new TreeSet<>(), other = new TreeSet<>(), words = new TreeSet<>();
+ for (final String text : log.split("\\R")) {
+ if (IGNORED.matcher(text).find()) continue;
+ Matcher m = (frame == null) ? null : frame.matcher(text);
+ TreeSet target;
+ if (m != null && m.find()) {
+ target = text.contains(fileName) ? own : other;
+ } else if (!isJava && (m = LINE_WORD.matcher(text)).find()) {
+ target = words;
+ } else {
+ continue;
+ }
+ try {
+ final int number = Integer.parseInt(m.group(1));
+ if (number > 0) target.add(number);
+ } catch (final NumberFormatException ignored) {
+ // too large to be a line
+ }
+ }
+ final TreeSet lines = new TreeSet<>(own.isEmpty() ? other : own);
+ lines.addAll(words);
+ return lines;
}
private void abort() {
@@ -331,23 +458,24 @@ private void abort() {
private void abort(final String msg, final boolean offsetNotice) {
abort();
- if (writer != null) {
+ // A run is parsed from its exception and from its console: tell once
+ if (writer != null && !noticeShown) {
+ noticeShown = true;
String finalMsg = "[INFO] " + msg + "\n";
if (offsetNotice)
finalMsg += "[INFO] Reported error line(s) may not match line numbers in the editor\n";
- writer.textArea.insert(finalMsg, lengthOfJTextAreaWriter);
+ final int at = Math.min(lengthOfJTextAreaWriter, writer.textArea.getDocument().getLength());
+ writer.textArea.insert(finalMsg, at);
}
- errorLines = null;
}
/**
- * This is just so that we can register errorLines in the Editor's
+ * This is just so that we can register the errors in the Editor's
* {@link org.fife.ui.rsyntaxtextarea.ErrorStrip}
*/
class ErrorStripNotifyingParser extends AbstractParser {
private final DefaultParseResult result;
- private final boolean highlightAbnoxiously = true;
public ErrorStripNotifyingParser() {
result = new DefaultParseResult(this);
@@ -355,7 +483,7 @@ public ErrorStripNotifyingParser() {
@Override
public boolean isEnabled() {
- return enabled && errorLines != null;
+ return enabled && !errors.isEmpty();
}
@Override
@@ -365,25 +493,18 @@ public ParseResult parse(final RSyntaxDocument doc, final String style) {
result.clearNotices();
result.setParsedLines(0, lineCount - 1);
if (isEnabled() && !SyntaxConstants.SYNTAX_STYLE_NONE.equals(style)) {
- errorLines.forEach(line -> {
- result.addNotice(new ErrorNotice(this, line));
- });
- if (highlightAbnoxiously) {
- final Color c = highlightColor();
- errorLines.forEach(line -> {
- try {
- editorPane.addLineHighlight(line, c);
- } catch (final BadLocationException ignored) {
- // do nothing
- }
- });
+ for (final FlaggedLine e : errors) {
+ // The document may be edited while parsing
+ final int index = root.getElementIndex(e.position().getOffset());
+ final Element line = root.getElement(index);
+ if (line != null) result.addNotice(new ErrorNotice(this, index, line));
}
}
return result;
-
}
}
+
private Color highlightColor() {
// https://stackoverflow.com/a/29576746
final Color c1 = editorPane.getCurrentLineHighlightColor();
@@ -395,34 +516,20 @@ protected static Color averageColors(final Color c1, final Color c2) {
// https://stackoverflow.com/a/29576746
final int r = (int) Math.sqrt( (Math.pow(c1.getRed(), 2) + Math.pow(c2.getRed(), 2)) / 2);
final int g = (int) Math.sqrt( (Math.pow(c1.getGreen(), 2) + Math.pow(c2.getGreen(), 2)) / 2);
- final int b = (int) Math.sqrt( (Math.pow(c1.getBlue(), 2) + Math.pow(c2.getGreen(), 2)) / 2);
+ final int b = (int) Math.sqrt( (Math.pow(c1.getBlue(), 2) + Math.pow(c2.getBlue(), 2)) / 2);
return new Color(r, g, b, c1.getAlpha());
}
class ErrorNotice extends DefaultParserNotice {
- public ErrorNotice(final Parser parser, final int line) {
- super(parser, "Run Error: Line " + (line + 1), line);
+ /* Notice lines are 1-based. The offset and length make the error strip
+ * mark, the editor underline and the click action agree on the line */
+ public ErrorNotice(final Parser parser, final int line, final Element lineElement) {
+ super(parser, "Run Error: Line " + (line + 1), line + 1, lineElement.getStartOffset(),
+ Math.max(1, lineElement.getEndOffset() - 1 - lineElement.getStartOffset()));
setColor(COLOR);
setLevel(Level.ERROR);
setShowInEditor(true);
}
}
-
- public static void main(final String[] args) throws Exception {
- // poor man's test for REGEX filtering
- final String groovy = " at Script1.run(Script1.groovy:51)";
- final String python = "File \"New_.py\", line 51, in ";
- final String ruby = " at Batch_Convert.rb:51";
- final String scala = " at line number 51 at column number 18";
- final String beanshell = "or class name: Systesm : at Line: 51 : in file: ";
- final String javascript = " at jdk.nashorn.internal.scripts.Script$15$Greeting.:program(Greeting.js:51)";
- Arrays.asList(groovy, python, ruby, scala, beanshell, javascript).forEach(lang -> {
- final ErrorParser parser = new ErrorParser(new EditorPane());
- final TreeSet errorLines = new TreeSet<>();
- parser.extractLineIndicesFromFilteredTextLines(lang, errorLines);
- assert (errorLines.first() == 50);
- System.out.println((errorLines.first() == 50) + ": <<" + lang + ">> ");
- });
- }
}
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 c34c1737..cf64851b 100644
--- a/src/main/java/org/scijava/ui/swing/script/TextEditor.java
+++ b/src/main/java/org/scijava/ui/swing/script/TextEditor.java
@@ -3580,6 +3580,7 @@ private void execute(final boolean selectionOnly) throws IOException {
}
else {
text = tab.getEditorPane().getText();
+ getEditorPane().getErrorHighlighter().setSelectedCodeExecution(false);
}
execute(tab, text, false);
@@ -3596,6 +3597,8 @@ private void execute(final boolean selectionOnly) throws IOException {
private void execute(final TextEditorTab tab, final String text, final boolean writeCommandLog) throws IOException {
tab.prepare();
+ // Prompt commands have no lines in the editor
+ if (writeCommandLog) getEditorPane().getErrorHighlighter().setPromptExecution();
final JTextAreaWriter output = new JTextAreaWriter(tab.screen, log);
final JTextAreaWriter errors = new JTextAreaWriter(errorScreen, log);
@@ -3749,6 +3752,7 @@ public void runScript() {
else getTab().showOutput();
markCompileStart();
+ getEditorPane().getErrorHighlighter().setSelectedCodeExecution(false);
final JTextAreaWriter output = new JTextAreaWriter(getTab().screen, log);
final JTextAreaWriter errors = new JTextAreaWriter(errorScreen, log);
@@ -3813,6 +3817,8 @@ public void markCompileStart() {
public void markCompileStart(final boolean with_timestamp) {
errorHandler = null;
+ // Errors flagged by a previous run are outdated
+ getEditorPane().getErrorHighlighter().reset();
getTab().startNewRun();
if (with_timestamp) {
@@ -4297,6 +4303,7 @@ private Reader evalScript(final String filename, Reader reader,
}
catch (final ExecutionException e) {
log.error(e);
+ getEditorPane().getErrorHighlighter().parse(e);
} finally {
getEditorPane().getErrorHighlighter().parse();
}
diff --git a/src/test/java/org/scijava/ui/swing/script/ErrorParserTest.java b/src/test/java/org/scijava/ui/swing/script/ErrorParserTest.java
new file mode 100644
index 00000000..0f8a6705
--- /dev/null
+++ b/src/test/java/org/scijava/ui/swing/script/ErrorParserTest.java
@@ -0,0 +1,113 @@
+/*
+ * #%L
+ * Script Editor and Interpreter for SciJava script languages.
+ * %%
+ * Copyright (C) 2009 - 2026 SciJava developers.
+ * %%
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ * #L%
+ */
+
+package org.scijava.ui.swing.script;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.awt.Color;
+import java.util.List;
+import java.util.Set;
+import java.util.TreeSet;
+
+import javax.script.ScriptException;
+
+import org.junit.Test;
+
+public class ErrorParserTest {
+
+ private static Set scrape(final String log, final String ext) {
+ return ErrorParser.scrape(log, "Script." + ext, List.of(ext), false);
+ }
+
+ @Test
+ public void testRuntimeFormats() {
+ assertEquals(Set.of(51), scrape("\tat Script1.run(Script1.groovy:51)", "groovy"));
+ assertEquals(Set.of(51), scrape("File \"New_.py\", line 51, in ", "py"));
+ assertEquals(Set.of(51), scrape(" at Batch_Convert.rb:51", "rb"));
+ assertEquals(Set.of(51), scrape(" at line number 51 at column number 18", "scala"));
+ assertEquals(Set.of(51), scrape("or class name: Systesm : at Line: 51 : in file: ", "bsh"));
+ assertEquals(Set.of(51), scrape("\tat jdk.nashorn.internal.scripts.Script$15$Greeting.:program(Greeting.js:51)", "js"));
+ }
+
+ @Test
+ public void testIgnoresLookalikes() {
+ assertTrue(scrape("Connecting to localhost:8080", "groovy").isEmpty());
+ assertTrue(scrape("Invalid command line argument 5", "py").isEmpty());
+ assertTrue(scrape("at 12:30:45 inline pipeline deadline: 3", "py").isEmpty());
+ assertTrue(scrape("\tat foo.Bar.run(Bar.java:123)", "r").isEmpty());
+ assertTrue(scrape("\tat org.python.core.PyException.(PyException.java:123)", "py").isEmpty());
+ assertTrue(scrape("\tat org.codehaus.groovy.runtime.callsite.Foo.call(Foo.groovy:99)", "groovy").isEmpty());
+ }
+
+ @Test
+ public void testPrefersOwnScript() {
+ final String log = "at Helper.run(Helper.groovy:12)\nat Script.run(Script.groovy:5)";
+ assertEquals(Set.of(5), scrape(log, "groovy"));
+ // Names in frames may differ from the editor's: use what we have
+ assertEquals(Set.of(12), scrape("at Helper.run(Helper.groovy:12)", "groovy"));
+ }
+
+ @Test
+ public void testJava() {
+ final String name = "Foo.java";
+ assertEquals(Set.of(12), ErrorParser.scrape("/tmp/Foo.java:12: error: ';' expected", name, List.of("java"), true));
+ assertEquals(Set.of(12), ErrorParser.scrape("Foo.java:12: error: ';' expected", name, List.of("java"), true));
+ assertEquals(Set.of(7), ErrorParser.scrape("\tat Foo.run(Foo.java:7)", name, List.of("java"), true));
+ assertTrue(ErrorParser.scrape("/tmp/MyFoo.java:12: error", name, List.of("java"), true).isEmpty());
+ }
+
+ @Test
+ public void testSeveralLinesAndOverflow() {
+ assertEquals(new TreeSet<>(List.of(3, 8)), scrape("x.groovy:3\nnoise\ny.groovy:8\nz.groovy:99999999999", "groovy"));
+ }
+
+ @Test
+ public void testFromThrowable() {
+ final ScriptException se = new ScriptException("boom", "/some/dir/Script.groovy", 4);
+ final Exception wrapper = new RuntimeException("wrapped", se);
+ wrapper.setStackTrace(new StackTraceElement[] { //
+ new StackTraceElement("Script", "run", "Script.groovy", 9), //
+ new StackTraceElement("org.Foo", "bar", "Foo.java", 77) });
+ final TreeSet lines = new TreeSet<>();
+ ErrorParser.fromThrowable(wrapper, "Script.groovy", lines);
+ assertEquals(Set.of(4, 9), lines);
+ // Errors in other files are not ours
+ lines.clear();
+ ErrorParser.fromThrowable(new ScriptException("x", "Other.groovy", 5), "Script.groovy", lines);
+ assertTrue(lines.isEmpty());
+ }
+
+ @Test
+ public void testAverageColors() {
+ final Color c = ErrorParser.averageColors(new Color(0, 0, 255), new Color(0, 255, 0));
+ assertEquals(c.getGreen(), c.getBlue());
+ }
+}
From 7d99659a96872533863b357927d6782e18d372ad Mon Sep 17 00:00:00 2001
From: Tiago Ferreira
Date: Sun, 15 Nov 2026 21:00:55 -0500
Subject: [PATCH 25/41] Wip:
- Activate REPL on display
- Color code Tasks in Error Strip
- Simplify help menu items with help buttons to Notes Panel
- Remove code duplication
---
.../ui/swing/script/FileSystemTreePanel.java | 6 +-
.../org/scijava/ui/swing/script/GuiUtils.java | 22 +++++++
.../ui/swing/script/ScalableErrorStrip.java | 4 +-
.../scijava/ui/swing/script/TasksPanel.java | 31 +++++++++-
.../scijava/ui/swing/script/TextEditor.java | 60 ++++++++++++++-----
.../ui/swing/script/TextEditorTab.java | 9 +--
6 files changed, 101 insertions(+), 31 deletions(-)
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 08bf1093..f5136510 100644
--- a/src/main/java/org/scijava/ui/swing/script/FileSystemTreePanel.java
+++ b/src/main/java/org/scijava/ui/swing/script/FileSystemTreePanel.java
@@ -194,11 +194,7 @@ private JToolBar statusToolbar() {
toolbar.addSeparator();
toolbar.add(statusOptions);
toolbar.add(Box.createHorizontalGlue());
- final FlatHelpButtonIcon helpIcon = new FlatHelpButtonIcon();
- helpIcon.setScale(.8f); // matches the font size set by the "small" style
- helpIcon.applyStyleProperty("questionMarkColor", GuiUtils.secondaryColor());
- helpIcon.applyStyleProperty("background", toolbar.getBackground());
- final JButton statusHelp = new JButton(helpIcon);
+ 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 a75b6527..e35dca06 100644
--- a/src/main/java/org/scijava/ui/swing/script/GuiUtils.java
+++ b/src/main/java/org/scijava/ui/swing/script/GuiUtils.java
@@ -78,6 +78,7 @@
import com.formdev.flatlaf.FlatClientProperties;
import com.formdev.flatlaf.FlatLaf;
+import com.formdev.flatlaf.icons.FlatHelpButtonIcon;
/** Static helpers for dialogs, menus and widgets shared by the script editor */
final class GuiUtils {
@@ -369,6 +370,27 @@ static JButton ellipsisButton(final Runnable action) {
}
+ /** 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) {
+ 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");
+ b.setBorder(null);
+ }
+ if (action != null) b.addActionListener(e -> action.run());
+ return b;
+ }
+
/** Rounded scrollbar thumbs without arrow buttons (FlatLaf only) */
static void flattenScrollBars(final JScrollPane scrollPane) {
final String style = "showButtons: false; trackArc: 999; thumbArc: 999; "
diff --git a/src/main/java/org/scijava/ui/swing/script/ScalableErrorStrip.java b/src/main/java/org/scijava/ui/swing/script/ScalableErrorStrip.java
index 28144be8..af6fb355 100644
--- a/src/main/java/org/scijava/ui/swing/script/ScalableErrorStrip.java
+++ b/src/main/java/org/scijava/ui/swing/script/ScalableErrorStrip.java
@@ -38,6 +38,7 @@
import org.fife.ui.rsyntaxtextarea.ErrorStrip;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import org.fife.ui.rsyntaxtextarea.parser.ParserNotice;
+import org.fife.ui.rsyntaxtextarea.parser.TaskTagParser;
import com.formdev.flatlaf.util.UIScale;
@@ -80,7 +81,8 @@ protected void paintCaretMarker(final Graphics2D g, final int width, final int h
@Override
protected void paintParserNoticeMarker(final Graphics2D g, final ParserNotice notice, final int width,
final int height) {
- final Color c = notice.getColor();
+ final Color tag = (notice instanceof TaskTagParser.TaskNotice) ? TasksPanel.tagColor(notice.getMessage()) : null;
+ final Color c = (tag != null) ? tag : notice.getColor();
FlatUIUtils.setRenderingHints(g);
g.setColor(c == null ? Color.GRAY : c);
g.fillRect(0, 0, width, height);
diff --git a/src/main/java/org/scijava/ui/swing/script/TasksPanel.java b/src/main/java/org/scijava/ui/swing/script/TasksPanel.java
index d1193890..02fdc3d5 100644
--- a/src/main/java/org/scijava/ui/swing/script/TasksPanel.java
+++ b/src/main/java/org/scijava/ui/swing/script/TasksPanel.java
@@ -30,6 +30,7 @@
package org.scijava.ui.swing.script;
import java.awt.BorderLayout;
+import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
@@ -64,6 +65,8 @@ record Task(TextEditorTab tab, int line, int offset, String text) {}
private static final long serialVersionUID = 1L;
private static final int REFRESH_DELAY_MS = 1500;
private static final int TEXT_MAX_CHARS = 100;
+ private static final String[] TAGS = { "TODO", "FIXME", "HACK" };
+ private static final Color[] TAG_COLORS = { new Color(48, 150, 252), new Color(237, 137, 54), new Color(155, 112, 225) };
private final Supplier> source;
private final DefaultListModel model = new DefaultListModel<>();
@@ -125,6 +128,24 @@ public void keyPressed(final KeyEvent e) {
poll.start();
}
+ /** The task keyword a comment starts with, or null */
+ static String tagOf(final String text) {
+ for (final String tag : TAGS)
+ if (text.startsWith(tag)) return tag;
+ return null;
+ }
+
+ /** The color of the keyword a task comment starts with, or null */
+ static Color tagColor(final String text) {
+ for (int i = 0; i < TAGS.length; i++)
+ if (text.startsWith(TAGS[i])) return TAG_COLORS[i];
+ return null;
+ }
+
+ private static String escape(final String s) {
+ return s.replace("&", "&").replace("<", "<").replace(">", ">");
+ }
+
/** Brings the list up to date (cheap if nothing changed). */
void refresh() {
final List current = source.get();
@@ -157,8 +178,14 @@ public Component getListCellRendererComponent(final JList> l,
String text = t.text();
if (text.length() > TEXT_MAX_CHARS) text = text.substring(0,
TEXT_MAX_CHARS) + "...";
- super.getListCellRendererComponent(l, (name == null ? "Untitled" : name) +
- ":" + t.line() + " " + text, index, selected, focus);
+ final String where = (name == null ? "Untitled" : name) + ":" + t.line();
+ final String tag = tagOf(text);
+ // Colored keyword, unless selected (the selection color needs contrast)
+ final String label = (tag == null || selected) ? where + " " + text
+ : "" + escape(where) + " " + tag + "" + escape(text
+ .substring(tag.length())) + "";
+ super.getListCellRendererComponent(l, label, index, selected, focus);
setBorder(new EmptyBorder(2, 6, 2, 6));
setToolTipText(t.text());
return this;
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 cf64851b..98074514 100644
--- a/src/main/java/org/scijava/ui/swing/script/TextEditor.java
+++ b/src/main/java/org/scijava/ui/swing/script/TextEditor.java
@@ -381,10 +381,10 @@ public TextEditor(final Context context) {
// Markers: bookmarks and tasks of all open tabs
final JPanel pane2 = new JPanel(new BorderLayout());
- pane2.add(header("Bookmarks"), BorderLayout.NORTH);
+ pane2.add(header("Bookmarks", this::showBookmarksHelp), BorderLayout.NORTH);
pane2.add(bookmarksPanel, BorderLayout.CENTER);
final JPanel pane3 = new JPanel(new BorderLayout());
- final JLabel tasksHeader = header("Tasks");
+ final JComponent tasksHeader = header("Tasks", this::showTasksHelp);
pane3.add(tasksHeader, BorderLayout.NORTH);
pane3.add(tasksPanel, BorderLayout.CENTER);
markersSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT, pane2, pane3);
@@ -957,6 +957,44 @@ private JLabel header(final String text) {
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 void showTasksHelp() {
+ showHTMLDialog("Task Tags Help", """
+ Comments containing TODO, FIXME or HACK are
+ registered as tasks automatically:
+
+ - They are listed in the Tasks section of the Markers tab, for all open
+ tabs. Double-click (or press Enter on) an entry to jump to it
+ - They are marked on the rightmost side of the editor, each keyword with its own color:
+ blue (
TODO), orange (FIXME) and purple (HACK).
+ Mouse over a mark for a summary of the task, and click on it to go to the line
+ - To remove a task, delete the keyword from the comment
+
""");
+ }
+
+ private void showBookmarksHelp() {
+ showHTMLDialog("Bookmarks Help", """
+ Bookmarks flag lines you want to come back to:
+
+ - Click next to a line number to add or remove a bookmark
+ - They are listed in the Bookmarks section of the Markers tab, for all
+ open tabs. Double-click (or press Enter on) an entry to jump to it
+ - Press Delete to remove the selected bookmark. Right-click an entry for more options,
+ e.g., to clear all bookmarks
+
""");
+ }
+
private void assembleEditMenu() {
// requires an existing instance of an EditorPane
final int ctrl = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
@@ -4531,20 +4569,10 @@ private JMenu helpMenu() {
item.addActionListener(e -> displayRecordableMap());
menu.add(item);
item = new JMenuItem("Task Tags How-To...");
- item.addActionListener(e -> {
- showHTMLDialog("Task Tags Help", //
- ""
- + "When inserted in source code comments, the following keywords will automatically " //
- + "register task definitions on the rightmost side of the Editor: TODO, " //
- + "README, and HACK.
" //
- + "" //
- + "- To add a task, simply type one of the keywords in a commented line, e.g., "//
- + "
TODO "//
- + "- To remove a task, delete the keyword from the comment
" //
- + "- Mouse over the annotation mark to access a summary of the task
" //
- + "- Click on the mark to go to the annotated line
"
- + "
");
- });
+ item.addActionListener(e -> showTasksHelp());
+ menu.add(item);
+ item = new JMenuItem("Bookmarks How-To...");
+ item.addActionListener(e -> showBookmarksHelp());
menu.add(item);
GuiUtils.addMenubarSeparator(menu, "Contextual Help:");
menu.add(openHelpWithoutFrames);
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 bcbc4c22..f3075381 100644
--- a/src/main/java/org/scijava/ui/swing/script/TextEditorTab.java
+++ b/src/main/java/org/scijava/ui/swing/script/TextEditorTab.java
@@ -60,8 +60,6 @@
import javax.swing.text.JTextComponent;
import com.formdev.flatlaf.FlatClientProperties;
-import com.formdev.flatlaf.icons.FlatFileChooserDetailsViewIcon;
-import com.formdev.flatlaf.icons.FlatHelpButtonIcon;
import com.formdev.flatlaf.util.UIScale;
import org.fife.ui.rsyntaxtextarea.ErrorStrip;
import org.fife.ui.rsyntaxtextarea.Style;
@@ -277,11 +275,7 @@ public void dragEnter(final DropTargetDragEvent e) {
updownarrows.putClientProperty(FlatClientProperties.STYLE_CLASS, "small");
promptBar.add(Box.createHorizontalGlue());
promptBar.add(updownarrows);
- final FlatHelpButtonIcon helpIcon = new FlatHelpButtonIcon();
- helpIcon.setScale(.8f); // matches the font size set by the "small" style
- helpIcon.applyStyleProperty("questionMarkColor", GuiUtils.secondaryColor());
- helpIcon.applyStyleProperty("background", promptBar.getBackground());
- final JButton statusHelp = new JButton(helpIcon);
+ final JButton statusHelp = GuiUtils.helpButton(null);
statusHelp.addActionListener(a -> {
final int shift = InputEvent.SHIFT_DOWN_MASK;
final int ctrl = InputEvent.CTRL_DOWN_MASK;
@@ -367,6 +361,7 @@ void setREPLEnabled(final boolean enable) {
prompt.setEnabled(enable);
promptPanel.setVisible(enable);
textEditor.syncStatusBar();
+ if (enable) prompt.requestFocusInWindow();
}
/** Whether the bottom part (output and prompt) is showing, i.e., not collapsed */
From 8d0376859130d38798730e46eb5fce44292465c2 Mon Sep 17 00:00:00 2001
From: Tiago Ferreira
Date: Sun, 15 Nov 2026 21:14:29 -0500
Subject: [PATCH 26/41] Refine side panels
- Apply blended scroll tracks to all side panels
- Add basic actions to scratchpad context menu
- Fix bookmark markers icon alignment
- Improve main tab layout
- Remember active tab in side panel across restarts
- Remove outdate menu items
---
.../ui/swing/script/CommandPalette.java | 10 +++
.../org/scijava/ui/swing/script/GuiUtils.java | 62 +++++++++++--------
.../scijava/ui/swing/script/GutterUtils.java | 23 ++++++-
.../scijava/ui/swing/script/NotesPanel.java | 42 ++++++++++++-
.../ui/swing/script/OutlineTreePanel.java | 6 ++
.../scijava/ui/swing/script/TextEditor.java | 36 ++++++-----
6 files changed, 135 insertions(+), 44 deletions(-)
diff --git a/src/main/java/org/scijava/ui/swing/script/CommandPalette.java b/src/main/java/org/scijava/ui/swing/script/CommandPalette.java
index d7c56bfa..afc81c22 100644
--- a/src/main/java/org/scijava/ui/swing/script/CommandPalette.java
+++ b/src/main/java/org/scijava/ui/swing/script/CommandPalette.java
@@ -219,6 +219,16 @@ void dispose() {
frame = null;
}
+ /** Hides the palette */
+ protected void hide() {
+ if (frame == null || !frame.isVisible()) return;
+ if (SwingUtilities.isEventDispatchThread()) {
+ hideWindow();
+ } else {
+ SwingUtilities.invokeLater(this::hideWindow);
+ }
+ }
+
private void hideWindow() {
if (frame != null) {
if (frame.isVisible())
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 e35dca06..5f03f320 100644
--- a/src/main/java/org/scijava/ui/swing/script/GuiUtils.java
+++ b/src/main/java/org/scijava/ui/swing/script/GuiUtils.java
@@ -52,26 +52,7 @@
import java.util.Map;
import java.util.List;
import java.util.ArrayList;
-
-import javax.swing.ButtonGroup;
-import javax.swing.JButton;
-import javax.swing.JCheckBoxMenuItem;
-import javax.swing.JComponent;
-import javax.swing.JDialog;
-import javax.swing.JLabel;
-import javax.swing.JMenu;
-import javax.swing.JMenuItem;
-import javax.swing.JOptionPane;
-import javax.swing.JPanel;
-import javax.swing.JPopupMenu;
-import javax.swing.JScrollPane;
-import javax.swing.JSplitPane;
-import javax.swing.JTabbedPane;
-import javax.swing.JTextPane;
-import javax.swing.JTree;
-import javax.swing.KeyStroke;
-import javax.swing.SwingUtilities;
-import javax.swing.UIManager;
+import javax.swing.*;
import org.scijava.platform.PlatformService;
import org.scijava.util.PlatformUtils;
@@ -391,12 +372,36 @@ private static JButton helpButton(final Runnable action, final float scale, fina
return b;
}
- /** Rounded scrollbar thumbs without arrow buttons (FlatLaf only) */
+ /**
+ * Rounded scrollbar thumbs without arrow buttons (FlatLaf only), on tracks that blend into the
+ * view: the tracks and corner follow the background of the view, e.g., after a theme change
+ */
static void flattenScrollBars(final JScrollPane scrollPane) {
- final String style = "showButtons: false; trackArc: 999; thumbArc: 999; "
- + "trackInsets: 2,2,2,2; thumbInsets: 2,2,2,2";
- scrollPane.getVerticalScrollBar().putClientProperty(FlatClientProperties.STYLE, style);
- scrollPane.getHorizontalScrollBar().putClientProperty(FlatClientProperties.STYLE, style);
+ final Component view = scrollPane.getViewport().getView();
+ final Runnable apply = () -> {
+ String style = "showButtons: false; trackArc: 999; thumbArc: 999; "
+ + "trackInsets: 2,2,2,2; thumbInsets: 2,2,2,2";
+ final Color bg = (view == null) ? null : view.getBackground();
+ if (bg != null) {
+ final String hex = String.format("#%06x", bg.getRGB() & 0xFFFFFF);
+ style += "; track: " + hex + "; hoverTrackColor: " + hex;
+ Component corner = scrollPane.getCorner(JScrollPane.LOWER_TRAILING_CORNER);
+ if (corner == null) {
+ corner = new JPanel();
+ scrollPane.setCorner(JScrollPane.LOWER_TRAILING_CORNER, corner);
+ }
+ corner.setBackground(bg);
+ }
+ scrollPane.getVerticalScrollBar().putClientProperty(FlatClientProperties.STYLE, style);
+ scrollPane.getHorizontalScrollBar().putClientProperty(FlatClientProperties.STYLE, style);
+ if (bg != null) {
+ // the scroll bar background shows as a 1px fringe around the rounded track
+ scrollPane.getVerticalScrollBar().setBackground(bg);
+ scrollPane.getHorizontalScrollBar().setBackground(bg);
+ }
+ };
+ apply.run();
+ if (view != null) view.addPropertyChangeListener("background", e -> apply.run());
}
/**
@@ -503,7 +508,12 @@ static JTabbedPane getJTabbedPane() {
final JButton triggerButton = ellipsisButton(null);
triggerButton.addActionListener( e -> popup.show(triggerButton,
triggerButton.getWidth() /2, triggerButton.getHeight() /2));
- tabbed.putClientProperty(FlatClientProperties.TABBED_PANE_TRAILING_COMPONENT, triggerButton);
+ // With leading alignment the trailing component is stretched to the free
+ // space: a wrapper keeps the button itself flushed to the right
+ final JPanel trailing = new JPanel(new java.awt.BorderLayout());
+ trailing.setOpaque(false);
+ trailing.add(triggerButton, java.awt.BorderLayout.EAST);
+ tabbed.putClientProperty(FlatClientProperties.TABBED_PANE_TRAILING_COMPONENT, trailing);
return tabbed;
}
diff --git a/src/main/java/org/scijava/ui/swing/script/GutterUtils.java b/src/main/java/org/scijava/ui/swing/script/GutterUtils.java
index 645bde5e..1bc8506b 100644
--- a/src/main/java/org/scijava/ui/swing/script/GutterUtils.java
+++ b/src/main/java/org/scijava/ui/swing/script/GutterUtils.java
@@ -60,7 +60,7 @@ private void updateBookmarkIcon() {
// this will clear existing bookmarks, so we'll need restore existing ones
final GutterIconInfo[] stash = gutter.getBookmarks();
- gutter.setBookmarkIcon(Icons.bookmark(color, UIScale.unscale(height)));
+ gutter.setBookmarkIcon(padded(Icons.bookmark(color, UIScale.unscale(height)), 3));
for (final GutterIconInfo info : stash) {
try {
@@ -71,6 +71,27 @@ private void updateBookmarkIcon() {
}
}
+ /** The icon is painted flush left in the icon column: pad it to center it */
+ private static javax.swing.Icon padded(final javax.swing.Icon icon, final int unscaledPad) {
+ final int pad = UIScale.scale(unscaledPad);
+ return new javax.swing.Icon() {
+ @Override
+ public void paintIcon(final java.awt.Component c, final java.awt.Graphics g, final int x, final int y) {
+ icon.paintIcon(c, g, x + pad, y);
+ }
+
+ @Override
+ public int getIconWidth() {
+ return icon.getIconWidth() + 2 * pad;
+ }
+
+ @Override
+ public int getIconHeight() {
+ return icon.getIconHeight();
+ }
+ };
+ }
+
public static void updateIcons(final Gutter gutter, final RTextArea textArea) {
final GutterUtils utils = new GutterUtils(gutter, textArea);
utils.updateBookmarkIcon();
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 735e28f6..6530a1ee 100644
--- a/src/main/java/org/scijava/ui/swing/script/NotesPanel.java
+++ b/src/main/java/org/scijava/ui/swing/script/NotesPanel.java
@@ -69,6 +69,7 @@ class NotesPanel extends JPanel {
private static final long serialVersionUID = 1L;
private static final String PREFS_COUNT = "script.editor.notes.chunks";
private static final String PREFS_CHUNK = "script.editor.notes.chunk";
+ private static final String PREFS_WRAP = "script.editor.notes.wrap";
private static final int CHUNK_SIZE = 4000;
private static final int MAX_CHARS = 200000;
private static final int SAVE_DELAY_MS = 1000;
@@ -114,10 +115,9 @@ protected void paintComponent(final java.awt.Graphics g) {
"They are saved between sessions");
}
};
- scratch.setLineWrap(true);
+ scratch.setLineWrap(prefs.getBoolean(prefsOwner, PREFS_WRAP, true));
scratch.setWrapStyleWord(true);
- scratch.setBorder(new EmptyBorder(4, 4, 4, 4));
- scratch.setToolTipText("Scratchpad: free text, saved between sessions");
+ scratch.setComponentPopupMenu(scratchMenu());
final JScrollPane scratchPane = new JScrollPane(scratch);
GuiUtils.flattenScrollBars(scratchPane);
@@ -212,6 +212,42 @@ public void changedUpdate(final DocumentEvent e) {
poll.start();
}
+ private JPopupMenu scratchMenu() {
+ final JPopupMenu menu = new JPopupMenu();
+ final JCheckBoxMenuItem wrap = new JCheckBoxMenuItem("Wrap Lines");
+ wrap.addActionListener(e -> {
+ scratch.setLineWrap(wrap.isSelected());
+ prefs.put(prefsOwner, PREFS_WRAP, wrap.isSelected());
+ });
+ menu.add(wrap);
+ menu.addSeparator();
+ final JMenuItem discard = new JMenuItem("Discard");
+ discard.addActionListener(e -> {
+ if (GuiUtils.confirm(this, "Discard the contents of the scratchpad?", "Discard Scratchpad?",
+ "Discard")) scratch.setText("");
+ });
+ menu.add(discard);
+ menu.addPopupMenuListener(new javax.swing.event.PopupMenuListener() {
+
+ @Override
+ public void popupMenuWillBecomeVisible(final javax.swing.event.PopupMenuEvent e) {
+ wrap.setSelected(scratch.getLineWrap());
+ discard.setEnabled(scratch.getDocument().getLength() > 0);
+ }
+
+ @Override
+ public void popupMenuWillBecomeInvisible(final javax.swing.event.PopupMenuEvent e) {
+ // nothing to do
+ }
+
+ @Override
+ public void popupMenuCanceled(final javax.swing.event.PopupMenuEvent e) {
+ // nothing to do
+ }
+ });
+ return menu;
+ }
+
/** Flushes pending scratchpad changes to the preferences. */
void flush() {
if (saveTimer.isRunning()) {
diff --git a/src/main/java/org/scijava/ui/swing/script/OutlineTreePanel.java b/src/main/java/org/scijava/ui/swing/script/OutlineTreePanel.java
index e2a00eb9..bced2b4c 100644
--- a/src/main/java/org/scijava/ui/swing/script/OutlineTreePanel.java
+++ b/src/main/java/org/scijava/ui/swing/script/OutlineTreePanel.java
@@ -62,6 +62,12 @@ class OutlineTreePanel extends JScrollPane {
setViewportView(new UnsupportedLangTree());
}
+ @Override
+ public void setViewportView(final java.awt.Component view) {
+ super.setViewportView(view);
+ GuiUtils.flattenScrollBars(this); // tracks follow the background of each new view
+ }
+
protected void rebuildSourceTree(final EditorPane pane) {
if (!isVisible())
return;
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 98074514..7bb4a0ce 100644
--- a/src/main/java/org/scijava/ui/swing/script/TextEditor.java
+++ b/src/main/java/org/scijava/ui/swing/script/TextEditor.java
@@ -246,6 +246,7 @@ public class TextEditor extends JFrame implements ActionListener,
private boolean consoleWrap, replWrap;
private static final String CONSOLE_WRAP_PREFS = "script.editor.ConsoleWrap";
private static final String REPL_WRAP_PREFS = "script.editor.ReplWrap";
+ private static final String SIDE_TAB_PREFS = "script.editor.SideTab";
private JButton statusPos, statusLang;
private JToggleButton statusSide, statusBelow, statusRight, statusRepl, statusVimToggle;
private int sideLastLocation = -1;
@@ -340,7 +341,7 @@ 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_FILL);
+ 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,
@@ -777,7 +778,9 @@ public TextEditor(final Context context) {
// add tab-related listeners
tabbed.addChangeListener(this);
sideTabs.addChangeListener(e -> {
- if (sideTabs.getSelectedIndex() == 1)
+ final int sel = sideTabs.getSelectedIndex();
+ if (sel > -1) prefService.put(getClass(), SIDE_TAB_PREFS, sideTabs.getTitleAt(sel));
+ if (SwingUtilities.isDescendingFrom(sourceTreePanel, sideTabs.getSelectedComponent()))
sourceTreePanel.rebuildSourceTree(getTab(tabbed.getSelectedIndex()).editorPane);
});
@@ -795,6 +798,13 @@ public TextEditor(final Context context) {
}
});
open(null); // make sure the editor pane is added
+ final String lastSideTab = prefService.get(getClass(), SIDE_TAB_PREFS, null);
+ for (int i = 0; lastSideTab != null && i < sideTabs.getTabCount(); i++) {
+ if (lastSideTab.equals(sideTabs.getTitleAt(i))) {
+ sideTabs.setSelectedIndex(i);
+ break;
+ }
+ }
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
// Tweaks for JSplitPane
@@ -969,23 +979,26 @@ private JComponent header(final String text, final Runnable help) {
return panel;
}
+ private static String tagHtml(final String tag) {
+ return String.format("%s", TasksPanel.tagColor(tag).getRGB() & 0xFFFFFF, tag);
+ }
+
private void showTasksHelp() {
showHTMLDialog("Task Tags Help", """
- Comments containing TODO, FIXME or HACK are
- registered as tasks automatically:
+
+ Comments containing %s, %s or %s are registered as tasks automatically:
- They are listed in the Tasks section of the Markers tab, for all open
tabs. Double-click (or press Enter on) an entry to jump to it
- - They are marked on the rightmost side of the editor, each keyword with its own color:
- blue (
TODO), orange (FIXME) and purple (HACK).
+ - They are marked on the rightmost side of the editor, each keyword with its own color.
Mouse over a mark for a summary of the task, and click on it to go to the line
- To remove a task, delete the keyword from the comment
-
""");
+ """.formatted(tagHtml("TODO"), tagHtml("FIXME"), tagHtml("HACK")));
}
private void showBookmarksHelp() {
showHTMLDialog("Bookmarks Help", """
-
Bookmarks flag lines you want to come back to:
+
Bookmarks flag lines you want to come back to:
- Click next to a line number to add or remove a bookmark
- They are listed in the Bookmarks section of the Markers tab, for all
@@ -4213,6 +4226,7 @@ boolean confirm(final String message, final String title, final String yesButton
}
void showHTMLDialog(final String title, final String htmlContents) {
+ if (cmdPalette != null) cmdPalette.hide();
GuiUtils.showHTMLDialog(this, title, htmlContents);
}
@@ -4568,12 +4582,6 @@ private JMenu helpMenu() {
item = new JMenuItem("List Recordable Actions...");
item.addActionListener(e -> displayRecordableMap());
menu.add(item);
- item = new JMenuItem("Task Tags How-To...");
- item.addActionListener(e -> showTasksHelp());
- menu.add(item);
- item = new JMenuItem("Bookmarks How-To...");
- item.addActionListener(e -> showBookmarksHelp());
- menu.add(item);
GuiUtils.addMenubarSeparator(menu, "Contextual Help:");
menu.add(openHelpWithoutFrames);
openHelpWithoutFrames.setMnemonic(KeyEvent.VK_O);
From 4b5d7326e516dffde9d44e2eae54db9e26181101 Mon Sep 17 00:00:00 2001
From: Tiago Ferreira
Date: Sun, 15 Nov 2026 22:30:03 -0500
Subject: [PATCH 27/41] Workaround IllegalComponentStateException when
dragging toolbars
---
.../ui/swing/script/CommandPalette.java | 4 ++--
.../scijava/ui/swing/script/EditorPane.java | 2 +-
.../ui/swing/script/FileSystemTreePanel.java | 4 ++--
.../org/scijava/ui/swing/script/GuiUtils.java | 18 ++++++++++++++++++
.../scijava/ui/swing/script/TextEditor.java | 2 +-
.../scijava/ui/swing/script/TextEditorTab.java | 4 ++--
6 files changed, 26 insertions(+), 8 deletions(-)
diff --git a/src/main/java/org/scijava/ui/swing/script/CommandPalette.java b/src/main/java/org/scijava/ui/swing/script/CommandPalette.java
index afc81c22..121fb300 100644
--- a/src/main/java/org/scijava/ui/swing/script/CommandPalette.java
+++ b/src/main/java/org/scijava/ui/swing/script/CommandPalette.java
@@ -546,7 +546,7 @@ private static class SearchField extends TextFieldWithPlaceholder {
putClientProperty(FlatClientProperties.TEXT_FIELD_LEADING_COMPONENT, options);
caseButton = secondaryToggle("Cc", "Match case");
whitespaceButton = secondaryToggle("\u2423", "Match whitespace");
- final JToolBar tb = new JToolBar();
+ final JToolBar tb = new GuiUtils.ToolBar();
tb.setFloatable(false);
tb.setMargin(new Insets(0, 0, 0, 2));
tb.add(caseButton);
@@ -677,7 +677,7 @@ private class TitleBar {
private static final float FONT_SCALE = .9f;
JToolBar getToolBar() {
- final JToolBar toolbar = new JToolBar();
+ final JToolBar toolbar = new GuiUtils.ToolBar();
toolbar.setOpaque(false);
toolbar.setFocusable(false);
toolbar.setFloatable(false);
diff --git a/src/main/java/org/scijava/ui/swing/script/EditorPane.java b/src/main/java/org/scijava/ui/swing/script/EditorPane.java
index 1cc2b9c8..21055b5f 100644
--- a/src/main/java/org/scijava/ui/swing/script/EditorPane.java
+++ b/src/main/java/org/scijava/ui/swing/script/EditorPane.java
@@ -832,7 +832,7 @@ public void setAutoCompletion(final boolean enabled) {
* Toggles whether auto-completion should adopt Java completions if the current
* language does not support auto-completion.
*
- * @param enabled Whether Java should be enabled as fallback language for
+ * @param value Whether Java should be enabled as fallback language for
* auto-completion
*/
void setFallbackAutoCompletion(final boolean value) {
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 f5136510..03994fc7 100644
--- a/src/main/java/org/scijava/ui/swing/script/FileSystemTreePanel.java
+++ b/src/main/java/org/scijava/ui/swing/script/FileSystemTreePanel.java
@@ -166,7 +166,7 @@ public Insets getBorderInsets(final Component c) {
}
private JToolBar statusToolbar() {
- final JToolBar toolbar = new JToolBar();
+ final JToolBar toolbar = new GuiUtils.ToolBar();
toolbar.setFloatable(false);
toolbar.setBackground(tree.getBackground());
// Continue the outline of the tree's scroll pane (the latter provides the top edge)
@@ -740,7 +740,7 @@ private class SearchField extends TextFieldWithPlaceholder {
collapsedToggle.setIcon(Icons.chevron(false));
collapsedToggle.setSelectedIcon(Icons.chevron(true));
- final JToolBar tb = new JToolBar();
+ final JToolBar tb = new GuiUtils.ToolBar();
tb.setFloatable(false);
tb.setMargin(new Insets(0, 0, 0, 2));
tb.add(collapsedToggle);
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 5f03f320..51bad67a 100644
--- a/src/main/java/org/scijava/ui/swing/script/GuiUtils.java
+++ b/src/main/java/org/scijava/ui/swing/script/GuiUtils.java
@@ -85,6 +85,24 @@ static boolean confirm(final Component parent, final String message, final Strin
JOptionPane.YES_OPTION;
}
+ /**
+ * A non-floatable toolbar without the drag listeners of its L&F. They throw
+ * an IllegalComponentStateException if the toolbar is hidden during a drag
+ * (e.g., when a window auto-hides)
+ */
+ static class ToolBar extends javax.swing.JToolBar {
+
+ @Override
+ public void updateUI() {
+ super.updateUI();
+ setFloatable(false);
+ for (final java.awt.event.MouseMotionListener l : getMouseMotionListeners()) {
+ if (l.getClass().getName().startsWith("javax.swing.plaf.basic.BasicToolBarUI"))
+ removeMouseMotionListener(l);
+ }
+ }
+ }
+
static void showHTMLDialog(final Component parent, final String title, final String htmlContents) {
final JTextPane f = new JTextPane();
f.setContentType("text/html");
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 7bb4a0ce..c7dc96ce 100644
--- a/src/main/java/org/scijava/ui/swing/script/TextEditor.java
+++ b/src/main/java/org/scijava/ui/swing/script/TextEditor.java
@@ -2123,7 +2123,7 @@ public Dimension getPreferredSize() { // fixed width: neighbors do not move as t
statusVimToggle.setToolTipText(vimMode.getToolTipText());
statusVimToggle.setFocusable(false);
statusVimToggle.addActionListener(e -> vimMode.setState(statusVimToggle.isSelected()));
- final JToolBar bar = new JToolBar();
+ final JToolBar bar = new GuiUtils.ToolBar();
bar.setFloatable(false);
final int gap = 4;
bar.setBorder(BorderFactory.createEmptyBorder(0, gap, 0, gap));
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 f3075381..f148ba45 100644
--- a/src/main/java/org/scijava/ui/swing/script/TextEditorTab.java
+++ b/src/main/java/org/scijava/ui/swing/script/TextEditorTab.java
@@ -182,7 +182,7 @@ public void dragEnter(final DropTargetDragEvent e) {
mirrorInto(combinedScreen, textEditor.getErrorScreen(), true);
final JPanel bottom = new JPanel(new BorderLayout());
- final JToolBar bar = new JToolBar();
+ final JToolBar bar = new GuiUtils.ToolBar();
bar.setFloatable(false);
bar.setBorder(BorderFactory.createEmptyBorder(1, 2, 1, 2));
@@ -256,7 +256,7 @@ public void dragEnter(final DropTargetDragEvent e) {
promptPanel = prompt_panel;
prompt_panel.setLayout(new BorderLayout());
- final JToolBar promptBar = new JToolBar();
+ final JToolBar promptBar = new GuiUtils.ToolBar();
promptBar.setFloatable(false);
promptBar.putClientProperty(FlatClientProperties.STYLE_CLASS, "small");
promptBar.setBorder(null);
From 638b3a0f005e6b8b9796ecd4678d6ebcf0cbf3a0 Mon Sep 17 00:00:00 2001
From: Tiago Ferreira
Date: Sun, 15 Nov 2026 22:52:31 -0500
Subject: [PATCH 28/41] Fix several bugs when Saving/Loading files
Loading:
- Set the modified state more reliably when loading templates from JARs
- setFileName(File): detect the language without renaming the file
Saving:
- Add the proposed name as pre-selection in the JFileChooser
- Refresh the tab title after saving (before the outdated asterisk marker would remain)
- Closing the Save / Discard / Cancel prompt no longer discards the file(!)
- Fix inverted logic in the GuiUtils.confirm prompt
---
.../scijava/ui/swing/script/EditorPane.java | 55 +++++++++++++++----
.../org/scijava/ui/swing/script/GuiUtils.java | 33 ++++++++++-
.../scijava/ui/swing/script/TextEditor.java | 41 ++++++++++----
3 files changed, 104 insertions(+), 25 deletions(-)
diff --git a/src/main/java/org/scijava/ui/swing/script/EditorPane.java b/src/main/java/org/scijava/ui/swing/script/EditorPane.java
index 21055b5f..e99b36c9 100644
--- a/src/main/java/org/scijava/ui/swing/script/EditorPane.java
+++ b/src/main/java/org/scijava/ui/swing/script/EditorPane.java
@@ -39,14 +39,16 @@
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
-import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
-import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
-import java.io.OutputStreamWriter;
import java.net.URL;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.AtomicMoveNotSupportedException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
@@ -521,11 +523,34 @@ public void write(final File file) throws IOException {
throw new IOException("Cannot create directory: " + dir);
}
}
- final BufferedWriter outFile =
- new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),
- "UTF-8"));
- outFile.write(getText());
- outFile.close();
+ // Build the text first and write to a temp file, so that a failure
+ // never leaves a truncated file behind
+ final byte[] bytes = getText().getBytes(StandardCharsets.UTF_8);
+ Path target = file.toPath();
+ if (Files.isSymbolicLink(target)) target = target.toRealPath();
+ final Path tmp = Files.createTempFile(target.toAbsolutePath().getParent(),
+ ".tmp-", ".part");
+ try {
+ Files.write(tmp, bytes);
+ if (Files.exists(target)) {
+ try {
+ Files.setPosixFilePermissions(tmp, Files.getPosixFilePermissions(target));
+ }
+ catch (final UnsupportedOperationException | IOException ignored) {
+ // not a POSIX file system
+ }
+ }
+ try {
+ Files.move(tmp, target, StandardCopyOption.REPLACE_EXISTING,
+ StandardCopyOption.ATOMIC_MOVE);
+ }
+ catch (final AtomicMoveNotSupportedException e) {
+ Files.move(tmp, target, StandardCopyOption.REPLACE_EXISTING);
+ }
+ }
+ finally {
+ Files.deleteIfExists(tmp);
+ }
modifyCount = 0;
fileLastModified = file.lastModified();
}
@@ -567,7 +592,10 @@ public void open(final File file) throws IOException {
}
try {
setText(string.toString());
- } catch (final Error | IndexOutOfBoundsException e2) {
+ } catch (final OutOfMemoryError oom) {
+ // Do not leave an empty editor that could overwrite the file
+ throw new IOException("Not enough memory to open " + file.getName(), oom);
+ } catch (final StackOverflowError | IndexOutOfBoundsException e2) {
// Mysterious parsing errors w/ IJM!? Syntax highlighting will
// fail but things should be back to normal on next repaint. See
// https://github.com/scijava/script-editor/issues/14
@@ -629,7 +657,7 @@ public void setFileName(final File file) {
curFile = file;
if (file != null) {
- setLanguageByFileName(file.getName());
+ setLanguageByFileName(file.getName(), false);
fallBackBaseName = null;
}
fileLastModified = file == null || !file.exists() ? 0 : file.lastModified();
@@ -687,9 +715,14 @@ protected String getFileName() {
* @see #setLanguage(ScriptLanguage, boolean)
*/
protected void setLanguageByFileName(final String name) {
+ setLanguageByFileName(name, true);
+ }
+
+ /** Sets the language from the extension. The file is renamed only if asked */
+ private void setLanguageByFileName(final String name, final boolean renameFile) {
final ScriptLanguage language = scriptService.getLanguageByExtension(FileUtils
.getExtension(name));
- setLanguage(language, false, language != null);
+ setLanguage(language, false, renameFile && language != null);
if (language == null) {
// Not executable: highlight only, and keep the file name as is
final String style = FileTypeUtil.get().guessContentType(new File(name));
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 51bad67a..98cdcac6 100644
--- a/src/main/java/org/scijava/ui/swing/script/GuiUtils.java
+++ b/src/main/java/org/scijava/ui/swing/script/GuiUtils.java
@@ -81,8 +81,37 @@ static void info(final Component parent, final String message, final String titl
static boolean confirm(final Component parent, final String message, final String title,
final String yesButtonLabel) {
- return JOptionPane.showConfirmDialog(parent, message, title, JOptionPane.YES_NO_OPTION) ==
- JOptionPane.YES_OPTION;
+ final Object[] options = { yesButtonLabel, "Cancel" };
+ return JOptionPane.showOptionDialog(parent, message, title, JOptionPane.DEFAULT_OPTION,
+ JOptionPane.QUESTION_MESSAGE, null, options, options[0]) == 0;
+ }
+
+ /**
+ * Save dialog proposing a file name (JFileChooser selects it, unlike a plain
+ * directory-based prompt). Returns null if cancelled
+ */
+ static File chooseSaveFile(final Component parent, final File suggestion, final String title) {
+ final JFileChooser chooser = new JFileChooser(suggestion.getParentFile());
+ chooser.setDialogTitle(title);
+ chooser.setSelectedFile(suggestion);
+ return (chooser.showSaveDialog(parent) == JFileChooser.APPROVE_OPTION)
+ ? chooser.getSelectedFile() : null;
+ }
+
+ /** Outcome of the prompt of {@link #confirmUnsaved} */
+ enum UnsavedChoice { SAVE, DISCARD, CANCEL }
+
+ /** Asks what to do with unsaved changes. Closing the dialog counts as cancel */
+ static UnsavedChoice confirmUnsaved(final Component parent, final String message,
+ final String title) {
+ final Object[] options = { "Save", "Discard", "Cancel" };
+ final int choice = JOptionPane.showOptionDialog(parent, message, title,
+ JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
+ return switch (choice) {
+ case 0 -> UnsavedChoice.SAVE;
+ case 1 -> UnsavedChoice.DISCARD;
+ default -> UnsavedChoice.CANCEL;
+ };
}
/**
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 c7dc96ce..a58cf719 100644
--- a/src/main/java/org/scijava/ui/swing/script/TextEditor.java
+++ b/src/main/java/org/scijava/ui/swing/script/TextEditor.java
@@ -1765,9 +1765,14 @@ public void loadTemplate(final URL url, final ScriptLanguage language) {
createNewDocument();
try {
- // Load the template
- final InputStream in = url.openStream();
- getTextArea().read(new BufferedReader(new InputStreamReader(in)), null);
+ // Load the template. NB: setText() keeps the document (and its
+ // listeners), unlike read()
+ final String text;
+ try (final InputStream in = url.openStream()) {
+ text = new String(in.readAllBytes(), StandardCharsets.UTF_8);
+ }
+ getTextArea().setText(text);
+ getTextArea().setCaretPosition(0);
if (language != null) {
setLanguage(language);
@@ -1836,12 +1841,13 @@ public boolean handleUnsavedChanges(final boolean beforeCompiling) {
save();
return true;
}
- if (GuiUtils.confirm(this, "Do you want to save changes?", "Save Changes?", "Save")) {
- return save();
- } else {
+ return switch (GuiUtils.confirmUnsaved(this, "Do you want to save changes?",
+ "Save Changes?")) {
+ case SAVE -> save();
// Compiled languages should not progress if their source is unsaved
- return !beforeCompiling;
- }
+ case DISCARD -> !beforeCompiling;
+ case CANCEL -> false;
+ };
}
private boolean isJava(final ScriptLanguage language) {
@@ -2992,8 +2998,15 @@ public boolean saveAs() {
final File ijDir = appService.getApp().getBaseDirectory();
file = new File(ijDir, editorPane.getFileName());
}
- final File fileToSave = uiService.chooseFile(file, FileWidget.SAVE_STYLE);
+ File fileToSave = GuiUtils.chooseSaveFile(this, file, "Save As");
if (fileToSave == null) return false;
+ // Keep the language of the script if no extension was typed
+ final ScriptLanguage language = editorPane.getCurrentLanguage();
+ if (language != null && FileUtils.getExtension(fileToSave.getName()).isEmpty()
+ && !language.getExtensions().isEmpty()) {
+ fileToSave = new File(fileToSave.getParentFile(),
+ fileToSave.getName() + "." + language.getExtensions().get(0));
+ }
return saveAs(fileToSave.getAbsolutePath(), true);
}
@@ -3004,12 +3017,13 @@ public void saveAs(final String path) {
public boolean saveAs(final String path, final boolean askBeforeReplacing) {
final File file = new File(path);
if (file.exists() && askBeforeReplacing
- && confirm("Do you want to replace " + path + "?", "Replace " + path + "?", "Replace"))
+ && !confirm("Do you want to replace " + path + "?", "Replace " + path + "?", "Replace"))
return false;
if (!write(file))
return false;
setEditorPaneFileName(file);
openRecent.add(path);
+ setTitle();
return true;
}
@@ -3051,10 +3065,13 @@ public boolean makeJar(final boolean includeSources) {
if (name.indexOf('_') < 0) name += "_";
name += ".jar";
- final File selectedFile = uiService.chooseFile(file, FileWidget.SAVE_STYLE);
+ final File dir = (file != null && file.getParentFile() != null)
+ ? file.getParentFile() : appService.getApp().getBaseDirectory();
+ final File selectedFile = GuiUtils.chooseSaveFile(this, new File(dir, name),
+ "Export as JAR");
if (selectedFile == null) return false;
if (selectedFile.exists()
- && confirm("Do you want to replace " + selectedFile + "?", "Replace " + selectedFile + "?", "Replace"))
+ && !confirm("Do you want to replace " + selectedFile + "?", "Replace " + selectedFile + "?", "Replace"))
return false;
try {
makeJar(selectedFile, includeSources);
From a39ea79df8d059594fa38add6af35f7c360efb35 Mon Sep 17 00:00:00 2001
From: Tiago Ferreira
Date: Sun, 15 Nov 2026 22:57:07 -0500
Subject: [PATCH 29/41] Replace Thread.stop() reliance in Executer.obliterate()
hread.stop() throws UnsupportedOperationException since JDK 20, so
killing a script logged a stack trace per thread and only interrupted
(when anything at all). Now:
- Interrupt all threads of the executer (deduplicated), then try stop()
only on threads still alive, giving up on the first
UnsupportedOperationException
- After a 1s grace period, report threads that are still running
(script name included, wrapper thread labeled "runner") in the error
screen and in the status bar, with a new error icon
- Refresh the Kill menu and window title after obliterate(), since the
wrapper thread's finally block may never run if it survives
- showTemporaryStatus() accepts an optional icon, and always clears the
icon of a previous message
Co-Authored-By: Claude Sonnet 5.5
---
.../org/scijava/ui/swing/script/Icons.java | 8 +++
.../scijava/ui/swing/script/TextEditor.java | 63 +++++++++++++++++--
2 files changed, 66 insertions(+), 5 deletions(-)
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 a832c6eb..c4b38451 100644
--- a/src/main/java/org/scijava/ui/swing/script/Icons.java
+++ b/src/main/java/org/scijava/ui/swing/script/Icons.java
@@ -31,6 +31,7 @@
import com.formdev.flatlaf.FlatLaf;
import com.formdev.flatlaf.icons.FlatAbstractIcon;
+import com.formdev.flatlaf.icons.FlatOptionPaneErrorIcon;
import com.formdev.flatlaf.ui.FlatUIUtils;
import com.formdev.flatlaf.util.UIScale;
@@ -63,6 +64,13 @@ final class Icons {
private Icons() {
}
+ /** Small error icon for status messages */
+ static Icon error() {
+ final FlatAbstractIcon icon = new FlatOptionPaneErrorIcon();
+ icon.setScale(.35f);
+ return icon;
+ }
+
/** Folder icon for the Files side tab (follows the component foreground) */
static Icon folder() {
return new GlyphIcon(FOLDER, null, null, false, 0, 0, 640, 640, 18);
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 a58cf719..984d6fd2 100644
--- a/src/main/java/org/scijava/ui/swing/script/TextEditor.java
+++ b/src/main/java/org/scijava/ui/swing/script/TextEditor.java
@@ -86,6 +86,7 @@
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
+import java.util.LinkedHashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -2004,12 +2005,19 @@ private void setAutoCompletionEnabled(final boolean enabled) {
* given delay. Text set by other means in the meantime is left untouched
*/
void showTemporaryStatus(final String message, final int millis) {
+ showTemporaryStatus(message, millis, null);
+ }
+
+ /** As above, with an optional icon shown next to the message */
+ void showTemporaryStatus(final String message, final int millis, final Icon icon) {
if (statusRestoreTimer != null && statusRestoreTimer.isRunning())
statusRestoreTimer.stop(); // keep the text saved by the pending message
else
statusRestoreText = statusText.getText();
statusText.setText(message);
+ statusText.setIcon(icon); // null clears the icon of a previous message
statusRestoreTimer = new Timer(millis, e -> {
+ if (icon != null && statusText.getIcon() == icon) statusText.setIcon(null);
if (message.equals(statusText.getText()))
statusText.setText(statusRestoreText);
});
@@ -3458,8 +3466,11 @@ List getAllThreads() {
}
/**
- * Totally destroy/stop all threads in this and all recursive thread
- * subgroups. Will remove itself from the executingTasks list.
+ * Interrupts all threads in this and all recursive thread subgroups, and
+ * additionally stops them if the JVM still allows it (Thread.stop() throws
+ * an UnsupportedOperationException since JDK 20). Threads that ignore the
+ * interrupt are reported in the error screen. Will remove itself from the
+ * executingTasks list.
*/
@SuppressWarnings("deprecation")
void obliterate() {
@@ -3471,17 +3482,50 @@ void obliterate() {
catch (final Exception e) {
log.error(e);
}
- for (final Thread thread : getAllThreads()) {
+ final List threads = getDistinctThreads();
+ threads.forEach(Thread::interrupt);
+ Thread.yield(); // give them a chance
+ for (final Thread thread : threads) {
+ if (!thread.isAlive()) continue;
try {
- thread.interrupt();
- Thread.yield(); // give it a chance
thread.stop();
}
+ catch (final UnsupportedOperationException unsupported) {
+ break; // no point in trying the remaining threads
+ }
catch (final Throwable t) {
log.error(t);
}
}
executingTasks.remove(this);
+ // The wrapper thread may survive (no Thread.stop()): refresh the state it would have
+ SwingUtilities.invokeLater(() -> kill.setEnabled(executingTasks.size() > 0));
+ setTitle();
+ reportSurvivors();
+ }
+
+ private List getDistinctThreads() {
+ return new ArrayList<>(new LinkedHashSet<>(getAllThreads()));
+ }
+
+ /**
+ * Checks after a grace period (threads spawned in the meantime included)
+ * and flags threads that are still running in the console and status bar
+ */
+ private void reportSurvivors() {
+ final String script = scriptNameOf(this);
+ final Timer timer = new Timer(1000, e -> {
+ final List names = new ArrayList<>();
+ for (final Thread t : getDistinctThreads())
+ if (t.isAlive()) names.add(t.getName().equals(getName()) ? "runner" : t.getName());
+ if (names.isEmpty()) return;
+ 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());
+ });
+ timer.setRepeats(false);
+ timer.start();
}
@Override
@@ -3550,6 +3594,15 @@ public List getExecutingTasks() {
return executingTasks;
}
+ /** The name of the script run by the executer (its tab is looked up) */
+ private String scriptNameOf(final Executer executer) {
+ for (int i = 0; i < tabbed.getTabCount(); i++) {
+ final TextEditorTab tab = (TextEditorTab) tabbed.getComponentAt(i);
+ if (executer == tab.getExecuter()) return tab.editorPane.getFileName();
+ }
+ return "script";
+ }
+
public void kill(final Executer executer) {
for (int i = 0; i < tabbed.getTabCount(); i++) {
final TextEditorTab tab = (TextEditorTab) tabbed.getComponentAt(i);
From cb27e6f4670fe75c854a3532cc05c9b4fa7ecf9c Mon Sep 17 00:00:00 2001
From: Tiago Ferreira
Date: Sun, 15 Nov 2026 23:13:02 -0500
Subject: [PATCH 30/41] Fix several latent bugs in TextEditor
- newTab(): resolve the language by extension (a leading dot is
optional) instead of passing the extension to getLanguageByName(),
which never matched. An unknown extension is now ignored instead of
setting a null language. Also return null if open() fails
- newTab(): compare the last language pref with equals(), not !=
- Run selected code: return right after the "Selection required!"
error instead of continuing with a null text
- Command history cropping: use Files.move(REPLACE_EXISTING) instead of
File.renameTo(), which fails silently on some platforms, and use
StandardCharsets.UTF_8
- Javadoc URL for core classes: use Runtime.version().feature(). The
java.version parsing threw on versions without dots (e.g., "21")
Co-Authored-By: Claude Sonnet 5.5
---
.../scijava/ui/swing/script/TextEditor.java | 37 ++++++++-----------
1 file changed, 15 insertions(+), 22 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 984d6fd2..3e204eb7 100644
--- a/src/main/java/org/scijava/ui/swing/script/TextEditor.java
+++ b/src/main/java/org/scijava/ui/swing/script/TextEditor.java
@@ -74,7 +74,9 @@
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
+import java.nio.file.Path;
import java.nio.file.Paths;
+import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Arrays;
@@ -2895,19 +2897,16 @@ public static boolean isBinary(final File file) {
* @return the text editor tab
*/
public TextEditorTab newTab(final String content, final String languageExtension) {
- String lang = languageExtension;
final TextEditorTab tab = open(null);
- if (null != lang && lang.length() > 0) {
- lang = lang.trim().toLowerCase();
-
- if ('.' != lang.charAt(0)) {
- lang = "." + languageExtension;
- }
-
- tab.editorPane.setLanguage(scriptService.getLanguageByName(languageExtension));
+ if (tab == null) return null; // open() failed
+ if (languageExtension != null && !languageExtension.isBlank()) {
+ String ext = languageExtension.trim().toLowerCase();
+ if (ext.startsWith(".")) ext = ext.substring(1);
+ final ScriptLanguage language = scriptService.getLanguageByExtension(ext);
+ if (language != null) tab.editorPane.setLanguage(language);
} else {
final String lastLanguageName = prefService.get(getClass(), LAST_LANGUAGE);
- if (null != lastLanguageName && "none" != lastLanguageName)
+ if (null != lastLanguageName && !"none".equals(lastLanguageName))
setLanguage(scriptService.getLanguageByName(lastLanguageName));
}
@@ -3694,9 +3693,9 @@ private void execute(final boolean selectionOnly) throws IOException {
final String selected = tab.getEditorPane().getSelectedText();
if (selected == null) {
error("Selection required!");
- text = null;
+ return;
}
- else text = selected + "\n"; // Ensure code blocks are terminated
+ text = selected + "\n"; // Ensure code blocks are terminated
getEditorPane().getErrorHighlighter().setSelectedCodeExecution(true);
}
else {
@@ -3854,11 +3853,10 @@ private ArrayList loadPromptLog(final ScriptLanguage language) {
croppedLog.add("#");
}
try {
- Files.write(Paths.get(path + "-tmp"), croppedLog, Charset.forName("UTF-8"),
+ final Path tmp = Paths.get(path + "-tmp");
+ Files.write(tmp, croppedLog, StandardCharsets.UTF_8, StandardOpenOption.CREATE,
StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.DSYNC);
- if (!new File(path + "-tmp").renameTo(new File(path))) {
- log.error("Could not rename command log file " + path + "-tmp to " + path);
- }
+ Files.move(tmp, Paths.get(path), StandardCopyOption.REPLACE_EXISTING);
} catch (final Exception e) {
log.error("Failed to crop history of prompt commands file " + path, e);
}
@@ -4104,12 +4102,7 @@ public void openHelp(String className, final boolean withFrames) {
if (className.startsWith("java.") || className.startsWith("javax.")) {
// Core Java class -- use javadoc.scijava.org/Java<#> link.
- final String javaVersion = System.getProperty("java.version");
- final String majorVersion;
- if (javaVersion.startsWith("1.")) {
- majorVersion = javaVersion.substring(2, javaVersion.indexOf('.', 2));
- }
- else majorVersion = javaVersion.substring(0, javaVersion.indexOf('.'));
+ final int majorVersion = Runtime.version().feature();
url = "https://javadoc.scijava.org/Java" + majorVersion + "/" + path;
}
else {
From f06fb1053fa220c36f8c25d5af13d7c9eb6b2f89 Mon Sep 17 00:00:00 2001
From: Tiago Ferreira
Date: Sun, 15 Nov 2026 23:30:04 -0500
Subject: [PATCH 31/41] Reduce per-event work and fix listener and resource
leaks in the editor
- Debounce layout saving (300 ms) and window title updates (200 ms).
Resize and divider drags fired a pref write per event, and every
keystroke refreshed the title. The pending layout save is flushed on
window closing, while the tabs still exist
- Stop checking for outside file changes on every edit. It still runs
on window focus and on tab switch
- FileSystemTree: coalesce bursts of watcher events into one refresh
per folder
- NotesPanel: run the refresh poll only while the panel is displayable
(start in addNotify, stop in removeNotify) instead of forever
- TextEditorTab.destroy(): null-safe, and detach the listener that
mirrors the shared error console into the combined console. It now
runs for every closed tab, not just the current one at window close
- TextEditor.dispose(): stop the timers and remove the editor and its
context from the static instances and contexts lists
- EditorPane.syncLanguageWithFileName(): on tab switches, only change
the language if it differs from the one implied by the file name
- File filter: apply regular expressions with find() instead of adding
anchors, which broke alternations such as "py|txt"
Co-Authored-By: Claude Sonnet 5.5
---
.../scijava/ui/swing/script/EditorPane.java | 24 ++++++++---
.../ui/swing/script/FileSystemTree.java | 18 +++++++-
.../ui/swing/script/FileSystemTreePanel.java | 8 ++--
.../scijava/ui/swing/script/NotesPanel.java | 16 +++++++-
.../scijava/ui/swing/script/TextEditor.java | 41 +++++++++++++++----
.../ui/swing/script/TextEditorTab.java | 28 +++++++++----
6 files changed, 106 insertions(+), 29 deletions(-)
diff --git a/src/main/java/org/scijava/ui/swing/script/EditorPane.java b/src/main/java/org/scijava/ui/swing/script/EditorPane.java
index e99b36c9..a9c72b49 100644
--- a/src/main/java/org/scijava/ui/swing/script/EditorPane.java
+++ b/src/main/java/org/scijava/ui/swing/script/EditorPane.java
@@ -723,11 +723,25 @@ private void setLanguageByFileName(final String name, final boolean renameFile)
final ScriptLanguage language = scriptService.getLanguageByExtension(FileUtils
.getExtension(name));
setLanguage(language, false, renameFile && language != null);
- if (language == null) {
- // Not executable: highlight only, and keep the file name as is
- final String style = FileTypeUtil.get().guessContentType(new File(name));
- if (style != null && !SYNTAX_STYLE_NONE.equals(style)) setSyntaxEditingStyle(style);
- }
+ if (language == null) guessSyntaxStyle(name);
+ }
+
+ /** Not executable: highlight only, and keep the file name as is */
+ private void guessSyntaxStyle(final String name) {
+ final String style = FileTypeUtil.get().guessContentType(new File(name));
+ if (style != null && !SYNTAX_STYLE_NONE.equals(style)) setSyntaxEditingStyle(style);
+ }
+
+ /**
+ * Makes the language match the file name without renaming the file. A cheap
+ * no-op if it already does (e.g., on tab switches)
+ */
+ void syncLanguageWithFileName() {
+ final String name = getFileName();
+ final ScriptLanguage language = scriptService.getLanguageByExtension(FileUtils
+ .getExtension(name));
+ if (language != currentLanguage) setLanguageByFileName(name, false);
+ else if (language == null) guessSyntaxStyle(name);
}
/**
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 25bf098a..9097bbae 100644
--- a/src/main/java/org/scijava/ui/swing/script/FileSystemTree.java
+++ b/src/main/java/org/scijava/ui/swing/script/FileSystemTree.java
@@ -923,10 +923,20 @@ private class DirectoryWatcher extends Thread {
private final Map keys = new ConcurrentHashMap<>();
private final Map byNode = new ConcurrentHashMap<>();
private WatchService watcher;
+ // Bursts of events (copies, builds) trigger a single refresh per folder
+ private final Set pending = ConcurrentHashMap.newKeySet();
+ private final javax.swing.Timer flushTimer = new javax.swing.Timer(250, e -> {
+ for (final Iterator it = pending.iterator(); it.hasNext();) {
+ final Node n = it.next();
+ it.remove();
+ refresh(n);
+ }
+ });
DirectoryWatcher() {
super("FileSystemTree watcher");
setDaemon(true);
+ flushTimer.setRepeats(false);
try {
watcher = FileSystems.getDefault().newWatchService();
start();
@@ -963,7 +973,12 @@ public void run() {
while (!isInterrupted()) {
final WatchKey key = watcher.take();
final Node node = keys.get(key);
- if (node != null && !key.pollEvents().isEmpty()) SwingUtilities.invokeLater(() -> refresh(node));
+ if (node != null && !key.pollEvents().isEmpty()) {
+ pending.add(node);
+ SwingUtilities.invokeLater(() -> {
+ if (!flushTimer.isRunning()) flushTimer.start();
+ });
+ }
if (!key.reset()) {
final Node gone = keys.remove(key);
if (gone != null) byNode.remove(gone);
@@ -972,6 +987,7 @@ public void run() {
} catch (final InterruptedException | ClosedWatchServiceException ignored) {
// we are done
} finally {
+ SwingUtilities.invokeLater(flushTimer::stop);
try {
watcher.close();
} catch (final IOException ignored) {
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 03994fc7..a95d0aa7 100644
--- a/src/main/java/org/scijava/ui/swing/script/FileSystemTreePanel.java
+++ b/src/main/java/org/scijava/ui/swing/script/FileSystemTreePanel.java
@@ -336,11 +336,9 @@ private boolean applyFilter() {
private FileFilter filterFor(final String text) throws PatternSyntaxException {
if (text.isEmpty()) return f -> true;
if (isRegexEnabled()) {
- String expr = text;
- if (!expr.startsWith("^")) expr = "^.*" + expr;
- if (!expr.endsWith("$")) expr += ".*$";
- final Pattern pattern = Pattern.compile(expr, isCaseSensitive() ? 0 : Pattern.CASE_INSENSITIVE);
- return f -> pattern.matcher(f.getName()).matches();
+ // find() so that alternations (py|txt) are not split by added anchors
+ final Pattern pattern = Pattern.compile(text, isCaseSensitive() ? 0 : Pattern.CASE_INSENSITIVE);
+ return f -> pattern.matcher(f.getName()).find();
}
if (isCaseSensitive()) return f -> f.getName().contains(text);
final String lowerCase = text.toLowerCase();
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 6530a1ee..f12e7a66 100644
--- a/src/main/java/org/scijava/ui/swing/script/NotesPanel.java
+++ b/src/main/java/org/scijava/ui/swing/script/NotesPanel.java
@@ -93,6 +93,7 @@ protected void paintComponent(final java.awt.Graphics g) {
}
};
private final Timer saveTimer;
+ private final Timer poll;
private boolean loading;
NotesPanel(final Supplier extends JTextComponent> activeEditor,
@@ -206,10 +207,21 @@ public void changedUpdate(final DocumentEvent e) {
// Cheap polling, only while visible. RSyntaxTextArea provides no listener
refresh();
- final Timer poll = new Timer(REFRESH_DELAY_MS, e -> {
+ poll = new Timer(REFRESH_DELAY_MS, e -> {
if (isShowing()) refresh();
});
- poll.start();
+ }
+
+ @Override
+ public void addNotify() {
+ super.addNotify();
+ if (!poll.isRunning()) poll.start();
+ }
+
+ @Override
+ public void removeNotify() {
+ poll.stop();
+ super.removeNotify();
}
private JPopupMenu scratchMenu() {
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 3e204eb7..ad45dfce 100644
--- a/src/main/java/org/scijava/ui/swing/script/TextEditor.java
+++ b/src/main/java/org/scijava/ui/swing/script/TextEditor.java
@@ -325,6 +325,13 @@ public class TextEditor extends JFrame implements ActionListener,
private boolean incremental = false;
private DragSource dragSource;
private boolean layoutLoading = true;
+ // Debounced: dividers and resizing fire many events per gesture, edits one per key
+ private final Timer layoutSaveTimer = new Timer(300, e -> saveWindowSizeToPrefs());
+ private final Timer titleTimer = new Timer(200, e -> setTitle());
+ {
+ layoutSaveTimer.setRepeats(false);
+ titleTimer.setRepeats(false);
+ }
private OutlineTreePanel sourceTreePanel;
protected final CommandPalette cmdPalette;
@@ -812,7 +819,7 @@ public TextEditor(final Context context) {
// Tweaks for JSplitPane
body.addPropertyChangeListener(evt -> {
- if ("dividerLocation".equals(evt.getPropertyName())) saveWindowSizeToPrefs();
+ if ("dividerLocation".equals(evt.getPropertyName())) saveWindowSizeToPrefsLater();
});
// Tweaks for FileSystemTree
@@ -871,6 +878,10 @@ public void windowOpened(final WindowEvent e) {
@Override
public void windowClosing(final WindowEvent e) {
+ if (layoutSaveTimer.isRunning()) { // flush while the tabs still exist
+ layoutSaveTimer.stop();
+ saveWindowSizeToPrefs();
+ }
if (!confirmClose()) return;
UIManager.removePropertyChangeListener(lookAndFeelListener);
tree.destroy();
@@ -879,7 +890,6 @@ public void windowClosing(final WindowEvent e) {
dragSource.removeDragSourceListener(l);
}
dragSource = null;
- getTab().destroy();
cmdPalette.dispose();
dispose();
}
@@ -921,7 +931,7 @@ public void windowGainedFocus(final WindowEvent e) {
@Override
public void componentResized(final ComponentEvent e) {
- saveWindowSizeToPrefs();
+ saveWindowSizeToPrefsLater();
}
});
@@ -1445,6 +1455,10 @@ public void loadWindowSizePreferences() {
*
* @see #loadWindowSizePreferences()
*/
+ private void saveWindowSizeToPrefsLater() {
+ if (!layoutLoading) layoutSaveTimer.restart();
+ }
+
public void saveWindowSizeToPrefs() {
if (notesPanel != null) notesPanel.flush();
if (layoutLoading) return;
@@ -2704,7 +2718,7 @@ public void stateChanged(final ChangeEvent e) {
//whiteSpace.setSelected(editorPane.isWhitespaceVisible());
- editorPane.setLanguageByFileName(editorPane.getFileName());
+ editorPane.syncLanguageWithFileName();
updateLanguageMenu(editorPane.getCurrentLanguage());
setTitle();
@@ -3165,6 +3179,15 @@ static void deleteRecursively(final File directory) {
directory.delete();
}
+ @Override
+ public void dispose() {
+ layoutSaveTimer.stop();
+ titleTimer.stop();
+ instances.remove(this);
+ contexts.remove(context);
+ super.dispose();
+ }
+
void setLanguage(final ScriptLanguage language) {
setLanguage(language, false);
}
@@ -4035,6 +4058,7 @@ private void switchTabRelative(final int delta) {
private void removeTab(final int index) {
final int menuItemIndex = index + tabsMenuTabsStart;
try {
+ ((TextEditorTab) tabbed.getComponentAt(index)).destroy();
tabbed.remove(index);
tabsMenuItems.remove(tabsMenu.getItem(menuItemIndex));
tabsMenu.remove(menuItemIndex);
@@ -4584,21 +4608,20 @@ public boolean confirmClose() {
return true;
}
+ // Outside changes are checked on window focus and tab switch, not per key
@Override
public void insertUpdate(final DocumentEvent e) {
- setTitle();
- checkForOutsideChanges();
+ titleTimer.restart();
}
@Override
public void removeUpdate(final DocumentEvent e) {
- setTitle();
- checkForOutsideChanges();
+ titleTimer.restart();
}
@Override
public void changedUpdate(final DocumentEvent e) {
- setTitle();
+ titleTimer.restart();
}
public void setFontSize(final float size) {
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 f148ba45..e63ff25e 100644
--- a/src/main/java/org/scijava/ui/swing/script/TextEditorTab.java
+++ b/src/main/java/org/scijava/ui/swing/script/TextEditorTab.java
@@ -57,6 +57,7 @@
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultCaret;
+import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
import com.formdev.flatlaf.FlatClientProperties;
@@ -114,6 +115,8 @@ public String toString() {
private final TextEditor textEditor;
private DropTarget dropTarget;
+ private Document mirroredErrorDoc;
+ private DocumentListener errorMirror;
private DropTargetListener dropTargetListener;
public TextEditorTab(final TextEditor textEditor) {
@@ -179,7 +182,8 @@ public void dragEnter(final DropTargetDragEvent e) {
textEditor.applyConsolePopupMenu(screen);
textEditor.applyConsolePopupMenu(combinedScreen);
mirrorInto(combinedScreen, screen, false);
- mirrorInto(combinedScreen, textEditor.getErrorScreen(), true);
+ mirroredErrorDoc = textEditor.getErrorScreen().getDocument();
+ errorMirror = mirrorInto(combinedScreen, textEditor.getErrorScreen(), true);
final JPanel bottom = new JPanel(new BorderLayout());
final JToolBar bar = new GuiUtils.ToolBar();
@@ -453,9 +457,17 @@ void toggleLayout(final boolean below) {
// Package private
void destroy() {
- dropTarget.removeDropTargetListener(dropTargetListener);
- dropTarget = null;
- dropTargetListener = null;
+ if (dropTarget != null) {
+ dropTarget.removeDropTargetListener(dropTargetListener);
+ dropTarget = null;
+ dropTargetListener = null;
+ }
+ // The error console is shared by all tabs
+ if (mirroredErrorDoc != null) {
+ mirroredErrorDoc.removeDocumentListener(errorMirror);
+ mirroredErrorDoc = null;
+ errorMirror = null;
+ }
}
/** Invoke in the context of the event dispatch thread. */
@@ -553,10 +565,10 @@ void applyConsoleColors() {
* Copies everything appended to {@code source} into {@code target}, so that
* {@code target} shows several streams in the order they were written.
*/
- private void mirrorInto(final ConsoleArea target, final JTextArea source,
+ private DocumentListener mirrorInto(final ConsoleArea target, final JTextArea source,
final boolean error)
{
- source.getDocument().addDocumentListener(new DocumentListener() {
+ final DocumentListener listener = new DocumentListener() {
@Override
public void insertUpdate(final DocumentEvent e) {
@@ -577,7 +589,9 @@ public void removeUpdate(final DocumentEvent e) {}
@Override
public void changedUpdate(final DocumentEvent e) {}
- });
+ };
+ source.getDocument().addDocumentListener(listener);
+ return listener;
}
public JTextArea getScreen() {
From a6b0cb41caf6c554afc2db9424cbe200658f424d Mon Sep 17 00:00:00 2001
From: Tiago Ferreira
Date: Sun, 15 Nov 2026 23:33:37 -0500
Subject: [PATCH 32/41] Ensure all FileChoosers accept drag & drop
---
.../ui/swing/script/FileFunctions.java | 7 +--
.../ui/swing/script/FileSystemTreePanel.java | 27 +-------
.../org/scijava/ui/swing/script/GuiUtils.java | 61 +++++++++++++++++--
.../scijava/ui/swing/script/TextEditor.java | 21 +++----
4 files changed, 72 insertions(+), 44 deletions(-)
diff --git a/src/main/java/org/scijava/ui/swing/script/FileFunctions.java b/src/main/java/org/scijava/ui/swing/script/FileFunctions.java
index 5978d4a0..a012d1f4 100644
--- a/src/main/java/org/scijava/ui/swing/script/FileFunctions.java
+++ b/src/main/java/org/scijava/ui/swing/script/FileFunctions.java
@@ -53,7 +53,6 @@
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
@@ -225,10 +224,8 @@ public String findSourcePath(final String className, final File workspace) {
if (paths.size() == 1) return new File(workspace, paths.get(0))
.getAbsolutePath();
//final String[] names = paths.toArray(new String[paths.size()]);
- final JFileChooser chooser = new JFileChooser(workspace);
- chooser.setDialogTitle("Choose path");
- if (chooser.showOpenDialog(parent) != JFileChooser.APPROVE_OPTION) return null;
- return chooser.getSelectedFile().getPath();
+ final File chosen = GuiUtils.chooseOpenFile(parent, workspace, "Choose path");
+ return (chosen == null) ? null : chosen.getPath();
}
protected void findJavaPaths(final File directory, final String prefix) {
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 a95d0aa7..a4cc236d 100644
--- a/src/main/java/org/scijava/ui/swing/script/FileSystemTreePanel.java
+++ b/src/main/java/org/scijava/ui/swing/script/FileSystemTreePanel.java
@@ -357,30 +357,9 @@ private JMenuItem addDirectoryMenuItem() {
add_directory.addActionListener(e -> {
final String folders = tree.getTopLevelFoldersString();
final String lastFolder = folders.substring(folders.lastIndexOf(File.pathSeparatorChar) + 1);
- final JFileChooser c = new JFileChooser();
- c.setDialogTitle("Choose Top-Level Folder");
- c.setCurrentDirectory(new File(lastFolder));
- c.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
- c.setFileHidingEnabled(true); // hide hidden files
- c.setAcceptAllFileFilterUsed(false); // disable "All files" as it has no meaning here
- c.setApproveButtonText("Choose Folder");
- c.setMultiSelectionEnabled(false);
- c.setDragEnabled(true);
- final FileDrop fileDrop = new FileDrop(c, files -> {
- if (files == null || files.length == 0 || files[0] == null) return;
- try {
- final File ref = files[0].getAbsoluteFile();
- c.setCurrentDirectory((ref.isDirectory()) ? ref : ref.getParentFile());
- } catch (final Throwable ignored) {
- GuiUtils.warn(this, "Could not retrieve location of dropped file(s).");
- }
- });
- if (JFileChooser.APPROVE_OPTION == c.showOpenDialog(this)) {
- final File f = c.getSelectedFile();
- if (f.isDirectory())
- tree.addRootDirectory(f.getAbsolutePath(), false);
- }
- fileDrop.uninstall();
+ final File f = GuiUtils.chooseDirectory(this, new File(lastFolder), "Choose Top-Level Folder",
+ "Choose Folder");
+ if (f != null && f.isDirectory()) tree.addRootDirectory(f.getAbsolutePath(), false);
});
return add_directory;
}
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 98cdcac6..1fd8e1ad 100644
--- a/src/main/java/org/scijava/ui/swing/script/GuiUtils.java
+++ b/src/main/java/org/scijava/ui/swing/script/GuiUtils.java
@@ -91,11 +91,64 @@ static boolean confirm(final Component parent, final String message, final Strin
* directory-based prompt). Returns null if cancelled
*/
static File chooseSaveFile(final Component parent, final File suggestion, final String title) {
- final JFileChooser chooser = new JFileChooser(suggestion.getParentFile());
+ return showChooser(parent, newChooser(suggestion, title, true), true);
+ }
+
+ /**
+ * Open dialog. The start location may be a directory or a file. Returns null
+ * if cancelled
+ */
+ static File chooseOpenFile(final Component parent, final File start, final String title) {
+ return showChooser(parent, newChooser(start, title, false), false);
+ }
+
+ /** Folder dialog. Returns null if cancelled */
+ static File chooseDirectory(final Component parent, final File start, final String title,
+ final String approveText) {
+ final JFileChooser chooser = newChooser(start, title, false);
+ chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
+ chooser.setFileHidingEnabled(true);
+ chooser.setAcceptAllFileFilterUsed(false); // has no meaning for folders
+ chooser.setMultiSelectionEnabled(false);
+ if (approveText != null) chooser.setApproveButtonText(approveText);
+ return showChooser(parent, chooser, false);
+ }
+
+ private static JFileChooser newChooser(final File start, final String title, final boolean save) {
+ final JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle(title);
- chooser.setSelectedFile(suggestion);
- return (chooser.showSaveDialog(parent) == JFileChooser.APPROVE_OPTION)
- ? chooser.getSelectedFile() : null;
+ chooser.setDragEnabled(true);
+ if (start != null) {
+ if (start.isDirectory()) {
+ chooser.setCurrentDirectory(start);
+ } else {
+ if (start.getParentFile() != null) chooser.setCurrentDirectory(start.getParentFile());
+ if (save || start.exists()) chooser.setSelectedFile(start);
+ }
+ }
+ return chooser;
+ }
+
+ /** Every file dialog goes through here so that all of them accept dropped files */
+ private static File showChooser(final Component parent, final JFileChooser chooser,
+ final boolean save) {
+ final FileDrop drop = new FileDrop(chooser, files -> {
+ if (files == null || files.length == 0 || files[0] == null) return;
+ final File ref = files[0].getAbsoluteFile();
+ if (ref.isDirectory()) {
+ chooser.setCurrentDirectory(ref);
+ } else if (ref.getParentFile() != null) {
+ chooser.setCurrentDirectory(ref.getParentFile());
+ if (!save && chooser.getFileSelectionMode() != JFileChooser.DIRECTORIES_ONLY)
+ chooser.setSelectedFile(ref);
+ }
+ });
+ try {
+ final int result = save ? chooser.showSaveDialog(parent) : chooser.showOpenDialog(parent);
+ return (result == JFileChooser.APPROVE_OPTION) ? chooser.getSelectedFile() : null;
+ } finally {
+ drop.uninstall();
+ }
}
/** Outcome of the prompt of {@link #confirmUnsaved} */
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 ad45dfce..c40b59fa 100644
--- a/src/main/java/org/scijava/ui/swing/script/TextEditor.java
+++ b/src/main/java/org/scijava/ui/swing/script/TextEditor.java
@@ -170,7 +170,6 @@
import org.scijava.util.MiscUtils;
import org.scijava.util.POM;
import org.scijava.util.Types;
-import org.scijava.widget.FileWidget;
import com.formdev.flatlaf.FlatClientProperties;
@@ -1216,8 +1215,9 @@ private File getMacroFile(final boolean openOtherwiseSave) {
if (getEditorPane().getFile() != null) {
dir = getEditorPane().getFile().getParentFile();
}
- return uiService.chooseFile(new File(dir, filename),
- (openOtherwiseSave) ? FileWidget.OPEN_STYLE : FileWidget.SAVE_STYLE);
+ final File suggestion = new File(dir, filename);
+ return (openOtherwiseSave) ? GuiUtils.chooseOpenFile(this, suggestion, "Load Macro")
+ : GuiUtils.chooseSaveFile(this, suggestion, "Save Macro");
}
return null;
}
@@ -1446,6 +1446,10 @@ public void loadWindowSizePreferences() {
layoutLoading = false;
}
+ private void saveWindowSizeToPrefsLater() {
+ if (!layoutLoading) layoutSaveTimer.restart();
+ }
+
/**
* Saves the Script Editor layout to persisted storage.
*
@@ -1455,10 +1459,6 @@ public void loadWindowSizePreferences() {
*
* @see #loadWindowSizePreferences()
*/
- private void saveWindowSizeToPrefsLater() {
- if (!layoutLoading) layoutSaveTimer.restart();
- }
-
public void saveWindowSizeToPrefs() {
if (notesPanel != null) notesPanel.flush();
if (layoutLoading) return;
@@ -4255,9 +4255,8 @@ public void extractSourceJar() {
public void extractSourceJar(final File file) {
try {
final FileFunctions functions = new FileFunctions(this);
- final File workspace =
- uiService.chooseFile(new File(System.getProperty("user.home")),
- FileWidget.DIRECTORY_STYLE);
+ final File workspace = GuiUtils.chooseDirectory(this,
+ new File(System.getProperty("user.home")), "Choose Workspace Folder", "Choose");
if (workspace == null) return;
final List paths =
functions.extractSourceJar(file.getAbsolutePath(), workspace);
@@ -4276,7 +4275,7 @@ public void extractSourceJar(final File file) {
/* extensionMustMatch == false means extension must not match */
private File openWithDialog(final File defaultDir) {
- return uiService.chooseFile(defaultDir, FileWidget.OPEN_STYLE);
+ return GuiUtils.chooseOpenFile(this, defaultDir, "Open");
}
/**
From d62bbf2f3da86c7be84b6d642d26334a5cef9ef1 Mon Sep 17 00:00:00 2001
From: Tiago Ferreira
Date: Sun, 15 Nov 2026 23:54:25 -0500
Subject: [PATCH 33/41] code cleanup
---
.../ui/swing/script/BookmarksPanel.java | 1 -
.../org/scijava/ui/swing/script/FileDrop.java | 1 -
.../scijava/ui/swing/script/NotesPanel.java | 3 -
.../scijava/ui/swing/script/TextEditor.java | 200 +++++++++++-------
.../ui/swing/script/TextEditorTab.java | 31 ++-
5 files changed, 130 insertions(+), 106 deletions(-)
diff --git a/src/main/java/org/scijava/ui/swing/script/BookmarksPanel.java b/src/main/java/org/scijava/ui/swing/script/BookmarksPanel.java
index 90440575..dc6c1a34 100644
--- a/src/main/java/org/scijava/ui/swing/script/BookmarksPanel.java
+++ b/src/main/java/org/scijava/ui/swing/script/BookmarksPanel.java
@@ -44,7 +44,6 @@
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
-import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
diff --git a/src/main/java/org/scijava/ui/swing/script/FileDrop.java b/src/main/java/org/scijava/ui/swing/script/FileDrop.java
index 0544410e..02f2e584 100644
--- a/src/main/java/org/scijava/ui/swing/script/FileDrop.java
+++ b/src/main/java/org/scijava/ui/swing/script/FileDrop.java
@@ -322,7 +322,6 @@ private static File[] parseUriList(final List lines) {
return files.toArray(new File[0]);
}
- @SuppressWarnings("serial")
private static final class Highlight extends JComponent {
private static final int THICKNESS = 2;
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 f12e7a66..d0ae9512 100644
--- a/src/main/java/org/scijava/ui/swing/script/NotesPanel.java
+++ b/src/main/java/org/scijava/ui/swing/script/NotesPanel.java
@@ -30,7 +30,6 @@
package org.scijava.ui.swing.script;
import java.awt.BorderLayout;
-import java.awt.Color;
import java.awt.Component;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
@@ -42,9 +41,7 @@
import java.util.List;
import java.util.function.Supplier;
import javax.swing.*;
-import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
-import javax.swing.border.MatteBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.JTextComponent;
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 c40b59fa..c2b94023 100644
--- a/src/main/java/org/scijava/ui/swing/script/TextEditor.java
+++ b/src/main/java/org/scijava/ui/swing/script/TextEditor.java
@@ -120,7 +120,6 @@
import javax.swing.text.Position;
import javax.swing.tree.TreePath;
-import com.formdev.flatlaf.icons.FlatSearchIcon;
import org.fife.ui.rsyntaxtextarea.AbstractTokenMakerFactory;
import org.fife.ui.rsyntaxtextarea.RSyntaxDocument;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
@@ -218,31 +217,64 @@ public class TextEditor extends JFrame implements ActionListener,
private static AbstractTokenMakerFactory tokenMakerFactory = null;
- private JTabbedPane tabbed;
- private JTabbedPane sideTabs;
- private NotesPanel notesPanel;
- private BookmarksPanel bookmarksPanel;
- private JSplitPane markersSplit;
- private TasksPanel tasksPanel;
- private JMenuItem newFile, open, save, saveas, compileAndRun, compile,
- close, undo, redo, cut, copy, paste, find, selectAll, kill,
- gotoLine, makeJar, makeJarWithSource, removeUnusedImports, sortImports,
- removeTrailingWhitespace, findNext, findPrevious, openHelp, addImport,
- nextError, previousError, openHelpWithoutFrames, nextTab,
- previousTab, runSelection, extractSourceJar, openSourceForClass,
- //openSourceForMenuItem, // this never had an actionListener!??
- openMacroFunctions, decreaseFontSize, increaseFontSize, chooseFontSize,
- chooseTabSize, gitGrep, convertToSpaces,
- convertToTabs, zapGremlins,openClassOrPackageHelp;
- private RecentFilesMenuItem openRecent;
- private JMenu editMenu, gitMenu, tabsMenu, fontSizeMenu, tabSizeMenu, codeMenu,
+ private final JTabbedPane tabbed;
+ private final JTabbedPane sideTabs;
+ private final NotesPanel notesPanel;
+ private final BookmarksPanel bookmarksPanel;
+ private final JSplitPane markersSplit;
+ private final TasksPanel tasksPanel;
+ private final JMenuItem newFile;
+ private final JMenuItem open;
+ private final JMenuItem save;
+ private final JMenuItem saveas;
+ private final JMenuItem compileAndRun;
+ private final JMenuItem compile;
+ private final JMenuItem close;
+ private JMenuItem undo;
+ private JMenuItem redo;
+ private JMenuItem cut;
+ private JMenuItem copy;
+ private JMenuItem paste;
+ private JMenuItem find;
+ private JMenuItem selectAll;
+ private final JMenuItem kill;
+ private JMenuItem gotoLine;
+ private final JMenuItem makeJar;
+ private final JMenuItem makeJarWithSource;
+ private final JMenuItem removeUnusedImports;
+ private final JMenuItem sortImports;
+ private final JMenuItem removeTrailingWhitespace;
+ private JMenuItem findNext;
+ private JMenuItem findPrevious;
+ private JMenuItem openHelp;
+ private final JMenuItem addImport;
+ private final JMenuItem nextError;
+ private final JMenuItem previousError;
+ private JMenuItem openHelpWithoutFrames;
+ private final JMenuItem nextTab;
+ private final JMenuItem previousTab;
+ private final JMenuItem runSelection;
+ private final JMenuItem extractSourceJar;
+ private final JMenuItem openSourceForClass;
+ private JMenuItem//openSourceForMenuItem, // this never had an actionListener!??
+ openMacroFunctions;
+ private final JMenuItem decreaseFontSize;
+ private final JMenuItem increaseFontSize;
+ private final JMenuItem chooseFontSize;
+ private final JMenuItem chooseTabSize;
+ private final JMenuItem gitGrep;
+ private final JMenuItem convertToSpaces;
+ private final JMenuItem convertToTabs;
+ private final JMenuItem zapGremlins;
+ private JMenuItem openClassOrPackageHelp;
+ private final RecentFilesMenuItem openRecent;
+ private final JMenu editMenu, gitMenu, tabsMenu, fontSizeMenu, tabSizeMenu, codeMenu,
runMenu;
- private int codeMenuCommentsIndex;
- private int tabsMenuTabsStart;
- private Set tabsMenuItems;
- private FindAndReplaceDialog findDialog;
+ private final int codeMenuCommentsIndex;
+ private final int tabsMenuTabsStart;
+ private final Set tabsMenuItems;
+ private final FindAndReplaceDialog findDialog;
private JButton statusTab;
- private FlatSearchIcon statusFastIcon;
private JButton statusWrap;
private JCheckBoxMenuItem wrapEditorItem;
private boolean consoleWrap, replWrap;
@@ -252,13 +284,22 @@ public class TextEditor extends JFrame implements ActionListener,
private JButton statusPos, statusLang;
private JToggleButton statusSide, statusBelow, statusRight, statusRepl, statusVimToggle;
private int sideLastLocation = -1;
- private JMenu languageMenu;
+ private final JMenu languageMenu;
private JLabel statusText;
private JLabel statusVim;
- private FileSystemTreePanel filesPanel;
- private JCheckBoxMenuItem autoSave, wrapLines, tabsEmulated, autoImport,
- autocompletion, fallbackAutocompletion, keylessAutocompletion,
- markOccurences, paintTabs, whiteSpace, marginLine, lockPane, vimMode;
+ private final FileSystemTreePanel filesPanel;
+ private final JCheckBoxMenuItem autoSave;
+ private JCheckBoxMenuItem wrapLines;
+ private final JCheckBoxMenuItem tabsEmulated;
+ private JCheckBoxMenuItem autocompletion;
+ private JCheckBoxMenuItem fallbackAutocompletion;
+ private JCheckBoxMenuItem keylessAutocompletion;
+ private JCheckBoxMenuItem markOccurences;
+ private JCheckBoxMenuItem paintTabs;
+ private JCheckBoxMenuItem whiteSpace;
+ private JCheckBoxMenuItem marginLine;
+ private final JCheckBoxMenuItem lockPane;
+ private JCheckBoxMenuItem vimMode;
private ButtonGroup themeRadioGroup;
private JTextArea errorScreen = new ConsoleArea(ConsoleArea.Content.ERRORS);
@@ -282,7 +323,7 @@ public class TextEditor extends JFrame implements ActionListener,
}
});
};
- private int[] panePositions;
+ private final int[] panePositions;
@Parameter
@@ -316,7 +357,7 @@ public class TextEditor extends JFrame implements ActionListener,
@Parameter(required = false)
private OptionsService optionsService;
- private Map languageMenuItems;
+ private final Map languageMenuItems;
private JRadioButtonMenuItem noneLanguageItem;
private EditableScriptInfo scriptInfo;
@@ -331,7 +372,7 @@ public class TextEditor extends JFrame implements ActionListener,
layoutSaveTimer.setRepeats(false);
titleTimer.setRepeats(false);
}
- private OutlineTreePanel sourceTreePanel;
+ private final OutlineTreePanel sourceTreePanel;
protected final CommandPalette cmdPalette;
public static final ArrayList instances = new ArrayList<>();
@@ -506,7 +547,7 @@ public TextEditor(final Context context) {
// get list of languages, and sort them by name
final ArrayList list =
new ArrayList<>(scriptService.getLanguages());
- Collections.sort(list, (l1, l2) -> {
+ list.sort((l1, l2) -> {
final String name1 = languageDisplayName(l1);
final String name2 = languageDisplayName(l2);
return MiscUtils.compare(name1, name2);
@@ -594,8 +635,7 @@ public TextEditor(final Context context) {
addImport = addToMenu(codeMenu, "Add Import...", 0, 0);
addImport.setMnemonic(KeyEvent.VK_I);
respectAutoImports = prefService.getBoolean(getClass(), AUTO_IMPORT_PREFS, false);
- autoImport =
- new JCheckBoxMenuItem("Auto-import (Deprecated)", respectAutoImports);
+ final JCheckBoxMenuItem autoImport = new JCheckBoxMenuItem("Auto-import (Deprecated)", respectAutoImports);
autoImport.setToolTipText("Automatically imports common classes before running code");
autoImport.addItemListener(e -> {
respectAutoImports = e.getStateChange() == ItemEvent.SELECTED;
@@ -709,8 +749,7 @@ public TextEditor(final Context context) {
final boolean[] fontSizeShortcutUsed = new boolean[10];
final ButtonGroup buttonGroup = new ButtonGroup();
for (final int size : new int[] { 8, 10, 12, 16, 20, 28, 42 }) {
- final JRadioButtonMenuItem item =
- new JRadioButtonMenuItem("" + size + " pt");
+ final JRadioButtonMenuItem item = new JRadioButtonMenuItem(size + " pt");
item.addActionListener(event -> setFontSize(size));
for (final char c : ("" + size).toCharArray()) {
final int digit = c - '0';
@@ -803,7 +842,7 @@ public TextEditor(final Context context) {
}
if (filteredFiles.size() < 10
|| confirm("Confirm loading of " + filteredFiles.size() + " items?", "Confirm?", "Load")) {
- filteredFiles.forEach(f -> open(f));
+ filteredFiles.forEach(this::open);
}
});
open(null); // make sure the editor pane is added
@@ -1641,16 +1680,6 @@ private JMenu getMenu(final JMenu root, final String menuItemPath,
return getMenu(subMenu, rest, createIfNecessary);
}
- /**
- * Initializes the Templates menu.
- *
- * Other components can add templates simply by providing scripts in their
- * resources, identified by a path of the form
- * {@code /script_templates/