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

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

see #16798 - be robust to svgSalamander errors when initializing JOSM actions

  • Property svn:eol-style set to native
File size: 21.3 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.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.PlatformManager;
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. The iconName is used, if this parameter is null
79 * @param installAdapters false, if you don't want to install layer changed and selection changed adapters
80 */
81 public 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 putValue("toolbar", 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 public 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 public 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}.
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 public 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 public 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 public 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 public 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 = new LayerChangeAdapter();
223 activeLayerChangeAdapter = new ActiveLayerChangeAdapter();
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 * Overwrite this if {@link #updateEnabledState()} should be called when the active / available layers change. Default is true.
236 * @return <code>true</code> if a {@link LayerChangeListener} and a {@link ActiveLayerChangeListener} should be registered.
237 * @since 10353
238 */
239 protected boolean listenToLayerChange() {
240 return true;
241 }
242
243 /**
244 * Overwrite this if {@link #updateEnabledState()} should be called when the selection changed. Default is true.
245 * @return <code>true</code> if a {@link DataSelectionListener} should be registered.
246 * @since 10353
247 */
248 protected boolean listenToSelectionChange() {
249 return true;
250 }
251
252 @Override
253 public void destroy() {
254 if (sc != null && !sc.isAutomatic()) {
255 MainApplication.unregisterActionShortcut(this);
256 }
257 if (layerChangeAdapter != null) {
258 getLayerManager().removeLayerChangeListener(layerChangeAdapter);
259 getLayerManager().removeActiveLayerChangeListener(activeLayerChangeAdapter);
260 }
261 if (selectionChangeAdapter != null) {
262 SelectionEventManager.getInstance().removeSelectionListener(selectionChangeAdapter);
263 }
264 }
265
266 private void setHelpId() {
267 String helpId = "Action/"+getClass().getName().substring(getClass().getName().lastIndexOf('.')+1);
268 if (helpId.endsWith("Action")) {
269 helpId = helpId.substring(0, helpId.length()-6);
270 }
271 putValue("help", helpId);
272 }
273
274 /**
275 * Returns the shortcut for this action.
276 * @return the shortcut for this action, or "No shortcut" if none is defined
277 */
278 public Shortcut getShortcut() {
279 if (sc == null) {
280 sc = Shortcut.registerShortcut("core:none", tr("No Shortcut"), KeyEvent.CHAR_UNDEFINED, Shortcut.NONE);
281 // as this shortcut is shared by all action that don't want to have a shortcut,
282 // we shouldn't allow the user to change it...
283 // this is handled by special name "core:none"
284 }
285 return sc;
286 }
287
288 /**
289 * Sets the tooltip text of this action.
290 * @param tooltip The text to display in tooltip. Can be {@code null}
291 */
292 public final void setTooltip(String tooltip) {
293 if (tooltip != null) {
294 putValue(SHORT_DESCRIPTION, PlatformManager.getPlatform().makeTooltip(tooltip, sc));
295 }
296 }
297
298 /**
299 * Gets the layer manager used for this action. Defaults to the main layer manager but you can overwrite this.
300 * <p>
301 * The layer manager must be available when {@link #installAdapters()} is called and must not change.
302 *
303 * @return The layer manager.
304 * @since 10353
305 */
306 public MainLayerManager getLayerManager() {
307 return MainApplication.getLayerManager();
308 }
309
310 protected static void waitFuture(final Future<?> future, final PleaseWaitProgressMonitor monitor) {
311 MainApplication.worker.submit(() -> {
312 try {
313 future.get();
314 } catch (InterruptedException | ExecutionException | CancellationException e) {
315 Logging.error(e);
316 return;
317 }
318 monitor.close();
319 });
320 }
321
322 /**
323 * Override in subclasses to init the enabled state of an action when it is
324 * created. Default behaviour is to call {@link #updateEnabledState()}
325 *
326 * @see #updateEnabledState()
327 * @see #updateEnabledState(Collection)
328 */
329 protected void initEnabledState() {
330 updateEnabledState();
331 }
332
333 /**
334 * Override in subclasses to update the enabled state of the action when
335 * something in the JOSM state changes, i.e. when a layer is removed or added.
336 *
337 * See {@link #updateEnabledState(Collection)} to respond to changes in the collection
338 * of selected primitives.
339 *
340 * Default behavior is empty.
341 *
342 * @see #updateEnabledState(Collection)
343 * @see #initEnabledState()
344 * @see #listenToLayerChange()
345 */
346 protected void updateEnabledState() {
347 }
348
349 /**
350 * Override in subclasses to update the enabled state of the action if the
351 * collection of selected primitives changes. This method is called with the
352 * new selection.
353 *
354 * @param selection the collection of selected primitives; may be empty, but not null
355 *
356 * @see #updateEnabledState()
357 * @see #initEnabledState()
358 * @see #listenToSelectionChange()
359 */
360 protected void updateEnabledState(Collection<? extends OsmPrimitive> selection) {
361 }
362
363 /**
364 * Updates enabled state according to primitives currently selected in edit data set, if any.
365 * Can be called in {@link #updateEnabledState()} implementations.
366 * @see #updateEnabledStateOnCurrentSelection(boolean)
367 * @since 10409
368 */
369 protected final void updateEnabledStateOnCurrentSelection() {
370 updateEnabledStateOnCurrentSelection(false);
371 }
372
373 /**
374 * Updates enabled state according to primitives currently selected in active data set, if any.
375 * Can be called in {@link #updateEnabledState()} implementations.
376 * @param allowReadOnly if {@code true}, read-only data sets are considered
377 * @since 13434
378 */
379 protected final void updateEnabledStateOnCurrentSelection(boolean allowReadOnly) {
380 DataSet ds = getLayerManager().getActiveDataSet();
381 if (ds != null && (allowReadOnly || !ds.isLocked())) {
382 updateEnabledState(ds.getSelected());
383 } else {
384 setEnabled(false);
385 }
386 }
387
388 /**
389 * Updates enabled state according to selected primitives, if any.
390 * Enables action if the collection is not empty and references primitives in a modifiable data layer.
391 * Can be called in {@link #updateEnabledState(Collection)} implementations.
392 * @param selection the collection of selected primitives
393 * @since 13434
394 */
395 protected final void updateEnabledStateOnModifiableSelection(Collection<? extends OsmPrimitive> selection) {
396 setEnabled(OsmUtils.isOsmCollectionEditable(selection));
397 }
398
399 /**
400 * Adapter for layer change events. Runs updateEnabledState() whenever the active layer changed.
401 */
402 protected class LayerChangeAdapter implements LayerChangeListener {
403 @Override
404 public void layerAdded(LayerAddEvent e) {
405 updateEnabledState();
406 }
407
408 @Override
409 public void layerRemoving(LayerRemoveEvent e) {
410 updateEnabledState();
411 }
412
413 @Override
414 public void layerOrderChanged(LayerOrderChangeEvent e) {
415 updateEnabledState();
416 }
417
418 @Override
419 public String toString() {
420 return "LayerChangeAdapter [" + JosmAction.this + ']';
421 }
422 }
423
424 /**
425 * Adapter for layer change events. Runs updateEnabledState() whenever the active layer changed.
426 */
427 protected class ActiveLayerChangeAdapter implements ActiveLayerChangeListener {
428 @Override
429 public void activeOrEditLayerChanged(ActiveLayerChangeEvent e) {
430 updateEnabledState();
431 }
432
433 @Override
434 public String toString() {
435 return "ActiveLayerChangeAdapter [" + JosmAction.this + ']';
436 }
437 }
438
439 /**
440 * Adapter for selection change events. Runs updateEnabledState() whenever the selection changed.
441 */
442 protected class SelectionChangeAdapter implements DataSelectionListener {
443 @Override
444 public void selectionChanged(SelectionChangeEvent event) {
445 updateEnabledState(event.getSelection());
446 }
447
448 @Override
449 public String toString() {
450 return "SelectionChangeAdapter [" + JosmAction.this + ']';
451 }
452 }
453
454 /**
455 * Check whether user is about to operate on data outside of the download area.
456 * Request confirmation if he is.
457 *
458 * @param operation the operation name which is used for setting some preferences
459 * @param dialogTitle the title of the dialog being displayed
460 * @param outsideDialogMessage the message text to be displayed when data is outside of the download area
461 * @param incompleteDialogMessage the message text to be displayed when data is incomplete
462 * @param primitives the primitives to operate on
463 * @param ignore {@code null} or a primitive to be ignored
464 * @return true, if operating on outlying primitives is OK; false, otherwise
465 * @since 12749 (moved from Command)
466 */
467 public static boolean checkAndConfirmOutlyingOperation(String operation,
468 String dialogTitle, String outsideDialogMessage, String incompleteDialogMessage,
469 Collection<? extends OsmPrimitive> primitives,
470 Collection<? extends OsmPrimitive> ignore) {
471 int checkRes = Command.checkOutlyingOrIncompleteOperation(primitives, ignore);
472 if ((checkRes & Command.IS_OUTSIDE) != 0) {
473 JPanel msg = new JPanel(new GridBagLayout());
474 msg.add(new JMultilineLabel("<html>" + outsideDialogMessage + "</html>"));
475 boolean answer = ConditionalOptionPaneUtil.showConfirmationDialog(
476 operation + "_outside_nodes",
477 MainApplication.getMainFrame(),
478 msg,
479 dialogTitle,
480 JOptionPane.YES_NO_OPTION,
481 JOptionPane.QUESTION_MESSAGE,
482 JOptionPane.YES_OPTION);
483 if (!answer)
484 return false;
485 }
486 if ((checkRes & Command.IS_INCOMPLETE) != 0) {
487 JPanel msg = new JPanel(new GridBagLayout());
488 msg.add(new JMultilineLabel("<html>" + incompleteDialogMessage + "</html>"));
489 boolean answer = ConditionalOptionPaneUtil.showConfirmationDialog(
490 operation + "_incomplete",
491 MainApplication.getMainFrame(),
492 msg,
493 dialogTitle,
494 JOptionPane.YES_NO_OPTION,
495 JOptionPane.QUESTION_MESSAGE,
496 JOptionPane.YES_OPTION);
497 if (!answer)
498 return false;
499 }
500 return true;
501 }
502}
Note: See TracBrowser for help on using the repository browser.