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.DefaultFocusTraversalPolicy;
010import java.awt.Dimension;
011import java.awt.GraphicsEnvironment;
012import java.awt.event.ActionEvent;
013import java.awt.event.KeyEvent;
014import java.awt.event.KeyListener;
015import java.util.ArrayList;
016import java.util.HashMap;
017import java.util.List;
018import java.util.Locale;
019import java.util.Map;
020
021import javax.swing.Action;
022import javax.swing.Box;
023import javax.swing.JCheckBoxMenuItem;
024import javax.swing.JMenu;
025import javax.swing.JMenuBar;
026import javax.swing.JMenuItem;
027import javax.swing.JPopupMenu;
028import javax.swing.JSeparator;
029import javax.swing.JTextField;
030import javax.swing.KeyStroke;
031import javax.swing.MenuElement;
032import javax.swing.MenuSelectionManager;
033import javax.swing.event.DocumentEvent;
034import javax.swing.event.DocumentListener;
035import javax.swing.event.MenuEvent;
036import javax.swing.event.MenuListener;
037
038import org.openstreetmap.josm.Main;
039import org.openstreetmap.josm.actions.AboutAction;
040import org.openstreetmap.josm.actions.AddNodeAction;
041import org.openstreetmap.josm.actions.AlignInCircleAction;
042import org.openstreetmap.josm.actions.AlignInLineAction;
043import org.openstreetmap.josm.actions.AutoScaleAction;
044import org.openstreetmap.josm.actions.ChangesetManagerToggleAction;
045import org.openstreetmap.josm.actions.CloseChangesetAction;
046import org.openstreetmap.josm.actions.CombineWayAction;
047import org.openstreetmap.josm.actions.CopyAction;
048import org.openstreetmap.josm.actions.CopyCoordinatesAction;
049import org.openstreetmap.josm.actions.CreateCircleAction;
050import org.openstreetmap.josm.actions.CreateMultipolygonAction;
051import org.openstreetmap.josm.actions.DeleteAction;
052import org.openstreetmap.josm.actions.DialogsToggleAction;
053import org.openstreetmap.josm.actions.DistributeAction;
054import org.openstreetmap.josm.actions.DownloadAction;
055import org.openstreetmap.josm.actions.DownloadNotesInViewAction;
056import org.openstreetmap.josm.actions.DownloadPrimitiveAction;
057import org.openstreetmap.josm.actions.DownloadReferrersAction;
058import org.openstreetmap.josm.actions.DuplicateAction;
059import org.openstreetmap.josm.actions.ExitAction;
060import org.openstreetmap.josm.actions.ExpertToggleAction;
061import org.openstreetmap.josm.actions.FollowLineAction;
062import org.openstreetmap.josm.actions.FullscreenToggleAction;
063import org.openstreetmap.josm.actions.GpxExportAction;
064import org.openstreetmap.josm.actions.HelpAction;
065import org.openstreetmap.josm.actions.HistoryInfoAction;
066import org.openstreetmap.josm.actions.HistoryInfoWebAction;
067import org.openstreetmap.josm.actions.InfoAction;
068import org.openstreetmap.josm.actions.InfoWebAction;
069import org.openstreetmap.josm.actions.JoinAreasAction;
070import org.openstreetmap.josm.actions.JoinNodeWayAction;
071import org.openstreetmap.josm.actions.JosmAction;
072import org.openstreetmap.josm.actions.JumpToAction;
073import org.openstreetmap.josm.actions.MergeLayerAction;
074import org.openstreetmap.josm.actions.MergeNodesAction;
075import org.openstreetmap.josm.actions.MergeSelectionAction;
076import org.openstreetmap.josm.actions.MirrorAction;
077import org.openstreetmap.josm.actions.MoveAction;
078import org.openstreetmap.josm.actions.MoveNodeAction;
079import org.openstreetmap.josm.actions.NewAction;
080import org.openstreetmap.josm.actions.OpenFileAction;
081import org.openstreetmap.josm.actions.OpenLocationAction;
082import org.openstreetmap.josm.actions.OrthogonalizeAction;
083import org.openstreetmap.josm.actions.OrthogonalizeAction.Undo;
084import org.openstreetmap.josm.actions.OverpassDownloadAction;
085import org.openstreetmap.josm.actions.PasteAction;
086import org.openstreetmap.josm.actions.PasteTagsAction;
087import org.openstreetmap.josm.actions.PreferenceToggleAction;
088import org.openstreetmap.josm.actions.PreferencesAction;
089import org.openstreetmap.josm.actions.PurgeAction;
090import org.openstreetmap.josm.actions.RedoAction;
091import org.openstreetmap.josm.actions.ReportBugAction;
092import org.openstreetmap.josm.actions.RestartAction;
093import org.openstreetmap.josm.actions.ReverseWayAction;
094import org.openstreetmap.josm.actions.SaveAction;
095import org.openstreetmap.josm.actions.SaveAsAction;
096import org.openstreetmap.josm.actions.SearchNotesDownloadAction;
097import org.openstreetmap.josm.actions.SelectAllAction;
098import org.openstreetmap.josm.actions.SelectNonBranchingWaySequencesAction;
099import org.openstreetmap.josm.actions.SessionSaveAsAction;
100import org.openstreetmap.josm.actions.ShowStatusReportAction;
101import org.openstreetmap.josm.actions.SimplifyWayAction;
102import org.openstreetmap.josm.actions.SplitWayAction;
103import org.openstreetmap.josm.actions.ToggleGPXLinesAction;
104import org.openstreetmap.josm.actions.UnGlueAction;
105import org.openstreetmap.josm.actions.UnJoinNodeWayAction;
106import org.openstreetmap.josm.actions.UndoAction;
107import org.openstreetmap.josm.actions.UnselectAllAction;
108import org.openstreetmap.josm.actions.UpdateDataAction;
109import org.openstreetmap.josm.actions.UpdateModifiedAction;
110import org.openstreetmap.josm.actions.UpdateSelectionAction;
111import org.openstreetmap.josm.actions.UploadAction;
112import org.openstreetmap.josm.actions.UploadSelectionAction;
113import org.openstreetmap.josm.actions.ViewportFollowToggleAction;
114import org.openstreetmap.josm.actions.WireframeToggleAction;
115import org.openstreetmap.josm.actions.ZoomInAction;
116import org.openstreetmap.josm.actions.ZoomOutAction;
117import org.openstreetmap.josm.actions.audio.AudioBackAction;
118import org.openstreetmap.josm.actions.audio.AudioFasterAction;
119import org.openstreetmap.josm.actions.audio.AudioFwdAction;
120import org.openstreetmap.josm.actions.audio.AudioNextAction;
121import org.openstreetmap.josm.actions.audio.AudioPlayPauseAction;
122import org.openstreetmap.josm.actions.audio.AudioPrevAction;
123import org.openstreetmap.josm.actions.audio.AudioSlowerAction;
124import org.openstreetmap.josm.actions.search.SearchAction;
125import org.openstreetmap.josm.data.Preferences.PreferenceChangeEvent;
126import org.openstreetmap.josm.data.Preferences.PreferenceChangedListener;
127import org.openstreetmap.josm.gui.io.RecentlyOpenedFilesMenu;
128import org.openstreetmap.josm.gui.layer.Layer;
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.TaggingPresetSearchAction;
133import org.openstreetmap.josm.gui.tagging.presets.TaggingPresetSearchPrimitiveDialog;
134import org.openstreetmap.josm.gui.widgets.DisableShortcutsOnFocusGainedTextField;
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 / 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 from Overpass API... **/
169    public final OverpassDownloadAction overpassDownload = new OverpassDownloadAction();
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 Tags */
207    public final PasteTagsAction pasteTags = new PasteTagsAction();
208    /** Edit / Duplicate */
209    public final DuplicateAction duplicate = new DuplicateAction();
210    /** Edit / Delete */
211    public final DeleteAction delete = new DeleteAction();
212    /** Edit / Purge... */
213    public final JosmAction purge = new PurgeAction();
214    /** Edit / Merge layer */
215    public final MergeLayerAction merge = new MergeLayerAction();
216    /** Edit / Merge selection */
217    public final MergeSelectionAction mergeSelected = new MergeSelectionAction();
218    /** Edit / Search... */
219    public final SearchAction search = new SearchAction();
220    /** Edit / Preferences */
221    public final PreferencesAction preferences = new PreferencesAction();
222
223    /* View menu */
224    /** View / Wireframe View */
225    public final WireframeToggleAction wireFrameToggleAction = new WireframeToggleAction();
226    public final JosmAction toggleGPXLines = new ToggleGPXLinesAction();
227    /** View / Advanced info */
228    public final InfoAction info = new InfoAction();
229    /** View / Advanced info (web) */
230    public final InfoWebAction infoweb = new InfoWebAction();
231    /** View / History */
232    public final HistoryInfoAction historyinfo = new HistoryInfoAction();
233    /** View / History (web) */
234    public final HistoryInfoWebAction historyinfoweb = new HistoryInfoWebAction();
235    /** View / "Zoom to"... actions */
236    public final Map<String, AutoScaleAction> autoScaleActions = new HashMap<>();
237    /** View / Jump to position */
238    public final JumpToAction jumpToAct = new JumpToAction();
239
240    /* Tools menu */
241    /** Tools / Split Way */
242    public final SplitWayAction splitWay = new SplitWayAction();
243    /** Tools / Combine Way */
244    public final CombineWayAction combineWay = new CombineWayAction();
245    /** Tools / Reverse Ways */
246    public final ReverseWayAction reverseWay = new ReverseWayAction();
247    /** Tools / Simplify Way */
248    public final SimplifyWayAction simplifyWay = new SimplifyWayAction();
249    /** Tools / Align Nodes in Circle */
250    public final AlignInCircleAction alignInCircle = new AlignInCircleAction();
251    /** Tools / Align Nodes in Line */
252    public final AlignInLineAction alignInLine = new AlignInLineAction();
253    /** Tools / Distribute Nodes */
254    public final DistributeAction distribute = new DistributeAction();
255    /** Tools / Orthogonalize Shape */
256    public final OrthogonalizeAction ortho = new OrthogonalizeAction();
257    /** Orthogonalize undo. Action is not shown in the menu. Only triggered by shortcut */
258    public final Undo orthoUndo = new Undo();
259    /** Tools / Mirror */
260    public final MirrorAction mirror = new MirrorAction();
261    /** Tools / Follow line */
262    public final FollowLineAction followLine = new FollowLineAction();
263    /** Tools / Add Node... */
264    public final AddNodeAction addNode = new AddNodeAction();
265    /** Tools / Move Node... */
266    public final MoveNodeAction moveNode = new MoveNodeAction();
267    /** Tools / Create Circle */
268    public final CreateCircleAction createCircle = new CreateCircleAction();
269    /** Tools / Merge Nodes */
270    public final MergeNodesAction mergeNodes = new MergeNodesAction();
271    /** Tools / Join Node to Way */
272    public final JoinNodeWayAction joinNodeWay = JoinNodeWayAction.createJoinNodeToWayAction();
273    /** Tools / Join Way to Node */
274    public final JoinNodeWayAction moveNodeOntoWay = JoinNodeWayAction.createMoveNodeOntoWayAction();
275    /** Tools / Disconnect Node from Way */
276    public final UnJoinNodeWayAction unJoinNodeWay = new UnJoinNodeWayAction();
277    /** Tools / Unglue Ways */
278    public final UnGlueAction unglueNodes = new UnGlueAction();
279    /** Tools / Join overlapping Areas */
280    public final JoinAreasAction joinAreas = new JoinAreasAction();
281    /** Tools / Create multipolygon */
282    public final CreateMultipolygonAction createMultipolygon = new CreateMultipolygonAction(false);
283    /** Tools / Update multipolygon */
284    public final CreateMultipolygonAction updateMultipolygon = new CreateMultipolygonAction(true);
285
286    /* Selection menu */
287    /** Selection / Select All */
288    public final SelectAllAction selectAll = new SelectAllAction();
289    /** Selection / Unselect All */
290    public final UnselectAllAction unselectAll = new UnselectAllAction();
291    /** Selection / Non-branching way sequences */
292    public final SelectNonBranchingWaySequencesAction nonBranchingWaySequences = new SelectNonBranchingWaySequencesAction();
293
294    /* Audio menu */
295    /** Audio / Play/Pause */
296    public final JosmAction audioPlayPause = new AudioPlayPauseAction();
297    /** Audio / Next marker */
298    public final JosmAction audioNext = new AudioNextAction();
299    /** Audio / Previous Marker */
300    public final JosmAction audioPrev = new AudioPrevAction();
301    /** Audio / Forward */
302    public final JosmAction audioFwd = new AudioFwdAction();
303    /** Audio / Back */
304    public final JosmAction audioBack = new AudioBackAction();
305    /** Audio / Faster */
306    public final JosmAction audioFaster = new AudioFasterAction();
307    /** Audio / Slower */
308    public final JosmAction audioSlower = new AudioSlowerAction();
309
310    /* Windows Menu */
311    /** Windows / Changeset Manager */
312    public final ChangesetManagerToggleAction changesetManager = new ChangesetManagerToggleAction();
313
314    /* Help menu */
315    /** Help / Help */
316    public final HelpAction help = new HelpAction();
317    /** Help / About */
318    public final AboutAction about = new AboutAction();
319    /** Help / Show Status Report */
320    public final ShowStatusReportAction statusreport = new ShowStatusReportAction();
321    /** Help / Report bug */
322    public final ReportBugAction reportbug = new ReportBugAction();
323
324    /**
325     * fileMenu contains I/O actions
326     */
327    public final JMenu fileMenu = addMenu("File", /* I18N: mnemonic: F */ trc("menu", "File"), KeyEvent.VK_F, 0, ht("/Menu/File"));
328    /**
329     * editMenu contains editing actions
330     */
331    public final JMenu editMenu = addMenu("Edit", /* I18N: mnemonic: E */ trc("menu", "Edit"), KeyEvent.VK_E, 1, ht("/Menu/Edit"));
332    /**
333     * viewMenu contains display actions (zoom, map styles, etc.)
334     */
335    public final JMenu viewMenu = addMenu("View", /* I18N: mnemonic: V */ trc("menu", "View"), KeyEvent.VK_V, 2, ht("/Menu/View"));
336    /**
337     * toolsMenu contains different geometry manipulation actions from JOSM core (most used)
338     * The plugins should use other menus
339     */
340    public final JMenu toolsMenu = addMenu("Tools", /* I18N: mnemonic: T */ trc("menu", "Tools"), KeyEvent.VK_T, 3, ht("/Menu/Tools"));
341    /**
342     * moreToolsMenu contains geometry-related actions from all the plugins
343     * @since 6082 (moved from Utilsplugin2)
344     */
345    // CHECKSTYLE.OFF: LineLength
346    public final JMenu moreToolsMenu = addMenu("More tools", /* I18N: mnemonic: M */ trc("menu", "More tools"), KeyEvent.VK_M, 4, ht("/Menu/MoreTools"));
347    /**
348     * dataMenu contains plugin actions that are related to certain tagging schemes (addressing opening hours),
349     * importing external data and using external web APIs
350     * @since 6082
351     */
352    public final JMenu dataMenu = addMenu("Data", /* I18N: mnemonic: D */ trc("menu", "Data"), KeyEvent.VK_D, 5, ht("/Menu/Data"));
353    /**
354     * selectionMenu contains all actions related to selecting different objects
355     * @since 6082 (moved from Utilsplugin2)
356     */
357    public final JMenu selectionMenu = addMenu("Selection", /* I18N: mnemonic: N */ trc("menu", "Selection"), KeyEvent.VK_N, 6, ht("/Menu/Selection"));
358    /**
359     * presetsMenu contains presets actions (search, presets tree)
360     */
361    public final JMenu presetsMenu = addMenu("Presets", /* I18N: mnemonic: P */ trc("menu", "Presets"), KeyEvent.VK_P, 7, ht("/Menu/Presets"));
362    /**
363     * submenu in Imagery menu that contains plugin-managed additional imagery layers
364     * @since 6097
365     */
366    public final JMenu imagerySubMenu = new JMenu(tr("More..."));
367    /**
368     * imageryMenu contains all imagery-related actions
369     */
370    public final ImageryMenu imageryMenu = addMenu(new ImageryMenu(imagerySubMenu), /* untranslated name */ "Imagery", KeyEvent.VK_I, 8, ht("/Menu/Imagery"));
371    // CHECKSTYLE.ON: LineLength
372    /**
373     * gpsMenu contains all plugin actions that are related
374     * to using GPS data, including opening, uploading and real-time tracking
375     * @since 6082
376     */
377    public final JMenu gpsMenu = addMenu("GPS", /* I18N: mnemonic: G */ trc("menu", "GPS"), KeyEvent.VK_G, 9, ht("/Menu/GPS"));
378    /** the window menu is split into several groups. The first is for windows that can be opened from
379     * this menu any time, e.g. the changeset editor. The second group is for toggle dialogs and the third
380     * group is for currently open windows that cannot be toggled, e.g. relation editors. It's recommended
381     * to use WINDOW_MENU_GROUP to determine the group integer.
382     */
383    public final JMenu windowMenu = addMenu("Windows", /* I18N: mnemonic: W */ trc("menu", "Windows"), KeyEvent.VK_W, 10, ht("/Menu/Windows"));
384
385    /**
386     * audioMenu contains all audio-related actions. Be careful, this menu is not guaranteed to be displayed at all
387     */
388    public JMenu audioMenu;
389    /**
390     * helpMenu contains JOSM general actions (Help, About, etc.)
391     */
392    public final JMenu helpMenu = addMenu("Help", /* I18N: mnemonic: H */ trc("menu", "Help"), KeyEvent.VK_H, 11, ht("/Menu/Help"));
393
394    private static final int defaultMenuPos = 11;
395
396    public final JosmAction moveUpAction = new MoveAction(MoveAction.Direction.UP);
397    public final JosmAction moveDownAction = new MoveAction(MoveAction.Direction.DOWN);
398    public final JosmAction moveLeftAction = new MoveAction(MoveAction.Direction.LEFT);
399    public final JosmAction moveRightAction = new MoveAction(MoveAction.Direction.RIGHT);
400
401    public final TaggingPresetSearchAction presetSearchAction = new TaggingPresetSearchAction();
402    public final TaggingPresetSearchPrimitiveDialog.Action presetSearchPrimitiveAction = new TaggingPresetSearchPrimitiveDialog.Action();
403    public final DialogsToggleAction dialogsToggleAction = new DialogsToggleAction();
404    public FullscreenToggleAction fullscreenToggleAction;
405
406    /**
407     * Popup menu to display menu items search result.
408     */
409    private final JPopupMenu searchResultsMenu = new JPopupMenu();
410
411    /** this menu listener hides unnecessary JSeparators in a menu list but does not remove them.
412     * If at a later time the separators are required, they will be made visible again. Intended
413     * usage is make menus not look broken if separators are used to group the menu and some of
414     * these groups are empty.
415     */
416    public static final MenuListener menuSeparatorHandler = new MenuListener() {
417        @Override
418        public void menuCanceled(MenuEvent e) {}
419
420        @Override
421        public void menuDeselected(MenuEvent e) {}
422
423        @Override
424        public void menuSelected(MenuEvent a) {
425            if (!(a.getSource() instanceof JMenu))
426                return;
427            final JPopupMenu m = ((JMenu) a.getSource()).getPopupMenu();
428            for (int i = 0; i < m.getComponentCount()-1; i++) {
429                if (!(m.getComponent(i) instanceof JSeparator)) {
430                    continue;
431                }
432                // hide separator if the next menu item is one as well
433                ((JSeparator) m.getComponent(i)).setVisible(!(m.getComponent(i+1) instanceof JSeparator));
434            }
435            // hide separator at the end of the menu
436            if (m.getComponent(m.getComponentCount()-1) instanceof JSeparator) {
437                ((JSeparator) m.getComponent(m.getComponentCount()-1)).setVisible(false);
438            }
439        }
440    };
441
442    /**
443     * @return the default position of tnew top-level menus
444     * @since 6088
445     */
446    public int getDefaultMenuPos() {
447         return defaultMenuPos;
448    }
449
450    /**
451     * Add a JosmAction at the end of a menu.
452     *
453     * This method handles all the shortcut handling. It also makes sure that actions that are
454     * handled by the OS are not duplicated on the menu.
455     * @param menu the menu to add the action to
456     * @param action the action that should get a menu item
457     * @return the created menu item
458     */
459    public static JMenuItem add(JMenu menu, JosmAction action) {
460        return add(menu, action, false);
461    }
462
463    /**
464     * Add a JosmAction at the end of a menu.
465     *
466     * This method handles all the shortcut handling. It also makes sure that actions that are
467     * handled by the OS are not duplicated on the menu.
468     * @param menu the menu to add the action to
469     * @param action the action that should get a menu item
470     * @param isExpert whether the entry should only be visible if the expert mode is activated
471     * @return the created menu item
472     */
473    public static JMenuItem add(JMenu menu, JosmAction action, boolean isExpert) {
474        return add(menu, action, isExpert, null);
475    }
476
477    /**
478     * Add a JosmAction at the end of a menu.
479     *
480     * This method handles all the shortcut handling. It also makes sure that actions that are
481     * handled by the OS are not duplicated on the menu.
482     * @param menu the menu to add the action to
483     * @param action the action that should get a menu item
484     * @param isExpert whether the entry should only be visible if the expert mode is activated
485     * @param index  an integer specifying the position at which to add the action
486     * @return the created menu item
487     */
488    public static JMenuItem add(JMenu menu, JosmAction action, boolean isExpert, Integer index) {
489        if (action.getShortcut().isAutomatic())
490            return null;
491        final JMenuItem menuitem;
492        if (index == null) {
493            menuitem = menu.add(action);
494        } else {
495            menuitem = menu.insert(action, index);
496        }
497        if (isExpert) {
498            ExpertToggleAction.addVisibilitySwitcher(menuitem);
499        }
500        KeyStroke ks = action.getShortcut().getKeyStroke();
501        if (ks != null) {
502            menuitem.setAccelerator(ks);
503        }
504        // some menus are hidden before they are populated with some items by plugins
505        if (!menu.isVisible()) menu.setVisible(true);
506        return menuitem;
507    }
508
509    /**
510     * Add the JosmAction {@code actionToBeInserted} directly below {@code existingMenuEntryAction}.
511     *
512     * This method handles all the shortcut handling. It also makes sure that actions that are
513     * handled by the OS are not duplicated on the menu.
514     * @param menu the menu to add the action to
515     * @param actionToBeInserted the action that should get a menu item directly below {@code existingMenuEntryAction}
516     * @param isExpert whether the entry should only be visible if the expert mode is activated
517     * @param existingMenuEntryAction an action already added to the menu {@code menu},
518     * the action {@code actionToBeInserted} is added directly below
519     * @return the created menu item
520     */
521    public static JMenuItem addAfter(JMenu menu, JosmAction actionToBeInserted, boolean isExpert, JosmAction existingMenuEntryAction) {
522        int i = 0;
523        for (Component c : menu.getMenuComponents()) {
524            if (c instanceof JMenuItem && ((JMenuItem) c).getAction() == existingMenuEntryAction) {
525                break;
526            }
527            i++;
528        }
529        return add(menu, actionToBeInserted, isExpert, i + 1);
530    }
531
532    /**
533     * Add a JosmAction to a menu.
534     *
535     * This method handles all the shortcut handling. It also makes sure that actions that are
536     * handled by the OS are not duplicated on the menu.
537     * @param <E> group item enum type
538     * @param menu to add the action to
539     * @param action the action that should get a menu item
540     * @param group the item should be added to. Groups are split by a separator.
541     *        0 is the first group, -1 will add the item to the end.
542     * @return The created menu item
543     */
544    public static <E extends Enum<E>> JMenuItem add(JMenu menu, JosmAction action, Enum<E> group) {
545        if (action.getShortcut().isAutomatic())
546            return null;
547        int i = getInsertionIndexForGroup(menu, group.ordinal());
548        JMenuItem menuitem = (JMenuItem) menu.add(new JMenuItem(action), i);
549        KeyStroke ks = action.getShortcut().getKeyStroke();
550        if (ks != null) {
551            menuitem.setAccelerator(ks);
552        }
553        return menuitem;
554    }
555
556    /**
557     * Add a JosmAction to a menu and automatically prints accelerator if available.
558     * Also adds a checkbox that may be toggled.
559     * @param <E> group enum item type
560     * @param menu to add the action to
561     * @param action the action that should get a menu item
562     * @param group the item should be added to. Groups are split by a separator. Use
563     *        one of the enums that are defined for some of the menus to tell in which
564     *        group the item should go.
565     * @return The created menu item
566     */
567    public static <E extends Enum<E>> JCheckBoxMenuItem addWithCheckbox(JMenu menu, JosmAction action, Enum<E> group) {
568        int i = getInsertionIndexForGroup(menu, group.ordinal());
569        final JCheckBoxMenuItem mi = (JCheckBoxMenuItem) menu.add(new JCheckBoxMenuItem(action), i);
570        final KeyStroke ks = action.getShortcut().getKeyStroke();
571        if (ks != null) {
572            mi.setAccelerator(ks);
573        }
574        return mi;
575    }
576
577    /**
578     * Finds the correct insertion index for a given group and adds separators if necessary
579     * @param menu menu
580     * @param group group number
581     * @return correct insertion index
582     */
583    private static int getInsertionIndexForGroup(JMenu menu, int group) {
584        if (group < 0)
585            return -1;
586        // look for separator that *ends* the group (or stop at end of menu)
587        int i;
588        for (i = 0; i < menu.getItemCount() && group >= 0; i++) {
589            if (menu.getItem(i) == null) {
590                group--;
591            }
592        }
593        // insert before separator that ends the group
594        if (group < 0) {
595            i--;
596        }
597        // not enough separators have been found, add them
598        while (group > 0) {
599            menu.addSeparator();
600            group--;
601            i++;
602        }
603        return i;
604    }
605
606    /**
607     * Creates a menu and adds it on the given position to the main menu.
608     *
609     * @param name              the untranslated name (used as identifier for shortcut registration)
610     * @param translatedName    the translated menu name (use {@code I18n.trc("menu", name)} to allow better internationalization
611     * @param mnemonicKey       the mnemonic key to register
612     * @param position          the position in the main menu
613     * @param relativeHelpTopic the relative help topic
614     * @return the newly created menu
615     */
616    public JMenu addMenu(String name, String translatedName, int mnemonicKey, int position, String relativeHelpTopic) {
617        final JMenu menu = new JMenu(translatedName);
618        if (!GraphicsEnvironment.isHeadless()) {
619            MenuScroller.setScrollerFor(menu);
620        }
621        return addMenu(menu, name, mnemonicKey, position, relativeHelpTopic);
622    }
623
624    /**
625     * Adds the given menu on the given position to the main menu.
626     * @param <T> menu type
627     *
628     * @param menu              the menu to add
629     * @param name              the untranslated name (used as identifier for shortcut registration)
630     * @param mnemonicKey       the mnemonic key to register
631     * @param position          the position in the main menu
632     * @param relativeHelpTopic the relative help topic
633     * @return the given {@code }menu}
634     */
635    public <T extends JMenu> T addMenu(T menu, String name, int mnemonicKey, int position, String relativeHelpTopic) {
636        Shortcut.registerShortcut("menu:" + name, tr("Menu: {0}", name), mnemonicKey,
637                Shortcut.MNEMONIC).setMnemonic(menu);
638        add(menu, position);
639        menu.putClientProperty("help", relativeHelpTopic);
640        return menu;
641    }
642
643    /**
644     * Constructs a new {@code MainMenu}.
645     */
646    public MainMenu() {
647        moreToolsMenu.setVisible(false);
648        dataMenu.setVisible(false);
649        gpsMenu.setVisible(false);
650
651        add(fileMenu, newAction);
652        add(fileMenu, openFile);
653        fileMenu.add(recentlyOpened);
654        add(fileMenu, openLocation);
655        fileMenu.addSeparator();
656        add(fileMenu, save);
657        add(fileMenu, saveAs);
658        sessionSaveAs = new SessionSaveAsAction();
659        ExpertToggleAction.addVisibilitySwitcher(fileMenu.add(sessionSaveAs));
660        add(fileMenu, gpxExport, true);
661        fileMenu.addSeparator();
662        add(fileMenu, download);
663        add(fileMenu, overpassDownload, true);
664        add(fileMenu, downloadPrimitive);
665        add(fileMenu, searchNotes);
666        add(fileMenu, downloadNotesInView);
667        add(fileMenu, downloadReferrers);
668        add(fileMenu, update);
669        add(fileMenu, updateSelection);
670        add(fileMenu, updateModified);
671        fileMenu.addSeparator();
672        add(fileMenu, upload);
673        add(fileMenu, uploadSelection);
674        Component sep = new JPopupMenu.Separator();
675        fileMenu.add(sep);
676        ExpertToggleAction.addVisibilitySwitcher(sep);
677        add(fileMenu, closeChangesetAction, true);
678        fileMenu.addSeparator();
679        add(fileMenu, restart);
680        add(fileMenu, exit);
681
682        add(editMenu, undo);
683        Main.main.undoRedo.addCommandQueueListener(undo);
684        add(editMenu, redo);
685        Main.main.undoRedo.addCommandQueueListener(redo);
686        editMenu.addSeparator();
687        add(editMenu, copy);
688        add(editMenu, copyCoordinates, true);
689        add(editMenu, paste);
690        add(editMenu, pasteTags);
691        add(editMenu, duplicate);
692        add(editMenu, delete);
693        add(editMenu, purge, true);
694        editMenu.addSeparator();
695        add(editMenu, merge);
696        add(editMenu, mergeSelected);
697        editMenu.addSeparator();
698        add(editMenu, search);
699        add(editMenu, presetSearchPrimitiveAction);
700        editMenu.addSeparator();
701        add(editMenu, preferences);
702
703        // -- wireframe toggle action
704        final JCheckBoxMenuItem wireframe = new JCheckBoxMenuItem(wireFrameToggleAction);
705        viewMenu.add(wireframe);
706        wireframe.setAccelerator(wireFrameToggleAction.getShortcut().getKeyStroke());
707        wireFrameToggleAction.addButtonModel(wireframe.getModel());
708
709        viewMenu.add(new MapPaintMenu());
710        viewMenu.addSeparator();
711        add(viewMenu, new ZoomInAction());
712        add(viewMenu, new ZoomOutAction());
713        viewMenu.addSeparator();
714        for (String mode : AutoScaleAction.MODES) {
715            AutoScaleAction autoScaleAction = new AutoScaleAction(mode);
716            autoScaleActions.put(mode, autoScaleAction);
717            add(viewMenu, autoScaleAction);
718        }
719
720        // -- viewport follow toggle action
721        ViewportFollowToggleAction viewportFollowToggleAction = new ViewportFollowToggleAction();
722        final JCheckBoxMenuItem vft = new JCheckBoxMenuItem(viewportFollowToggleAction);
723        ExpertToggleAction.addVisibilitySwitcher(vft);
724        viewMenu.add(vft);
725        vft.setAccelerator(viewportFollowToggleAction.getShortcut().getKeyStroke());
726        viewportFollowToggleAction.addButtonModel(vft.getModel());
727
728        if (Main.platform.canFullscreen()) {
729            // -- fullscreen toggle action
730            fullscreenToggleAction = new FullscreenToggleAction();
731            final JCheckBoxMenuItem fullscreen = new JCheckBoxMenuItem(fullscreenToggleAction);
732            viewMenu.addSeparator();
733            viewMenu.add(fullscreen);
734            fullscreen.setAccelerator(fullscreenToggleAction.getShortcut().getKeyStroke());
735            fullscreenToggleAction.addButtonModel(fullscreen.getModel());
736        }
737
738        // -- dialogs panel toggle action
739        final JCheckBoxMenuItem dialogsToggle = new JCheckBoxMenuItem(dialogsToggleAction);
740        dialogsToggle.setAccelerator(dialogsToggleAction.getShortcut().getKeyStroke());
741        dialogsToggleAction.addButtonModel(dialogsToggle.getModel());
742        viewMenu.add(dialogsToggle);
743
744        add(viewMenu, jumpToAct, true);
745        viewMenu.addSeparator();
746        add(viewMenu, info);
747        add(viewMenu, infoweb);
748        add(viewMenu, historyinfo);
749        add(viewMenu, historyinfoweb);
750        viewMenu.addSeparator();
751        viewMenu.add(new PreferenceToggleAction(tr("Main toolbar"),
752                tr("Toggles the visibility of the main toolbar (i.e., the horizontal toolbar)"),
753                "toolbar.visible", true).getCheckbox());
754        viewMenu.add(new PreferenceToggleAction(tr("Edit toolbar"),
755                tr("Toggles the visibility of the edit toolbar (i.e., the vertical tool)"),
756                "sidetoolbar.visible", true).getCheckbox());
757        // -- expert mode toggle action
758        final JCheckBoxMenuItem expertItem = new JCheckBoxMenuItem(ExpertToggleAction.getInstance());
759        viewMenu.add(expertItem);
760        ExpertToggleAction.getInstance().addButtonModel(expertItem.getModel());
761
762        add(presetsMenu, presetSearchAction);
763        add(presetsMenu, presetSearchPrimitiveAction);
764        add(presetsMenu, PreferencesAction.forPreferenceSubTab(tr("Preset preferences"),
765                tr("Click to open the tagging presets tab in the preferences"), TaggingPresetPreference.class));
766        presetsMenu.addSeparator();
767
768        add(imageryMenu, PreferencesAction.forPreferenceTab(tr("Imagery preferences"),
769                tr("Click to open the imagery tab in the preferences"), ImageryPreference.class));
770
771        add(selectionMenu, selectAll);
772        add(selectionMenu, unselectAll);
773        add(selectionMenu, nonBranchingWaySequences);
774
775        add(toolsMenu, splitWay);
776        add(toolsMenu, combineWay);
777        toolsMenu.addSeparator();
778        add(toolsMenu, reverseWay);
779        add(toolsMenu, simplifyWay);
780        toolsMenu.addSeparator();
781        add(toolsMenu, alignInCircle);
782        add(toolsMenu, alignInLine);
783        add(toolsMenu, distribute);
784        add(toolsMenu, ortho);
785        add(toolsMenu, mirror, true);
786        toolsMenu.addSeparator();
787        add(toolsMenu, followLine, true);
788        add(toolsMenu, addNode, true);
789        add(toolsMenu, moveNode, true);
790        add(toolsMenu, createCircle);
791        toolsMenu.addSeparator();
792        add(toolsMenu, mergeNodes);
793        add(toolsMenu, joinNodeWay);
794        add(toolsMenu, moveNodeOntoWay);
795        add(toolsMenu, unJoinNodeWay);
796        add(toolsMenu, unglueNodes);
797        toolsMenu.addSeparator();
798        add(toolsMenu, joinAreas);
799        add(toolsMenu, createMultipolygon);
800        add(toolsMenu, updateMultipolygon);
801
802        // -- changeset manager toggle action
803        final JCheckBoxMenuItem mi = MainMenu.addWithCheckbox(windowMenu, changesetManager,
804                MainMenu.WINDOW_MENU_GROUP.ALWAYS);
805        changesetManager.addButtonModel(mi.getModel());
806
807        if (!Main.pref.getBoolean("audio.menuinvisible", false)) {
808            showAudioMenu(true);
809        }
810
811        Main.pref.addPreferenceChangeListener(new PreferenceChangedListener() {
812            @Override
813            public void preferenceChanged(PreferenceChangeEvent e) {
814                if ("audio.menuinvisible".equals(e.getKey())) {
815                    showAudioMenu(!Boolean.parseBoolean(e.getNewValue().toString()));
816                }
817            }
818        });
819
820        add(helpMenu, statusreport);
821        add(helpMenu, reportbug);
822        helpMenu.addSeparator();
823
824        add(helpMenu, help);
825        add(helpMenu, about);
826        add(Box.createHorizontalGlue());
827        final DisableShortcutsOnFocusGainedTextField searchField = createSearchField();
828        add(searchField);
829
830        // Do not let search field take the focus automatically
831        setFocusTraversalPolicyProvider(true);
832        setFocusTraversalPolicy(new DefaultFocusTraversalPolicy() {
833            @Override
834            protected boolean accept(Component aComponent) {
835                return super.accept(aComponent) && !searchField.equals(aComponent);
836            }
837        });
838
839        windowMenu.addMenuListener(menuSeparatorHandler);
840
841        new PresetsMenuEnabler(presetsMenu).refreshEnabled();
842    }
843
844    private int getMaximumAvailableWidth() {
845        int maxWidth = getSize().width;
846        for (int i = 0; i < getMenuCount(); i++) {
847            JMenu menu = getMenu(i);
848            if (menu != null) {
849                maxWidth -= menu.getPreferredSize().width;
850            }
851        }
852        return maxWidth;
853    }
854
855    /**
856     * Create search field.
857     * @return the search field
858     */
859    private DisableShortcutsOnFocusGainedTextField createSearchField() {
860        DisableShortcutsOnFocusGainedTextField searchField = new DisableShortcutsOnFocusGainedTextField() {
861            @Override
862            public Dimension getPreferredSize() {
863                // JMenuBar uses a BoxLayout and it doesn't seem possible to specify a size factor,
864                // so compute the preferred size dynamically
865                return new Dimension(Math.min(200, Math.max(25, getMaximumAvailableWidth())),
866                        helpMenu.getPreferredSize().height);
867            }
868        };
869        Shortcut searchFieldShortcut = Shortcut.registerShortcut("menu:search-field", tr("Search menu items"), KeyEvent.VK_R, Shortcut.MNEMONIC);
870        searchFieldShortcut.setFocusAccelerator(searchField);
871        searchField.setEditable(true);
872        searchField.setMaximumSize(new Dimension(200, helpMenu.getPreferredSize().height));
873        searchField.setHint(tr("Search menu items"));
874        searchField.setToolTipText(Main.platform.makeTooltip(tr("Search menu items"), searchFieldShortcut));
875        searchField.addKeyListener(new SearchFieldKeyListener());
876        searchField.getDocument().addDocumentListener(new SearchFieldTextListener(this, searchField));
877        return searchField;
878    }
879
880    /**
881     * Search main menu for items with {@code textToFind} in title.
882     * @param textToFind The text to find
883     * @return not null list of found menu items.
884     */
885    private List<JMenuItem> findMenuItems(String textToFind) {
886        // Explicitely use default locale in this case, because we're looking for translated strings
887        textToFind = textToFind.toLowerCase(Locale.getDefault());
888        List<JMenuItem> result = new ArrayList<>();
889
890        // Iterate over main menus
891        for (MenuElement menuElement : getSubElements()) {
892            if (!(menuElement instanceof JMenu)) continue;
893
894            JMenu mainMenuItem = (JMenu) menuElement;
895            if (mainMenuItem.getAction() != null && mainMenuItem.getText().toLowerCase(Locale.getDefault()).contains(textToFind)) {
896                result.add(mainMenuItem);
897            }
898
899            //Search recursively
900            findMenuItems(mainMenuItem, textToFind, result);
901        }
902        return result;
903    }
904
905    /**
906     * Recursive walker for menu items. Only menu items with action are selected. If menu item
907     * contains {@code textToFind} it's appended to result.
908     * @param menu menu in which search will be performed
909     * @param textToFind The text to find
910     * @param result resulting list ofmenu items
911     */
912    private static void findMenuItems(final JMenu menu, final String textToFind, final List<JMenuItem> result) {
913        for (int i = 0; i < menu.getItemCount(); i++) {
914            JMenuItem menuItem = menu.getItem(i);
915            if (menuItem == null) continue;
916
917            // Explicitely use default locale in this case, because we're looking for translated strings
918            if (menuItem.getAction() != null && menuItem.getText().toLowerCase(Locale.getDefault()).contains(textToFind)) {
919                result.add(menuItem);
920            }
921
922            // Go recursive if needed
923            if (menuItem instanceof JMenu) {
924                findMenuItems((JMenu) menuItem, textToFind, result);
925            }
926        }
927    }
928
929    protected void showAudioMenu(boolean showMenu) {
930        if (showMenu && audioMenu == null) {
931            audioMenu = addMenu("Audio", /* I18N: mnemonic: U */ trc("menu", "Audio"), KeyEvent.VK_U, defaultMenuPos, ht("/Menu/Audio"));
932            add(audioMenu, audioPlayPause);
933            add(audioMenu, audioNext);
934            add(audioMenu, audioPrev);
935            add(audioMenu, audioFwd);
936            add(audioMenu, audioBack);
937            add(audioMenu, audioSlower);
938            add(audioMenu, audioFaster);
939            validate();
940        } else if (!showMenu && audioMenu != null) {
941            remove(audioMenu);
942            audioMenu.removeAll();
943            audioMenu = null;
944            validate();
945        }
946    }
947
948    static class PresetsMenuEnabler implements MapView.LayerChangeListener {
949        private final JMenu presetsMenu;
950
951        PresetsMenuEnabler(JMenu presetsMenu) {
952            MapView.addLayerChangeListener(this);
953            this.presetsMenu = presetsMenu;
954        }
955
956        /**
957         * Refreshes the enabled state
958         */
959        protected void refreshEnabled() {
960            presetsMenu.setEnabled(Main.main.hasEditLayer());
961        }
962
963        @Override
964        public void activeLayerChange(Layer oldLayer, Layer newLayer) {
965            refreshEnabled();
966        }
967
968        @Override
969        public void layerAdded(Layer newLayer) {
970            refreshEnabled();
971        }
972
973        @Override
974        public void layerRemoved(Layer oldLayer) {
975            refreshEnabled();
976        }
977    }
978
979    /**
980     * This listener is designed to handle ENTER key pressed in menu search field.
981     * When user presses Enter key then selected item of "searchResultsMenu" is triggered.
982     */
983    private static class SearchFieldKeyListener implements KeyListener {
984
985        @Override
986        public void keyPressed(KeyEvent e) {
987            if (e.getKeyCode() == KeyEvent.VK_ENTER) {
988                // On ENTER selected menu item must be triggered
989                MenuElement[] selection = MenuSelectionManager.defaultManager().getSelectedPath();
990                if (selection.length > 1) {
991                    MenuElement selectedElement = selection[selection.length-1];
992                    if (selectedElement instanceof JMenuItem) {
993                        JMenuItem selectedItem = (JMenuItem) selectedElement;
994                        Action menuAction = selectedItem.getAction();
995                        menuAction.actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, null));
996                        if (Main.isDebugEnabled()) {
997                            Main.debug(getClass().getName()+" consuming event "+e);
998                        }
999                        e.consume();
1000                    }
1001                }
1002            }
1003        }
1004
1005        @Override
1006        public void keyTyped(KeyEvent e) {
1007            // Not used
1008        }
1009
1010        @Override
1011        public void keyReleased(KeyEvent e) {
1012            // Not used
1013        }
1014    }
1015
1016    private class SearchFieldTextListener implements DocumentListener {
1017        private final JTextField searchField;
1018        private final MainMenu mainMenu;
1019        private String currentSearchText;
1020
1021        SearchFieldTextListener(MainMenu mainMenu, JTextField searchField) {
1022            this.mainMenu = mainMenu;
1023            this.searchField = searchField;
1024        }
1025
1026        @Override
1027        public void insertUpdate(DocumentEvent e) {
1028            doSearch(searchField.getText());
1029        }
1030
1031        @Override
1032        public void removeUpdate(DocumentEvent e) {
1033            doSearch(searchField.getText());
1034        }
1035
1036        @Override
1037        public void changedUpdate(DocumentEvent e) {
1038            doSearch(searchField.getText());
1039        }
1040
1041        //TODO: perform some delay (maybe 200 ms) before actual searching.
1042        void doSearch(String searchTerm) {
1043            // Explicitely use default locale in this case, because we're looking for translated strings
1044            searchTerm = searchTerm.trim().toLowerCase(Locale.getDefault());
1045
1046            if (searchTerm.equals(currentSearchText)) {
1047                return;
1048            }
1049            currentSearchText = searchTerm;
1050            if (searchTerm.isEmpty()) {
1051                // No text to search
1052                hideMenu();
1053                return;
1054            }
1055
1056            List<JMenuItem> searchResult = mainMenu.findMenuItems(currentSearchText);
1057            if (searchResult.isEmpty()) {
1058                // Nothing found
1059                hideMenu();
1060                return;
1061            }
1062
1063            if (searchResult.size() > 20) {
1064                // Too many items found...
1065                searchResult = searchResult.subList(0, 20);
1066            }
1067
1068            // Update Popup menu
1069            searchResultsMenu.removeAll();
1070            for (JMenuItem foundItem : searchResult) {
1071                searchResultsMenu.add(foundItem.getText()).setAction(foundItem.getAction());
1072            }
1073            // Put menu right under search field
1074            searchResultsMenu.pack();
1075            searchResultsMenu.show(mainMenu, searchField.getX(), searchField.getY() + searchField.getHeight());
1076
1077            // This is tricky. User still is able to edit search text. While Up and Down keys are handled by Popup Menu.
1078            searchField.requestFocusInWindow();
1079        }
1080
1081        private void hideMenu() {
1082            searchResultsMenu.setVisible(false);
1083        }
1084    }
1085}