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, 6 years ago

fix #13467 - use DataSelectionListener everywhere. Deprecate SelectionChangedListener

  • Property svn:eol-style set to native
File size: 20.2 KB
RevLine 
[6380]1// License: GPL. For details, see LICENSE file.
[30]2package org.openstreetmap.josm.actions;
3
[1182]4import static org.openstreetmap.josm.tools.I18n.tr;
5
[12749]6import java.awt.GridBagLayout;
[4982]7import java.awt.event.KeyEvent;
[1820]8import java.util.Collection;
[10212]9import java.util.concurrent.CancellationException;
10import java.util.concurrent.ExecutionException;
[10074]11import java.util.concurrent.Future;
[1820]12
[30]13import javax.swing.AbstractAction;
[12749]14import javax.swing.JOptionPane;
15import javax.swing.JPanel;
[30]16
[43]17import org.openstreetmap.josm.Main;
[12749]18import org.openstreetmap.josm.command.Command;
[13925]19import org.openstreetmap.josm.data.osm.DataSelectionListener;
[558]20import org.openstreetmap.josm.data.osm.DataSet;
[1820]21import org.openstreetmap.josm.data.osm.OsmPrimitive;
[13611]22import org.openstreetmap.josm.data.osm.OsmUtils;
[12051]23import org.openstreetmap.josm.data.osm.event.SelectionEventManager;
[12749]24import org.openstreetmap.josm.gui.ConditionalOptionPaneUtil;
[12634]25import org.openstreetmap.josm.gui.MainApplication;
[10353]26import org.openstreetmap.josm.gui.layer.LayerManager.LayerAddEvent;
[10345]27import org.openstreetmap.josm.gui.layer.LayerManager.LayerChangeListener;
[10353]28import org.openstreetmap.josm.gui.layer.LayerManager.LayerOrderChangeEvent;
29import org.openstreetmap.josm.gui.layer.LayerManager.LayerRemoveEvent;
30import org.openstreetmap.josm.gui.layer.MainLayerManager;
[10345]31import org.openstreetmap.josm.gui.layer.MainLayerManager.ActiveLayerChangeEvent;
32import org.openstreetmap.josm.gui.layer.MainLayerManager.ActiveLayerChangeListener;
[12675]33import org.openstreetmap.josm.gui.progress.swing.PleaseWaitProgressMonitor;
[12749]34import org.openstreetmap.josm.gui.widgets.JMultilineLabel;
[208]35import org.openstreetmap.josm.tools.Destroyable;
[71]36import org.openstreetmap.josm.tools.ImageProvider;
[13647]37import org.openstreetmap.josm.tools.ImageResource;
[12620]38import org.openstreetmap.josm.tools.Logging;
[1084]39import org.openstreetmap.josm.tools.Shortcut;
[30]40
41/**
42 * Base class helper for all Actions in JOSM. Just to make the life easier.
[2305]43 *
[10353]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 *
[13925]47 * A JosmAction can register a {@link LayerChangeListener} and a {@link DataSelectionListener}. Upon
[5275]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
[10972]50 * of a JosmAction depending on the {@link #getLayerManager()} state.
[2305]51 *
[208]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).
[1023]55 *
[30]56 * @author imi
57 */
[6889]58public abstract class JosmAction extends AbstractAction implements Destroyable {
[30]59
[8308]60 protected transient Shortcut sc;
61 private transient LayerChangeAdapter layerChangeAdapter;
[10353]62 private transient ActiveLayerChangeAdapter activeLayerChangeAdapter;
[8308]63 private transient SelectionChangeAdapter selectionChangeAdapter;
[208]64
[6814]65 /**
[5110]66 * Constructs a {@code JosmAction}.
[1169]67 *
[1935]68 * @param name the action's text as displayed on the menu (if it is added to a menu)
[5110]69 * @param icon the icon to use
[1935]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,
[1169]75 * the user CANNOT configure a shortcut for your action.
[5110]76 * @param registerInToolbar register this action for the toolbar preferences?
[4733]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
[7693]79 */
[8509]80 public JosmAction(String name, ImageProvider icon, String tooltip, Shortcut shortcut, boolean registerInToolbar,
81 String toolbarId, boolean installAdapters) {
[7693]82 super(name);
[13647]83 if (icon != null) {
84 ImageResource resource = icon.getResource();
85 if (resource != null) {
86 resource.attachImageIcon(this, true);
87 }
88 }
[7693]89 setHelpId();
90 sc = shortcut;
[12320]91 if (sc != null && !sc.isAutomatic()) {
[12639]92 MainApplication.registerActionShortcut(this, sc);
[7693]93 }
94 setTooltip(tooltip);
95 if (getValue("toolbar") == null) {
96 putValue("toolbar", toolbarId);
97 }
[12637]98 if (registerInToolbar && MainApplication.getToolbar() != null) {
99 MainApplication.getToolbar().register(this);
[7693]100 }
101 if (installAdapters) {
102 installAdapters();
103 }
104 }
105
106 /**
[5110]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.
[5526]119 * @param registerInToolbar register this action for the toolbar preferences?
[5110]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 */
[8509]123 public JosmAction(String name, String iconName, String tooltip, Shortcut shortcut, boolean registerInToolbar,
124 String toolbarId, boolean installAdapters) {
[13647]125 this(name, iconName == null ? null : new ImageProvider(iconName).setOptional(true), tooltip, shortcut, registerInToolbar,
[5110]126 toolbarId == null ? iconName : toolbarId, installAdapters);
127 }
128
[6814]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 */
[5526]145 public JosmAction(String name, String iconName, String tooltip, Shortcut shortcut, boolean registerInToolbar, boolean installAdapters) {
146 this(name, iconName, tooltip, shortcut, registerInToolbar, null, installAdapters);
[4733]147 }
148
[6814]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 */
[5526]164 public JosmAction(String name, String iconName, String tooltip, Shortcut shortcut, boolean registerInToolbar) {
165 this(name, iconName, tooltip, shortcut, registerInToolbar, null, true);
[4733]166 }
167
[6814]168 /**
169 * Constructs a new {@code JosmAction}.
170 */
[1820]171 public JosmAction() {
[3327]172 this(true);
173 }
174
[6814]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 */
[3327]180 public JosmAction(boolean installAdapters) {
[1820]181 setHelpId();
[3327]182 if (installAdapters) {
183 installAdapters();
184 }
[1820]185 }
[10409]186
[10353]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();
[13925]204 SelectionEventManager.getInstance().addSelectionListenerForEdt(selectionChangeAdapter);
[10353]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.
[10354]212 * @since 10353
[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.
[13925]220 * @return <code>true</code> if a {@link DataSelectionListener} should be registered.
[10354]221 * @since 10353
[10353]222 */
223 protected boolean listenToSelectionChange() {
224 return true;
225 }
226
[5459]227 @Override
[1169]228 public void destroy() {
[12320]229 if (sc != null && !sc.isAutomatic()) {
[12639]230 MainApplication.unregisterActionShortcut(this);
[1169]231 }
[10345]232 if (layerChangeAdapter != null) {
[10353]233 getLayerManager().removeLayerChangeListener(layerChangeAdapter);
234 getLayerManager().removeActiveLayerChangeListener(activeLayerChangeAdapter);
[10345]235 }
[10353]236 if (selectionChangeAdapter != null) {
[13925]237 SelectionEventManager.getInstance().removeSelectionListener(selectionChangeAdapter);
[10353]238 }
[1169]239 }
[1023]240
[1169]241 private void setHelpId() {
242 String helpId = "Action/"+getClass().getName().substring(getClass().getName().lastIndexOf('.')+1);
[1814]243 if (helpId.endsWith("Action")) {
[1169]244 helpId = helpId.substring(0, helpId.length()-6);
[1814]245 }
[1169]246 putValue("help", helpId);
247 }
[1814]248
[6814]249 /**
[10353]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 /**
[6814]264 * Sets the tooltip text of this action.
265 * @param tooltip The text to display in tooltip. Can be {@code null}
266 */
[6890]267 public final void setTooltip(String tooltip) {
[5026]268 if (tooltip != null) {
269 putValue(SHORT_DESCRIPTION, Main.platform.makeTooltip(tooltip, sc));
270 }
[4908]271 }
272
[1814]273 /**
[10353]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.
[10354]279 * @since 10353
[10353]280 */
281 public MainLayerManager getLayerManager() {
[12636]282 return MainApplication.getLayerManager();
[10353]283 }
284
[10074]285 protected static void waitFuture(final Future<?> future, final PleaseWaitProgressMonitor monitor) {
[12634]286 MainApplication.worker.submit(() -> {
[10074]287 try {
288 future.get();
[10212]289 } catch (InterruptedException | ExecutionException | CancellationException e) {
[12620]290 Logging.error(e);
[10074]291 return;
292 }
293 monitor.close();
[10601]294 });
[10074]295 }
296
[2260]297 /**
298 * Override in subclasses to init the enabled state of an action when it is
[5266]299 * created. Default behaviour is to call {@link #updateEnabledState()}
[2305]300 *
[2260]301 * @see #updateEnabledState()
302 * @see #updateEnabledState(Collection)
303 */
[2256]304 protected void initEnabledState() {
[2260]305 updateEnabledState();
[2256]306 }
307
[2260]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.
[2305]311 *
[5266]312 * See {@link #updateEnabledState(Collection)} to respond to changes in the collection
[2260]313 * of selected primitives.
[2305]314 *
[2260]315 * Default behavior is empty.
[2305]316 *
[2260]317 * @see #updateEnabledState(Collection)
318 * @see #initEnabledState()
[10353]319 * @see #listenToLayerChange()
[2260]320 */
[1820]321 protected void updateEnabledState() {
322 }
323
[2260]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
[3504]327 * new selection.
[2305]328 *
[3504]329 * @param selection the collection of selected primitives; may be empty, but not null
[2305]330 *
[2260]331 * @see #updateEnabledState()
332 * @see #initEnabledState()
[10353]333 * @see #listenToSelectionChange()
[2260]334 */
[2256]335 protected void updateEnabledState(Collection<? extends OsmPrimitive> selection) {
336 }
337
[1820]338 /**
[10409]339 * Updates enabled state according to primitives currently selected in edit data set, if any.
340 * Can be called in {@link #updateEnabledState()} implementations.
[13434]341 * @see #updateEnabledStateOnCurrentSelection(boolean)
[10409]342 * @since 10409
343 */
344 protected final void updateEnabledStateOnCurrentSelection() {
[13434]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();
[13453]356 if (ds != null && (allowReadOnly || !ds.isLocked())) {
[13434]357 updateEnabledState(ds.getSelected());
358 } else {
[10409]359 setEnabled(false);
360 }
361 }
362
363 /**
[13434]364 * Updates enabled state according to selected primitives, if any.
[13486]365 * Enables action if the collection is not empty and references primitives in a modifiable data layer.
[13434]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) {
[13611]371 setEnabled(OsmUtils.isOsmCollectionEditable(selection));
[13434]372 }
373
374 /**
[10345]375 * Adapter for layer change events. Runs updateEnabledState() whenever the active layer changed.
[1820]376 */
[10353]377 protected class LayerChangeAdapter implements LayerChangeListener {
[6084]378 @Override
[10353]379 public void layerAdded(LayerAddEvent e) {
[10345]380 updateEnabledState();
[1820]381 }
382
[6084]383 @Override
[10353]384 public void layerRemoving(LayerRemoveEvent e) {
385 updateEnabledState();
386 }
387
388 @Override
389 public void layerOrderChanged(LayerOrderChangeEvent e) {
390 updateEnabledState();
391 }
392
393 @Override
[10345]394 public String toString() {
[11538]395 return "LayerChangeAdapter [" + JosmAction.this + ']';
[1820]396 }
397 }
398
399 /**
[10353]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() {
[11538]410 return "ActiveLayerChangeAdapter [" + JosmAction.this + ']';
[10353]411 }
412 }
413
414 /**
[10345]415 * Adapter for selection change events. Runs updateEnabledState() whenever the selection changed.
[1820]416 */
[13925]417 protected class SelectionChangeAdapter implements DataSelectionListener {
[6084]418 @Override
[13925]419 public void selectionChanged(SelectionChangeEvent event) {
420 updateEnabledState(event.getSelection());
[1820]421 }
[10345]422
423 @Override
424 public String toString() {
[11538]425 return "SelectionChangeAdapter [" + JosmAction.this + ']';
[10345]426 }
[1820]427 }
[12749]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 }
[30]477}
Note: See TracBrowser for help on using the repository browser.