source: josm/trunk/src/org/openstreetmap/josm/gui/MainMenu.java@ 15633

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

fix #18514 - make all changeset actions and dialogs only accessible in expert mode

  • Property svn:eol-style set to native
File size: 44.0 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.gui;
3
4import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
5import static org.openstreetmap.josm.tools.I18n.tr;
6import static org.openstreetmap.josm.tools.I18n.trc;
7
8import java.awt.Component;
9import java.awt.GraphicsEnvironment;
10import java.awt.event.KeyEvent;
11import java.util.ArrayList;
12import java.util.Arrays;
13import java.util.Collection;
14import java.util.HashMap;
15import java.util.List;
16import java.util.Locale;
17import java.util.Map;
18import java.util.Objects;
19import java.util.Optional;
20
21import javax.swing.JCheckBoxMenuItem;
22import javax.swing.JMenu;
23import javax.swing.JMenuBar;
24import javax.swing.JMenuItem;
25import javax.swing.JPopupMenu;
26import javax.swing.JSeparator;
27import javax.swing.KeyStroke;
28import javax.swing.event.MenuEvent;
29import javax.swing.event.MenuListener;
30
31import org.openstreetmap.josm.actions.AboutAction;
32import org.openstreetmap.josm.actions.AddNodeAction;
33import org.openstreetmap.josm.actions.AlignInCircleAction;
34import org.openstreetmap.josm.actions.AlignInLineAction;
35import org.openstreetmap.josm.actions.AutoScaleAction;
36import org.openstreetmap.josm.actions.AutoScaleAction.AutoScaleMode;
37import org.openstreetmap.josm.actions.ChangesetManagerToggleAction;
38import org.openstreetmap.josm.actions.CloseChangesetAction;
39import org.openstreetmap.josm.actions.CombineWayAction;
40import org.openstreetmap.josm.actions.CopyAction;
41import org.openstreetmap.josm.actions.CopyCoordinatesAction;
42import org.openstreetmap.josm.actions.CreateCircleAction;
43import org.openstreetmap.josm.actions.CreateMultipolygonAction;
44import org.openstreetmap.josm.actions.DeleteAction;
45import org.openstreetmap.josm.actions.DeleteLayerAction;
46import org.openstreetmap.josm.actions.DialogsToggleAction;
47import org.openstreetmap.josm.actions.DistributeAction;
48import org.openstreetmap.josm.actions.DownloadAction;
49import org.openstreetmap.josm.actions.DownloadAlongWayAction;
50import org.openstreetmap.josm.actions.DownloadNotesInViewAction;
51import org.openstreetmap.josm.actions.DownloadOsmInViewAction;
52import org.openstreetmap.josm.actions.DownloadPrimitiveAction;
53import org.openstreetmap.josm.actions.DownloadReferrersAction;
54import org.openstreetmap.josm.actions.DrawBoundariesOfDownloadedDataAction;
55import org.openstreetmap.josm.actions.DuplicateAction;
56import org.openstreetmap.josm.actions.ExitAction;
57import org.openstreetmap.josm.actions.ExpertToggleAction;
58import org.openstreetmap.josm.actions.FollowLineAction;
59import org.openstreetmap.josm.actions.FullscreenToggleAction;
60import org.openstreetmap.josm.actions.GpxExportAction;
61import org.openstreetmap.josm.actions.HelpAction;
62import org.openstreetmap.josm.actions.HistoryInfoAction;
63import org.openstreetmap.josm.actions.HistoryInfoWebAction;
64import org.openstreetmap.josm.actions.InfoAction;
65import org.openstreetmap.josm.actions.InfoWebAction;
66import org.openstreetmap.josm.actions.JoinAreasAction;
67import org.openstreetmap.josm.actions.JoinNodeWayAction;
68import org.openstreetmap.josm.actions.JosmAction;
69import org.openstreetmap.josm.actions.JumpToAction;
70import org.openstreetmap.josm.actions.MergeLayerAction;
71import org.openstreetmap.josm.actions.MergeNodesAction;
72import org.openstreetmap.josm.actions.MergeSelectionAction;
73import org.openstreetmap.josm.actions.MirrorAction;
74import org.openstreetmap.josm.actions.MoveAction;
75import org.openstreetmap.josm.actions.MoveNodeAction;
76import org.openstreetmap.josm.actions.NewAction;
77import org.openstreetmap.josm.actions.OpenFileAction;
78import org.openstreetmap.josm.actions.OpenLocationAction;
79import org.openstreetmap.josm.actions.OrthogonalizeAction;
80import org.openstreetmap.josm.actions.OrthogonalizeAction.Undo;
81import org.openstreetmap.josm.actions.PasteAction;
82import org.openstreetmap.josm.actions.PasteAtSourcePositionAction;
83import org.openstreetmap.josm.actions.PasteTagsAction;
84import org.openstreetmap.josm.actions.PreferenceToggleAction;
85import org.openstreetmap.josm.actions.PreferencesAction;
86import org.openstreetmap.josm.actions.PurgeAction;
87import org.openstreetmap.josm.actions.RedoAction;
88import org.openstreetmap.josm.actions.ReorderImageryLayersAction;
89import org.openstreetmap.josm.actions.ReportBugAction;
90import org.openstreetmap.josm.actions.RestartAction;
91import org.openstreetmap.josm.actions.ReverseWayAction;
92import org.openstreetmap.josm.actions.SaveAction;
93import org.openstreetmap.josm.actions.SaveAsAction;
94import org.openstreetmap.josm.actions.SearchNotesDownloadAction;
95import org.openstreetmap.josm.actions.SelectAllAction;
96import org.openstreetmap.josm.actions.SelectNonBranchingWaySequencesAction;
97import org.openstreetmap.josm.actions.SessionSaveAsAction;
98import org.openstreetmap.josm.actions.ShowStatusReportAction;
99import org.openstreetmap.josm.actions.SimplifyWayAction;
100import org.openstreetmap.josm.actions.SplitWayAction;
101import org.openstreetmap.josm.actions.TaggingPresetSearchAction;
102import org.openstreetmap.josm.actions.UnGlueAction;
103import org.openstreetmap.josm.actions.UnJoinNodeWayAction;
104import org.openstreetmap.josm.actions.UndoAction;
105import org.openstreetmap.josm.actions.UnselectAllAction;
106import org.openstreetmap.josm.actions.UpdateDataAction;
107import org.openstreetmap.josm.actions.UpdateModifiedAction;
108import org.openstreetmap.josm.actions.UpdateSelectionAction;
109import org.openstreetmap.josm.actions.UploadAction;
110import org.openstreetmap.josm.actions.UploadSelectionAction;
111import org.openstreetmap.josm.actions.ViewportFollowToggleAction;
112import org.openstreetmap.josm.actions.WireframeToggleAction;
113import org.openstreetmap.josm.actions.ZoomInAction;
114import org.openstreetmap.josm.actions.ZoomOutAction;
115import org.openstreetmap.josm.actions.audio.AudioBackAction;
116import org.openstreetmap.josm.actions.audio.AudioFasterAction;
117import org.openstreetmap.josm.actions.audio.AudioFwdAction;
118import org.openstreetmap.josm.actions.audio.AudioNextAction;
119import org.openstreetmap.josm.actions.audio.AudioPlayPauseAction;
120import org.openstreetmap.josm.actions.audio.AudioPrevAction;
121import org.openstreetmap.josm.actions.audio.AudioSlowerAction;
122import org.openstreetmap.josm.actions.mapmode.MapMode;
123import org.openstreetmap.josm.actions.search.SearchAction;
124import org.openstreetmap.josm.data.UndoRedoHandler;
125import org.openstreetmap.josm.gui.dialogs.MenuItemSearchDialog;
126import org.openstreetmap.josm.gui.io.RecentlyOpenedFilesMenu;
127import org.openstreetmap.josm.gui.layer.MainLayerManager.ActiveLayerChangeEvent;
128import org.openstreetmap.josm.gui.layer.MainLayerManager.ActiveLayerChangeListener;
129import org.openstreetmap.josm.gui.mappaint.MapPaintMenu;
130import org.openstreetmap.josm.gui.preferences.imagery.ImageryPreference;
131import org.openstreetmap.josm.gui.preferences.map.TaggingPresetPreference;
132import org.openstreetmap.josm.gui.tagging.presets.TaggingPresetSearchPrimitiveDialog;
133import org.openstreetmap.josm.spi.preferences.Config;
134import org.openstreetmap.josm.tools.PlatformManager;
135import org.openstreetmap.josm.tools.Shortcut;
136
137/**
138 * This is the JOSM main menu bar. It is overwritten to initialize itself and provide all menu
139 * entries as member variables (sort of collect them).
140 *
141 * It also provides possibilities to attach new menu entries (used by plugins).
142 *
143 * @author Immanuel.Scholz
144 */
145public class MainMenu extends JMenuBar {
146
147 public enum WINDOW_MENU_GROUP { ALWAYS, TOGGLE_DIALOG, VOLATILE }
148
149 /* File menu */
150 /** File / New Layer **/
151 public final NewAction newAction = new NewAction();
152 /** File / Open... **/
153 public final OpenFileAction openFile = new OpenFileAction();
154 /** File / Open Recent > **/
155 public final RecentlyOpenedFilesMenu recentlyOpened = new RecentlyOpenedFilesMenu();
156 /** File / Open Location... **/
157 public final OpenLocationAction openLocation = new OpenLocationAction();
158 /** File / Delete Layer **/
159 public final DeleteLayerAction deleteLayerAction = new DeleteLayerAction();
160 /** File / Save **/
161 public final SaveAction save = SaveAction.getInstance();
162 /** File / Save As... **/
163 public final SaveAsAction saveAs = SaveAsAction.getInstance();
164 /** File / Session > Save Session As... **/
165 public SessionSaveAsAction sessionSaveAs;
166 /** File / Export to GPX... **/
167 public final GpxExportAction gpxExport = new GpxExportAction();
168 /** File / Download from OSM... **/
169 public final DownloadAction download = new DownloadAction();
170 /** File / Download in current view **/
171 public final DownloadOsmInViewAction downloadInView = new DownloadOsmInViewAction();
172 /** File / Download object... **/
173 public final DownloadPrimitiveAction downloadPrimitive = new DownloadPrimitiveAction();
174 /** File / Download notes in current view **/
175 public final DownloadNotesInViewAction downloadNotesInView = DownloadNotesInViewAction.newActionWithNoteIcon();
176 /** File / Search Notes... **/
177 public final SearchNotesDownloadAction searchNotes = new SearchNotesDownloadAction();
178 /** File / Download parent ways/relations... **/
179 public final DownloadReferrersAction downloadReferrers = new DownloadReferrersAction();
180 /** File / Close open changesets... **/
181 public final CloseChangesetAction closeChangesetAction = new CloseChangesetAction();
182 /** File / Update data **/
183 public final JosmAction update = new UpdateDataAction();
184 /** File / Update selection **/
185 public final JosmAction updateSelection = new UpdateSelectionAction();
186 /** File / Update modified **/
187 public final JosmAction updateModified = new UpdateModifiedAction();
188 /** File / Upload data **/
189 public final JosmAction upload = new UploadAction();
190 /** File / Upload selection **/
191 public final JosmAction uploadSelection = new UploadSelectionAction();
192 /** File / Restart **/
193 public final RestartAction restart = new RestartAction();
194 /** File / Exit **/
195 public final ExitAction exit = new ExitAction();
196
197 /* Edit menu */
198 /** Edit / Undo... */
199 public final UndoAction undo = new UndoAction();
200 /** Edit / Redo */
201 public final RedoAction redo = new RedoAction();
202 /** Edit / Copy */
203 public final CopyAction copy = new CopyAction();
204 /** Edit / Copy Coordinates */
205 public final JosmAction copyCoordinates = new CopyCoordinatesAction();
206 /** Edit / Paste */
207 public final PasteAction paste = new PasteAction();
208 /** Edit / Paste at source */
209 private final PasteAtSourcePositionAction pasteAtSource = new PasteAtSourcePositionAction();
210 /** Edit / Paste Tags */
211 public final PasteTagsAction pasteTags = new PasteTagsAction();
212 /** Edit / Duplicate */
213 public final DuplicateAction duplicate = new DuplicateAction();
214 /** Edit / Delete */
215 public final DeleteAction delete = new DeleteAction();
216 /** Edit / Purge... */
217 public final JosmAction purge = new PurgeAction();
218 /** Edit / Merge layer */
219 public final MergeLayerAction merge = new MergeLayerAction();
220 /** Edit / Merge selection */
221 public final MergeSelectionAction mergeSelected = new MergeSelectionAction();
222 /** Edit / Search... */
223 public final SearchAction search = new SearchAction();
224 /** Edit / Preferences */
225 public final PreferencesAction preferences = new PreferencesAction();
226
227 /* View menu */
228 /** View / Wireframe View */
229 public final WireframeToggleAction wireFrameToggleAction = new WireframeToggleAction();
230 /** View / Hatch area outside download */
231 public final DrawBoundariesOfDownloadedDataAction drawBoundariesOfDownloadedDataAction = new DrawBoundariesOfDownloadedDataAction();
232 /** View / Advanced info */
233 public final InfoAction info = new InfoAction();
234 /** View / Advanced info (web) */
235 public final InfoWebAction infoweb = new InfoWebAction();
236 /** View / History */
237 public final HistoryInfoAction historyinfo = new HistoryInfoAction();
238 /** View / History (web) */
239 public final HistoryInfoWebAction historyinfoweb = new HistoryInfoWebAction();
240 /** View / "Zoom to"... actions */
241 public final Map<String, AutoScaleAction> autoScaleActions = new HashMap<>();
242 /** View / Jump to position */
243 public final JumpToAction jumpToAct = new JumpToAction();
244
245 /* Tools menu */
246 /** Tools / Split Way */
247 public final SplitWayAction splitWay = new SplitWayAction();
248 /** Tools / Combine Way */
249 public final CombineWayAction combineWay = new CombineWayAction();
250 /** Tools / Reverse Ways */
251 public final ReverseWayAction reverseWay = new ReverseWayAction();
252 /** Tools / Simplify Way */
253 public final SimplifyWayAction simplifyWay = new SimplifyWayAction();
254 /** Tools / Align Nodes in Circle */
255 public final AlignInCircleAction alignInCircle = new AlignInCircleAction();
256 /** Tools / Align Nodes in Line */
257 public final AlignInLineAction alignInLine = new AlignInLineAction();
258 /** Tools / Distribute Nodes */
259 public final DistributeAction distribute = new DistributeAction();
260 /** Tools / Orthogonalize Shape */
261 public final OrthogonalizeAction ortho = new OrthogonalizeAction();
262 /** Orthogonalize undo. Action is not shown in the menu. Only triggered by shortcut */
263 public final Undo orthoUndo = new Undo();
264 /** Tools / Mirror */
265 public final MirrorAction mirror = new MirrorAction();
266 /** Tools / Follow line */
267 public final FollowLineAction followLine = new FollowLineAction();
268 /** Tools / Add Node... */
269 public final AddNodeAction addNode = new AddNodeAction();
270 /** Tools / Move Node... */
271 public final MoveNodeAction moveNode = new MoveNodeAction();
272 /** Tools / Create Circle */
273 public final CreateCircleAction createCircle = new CreateCircleAction();
274 /** Tools / Merge Nodes */
275 public final MergeNodesAction mergeNodes = new MergeNodesAction();
276 /** Tools / Join Node to Way */
277 public final JoinNodeWayAction joinNodeWay = JoinNodeWayAction.createJoinNodeToWayAction();
278 /** Tools / Join Way to Node */
279 public final JoinNodeWayAction moveNodeOntoWay = JoinNodeWayAction.createMoveNodeOntoWayAction();
280 /** Tools / Disconnect Node from Way */
281 public final UnJoinNodeWayAction unJoinNodeWay = new UnJoinNodeWayAction();
282 /** Tools / Unglue Ways */
283 public final UnGlueAction unglueNodes = new UnGlueAction();
284 /** Tools / Join overlapping Areas */
285 public final JoinAreasAction joinAreas = new JoinAreasAction();
286 /** Tools / Create multipolygon */
287 public final CreateMultipolygonAction createMultipolygon = new CreateMultipolygonAction(false);
288 /** Tools / Update multipolygon */
289 public final CreateMultipolygonAction updateMultipolygon = new CreateMultipolygonAction(true);
290 /** Tools / Download along way */
291 public final DownloadAlongWayAction downloadAlongWay = new DownloadAlongWayAction();
292
293 /* Selection menu */
294 /** Selection / Select All */
295 public final SelectAllAction selectAll = new SelectAllAction();
296 /** Selection / Unselect All */
297 public final UnselectAllAction unselectAll = new UnselectAllAction();
298 /** Selection / Non-branching way sequences */
299 public final SelectNonBranchingWaySequencesAction nonBranchingWaySequences = new SelectNonBranchingWaySequencesAction();
300
301 /* Audio menu */
302 /** Audio / Play/Pause */
303 public final JosmAction audioPlayPause = new AudioPlayPauseAction();
304 /** Audio / Next marker */
305 public final JosmAction audioNext = new AudioNextAction();
306 /** Audio / Previous Marker */
307 public final JosmAction audioPrev = new AudioPrevAction();
308 /** Audio / Forward */
309 public final JosmAction audioFwd = new AudioFwdAction();
310 /** Audio / Back */
311 public final JosmAction audioBack = new AudioBackAction();
312 /** Audio / Faster */
313 public final JosmAction audioFaster = new AudioFasterAction();
314 /** Audio / Slower */
315 public final JosmAction audioSlower = new AudioSlowerAction();
316
317 /* Windows Menu */
318 /** Windows / Changeset Manager */
319 public final ChangesetManagerToggleAction changesetManager = new ChangesetManagerToggleAction();
320
321 /* Help menu */
322 /** Help / Help */
323 public final HelpAction help = new HelpAction();
324 /** Help / About */
325 public final AboutAction about = new AboutAction();
326 /** Help / Show Status Report */
327 public final ShowStatusReportAction statusreport = new ShowStatusReportAction();
328 /** Help / Report bug */
329 public final ReportBugAction reportbug = new ReportBugAction();
330
331 /**
332 * fileMenu contains I/O actions
333 */
334 public final JMenu fileMenu = addMenu("File", /* I18N: mnemonic: F */ trc("menu", "File"), KeyEvent.VK_F, 0, ht("/Menu/File"));
335 /**
336 * editMenu contains editing actions
337 */
338 public final JMenu editMenu = addMenu("Edit", /* I18N: mnemonic: E */ trc("menu", "Edit"), KeyEvent.VK_E, 1, ht("/Menu/Edit"));
339 /**
340 * viewMenu contains display actions (zoom, map styles, etc.)
341 */
342 public final JMenu viewMenu = addMenu("View", /* I18N: mnemonic: V */ trc("menu", "View"), KeyEvent.VK_V, 2, ht("/Menu/View"));
343 /**
344 * modeMenu contains map modes
345 */
346 public final JMenu modeMenu = addMenu(new ModeMenu(), /* I18N: mnemonic: M */ trc("menu", "Mode"), KeyEvent.VK_M, 3, ht("/Menu/Mode"));
347 /**
348 * toolsMenu contains different geometry manipulation actions from JOSM core (most used)
349 * The plugins should use other menus
350 */
351 public final JMenu toolsMenu = addMenu("Tools", /* I18N: mnemonic: T */ trc("menu", "Tools"), KeyEvent.VK_T, 4, ht("/Menu/Tools"));
352 /**
353 * moreToolsMenu contains geometry-related actions from all the plugins
354 * @since 6082 (moved from Utilsplugin2)
355 */
356 // CHECKSTYLE.OFF: LineLength
357 public final JMenu moreToolsMenu = addMenu("More tools", /* I18N: mnemonic: O */ trc("menu", "More tools"), KeyEvent.VK_O, 5, ht("/Menu/MoreTools"));
358 /**
359 * dataMenu contains plugin actions that are related to certain tagging schemes (addressing opening hours),
360 * importing external data and using external web APIs
361 * @since 6082
362 */
363 public final JMenu dataMenu = addMenu("Data", /* I18N: mnemonic: D */ trc("menu", "Data"), KeyEvent.VK_D, 6, ht("/Menu/Data"));
364 /**
365 * selectionMenu contains all actions related to selecting different objects
366 * @since 6082 (moved from Utilsplugin2)
367 */
368 public final JMenu selectionMenu = addMenu("Selection", /* I18N: mnemonic: N */ trc("menu", "Selection"), KeyEvent.VK_N, 7, ht("/Menu/Selection"));
369 /**
370 * presetsMenu contains presets actions (search, presets tree)
371 */
372 public final JMenu presetsMenu = addMenu("Presets", /* I18N: mnemonic: P */ trc("menu", "Presets"), KeyEvent.VK_P, 8, ht("/Menu/Presets"));
373 /**
374 * submenu in Imagery menu that contains plugin-managed additional imagery layers
375 * @since 6097
376 */
377 public final JMenu imagerySubMenu = new JMenu(tr("More..."));
378 /**
379 * imageryMenu contains all imagery-related actions
380 */
381 public final ImageryMenu imageryMenu = addMenu(new ImageryMenu(imagerySubMenu), /* untranslated name */ "Imagery", KeyEvent.VK_I, 9, ht("/Menu/Imagery"));
382 // CHECKSTYLE.ON: LineLength
383 /**
384 * gpsMenu contains all plugin actions that are related
385 * to using GPS data, including opening, uploading and real-time tracking
386 * @since 6082
387 */
388 public final JMenu gpsMenu = addMenu("GPS", /* I18N: mnemonic: G */ trc("menu", "GPS"), KeyEvent.VK_G, 10, ht("/Menu/GPS"));
389 /** the window menu is split into several groups. The first is for windows that can be opened from
390 * this menu any time, e.g. the changeset editor. The second group is for toggle dialogs and the third
391 * group is for currently open windows that cannot be toggled, e.g. relation editors. It's recommended
392 * to use WINDOW_MENU_GROUP to determine the group integer.
393 */
394 public final JMenu windowMenu = addMenu("Windows", /* I18N: mnemonic: W */ trc("menu", "Windows"), KeyEvent.VK_W, 11, ht("/ToggleDialogs"));
395
396 /**
397 * audioMenu contains all audio-related actions. Be careful, this menu is not guaranteed to be displayed at all
398 */
399 public JMenu audioMenu;
400 /**
401 * helpMenu contains JOSM general actions (Help, About, etc.)
402 */
403 public final JMenu helpMenu = addMenu("Help", /* I18N: mnemonic: H */ trc("menu", "Help"), KeyEvent.VK_H, 12, ht("/Menu/Help"));
404
405 private static final int defaultMenuPos = 12;
406
407 /** Move the selection up */
408 public final JosmAction moveUpAction = new MoveAction(MoveAction.Direction.UP);
409 /** Move the selection down */
410 public final JosmAction moveDownAction = new MoveAction(MoveAction.Direction.DOWN);
411 /** Move the selection left */
412 public final JosmAction moveLeftAction = new MoveAction(MoveAction.Direction.LEFT);
413 /** Move the selection right */
414 public final JosmAction moveRightAction = new MoveAction(MoveAction.Direction.RIGHT);
415
416 /** Reorder imagery layers */
417 public final ReorderImageryLayersAction reorderImageryLayersAction = new ReorderImageryLayersAction();
418
419 /** Search tagging presets */
420 public final TaggingPresetSearchAction presetSearchAction = new TaggingPresetSearchAction();
421 /** Search objects by their tagging preset */
422 public final TaggingPresetSearchPrimitiveDialog.Action presetSearchPrimitiveAction = new TaggingPresetSearchPrimitiveDialog.Action();
423 /** Toggle visibility of dialogs panel */
424 public final DialogsToggleAction dialogsToggleAction = new DialogsToggleAction();
425 /** Toggle the full-screen mode */
426 public FullscreenToggleAction fullscreenToggleAction;
427
428 /** this menu listener hides unnecessary JSeparators in a menu list but does not remove them.
429 * If at a later time the separators are required, they will be made visible again. Intended
430 * usage is make menus not look broken if separators are used to group the menu and some of
431 * these groups are empty.
432 */
433 public static final MenuListener menuSeparatorHandler = new MenuListener() {
434 @Override
435 public void menuCanceled(MenuEvent e) {
436 // Do nothing
437 }
438
439 @Override
440 public void menuDeselected(MenuEvent e) {
441 // Do nothing
442 }
443
444 @Override
445 public void menuSelected(MenuEvent a) {
446 if (!(a.getSource() instanceof JMenu))
447 return;
448 final JPopupMenu m = ((JMenu) a.getSource()).getPopupMenu();
449 for (int i = 0; i < m.getComponentCount()-1; i++) {
450 // hide separator if the next menu item is one as well
451 if (m.getComponent(i) instanceof JSeparator && m.getComponent(i+1) instanceof JSeparator) {
452 ((JSeparator) m.getComponent(i)).setVisible(false);
453 }
454 }
455 // hide separator at the end of the menu
456 if (m.getComponent(m.getComponentCount()-1) instanceof JSeparator) {
457 ((JSeparator) m.getComponent(m.getComponentCount()-1)).setVisible(false);
458 }
459 }
460 };
461
462 /**
463 * @return the default position of new top-level menus
464 * @since 6088
465 */
466 public int getDefaultMenuPos() {
467 return defaultMenuPos;
468 }
469
470 /**
471 * Add a JosmAction at the end of a menu.
472 *
473 * This method handles all the shortcut handling. It also makes sure that actions that are
474 * handled by the OS are not duplicated on the menu.
475 * @param menu the menu to add the action to
476 * @param action the action that should get a menu item
477 * @return the created menu item
478 */
479 public static JMenuItem add(JMenu menu, JosmAction action) {
480 return add(menu, action, false);
481 }
482
483 /**
484 * Add a JosmAction at the end of a menu.
485 *
486 * This method handles all the shortcut handling. It also makes sure that actions that are
487 * handled by the OS are not duplicated on the menu.
488 * @param menu the menu to add the action to
489 * @param action the action that should get a menu item
490 * @param isExpert whether the entry should only be visible if the expert mode is activated
491 * @return the created menu item
492 */
493 public static JMenuItem add(JMenu menu, JosmAction action, boolean isExpert) {
494 return add(menu, action, isExpert, null);
495 }
496
497 /**
498 * Add a JosmAction at the end of a menu.
499 *
500 * This method handles all the shortcut handling. It also makes sure that actions that are
501 * handled by the OS are not duplicated on the menu.
502 * @param menu the menu to add the action to
503 * @param action the action that should get a menu item
504 * @param isExpert whether the entry should only be visible if the expert mode is activated
505 * @param index an integer specifying the position at which to add the action
506 * @return the created menu item
507 */
508 public static JMenuItem add(JMenu menu, JosmAction action, boolean isExpert, Integer index) {
509 if (action.getShortcut().isAutomatic())
510 return null;
511 final JMenuItem menuitem;
512 if (index == null) {
513 menuitem = menu.add(action);
514 } else {
515 menuitem = menu.insert(action, index);
516 }
517 if (isExpert) {
518 ExpertToggleAction.addVisibilitySwitcher(menuitem);
519 }
520 KeyStroke ks = action.getShortcut().getKeyStroke();
521 if (ks != null) {
522 menuitem.setAccelerator(ks);
523 }
524 // some menus are hidden before they are populated with some items by plugins
525 if (!menu.isVisible()) menu.setVisible(true);
526 return menuitem;
527 }
528
529 /**
530 * Add the JosmAction {@code actionToBeInserted} directly below {@code existingMenuEntryAction}.
531 *
532 * This method handles all the shortcut handling. It also makes sure that actions that are
533 * handled by the OS are not duplicated on the menu.
534 * @param menu the menu to add the action to
535 * @param actionToBeInserted the action that should get a menu item directly below {@code existingMenuEntryAction}
536 * @param isExpert whether the entry should only be visible if the expert mode is activated
537 * @param existingMenuEntryAction an action already added to the menu {@code menu},
538 * the action {@code actionToBeInserted} is added directly below
539 * @return the created menu item
540 */
541 public static JMenuItem addAfter(JMenu menu, JosmAction actionToBeInserted, boolean isExpert, JosmAction existingMenuEntryAction) {
542 int i = 0;
543 for (Component c : menu.getMenuComponents()) {
544 if (c instanceof JMenuItem && ((JMenuItem) c).getAction() == existingMenuEntryAction) {
545 break;
546 }
547 i++;
548 }
549 return add(menu, actionToBeInserted, isExpert, i + 1);
550 }
551
552 /**
553 * Add a JosmAction to a menu.
554 *
555 * This method handles all the shortcut handling. It also makes sure that actions that are
556 * handled by the OS are not duplicated on the menu.
557 * @param <E> group item enum type
558 * @param menu to add the action to
559 * @param action the action that should get a menu item
560 * @param group the item should be added to. Groups are split by a separator.
561 * 0 is the first group, -1 will add the item to the end.
562 * @return The created menu item
563 */
564 public static <E extends Enum<E>> JMenuItem add(JMenu menu, JosmAction action, Enum<E> group) {
565 if (action.getShortcut().isAutomatic())
566 return null;
567 int i = getInsertionIndexForGroup(menu, group.ordinal(), false);
568 JMenuItem menuitem = (JMenuItem) menu.add(new JMenuItem(action), i);
569 KeyStroke ks = action.getShortcut().getKeyStroke();
570 if (ks != null) {
571 menuitem.setAccelerator(ks);
572 }
573 return menuitem;
574 }
575
576 /**
577 * Add a JosmAction to a menu and automatically prints accelerator if available.
578 * Also adds a checkbox that may be toggled.
579 * @param <E> group enum item type
580 * @param menu to add the action to
581 * @param action the action that should get a menu item
582 * @param group the item should be added to. Groups are split by a separator. Use
583 * one of the enums that are defined for some of the menus to tell in which
584 * group the item should go.
585 * @return The created menu item
586 */
587 public static <E extends Enum<E>> JCheckBoxMenuItem addWithCheckbox(JMenu menu, JosmAction action, Enum<E> group) {
588 return addWithCheckbox(menu, action, group, false, false);
589 }
590
591 /**
592 * Add a JosmAction to a menu and automatically prints accelerator if available.
593 * Also adds a checkbox that may be toggled.
594 * @param <E> group enum item type
595 * @param menu to add the action to
596 * @param action the action that should get a menu item
597 * @param group the item should be added to. Groups are split by a separator. Use
598 * one of the enums that are defined for some of the menus to tell in which
599 * group the item should go.
600 * @param isEntryExpert whether the entry should only be visible if the expert mode is activated
601 * @param isGroupSeparatorExpert whether the group separator should only be visible if the expert mode is activated
602 * @return The created menu item
603 * @since 15633
604 */
605 public static <E extends Enum<E>> JCheckBoxMenuItem addWithCheckbox(JMenu menu, JosmAction action, Enum<E> group,
606 boolean isEntryExpert, boolean isGroupSeparatorExpert) {
607 int i = getInsertionIndexForGroup(menu, group.ordinal(), isGroupSeparatorExpert);
608 final JCheckBoxMenuItem mi = (JCheckBoxMenuItem) menu.add(new JCheckBoxMenuItem(action), i);
609 final KeyStroke ks = action.getShortcut().getKeyStroke();
610 if (ks != null) {
611 mi.setAccelerator(ks);
612 }
613 if (isEntryExpert) {
614 ExpertToggleAction.addVisibilitySwitcher(mi);
615 }
616 return mi;
617 }
618
619 /**
620 * Finds the correct insertion index for a given group and adds separators if necessary
621 * @param menu menu
622 * @param group group number
623 * @param isGroupSeparatorExpert whether the added separators should only be visible if the expert mode is activated
624 * @return correct insertion index
625 */
626 private static int getInsertionIndexForGroup(JMenu menu, int group, boolean isGroupSeparatorExpert) {
627 if (group < 0)
628 return -1;
629 // look for separator that *ends* the group (or stop at end of menu)
630 int i;
631 for (i = 0; i < menu.getItemCount() && group >= 0; i++) {
632 if (menu.getItem(i) == null) {
633 group--;
634 }
635 }
636 // insert before separator that ends the group
637 if (group < 0) {
638 i--;
639 }
640 // not enough separators have been found, add them
641 while (group > 0) {
642 menu.addSeparator();
643 if (isGroupSeparatorExpert) {
644 ExpertToggleAction.addVisibilitySwitcher(menu.getMenuComponent(menu.getMenuComponentCount() - 1));
645 }
646 group--;
647 i++;
648 }
649 return i;
650 }
651
652 /**
653 * Creates a menu and adds it on the given position to the main menu.
654 *
655 * @param name the untranslated name (used as identifier for shortcut registration)
656 * @param translatedName the translated menu name (use {@code I18n.trc("menu", name)} to allow better internationalization
657 * @param mnemonicKey the mnemonic key to register
658 * @param position the position in the main menu
659 * @param relativeHelpTopic the relative help topic
660 * @return the newly created menu
661 */
662 public JMenu addMenu(String name, String translatedName, int mnemonicKey, int position, String relativeHelpTopic) {
663 final JMenu menu = new JMenu(translatedName);
664 if (!GraphicsEnvironment.isHeadless()) {
665 MenuScroller.setScrollerFor(menu);
666 }
667 return addMenu(menu, name, mnemonicKey, position, relativeHelpTopic);
668 }
669
670 /**
671 * Adds the given menu on the given position to the main menu.
672 * @param <T> menu type
673 *
674 * @param menu the menu to add
675 * @param name the untranslated name (used as identifier for shortcut registration)
676 * @param mnemonicKey the mnemonic key to register
677 * @param position the position in the main menu
678 * @param relativeHelpTopic the relative help topic
679 * @return the given {@code }menu}
680 */
681 public <T extends JMenu> T addMenu(T menu, String name, int mnemonicKey, int position, String relativeHelpTopic) {
682 Shortcut.registerShortcut("menu:" + name, tr("Menu: {0}", name), mnemonicKey,
683 Shortcut.MNEMONIC).setMnemonic(menu);
684 add(menu, position);
685 menu.putClientProperty("help", relativeHelpTopic);
686 return menu;
687 }
688
689 /**
690 * Initialize the main menu.
691 * @since 10340
692 */
693 // CHECKSTYLE.OFF: ExecutableStatementCountCheck
694 public void initialize() {
695 moreToolsMenu.setVisible(false);
696 dataMenu.setVisible(false);
697 gpsMenu.setVisible(false);
698
699 add(fileMenu, newAction);
700 add(fileMenu, openFile);
701 fileMenu.add(recentlyOpened);
702 add(fileMenu, openLocation);
703 add(fileMenu, deleteLayerAction);
704 fileMenu.addSeparator();
705 add(fileMenu, save);
706 add(fileMenu, saveAs);
707 sessionSaveAs = new SessionSaveAsAction();
708 ExpertToggleAction.addVisibilitySwitcher(fileMenu.add(sessionSaveAs));
709 add(fileMenu, gpxExport, true);
710 fileMenu.addSeparator();
711 add(fileMenu, download);
712 add(fileMenu, downloadInView, true);
713 add(fileMenu, downloadAlongWay);
714 add(fileMenu, downloadPrimitive);
715 add(fileMenu, searchNotes);
716 add(fileMenu, downloadNotesInView);
717 add(fileMenu, downloadReferrers);
718 add(fileMenu, update);
719 add(fileMenu, updateSelection);
720 add(fileMenu, updateModified);
721 fileMenu.addSeparator();
722 add(fileMenu, upload);
723 add(fileMenu, uploadSelection);
724 Component sep = new JPopupMenu.Separator();
725 fileMenu.add(sep);
726 ExpertToggleAction.addVisibilitySwitcher(sep);
727 add(fileMenu, closeChangesetAction, true);
728 fileMenu.addSeparator();
729 add(fileMenu, restart);
730 add(fileMenu, exit);
731
732 add(editMenu, undo);
733 UndoRedoHandler.getInstance().addCommandQueueListener(undo);
734 add(editMenu, redo);
735 UndoRedoHandler.getInstance().addCommandQueueListener(redo);
736 editMenu.addSeparator();
737 add(editMenu, copy);
738 add(editMenu, copyCoordinates, true);
739 add(editMenu, paste);
740 add(editMenu, pasteAtSource, true);
741 add(editMenu, pasteTags);
742 add(editMenu, duplicate);
743 add(editMenu, delete);
744 add(editMenu, purge, true);
745 editMenu.addSeparator();
746 add(editMenu, merge);
747 add(editMenu, mergeSelected);
748 editMenu.addSeparator();
749 add(editMenu, search);
750 add(editMenu, presetSearchPrimitiveAction);
751 editMenu.addSeparator();
752 add(editMenu, preferences);
753
754 // -- wireframe toggle action
755 final JCheckBoxMenuItem wireframe = new JCheckBoxMenuItem(wireFrameToggleAction);
756 viewMenu.add(wireframe);
757 wireframe.setAccelerator(wireFrameToggleAction.getShortcut().getKeyStroke());
758 wireFrameToggleAction.addButtonModel(wireframe.getModel());
759 final JCheckBoxMenuItem hatchAreaOutsideDownloadMenuItem = drawBoundariesOfDownloadedDataAction.getCheckbox();
760 viewMenu.add(hatchAreaOutsideDownloadMenuItem);
761 ExpertToggleAction.addVisibilitySwitcher(hatchAreaOutsideDownloadMenuItem);
762
763 viewMenu.add(new MapPaintMenu());
764 viewMenu.addSeparator();
765 add(viewMenu, new ZoomInAction());
766 add(viewMenu, new ZoomOutAction());
767 viewMenu.addSeparator();
768 for (AutoScaleMode mode : AutoScaleMode.values()) {
769 AutoScaleAction autoScaleAction = new AutoScaleAction(mode);
770 autoScaleActions.put(mode.getEnglishLabel(), autoScaleAction);
771 add(viewMenu, autoScaleAction);
772 }
773
774 // -- viewport follow toggle action
775 ViewportFollowToggleAction viewportFollowToggleAction = new ViewportFollowToggleAction();
776 final JCheckBoxMenuItem vft = new JCheckBoxMenuItem(viewportFollowToggleAction);
777 ExpertToggleAction.addVisibilitySwitcher(vft);
778 viewMenu.add(vft);
779 vft.setAccelerator(viewportFollowToggleAction.getShortcut().getKeyStroke());
780 viewportFollowToggleAction.addButtonModel(vft.getModel());
781
782 if (PlatformManager.getPlatform().canFullscreen()) {
783 // -- fullscreen toggle action
784 fullscreenToggleAction = new FullscreenToggleAction();
785 final JCheckBoxMenuItem fullscreen = new JCheckBoxMenuItem(fullscreenToggleAction);
786 viewMenu.addSeparator();
787 viewMenu.add(fullscreen);
788 fullscreen.setAccelerator(fullscreenToggleAction.getShortcut().getKeyStroke());
789 fullscreenToggleAction.addButtonModel(fullscreen.getModel());
790 }
791
792 add(viewMenu, jumpToAct, true);
793 viewMenu.addSeparator();
794 add(viewMenu, info);
795 add(viewMenu, infoweb);
796 add(viewMenu, historyinfo);
797 add(viewMenu, historyinfoweb);
798 viewMenu.addSeparator();
799 viewMenu.add(new PreferenceToggleAction(tr("Main toolbar"),
800 tr("Toggles the visibility of the main toolbar (i.e., the horizontal toolbar)"),
801 "toolbar.visible", true).getCheckbox());
802 viewMenu.add(new PreferenceToggleAction(tr("Edit toolbar"),
803 tr("Toggles the visibility of the edit toolbar (i.e., the vertical tool)"),
804 "sidetoolbar.visible", true).getCheckbox());
805 // -- dialogs panel toggle action
806 final JCheckBoxMenuItem dialogsToggle = new JCheckBoxMenuItem(dialogsToggleAction);
807 dialogsToggle.setAccelerator(dialogsToggleAction.getShortcut().getKeyStroke());
808 dialogsToggleAction.addButtonModel(dialogsToggle.getModel());
809 viewMenu.add(dialogsToggle);
810 viewMenu.addSeparator();
811 // -- expert mode toggle action
812 final JCheckBoxMenuItem expertItem = new JCheckBoxMenuItem(ExpertToggleAction.getInstance());
813 viewMenu.add(expertItem);
814 ExpertToggleAction.getInstance().addButtonModel(expertItem.getModel());
815
816 add(presetsMenu, presetSearchAction);
817 add(presetsMenu, presetSearchPrimitiveAction);
818 add(presetsMenu, PreferencesAction.forPreferenceSubTab(tr("Preset preferences"),
819 tr("Click to open the tagging presets tab in the preferences"), TaggingPresetPreference.class));
820 presetsMenu.addSeparator();
821
822 add(imageryMenu, reorderImageryLayersAction);
823 add(imageryMenu, PreferencesAction.forPreferenceTab(tr("Imagery preferences..."),
824 tr("Click to open the imagery tab in the preferences"), ImageryPreference.class));
825
826 add(selectionMenu, selectAll);
827 add(selectionMenu, unselectAll);
828 add(selectionMenu, nonBranchingWaySequences);
829
830 add(toolsMenu, splitWay);
831 add(toolsMenu, combineWay);
832 toolsMenu.addSeparator();
833 add(toolsMenu, reverseWay);
834 add(toolsMenu, simplifyWay);
835 toolsMenu.addSeparator();
836 add(toolsMenu, alignInCircle);
837 add(toolsMenu, alignInLine);
838 add(toolsMenu, distribute);
839 add(toolsMenu, ortho);
840 add(toolsMenu, mirror, true);
841 toolsMenu.addSeparator();
842 add(toolsMenu, followLine, true);
843 add(toolsMenu, addNode, true);
844 add(toolsMenu, moveNode, true);
845 add(toolsMenu, createCircle);
846 toolsMenu.addSeparator();
847 add(toolsMenu, mergeNodes);
848 add(toolsMenu, joinNodeWay);
849 add(toolsMenu, moveNodeOntoWay);
850 add(toolsMenu, unJoinNodeWay);
851 add(toolsMenu, unglueNodes);
852 toolsMenu.addSeparator();
853 add(toolsMenu, joinAreas);
854 add(toolsMenu, createMultipolygon);
855 add(toolsMenu, updateMultipolygon);
856
857 // -- changeset manager toggle action
858 final JCheckBoxMenuItem mi = MainMenu.addWithCheckbox(windowMenu, changesetManager,
859 MainMenu.WINDOW_MENU_GROUP.ALWAYS, true, false);
860 changesetManager.addButtonModel(mi.getModel());
861
862 if (!Config.getPref().getBoolean("audio.menuinvisible", false)) {
863 showAudioMenu(true);
864 }
865
866 Config.getPref().addPreferenceChangeListener(e -> {
867 if ("audio.menuinvisible".equals(e.getKey())) {
868 showAudioMenu(!Boolean.parseBoolean(e.getNewValue().toString()));
869 }
870 });
871
872 add(helpMenu, new MenuItemSearchDialog.Action());
873 helpMenu.addSeparator();
874 add(helpMenu, statusreport);
875 add(helpMenu, reportbug);
876 helpMenu.addSeparator();
877
878 add(helpMenu, help);
879 add(helpMenu, about);
880
881 windowMenu.addMenuListener(menuSeparatorHandler);
882
883 new EditLayerMenuEnabler(Arrays.asList(modeMenu, presetsMenu));
884 }
885 // CHECKSTYLE.ON: ExecutableStatementCountCheck
886
887 /**
888 * Search main menu for items with {@code textToFind} in title.
889 * @param textToFind The text to find
890 * @param skipPresets whether to skip the {@link #presetsMenu} in the search
891 * @return not null list of found menu items.
892 */
893 public List<JMenuItem> findMenuItems(String textToFind, boolean skipPresets) {
894 // Explicitly use default locale in this case, because we're looking for translated strings
895 textToFind = textToFind.toLowerCase(Locale.getDefault());
896 List<JMenuItem> result = new ArrayList<>();
897 for (int i = 0; i < getMenuCount(); i++) {
898 if (getMenu(i) != null && (!skipPresets || presetsMenu != getMenu(i))) {
899 findMenuItems(getMenu(i), textToFind, result);
900 }
901 }
902 return result;
903 }
904
905 /**
906 * Returns the {@link JCheckBoxMenuItem} for the given {@link MapMode}.
907 * @param mode map mode
908 * @return the {@code JCheckBoxMenuItem} for the given {@code MapMode}
909 * @since 15438
910 */
911 public Optional<JCheckBoxMenuItem> findMapModeMenuItem(MapMode mode) {
912 return Arrays.stream(modeMenu.getMenuComponents())
913 .filter(m -> m instanceof JCheckBoxMenuItem)
914 .map(m -> (JCheckBoxMenuItem) m)
915 .filter(m -> Objects.equals(mode, m.getAction()))
916 .findFirst();
917 }
918
919 /**
920 * Recursive walker for menu items. Only menu items with action are selected. If menu item
921 * contains {@code textToFind} it's appended to result.
922 * @param menu menu in which search will be performed
923 * @param textToFind The text to find
924 * @param result resulting list of menu items
925 */
926 private static void findMenuItems(final JMenu menu, final String textToFind, final List<JMenuItem> result) {
927 for (int i = 0; i < menu.getItemCount(); i++) {
928 JMenuItem menuItem = menu.getItem(i);
929 if (menuItem == null) continue;
930
931 // Explicitly use default locale in this case, because we're looking for translated strings
932 if (menuItem.getAction() != null && menuItem.getText().toLowerCase(Locale.getDefault()).contains(textToFind)) {
933 result.add(menuItem);
934 }
935
936 // Go recursive if needed
937 if (menuItem instanceof JMenu) {
938 findMenuItems((JMenu) menuItem, textToFind, result);
939 }
940 }
941 }
942
943 protected void showAudioMenu(boolean showMenu) {
944 if (showMenu && audioMenu == null) {
945 audioMenu = addMenu("Audio", /* I18N: mnemonic: U */ trc("menu", "Audio"), KeyEvent.VK_U, defaultMenuPos, ht("/Menu/Audio"));
946 add(audioMenu, audioPlayPause);
947 add(audioMenu, audioNext);
948 add(audioMenu, audioPrev);
949 add(audioMenu, audioFwd);
950 add(audioMenu, audioBack);
951 add(audioMenu, audioSlower);
952 add(audioMenu, audioFaster);
953 validate();
954 } else if (!showMenu && audioMenu != null) {
955 remove(audioMenu);
956 audioMenu.removeAll();
957 audioMenu = null;
958 validate();
959 }
960 }
961
962 static class EditLayerMenuEnabler implements ActiveLayerChangeListener {
963 private final Collection<JMenu> menus;
964
965 EditLayerMenuEnabler(Collection<JMenu> menus) {
966 this.menus = Objects.requireNonNull(menus);
967 MainApplication.getLayerManager().addAndFireActiveLayerChangeListener(this);
968 }
969
970 @Override
971 public void activeOrEditLayerChanged(ActiveLayerChangeEvent e) {
972 menus.forEach(m -> m.setEnabled(e.getSource().getEditLayer() != null));
973 }
974 }
975}
Note: See TracBrowser for help on using the repository browser.