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), /* I18N: mnemonic: I */ "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 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 menu to add the action to
538     * @param action the action that should get a menu item
539     * @param group the item should be added to. Groups are split by a separator.
540     *        0 is the first group, -1 will add the item to the end.
541     * @return The created menu item
542     */
543    public static <E extends Enum<E>> JMenuItem add(JMenu menu, JosmAction action, Enum<E> group) {
544        if (action.getShortcut().isAutomatic())
545            return null;
546        int i = getInsertionIndexForGroup(menu, group.ordinal());
547        JMenuItem menuitem = (JMenuItem) menu.add(new JMenuItem(action), i);
548        KeyStroke ks = action.getShortcut().getKeyStroke();
549        if (ks != null) {
550            menuitem.setAccelerator(ks);
551        }
552        return menuitem;
553    }
554
555    /**
556     * Add a JosmAction to a menu and automatically prints accelerator if available.
557     * Also adds a checkbox that may be toggled.
558     * @param menu to add the action to
559     * @param action the action that should get a menu item
560     * @param group the item should be added to. Groups are split by a separator. Use
561     *        one of the enums that are defined for some of the menus to tell in which
562     *        group the item should go.
563     * @return The created menu item
564     */
565    public static <E extends Enum<E>> JCheckBoxMenuItem addWithCheckbox(JMenu menu, JosmAction action, Enum<E> group) {
566        int i = getInsertionIndexForGroup(menu, group.ordinal());
567        final JCheckBoxMenuItem mi = (JCheckBoxMenuItem) menu.add(new JCheckBoxMenuItem(action), i);
568        final KeyStroke ks = action.getShortcut().getKeyStroke();
569        if (ks != null) {
570            mi.setAccelerator(ks);
571        }
572        return mi;
573    }
574
575    /** finds the correct insertion index for a given group and adds separators if necessary */
576    private static int getInsertionIndexForGroup(JMenu menu, int group) {
577        if (group < 0)
578            return -1;
579        // look for separator that *ends* the group (or stop at end of menu)
580        int i;
581        for (i = 0; i < menu.getItemCount() && group >= 0; i++) {
582            if (menu.getItem(i) == null) {
583                group--;
584            }
585        }
586        // insert before separator that ends the group
587        if (group < 0) {
588            i--;
589        }
590        // not enough separators have been found, add them
591        while (group > 0) {
592            menu.addSeparator();
593            group--;
594            i++;
595        }
596        return i;
597    }
598
599    /**
600     * Creates a menu and adds it on the given position to the main menu.
601     *
602     * @param name              the untranslated name (used as identifier for shortcut registration)
603     * @param translatedName    the translated menu name (use {@code I18n.trc("menu", name)} to allow better internationalization
604     * @param mnemonicKey       the mnemonic key to register
605     * @param position          the position in the main menu
606     * @param relativeHelpTopic the relative help topic
607     * @return the newly created menu
608     */
609    public JMenu addMenu(String name, String translatedName, int mnemonicKey, int position, String relativeHelpTopic) {
610        final JMenu menu = new JMenu(translatedName);
611        if (!GraphicsEnvironment.isHeadless()) {
612            MenuScroller.setScrollerFor(menu);
613        }
614        return addMenu(menu, name, mnemonicKey, position, relativeHelpTopic);
615    }
616
617    /**
618     * Adds the given menu on the given position to the main menu.
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}", getName()), mnemonicKey,
629                Shortcut.MNEMONIC).setMnemonic(menu);
630        add(menu, position);
631        menu.putClientProperty("help", relativeHelpTopic);
632        return menu;
633    }
634
635    /**
636     * Constructs a new {@code MainMenu}.
637     */
638    public MainMenu() {
639        moreToolsMenu.setVisible(false);
640        dataMenu.setVisible(false);
641        gpsMenu.setVisible(false);
642
643        add(fileMenu, newAction);
644        add(fileMenu, openFile);
645        fileMenu.add(recentlyOpened);
646        add(fileMenu, openLocation);
647        fileMenu.addSeparator();
648        add(fileMenu, save);
649        add(fileMenu, saveAs);
650        sessionSaveAs = new SessionSaveAsAction();
651        ExpertToggleAction.addVisibilitySwitcher(fileMenu.add(sessionSaveAs));
652        add(fileMenu, gpxExport, true);
653        fileMenu.addSeparator();
654        add(fileMenu, download);
655        add(fileMenu, overpassDownload, true);
656        add(fileMenu, downloadPrimitive);
657        add(fileMenu, searchNotes);
658        add(fileMenu, downloadNotesInView);
659        add(fileMenu, downloadReferrers);
660        add(fileMenu, update);
661        add(fileMenu, updateSelection);
662        add(fileMenu, updateModified);
663        fileMenu.addSeparator();
664        add(fileMenu, upload);
665        add(fileMenu, uploadSelection);
666        Component sep = new JPopupMenu.Separator();
667        fileMenu.add(sep);
668        ExpertToggleAction.addVisibilitySwitcher(sep);
669        add(fileMenu, closeChangesetAction, true);
670        fileMenu.addSeparator();
671        add(fileMenu, restart);
672        add(fileMenu, exit);
673
674        add(editMenu, undo);
675        Main.main.undoRedo.addCommandQueueListener(undo);
676        add(editMenu, redo);
677        Main.main.undoRedo.addCommandQueueListener(redo);
678        editMenu.addSeparator();
679        add(editMenu, copy);
680        add(editMenu, copyCoordinates, true);
681        add(editMenu, paste);
682        add(editMenu, pasteTags);
683        add(editMenu, duplicate);
684        add(editMenu, delete);
685        add(editMenu, purge, true);
686        editMenu.addSeparator();
687        add(editMenu, merge);
688        add(editMenu, mergeSelected);
689        editMenu.addSeparator();
690        add(editMenu, search);
691        add(editMenu, presetSearchPrimitiveAction);
692        editMenu.addSeparator();
693        add(editMenu, preferences);
694
695        // -- wireframe toggle action
696        final JCheckBoxMenuItem wireframe = new JCheckBoxMenuItem(wireFrameToggleAction);
697        viewMenu.add(wireframe);
698        wireframe.setAccelerator(wireFrameToggleAction.getShortcut().getKeyStroke());
699        wireFrameToggleAction.addButtonModel(wireframe.getModel());
700
701        viewMenu.add(new MapPaintMenu());
702        viewMenu.addSeparator();
703        add(viewMenu, new ZoomInAction());
704        add(viewMenu, new ZoomOutAction());
705        viewMenu.addSeparator();
706        for (String mode : AutoScaleAction.MODES) {
707            AutoScaleAction autoScaleAction = new AutoScaleAction(mode);
708            autoScaleActions.put(mode, autoScaleAction);
709            add(viewMenu, autoScaleAction);
710        }
711
712        // -- viewport follow toggle action
713        ViewportFollowToggleAction viewportFollowToggleAction = new ViewportFollowToggleAction();
714        final JCheckBoxMenuItem vft = new JCheckBoxMenuItem(viewportFollowToggleAction);
715        ExpertToggleAction.addVisibilitySwitcher(vft);
716        viewMenu.add(vft);
717        vft.setAccelerator(viewportFollowToggleAction.getShortcut().getKeyStroke());
718        viewportFollowToggleAction.addButtonModel(vft.getModel());
719
720        if (Main.platform.canFullscreen()) {
721            // -- fullscreen toggle action
722            fullscreenToggleAction = new FullscreenToggleAction();
723            final JCheckBoxMenuItem fullscreen = new JCheckBoxMenuItem(fullscreenToggleAction);
724            viewMenu.addSeparator();
725            viewMenu.add(fullscreen);
726            fullscreen.setAccelerator(fullscreenToggleAction.getShortcut().getKeyStroke());
727            fullscreenToggleAction.addButtonModel(fullscreen.getModel());
728        }
729
730        // -- dialogs panel toggle action
731        final JCheckBoxMenuItem dialogsToggle = new JCheckBoxMenuItem(dialogsToggleAction);
732        dialogsToggle.setAccelerator(dialogsToggleAction.getShortcut().getKeyStroke());
733        dialogsToggleAction.addButtonModel(dialogsToggle.getModel());
734        viewMenu.add(dialogsToggle);
735
736        add(viewMenu, jumpToAct, true);
737        viewMenu.addSeparator();
738        add(viewMenu, info);
739        add(viewMenu, infoweb);
740        add(viewMenu, historyinfo);
741        add(viewMenu, historyinfoweb);
742        viewMenu.addSeparator();
743        viewMenu.add(new PreferenceToggleAction(tr("Main toolbar"),
744                tr("Toggles the visibility of the main toolbar (i.e., the horizontal toolbar)"),
745                "toolbar.visible", true).getCheckbox());
746        viewMenu.add(new PreferenceToggleAction(tr("Edit toolbar"),
747                tr("Toggles the visibility of the edit toolbar (i.e., the vertical tool)"),
748                "sidetoolbar.visible", true).getCheckbox());
749        // -- expert mode toggle action
750        final JCheckBoxMenuItem expertItem = new JCheckBoxMenuItem(ExpertToggleAction.getInstance());
751        viewMenu.add(expertItem);
752        ExpertToggleAction.getInstance().addButtonModel(expertItem.getModel());
753
754        add(presetsMenu, presetSearchAction);
755        add(presetsMenu, presetSearchPrimitiveAction);
756        add(presetsMenu, PreferencesAction.forPreferenceSubTab(tr("Preset preferences"),
757                tr("Click to open the tagging presets tab in the preferences"), TaggingPresetPreference.class));
758        presetsMenu.addSeparator();
759
760        add(imageryMenu, PreferencesAction.forPreferenceTab(tr("Imagery preferences"),
761                tr("Click to open the imagery tab in the preferences"), ImageryPreference.class));
762
763        add(selectionMenu, selectAll);
764        add(selectionMenu, unselectAll);
765        add(selectionMenu, nonBranchingWaySequences);
766
767        add(toolsMenu, splitWay);
768        add(toolsMenu, combineWay);
769        toolsMenu.addSeparator();
770        add(toolsMenu, reverseWay);
771        add(toolsMenu, simplifyWay);
772        toolsMenu.addSeparator();
773        add(toolsMenu, alignInCircle);
774        add(toolsMenu, alignInLine);
775        add(toolsMenu, distribute);
776        add(toolsMenu, ortho);
777        add(toolsMenu, mirror, true);
778        toolsMenu.addSeparator();
779        add(toolsMenu, followLine, true);
780        add(toolsMenu, addNode, true);
781        add(toolsMenu, moveNode, true);
782        add(toolsMenu, createCircle);
783        toolsMenu.addSeparator();
784        add(toolsMenu, mergeNodes);
785        add(toolsMenu, joinNodeWay);
786        add(toolsMenu, moveNodeOntoWay);
787        add(toolsMenu, unJoinNodeWay);
788        add(toolsMenu, unglueNodes);
789        toolsMenu.addSeparator();
790        add(toolsMenu, joinAreas);
791        add(toolsMenu, createMultipolygon);
792        add(toolsMenu, updateMultipolygon);
793
794        // -- changeset manager toggle action
795        final JCheckBoxMenuItem mi = MainMenu.addWithCheckbox(windowMenu, changesetManager,
796                MainMenu.WINDOW_MENU_GROUP.ALWAYS);
797        changesetManager.addButtonModel(mi.getModel());
798
799        if (!Main.pref.getBoolean("audio.menuinvisible", false)) {
800            showAudioMenu(true);
801        }
802
803        Main.pref.addPreferenceChangeListener(new PreferenceChangedListener() {
804            @Override
805            public void preferenceChanged(PreferenceChangeEvent e) {
806                if ("audio.menuinvisible".equals(e.getKey())) {
807                    showAudioMenu(!Boolean.parseBoolean(e.getNewValue().toString()));
808                }
809            }
810        });
811
812        helpMenu.add(statusreport);
813        helpMenu.add(reportbug);
814        helpMenu.addSeparator();
815
816        // FIXME why is help not a JosmAction?
817        helpMenu.add(help).setAccelerator(Shortcut.registerShortcut("system:help", tr("Help"), KeyEvent.VK_F1,
818                Shortcut.DIRECT).getKeyStroke());
819        add(helpMenu, about);
820        add(Box.createHorizontalGlue());
821        final DisableShortcutsOnFocusGainedTextField searchField = createSearchField();
822        add(searchField);
823
824        // Do not let search field take the focus automatically
825        setFocusTraversalPolicyProvider(true);
826        setFocusTraversalPolicy(new DefaultFocusTraversalPolicy() {
827            @Override
828            protected boolean accept(Component aComponent) {
829                return super.accept(aComponent) && !searchField.equals(aComponent);
830            }
831        });
832
833        windowMenu.addMenuListener(menuSeparatorHandler);
834
835        new PresetsMenuEnabler(presetsMenu).refreshEnabled();
836    }
837
838    private int getMaximumAvailableWidth() {
839        int maxWidth = getSize().width;
840        for (int i = 0; i < getMenuCount(); i++) {
841            JMenu menu = getMenu(i);
842            if (menu != null) {
843                maxWidth -= menu.getPreferredSize().width;
844            }
845        }
846        return maxWidth;
847    }
848
849    /**
850     * Create search field.
851     * @return the search field
852     */
853    private DisableShortcutsOnFocusGainedTextField createSearchField() {
854        DisableShortcutsOnFocusGainedTextField searchField = new DisableShortcutsOnFocusGainedTextField() {
855            @Override
856            public Dimension getPreferredSize() {
857                // JMenuBar uses a BoxLayout and it doesn't seem possible to specify a size factor,
858                // so compute the preferred size dynamically
859                return new Dimension(Math.min(200, Math.max(25, getMaximumAvailableWidth())),
860                        helpMenu.getPreferredSize().height);
861            }
862        };
863        Shortcut searchFieldShortcut = Shortcut.registerShortcut("menu:search-field", tr("Search menu items"), KeyEvent.VK_R, Shortcut.MNEMONIC);
864        searchFieldShortcut.setFocusAccelerator(searchField);
865        searchField.setEditable(true);
866        searchField.setMaximumSize(new Dimension(200, helpMenu.getPreferredSize().height));
867        searchField.setHint(tr("Search menu items"));
868        searchField.setToolTipText(Main.platform.makeTooltip(tr("Search menu items"), searchFieldShortcut));
869        searchField.addKeyListener(new SearchFieldKeyListener());
870        searchField.getDocument().addDocumentListener(new SearchFieldTextListener(this, searchField));
871        return searchField;
872    }
873
874    /**
875     * Search main menu for items with {@code textToFind} in title.
876     * @param textToFind The text to find
877     * @return not null list of found menu items.
878     */
879    private List<JMenuItem> findMenuItems(String textToFind) {
880        // Explicitely use default locale in this case, because we're looking for translated strings
881        textToFind = textToFind.toLowerCase(Locale.getDefault());
882        List<JMenuItem> result = new ArrayList<>();
883
884        // Iterate over main menus
885        for (MenuElement menuElement : getSubElements()) {
886            if (!(menuElement instanceof JMenu)) continue;
887
888            JMenu mainMenuItem = (JMenu) menuElement;
889            if (mainMenuItem.getAction() != null && mainMenuItem.getText().toLowerCase(Locale.getDefault()).contains(textToFind)) {
890                result.add(mainMenuItem);
891            }
892
893            //Search recursively
894            findMenuItems(mainMenuItem, textToFind, result);
895        }
896        return result;
897    }
898
899    /**
900     * Recursive walker for menu items. Only menu items with action are selected. If menu item
901     * contains {@code textToFind} it's appended to result.
902     * @param menu menu in which search will be performed
903     * @param textToFind The text to find
904     * @param result resulting list ofmenu items
905     */
906    private static void findMenuItems(final JMenu menu, final String textToFind, final List<JMenuItem> result) {
907        for (int i = 0; i < menu.getItemCount(); i++) {
908            JMenuItem menuItem = menu.getItem(i);
909            if (menuItem == null) continue;
910
911            // Explicitely use default locale in this case, because we're looking for translated strings
912            if (menuItem.getAction() != null && menuItem.getText().toLowerCase(Locale.getDefault()).contains(textToFind)) {
913                result.add(menuItem);
914            }
915
916            // Go recursive if needed
917            if (menuItem instanceof JMenu) {
918                findMenuItems((JMenu) menuItem, textToFind, result);
919            }
920        }
921    }
922
923    protected void showAudioMenu(boolean showMenu) {
924        if (showMenu && audioMenu == null) {
925            audioMenu = addMenu("Audio", /* I18N: mnemonic: U */ trc("menu", "Audio"), KeyEvent.VK_U, defaultMenuPos, ht("/Menu/Audio"));
926            add(audioMenu, audioPlayPause);
927            add(audioMenu, audioNext);
928            add(audioMenu, audioPrev);
929            add(audioMenu, audioFwd);
930            add(audioMenu, audioBack);
931            add(audioMenu, audioSlower);
932            add(audioMenu, audioFaster);
933            validate();
934        } else if (!showMenu && audioMenu != null) {
935            remove(audioMenu);
936            audioMenu.removeAll();
937            audioMenu = null;
938            validate();
939        }
940    }
941
942    static class PresetsMenuEnabler implements MapView.LayerChangeListener {
943        private JMenu presetsMenu;
944
945        PresetsMenuEnabler(JMenu presetsMenu) {
946            MapView.addLayerChangeListener(this);
947            this.presetsMenu = presetsMenu;
948        }
949
950        /**
951         * Refreshes the enabled state
952         */
953        protected void refreshEnabled() {
954            presetsMenu.setEnabled(Main.main.hasEditLayer());
955        }
956
957        @Override
958        public void activeLayerChange(Layer oldLayer, Layer newLayer) {
959            refreshEnabled();
960        }
961
962        @Override
963        public void layerAdded(Layer newLayer) {
964            refreshEnabled();
965        }
966
967        @Override
968        public void layerRemoved(Layer oldLayer) {
969            refreshEnabled();
970        }
971    }
972
973    /**
974     * This listener is designed to handle ENTER key pressed in menu search field.
975     * When user presses Enter key then selected item of "searchResultsMenu" is triggered.
976     */
977    private static class SearchFieldKeyListener implements KeyListener {
978
979        @Override
980        public void keyPressed(KeyEvent e) {
981            if (e.getKeyCode() == KeyEvent.VK_ENTER) {
982                // On ENTER selected menu item must be triggered
983                MenuElement[] selection = MenuSelectionManager.defaultManager().getSelectedPath();
984                if (selection.length > 1) {
985                    MenuElement selectedElement = selection[selection.length-1];
986                    if (selectedElement instanceof JMenuItem) {
987                        JMenuItem selectedItem = (JMenuItem) selectedElement;
988                        Action menuAction = selectedItem.getAction();
989                        menuAction.actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, null));
990                        if (Main.isDebugEnabled()) {
991                            Main.debug(getClass().getName()+" consuming event "+e);
992                        }
993                        e.consume();
994                    }
995                }
996            }
997        }
998
999        @Override
1000        public void keyTyped(KeyEvent e) {
1001            // Not used
1002        }
1003
1004        @Override
1005        public void keyReleased(KeyEvent e) {
1006            // Not used
1007        }
1008    }
1009
1010    private class SearchFieldTextListener implements DocumentListener {
1011        private final JTextField searchField;
1012        private final MainMenu mainMenu;
1013        private String currentSearchText;
1014
1015        SearchFieldTextListener(MainMenu mainMenu, JTextField searchField) {
1016            this.mainMenu = mainMenu;
1017            this.searchField = searchField;
1018        }
1019
1020        @Override
1021        public void insertUpdate(DocumentEvent e) {
1022            doSearch(searchField.getText());
1023        }
1024
1025        @Override
1026        public void removeUpdate(DocumentEvent e) {
1027            doSearch(searchField.getText());
1028        }
1029
1030        @Override
1031        public void changedUpdate(DocumentEvent e) {
1032            doSearch(searchField.getText());
1033        }
1034
1035        //TODO: perform some delay (maybe 200 ms) before actual searching.
1036        void doSearch(String searchTerm) {
1037            // Explicitely use default locale in this case, because we're looking for translated strings
1038            searchTerm = searchTerm.trim().toLowerCase(Locale.getDefault());
1039
1040            if (searchTerm.equals(currentSearchText)) {
1041                return;
1042            }
1043            currentSearchText = searchTerm;
1044            if (searchTerm.isEmpty()) {
1045                // No text to search
1046                hideMenu();
1047                return;
1048            }
1049
1050            List<JMenuItem> searchResult = mainMenu.findMenuItems(currentSearchText);
1051            if (searchResult.isEmpty()) {
1052                // Nothing found
1053                hideMenu();
1054                return;
1055            }
1056
1057            if (searchResult.size() > 20) {
1058                // Too many items found...
1059                searchResult = searchResult.subList(0, 20);
1060            }
1061
1062            // Update Popup menu
1063            searchResultsMenu.removeAll();
1064            for (JMenuItem foundItem : searchResult) {
1065                searchResultsMenu.add(foundItem.getText()).setAction(foundItem.getAction());
1066            }
1067            // Put menu right under search field
1068            searchResultsMenu.pack();
1069            searchResultsMenu.show(mainMenu, searchField.getX(), searchField.getY() + searchField.getHeight());
1070
1071            // This is tricky. User still is able to edit search text. While Up and Down keys are handled by Popup Menu.
1072            searchField.requestFocusInWindow();
1073        }
1074
1075        private void hideMenu() {
1076            searchResultsMenu.setVisible(false);
1077        }
1078    }
1079}