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

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

fix copyright/license headers globally

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