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

Last change on this file since 16553 was 16553, checked in by Don-vip, 4 years ago

see #19334 - javadoc fixes + protected constructors for abstract classes

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