001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui;
003
004import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
005import static org.openstreetmap.josm.tools.I18n.tr;
006import static org.openstreetmap.josm.tools.I18n.trc;
007
008import java.awt.Component;
009import java.awt.GraphicsEnvironment;
010import java.awt.event.KeyEvent;
011import java.util.ArrayList;
012import java.util.Arrays;
013import java.util.Collection;
014import java.util.HashMap;
015import java.util.List;
016import java.util.Locale;
017import java.util.Map;
018import java.util.Objects;
019import java.util.Optional;
020
021import javax.swing.JCheckBoxMenuItem;
022import javax.swing.JMenu;
023import javax.swing.JMenuBar;
024import javax.swing.JMenuItem;
025import javax.swing.JPopupMenu;
026import javax.swing.JSeparator;
027import javax.swing.KeyStroke;
028import javax.swing.event.MenuEvent;
029import javax.swing.event.MenuListener;
030
031import org.openstreetmap.josm.actions.AboutAction;
032import org.openstreetmap.josm.actions.AddNodeAction;
033import org.openstreetmap.josm.actions.AlignInCircleAction;
034import org.openstreetmap.josm.actions.AlignInLineAction;
035import org.openstreetmap.josm.actions.AutoScaleAction;
036import org.openstreetmap.josm.actions.AutoScaleAction.AutoScaleMode;
037import org.openstreetmap.josm.actions.ChangesetManagerToggleAction;
038import org.openstreetmap.josm.actions.CloseChangesetAction;
039import org.openstreetmap.josm.actions.CombineWayAction;
040import org.openstreetmap.josm.actions.CopyAction;
041import org.openstreetmap.josm.actions.CopyCoordinatesAction;
042import org.openstreetmap.josm.actions.CreateCircleAction;
043import org.openstreetmap.josm.actions.CreateMultipolygonAction;
044import org.openstreetmap.josm.actions.DeleteAction;
045import org.openstreetmap.josm.actions.DeleteLayerAction;
046import org.openstreetmap.josm.actions.DialogsToggleAction;
047import org.openstreetmap.josm.actions.DistributeAction;
048import org.openstreetmap.josm.actions.DownloadAction;
049import org.openstreetmap.josm.actions.DownloadAlongWayAction;
050import org.openstreetmap.josm.actions.DownloadNotesInViewAction;
051import org.openstreetmap.josm.actions.DownloadOsmInViewAction;
052import org.openstreetmap.josm.actions.DownloadPrimitiveAction;
053import org.openstreetmap.josm.actions.DownloadReferrersAction;
054import org.openstreetmap.josm.actions.DrawBoundariesOfDownloadedDataAction;
055import org.openstreetmap.josm.actions.DuplicateAction;
056import org.openstreetmap.josm.actions.ExitAction;
057import org.openstreetmap.josm.actions.ExpertToggleAction;
058import org.openstreetmap.josm.actions.FollowLineAction;
059import org.openstreetmap.josm.actions.FullscreenToggleAction;
060import org.openstreetmap.josm.actions.GpxExportAction;
061import org.openstreetmap.josm.actions.HelpAction;
062import org.openstreetmap.josm.actions.HistoryInfoAction;
063import org.openstreetmap.josm.actions.HistoryInfoWebAction;
064import org.openstreetmap.josm.actions.InfoAction;
065import org.openstreetmap.josm.actions.InfoWebAction;
066import org.openstreetmap.josm.actions.JoinAreasAction;
067import org.openstreetmap.josm.actions.JoinNodeWayAction;
068import org.openstreetmap.josm.actions.JosmAction;
069import org.openstreetmap.josm.actions.JumpToAction;
070import org.openstreetmap.josm.actions.MergeLayerAction;
071import org.openstreetmap.josm.actions.MergeNodesAction;
072import org.openstreetmap.josm.actions.MergeSelectionAction;
073import org.openstreetmap.josm.actions.MirrorAction;
074import org.openstreetmap.josm.actions.MoveAction;
075import org.openstreetmap.josm.actions.MoveNodeAction;
076import org.openstreetmap.josm.actions.NewAction;
077import org.openstreetmap.josm.actions.OpenFileAction;
078import org.openstreetmap.josm.actions.OpenLocationAction;
079import org.openstreetmap.josm.actions.OrthogonalizeAction;
080import org.openstreetmap.josm.actions.OrthogonalizeAction.Undo;
081import org.openstreetmap.josm.actions.PasteAction;
082import org.openstreetmap.josm.actions.PasteAtSourcePositionAction;
083import org.openstreetmap.josm.actions.PasteTagsAction;
084import org.openstreetmap.josm.actions.PreferenceToggleAction;
085import org.openstreetmap.josm.actions.PreferencesAction;
086import org.openstreetmap.josm.actions.PurgeAction;
087import org.openstreetmap.josm.actions.RedoAction;
088import org.openstreetmap.josm.actions.ReorderImageryLayersAction;
089import org.openstreetmap.josm.actions.ReportBugAction;
090import org.openstreetmap.josm.actions.RestartAction;
091import org.openstreetmap.josm.actions.ReverseWayAction;
092import org.openstreetmap.josm.actions.SaveAction;
093import org.openstreetmap.josm.actions.SaveAsAction;
094import org.openstreetmap.josm.actions.SearchNotesDownloadAction;
095import org.openstreetmap.josm.actions.SelectAllAction;
096import org.openstreetmap.josm.actions.SelectNonBranchingWaySequencesAction;
097import org.openstreetmap.josm.actions.SessionSaveAsAction;
098import org.openstreetmap.josm.actions.ShowStatusReportAction;
099import 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                if (!(m.getComponent(i) instanceof JSeparator)) {
451                    continue;
452                }
453                // hide separator if the next menu item is one as well
454                ((JSeparator) m.getComponent(i)).setVisible(!(m.getComponent(i+1) instanceof JSeparator));
455            }
456            // hide separator at the end of the menu
457            if (m.getComponent(m.getComponentCount()-1) instanceof JSeparator) {
458                ((JSeparator) m.getComponent(m.getComponentCount()-1)).setVisible(false);
459            }
460        }
461    };
462
463    /**
464     * @return the default position of new top-level menus
465     * @since 6088
466     */
467    public int getDefaultMenuPos() {
468         return defaultMenuPos;
469    }
470
471    /**
472     * Add a JosmAction at the end of a menu.
473     *
474     * This method handles all the shortcut handling. It also makes sure that actions that are
475     * handled by the OS are not duplicated on the menu.
476     * @param menu the menu to add the action to
477     * @param action the action that should get a menu item
478     * @return the created menu item
479     */
480    public static JMenuItem add(JMenu menu, JosmAction action) {
481        return add(menu, action, false);
482    }
483
484    /**
485     * Add a JosmAction at the end of a menu.
486     *
487     * This method handles all the shortcut handling. It also makes sure that actions that are
488     * handled by the OS are not duplicated on the menu.
489     * @param menu the menu to add the action to
490     * @param action the action that should get a menu item
491     * @param isExpert whether the entry should only be visible if the expert mode is activated
492     * @return the created menu item
493     */
494    public static JMenuItem add(JMenu menu, JosmAction action, boolean isExpert) {
495        return add(menu, action, isExpert, null);
496    }
497
498    /**
499     * Add a JosmAction at the end of a menu.
500     *
501     * This method handles all the shortcut handling. It also makes sure that actions that are
502     * handled by the OS are not duplicated on the menu.
503     * @param menu the menu to add the action to
504     * @param action the action that should get a menu item
505     * @param isExpert whether the entry should only be visible if the expert mode is activated
506     * @param index  an integer specifying the position at which to add the action
507     * @return the created menu item
508     */
509    public static JMenuItem add(JMenu menu, JosmAction action, boolean isExpert, Integer index) {
510        if (action.getShortcut().isAutomatic())
511            return null;
512        final JMenuItem menuitem;
513        if (index == null) {
514            menuitem = menu.add(action);
515        } else {
516            menuitem = menu.insert(action, index);
517        }
518        if (isExpert) {
519            ExpertToggleAction.addVisibilitySwitcher(menuitem);
520        }
521        KeyStroke ks = action.getShortcut().getKeyStroke();
522        if (ks != null) {
523            menuitem.setAccelerator(ks);
524        }
525        // some menus are hidden before they are populated with some items by plugins
526        if (!menu.isVisible()) menu.setVisible(true);
527        return menuitem;
528    }
529
530    /**
531     * Add the JosmAction {@code actionToBeInserted} directly below {@code existingMenuEntryAction}.
532     *
533     * This method handles all the shortcut handling. It also makes sure that actions that are
534     * handled by the OS are not duplicated on the menu.
535     * @param menu the menu to add the action to
536     * @param actionToBeInserted the action that should get a menu item directly below {@code existingMenuEntryAction}
537     * @param isExpert whether the entry should only be visible if the expert mode is activated
538     * @param existingMenuEntryAction an action already added to the menu {@code menu},
539     * the action {@code actionToBeInserted} is added directly below
540     * @return the created menu item
541     */
542    public static JMenuItem addAfter(JMenu menu, JosmAction actionToBeInserted, boolean isExpert, JosmAction existingMenuEntryAction) {
543        int i = 0;
544        for (Component c : menu.getMenuComponents()) {
545            if (c instanceof JMenuItem && ((JMenuItem) c).getAction() == existingMenuEntryAction) {
546                break;
547            }
548            i++;
549        }
550        return add(menu, actionToBeInserted, isExpert, i + 1);
551    }
552
553    /**
554     * Add a JosmAction to a menu.
555     *
556     * This method handles all the shortcut handling. It also makes sure that actions that are
557     * handled by the OS are not duplicated on the menu.
558     * @param <E> group item enum type
559     * @param menu to add the action to
560     * @param action the action that should get a menu item
561     * @param group the item should be added to. Groups are split by a separator.
562     *        0 is the first group, -1 will add the item to the end.
563     * @return The created menu item
564     */
565    public static <E extends Enum<E>> JMenuItem add(JMenu menu, JosmAction action, Enum<E> group) {
566        if (action.getShortcut().isAutomatic())
567            return null;
568        int i = getInsertionIndexForGroup(menu, group.ordinal());
569        JMenuItem menuitem = (JMenuItem) menu.add(new JMenuItem(action), i);
570        KeyStroke ks = action.getShortcut().getKeyStroke();
571        if (ks != null) {
572            menuitem.setAccelerator(ks);
573        }
574        return menuitem;
575    }
576
577    /**
578     * Add a JosmAction to a menu and automatically prints accelerator if available.
579     * Also adds a checkbox that may be toggled.
580     * @param <E> group enum item type
581     * @param menu to add the action to
582     * @param action the action that should get a menu item
583     * @param group the item should be added to. Groups are split by a separator. Use
584     *        one of the enums that are defined for some of the menus to tell in which
585     *        group the item should go.
586     * @return The created menu item
587     */
588    public static <E extends Enum<E>> JCheckBoxMenuItem addWithCheckbox(JMenu menu, JosmAction action, Enum<E> group) {
589        int i = getInsertionIndexForGroup(menu, group.ordinal());
590        final JCheckBoxMenuItem mi = (JCheckBoxMenuItem) menu.add(new JCheckBoxMenuItem(action), i);
591        final KeyStroke ks = action.getShortcut().getKeyStroke();
592        if (ks != null) {
593            mi.setAccelerator(ks);
594        }
595        return mi;
596    }
597
598    /**
599     * Finds the correct insertion index for a given group and adds separators if necessary
600     * @param menu menu
601     * @param group group number
602     * @return correct insertion index
603     */
604    private static int getInsertionIndexForGroup(JMenu menu, int group) {
605        if (group < 0)
606            return -1;
607        // look for separator that *ends* the group (or stop at end of menu)
608        int i;
609        for (i = 0; i < menu.getItemCount() && group >= 0; i++) {
610            if (menu.getItem(i) == null) {
611                group--;
612            }
613        }
614        // insert before separator that ends the group
615        if (group < 0) {
616            i--;
617        }
618        // not enough separators have been found, add them
619        while (group > 0) {
620            menu.addSeparator();
621            group--;
622            i++;
623        }
624        return i;
625    }
626
627    /**
628     * Creates a menu and adds it on the given position to the main menu.
629     *
630     * @param name              the untranslated name (used as identifier for shortcut registration)
631     * @param translatedName    the translated menu name (use {@code I18n.trc("menu", name)} to allow better internationalization
632     * @param mnemonicKey       the mnemonic key to register
633     * @param position          the position in the main menu
634     * @param relativeHelpTopic the relative help topic
635     * @return the newly created menu
636     */
637    public JMenu addMenu(String name, String translatedName, int mnemonicKey, int position, String relativeHelpTopic) {
638        final JMenu menu = new JMenu(translatedName);
639        if (!GraphicsEnvironment.isHeadless()) {
640            MenuScroller.setScrollerFor(menu);
641        }
642        return addMenu(menu, name, mnemonicKey, position, relativeHelpTopic);
643    }
644
645    /**
646     * Adds the given menu on the given position to the main menu.
647     * @param <T> menu type
648     *
649     * @param menu              the menu to add
650     * @param name              the untranslated name (used as identifier for shortcut registration)
651     * @param mnemonicKey       the mnemonic key to register
652     * @param position          the position in the main menu
653     * @param relativeHelpTopic the relative help topic
654     * @return the given {@code }menu}
655     */
656    public <T extends JMenu> T addMenu(T menu, String name, int mnemonicKey, int position, String relativeHelpTopic) {
657        Shortcut.registerShortcut("menu:" + name, tr("Menu: {0}", name), mnemonicKey,
658                Shortcut.MNEMONIC).setMnemonic(menu);
659        add(menu, position);
660        menu.putClientProperty("help", relativeHelpTopic);
661        return menu;
662    }
663
664    /**
665     * Initialize the main menu.
666     * @since 10340
667     */
668    // CHECKSTYLE.OFF: ExecutableStatementCountCheck
669    public void initialize() {
670        moreToolsMenu.setVisible(false);
671        dataMenu.setVisible(false);
672        gpsMenu.setVisible(false);
673
674        add(fileMenu, newAction);
675        add(fileMenu, openFile);
676        fileMenu.add(recentlyOpened);
677        add(fileMenu, openLocation);
678        add(fileMenu, deleteLayerAction);
679        fileMenu.addSeparator();
680        add(fileMenu, save);
681        add(fileMenu, saveAs);
682        sessionSaveAs = new SessionSaveAsAction();
683        ExpertToggleAction.addVisibilitySwitcher(fileMenu.add(sessionSaveAs));
684        add(fileMenu, gpxExport, true);
685        fileMenu.addSeparator();
686        add(fileMenu, download);
687        add(fileMenu, downloadInView, true);
688        add(fileMenu, downloadAlongWay);
689        add(fileMenu, downloadPrimitive);
690        add(fileMenu, searchNotes);
691        add(fileMenu, downloadNotesInView);
692        add(fileMenu, downloadReferrers);
693        add(fileMenu, update);
694        add(fileMenu, updateSelection);
695        add(fileMenu, updateModified);
696        fileMenu.addSeparator();
697        add(fileMenu, upload);
698        add(fileMenu, uploadSelection);
699        Component sep = new JPopupMenu.Separator();
700        fileMenu.add(sep);
701        ExpertToggleAction.addVisibilitySwitcher(sep);
702        add(fileMenu, closeChangesetAction, true);
703        fileMenu.addSeparator();
704        add(fileMenu, restart);
705        add(fileMenu, exit);
706
707        add(editMenu, undo);
708        UndoRedoHandler.getInstance().addCommandQueueListener(undo);
709        add(editMenu, redo);
710        UndoRedoHandler.getInstance().addCommandQueueListener(redo);
711        editMenu.addSeparator();
712        add(editMenu, copy);
713        add(editMenu, copyCoordinates, true);
714        add(editMenu, paste);
715        add(editMenu, pasteAtSource, true);
716        add(editMenu, pasteTags);
717        add(editMenu, duplicate);
718        add(editMenu, delete);
719        add(editMenu, purge, true);
720        editMenu.addSeparator();
721        add(editMenu, merge);
722        add(editMenu, mergeSelected);
723        editMenu.addSeparator();
724        add(editMenu, search);
725        add(editMenu, presetSearchPrimitiveAction);
726        editMenu.addSeparator();
727        add(editMenu, preferences);
728
729        // -- wireframe toggle action
730        final JCheckBoxMenuItem wireframe = new JCheckBoxMenuItem(wireFrameToggleAction);
731        viewMenu.add(wireframe);
732        wireframe.setAccelerator(wireFrameToggleAction.getShortcut().getKeyStroke());
733        wireFrameToggleAction.addButtonModel(wireframe.getModel());
734        final JCheckBoxMenuItem hatchAreaOutsideDownloadMenuItem = drawBoundariesOfDownloadedDataAction.getCheckbox();
735        viewMenu.add(hatchAreaOutsideDownloadMenuItem);
736        ExpertToggleAction.addVisibilitySwitcher(hatchAreaOutsideDownloadMenuItem);
737
738        viewMenu.add(new MapPaintMenu());
739        viewMenu.addSeparator();
740        add(viewMenu, new ZoomInAction());
741        add(viewMenu, new ZoomOutAction());
742        viewMenu.addSeparator();
743        for (AutoScaleMode mode : AutoScaleMode.values()) {
744            AutoScaleAction autoScaleAction = new AutoScaleAction(mode);
745            autoScaleActions.put(mode.getEnglishLabel(), autoScaleAction);
746            add(viewMenu, autoScaleAction);
747        }
748
749        // -- viewport follow toggle action
750        ViewportFollowToggleAction viewportFollowToggleAction = new ViewportFollowToggleAction();
751        final JCheckBoxMenuItem vft = new JCheckBoxMenuItem(viewportFollowToggleAction);
752        ExpertToggleAction.addVisibilitySwitcher(vft);
753        viewMenu.add(vft);
754        vft.setAccelerator(viewportFollowToggleAction.getShortcut().getKeyStroke());
755        viewportFollowToggleAction.addButtonModel(vft.getModel());
756
757        if (PlatformManager.getPlatform().canFullscreen()) {
758            // -- fullscreen toggle action
759            fullscreenToggleAction = new FullscreenToggleAction();
760            final JCheckBoxMenuItem fullscreen = new JCheckBoxMenuItem(fullscreenToggleAction);
761            viewMenu.addSeparator();
762            viewMenu.add(fullscreen);
763            fullscreen.setAccelerator(fullscreenToggleAction.getShortcut().getKeyStroke());
764            fullscreenToggleAction.addButtonModel(fullscreen.getModel());
765        }
766
767        add(viewMenu, jumpToAct, true);
768        viewMenu.addSeparator();
769        add(viewMenu, info);
770        add(viewMenu, infoweb);
771        add(viewMenu, historyinfo);
772        add(viewMenu, historyinfoweb);
773        viewMenu.addSeparator();
774        viewMenu.add(new PreferenceToggleAction(tr("Main toolbar"),
775                tr("Toggles the visibility of the main toolbar (i.e., the horizontal toolbar)"),
776                "toolbar.visible", true).getCheckbox());
777        viewMenu.add(new PreferenceToggleAction(tr("Edit toolbar"),
778                tr("Toggles the visibility of the edit toolbar (i.e., the vertical tool)"),
779                "sidetoolbar.visible", true).getCheckbox());
780        // -- dialogs panel toggle action
781        final JCheckBoxMenuItem dialogsToggle = new JCheckBoxMenuItem(dialogsToggleAction);
782        dialogsToggle.setAccelerator(dialogsToggleAction.getShortcut().getKeyStroke());
783        dialogsToggleAction.addButtonModel(dialogsToggle.getModel());
784        viewMenu.add(dialogsToggle);
785        viewMenu.addSeparator();
786        // -- expert mode toggle action
787        final JCheckBoxMenuItem expertItem = new JCheckBoxMenuItem(ExpertToggleAction.getInstance());
788        viewMenu.add(expertItem);
789        ExpertToggleAction.getInstance().addButtonModel(expertItem.getModel());
790
791        add(presetsMenu, presetSearchAction);
792        add(presetsMenu, presetSearchPrimitiveAction);
793        add(presetsMenu, PreferencesAction.forPreferenceSubTab(tr("Preset preferences"),
794                tr("Click to open the tagging presets tab in the preferences"), TaggingPresetPreference.class));
795        presetsMenu.addSeparator();
796
797        add(imageryMenu, reorderImageryLayersAction);
798        add(imageryMenu, PreferencesAction.forPreferenceTab(tr("Imagery preferences..."),
799                tr("Click to open the imagery tab in the preferences"), ImageryPreference.class));
800
801        add(selectionMenu, selectAll);
802        add(selectionMenu, unselectAll);
803        add(selectionMenu, nonBranchingWaySequences);
804
805        add(toolsMenu, splitWay);
806        add(toolsMenu, combineWay);
807        toolsMenu.addSeparator();
808        add(toolsMenu, reverseWay);
809        add(toolsMenu, simplifyWay);
810        toolsMenu.addSeparator();
811        add(toolsMenu, alignInCircle);
812        add(toolsMenu, alignInLine);
813        add(toolsMenu, distribute);
814        add(toolsMenu, ortho);
815        add(toolsMenu, mirror, true);
816        toolsMenu.addSeparator();
817        add(toolsMenu, followLine, true);
818        add(toolsMenu, addNode, true);
819        add(toolsMenu, moveNode, true);
820        add(toolsMenu, createCircle);
821        toolsMenu.addSeparator();
822        add(toolsMenu, mergeNodes);
823        add(toolsMenu, joinNodeWay);
824        add(toolsMenu, moveNodeOntoWay);
825        add(toolsMenu, unJoinNodeWay);
826        add(toolsMenu, unglueNodes);
827        toolsMenu.addSeparator();
828        add(toolsMenu, joinAreas);
829        add(toolsMenu, createMultipolygon);
830        add(toolsMenu, updateMultipolygon);
831
832        // -- changeset manager toggle action
833        final JCheckBoxMenuItem mi = MainMenu.addWithCheckbox(windowMenu, changesetManager,
834                MainMenu.WINDOW_MENU_GROUP.ALWAYS);
835        changesetManager.addButtonModel(mi.getModel());
836
837        if (!Config.getPref().getBoolean("audio.menuinvisible", false)) {
838            showAudioMenu(true);
839        }
840
841        Config.getPref().addPreferenceChangeListener(e -> {
842            if ("audio.menuinvisible".equals(e.getKey())) {
843                showAudioMenu(!Boolean.parseBoolean(e.getNewValue().toString()));
844            }
845        });
846
847        add(helpMenu, new MenuItemSearchDialog.Action());
848        helpMenu.addSeparator();
849        add(helpMenu, statusreport);
850        add(helpMenu, reportbug);
851        helpMenu.addSeparator();
852
853        add(helpMenu, help);
854        add(helpMenu, about);
855
856        windowMenu.addMenuListener(menuSeparatorHandler);
857
858        new EditLayerMenuEnabler(Arrays.asList(modeMenu, presetsMenu));
859    }
860    // CHECKSTYLE.ON: ExecutableStatementCountCheck
861
862    /**
863     * Search main menu for items with {@code textToFind} in title.
864     * @param textToFind The text to find
865     * @param skipPresets whether to skip the {@link #presetsMenu} in the search
866     * @return not null list of found menu items.
867     */
868    public List<JMenuItem> findMenuItems(String textToFind, boolean skipPresets) {
869        // Explicitly use default locale in this case, because we're looking for translated strings
870        textToFind = textToFind.toLowerCase(Locale.getDefault());
871        List<JMenuItem> result = new ArrayList<>();
872        for (int i = 0; i < getMenuCount(); i++) {
873            if (getMenu(i) != null && (!skipPresets || presetsMenu != getMenu(i))) {
874                findMenuItems(getMenu(i), textToFind, result);
875            }
876        }
877        return result;
878    }
879
880    /**
881     * Returns the {@link JCheckBoxMenuItem} for the given {@link MapMode}.
882     * @param mode map mode
883     * @return the {@code JCheckBoxMenuItem} for the given {@code MapMode}
884     * @since 15438
885     */
886    public Optional<JCheckBoxMenuItem> findMapModeMenuItem(MapMode mode) {
887        return Arrays.stream(modeMenu.getMenuComponents())
888                .filter(m -> m instanceof JCheckBoxMenuItem)
889                .map(m -> (JCheckBoxMenuItem) m)
890                .filter(m -> Objects.equals(mode, m.getAction()))
891                .findFirst();
892    }
893
894    /**
895     * Recursive walker for menu items. Only menu items with action are selected. If menu item
896     * contains {@code textToFind} it's appended to result.
897     * @param menu menu in which search will be performed
898     * @param textToFind The text to find
899     * @param result resulting list of menu items
900     */
901    private static void findMenuItems(final JMenu menu, final String textToFind, final List<JMenuItem> result) {
902        for (int i = 0; i < menu.getItemCount(); i++) {
903            JMenuItem menuItem = menu.getItem(i);
904            if (menuItem == null) continue;
905
906            // Explicitly use default locale in this case, because we're looking for translated strings
907            if (menuItem.getAction() != null && menuItem.getText().toLowerCase(Locale.getDefault()).contains(textToFind)) {
908                result.add(menuItem);
909            }
910
911            // Go recursive if needed
912            if (menuItem instanceof JMenu) {
913                findMenuItems((JMenu) menuItem, textToFind, result);
914            }
915        }
916    }
917
918    protected void showAudioMenu(boolean showMenu) {
919        if (showMenu && audioMenu == null) {
920            audioMenu = addMenu("Audio", /* I18N: mnemonic: U */ trc("menu", "Audio"), KeyEvent.VK_U, defaultMenuPos, ht("/Menu/Audio"));
921            add(audioMenu, audioPlayPause);
922            add(audioMenu, audioNext);
923            add(audioMenu, audioPrev);
924            add(audioMenu, audioFwd);
925            add(audioMenu, audioBack);
926            add(audioMenu, audioSlower);
927            add(audioMenu, audioFaster);
928            validate();
929        } else if (!showMenu && audioMenu != null) {
930            remove(audioMenu);
931            audioMenu.removeAll();
932            audioMenu = null;
933            validate();
934        }
935    }
936
937    static class EditLayerMenuEnabler implements ActiveLayerChangeListener {
938        private final Collection<JMenu> menus;
939
940        EditLayerMenuEnabler(Collection<JMenu> menus) {
941            this.menus = Objects.requireNonNull(menus);
942            MainApplication.getLayerManager().addAndFireActiveLayerChangeListener(this);
943        }
944
945        @Override
946        public void activeOrEditLayerChanged(ActiveLayerChangeEvent e) {
947            menus.forEach(m -> m.setEnabled(e.getSource().getEditLayer() != null));
948        }
949    }
950}