source: josm/trunk/src/org/openstreetmap/josm/gui/MainMenu.java @ 12641

Last change on this file since 12641 was 12641, checked in by Don-vip, 2 months ago

see #15182 - deprecate Main.main.undoRedo. Replacement: gui.MainApplication.undoRedo

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