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

Last change on this file since 8855 was 8840, checked in by Don-vip, 9 years ago

sonar - squid:S3052 - Fields should not be initialized to default values

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