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

Last change on this file since 13632 was 13611, checked in by Don-vip, 6 years ago

fix #16176 - NPE

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