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

Last change on this file since 9261 was 9261, checked in by stoecker, 8 years ago

I18n cleanup

  • Property svn:eol-style set to native
File size: 46.8 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.presets.TaggingPresetSearchAction;
133import org.openstreetmap.josm.gui.tagging.presets.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), /* untranslated name */ "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 final 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 <E> group item enum type
538 * @param menu to add the action to
539 * @param action the action that should get a menu item
540 * @param group the item should be added to. Groups are split by a separator.
541 * 0 is the first group, -1 will add the item to the end.
542 * @return The created menu item
543 */
544 public static <E extends Enum<E>> JMenuItem add(JMenu menu, JosmAction action, Enum<E> group) {
545 if (action.getShortcut().isAutomatic())
546 return null;
547 int i = getInsertionIndexForGroup(menu, group.ordinal());
548 JMenuItem menuitem = (JMenuItem) menu.add(new JMenuItem(action), i);
549 KeyStroke ks = action.getShortcut().getKeyStroke();
550 if (ks != null) {
551 menuitem.setAccelerator(ks);
552 }
553 return menuitem;
554 }
555
556 /**
557 * Add a JosmAction to a menu and automatically prints accelerator if available.
558 * Also adds a checkbox that may be toggled.
559 * @param <E> group enum item type
560 * @param menu to add the action to
561 * @param action the action that should get a menu item
562 * @param group the item should be added to. Groups are split by a separator. Use
563 * one of the enums that are defined for some of the menus to tell in which
564 * group the item should go.
565 * @return The created menu item
566 */
567 public static <E extends Enum<E>> JCheckBoxMenuItem addWithCheckbox(JMenu menu, JosmAction action, Enum<E> group) {
568 int i = getInsertionIndexForGroup(menu, group.ordinal());
569 final JCheckBoxMenuItem mi = (JCheckBoxMenuItem) menu.add(new JCheckBoxMenuItem(action), i);
570 final KeyStroke ks = action.getShortcut().getKeyStroke();
571 if (ks != null) {
572 mi.setAccelerator(ks);
573 }
574 return mi;
575 }
576
577 /**
578 * Finds the correct insertion index for a given group and adds separators if necessary
579 * @param menu menu
580 * @param group group number
581 * @return correct insertion index
582 */
583 private static int getInsertionIndexForGroup(JMenu menu, int group) {
584 if (group < 0)
585 return -1;
586 // look for separator that *ends* the group (or stop at end of menu)
587 int i;
588 for (i = 0; i < menu.getItemCount() && group >= 0; i++) {
589 if (menu.getItem(i) == null) {
590 group--;
591 }
592 }
593 // insert before separator that ends the group
594 if (group < 0) {
595 i--;
596 }
597 // not enough separators have been found, add them
598 while (group > 0) {
599 menu.addSeparator();
600 group--;
601 i++;
602 }
603 return i;
604 }
605
606 /**
607 * Creates a menu and adds it on the given position to the main menu.
608 *
609 * @param name the untranslated name (used as identifier for shortcut registration)
610 * @param translatedName the translated menu name (use {@code I18n.trc("menu", name)} to allow better internationalization
611 * @param mnemonicKey the mnemonic key to register
612 * @param position the position in the main menu
613 * @param relativeHelpTopic the relative help topic
614 * @return the newly created menu
615 */
616 public JMenu addMenu(String name, String translatedName, int mnemonicKey, int position, String relativeHelpTopic) {
617 final JMenu menu = new JMenu(translatedName);
618 if (!GraphicsEnvironment.isHeadless()) {
619 MenuScroller.setScrollerFor(menu);
620 }
621 return addMenu(menu, name, mnemonicKey, position, relativeHelpTopic);
622 }
623
624 /**
625 * Adds the given menu on the given position to the main menu.
626 * @param <T> menu type
627 *
628 * @param menu the menu to add
629 * @param name the untranslated name (used as identifier for shortcut registration)
630 * @param mnemonicKey the mnemonic key to register
631 * @param position the position in the main menu
632 * @param relativeHelpTopic the relative help topic
633 * @return the given {@code }menu}
634 */
635 public <T extends JMenu> T addMenu(T menu, String name, int mnemonicKey, int position, String relativeHelpTopic) {
636 Shortcut.registerShortcut("menu:" + name, tr("Menu: {0}", name), mnemonicKey,
637 Shortcut.MNEMONIC).setMnemonic(menu);
638 add(menu, position);
639 menu.putClientProperty("help", relativeHelpTopic);
640 return menu;
641 }
642
643 /**
644 * Constructs a new {@code MainMenu}.
645 */
646 public MainMenu() {
647 moreToolsMenu.setVisible(false);
648 dataMenu.setVisible(false);
649 gpsMenu.setVisible(false);
650
651 add(fileMenu, newAction);
652 add(fileMenu, openFile);
653 fileMenu.add(recentlyOpened);
654 add(fileMenu, openLocation);
655 fileMenu.addSeparator();
656 add(fileMenu, save);
657 add(fileMenu, saveAs);
658 sessionSaveAs = new SessionSaveAsAction();
659 ExpertToggleAction.addVisibilitySwitcher(fileMenu.add(sessionSaveAs));
660 add(fileMenu, gpxExport, true);
661 fileMenu.addSeparator();
662 add(fileMenu, download);
663 add(fileMenu, overpassDownload, true);
664 add(fileMenu, downloadPrimitive);
665 add(fileMenu, searchNotes);
666 add(fileMenu, downloadNotesInView);
667 add(fileMenu, downloadReferrers);
668 add(fileMenu, update);
669 add(fileMenu, updateSelection);
670 add(fileMenu, updateModified);
671 fileMenu.addSeparator();
672 add(fileMenu, upload);
673 add(fileMenu, uploadSelection);
674 Component sep = new JPopupMenu.Separator();
675 fileMenu.add(sep);
676 ExpertToggleAction.addVisibilitySwitcher(sep);
677 add(fileMenu, closeChangesetAction, true);
678 fileMenu.addSeparator();
679 add(fileMenu, restart);
680 add(fileMenu, exit);
681
682 add(editMenu, undo);
683 Main.main.undoRedo.addCommandQueueListener(undo);
684 add(editMenu, redo);
685 Main.main.undoRedo.addCommandQueueListener(redo);
686 editMenu.addSeparator();
687 add(editMenu, copy);
688 add(editMenu, copyCoordinates, true);
689 add(editMenu, paste);
690 add(editMenu, pasteTags);
691 add(editMenu, duplicate);
692 add(editMenu, delete);
693 add(editMenu, purge, true);
694 editMenu.addSeparator();
695 add(editMenu, merge);
696 add(editMenu, mergeSelected);
697 editMenu.addSeparator();
698 add(editMenu, search);
699 add(editMenu, presetSearchPrimitiveAction);
700 editMenu.addSeparator();
701 add(editMenu, preferences);
702
703 // -- wireframe toggle action
704 final JCheckBoxMenuItem wireframe = new JCheckBoxMenuItem(wireFrameToggleAction);
705 viewMenu.add(wireframe);
706 wireframe.setAccelerator(wireFrameToggleAction.getShortcut().getKeyStroke());
707 wireFrameToggleAction.addButtonModel(wireframe.getModel());
708
709 viewMenu.add(new MapPaintMenu());
710 viewMenu.addSeparator();
711 add(viewMenu, new ZoomInAction());
712 add(viewMenu, new ZoomOutAction());
713 viewMenu.addSeparator();
714 for (String mode : AutoScaleAction.MODES) {
715 AutoScaleAction autoScaleAction = new AutoScaleAction(mode);
716 autoScaleActions.put(mode, autoScaleAction);
717 add(viewMenu, autoScaleAction);
718 }
719
720 // -- viewport follow toggle action
721 ViewportFollowToggleAction viewportFollowToggleAction = new ViewportFollowToggleAction();
722 final JCheckBoxMenuItem vft = new JCheckBoxMenuItem(viewportFollowToggleAction);
723 ExpertToggleAction.addVisibilitySwitcher(vft);
724 viewMenu.add(vft);
725 vft.setAccelerator(viewportFollowToggleAction.getShortcut().getKeyStroke());
726 viewportFollowToggleAction.addButtonModel(vft.getModel());
727
728 if (Main.platform.canFullscreen()) {
729 // -- fullscreen toggle action
730 fullscreenToggleAction = new FullscreenToggleAction();
731 final JCheckBoxMenuItem fullscreen = new JCheckBoxMenuItem(fullscreenToggleAction);
732 viewMenu.addSeparator();
733 viewMenu.add(fullscreen);
734 fullscreen.setAccelerator(fullscreenToggleAction.getShortcut().getKeyStroke());
735 fullscreenToggleAction.addButtonModel(fullscreen.getModel());
736 }
737
738 // -- dialogs panel toggle action
739 final JCheckBoxMenuItem dialogsToggle = new JCheckBoxMenuItem(dialogsToggleAction);
740 dialogsToggle.setAccelerator(dialogsToggleAction.getShortcut().getKeyStroke());
741 dialogsToggleAction.addButtonModel(dialogsToggle.getModel());
742 viewMenu.add(dialogsToggle);
743
744 add(viewMenu, jumpToAct, true);
745 viewMenu.addSeparator();
746 add(viewMenu, info);
747 add(viewMenu, infoweb);
748 add(viewMenu, historyinfo);
749 add(viewMenu, historyinfoweb);
750 viewMenu.addSeparator();
751 viewMenu.add(new PreferenceToggleAction(tr("Main toolbar"),
752 tr("Toggles the visibility of the main toolbar (i.e., the horizontal toolbar)"),
753 "toolbar.visible", true).getCheckbox());
754 viewMenu.add(new PreferenceToggleAction(tr("Edit toolbar"),
755 tr("Toggles the visibility of the edit toolbar (i.e., the vertical tool)"),
756 "sidetoolbar.visible", true).getCheckbox());
757 // -- expert mode toggle action
758 final JCheckBoxMenuItem expertItem = new JCheckBoxMenuItem(ExpertToggleAction.getInstance());
759 viewMenu.add(expertItem);
760 ExpertToggleAction.getInstance().addButtonModel(expertItem.getModel());
761
762 add(presetsMenu, presetSearchAction);
763 add(presetsMenu, presetSearchPrimitiveAction);
764 add(presetsMenu, PreferencesAction.forPreferenceSubTab(tr("Preset preferences"),
765 tr("Click to open the tagging presets tab in the preferences"), TaggingPresetPreference.class));
766 presetsMenu.addSeparator();
767
768 add(imageryMenu, PreferencesAction.forPreferenceTab(tr("Imagery preferences"),
769 tr("Click to open the imagery tab in the preferences"), ImageryPreference.class));
770
771 add(selectionMenu, selectAll);
772 add(selectionMenu, unselectAll);
773 add(selectionMenu, nonBranchingWaySequences);
774
775 add(toolsMenu, splitWay);
776 add(toolsMenu, combineWay);
777 toolsMenu.addSeparator();
778 add(toolsMenu, reverseWay);
779 add(toolsMenu, simplifyWay);
780 toolsMenu.addSeparator();
781 add(toolsMenu, alignInCircle);
782 add(toolsMenu, alignInLine);
783 add(toolsMenu, distribute);
784 add(toolsMenu, ortho);
785 add(toolsMenu, mirror, true);
786 toolsMenu.addSeparator();
787 add(toolsMenu, followLine, true);
788 add(toolsMenu, addNode, true);
789 add(toolsMenu, moveNode, true);
790 add(toolsMenu, createCircle);
791 toolsMenu.addSeparator();
792 add(toolsMenu, mergeNodes);
793 add(toolsMenu, joinNodeWay);
794 add(toolsMenu, moveNodeOntoWay);
795 add(toolsMenu, unJoinNodeWay);
796 add(toolsMenu, unglueNodes);
797 toolsMenu.addSeparator();
798 add(toolsMenu, joinAreas);
799 add(toolsMenu, createMultipolygon);
800 add(toolsMenu, updateMultipolygon);
801
802 // -- changeset manager toggle action
803 final JCheckBoxMenuItem mi = MainMenu.addWithCheckbox(windowMenu, changesetManager,
804 MainMenu.WINDOW_MENU_GROUP.ALWAYS);
805 changesetManager.addButtonModel(mi.getModel());
806
807 if (!Main.pref.getBoolean("audio.menuinvisible", false)) {
808 showAudioMenu(true);
809 }
810
811 Main.pref.addPreferenceChangeListener(new PreferenceChangedListener() {
812 @Override
813 public void preferenceChanged(PreferenceChangeEvent e) {
814 if ("audio.menuinvisible".equals(e.getKey())) {
815 showAudioMenu(!Boolean.parseBoolean(e.getNewValue().toString()));
816 }
817 }
818 });
819
820 helpMenu.add(statusreport);
821 helpMenu.add(reportbug);
822 helpMenu.addSeparator();
823
824 // FIXME why is help not a JosmAction?
825 helpMenu.add(help).setAccelerator(Shortcut.registerShortcut("system:help", tr("Help"), KeyEvent.VK_F1,
826 Shortcut.DIRECT).getKeyStroke());
827 add(helpMenu, about);
828 add(Box.createHorizontalGlue());
829 final DisableShortcutsOnFocusGainedTextField searchField = createSearchField();
830 add(searchField);
831
832 // Do not let search field take the focus automatically
833 setFocusTraversalPolicyProvider(true);
834 setFocusTraversalPolicy(new DefaultFocusTraversalPolicy() {
835 @Override
836 protected boolean accept(Component aComponent) {
837 return super.accept(aComponent) && !searchField.equals(aComponent);
838 }
839 });
840
841 windowMenu.addMenuListener(menuSeparatorHandler);
842
843 new PresetsMenuEnabler(presetsMenu).refreshEnabled();
844 }
845
846 private int getMaximumAvailableWidth() {
847 int maxWidth = getSize().width;
848 for (int i = 0; i < getMenuCount(); i++) {
849 JMenu menu = getMenu(i);
850 if (menu != null) {
851 maxWidth -= menu.getPreferredSize().width;
852 }
853 }
854 return maxWidth;
855 }
856
857 /**
858 * Create search field.
859 * @return the search field
860 */
861 private DisableShortcutsOnFocusGainedTextField createSearchField() {
862 DisableShortcutsOnFocusGainedTextField searchField = new DisableShortcutsOnFocusGainedTextField() {
863 @Override
864 public Dimension getPreferredSize() {
865 // JMenuBar uses a BoxLayout and it doesn't seem possible to specify a size factor,
866 // so compute the preferred size dynamically
867 return new Dimension(Math.min(200, Math.max(25, getMaximumAvailableWidth())),
868 helpMenu.getPreferredSize().height);
869 }
870 };
871 Shortcut searchFieldShortcut = Shortcut.registerShortcut("menu:search-field", tr("Search menu items"), KeyEvent.VK_R, Shortcut.MNEMONIC);
872 searchFieldShortcut.setFocusAccelerator(searchField);
873 searchField.setEditable(true);
874 searchField.setMaximumSize(new Dimension(200, helpMenu.getPreferredSize().height));
875 searchField.setHint(tr("Search menu items"));
876 searchField.setToolTipText(Main.platform.makeTooltip(tr("Search menu items"), searchFieldShortcut));
877 searchField.addKeyListener(new SearchFieldKeyListener());
878 searchField.getDocument().addDocumentListener(new SearchFieldTextListener(this, searchField));
879 return searchField;
880 }
881
882 /**
883 * Search main menu for items with {@code textToFind} in title.
884 * @param textToFind The text to find
885 * @return not null list of found menu items.
886 */
887 private List<JMenuItem> findMenuItems(String textToFind) {
888 // Explicitely use default locale in this case, because we're looking for translated strings
889 textToFind = textToFind.toLowerCase(Locale.getDefault());
890 List<JMenuItem> result = new ArrayList<>();
891
892 // Iterate over main menus
893 for (MenuElement menuElement : getSubElements()) {
894 if (!(menuElement instanceof JMenu)) continue;
895
896 JMenu mainMenuItem = (JMenu) menuElement;
897 if (mainMenuItem.getAction() != null && mainMenuItem.getText().toLowerCase(Locale.getDefault()).contains(textToFind)) {
898 result.add(mainMenuItem);
899 }
900
901 //Search recursively
902 findMenuItems(mainMenuItem, textToFind, result);
903 }
904 return result;
905 }
906
907 /**
908 * Recursive walker for menu items. Only menu items with action are selected. If menu item
909 * contains {@code textToFind} it's appended to result.
910 * @param menu menu in which search will be performed
911 * @param textToFind The text to find
912 * @param result resulting list ofmenu items
913 */
914 private static void findMenuItems(final JMenu menu, final String textToFind, final List<JMenuItem> result) {
915 for (int i = 0; i < menu.getItemCount(); i++) {
916 JMenuItem menuItem = menu.getItem(i);
917 if (menuItem == null) continue;
918
919 // Explicitely use default locale in this case, because we're looking for translated strings
920 if (menuItem.getAction() != null && menuItem.getText().toLowerCase(Locale.getDefault()).contains(textToFind)) {
921 result.add(menuItem);
922 }
923
924 // Go recursive if needed
925 if (menuItem instanceof JMenu) {
926 findMenuItems((JMenu) menuItem, textToFind, result);
927 }
928 }
929 }
930
931 protected void showAudioMenu(boolean showMenu) {
932 if (showMenu && audioMenu == null) {
933 audioMenu = addMenu("Audio", /* I18N: mnemonic: U */ trc("menu", "Audio"), KeyEvent.VK_U, defaultMenuPos, ht("/Menu/Audio"));
934 add(audioMenu, audioPlayPause);
935 add(audioMenu, audioNext);
936 add(audioMenu, audioPrev);
937 add(audioMenu, audioFwd);
938 add(audioMenu, audioBack);
939 add(audioMenu, audioSlower);
940 add(audioMenu, audioFaster);
941 validate();
942 } else if (!showMenu && audioMenu != null) {
943 remove(audioMenu);
944 audioMenu.removeAll();
945 audioMenu = null;
946 validate();
947 }
948 }
949
950 static class PresetsMenuEnabler implements MapView.LayerChangeListener {
951 private final JMenu presetsMenu;
952
953 PresetsMenuEnabler(JMenu presetsMenu) {
954 MapView.addLayerChangeListener(this);
955 this.presetsMenu = presetsMenu;
956 }
957
958 /**
959 * Refreshes the enabled state
960 */
961 protected void refreshEnabled() {
962 presetsMenu.setEnabled(Main.main.hasEditLayer());
963 }
964
965 @Override
966 public void activeLayerChange(Layer oldLayer, Layer newLayer) {
967 refreshEnabled();
968 }
969
970 @Override
971 public void layerAdded(Layer newLayer) {
972 refreshEnabled();
973 }
974
975 @Override
976 public void layerRemoved(Layer oldLayer) {
977 refreshEnabled();
978 }
979 }
980
981 /**
982 * This listener is designed to handle ENTER key pressed in menu search field.
983 * When user presses Enter key then selected item of "searchResultsMenu" is triggered.
984 */
985 private static class SearchFieldKeyListener implements KeyListener {
986
987 @Override
988 public void keyPressed(KeyEvent e) {
989 if (e.getKeyCode() == KeyEvent.VK_ENTER) {
990 // On ENTER selected menu item must be triggered
991 MenuElement[] selection = MenuSelectionManager.defaultManager().getSelectedPath();
992 if (selection.length > 1) {
993 MenuElement selectedElement = selection[selection.length-1];
994 if (selectedElement instanceof JMenuItem) {
995 JMenuItem selectedItem = (JMenuItem) selectedElement;
996 Action menuAction = selectedItem.getAction();
997 menuAction.actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, null));
998 if (Main.isDebugEnabled()) {
999 Main.debug(getClass().getName()+" consuming event "+e);
1000 }
1001 e.consume();
1002 }
1003 }
1004 }
1005 }
1006
1007 @Override
1008 public void keyTyped(KeyEvent e) {
1009 // Not used
1010 }
1011
1012 @Override
1013 public void keyReleased(KeyEvent e) {
1014 // Not used
1015 }
1016 }
1017
1018 private class SearchFieldTextListener implements DocumentListener {
1019 private final JTextField searchField;
1020 private final MainMenu mainMenu;
1021 private String currentSearchText;
1022
1023 SearchFieldTextListener(MainMenu mainMenu, JTextField searchField) {
1024 this.mainMenu = mainMenu;
1025 this.searchField = searchField;
1026 }
1027
1028 @Override
1029 public void insertUpdate(DocumentEvent e) {
1030 doSearch(searchField.getText());
1031 }
1032
1033 @Override
1034 public void removeUpdate(DocumentEvent e) {
1035 doSearch(searchField.getText());
1036 }
1037
1038 @Override
1039 public void changedUpdate(DocumentEvent e) {
1040 doSearch(searchField.getText());
1041 }
1042
1043 //TODO: perform some delay (maybe 200 ms) before actual searching.
1044 void doSearch(String searchTerm) {
1045 // Explicitely use default locale in this case, because we're looking for translated strings
1046 searchTerm = searchTerm.trim().toLowerCase(Locale.getDefault());
1047
1048 if (searchTerm.equals(currentSearchText)) {
1049 return;
1050 }
1051 currentSearchText = searchTerm;
1052 if (searchTerm.isEmpty()) {
1053 // No text to search
1054 hideMenu();
1055 return;
1056 }
1057
1058 List<JMenuItem> searchResult = mainMenu.findMenuItems(currentSearchText);
1059 if (searchResult.isEmpty()) {
1060 // Nothing found
1061 hideMenu();
1062 return;
1063 }
1064
1065 if (searchResult.size() > 20) {
1066 // Too many items found...
1067 searchResult = searchResult.subList(0, 20);
1068 }
1069
1070 // Update Popup menu
1071 searchResultsMenu.removeAll();
1072 for (JMenuItem foundItem : searchResult) {
1073 searchResultsMenu.add(foundItem.getText()).setAction(foundItem.getAction());
1074 }
1075 // Put menu right under search field
1076 searchResultsMenu.pack();
1077 searchResultsMenu.show(mainMenu, searchField.getX(), searchField.getY() + searchField.getHeight());
1078
1079 // This is tricky. User still is able to edit search text. While Up and Down keys are handled by Popup Menu.
1080 searchField.requestFocusInWindow();
1081 }
1082
1083 private void hideMenu() {
1084 searchResultsMenu.setVisible(false);
1085 }
1086 }
1087}
Note: See TracBrowser for help on using the repository browser.