/*
* $Id$
*
* Copyright (c) 2008-2009 by Brent Easton
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License (LGPL) as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, copies are available
* at http://www.opensource.org.
*/
package VASSAL.tools;
import java.util.HashMap;
import javax.swing.KeyStroke;
public class NamedKeyManager {
protected static NamedKeyManager instance;
/*
* Named Keys are allocated real Keystrokes
* in the sequence from '\uE000' to '\uF8FE'.
* The value '\uF8FF' is used as a place marker to
* indicate a real KeyStroke has not been allocated yet.
*/
protected static final int NAMED_START = '\uE000';
protected static final int NAMED_END = '\uF8FE';
protected static final int NAMED_MARKER = '\uF8FF';
protected static int nextNamedKey = NAMED_START;
protected static HashMap<String, KeyStroke> strokes =
new HashMap<String, KeyStroke>();
public NamedKeyManager() {
}
public static NamedKeyManager getInstance() {
if (instance == null) {
instance = new NamedKeyManager();
}
return instance;
}
/**
* Return true if the supplied KeyStroke is in the range allocated
* to NamedKeyStrokes
* @param k KeyStroke
* @return true if this was generated by us
*/
public static boolean isNamed(KeyStroke k) {
if (k == null) {
return false;
}
int code = k.getKeyCode();
return code == NAMED_MARKER || (code >= NAMED_START && code <= NAMED_END);
}
/**
* Return a generic marker KeyStroke
* @return
*/
public static KeyStroke getMarkerKeyStroke() {
return KeyStroke.getKeyStroke(NAMED_MARKER, 0);
}
/**
* Return the generated KeyStroke associated with the NamedKeyStroke
* @param vkey
* @return generated KeyStroke
*/
public KeyStroke getKeyStroke(NamedKeyStroke vkey) {
// No name means it is just a standard keystroke
if (!vkey.isNamed()) {
return vkey.getStroke();
}
// Look up the name in the cache and allocate the next
// available KeyStroke if required.
KeyStroke stroke = strokes.get(vkey.getName());
if (stroke == null) {
stroke = KeyStroke.getKeyStroke(getNextStroke(), 0);
strokes.put(vkey.getName(), stroke);
}
return stroke;
}
/**
* Return the next KeyStroke from the pool
* @return KeyStroke Id
*/
public int getNextStroke() {
if (nextNamedKey == NAMED_END) {
throw new IllegalStateException("Too many Named Keys");
}
return nextNamedKey++;
}
}