source: josm/trunk/src/org/openstreetmap/josm/actions/JosmAction.java @ 13925

Last change on this file since 13925 was 13925, checked in by Don-vip, 2 months ago

fix #13467 - use DataSelectionListener everywhere. Deprecate SelectionChangedListener

  • Property svn:eol-style set to native
File size: 20.2 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.actions;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.awt.GridBagLayout;
7import java.awt.event.KeyEvent;
8import java.util.Collection;
9import java.util.concurrent.CancellationException;
10import java.util.concurrent.ExecutionException;
11import java.util.concurrent.Future;
12
13import javax.swing.AbstractAction;
14import javax.swing.JOptionPane;
15import javax.swing.JPanel;
16
17import org.openstreetmap.josm.Main;
18import org.openstreetmap.josm.command.Command;
19import org.openstreetmap.josm.data.osm.DataSelectionListener;
20import org.openstreetmap.josm.data.osm.DataSet;
21import org.openstreetmap.josm.data.osm.OsmPrimitive;
22import org.openstreetmap.josm.data.osm.OsmUtils;
23import org.openstreetmap.josm.data.osm.event.SelectionEventManager;
24import org.openstreetmap.josm.gui.ConditionalOptionPaneUtil;
25import org.openstreetmap.josm.gui.MainApplication;
26import org.openstreetmap.josm.gui.layer.LayerManager.LayerAddEvent;
27import org.openstreetmap.josm.gui.layer.LayerManager.LayerChangeListener;
28import org.openstreetmap.josm.gui.layer.LayerManager.LayerOrderChangeEvent;
29import org.openstreetmap.josm.gui.layer.LayerManager.LayerRemoveEvent;
30import org.openstreetmap.josm.gui.layer.MainLayerManager;
31import org.openstreetmap.josm.gui.layer.MainLayerManager.ActiveLayerChangeEvent;
32import org.openstreetmap.josm.gui.layer.MainLayerManager.ActiveLayerChangeListener;
33import org.openstreetmap.josm.gui.progress.swing.PleaseWaitProgressMonitor;
34import org.openstreetmap.josm.gui.widgets.JMultilineLabel;
35import org.openstreetmap.josm.tools.Destroyable;
36import org.openstreetmap.josm.tools.ImageProvider;
37import org.openstreetmap.josm.tools.ImageResource;
38import org.openstreetmap.josm.tools.Logging;
39import org.openstreetmap.josm.tools.Shortcut;
40
41/**
42 * Base class helper for all Actions in JOSM. Just to make the life easier.
43 *
44 * This action allows you to set up an icon, a tooltip text, a globally registered shortcut, register it in the main toolbar and set up
45 * layer/selection listeners that call {@link #updateEnabledState()} whenever the global context is changed.
46 *
47 * A JosmAction can register a {@link LayerChangeListener} and a {@link DataSelectionListener}. Upon
48 * a layer change event or a selection change event it invokes {@link #updateEnabledState()}.
49 * Subclasses can override {@link #updateEnabledState()} in order to update the {@link #isEnabled()}-state
50 * of a JosmAction depending on the {@link #getLayerManager()} state.
51 *
52 * destroy() from interface Destroyable is called e.g. for MapModes, when the last layer has
53 * been removed and so the mapframe will be destroyed. For other JosmActions, destroy() may never
54 * be called (currently).
55 *
56 * @author imi
57 */
58public abstract class JosmAction extends AbstractAction implements Destroyable {
59
60    protected transient Shortcut sc;
61    private transient LayerChangeAdapter layerChangeAdapter;
62    private transient ActiveLayerChangeAdapter activeLayerChangeAdapter;
63    private transient SelectionChangeAdapter selectionChangeAdapter;
64
65    /**
66     * Constructs a {@code JosmAction}.
67     *
68     * @param name the action's text as displayed on the menu (if it is added to a menu)
69     * @param icon the icon to use
70     * @param tooltip  a longer description of the action that will be displayed in the tooltip. Please note
71     *           that html is not supported for menu actions on some platforms.
72     * @param shortcut a ready-created shortcut object or null if you don't want a shortcut. But you always
73     *            do want a shortcut, remember you can always register it with group=none, so you
74     *            won't be assigned a shortcut unless the user configures one. If you pass null here,
75     *            the user CANNOT configure a shortcut for your action.
76     * @param registerInToolbar register this action for the toolbar preferences?
77     * @param toolbarId identifier for the toolbar preferences. The iconName is used, if this parameter is null
78     * @param installAdapters false, if you don't want to install layer changed and selection changed adapters
79     */
80    public JosmAction(String name, ImageProvider icon, String tooltip, Shortcut shortcut, boolean registerInToolbar,
81            String toolbarId, boolean installAdapters) {
82        super(name);
83        if (icon != null) {
84            ImageResource resource = icon.getResource();
85            if (resource != null) {
86                resource.attachImageIcon(this, true);
87            }
88        }
89        setHelpId();
90        sc = shortcut;
91        if (sc != null && !sc.isAutomatic()) {
92            MainApplication.registerActionShortcut(this, sc);
93        }
94        setTooltip(tooltip);
95        if (getValue("toolbar") == null) {
96            putValue("toolbar", toolbarId);
97        }
98        if (registerInToolbar && MainApplication.getToolbar() != null) {
99            MainApplication.getToolbar().register(this);
100        }
101        if (installAdapters) {
102            installAdapters();
103        }
104    }
105
106    /**
107     * The new super for all actions.
108     *
109     * Use this super constructor to setup your action.
110     *
111     * @param name the action's text as displayed on the menu (if it is added to a menu)
112     * @param iconName the filename of the icon to use
113     * @param tooltip  a longer description of the action that will be displayed in the tooltip. Please note
114     *           that html is not supported for menu actions on some platforms.
115     * @param shortcut a ready-created shortcut object or null if you don't want a shortcut. But you always
116     *            do want a shortcut, remember you can always register it with group=none, so you
117     *            won't be assigned a shortcut unless the user configures one. If you pass null here,
118     *            the user CANNOT configure a shortcut for your action.
119     * @param registerInToolbar register this action for the toolbar preferences?
120     * @param toolbarId identifier for the toolbar preferences. The iconName is used, if this parameter is null
121     * @param installAdapters false, if you don't want to install layer changed and selection changed adapters
122     */
123    public JosmAction(String name, String iconName, String tooltip, Shortcut shortcut, boolean registerInToolbar,
124            String toolbarId, boolean installAdapters) {
125        this(name, iconName == null ? null : new ImageProvider(iconName).setOptional(true), tooltip, shortcut, registerInToolbar,
126                toolbarId == null ? iconName : toolbarId, installAdapters);
127    }
128
129    /**
130     * Constructs a new {@code JosmAction}.
131     *
132     * Use this super constructor to setup your action.
133     *
134     * @param name the action's text as displayed on the menu (if it is added to a menu)
135     * @param iconName the filename of the icon to use
136     * @param tooltip  a longer description of the action that will be displayed in the tooltip. Please note
137     *           that html is not supported for menu actions on some platforms.
138     * @param shortcut a ready-created shortcut object or null if you don't want a shortcut. But you always
139     *            do want a shortcut, remember you can always register it with group=none, so you
140     *            won't be assigned a shortcut unless the user configures one. If you pass null here,
141     *            the user CANNOT configure a shortcut for your action.
142     * @param registerInToolbar register this action for the toolbar preferences?
143     * @param installAdapters false, if you don't want to install layer changed and selection changed adapters
144     */
145    public JosmAction(String name, String iconName, String tooltip, Shortcut shortcut, boolean registerInToolbar, boolean installAdapters) {
146        this(name, iconName, tooltip, shortcut, registerInToolbar, null, installAdapters);
147    }
148
149    /**
150     * Constructs a new {@code JosmAction}.
151     *
152     * Use this super constructor to setup your action.
153     *
154     * @param name the action's text as displayed on the menu (if it is added to a menu)
155     * @param iconName the filename of the icon to use
156     * @param tooltip  a longer description of the action that will be displayed in the tooltip. Please note
157     *           that html is not supported for menu actions on some platforms.
158     * @param shortcut a ready-created shortcut object or null if you don't want a shortcut. But you always
159     *            do want a shortcut, remember you can always register it with group=none, so you
160     *            won't be assigned a shortcut unless the user configures one. If you pass null here,
161     *            the user CANNOT configure a shortcut for your action.
162     * @param registerInToolbar register this action for the toolbar preferences?
163     */
164    public JosmAction(String name, String iconName, String tooltip, Shortcut shortcut, boolean registerInToolbar) {
165        this(name, iconName, tooltip, shortcut, registerInToolbar, null, true);
166    }
167
168    /**
169     * Constructs a new {@code JosmAction}.
170     */
171    public JosmAction() {
172        this(true);
173    }
174
175    /**
176     * Constructs a new {@code JosmAction}.
177     *
178     * @param installAdapters false, if you don't want to install layer changed and selection changed adapters
179     */
180    public JosmAction(boolean installAdapters) {
181        setHelpId();
182        if (installAdapters) {
183            installAdapters();
184        }
185    }
186
187    /**
188     * Installs the listeners to this action.
189     * <p>
190     * This should either never be called or only called in the constructor of this action.
191     * <p>
192     * All registered adapters should be removed in {@link #destroy()}
193     */
194    protected void installAdapters() {
195        // make this action listen to layer change and selection change events
196        if (listenToLayerChange()) {
197            layerChangeAdapter = new LayerChangeAdapter();
198            activeLayerChangeAdapter = new ActiveLayerChangeAdapter();
199            getLayerManager().addLayerChangeListener(layerChangeAdapter);
200            getLayerManager().addActiveLayerChangeListener(activeLayerChangeAdapter);
201        }
202        if (listenToSelectionChange()) {
203            selectionChangeAdapter = new SelectionChangeAdapter();
204            SelectionEventManager.getInstance().addSelectionListenerForEdt(selectionChangeAdapter);
205        }
206        initEnabledState();
207    }
208
209    /**
210     * Overwrite this if {@link #updateEnabledState()} should be called when the active / availabe layers change. Default is true.
211     * @return <code>true</code> if a {@link LayerChangeListener} and a {@link ActiveLayerChangeListener} should be registered.
212     * @since 10353
213     */
214    protected boolean listenToLayerChange() {
215        return true;
216    }
217
218    /**
219     * Overwrite this if {@link #updateEnabledState()} should be called when the selection changed. Default is true.
220     * @return <code>true</code> if a {@link DataSelectionListener} should be registered.
221     * @since 10353
222     */
223    protected boolean listenToSelectionChange() {
224        return true;
225    }
226
227    @Override
228    public void destroy() {
229        if (sc != null && !sc.isAutomatic()) {
230            MainApplication.unregisterActionShortcut(this);
231        }
232        if (layerChangeAdapter != null) {
233            getLayerManager().removeLayerChangeListener(layerChangeAdapter);
234            getLayerManager().removeActiveLayerChangeListener(activeLayerChangeAdapter);
235        }
236        if (selectionChangeAdapter != null) {
237            SelectionEventManager.getInstance().removeSelectionListener(selectionChangeAdapter);
238        }
239    }
240
241    private void setHelpId() {
242        String helpId = "Action/"+getClass().getName().substring(getClass().getName().lastIndexOf('.')+1);
243        if (helpId.endsWith("Action")) {
244            helpId = helpId.substring(0, helpId.length()-6);
245        }
246        putValue("help", helpId);
247    }
248
249    /**
250     * Returns the shortcut for this action.
251     * @return the shortcut for this action, or "No shortcut" if none is defined
252     */
253    public Shortcut getShortcut() {
254        if (sc == null) {
255            sc = Shortcut.registerShortcut("core:none", tr("No Shortcut"), KeyEvent.CHAR_UNDEFINED, Shortcut.NONE);
256            // as this shortcut is shared by all action that don't want to have a shortcut,
257            // we shouldn't allow the user to change it...
258            // this is handled by special name "core:none"
259        }
260        return sc;
261    }
262
263    /**
264     * Sets the tooltip text of this action.
265     * @param tooltip The text to display in tooltip. Can be {@code null}
266     */
267    public final void setTooltip(String tooltip) {
268        if (tooltip != null) {
269            putValue(SHORT_DESCRIPTION, Main.platform.makeTooltip(tooltip, sc));
270        }
271    }
272
273    /**
274     * Gets the layer manager used for this action. Defaults to the main layer manager but you can overwrite this.
275     * <p>
276     * The layer manager must be available when {@link #installAdapters()} is called and must not change.
277     *
278     * @return The layer manager.
279     * @since 10353
280     */
281    public MainLayerManager getLayerManager() {
282        return MainApplication.getLayerManager();
283    }
284
285    protected static void waitFuture(final Future<?> future, final PleaseWaitProgressMonitor monitor) {
286        MainApplication.worker.submit(() -> {
287                        try {
288                            future.get();
289                        } catch (InterruptedException | ExecutionException | CancellationException e) {
290                            Logging.error(e);
291                            return;
292                        }
293                        monitor.close();
294                    });
295    }
296
297    /**
298     * Override in subclasses to init the enabled state of an action when it is
299     * created. Default behaviour is to call {@link #updateEnabledState()}
300     *
301     * @see #updateEnabledState()
302     * @see #updateEnabledState(Collection)
303     */
304    protected void initEnabledState() {
305        updateEnabledState();
306    }
307
308    /**
309     * Override in subclasses to update the enabled state of the action when
310     * something in the JOSM state changes, i.e. when a layer is removed or added.
311     *
312     * See {@link #updateEnabledState(Collection)} to respond to changes in the collection
313     * of selected primitives.
314     *
315     * Default behavior is empty.
316     *
317     * @see #updateEnabledState(Collection)
318     * @see #initEnabledState()
319     * @see #listenToLayerChange()
320     */
321    protected void updateEnabledState() {
322    }
323
324    /**
325     * Override in subclasses to update the enabled state of the action if the
326     * collection of selected primitives changes. This method is called with the
327     * new selection.
328     *
329     * @param selection the collection of selected primitives; may be empty, but not null
330     *
331     * @see #updateEnabledState()
332     * @see #initEnabledState()
333     * @see #listenToSelectionChange()
334     */
335    protected void updateEnabledState(Collection<? extends OsmPrimitive> selection) {
336    }
337
338    /**
339     * Updates enabled state according to primitives currently selected in edit data set, if any.
340     * Can be called in {@link #updateEnabledState()} implementations.
341     * @see #updateEnabledStateOnCurrentSelection(boolean)
342     * @since 10409
343     */
344    protected final void updateEnabledStateOnCurrentSelection() {
345        updateEnabledStateOnCurrentSelection(false);
346    }
347
348    /**
349     * Updates enabled state according to primitives currently selected in active data set, if any.
350     * Can be called in {@link #updateEnabledState()} implementations.
351     * @param allowReadOnly if {@code true}, read-only data sets are considered
352     * @since 13434
353     */
354    protected final void updateEnabledStateOnCurrentSelection(boolean allowReadOnly) {
355        DataSet ds = getLayerManager().getActiveDataSet();
356        if (ds != null && (allowReadOnly || !ds.isLocked())) {
357            updateEnabledState(ds.getSelected());
358        } else {
359            setEnabled(false);
360        }
361    }
362
363    /**
364     * Updates enabled state according to selected primitives, if any.
365     * Enables action if the collection is not empty and references primitives in a modifiable data layer.
366     * Can be called in {@link #updateEnabledState(Collection)} implementations.
367     * @param selection the collection of selected primitives
368     * @since 13434
369     */
370    protected final void updateEnabledStateOnModifiableSelection(Collection<? extends OsmPrimitive> selection) {
371        setEnabled(OsmUtils.isOsmCollectionEditable(selection));
372    }
373
374    /**
375     * Adapter for layer change events. Runs updateEnabledState() whenever the active layer changed.
376     */
377    protected class LayerChangeAdapter implements LayerChangeListener {
378        @Override
379        public void layerAdded(LayerAddEvent e) {
380            updateEnabledState();
381        }
382
383        @Override
384        public void layerRemoving(LayerRemoveEvent e) {
385            updateEnabledState();
386        }
387
388        @Override
389        public void layerOrderChanged(LayerOrderChangeEvent e) {
390            updateEnabledState();
391        }
392
393        @Override
394        public String toString() {
395            return "LayerChangeAdapter [" + JosmAction.this + ']';
396        }
397    }
398
399    /**
400     * Adapter for layer change events. Runs updateEnabledState() whenever the active layer changed.
401     */
402    protected class ActiveLayerChangeAdapter implements ActiveLayerChangeListener {
403        @Override
404        public void activeOrEditLayerChanged(ActiveLayerChangeEvent e) {
405            updateEnabledState();
406        }
407
408        @Override
409        public String toString() {
410            return "ActiveLayerChangeAdapter [" + JosmAction.this + ']';
411        }
412    }
413
414    /**
415     * Adapter for selection change events. Runs updateEnabledState() whenever the selection changed.
416     */
417    protected class SelectionChangeAdapter implements DataSelectionListener {
418        @Override
419        public void selectionChanged(SelectionChangeEvent event) {
420            updateEnabledState(event.getSelection());
421        }
422
423        @Override
424        public String toString() {
425            return "SelectionChangeAdapter [" + JosmAction.this + ']';
426        }
427    }
428
429    /**
430     * Check whether user is about to operate on data outside of the download area.
431     * Request confirmation if he is.
432     *
433     * @param operation the operation name which is used for setting some preferences
434     * @param dialogTitle the title of the dialog being displayed
435     * @param outsideDialogMessage the message text to be displayed when data is outside of the download area
436     * @param incompleteDialogMessage the message text to be displayed when data is incomplete
437     * @param primitives the primitives to operate on
438     * @param ignore {@code null} or a primitive to be ignored
439     * @return true, if operating on outlying primitives is OK; false, otherwise
440     * @since 12749 (moved from Command)
441     */
442    public static boolean checkAndConfirmOutlyingOperation(String operation,
443            String dialogTitle, String outsideDialogMessage, String incompleteDialogMessage,
444            Collection<? extends OsmPrimitive> primitives,
445            Collection<? extends OsmPrimitive> ignore) {
446        int checkRes = Command.checkOutlyingOrIncompleteOperation(primitives, ignore);
447        if ((checkRes & Command.IS_OUTSIDE) != 0) {
448            JPanel msg = new JPanel(new GridBagLayout());
449            msg.add(new JMultilineLabel("<html>" + outsideDialogMessage + "</html>"));
450            boolean answer = ConditionalOptionPaneUtil.showConfirmationDialog(
451                    operation + "_outside_nodes",
452                    Main.parent,
453                    msg,
454                    dialogTitle,
455                    JOptionPane.YES_NO_OPTION,
456                    JOptionPane.QUESTION_MESSAGE,
457                    JOptionPane.YES_OPTION);
458            if (!answer)
459                return false;
460        }
461        if ((checkRes & Command.IS_INCOMPLETE) != 0) {
462            JPanel msg = new JPanel(new GridBagLayout());
463            msg.add(new JMultilineLabel("<html>" + incompleteDialogMessage + "</html>"));
464            boolean answer = ConditionalOptionPaneUtil.showConfirmationDialog(
465                    operation + "_incomplete",
466                    Main.parent,
467                    msg,
468                    dialogTitle,
469                    JOptionPane.YES_NO_OPTION,
470                    JOptionPane.QUESTION_MESSAGE,
471                    JOptionPane.YES_OPTION);
472            if (!answer)
473                return false;
474        }
475        return true;
476    }
477}
Note: See TracBrowser for help on using the repository browser.