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/pom.xml b/pom.xml index 06ff8814..10ac41f6 100644 --- a/pom.xml +++ b/pom.xml @@ -140,6 +140,7 @@ + 11 org.scijava.ui.swing.script.Main org.scijava.ui.swing.script bsd_2 @@ -147,6 +148,10 @@ sign,deploy-to-scijava + + + 3.8 + 4.0.1 @@ -163,11 +168,16 @@ org.scijava scripting-java + + org.scijava + scijava-ui-swing + com.fifesoft rsyntaxtextarea + ${rsyntaxtextarea.version} com.fifesoft @@ -193,11 +203,6 @@ parsington test - - org.scijava - scijava-ui-swing - test - org.scijava scripting-groovy @@ -206,6 +211,7 @@ com.formdev flatlaf + 3.8 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..dc6c1a34 --- /dev/null +++ b/src/main/java/org/scijava/ui/swing/script/BookmarksPanel.java @@ -0,0 +1,240 @@ +/* + * #%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.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 = 1500; + 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()) GuiUtils.paintEmptyHint(g, 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); + 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(); + } + + /** 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; + } + } +} 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..0d7f3cac 100644 --- a/src/main/java/org/scijava/ui/swing/script/CommandPalette.java +++ b/src/main/java/org/scijava/ui/swing/script/CommandPalette.java @@ -29,15 +29,22 @@ package org.scijava.ui.swing.script; +import java.awt.AlphaComposite; 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.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; @@ -48,27 +55,36 @@ import java.util.List; import java.util.Map; import java.util.TreeMap; +import java.util.function.Consumer; +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.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; @@ -76,7 +92,12 @@ 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; +import com.formdev.flatlaf.util.Animator; +import com.formdev.flatlaf.util.CubicBezierEasing; +import com.formdev.flatlaf.util.UIScale; class CommandPalette { @@ -84,25 +105,47 @@ class CommandPalette { /** 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(); 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) { + void install(final JMenu menu) { final Action action = new AbstractAction(NAME) { private static final long serialVersionUID = -7030359886427866104L; @@ -114,7 +157,30 @@ public void actionPerformed(final ActionEvent e) { }; action.putValue(Action.ACCELERATOR_KEY, ACCELERATOR); - toolsMenu.add(new JMenuItem(action)); + action.putValue(Action.SMALL_ICON, Icons.magnifier()); + menu.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, Icons.magnifier()) { + + 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 GuiUtils.prettifiedKey(ACCELERATOR).trim(); } Map getShortcuts() { @@ -142,25 +208,46 @@ 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; } + /** 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) 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,124 +262,502 @@ public void mouseClicked(final MouseEvent e) { } }); populateList(""); - frame.add(table.getScrollPane()); + frame.add(table.getScrollPane(), BorderLayout.SOUTH); frame.pack(); + GuiUtils.enableDrag(frame.getRootPane()); + GuiUtils.enableDrag(titleBar); } - private String[] makeRow(final CmdAction ca) { - return new String[] {ca.id, ca.description()}; + 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()); + }); } - 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)); + // 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 && textEditor.isDisplayable()) + 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 static class Scored { + + private final CmdAction cmd; + private final int score; + + Scored(final CmdAction cmd, final int score) { + this.cmd = cmd; + this.score = score; + } + + CmdAction cmd() { + return cmd; + } + + int score() { + return 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 static Color defaultFieldBackground() { + final Color c = UIManager.getColor("TextField.background"); + return (c != null) ? c : Color.WHITE; } - private void runCmd(final String command) { + 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)); } }); } 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()) { hideWindow(); } else { - frame.center(textEditor); - table.clearSelection(); + if (searchField.getText().isBlank()) + table.clearSelection(); + else + searchField.selectAll(); + restoreOrCenterLocation(); frame.setVisible(true); searchField.requestFocus(); } } - private static class SearchField extends TextEditor.TextFieldWithPlaceholder { + 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.max(minX, Math.min(maxX, frame.getX())), Math.max(minY, Math.min(maxY, frame.getY()))); + } + + 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 = GuiUtils.secondaryColor(); + return (c != null) ? c : Color.GRAY; + } + + /** + * 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) { + private static final long serialVersionUID = 1L; + + @Override + public Color getForeground() { + final Color c = GuiUtils.secondaryColor(); + return (c != null) ? c : 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); + } + + /** The search field, with options menu, and case and whitespace toggles */ + private static class SearchField extends 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 GuiUtils.ToolBar(); + 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, GuiUtils.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; + } + } + } + + /** 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.max(0f, Math.min(1f, alpha)))); + 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 GuiUtils.ToolBar(); + 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); + GuiUtils.enableDrag(label); + parent.add(label); + 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); + 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 +773,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 +793,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 +820,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 +852,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 +876,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 +889,27 @@ private class CmdTable extends JTable { setFillsViewportHeight(true); } + @Override + public void updateUI() { + super.updateUI(); + setBackground(background()); + if (getParent() instanceof JViewport) + ((JViewport) getParent()).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() { + GuiUtils.recolorTracks(this, background()); + super.updateUI(); + } + }; scrollPane.setWheelScrollingEnabled(true); + scrollPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 0, 0)); return scrollPane; } @@ -444,31 +922,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) ? GuiUtils.mix(selectionColor(), bg, .35) : bg); + if (cmd != null && cmd.isDisabled()) + setForeground(GuiUtils.mix(fg, bg, .45)); + else + 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)); + 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 +960,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 +979,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 +993,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,30 +1027,101 @@ 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) + t = (String) action.getValue(Action.SHORT_DESCRIPTION); + tooltipCache = (t == null) ? "" : t.replaceAll("<[^>]*>", ""); // strip HTML once + } + 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 id.toLowerCase().contains(lowercaseQuery) || menuLocation.toLowerCase().contains(lowercaseQuery); + 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) { 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; } @@ -578,161 +1132,37 @@ 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() + " "); - break; - case KeyEvent.KEY_PRESSED: - case KeyEvent.KEY_RELEASED: - s.append(getKeyText(key.getKeyCode()) + " "); - 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); - } - 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); + /** 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 +1186,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("Context Menu"))); } } @@ -809,27 +1236,24 @@ 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) { + final JMenu subMenu = (JMenu) m; + final List subPath = new ArrayList<>(path); + if (subMenu.getText() != null) + subPath.add(subMenu.getText()); + parseMenu(subPath, subMenu); + } else { + registerMain(m, path); } } @@ -865,22 +1289,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 +1312,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); } } @@ -921,7 +1346,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()); } }); @@ -929,7 +1354,7 @@ public void actionPerformed(final ActionEvent e) { @Override String description() { - return "|Unmatched action|"; + return "Unmatched action"; } } } 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 a81ec716..15f45e0f 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; @@ -54,14 +56,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 +71,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 +80,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 +114,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 +125,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 +192,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); @@ -248,24 +250,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, "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)); - TextEditor.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)); - TextEditor.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)); - TextEditor.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,13 +282,12 @@ 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, "Occurrences:"); popup.add(getMenuItem("Next Occurrence", EditorPaneActions.rtaNextOccurrenceAction, false)); popup.add(getMenuItem("Previous Occurrence", EditorPaneActions.rtaPrevOccurrenceAction, false)); - TextEditor.GuiUtils.addPopupMenuSeparator(popup, "Utilities:"); + GuiUtils.addPopupMenuSeparator(popup, "Links:"); popup.add(new OpenLinkUnderCursor().getMenuItem()); popup.add(new SearchWebOnSelectedText().getMenuItem()); - popup.add(noneLangSyntaxMenu); super.setPopupMenu(popup); } @@ -298,68 +299,8 @@ 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) { - TextEditor.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 - } - } + GuiUtils.error(this, message); } @Override @@ -383,14 +324,45 @@ public RTextScrollPane wrappedInScrollbars() { final RTextScrollPane sp = new RTextScrollPane(this); sp.setPreferredSize(new Dimension(600, 350)); sp.setIconRowHeaderEnabled(true); + 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, this); + } finally { + quietBookmarks = false; + } + } + RecordableTextAction wordMovement(final String id, final int direction, final boolean select) { return new RecordableTextAction(id) { private static final long serialVersionUID = 1L; @@ -480,6 +452,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(); @@ -528,6 +509,15 @@ public boolean wasChangedOutside() { curFile.lastModified() != fileLastModified; } + /** + * Records the current modification time of the file as already seen, so that + * {@link #wasChangedOutside()} is false until the file changes again (e.g., + * when the user chose not to reload it). + */ + void acknowledgeOutsideChange() { + if (curFile != null && curFile.exists()) fileLastModified = curFile.lastModified(); + } + /** * Write the contents of this {@link EditorPane} to given file. * @@ -542,11 +532,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(); } @@ -588,7 +601,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 @@ -650,7 +666,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(); @@ -708,8 +724,33 @@ protected String getFileName() { * @see #setLanguage(ScriptLanguage, boolean) */ protected void setLanguageByFileName(final String name) { - setLanguage(scriptService.getLanguageByExtension(FileUtils - .getExtension(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, renameFile && language != null); + 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); } /** @@ -734,6 +775,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 = @@ -757,7 +804,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)) { @@ -790,7 +837,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 @@ -842,7 +888,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) { @@ -931,7 +977,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) { @@ -1093,7 +1139,7 @@ public void loadPreferences() { setAutoCompletion(true); setKeylessAutoCompletion(true); // true for backwards compatibility with ImageJ macro auto-completion setFallbackAutoCompletion(false); - setMarkOccurrences(false); + setMarkOccurrences(true); } else { resetTabSize(); setFontSize(prefService.getFloat(getClass(), FONT_SIZE_PREFS, getFontSize())); @@ -1104,7 +1150,7 @@ public void loadPreferences() { setAutoCompletion(prefService.getBoolean(getClass(), AUTOCOMPLETE_PREFS, true)); setKeylessAutoCompletion(prefService.getBoolean(getClass(), AUTOCOMPLETE_KEYLESS_PREFS, true)); // true for backwards compatibility with ImageJ macro setFallbackAutoCompletion(prefService.getBoolean(getClass(), AUTOCOMPLETE_FALLBACK_PREFS, false)); - setMarkOccurrences(prefService.getBoolean(getClass(), MARK_OCCURRENCES_PREFS, false)); + setMarkOccurrences(prefService.getBoolean(getClass(), MARK_OCCURRENCES_PREFS, true)); setMarginLineEnabled(prefService.getBoolean(getClass(), MARGIN_VISIBLE_PREFS, false)); setVimEnabled(prefService.getBoolean(getClass(), VIM_PREFS, false)); applyTheme(themeName()); @@ -1114,16 +1160,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) && TextEditor.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); } @@ -1138,17 +1182,17 @@ private void applyTheme(final Theme th) throws IllegalArgumentException { final float existingFontSize = getFontSize(); th.apply(this); setFontSize(existingFontSize); - GutterUtils.updateIcons(gutter); + updateGutterIcons(); } 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) { @@ -1211,7 +1255,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/EditorPaneActions.java b/src/main/java/org/scijava/ui/swing/script/EditorPaneActions.java index 8524b37a..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); } @@ -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/ErrorParser.java b/src/main/java/org/scijava/ui/swing/script/ErrorParser.java index 292cb0d4..51ab61dd 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,167 @@ 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 static class FlaggedLine { + + private final Position position; + private final String text; + private final Object highlight; + + FlaggedLine(final Position position, final String text, final Object highlight) { + this.position = position; + this.text = text; + this.highlight = highlight; + } + + Position position() { + return position; + } + + String text() { + return text; + } + + Object highlight() { + return 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 +235,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 +297,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 +308,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 +331,151 @@ 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); + if (lineOffset == UNKNOWN) { + abort("Code selection unknown: Errors 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(); - 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) { + final ScriptException se = (ScriptException) c; + if (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 +484,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 +509,7 @@ public ErrorStripNotifyingParser() { @Override public boolean isEnabled() { - return enabled && errorLines != null; + return enabled && !errors.isEmpty(); } @Override @@ -365,25 +519,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 +542,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/FileDrop.java b/src/main/java/org/scijava/ui/swing/script/FileDrop.java index 547dc74f..02f2e584 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,416 @@ 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()); - } - } - - return list.toArray(new File[list.size()]); - } catch (final IOException ex) { - log(out, "FileDrop: IOException"); + 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 new File[0]; } - // END 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support added. - - 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(); - 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 - - /** - * 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 - - /* ******** I N N E R I N T E R F A C E L I S T E N E R ******** */ - - /** - * 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 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 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 class Event + 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]); + } - /** - * 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"; + 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 - * 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 + @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 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()); - } - } - }); - 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); + if (!node.isDirectory()) { + final File file = new File(node.path); + leaf_listeners.forEach(l -> l.leafDoubleClicked(file)); } - return this; } }); - setVisible(true); + } + + /** + * 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" }; + GuiUtils.paintEmptyHint(g, this, lines); } /** * 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; + } + if (!prune_active) saved_expansion = expandedFolders(); + prune_active = true; + scanning = true; + final List 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 + } + } + + /** 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; + } + + private void restoreHiddenTops() { + hidden_tops.forEach((index, node) -> getModel().insertNodeInto(node, root(), Math.min(index, root().getChildCount()))); + hidden_tops.clear(); + } + + 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; } - // 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 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); } - synchronized public void addLeafListener(final LeafListener l) { - this.leaf_listeners.add(l); + /** 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); + } + } } - synchronized public void removeLeafListener(final LeafListener l) { - this.leaf_listeners.remove(l); + /** + * 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); } - synchronized public ArrayList getLeafListeners() { - return new ArrayList<>(this.leaf_listeners); + 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<>(); + // 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 { - 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()) { + pending.add(node); + SwingUtilities.invokeLater(() -> { + if (!flushTimer.isRunning()) flushTimer.start(); + }); } - - @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())); + if (!key.reset()) { + final Node gone = keys.remove(key); + if (gone != null) byNode.remove(gone); } - }); - - 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 { + SwingUtilities.invokeLater(flushTimer::stop); + 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..a4cc236d 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,28 @@ 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.border.AbstractBorder; +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 +67,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,216 +91,341 @@ 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); + 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 (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) { + GuiUtils.warn(this, "Could not retrieve location of dropped file(s)."); } }); - addContextualMenuToTree(); + } + + /** 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 GuiUtils.ToolBar(); + 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())); + final JToggleButton statusFast = new JToggleButton("Fast Mode"); + statusFast.putClientProperty(FlatClientProperties.STYLE_CLASS, "small"); + 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") : 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(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 JButton statusHelp = GuiUtils.helpButton(null); + 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; + } + } + + private FileFilter filterFor(final String text) throws PatternSyntaxException { + if (text.isEmpty()) return f -> true; + if (isRegexEnabled()) { + // 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(); } - // 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; + if (isCaseSensitive()) return f -> f.getName().contains(text); + final String lowerCase = text.toLowerCase(); + return f -> f.getName().toLowerCase().contains(lowerCase); } - private JButton addDirectoryButton() { - final JButton add_directory = thinButton("+", .25f); - add_directory.setToolTipText("Add a directory"); + 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 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); - new FileDrop(c, files -> { - if (files.length == 0) - return; - final File firstFile = files[0]; - c.setCurrentDirectory((firstFile.isDirectory()) ? firstFile : firstFile.getParentFile()); - c.rescanCurrentDirectory(); - }); - if (JFileChooser.APPROVE_OPTION == c.showOpenDialog(this)) { - final File f = c.getSelectedFile(); - if (f.isDirectory()) - tree.addRootDirectory(f.getAbsolutePath(), false); - } - FileDrop.remove(c); + final String lastFolder = folders.substring(folders.lastIndexOf(File.pathSeparatorChar) + 1); + 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; } - 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) { + 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,59 +438,192 @@ 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()); + + 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 -> { + 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()); + + 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 { 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) { - TextEditor.GuiUtils.error(this, "Folder of selected item does not seem to be accessible."); + } catch (final Throwable ignored) { + 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) { - 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)); - } catch (final Exception ignored) { - TextEditor.GuiUtils.error(this, "Could not open path in Terminal."); + GuiUtils.openTerminal(new File(filepath)); + } catch (final Throwable ignored) { + 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"))); + + GuiUtils.addPopupMenuSeparator(popup, "Contents:"); + final JMenuItem collapseAll = new JMenuItem("Collapse All"); + jmi = collapseAll; + jmi.addActionListener(e -> 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); + + 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 +633,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:

" // - + "
" // - + " " // - + " " // - + " " // - + " " // - + " " // - + " " // - + " " // - + " " // - + " " // - + " " // - + " " // - + " " // - + "
PatternResult
py$Display filenames ending with py
^DemoDisplay 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)
" // + + "
"; + + GuiUtils.showHTMLDialog(this.getRootPane(), "Files Pane", msg); } private boolean isCaseSensitive() { @@ -413,47 +675,141 @@ 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 class SearchField extends TextEditor.TextFieldWithPlaceholder { + private void setCollapsedEnabled(final boolean b) { + userChoice = true; + tree.setSearchCollapsedFolders(b); + applyFilter(); + } + + private class SearchField extends 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(Icons.chevron(false)); + collapsedToggle.setSelectedIcon(Icons.chevron(true)); + + final JToolBar tb = new GuiUtils.ToolBar(); + tb.setFloatable(false); + 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 = 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; } - @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(); + 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; } } } 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..76d627af --- /dev/null +++ b/src/main/java/org/scijava/ui/swing/script/GuiUtils.java @@ -0,0 +1,802 @@ +/* + * #%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.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; +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 java.util.List; +import java.util.ArrayList; +import javax.swing.*; + +import org.scijava.platform.PlatformService; +import org.scijava.util.PlatformUtils; + +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 { + + 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) { + 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) { + 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.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} */ + 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]); + switch (choice) { + case 0: return UnsavedChoice.SAVE; + case 1: return UnsavedChoice.DISCARD; + default: return UnsavedChoice.CANCEL; + } + } + + /** + * A split pane that keeps a collapsed side collapsed while it is resized. By default, + * resizing a window redistributes space among the components, and a collapsed one (e.g., + * a hidden side panel or console) re-appears, either because of its resize weight or + * because its minimum size is enforced + */ + static class StickySplitPane extends javax.swing.JSplitPane { + + private static final long serialVersionUID = 1L; + private static final int NONE = 0, FIRST = 1, SECOND = 2; + private int collapsedBeforeResize = NONE; + private boolean settling; + + StickySplitPane(final int orientation) { + super(orientation); + } + + StickySplitPane(final int orientation, final Component first, final Component second) { + super(orientation, first, second); + } + + /** Whether a layout that restores a collapsed component is in progress (divider locations are transient) */ + boolean isSettling() { + return settling; + } + + /** The component that is currently collapsed (FIRST, SECOND), or NONE */ + private int collapsedComponent() { + final boolean vertical = getOrientation() == VERTICAL_SPLIT; + final int size = vertical ? getHeight() : getWidth(); + final int loc = getDividerLocation(); + if (size <= 0 || loc < 0) return NONE; // not laid out yet + final Insets in = getInsets(); + if (loc <= (vertical ? in.top : in.left) + 5) return FIRST; + if (loc >= size - getDividerSize() - (vertical ? in.bottom : in.right) - 5) return SECOND; + return NONE; + } + + @Override + public void setBounds(final int x, final int y, final int width, final int height) { + if (width != getWidth() || height != getHeight()) collapsedBeforeResize = collapsedComponent(); + super.setBounds(x, y, width, height); + } + + @Override + public void doLayout() { + final int wasCollapsed = collapsedBeforeResize; + collapsedBeforeResize = NONE; + settling = wasCollapsed != NONE; + try { + super.doLayout(); + if (wasCollapsed != NONE && collapsedComponent() != wasCollapsed) { + setDividerLocation(wasCollapsed == FIRST ? 0d : 1d); + super.doLayout(); + } + } finally { + settling = false; + } + } + } + + /** + * 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"); + 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); + } + 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[] 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() { + return getJTabbedPane(JTabbedPane.TOP); + } + + /** As {@link #getJTabbedPane()}, with the tabs initially at the given placement (JTabbedPane.TOP, LEFT, ...) */ + static JTabbedPane getJTabbedPane(final int initialPlacement) { + 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(); + 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, pos.equalsIgnoreCase(placementName(initialPlacement))); + jcbmi.addItemListener(e -> { + if (e.getStateChange() != java.awt.event.ItemEvent.SELECTED) return; // ignore the deselected item + 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); + } + final JButton triggerButton = ellipsisButton(null); + triggerButton.addActionListener( e -> popup.show(triggerButton, + triggerButton.getWidth() /2, triggerButton.getHeight() /2)); + // 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); + // With tabs on the left/right the free space is vertical: flush the button to the bottom instead + tabbed.addPropertyChangeListener("tabPlacement", evt -> { + final boolean vertical = tabbed.getTabPlacement() == JTabbedPane.LEFT + || tabbed.getTabPlacement() == JTabbedPane.RIGHT; + // dots run across the tab strip: vertical for tabs on top/bottom, horizontal for left/right + triggerButton.setIcon(vertical ? Icons.ellipsis() : Icons.ellipsisVertical()); + trailing.add(triggerButton, vertical ? java.awt.BorderLayout.SOUTH : java.awt.BorderLayout.EAST); + trailing.revalidate(); + trailing.repaint(); + }); + tabbed.putClientProperty(FlatClientProperties.TABBED_PANE_TRAILING_COMPONENT, trailing); + if (initialPlacement != JTabbedPane.TOP) tabbed.setTabPlacement(initialPlacement); // after the listener: updates the button + return tabbed; + } + + private static String placementName(final int placement) { + switch (placement) { + case JTabbedPane.LEFT: return "Left"; + case JTabbedPane.BOTTOM: return "Bottom"; + case JTabbedPane.RIGHT: return "Right"; + default: return "Top"; + } + } + + /** 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.max(0d, Math.min(1d, weight)); + 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); + } + + /** + * 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 }; + 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..1bc8506b 100644 --- a/src/main/java/org/scijava/ui/swing/script/GutterUtils.java +++ b/src/main/java/org/scijava/ui/swing/script/GutterUtils.java @@ -29,118 +29,71 @@ 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; +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; - gutter.setSpacingBetweenLineNumbersAndFoldIndicator(0); + this.textArea = textArea; //gutter.setFoldIndicatorStyle(org.fife.ui.rtextarea.FoldIndicatorStyle.MODERN); // DEFAULT - 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); - 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(padded(Icons.bookmark(color, UIScale.unscale(height)), 3)); 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); - //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; - } + /** 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 size; - } + @Override + public int getIconWidth() { + return icon.getIconWidth() + 2 * pad; + } - @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); + @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/Icons.java b/src/main/java/org/scijava/ui/swing/script/Icons.java new file mode 100644 index 00000000..b1ba70ec --- /dev/null +++ b/src/main/java/org/scijava/ui/swing/script/Icons.java @@ -0,0 +1,424 @@ +/* + * #%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.icons.FlatOptionPaneErrorIcon; +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 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 static final String ELLIPSIS = "M96 320C96 289.1 121.1 264 152 264C182.9 264 208 289.1 208 320C208 350.9 182.9 376 152 376C121.1 376 96 350.9 96 320zM264 320C264 289.1 289.1 264 320 264C350.9 264 376 289.1 376 320C376 350.9 350.9 376 320 376C289.1 376 264 350.9 264 320zM488 264C518.9 264 544 289.1 544 320C544 350.9 518.9 376 488 376C457.1 376 432 350.9 432 320C432 289.1 457.1 264 488 264z"; + private static final String ELLIPSIS_VERTICAL = "M320 208C289.1 208 264 182.9 264 152C264 121.1 289.1 96 320 96C350.9 96 376 121.1 376 152C376 182.9 350.9 208 320 208zM320 432C350.9 432 376 457.1 376 488C376 518.9 350.9 544 320 544C289.1 544 264 518.9 264 488C264 457.1 289.1 432 320 432zM376 320C376 350.9 350.9 376 320 376C289.1 376 264 350.9 264 320C264 289.1 289.1 264 320 264C350.9 264 376 289.1 376 320z"; + + private Icons() { + } + + /** Three dots in a row (follows the component foreground) */ + static Icon ellipsis() { + return new GlyphIcon(ELLIPSIS, null, null, false, 0, 0, 640, 640, 18); + } + + /** Three dots in a column (follows the component foreground) */ + static Icon ellipsisVertical() { + return new GlyphIcon(ELLIPSIS_VERTICAL, null, null, false, 0, 0, 640, 640, 18); + } + + /** Small error icon for status messages */ + static Icon error() { + final FlatAbstractIcon icon = new FlatOptionPaneErrorIcon(); + icon.setScale(.35f); + return icon; + } + + /** 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 + */ + 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); + } + + /** + * 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( + BOOKMARK, + color, color, false, 128, 64, 384, 512, height); + } + + /** + * 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(); + } + + /** + * Foreground color with which to paint an icon. Note: The component may be + * null, e.g. when macOS renders icons for its native screen menu bar. + */ + private static Color foreground(final Component c) { + if (c != null) return c.getForeground(); + final Color color = UIManager.getColor("MenuItem.foreground"); + return color != null ? color : Color.GRAY; + } + + /** + * 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 = light == null ? foreground(c) : 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 + break; + case 'L': + p.lineTo(v[0], v[1]); + break; + case 'C': + p.curveTo(v[0], v[1], v[2], v[3], v[4], v[5]); + break; + 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(foreground(c)); + g.drawRoundRect(1, 2, 13, 11, 3, 3); + paintContent(g, c instanceof AbstractButton && ((AbstractButton) c).isSelected()); + } + } + + private static 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 { + FlatUIUtils.setRenderingHints(g2); + g2.setColor(foreground(c)); + 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(foreground(c)); + 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 new file mode 100644 index 00000000..d0ae9512 --- /dev/null +++ b/src/main/java/org/scijava/ui/swing/script/NotesPanel.java @@ -0,0 +1,434 @@ +/* + * #%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.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.EmptyBorder; +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 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 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 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 final Timer poll; + private boolean loading; + + NotesPanel(final Supplier activeEditor, + final PrefService prefs, final Class prefsOwner) + { + super(new BorderLayout()); + this.activeEditor = activeEditor; + this.prefs = prefs; + this.prefsOwner = prefsOwner; + + // Scratchpad + 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 snippets", + "They are saved between sessions"); + } + }; + scratch.setLineWrap(prefs.getBoolean(prefsOwner, PREFS_WRAP, true)); + scratch.setWrapStyleWord(true); + scratch.setComponentPopupMenu(scratchMenu()); + final JScrollPane scratchPane = new JScrollPane(scratch); + 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); + GuiUtils.flattenScrollBars(listPane); + final JPanel pane2 = new JPanel(new BorderLayout()); + final JLabel clipboardHeader = header("Clipboard History"); + 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 + 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(); + poll = new Timer(REFRESH_DELAY_MS, e -> { + if (isShowing()) refresh(); + }); + } + + @Override + public void addNotify() { + super.addNotify(); + if (!poll.isRunning()) poll.start(); + } + + @Override + public void removeNotify() { + poll.stop(); + super.removeNotify(); + } + + 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()) { + 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(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; + } + } +} 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 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(); + } + + /** 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(); + 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) + "..."; + 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 65713ca5..5ff2ab3b 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; @@ -59,8 +49,11 @@ 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.beans.PropertyChangeListener; import java.io.BufferedReader; import java.io.CharArrayWriter; import java.io.File; @@ -78,25 +71,32 @@ 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; +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; 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; import java.util.HashSet; +import java.util.LinkedHashSet; import java.util.LinkedHashMap; import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; import java.util.Map; 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; @@ -108,36 +108,13 @@ import javax.script.ScriptEngine; import javax.script.ScriptException; -import javax.swing.AbstractAction; -import javax.swing.AbstractButton; -import javax.swing.BoxLayout; -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.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; 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; @@ -145,8 +122,11 @@ import javax.swing.tree.TreePath; 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.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; @@ -163,6 +143,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; @@ -179,6 +160,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; @@ -187,11 +169,9 @@ 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.FlatLaf; +import com.formdev.flatlaf.FlatClientProperties; /** * A versatile script editor for SciJava applications. @@ -212,8 +192,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"; @@ -235,31 +218,101 @@ public class TextEditor extends JFrame implements ActionListener, private static AbstractTokenMakerFactory tokenMakerFactory = null; - private JTabbedPane tabbed; - 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, replaceTabsWithSpaces, - replaceSpacesWithTabs, zapGremlins,openClassOrPackageHelp; - private RecentFilesMenuItem openRecent; - private JMenu editMenu, gitMenu, tabsMenu, fontSizeMenu, tabSizeMenu, toolsMenu, + 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 tabsMenuTabsStart; - private Set tabsMenuItems; - private FindAndReplaceDialog findDialog; - private JCheckBoxMenuItem autoSave, wrapLines, tabsEmulated, autoImport, - autocompletion, fallbackAutocompletion, keylessAutocompletion, - markOccurences, paintTabs, whiteSpace, marginLine, lockPane, vimMode; + private final int codeMenuCommentsIndex; + private final int tabsMenuTabsStart; + private final Set tabsMenuItems; + private final FindAndReplaceDialog findDialog; + private JButton statusTab; + 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 static final String SIDE_TAB_PREFS = "script.editor.SideTab"; + private JButton statusPos, statusLang; + private JToggleButton statusSide, statusBelow, statusRight, statusRepl, statusVimToggle; + private int sideLastLocation = -1; + private final JMenu languageMenu; + private JLabel statusText; + private JLabel statusVim; + 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; + /** Share of the window given to the side panel by default */ + private static final double SIDE_SHARE = .20d; + private JCheckBoxMenuItem vimMode; + private JCheckBoxMenuItem sidePaneItem, consoleItem; // Window menu: kept in sync with the status bar + private boolean syncingPanes; + private boolean disposed; // see dispose() + private boolean checkingOutsideChanges; // true while the "file changed outside" dialog is showing + private boolean syncingVim; // true while the Vim menu item and status toggle are being synchronized private ButtonGroup themeRadioGroup; private JTextArea errorScreen = new ConsoleArea(ConsoleArea.Content.ERRORS); private final FileSystemTree tree; - private final JSplitPane body; + private final GuiUtils.StickySplitPane body; private int compileStartOffset; private Position compileStartPosition; @@ -267,8 +320,17 @@ public class TextEditor extends JFrame implements ActionListener, private boolean respectAutoImports; private String activeTheme; - private int[] panePositions; - + // 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 + } + }); + }; @Parameter private Context context; @@ -301,7 +363,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; @@ -309,11 +371,20 @@ public class TextEditor extends JFrame implements ActionListener, private boolean incremental = false; private DragSource dragSource; private boolean layoutLoading = true; - private OutlineTreePanel sourceTreePanel; + // 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 final OutlineTreePanel sourceTreePanel; protected final CommandPalette cmdPalette; - public static final ArrayList instances = new ArrayList<>(); - public static final ArrayList contexts = new ArrayList<>(); + /** The editors that are open: an editor is removed from here when it is disposed */ + public static final List instances = new CopyOnWriteArrayList<>(); + /** The contexts of the open editors (parallel to {@link #instances}) */ + public static final List contexts = new CopyOnWriteArrayList<>(); public TextEditor(final Context context) { @@ -322,15 +393,74 @@ 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(); - 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); + tabbed.putClientProperty(FlatClientProperties.TABBED_PANE_TAB_AREA_ALIGNMENT, + FlatClientProperties.TABBED_PANE_ALIGN_LEADING); + tabbed.putClientProperty(FlatClientProperties.TABBED_PANE_TAB_CLOSABLE, true); + tabbed.putClientProperty(FlatClientProperties.TABBED_PANE_TAB_CLOSE_TOOLTIPTEXT, "Close"); + tabbed.putClientProperty(FlatClientProperties.TABBED_PANE_TAB_CLOSE_CALLBACK, + (BiConsumer) (pane, index) -> { + pane.setSelectedIndex(index); + closeTab(true); + }); + installCloseTabsPopup(); + tree = new FileSystemTree(log); + sideTabs = GuiUtils.getJTabbedPane(JTabbedPane.LEFT); + sideTabs.putClientProperty(FlatClientProperties.TABBED_PANE_TAB_AREA_ALIGNMENT, + FlatClientProperties.TABBED_PANE_ALIGN_FILL); + // Icon-only tabs: only the selected tab shows its title, keeping the pane narrow + sideTabs.putClientProperty(FlatClientProperties.TABBED_PANE_TAB_WIDTH_MODE, + FlatClientProperties.TABBED_PANE_TAB_WIDTH_MODE_COMPACT); + filesPanel = new FileSystemTreePanel(tree, context); + filesPanel.setActiveScriptSupplier(() -> { + try { + return getEditorPane().getFile(); + } catch (final RuntimeException ignored) { + return null; + } + }); + addSideTab("Files", Icons.folder(), filesPanel); + + sourceTreePanel = new OutlineTreePanel(); + bookmarksPanel = new BookmarksPanel(this::collectBookmarks, this::goToBookmark); + tasksPanel = new TasksPanel(this::collectTasks, this::goToTask); + + // Outline + final JPanel pane1 = new JPanel(new BorderLayout()); + final JLabel outlineHeader = header("Structure"); + pane1.add(outlineHeader, BorderLayout.NORTH); + pane1.add(sourceTreePanel, BorderLayout.CENTER); + + addSideTab("Outline", Icons.outline(), pane1); + + // Markers: bookmarks and tasks of all open tabs + final JPanel pane2 = new JPanel(new BorderLayout()); + pane2.add(header("Bookmarks", this::showBookmarksHelp), BorderLayout.NORTH); + pane2.add(bookmarksPanel, BorderLayout.CENTER); + final JPanel pane3 = new JPanel(new BorderLayout()); + 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); + 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(); + } catch (final RuntimeException ignored) { + return null; + } + }, prefService, getClass()); + addSideTab("Notes", Icons.clipboard(), notesPanel); + body = new GuiUtils.StickySplitPane(JSplitPane.HORIZONTAL_SPLIT, sideTabs, tabbed); + GuiUtils.installSplitHandle(null, body); // These items are dynamic and need to be initialized before EditorPane creation initializeDynamicMenuComponents(); @@ -358,6 +488,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); @@ -373,22 +517,8 @@ public TextEditor(final Context context) { } else { new SetWritableAction().actionPerformedImpl(e, getEditorPane()); } + 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(); @@ -418,13 +548,14 @@ 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(); // 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); @@ -502,19 +633,17 @@ 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 = - 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; @@ -524,22 +653,39 @@ 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); + 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"); + + 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 -- @@ -562,19 +708,23 @@ public TextEditor(final Context context) { tabsMenu.setMnemonic(KeyEvent.VK_W); GuiUtils.addMenubarSeparator(tabsMenu, "Panes:"); // Assume initial status from prefs or panel visibility - final JCheckBoxMenuItem jcmi1 = new JCheckBoxMenuItem("Side Pane", + final JCheckBoxMenuItem jcmi1 = sidePaneItem = new JCheckBoxMenuItem("Side Pane", prefService.getInt(getClass(), MAIN_DIV_LOCATION, body.getDividerLocation()) > 0 || isLeftPaneExpanded(body)); - jcmi1.addItemListener(e -> collapseSplitPane(0, !jcmi1.isSelected())); + jcmi1.addItemListener(e -> { + if (!syncingPanes) setSidePanelVisible(jcmi1.isSelected()); + }); tabsMenu.add(jcmi1); // Console not initialized. Assume it is displayed if no prefs read - final JCheckBoxMenuItem jcmi2 = new JCheckBoxMenuItem("Console", + final JCheckBoxMenuItem jcmi2 = consoleItem = new JCheckBoxMenuItem("Console", prefService.getInt(getClass(), TAB_DIV_LOCATION, 1) > 0); - jcmi2.addItemListener(e -> collapseSplitPane(1, !jcmi2.isSelected())); + jcmi2.addItemListener(e -> { + if (!syncingPanes) getTab().setBottomVisible(jcmi2.isSelected()); + }); 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); @@ -611,8 +761,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'; @@ -635,7 +784,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 +797,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); @@ -656,10 +809,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); @@ -679,13 +830,17 @@ public TextEditor(final Context context) { appendPreferences(options); mbar.add(options); mbar.add(helpMenu()); + mbar.add(Box.createHorizontalGlue()); + mbar.add(cmdPalette.getMenuButton()); // -- END MENUS -- // 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); }); @@ -699,16 +854,22 @@ 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 + 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 - body.setOneTouchExpandable(true); body.addPropertyChangeListener(evt -> { - if ("dividerLocation".equals(evt.getPropertyName())) saveWindowSizeToPrefs(); + if ("dividerLocation".equals(evt.getPropertyName())) saveWindowSizeToPrefsLater(); }); // Tweaks for FileSystemTree @@ -743,11 +904,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); @@ -759,18 +919,21 @@ 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) { + UIManager.addPropertyChangeListener(lookAndFeelListener); + showTemporaryStatus("Tip: press " + cmdPalette.getAcceleratorString() + + " to search all commands and actions", 10000); + } + @Override public void windowClosing(final WindowEvent e) { - if (!confirmClose()) return; - tree.destroy(); - // Necessary to prevent memory leaks - for (final DragSourceListener l : dragSource.getDragSourceListeners()) { - dragSource.removeDragSourceListener(l); + if (layoutSaveTimer.isRunning()) { // flush while the tabs still exist + layoutSaveTimer.stop(); + saveWindowSizeToPrefs(); } - dragSource = null; - getTab().destroy(); - cmdPalette.dispose(); - dispose(); + if (!confirmClose()) return; + dispose(); // releases everything this editor registered } }); @@ -785,7 +948,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); @@ -793,15 +956,14 @@ public void windowGainedFocus(final WindowEvent e) { try { threadService.invoke(() -> { pack(); - body.setDividerLocation(0.2); // Important!: will be read as prefs. default + body.setDividerLocation(SIDE_SHARE); // Important!: will be read as prefs. default getTab().setREPLVisible(false); loadWindowSizePreferences(); pack(); }); } catch (final Exception ie) { - /* ignore */ - log.debug(ie); + log.error("Failed to lay out Script Editor window", ie); } findDialog = new FindAndReplaceDialog(this); @@ -810,7 +972,7 @@ public void windowGainedFocus(final WindowEvent e) { @Override public void componentResized(final ComponentEvent e) { - saveWindowSizeToPrefs(); + saveWindowSizeToPrefsLater(); } }); @@ -825,29 +987,75 @@ 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()); // Ensure menu commands are up-to-date updateUI(true); - // Store locations of splitpanes - panePositions = new int[]{body.getDividerLocation(), getTab().getDividerLocation()}; editorPane.requestFocus(); } private void resetLayout() { - body.setDividerLocation(.2d); - getTab().setOrientation(JSplitPane.VERTICAL_SPLIT); - getTab().setDividerLocation((incremental) ? .7d : .75d); - if (incremental) - getTab().getScreenAndPromptSplit().setDividerLocation(.5d); - getTab().setREPLVisible(incremental); + body.setDividerLocation(SIDE_SHARE); + getTab().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)); + label.putClientProperty(FlatClientProperties.STYLE_CLASS, "small"); + label.setForeground(GuiUtils.secondaryColor()); + return label; + } + + /** A header with a help button on its right, which is also a split handle */ + private JComponent header(final String text, final Runnable help) { + final JLabel label = header(text); + // installSplitHandle() leaves explicitly set cursors of children alone + label.setCursor(Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR)); + final JPanel panel = new JPanel(new BorderLayout()); + panel.setOpaque(false); + panel.add(label, BorderLayout.CENTER); + panel.add(GuiUtils.helpButton(help), BorderLayout.EAST); + return panel; + } + + private static String tagHtml(final String tag) { + return String.format("%s", TasksPanel.tagColor(tag).getRGB() & 0xFFFFFF, tag); + } + + private void showTasksHelp() { + showHTMLDialog("Task Tags Help", String.format("" // + + "
\n" // + + "Comments containing %s, %s or %s are registered as tasks automatically:\n" // + + "
    \n" // + + "
  • 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" // + + "
", tagHtml("TODO"), tagHtml("FIXME"), tagHtml("HACK"))); + } + + private void showBookmarksHelp() { + showHTMLDialog("Bookmarks Help", "" // + + "
Bookmarks flag lines you want to come back to:\n" // + + "
    \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" // + + "
"); + } + private void assembleEditMenu() { // requires an existing instance of an EditorPane final int ctrl = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); @@ -861,6 +1069,13 @@ 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(); + if (!statusSide.isSelected()) statusSide.doClick(); + }); + editMenu.add(notesItem); GuiUtils.addMenubarSeparator(editMenu, "Find:"); find = addToMenu(editMenu, "Find/Replace...", KeyEvent.VK_F, ctrl); find.setMnemonic(KeyEvent.VK_F); @@ -894,26 +1109,41 @@ 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); 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."); @@ -924,7 +1154,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."); @@ -939,6 +1170,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) { @@ -954,7 +1186,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."); @@ -966,8 +1199,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."); @@ -1018,8 +1251,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; } @@ -1137,8 +1371,11 @@ 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())); - markOccurences = new JCheckBoxMenuItem("Mark Occurences", false); + wrapLines.addItemListener(e -> { + setWrapLines(wrapLines.getState()); + syncStatusBar(); + }); + markOccurences = new JCheckBoxMenuItem("Mark Occurrences", true); 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())); @@ -1157,10 +1394,13 @@ private void initializeDynamicMenuComponents() { fallbackAutocompletion.setToolTipText("If selected, Java completions will be used when scripting
" + "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/

