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

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

fix remaining checkstyle issues

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