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