source: josm/trunk/src/org/openstreetmap/josm/tools/Shortcut.java@ 11915

Last change on this file since 11915 was 11553, checked in by Don-vip, 7 years ago

refactor handling of null values - use Java 8 Optional where possible

  • Property svn:eol-style set to native
File size: 22.1 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.tools;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.awt.event.KeyEvent;
7import java.util.ArrayList;
8import java.util.Arrays;
9import java.util.Comparator;
10import java.util.HashMap;
11import java.util.List;
12import java.util.Map;
13import java.util.Optional;
14import java.util.concurrent.CopyOnWriteArrayList;
15import java.util.function.Predicate;
16import java.util.stream.Collectors;
17
18import javax.swing.AbstractAction;
19import javax.swing.AbstractButton;
20import javax.swing.JMenu;
21import javax.swing.KeyStroke;
22import javax.swing.text.JTextComponent;
23
24import org.openstreetmap.josm.Main;
25import org.openstreetmap.josm.gui.util.GuiHelper;
26
27/**
28 * Global shortcut class.
29 *
30 * Note: This class represents a single shortcut, contains the factory to obtain
31 * shortcut objects from, manages shortcuts and shortcut collisions, and
32 * finally manages loading and saving shortcuts to/from the preferences.
33 *
34 * Action authors: You only need the {@link #registerShortcut} factory. Ignore everything else.
35 *
36 * All: Use only public methods that are also marked to be used. The others are
37 * public so the shortcut preferences can use them.
38 * @since 1084
39 */
40public final class Shortcut {
41 /** the unique ID of the shortcut */
42 private final String shortText;
43 /** a human readable description that will be shown in the preferences */
44 private String longText;
45 /** the key, the caller requested */
46 private final int requestedKey;
47 /** the group, the caller requested */
48 private final int requestedGroup;
49 /** the key that actually is used */
50 private int assignedKey;
51 /** the modifiers that are used */
52 private int assignedModifier;
53 /** true if it got assigned what was requested.
54 * (Note: modifiers will be ignored in favour of group when loading it from the preferences then.) */
55 private boolean assignedDefault;
56 /** true if the user changed this shortcut */
57 private boolean assignedUser;
58 /** true if the user cannot change this shortcut (Note: it also will not be saved into the preferences) */
59 private boolean automatic;
60 /** true if the user requested this shortcut to be set to its default value
61 * (will happen on next restart, as this shortcut will not be saved to the preferences) */
62 private boolean reset;
63
64 // simple constructor
65 private Shortcut(String shortText, String longText, int requestedKey, int requestedGroup, int assignedKey, int assignedModifier,
66 boolean assignedDefault, boolean assignedUser) {
67 this.shortText = shortText;
68 this.longText = longText;
69 this.requestedKey = requestedKey;
70 this.requestedGroup = requestedGroup;
71 this.assignedKey = assignedKey;
72 this.assignedModifier = assignedModifier;
73 this.assignedDefault = assignedDefault;
74 this.assignedUser = assignedUser;
75 this.automatic = false;
76 this.reset = false;
77 }
78
79 public String getShortText() {
80 return shortText;
81 }
82
83 public String getLongText() {
84 return longText;
85 }
86
87 // a shortcut will be renamed when it is handed out again, because the original name may be a dummy
88 private void setLongText(String longText) {
89 this.longText = longText;
90 }
91
92 public int getAssignedKey() {
93 return assignedKey;
94 }
95
96 public int getAssignedModifier() {
97 return assignedModifier;
98 }
99
100 public boolean isAssignedDefault() {
101 return assignedDefault;
102 }
103
104 public boolean isAssignedUser() {
105 return assignedUser;
106 }
107
108 public boolean isAutomatic() {
109 return automatic;
110 }
111
112 public boolean isChangeable() {
113 return !automatic && !"core:none".equals(shortText);
114 }
115
116 private boolean isReset() {
117 return reset;
118 }
119
120 /**
121 * FOR PREF PANE ONLY
122 */
123 public void setAutomatic() {
124 automatic = true;
125 }
126
127 /**
128 * FOR PREF PANE ONLY.<p>
129 * Sets the modifiers that are used.
130 * @param assignedModifier assigned modifier
131 */
132 public void setAssignedModifier(int assignedModifier) {
133 this.assignedModifier = assignedModifier;
134 }
135
136 /**
137 * FOR PREF PANE ONLY.<p>
138 * Sets the key that actually is used.
139 * @param assignedKey assigned key
140 */
141 public void setAssignedKey(int assignedKey) {
142 this.assignedKey = assignedKey;
143 }
144
145 /**
146 * FOR PREF PANE ONLY.<p>
147 * Sets whether the user has changed this shortcut.
148 * @param assignedUser {@code true} if the user has changed this shortcut
149 */
150 public void setAssignedUser(boolean assignedUser) {
151 this.reset = (this.assignedUser || reset) && !assignedUser;
152 if (assignedUser) {
153 assignedDefault = false;
154 } else if (reset) {
155 assignedKey = requestedKey;
156 assignedModifier = findModifier(requestedGroup, null);
157 }
158 this.assignedUser = assignedUser;
159 }
160
161 /**
162 * Use this to register the shortcut with Swing
163 * @return the key stroke
164 */
165 public KeyStroke getKeyStroke() {
166 if (assignedModifier != -1)
167 return KeyStroke.getKeyStroke(assignedKey, assignedModifier);
168 return null;
169 }
170
171 // create a shortcut object from an string as saved in the preferences
172 private Shortcut(String prefString) {
173 List<String> s = new ArrayList<>(Main.pref.getCollection(prefString));
174 this.shortText = prefString.substring(15);
175 this.longText = s.get(0);
176 this.requestedKey = Integer.parseInt(s.get(1));
177 this.requestedGroup = Integer.parseInt(s.get(2));
178 this.assignedKey = Integer.parseInt(s.get(3));
179 this.assignedModifier = Integer.parseInt(s.get(4));
180 this.assignedDefault = Boolean.parseBoolean(s.get(5));
181 this.assignedUser = Boolean.parseBoolean(s.get(6));
182 }
183
184 private void saveDefault() {
185 Main.pref.getCollection("shortcut.entry."+shortText, Arrays.asList(new String[]{longText,
186 String.valueOf(requestedKey), String.valueOf(requestedGroup), String.valueOf(requestedKey),
187 String.valueOf(getGroupModifier(requestedGroup)), String.valueOf(true), String.valueOf(false)}));
188 }
189
190 // get a string that can be put into the preferences
191 private boolean save() {
192 if (isAutomatic() || isReset() || !isAssignedUser()) {
193 return Main.pref.putCollection("shortcut.entry."+shortText, null);
194 } else {
195 return Main.pref.putCollection("shortcut.entry."+shortText, Arrays.asList(new String[]{longText,
196 String.valueOf(requestedKey), String.valueOf(requestedGroup), String.valueOf(assignedKey),
197 String.valueOf(assignedModifier), String.valueOf(assignedDefault), String.valueOf(assignedUser)}));
198 }
199 }
200
201 private boolean isSame(int isKey, int isModifier) {
202 // an unassigned shortcut is different from any other shortcut
203 return isKey == assignedKey && isModifier == assignedModifier && assignedModifier != getGroupModifier(NONE);
204 }
205
206 public boolean isEvent(KeyEvent e) {
207 KeyStroke ks = getKeyStroke();
208 return ks != null && ks.equals(KeyStroke.getKeyStroke(e.getKeyCode(), e.getModifiers()));
209 }
210
211 /**
212 * use this to set a menu's mnemonic
213 * @param menu menu
214 */
215 public void setMnemonic(JMenu menu) {
216 if (assignedModifier == getGroupModifier(MNEMONIC) && getKeyStroke() != null && KeyEvent.getKeyText(assignedKey).length() == 1) {
217 menu.setMnemonic(KeyEvent.getKeyText(assignedKey).charAt(0)); //getKeyStroke().getKeyChar() seems not to work here
218 }
219 }
220
221 /**
222 * use this to set a buttons's mnemonic
223 * @param button button
224 */
225 public void setMnemonic(AbstractButton button) {
226 if (assignedModifier == getGroupModifier(MNEMONIC) && getKeyStroke() != null && KeyEvent.getKeyText(assignedKey).length() == 1) {
227 button.setMnemonic(KeyEvent.getKeyText(assignedKey).charAt(0)); //getKeyStroke().getKeyChar() seems not to work here
228 }
229 }
230
231 /**
232 * Sets the mnemonic key on a text component.
233 * @param component component
234 */
235 public void setFocusAccelerator(JTextComponent component) {
236 if (assignedModifier == getGroupModifier(MNEMONIC) && getKeyStroke() != null && KeyEvent.getKeyText(assignedKey).length() == 1) {
237 component.setFocusAccelerator(KeyEvent.getKeyText(assignedKey).charAt(0));
238 }
239 }
240
241 /**
242 * use this to set a actions's accelerator
243 * @param action action
244 */
245 public void setAccelerator(AbstractAction action) {
246 if (getKeyStroke() != null) {
247 action.putValue(AbstractAction.ACCELERATOR_KEY, getKeyStroke());
248 }
249 }
250
251 /**
252 * Returns a human readable text for the shortcut.
253 * @return a human readable text for the shortcut
254 */
255 public String getKeyText() {
256 KeyStroke keyStroke = getKeyStroke();
257 if (keyStroke == null) return "";
258 String modifText = KeyEvent.getKeyModifiersText(keyStroke.getModifiers());
259 if ("".equals(modifText)) return KeyEvent.getKeyText(keyStroke.getKeyCode());
260 return modifText + '+' + KeyEvent.getKeyText(keyStroke.getKeyCode());
261 }
262
263 @Override
264 public String toString() {
265 return getKeyText();
266 }
267
268 ///////////////////////////////
269 // everything's static below //
270 ///////////////////////////////
271
272 // here we store our shortcuts
273 private static ShortcutCollection shortcuts = new ShortcutCollection();
274
275 private static class ShortcutCollection extends CopyOnWriteArrayList<Shortcut> {
276 @Override
277 public boolean add(Shortcut shortcut) {
278 // expensive consistency check only in debug mode
279 if (Main.isDebugEnabled()
280 && stream().map(Shortcut::getShortText).anyMatch(shortcut.getShortText()::equals)) {
281 Main.warn(new AssertionError(shortcut.getShortText() + " already added"));
282 }
283 return super.add(shortcut);
284 }
285
286 void replace(Shortcut newShortcut) {
287 final Optional<Shortcut> existing = findShortcutByKeyOrShortText(-1, NONE, newShortcut.shortText);
288 if (existing.isPresent()) {
289 replaceAll(sc -> existing.get() == sc ? newShortcut : sc);
290 } else {
291 add(newShortcut);
292 }
293 }
294 }
295
296 // and here our modifier groups
297 private static Map<Integer, Integer> groups = new HashMap<>();
298
299 // check if something collides with an existing shortcut
300
301 /**
302 * Returns the registered shortcut fot the key and modifier
303 * @param requestedKey the requested key
304 * @param modifier the modifier
305 * @return an {@link Optional} registered shortcut, never {@code null}
306 */
307 public static Optional<Shortcut> findShortcut(int requestedKey, int modifier) {
308 return findShortcutByKeyOrShortText(requestedKey, modifier, null);
309 }
310
311 private static Optional<Shortcut> findShortcutByKeyOrShortText(int requestedKey, int modifier, String shortText) {
312 final Predicate<Shortcut> sameKey = sc -> modifier != getGroupModifier(NONE) && sc.isSame(requestedKey, modifier);
313 final Predicate<Shortcut> sameShortText = sc -> sc.getShortText().equals(shortText);
314 return shortcuts.stream()
315 .filter(sameKey.or(sameShortText))
316 .sorted(Comparator.comparingInt(sc -> sameShortText.test(sc) ? 0 : 1))
317 .findAny();
318 }
319
320 /**
321 * Returns a list of all shortcuts.
322 * @return a list of all shortcuts
323 */
324 public static List<Shortcut> listAll() {
325 return shortcuts.stream()
326 .filter(c -> !"core:none".equals(c.shortText))
327 .collect(Collectors.toList());
328 }
329
330 /** None group: used with KeyEvent.CHAR_UNDEFINED if no shortcut is defined */
331 public static final int NONE = 5000;
332 public static final int MNEMONIC = 5001;
333 /** Reserved group: for system shortcuts only */
334 public static final int RESERVED = 5002;
335 /** Direct group: no modifier */
336 public static final int DIRECT = 5003;
337 /** Alt group */
338 public static final int ALT = 5004;
339 /** Shift group */
340 public static final int SHIFT = 5005;
341 /** Command group. Matches CTRL modifier on Windows/Linux but META modifier on OS X */
342 public static final int CTRL = 5006;
343 /** Alt-Shift group */
344 public static final int ALT_SHIFT = 5007;
345 /** Alt-Command group. Matches ALT-CTRL modifier on Windows/Linux but ALT-META modifier on OS X */
346 public static final int ALT_CTRL = 5008;
347 /** Command-Shift group. Matches CTRL-SHIFT modifier on Windows/Linux but META-SHIFT modifier on OS X */
348 public static final int CTRL_SHIFT = 5009;
349 /** Alt-Command-Shift group. Matches ALT-CTRL-SHIFT modifier on Windows/Linux but ALT-META-SHIFT modifier on OS X */
350 public static final int ALT_CTRL_SHIFT = 5010;
351
352 /* for reassignment */
353 private static int[] mods = {ALT_CTRL, ALT_SHIFT, CTRL_SHIFT, ALT_CTRL_SHIFT};
354 private static int[] keys = {KeyEvent.VK_F1, KeyEvent.VK_F2, KeyEvent.VK_F3, KeyEvent.VK_F4,
355 KeyEvent.VK_F5, KeyEvent.VK_F6, KeyEvent.VK_F7, KeyEvent.VK_F8,
356 KeyEvent.VK_F9, KeyEvent.VK_F10, KeyEvent.VK_F11, KeyEvent.VK_F12};
357
358 // bootstrap
359 private static boolean initdone;
360 private static void doInit() {
361 if (initdone) return;
362 initdone = true;
363 int commandDownMask = GuiHelper.getMenuShortcutKeyMaskEx();
364 groups.put(NONE, -1);
365 groups.put(MNEMONIC, KeyEvent.ALT_DOWN_MASK);
366 groups.put(DIRECT, 0);
367 groups.put(ALT, KeyEvent.ALT_DOWN_MASK);
368 groups.put(SHIFT, KeyEvent.SHIFT_DOWN_MASK);
369 groups.put(CTRL, commandDownMask);
370 groups.put(ALT_SHIFT, KeyEvent.ALT_DOWN_MASK | KeyEvent.SHIFT_DOWN_MASK);
371 groups.put(ALT_CTRL, KeyEvent.ALT_DOWN_MASK | commandDownMask);
372 groups.put(CTRL_SHIFT, commandDownMask | KeyEvent.SHIFT_DOWN_MASK);
373 groups.put(ALT_CTRL_SHIFT, KeyEvent.ALT_DOWN_MASK | commandDownMask | KeyEvent.SHIFT_DOWN_MASK);
374
375 // (1) System reserved shortcuts
376 Main.platform.initSystemShortcuts();
377 // (2) User defined shortcuts
378 Main.pref.getAllPrefixCollectionKeys("shortcut.entry.").stream()
379 .map(Shortcut::new)
380 .filter(sc -> !findShortcut(sc.getAssignedKey(), sc.getAssignedModifier()).isPresent())
381 .sorted(Comparator.comparing(sc -> sc.isAssignedUser() ? 1 : sc.isAssignedDefault() ? 2 : 3))
382 .forEachOrdered(shortcuts::replace);
383 }
384
385 private static int getGroupModifier(int group) {
386 return Optional.ofNullable(groups.get(group)).orElse(-1);
387 }
388
389 private static int findModifier(int group, Integer modifier) {
390 if (modifier == null) {
391 modifier = getGroupModifier(group);
392 if (modifier == null) { // garbage in, no shortcut out
393 modifier = getGroupModifier(NONE);
394 }
395 }
396 return modifier;
397 }
398
399 // shutdown handling
400 public static boolean savePrefs() {
401 return shortcuts.stream()
402 .map(Shortcut::save)
403 .reduce(Boolean.FALSE, Boolean::logicalOr); // has changed
404 }
405
406 /**
407 * FOR PLATFORMHOOK USE ONLY.
408 * <p>
409 * This registers a system shortcut. See PlatformHook for details.
410 * @param shortText an ID. re-use a {@code "system:*"} ID if possible, else use something unique.
411 * @param longText this will be displayed in the shortcut preferences dialog. Better
412 * use something the user will recognize...
413 * @param key the key. Use a {@link KeyEvent KeyEvent.VK_*} constant here.
414 * @param modifier the modifier. Use a {@link KeyEvent KeyEvent.*_MASK} constant here.
415 * @return the system shortcut
416 */
417 public static Shortcut registerSystemShortcut(String shortText, String longText, int key, int modifier) {
418 final Optional<Shortcut> existing = findShortcutByKeyOrShortText(key, modifier, shortText);
419 if (existing.isPresent() && shortText.equals(existing.get().getShortText())) {
420 return existing.get();
421 } else if (existing.isPresent()) {
422 // this always is a logic error in the hook
423 Main.error("CONFLICT WITH SYSTEM KEY " + shortText + ": " + existing.get());
424 return null;
425 }
426 final Shortcut shortcut = new Shortcut(shortText, longText, key, RESERVED, key, modifier, true, false);
427 shortcuts.add(shortcut);
428 return shortcut;
429 }
430
431 /**
432 * Register a shortcut.
433 *
434 * Here you get your shortcuts from. The parameters are:
435 *
436 * @param shortText an ID. re-use a {@code "system:*"} ID if possible, else use something unique.
437 * {@code "menu:*"} is reserved for menu mnemonics, {@code "core:*"} is reserved for
438 * actions that are part of JOSM's core. Use something like
439 * {@code <pluginname>+":"+<actionname>}.
440 * @param longText this will be displayed in the shortcut preferences dialog. Better
441 * use something the user will recognize...
442 * @param requestedKey the key you'd prefer. Use a {@link KeyEvent KeyEvent.VK_*} constant here.
443 * @param requestedGroup the group this shortcut fits best. This will determine the
444 * modifiers your shortcut will get assigned. Use the constants defined above.
445 * @return the shortcut
446 */
447 public static Shortcut registerShortcut(String shortText, String longText, int requestedKey, int requestedGroup) {
448 return registerShortcut(shortText, longText, requestedKey, requestedGroup, null);
449 }
450
451 // and now the workhorse. same parameters as above, just one more
452 private static Shortcut registerShortcut(String shortText, String longText, int requestedKey, int requestedGroup, Integer modifier) {
453 doInit();
454 Integer defaultModifier = findModifier(requestedGroup, modifier);
455 final Optional<Shortcut> existing = findShortcutByKeyOrShortText(requestedKey, defaultModifier, shortText);
456 if (existing.isPresent() && shortText.equals(existing.get().getShortText())) {
457 // a re-register? maybe a sc already read from the preferences?
458 final Shortcut sc = existing.get();
459 sc.setLongText(longText); // or set by the platformHook, in this case the original longText doesn't match the real action
460 sc.saveDefault();
461 return sc;
462 } else if (existing.isPresent()) {
463 final Shortcut conflict = existing.get();
464 if (Main.isPlatformOsx()) {
465 // Try to reassign Meta to Ctrl
466 int newmodifier = findNewOsxModifier(requestedGroup);
467 if (!findShortcut(requestedKey, newmodifier).isPresent()) {
468 Main.info("Reassigning OSX shortcut '" + shortText + "' from Meta to Ctrl because of conflict with " + conflict);
469 return reassignShortcut(shortText, longText, requestedKey, conflict, requestedGroup, requestedKey, newmodifier);
470 }
471 }
472 for (int m : mods) {
473 for (int k : keys) {
474 int newmodifier = getGroupModifier(m);
475 if (!findShortcut(k, newmodifier).isPresent()) {
476 Main.info("Reassigning shortcut '" + shortText + "' from " + modifier + " to " + newmodifier +
477 " because of conflict with " + conflict);
478 return reassignShortcut(shortText, longText, requestedKey, conflict, m, k, newmodifier);
479 }
480 }
481 }
482 } else {
483 Shortcut newsc = new Shortcut(shortText, longText, requestedKey, requestedGroup, requestedKey, defaultModifier, true, false);
484 newsc.saveDefault();
485 shortcuts.add(newsc);
486 return newsc;
487 }
488
489 return null;
490 }
491
492 private static int findNewOsxModifier(int requestedGroup) {
493 switch (requestedGroup) {
494 case CTRL: return KeyEvent.CTRL_DOWN_MASK;
495 case ALT_CTRL: return KeyEvent.ALT_DOWN_MASK | KeyEvent.CTRL_DOWN_MASK;
496 case CTRL_SHIFT: return KeyEvent.CTRL_DOWN_MASK | KeyEvent.SHIFT_DOWN_MASK;
497 case ALT_CTRL_SHIFT: return KeyEvent.ALT_DOWN_MASK | KeyEvent.CTRL_DOWN_MASK | KeyEvent.SHIFT_DOWN_MASK;
498 default: return 0;
499 }
500 }
501
502 private static Shortcut reassignShortcut(String shortText, String longText, int requestedKey, Shortcut conflict,
503 int m, int k, int newmodifier) {
504 Shortcut newsc = new Shortcut(shortText, longText, requestedKey, m, k, newmodifier, false, false);
505 Main.info(tr("Silent shortcut conflict: ''{0}'' moved by ''{1}'' to ''{2}''.",
506 shortText, conflict.getShortText(), newsc.getKeyText()));
507 newsc.saveDefault();
508 shortcuts.add(newsc);
509 return newsc;
510 }
511
512 /**
513 * Replies the platform specific key stroke for the 'Copy' command, i.e.
514 * 'Ctrl-C' on windows or 'Meta-C' on a Mac. null, if the platform specific
515 * copy command isn't known.
516 *
517 * @return the platform specific key stroke for the 'Copy' command
518 */
519 public static KeyStroke getCopyKeyStroke() {
520 return getKeyStrokeForShortKey("system:copy");
521 }
522
523 /**
524 * Replies the platform specific key stroke for the 'Paste' command, i.e.
525 * 'Ctrl-V' on windows or 'Meta-V' on a Mac. null, if the platform specific
526 * paste command isn't known.
527 *
528 * @return the platform specific key stroke for the 'Paste' command
529 */
530 public static KeyStroke getPasteKeyStroke() {
531 return getKeyStrokeForShortKey("system:paste");
532 }
533
534 /**
535 * Replies the platform specific key stroke for the 'Cut' command, i.e.
536 * 'Ctrl-X' on windows or 'Meta-X' on a Mac. null, if the platform specific
537 * 'Cut' command isn't known.
538 *
539 * @return the platform specific key stroke for the 'Cut' command
540 */
541 public static KeyStroke getCutKeyStroke() {
542 return getKeyStrokeForShortKey("system:cut");
543 }
544
545 private static KeyStroke getKeyStrokeForShortKey(String shortKey) {
546 return shortcuts.stream()
547 .filter(sc -> shortKey.equals(sc.getShortText()))
548 .findAny()
549 .map(Shortcut::getKeyStroke)
550 .orElse(null);
551 }
552}
Note: See TracBrowser for help on using the repository browser.