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

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

see #18514 - disable Window menu when empty

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