001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui.widgets;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005
006import java.awt.GraphicsEnvironment;
007import java.awt.event.ActionEvent;
008import java.awt.event.KeyEvent;
009import java.beans.PropertyChangeListener;
010import java.util.Optional;
011
012import javax.swing.AbstractAction;
013import javax.swing.Action;
014import javax.swing.ImageIcon;
015import javax.swing.JMenuItem;
016import javax.swing.JPopupMenu;
017import javax.swing.KeyStroke;
018import javax.swing.event.UndoableEditListener;
019import javax.swing.text.DefaultEditorKit;
020import javax.swing.text.JTextComponent;
021import javax.swing.undo.CannotRedoException;
022import javax.swing.undo.CannotUndoException;
023import javax.swing.undo.UndoManager;
024
025import org.openstreetmap.josm.spi.preferences.Config;
026import org.openstreetmap.josm.tools.ImageProvider;
027import org.openstreetmap.josm.tools.Logging;
028import org.openstreetmap.josm.tools.PlatformManager;
029import org.openstreetmap.josm.tools.Shortcut;
030
031/**
032 * A popup menu designed for text components. It displays the following actions:
033 * <ul>
034 * <li>Undo</li>
035 * <li>Redo</li>
036 * <li>Cut</li>
037 * <li>Copy</li>
038 * <li>Paste</li>
039 * <li>Delete</li>
040 * <li>Select All</li>
041 * </ul>
042 * @since 5886
043 */
044public class TextContextualPopupMenu extends JPopupMenu {
045
046    private static final String EDITABLE = "editable";
047
048    protected JTextComponent component;
049    protected boolean undoRedo;
050    protected final UndoAction undoAction = new UndoAction();
051    protected final RedoAction redoAction = new RedoAction();
052    protected final UndoManager undo = new UndoManager();
053
054    protected final transient UndoableEditListener undoEditListener = e -> {
055        undo.addEdit(e.getEdit());
056        updateUndoRedoState();
057    };
058
059    protected final transient PropertyChangeListener propertyChangeListener = evt -> {
060        if (EDITABLE.equals(evt.getPropertyName())) {
061            removeAll();
062            addMenuEntries();
063        }
064    };
065
066    /**
067     * Creates a new {@link TextContextualPopupMenu}.
068     */
069    protected TextContextualPopupMenu() {
070        // Restricts visibility
071    }
072
073    private void updateUndoRedoState() {
074        undoAction.updateUndoState();
075        redoAction.updateRedoState();
076    }
077
078    /**
079     * Attaches this contextual menu to the given text component.
080     * A menu can only be attached to a single component.
081     * @param component The text component that will display the menu and handle its actions.
082     * @param undoRedo {@code true} if undo/redo must be supported
083     * @return {@code this}
084     * @see #detach()
085     */
086    protected TextContextualPopupMenu attach(JTextComponent component, boolean undoRedo) {
087        if (component != null && !isAttached()) {
088            this.component = component;
089            if (undoRedo && component.isEditable()) {
090                enableUndoRedo();
091            }
092            addMenuEntries();
093            component.addPropertyChangeListener(EDITABLE, propertyChangeListener);
094        }
095        return this;
096    }
097
098    private void enableUndoRedo() {
099        if (!undoRedo) {
100            component.getDocument().addUndoableEditListener(undoEditListener);
101            if (!GraphicsEnvironment.isHeadless()) {
102                final Optional<Shortcut> undoShortcut = Shortcut.listAll().stream()
103                        .filter(shortcut -> "system:undo".equals(shortcut.getShortText())).findFirst();
104                final Optional<Shortcut> redoShortcut = Shortcut.listAll().stream()
105                        .filter(shortcut -> "system:redo".equals(shortcut.getShortText())).findFirst();
106                if (undoShortcut.isPresent()) {
107                    component.getInputMap().put(undoShortcut.get().getKeyStroke(), undoAction);
108                } else {
109                    component.getInputMap().put(
110                            KeyStroke.getKeyStroke(KeyEvent.VK_Z, PlatformManager.getPlatform().getMenuShortcutKeyMaskEx()), undoAction);
111                }
112                if (redoShortcut.isPresent()) {
113                    component.getInputMap().put(redoShortcut.get().getKeyStroke(), redoAction);
114                } else {
115                    component.getInputMap().put(
116                            KeyStroke.getKeyStroke(KeyEvent.VK_Y, PlatformManager.getPlatform().getMenuShortcutKeyMaskEx()), redoAction);
117                }
118            }
119            undoRedo = true;
120        }
121    }
122
123    private void disableUndoRedo() {
124        if (undoRedo) {
125            if (!GraphicsEnvironment.isHeadless()) {
126                component.getInputMap().remove(
127                        KeyStroke.getKeyStroke(KeyEvent.VK_Z, PlatformManager.getPlatform().getMenuShortcutKeyMaskEx()));
128                component.getInputMap().remove(
129                        KeyStroke.getKeyStroke(KeyEvent.VK_Y, PlatformManager.getPlatform().getMenuShortcutKeyMaskEx()));
130            }
131            component.getDocument().removeUndoableEditListener(undoEditListener);
132            undoRedo = false;
133        }
134    }
135
136    private void addMenuEntries() {
137        if (component.isEditable()) {
138            if (undoRedo) {
139                addMenuEntry(new JMenuItem(undoAction), "undo");
140                addMenuEntry(new JMenuItem(redoAction), "redo");
141                addSeparator();
142            }
143            addMenuEntry(component, tr("Cut"), DefaultEditorKit.cutAction, /* ICON */ "cut");
144        }
145        addMenuEntry(component, tr("Copy"), DefaultEditorKit.copyAction, /* ICON */ "copy");
146        if (component.isEditable()) {
147            addMenuEntry(component, tr("Paste"), DefaultEditorKit.pasteAction, /* ICON */ "paste");
148            addMenuEntry(component, tr("Delete"), DefaultEditorKit.deleteNextCharAction, /* ICON */ "dialogs/delete");
149        }
150        addSeparator();
151        addMenuEntry(component, tr("Select All"), DefaultEditorKit.selectAllAction, /* ICON */ "dialogs/select");
152    }
153
154    /**
155     * Detaches this contextual menu from its text component.
156     * @return {@code this}
157     * @see #attach(JTextComponent, boolean)
158     */
159    protected TextContextualPopupMenu detach() {
160        if (isAttached()) {
161            component.removePropertyChangeListener(EDITABLE, propertyChangeListener);
162            removeAll();
163            if (undoRedo) {
164                disableUndoRedo();
165            }
166            component = null;
167        }
168        return this;
169    }
170
171    /**
172     * Creates a new {@link TextContextualPopupMenu} and enables it for the given text component.
173     * @param component The component that will display the menu and handle its actions.
174     * @param undoRedo Enables or not Undo/Redo feature. Not recommended for table cell editors, unless each cell provides its own editor
175     * @return The {@link PopupMenuLauncher} responsible of displaying the popup menu.
176     *         Call {@link #disableMenuFor} with this object if you want to disable the menu later.
177     * @see #disableMenuFor
178     */
179    public static PopupMenuLauncher enableMenuFor(JTextComponent component, boolean undoRedo) {
180        PopupMenuLauncher launcher = new PopupMenuLauncher(new TextContextualPopupMenu().attach(component, undoRedo), true);
181        component.addMouseListener(launcher);
182        return launcher;
183    }
184
185    /**
186     * Disables the {@link TextContextualPopupMenu} attached to the given popup menu launcher and text component.
187     * @param component The component that currently displays the menu and handles its actions.
188     * @param launcher The {@link PopupMenuLauncher} obtained via {@link #enableMenuFor}.
189     * @see #enableMenuFor
190     */
191    public static void disableMenuFor(JTextComponent component, PopupMenuLauncher launcher) {
192        if (launcher.getMenu() instanceof TextContextualPopupMenu) {
193            ((TextContextualPopupMenu) launcher.getMenu()).detach();
194            component.removeMouseListener(launcher);
195        }
196    }
197
198    /**
199     * Empties the internal undo manager.
200     * @since 14977
201     */
202    public void discardAllUndoableEdits() {
203        undo.discardAllEdits();
204        updateUndoRedoState();
205    }
206
207    /**
208     * Determines if this popup is currently attached to a component.
209     * @return {@code true} if this popup is currently attached to a component, {@code false} otherwise.
210     */
211    public final boolean isAttached() {
212        return component != null;
213    }
214
215    protected void addMenuEntry(JTextComponent component, String label, String actionName, String iconName) {
216        Action action = component.getActionMap().get(actionName);
217        if (action != null) {
218            JMenuItem mi = new JMenuItem(action);
219            mi.setText(label);
220            addMenuEntry(mi, iconName);
221        }
222    }
223
224    protected void addMenuEntry(JMenuItem mi, String iconName) {
225        if (iconName != null && Config.getPref().getBoolean("text.popupmenu.useicons", true)) {
226            ImageIcon icon = new ImageProvider(iconName).setSize(ImageProvider.ImageSizes.SMALLICON).get();
227            mi.setIcon(icon);
228        }
229        add(mi);
230    }
231
232    protected class UndoAction extends AbstractAction {
233
234        /**
235         * Constructs a new {@code UndoAction}.
236         */
237        public UndoAction() {
238            super(tr("Undo"));
239            setEnabled(false);
240        }
241
242        @Override
243        public void actionPerformed(ActionEvent e) {
244            try {
245                undo.undo();
246            } catch (CannotUndoException ex) {
247                Logging.trace(ex);
248            } finally {
249                updateUndoState();
250                redoAction.updateRedoState();
251            }
252        }
253
254        public void updateUndoState() {
255            if (undo.canUndo()) {
256                setEnabled(true);
257                putValue(Action.NAME, undo.getUndoPresentationName());
258            } else {
259                setEnabled(false);
260                putValue(Action.NAME, tr("Undo"));
261            }
262        }
263    }
264
265    protected class RedoAction extends AbstractAction {
266
267        /**
268         * Constructs a new {@code RedoAction}.
269         */
270        public RedoAction() {
271            super(tr("Redo"));
272            new ImageProvider("redo").getResource().attachImageIcon(this);
273            setEnabled(false);
274        }
275
276        @Override
277        public void actionPerformed(ActionEvent e) {
278            try {
279                undo.redo();
280            } catch (CannotRedoException ex) {
281                Logging.trace(ex);
282            } finally {
283                updateRedoState();
284                undoAction.updateUndoState();
285            }
286        }
287
288        public void updateRedoState() {
289            if (undo.canRedo()) {
290                setEnabled(true);
291                putValue(Action.NAME, undo.getRedoPresentationName());
292            } else {
293                setEnabled(false);
294                putValue(Action.NAME, tr("Redo"));
295            }
296        }
297    }
298}