/}. - *

- * - * @param templatesMenu the top-level menu to populate - */ /** Gets the plugin label of the given language if it has one, else its language name. */ private static String languageDisplayName(final ScriptLanguage language) { final String label = language.getInfo() == null ? null : language.getInfo().getLabel(); @@ -1499,6 +1748,16 @@ private String declaredLanguage(final URL url) { return null; } + /** + * 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/

/}. + *

+ * + * @param templatesMenu the top-level menu to populate + */ private void addTemplates(final JMenu templatesMenu) { final File baseDir = appService.getApp().getBaseDirectory(); @@ -1569,15 +1828,21 @@ 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); } final String path = url.getPath(); setEditorPaneFileName(path.substring(path.lastIndexOf('/') + 1)); + getEditorPane().resetModified(); } catch (final Exception e) { log.error(e); @@ -1594,6 +1859,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()); } @@ -1638,11 +1904,12 @@ 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 { + switch (GuiUtils.confirmUnsaved(this, "Do you want to save changes?", + "Save Changes?")) { + case SAVE: return save(); // Compiled languages should not progress if their source is unsaved - return !beforeCompiling; + case DISCARD: return !beforeCompiling; + default: return false; } } @@ -1776,10 +2043,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(); } @@ -1792,6 +2059,340 @@ 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) { + 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); + }); + 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(" "); + 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; + + @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 9999, Col 999")); + return d; + } + }; + statusPos.setToolTipText("Caret position. Click to go to line..."); + statusPos.setFocusable(false); + 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.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 = 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); + 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)); + statusSide = new JToggleButton(Icons.sidebar()); + statusSide.setToolTipText("Shows/hides the side panel (Files, Outline, Notes)"); + statusSide.setFocusable(false); + statusSide.setSelected(true); + statusSide.addActionListener(e -> setSidePanelVisible(statusSide.isSelected())); + body.addPropertyChangeListener("dividerLocation", evt -> { + final int loc = body.getDividerLocation(); + if (loc > 50 && !body.isSettling()) sideLastLocation = loc; + statusSide.setSelected(loc > 5); + syncPaneItems(loc > 5, null); + }); + // Layout of the console: below or beside the editor. Clicking the active one collapses/restores it + statusBelow = new JToggleButton(Icons.bottomPane()); + statusBelow.setToolTipText("Vertical Layout: Console below the editor.
Click again to hide/show it"); + statusRight = new JToggleButton(Icons.rightPane()); + statusRight.setToolTipText("Horizontal Layout: Console beside the editor.
Click again to hide/show it"); + statusBelow.setActionCommand("Console Below Editor (Toggle)"); + statusRight.setActionCommand("Console Beside Editor (Toggle)"); + for (final JToggleButton b : new JToggleButton[] { statusBelow, statusRight }) { + b.setFocusable(false); + cmdPalette.register(b, "Status Bar"); + } + statusBelow.setSelected(true); + statusBelow.addActionListener(e -> { + getTab().toggleLayout(true); + syncStatusBar(); + }); + statusRight.addActionListener(e -> { + getTab().toggleLayout(false); + syncStatusBar(); + }); + statusRepl = new JToggleButton("REPL", Icons.repl()); + statusRepl.setActionCommand("Toggle REPL Prompt"); + 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 + }); + statusVimToggle = new JToggleButton("Vim"); + statusVimToggle.setFont(statusVimToggle.getFont().deriveFont(statusVimToggle.getFont().getSize2D() * .9f)); + statusVimToggle.setToolTipText(vimMode.getToolTipText()); + statusVimToggle.setFocusable(false); + statusVimToggle.addActionListener(e -> setVimMode(statusVimToggle.isSelected())); + final JToolBar bar = new GuiUtils.ToolBar(); + bar.setFloatable(false); + 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(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(statusPos); + bar.add(statusLang); + bar.add(statusWrap); + bar.add(statusTab); + 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; + } + + /** 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(); + 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..."); + 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"; + 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) { + lead.append(" ".repeat(Math.max(0, col))); + } else { + lead.append("\t".repeat(Math.max(0, col / tabSize))); + lead.append(" ".repeat(Math.max(0, col % tabSize))); + } + 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; + } + 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) { + error("Could not convert the indentation: " + ex.getMessage()); + } + } + + 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 + } + } + + /** 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; + try { + final EditorPane pane = getEditorPane(); + 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(); + syncPaneItems(null, shown); + statusBelow.setSelected(shown && tab.isLayoutBelow()); + statusRight.setSelected(shown && !tab.isLayoutBelow()); + } + if (statusRepl != null) statusRepl.setSelected(getTab().isREPLEnabled()); + syncVimControls(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 + } + } + private void setTabsEmulated(final boolean emulated) { for (int i = 0; i < tabbed.getTabCount(); i++) getEditorPane(i).setTabsEmulated(emulated); @@ -1834,6 +2435,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); @@ -1857,6 +2481,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. @@ -1883,19 +2581,51 @@ boolean handleVimCommand(final String command) { } } + /** Shows/hides the side panel (Files, Outline, Notes), restoring its last width */ + private void setSidePanelVisible(final boolean visible) { + if (visible) body.setDividerLocation(sideLastLocation > 50 ? sideLastLocation : (int) (body.getWidth() * SIDE_SHARE)); + else body.setDividerLocation(0); // the location is remembered by the divider listener + } + + /** Updates the Window menu items without triggering their listeners (null: leave as is) */ + private void syncPaneItems(final Boolean side, final Boolean console) { + syncingPanes = true; + try { + if (side != null && sidePaneItem != null) sidePaneItem.setSelected(side); + if (console != null && consoleItem != null) consoleItem.setSelected(console); + } finally { + syncingPanes = false; + } + } + + /** Applies Vim mode to all tabs, keeping the menu item and the status bar toggle in sync */ private void setVimMode(final boolean enabled) { + if (syncingVim) return; for (int i = 0; i < tabbed.getTabCount(); i++) getEditorPane(i).setVimEnabled(enabled); + syncVimControls(enabled); getEditorPane().requestFocusInWindow(); } + /** Shows the given Vim state in both controls without triggering their listeners */ + private void syncVimControls(final boolean enabled) { + syncingVim = true; + try { + if (vimMode != null) vimMode.setState(enabled); + if (statusVimToggle != null) statusVimToggle.setSelected(enabled); + } finally { + syncingVim = false; + } + } + 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"); @@ -1903,7 +2633,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); @@ -1914,6 +2644,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(); @@ -1921,14 +2654,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 */ @@ -1960,10 +2700,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); } @@ -1982,39 +2731,10 @@ private void updateThemeControls(final String theme) { } } - private void collapseSplitPane(final int pane, final boolean collapse) { - final JSplitPane jsp = (pane == 0) ? body : getTab(); - if (collapse) { - panePositions[pane] = jsp.getDividerLocation(); - if (pane == 0) { // collapse to left - jsp.setDividerLocation(0.0d); - } else { // collapse to bottom - jsp.setDividerLocation(1.0d); - } - } else { - jsp.setDividerLocation(panePositions[pane]); - // Check if user collapsed pane manually (stashed panePosition is invalid) - final boolean expanded = (pane == 0) ? isLeftPaneExpanded(jsp) : isRightOrBottomPaneExpanded(jsp); - if (!expanded - // && JOptionPane.OK_OPTION == JOptionPane.showConfirmDialog(TextEditor.this, // - // "Expand to default position?", "Expand to Defaults?", JOptionPane.OK_CANCEL_OPTION) - ) { - jsp.setDividerLocation((pane == 0) ? .2d : .75d); - panePositions[pane] = jsp.getDividerLocation(); - } - } - } - private boolean isLeftPaneExpanded(final JSplitPane pane) { return pane.isVisible() && pane.getLeftComponent().getWidth() > 0; } - private boolean isRightOrBottomPaneExpanded(final JSplitPane pane) { - final int dim = (pane.getOrientation() == JSplitPane.VERTICAL_SPLIT) ? pane.getRightComponent().getHeight() - : pane.getRightComponent().getWidth(); - return pane.isVisible() && dim > 0; - } - protected boolean handleTabsMenu(final Object source) { if (!(source instanceof JMenuItem)) return false; final JMenuItem item = (JMenuItem) source; @@ -2036,12 +2756,13 @@ public void stateChanged(final ChangeEvent e) { } final EditorPane editorPane = getEditorPane(index); lockPane.setSelected(editorPane.isLocked()); + syncStatusBar(); editorPane.requestFocus(); checkForOutsideChanges(); //whiteSpace.setSelected(editorPane.isWhitespaceVisible()); - editorPane.setLanguageByFileName(editorPane.getFileName()); + editorPane.syncLanguageWithFileName(); updateLanguageMenu(editorPane.getCurrentLanguage()); setTitle(); @@ -2085,12 +2806,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,18 +2824,63 @@ 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(); + } + + 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(); + } + + /** 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); + if (!SwingUtilities.isEventDispatchThread()) { + SwingUtilities.invokeLater(this::listBookmarks); + return; } + sideTabs.setSelectedComponent(markersSplit); + bookmarksPanel.refresh(); + tasksPanel.refresh(); + if (!statusSide.isSelected()) statusSide.doClick(); } void clearAllBookmarks() { final Vector bookmarks = getAllBookmarks(); if (bookmarks.isEmpty()) return; - ; if (confirm("Delete all bookmarks?", "Confirm Deletion?", "Delete")) { bookmarks.forEach(bk -> bk.tab.editorPane.toggleBookmark(bk.getLineNumber())); } @@ -2183,19 +2954,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)); } @@ -2228,6 +2996,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 @@ -2262,13 +3031,17 @@ public TextEditorTab open(final File file) { if (file != null) openRecent.add(file.getAbsolutePath()); else { final String lastLanguageName = prefService.get(getClass(), LAST_LANGUAGE); - if ("none" != lastLanguageName) + if (!"none".equals(lastLanguageName)) setLanguage(scriptService.getLanguageByName(lastLanguageName)); } 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) { @@ -2289,8 +3062,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); } @@ -2301,12 +3081,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; } @@ -2344,14 +3125,17 @@ 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"; - 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); @@ -2398,7 +3182,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()); @@ -2438,6 +3222,31 @@ static void deleteRecursively(final File directory) { directory.delete(); } + /** + * Releases everything this editor registered with static or long-lived objects, so that + * it can be garbage collected. All the ways of closing the editor end up here (closing the + * window, disposing of the context). A disposed editor must not be reused: create a new one + */ + @Override + public void dispose() { + if (!disposed) { // can be called more than once + disposed = true; + layoutSaveTimer.stop(); + titleTimer.stop(); + UIManager.removePropertyChangeListener(lookAndFeelListener); + tree.destroy(); + if (dragSource != null) { // necessary to prevent memory leaks + for (final DragSourceListener l : dragSource.getDragSourceListeners()) + dragSource.removeDragSourceListener(l); + dragSource = null; + } + cmdPalette.dispose(); + instances.remove(this); + contexts.remove(context); + } + super.dispose(); + } + void setLanguage(final ScriptLanguage language) { setLanguage(language, false); } @@ -2457,6 +3266,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 @@ -2564,10 +3374,11 @@ else if (tabSize == Integer.parseInt(item.getText())) { } } markOccurences.setState(pane.getMarkOccurrences()); - vimMode.setState(pane.isVimEnabled()); + syncVimControls(pane.isVimEnabled()); 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()); @@ -2690,7 +3501,7 @@ public void run() { handleException(e); } // Leave kill menu item enabled if other tasks are running - kill.setEnabled(executingTasks.size() > 0); + kill.setEnabled(!executingTasks.isEmpty()); setTitle(); } } @@ -2736,10 +3547,13 @@ 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") + @SuppressWarnings({"removal" }) // Thread.stop() is marked for removal void obliterate() { try { // Stop printing to the screen @@ -2749,17 +3563,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.isEmpty())); + 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 @@ -2828,6 +3675,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); @@ -2843,7 +3699,7 @@ public void kill(final Executer executer) { * kill it. */ public void chooseTaskToKill() { - if (executingTasks.size() == 0) { + if (executingTasks.isEmpty()) { error("\nNo running scripts\n"); return; } @@ -2899,8 +3755,15 @@ public void runBatch() { return; } final ScriptInfo info = new ScriptInfo(context, // - "dummy." + getCurrentLanguage().getExtensions().get(0), // + "batch_submission." + getCurrentLanguage().getExtensions().get(0), // 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); } @@ -2912,13 +3775,14 @@ 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 { text = tab.getEditorPane().getText(); + getEditorPane().getErrorHighlighter().setSelectedCodeExecution(false); } execute(tab, text, false); @@ -2935,6 +3799,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); @@ -2955,7 +3821,7 @@ public void execute() { errors.flush(); markCompileEnd(); // For executions from the prompt - if (writeCommandLog && null != text && text.trim().length() > 0) { + if (writeCommandLog && null != text && !text.trim().isEmpty()) { writePromptLog(getEditorPane().getCurrentLanguage(), text); } } @@ -3026,7 +3892,7 @@ private void writePromptLog(final ScriptLanguage language, final String text) { file.getParentFile().mkdirs(); file.createNewFile(); // atomic } - Files.write(Paths.get(path), Arrays.asList(new String[]{text, "#"}), Charset.forName("UTF-8"), + Files.write(Paths.get(path), Arrays.asList(text, "#"), StandardCharsets.UTF_8, StandardOpenOption.APPEND, StandardOpenOption.DSYNC); } catch (final IOException e) { log.error("Failed to write executed prompt command to file " + path, e); @@ -3051,9 +3917,9 @@ private ArrayList loadPromptLog(final ScriptLanguage language) { ra = new RandomAccessFile(path, "r"); final byte[] bytes = new byte[(int)ra.length()]; ra.readFully(bytes); - final String sep = System.getProperty("line.separator"); // used fy Files.write above - commands.addAll(Arrays.asList(new String(bytes, Charset.forName("UTF-8")).split(sep + "#" + sep))); - if (0 == commands.get(commands.size()-1).length()) commands.remove(commands.size() -1); // last entry is empty + final String sep = System.lineSeparator(); // used fy Files.write above + commands.addAll(Arrays.asList(new String(bytes, StandardCharsets.UTF_8).split(sep + "#" + sep))); + if (commands.get(commands.size() - 1).isEmpty()) commands.remove(commands.size() - 1); // last entry is empty } catch (final IOException e) { log.error("Failed to read history of prompt commands from file " + path, e); return lines; @@ -3069,11 +3935,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); } @@ -3088,6 +3953,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); @@ -3152,6 +4018,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) { @@ -3249,6 +4117,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); @@ -3316,12 +4185,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 { @@ -3450,9 +4314,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); @@ -3471,7 +4334,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"); } /** @@ -3508,6 +4371,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); } @@ -3555,7 +4419,7 @@ private boolean isCompiled() { return language.isCompiledLanguage(); } - private final class EditableScriptInfo extends ScriptInfo + private static final class EditableScriptInfo extends ScriptInfo { private String script; @@ -3619,8 +4483,9 @@ private Reader evalScript(final String filename, Reader reader, } // map stdout and stderr to the UI - this.module.setOutputWriter(output); - this.module.setErrorWriter(errors); + final ScriptModule runModule = this.module; + runModule.setOutputWriter(output); + runModule.setErrorWriter(errors); // prepare the highlighter getEditorPane().getErrorHighlighter().setEnabled(!respectAutoImports); @@ -3629,15 +4494,24 @@ private Reader evalScript(final String filename, Reader reader, // execute the script try { - moduleService.run(module, true).get(); + moduleService.run(runModule, true).get(); } catch (final InterruptedException e) { error("Interrupted"); } catch (final ExecutionException e) { log.error(e); + getEditorPane().getErrorHighlighter().parse(e); } finally { getEditorPane().getErrorHighlighter().parse(); + // A one-off run must not keep its module: it holds the script engine and thus every + // variable the script created (e.g., large images), even after this window is closed. + // Objects the script itself keeps alive (threads, listeners, displays) are not + // affected. In REPL mode the state is kept on purpose + if (!incremental && this.module == runModule) { + this.module = null; + this.scriptInfo = null; + } } return reader; } @@ -3670,7 +4544,7 @@ public void keyPressed(final KeyEvent ke) { return; } final String text = prompt.getText(); - if (null == text || 0 == text.trim().length()) { + if (null == text || text.trim().isEmpty()) { ke.consume(); // avoid writing the line break return; } @@ -3801,21 +4675,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) { @@ -3854,6 +4727,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()); @@ -3861,22 +4735,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 -> { - 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
  • " - + "
"); - }); - menu.add(item); GuiUtils.addMenubarSeparator(menu, "Contextual Help:"); menu.add(openHelpWithoutFrames); openHelpWithoutFrames.setMnemonic(KeyEvent.VK_O); @@ -3890,14 +4748,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; } @@ -3971,11 +4827,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) { @@ -3990,237 +4841,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; - } - } - - 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; - } - - 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(); - final JPopupMenu popup = new JPopupMenu(); - tabbed.setComponentPopupMenu(popup); - final ButtonGroup bGroup = new ButtonGroup(); - for (final String pos : new String[] { "Top", "Left", "Bottom", "Right" }) { - final JMenuItem jcbmi = new JCheckBoxMenuItem("Place on " + 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); - } - 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; - } - } - - static class TextFieldWithPlaceholder extends JTextField { - - private static final long serialVersionUID = 1L; - private String placeholder; - - void setPlaceholder(final String placeholder) { - this.placeholder = placeholder; - update(getGraphics()); - } - - Font getPlaceholderFont() { - return getFont().deriveFont(Font.ITALIC); - } - - String getPlaceholder() { - return placeholder; - } - - @Override - protected void paintComponent(final java.awt.Graphics g) { - super.paintComponent(g); - if (getText().isEmpty()) { - final Graphics2D g2 = (Graphics2D) g.create(); - g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); - g2.setColor(getDisabledTextColor()); - g2.setFont(getPlaceholderFont()); - 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..2e555ad0 100644 --- a/src/main/java/org/scijava/ui/swing/script/TextEditorTab.java +++ b/src/main/java/org/scijava/ui/swing/script/TextEditorTab.java @@ -31,10 +31,12 @@ import java.awt.BorderLayout; import java.awt.Color; +import java.awt.Component; import java.awt.Dimension; -import java.awt.Font; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; +import java.awt.FontMetrics; +import java.awt.Graphics; +import java.awt.Insets; +import java.awt.Rectangle; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.dnd.DnDConstants; @@ -43,26 +45,20 @@ import java.awt.dnd.DropTargetDropEvent; import java.awt.dnd.DropTargetEvent; 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.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.DefaultCaret; +import javax.swing.text.Document; import javax.swing.text.JTextComponent; +import com.formdev.flatlaf.FlatClientProperties; +import com.formdev.flatlaf.util.UIScale; import org.fife.ui.rsyntaxtextarea.ErrorStrip; import org.fife.ui.rsyntaxtextarea.Style; import org.fife.ui.rsyntaxtextarea.Token; @@ -73,10 +69,7 @@ * * @author Jonathan Hale */ -public class TextEditorTab extends JSplitPane { - - private static final String DOWN_ARROW = "\u25BC"; - private static final String RIGHT_ARROW = "\u25B6"; +public class TextEditorTab extends GuiUtils.StickySplitPane { /** Which console stream(s) to display. */ private enum ConsoleView { @@ -99,10 +92,8 @@ 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,20 +101,27 @@ public String toString() { private boolean updatingViewChooser; private volatile boolean skipErrorMirroring; private Executer executer; - private final JButton runit, batchit, killit, switchSplit; + private final JButton runit; + private final JButton killit; private final JComboBox viewChooser; - private final JCheckBox incremental; + private boolean replOn; // the REPL is on (prompt shown) + private final JPanel promptPanel; + private final int promptDividerSize; // thickness of the divider above the prompt (hidden while the REPL is off) private final JSplitPane screenAndPromptSplit; private int screenAndPromptSplitDividerLocation; + /** Share of the tab given to the editor when the console is shown */ + private static final double EDITOR_SHARE = .7d; + private int bottomLastLocation = -1; // divider location while the bottom part was last shown private final TextEditor textEditor; private DropTarget dropTarget; + private Document mirroredErrorDoc; + private DocumentListener errorMirror; private DropTargetListener dropTargetListener; public TextEditorTab(final TextEditor textEditor) { super(JSplitPane.VERTICAL_SPLIT); super.setResizeWeight(350.0 / 430.0); - setOneTouchExpandable(true); this.textEditor = textEditor; editorPane = new EditorPane(); @@ -142,7 +140,7 @@ public void drop(final DropTargetDropEvent e) { if (!t.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) return; try { final Object o = t.getTransferData(DataFlavor.javaFileListFlavor); - if (!(o instanceof List)) return; + if (!(o instanceof List)) return; final List list = (List) o; if (list.isEmpty()) return; String path; @@ -176,208 +174,178 @@ 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); 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"); + mirroredErrorDoc = textEditor.getErrorScreen().getDocument(); + errorMirror = mirrorInto(combinedScreen, textEditor.getErrorScreen(), true); + + final JPanel bottom = new JPanel(new BorderLayout()); + final JToolBar bar = new GuiUtils.ToolBar(); + bar.setFloatable(false); + bar.setBorder(BorderFactory.createEmptyBorder(1, 2, 1, 2)); + + 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()); - bottom.add(runit, bc); + bar.add(runit); + + final JButton batchit = new JButton("Batch", Icons.fastForward(false)); + batchit.putClientProperty("JButton.buttonType", "borderless"); - bc.gridx = 1; - batchit = new JButton("Batch"); + batchit.setDisabledIcon(Icons.fastForward(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", Icons.stop(false)); + killit.setDisabledIcon(Icons.stop(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); + 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); + bar.add(Box.createHorizontalStrut(4)); + + final JButton clear = new JButton("Clear", Icons.trash(false)); + clear.setDisabledIcon(Icons.trash(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); - bottom.add(scroll, bc); + GuiUtils.flattenScrollBars(scroll); + bottom.add(bar, BorderLayout.PAGE_START); + bottom.add(scroll, BorderLayout.CENTER); prompt.setEnabled(false); 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)); - 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 -> { - 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"); - }); - 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; + // The REPL, when visible, never gets squeezed below its bar plus one row of text + final JPanel prompt_panel = new JPanel() { + + private static final long serialVersionUID = 1L; + + @Override + public Dimension getMinimumSize() { + int h = 0; + if (getLayout() instanceof BorderLayout) { + final Component bar = ((BorderLayout) getLayout()).getLayoutComponent(this, BorderLayout.NORTH); + if (bar != null) h += bar.getPreferredSize().height; + } + final Insets in = prompt.getInsets(); + return new Dimension(0, h + prompt.getFontMetrics(prompt.getFont()).getHeight() + in.top + in.bottom); } - textEditor.setIncremental(incremental.isSelected()); - prompt_title.setText(incremental.isSelected() ? // - "REPL: " + textEditor.getCurrentLanguage().getLanguageName() : ""); - prompt.setEnabled(incremental.isSelected()); - prompt_panel.setVisible(incremental.isSelected()); + }; + prompt_panel.setVisible(false); + promptPanel = prompt_panel; + prompt_panel.setLayout(new BorderLayout()); + + final JToolBar promptBar = new GuiUtils.ToolBar(); + promptBar.setFloatable(false); + promptBar.putClientProperty(FlatClientProperties.STYLE_CLASS, "small"); + promptBar.setBorder(null); + promptBar.setMargin(null); + prompt_panel.add(promptBar, BorderLayout.PAGE_START); + // Same scroll pane (and thus border) as the console + final JScrollPane promptScroll = new JScrollPane(prompt); + GuiUtils.flattenScrollBars(promptScroll); + prompt_panel.add(promptScroll, BorderLayout.CENTER); + final JLabel label = new JLabel(); + label.setForeground(GuiUtils.secondaryColor()); + label.setIcon(Icons.repl()); + 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 JButton statusHelp = GuiUtils.helpButton(null); + statusHelp.addActionListener(a -> { + final int shift = InputEvent.SHIFT_DOWN_MASK; + final int ctrl = InputEvent.CTRL_DOWN_MASK; + final String html = String.format("" // + + "\n" // + + "\n" // + + "\n" // + + "\n" // + + "\n" // + + "\n" // + + "
%sEvaluate code
%sAdd line break (also with Ctrl, Alt or Meta)
%s or %sPrevious entry in the history
%s or %sNext entry in the history
\n" // + + "

