* 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) *
- * public class MyClass implements FileDrop.Listener
- * ...
- * public void filesDropped( java.io.File[] files )
- * {
- * ...
- * } // end filesDropped
- * ...
- *
- *
- * @since 1.1
- */
- public static interface Listener {
+ 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);
+ }
- /**
- * 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 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());
+ }
+ highlight = null;
+ }
- } // end inner-interface Listener
+ 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);
+ }
- /* ******** I N N E R C L A S S ******** */
+ private void notifyListener(final File[] files) {
+ try {
+ listener.filesDropped(files);
+ } catch (final RuntimeException ex) {
+ LOGGER.log(Level.WARNING, "Listener failed", ex);
+ }
+ }
- /**
- * 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 static boolean isUriList(final DataFlavor flavor) { + return flavor.isRepresentationClassReader() && flavor.isMimeTypeEqual( + URI_LIST_MIME); + } - private final java.io.File[] files; + private static boolean isDragOk(final DataFlavor[] flavors) { + for (final DataFlavor f : flavors) { + if (DataFlavor.javaFileListFlavor.equals(f) || isUriList(f)) return true; + } + return false; + } - /** - * 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 DataFlavor findUriListFlavor(final Transferable tr) { + for (final DataFlavor f : tr.getTransferDataFlavors()) { + if (isUriList(f)) return f; + } + return null; + } - /** - * 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 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- * ... - * 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"; + private static final class Highlight extends JComponent { - /** - * 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); + private static final int THICKNESS = 2; + private final Color color; - private Fetcher fetcher; - private Object data; + Highlight(final Color color) { + this.color = color; + setOpaque(false); + setFocusable(false); + } - private java.awt.datatransfer.DataFlavor customFlavor; + // Let mouse events (and drop target lookups) go through + @Override + public boolean contains(final int x, final int y) { + return false; + } - /** - * 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 - * fromdata.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
+ @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 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
+ private static final class Installed {
- /**
- * 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
+ final Component component;
+ final DropTarget previous;
+ final DropTarget ours;
- /**
- * 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..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) {
@@ -372,7 +369,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 +401,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..9097bbae 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,970 @@
*/
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 SetOverview
" // - + "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 | " // - + "
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) " // + + "
" + 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); + } + 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 "\u21b5"; + case KeyEvent.VK_BACK_SPACE: return "\u232b"; + case KeyEvent.VK_TAB: return "\u21b9"; + 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 "\u21de"; + case KeyEvent.VK_PAGE_DOWN: return "\u21df"; + case KeyEvent.VK_END: return "END"; + case KeyEvent.VK_HOME: return "Home"; + case KeyEvent.VK_LEFT: return "\u2190"; + case KeyEvent.VK_UP: return "\u2191"; + case KeyEvent.VK_RIGHT: return "\u2192"; + case KeyEvent.VK_DOWN: return "\u2193"; + case KeyEvent.VK_MULTIPLY: return "[Num \u00d7]"; + case KeyEvent.VK_ADD: return "[Num +]"; + case KeyEvent.VK_SUBTRACT: return "[Num \u2212]"; + case KeyEvent.VK_DIVIDE: return "[Num /]"; + case KeyEvent.VK_DELETE: return "\u2326"; + 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); + } + } + + /** + * 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 { + 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) { + // do nothing + } + return new Color(0x3E73B9); + } + + 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(Icons.ellipsisVertical()); + b.setFocusable(false); + b.putClientProperty(FlatClientProperties.BUTTON_TYPE, FlatClientProperties.BUTTON_TYPE_TOOLBAR_BUTTON); + if (action != null) b.addActionListener(e -> action.run()); + b.setForeground(secondaryColor()); // the icon follows the foreground. Set last: style updates reset UI foregrounds + return b; + } + + + /** Small round "?" button, in the style of the editor's other help buttons */ + static JButton helpButton(final Runnable action) { + return helpButton(action, .75f, true); + } + + private static JButton helpButton(final Runnable action, final float scale, final boolean borderless) { + 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), 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 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()); + } + + /** + * 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
+ * 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 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; + 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" + escape(tip) + ""); + return this; + } + } +} 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..bced2b4c 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,12 @@ class OutlineTreePanel extends JScrollPane { super(); fontSize = getFont().getSize(); setViewportView(new UnsupportedLangTree()); - placeholdColor = TextEditor.GuiUtils.getDisabledComponentColor(); + } + + @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) { @@ -115,10 +109,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); @@ -131,8 +125,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(); @@ -146,11 +145,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 +159,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"); } } 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/ScalableErrorStrip.java b/src/main/java/org/scijava/ui/swing/script/ScalableErrorStrip.java new file mode 100644 index 00000000..af6fb355 --- /dev/null +++ b/src/main/java/org/scijava/ui/swing/script/ScalableErrorStrip.java @@ -0,0 +1,90 @@ +/* + * #%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 org.fife.ui.rsyntaxtextarea.parser.TaskTagParser; + +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 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/ScriptEditor.java b/src/main/java/org/scijava/ui/swing/script/ScriptEditor.java index 6c07a5d1..7d5a324e 100644 --- a/src/main/java/org/scijava/ui/swing/script/ScriptEditor.java +++ b/src/main/java/org/scijava/ui/swing/script/ScriptEditor.java @@ -29,6 +29,8 @@ package org.scijava.ui.swing.script; +import java.awt.EventQueue; + import org.scijava.Context; import org.scijava.command.Command; import org.scijava.plugin.Menu; @@ -50,7 +52,9 @@ public class ScriptEditor implements Command { @Override public void run() { - new TextEditor(context).setVisible(true); + // Note: Swing components must be built and shown on the EDT; otherwise + // layout races with the EDT and can leave the window collapsed. + EventQueue.invokeLater(() -> new TextEditor(context).setVisible(true)); } } 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..e9070e0f --- /dev/null +++ b/src/main/java/org/scijava/ui/swing/script/TasksPanel.java @@ -0,0 +1,223 @@ +/* + * #%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.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 */ + static class Task { + + private final TextEditorTab tab; + private final int line; + private final int offset; + private final String text; + + Task(final TextEditorTab tab, final int line, final int offset, final String text) { + this.tab = tab; + this.line = line; + this.offset = offset; + this.text = text; + } + + TextEditorTab tab() { + return tab; + } + + int line() { + return line; + } + + int offset() { + return offset; + } + + String text() { + return 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
- They are listed in the Tasks section of the Markers tab, for all open\n" // + + "tabs. Double-click (or press Enter on) an entry to jump to it \n" // + + "
- They are marked on the rightmost side of the editor, each keyword with its own color.\n" // + + "Mouse over a mark for a summary of the task, and click on it to go to the line \n" // + + "
- To remove a task, delete the keyword from the comment \n" // + + "
- Click next to a line number to add or remove a bookmark \n" // + + "
- They are listed in the Bookmarks section of the Markers tab, for all\n" // + + "open tabs. Double-click (or press Enter on) an entry to jump to it \n" // + + "
- Press Delete to remove the selected bookmark. Right-click an entry for more options,\n" // + + "e.g., to clear all bookmarks \n" // + + "
- > source, final Consumer
- \n" //
+ + "
- \n" //
+ + "
" + "a language for which auto-completions are not available"); fallbackAutocompletion.addItemListener(e -> setFallbackAutoCompletion(fallbackAutocompletion.getState())); - vimMode = new JCheckBoxMenuItem("Vim Mode", false); + // Vim mode is remembered across sessions. NB: panes read the same preference when loaded + vimMode = new JCheckBoxMenuItem("Vim Mode", prefService.getBoolean(EditorPane.class, EditorPane.VIM_PREFS, false)); vimMode.setToolTipText("Edit with vim-style modal key bindings.
" + "Press Esc for normal mode; :w saves, :q closes the tab"); - vimMode.addItemListener(e -> setVimMode(vimMode.getState())); + vimMode.addItemListener(e -> { + if (!syncingVim) setVimMode(vimMode.getState()); + }); themeRadioGroup = new ButtonGroup(); // Help menu. These are 'dynamic' items @@ -1185,12 +1425,19 @@ private void initializeDynamicMenuComponents() { * ask the user whether to reload. */ public void checkForOutsideChanges() { + if (checkingOutsideChanges) return; // the dialog itself moves the window focus around final EditorPane editorPane = getEditorPane(); if (editorPane.wasChangedOutside()) { - reload(editorPane.getFile().getName() + - "\nwas changed outside of the editor."); + checkingOutsideChanges = true; + try { + final boolean reloaded = reload(editorPane.getFile().getName() + + "\nwas changed outside of the editor."); + // Not reloaded (declined, dialog closed or error): do not ask again for this version of the file + if (!reloaded) editorPane.acknowledgeOutsideChange(); + } finally { + checkingOutsideChanges = false; + } } - } /** @@ -1245,6 +1492,10 @@ public void loadWindowSizePreferences() { layoutLoading = false; } + private void saveWindowSizeToPrefsLater() { + if (!layoutLoading) layoutSaveTimer.restart(); + } + /** * Saves the Script Editor layout to persisted storage. *
@@ -1255,6 +1506,7 @@ public void loadWindowSizePreferences() { * @see #loadWindowSizePreferences() */ public void saveWindowSizeToPrefs() { + if (notesPanel != null) notesPanel.flush(); if (layoutLoading) return; final Dimension dim = getSize(); @@ -1333,6 +1585,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 { @@ -1352,7 +1610,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; } @@ -1428,16 +1687,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/