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