With Arrow Keys on, %s and %s also navigate the history. Combined
\n" // + + "with a modifier (e.g., %s) they move the caret within a multi-line prompt.

\n" // + + "", + 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) Key Bindings", html); }); + promptBar.add(statusHelp); + + // Compact bar: drop the vertical padding FlatLaf adds to toolbar buttons (margin 3 + spacing 1) + final String tight = "toolbar.margin: 0,3,0,3; toolbar.spacingInsets: 0,0,0,0"; + updownarrows.putClientProperty(FlatClientProperties.STYLE, tight); + updownarrows.setForeground(GuiUtils.secondaryColor()); // Must come after the style properties: applying them resets UIResource foregrounds + statusHelp.putClientProperty(FlatClientProperties.STYLE, tight); screenAndPromptSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT, bottom, prompt_panel); + screenAndPromptSplit.setResizeWeight(1d); // output takes the changes in height, the prompt keeps its size + // No divider: the prompt bar is the handle. Keep promptDividerSize at 0 so toggling the REPL + // never brings the divider back + 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 // 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()); 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); + 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 screenAndPromptSplit.setDividerLocation(1.0); setView(view); // sync the console and chooser with the initial view @@ -385,11 +353,68 @@ 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 (!isSettling() && 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(); + if (enable) { + fitPrompt(); + prompt.requestFocusInWindow(); + } + } + + /** 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() < 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 = collapsedLocation(); + setDividerLocation(bottomLastLocation > 50 && bottomLastLocation < max - 5 ? bottomLastLocation + : (int) (axisSize() * EDITOR_SHARE)); + } else { + setDividerLocation(1d); // all the way down + } + } + // Package-private JSplitPane getScreenAndPromptSplit() { return screenAndPromptSplit; @@ -397,6 +422,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 @@ -411,26 +437,91 @@ 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 + screenAndPromptSplitDividerLocation = 0; + 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(EDITOR_SHARE); + fitPrompt(); + } + + /** + * Keeps the REPL usable after the geometry of the console changed (layout switch, REPL turned + * on): the prompt always keeps at least one row of text and, in the side-by-side layout, + * where the console column spans the whole height, the output gets at most half of it + */ + void fitPrompt() { + SwingUtilities.invokeLater(() -> { + if (!replOn) return; + final int h = screenAndPromptSplit.getHeight(); + if (h <= 0) return; + final int current = screenAndPromptSplit.getDividerLocation(); + int loc = current; + if (!isLayoutBelow()) loc = Math.min(loc, h / 2); + loc = Math.min(loc, h - screenAndPromptSplit.getDividerSize() - promptPanel.getMinimumSize().height); + if (loc != current) screenAndPromptSplit.setDividerLocation(loc); + }); + } + + /** Restores the default layout: console below the editor, default proportions */ + void resetLayout() { + setOrientation(JSplitPane.VERTICAL_SPLIT); + bottomLastLocation = -1; + setDividerLocation(EDITOR_SHARE); + if (replOn) { + SwingUtilities.invokeLater(() -> screenAndPromptSplit.setDividerLocation(.5d)); + fitPrompt(); + } } // 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. */ 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); @@ -442,7 +533,7 @@ public void restore() { runit.setEnabled(true); killit.setEnabled(false); setExecutor(null); - if(incremental.isSelected()) + if (replOn) prompt.requestFocusInWindow(); }); } @@ -453,6 +544,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); } @@ -497,6 +589,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. @@ -517,10 +614,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) { @@ -541,20 +638,28 @@ public void removeUpdate(final DocumentEvent e) {} @Override public void changedUpdate(final DocumentEvent e) {} - }); + }; + source.getDocument().addDocumentListener(listener); + return listener; } public JTextArea getScreen() { switch (view) { - case ERRORS: - return textEditor.getErrorScreen(); - case BOTH: - return combinedScreen; - default: - return screen; + case ERRORS: return textEditor.getErrorScreen(); + case BOTH: return combinedScreen; + default: return screen; } } + void setConsoleWrap(final boolean wrap) { + screen.setLineWrap(wrap); + combinedScreen.setLineWrap(wrap); + } + + void setPromptWrap(final boolean wrap) { + prompt.setLineWrap(wrap); + } + public JTextArea getPrompt() { return prompt; } @@ -611,4 +716,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 + } + } + } } 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(); + } + } + +} 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/java/org/scijava/ui/swing/script/vim/VimHandler.java b/src/main/java/org/scijava/ui/swing/script/vim/VimHandler.java index 218ca738..8ef4db8e 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}. @@ -243,17 +244,10 @@ private String modeStatus() { 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 = ""; + 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; return modeText + (modeText.isEmpty() ? "" : " ") + printable(pending); @@ -2018,7 +2012,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() { 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..de260f1c --- /dev/null +++ b/src/main/resources/org/scijava/ui/swing/script/themes/scijava-dark.xml @@ -0,0 +1,78 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +