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

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

see #15229 - see #15182 - deprecate GuiHelper.getMenuShortcutKeyMaskEx() - replaced by PlatformHook.getMenuShortcutKeyMaskEx()

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