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

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

fix #16935 - simplify/cleanup help topics of ToggleDialog/ToggleDialogAction

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