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