final/src/Middleware.java

58 lines
1.7 KiB
Java

import com.sun.jdi.request.DuplicateRequestException;
import java.awt.event.KeyEvent;
import java.io.Serializable;
import java.util.ArrayList;
public class Middleware implements Serializable {
public static ArrayList<Integer> allOldCode = new ArrayList<Integer>();
public static ArrayList<Integer> allNewCode = new ArrayList<Integer>();
public final int oldCode;
public final int newCode;
public boolean isDestroyed = false;
Middleware(int oldCode, int newCode) {
// if (!canCreate(oldCode, newCode)) {
// TODO: replace with more appropriate exception
// throw new DuplicateRequestException();
// }
allOldCode.add(oldCode);
allNewCode.add(newCode);
this.oldCode = oldCode;
this.newCode = newCode;
}
public boolean canIntercept(KeyEvent e) {
return e.getKeyCode() == newCode && !isDestroyed;
}
public KeyEvent interceptKey(KeyEvent e) {
e.setKeyCode(oldCode);
return e;
}
public void destroy() {
allOldCode.remove(oldCode);
allNewCode.remove(newCode);
isDestroyed = true;
}
public static boolean canCreate(int oldCode, int newCode) {
return (!allOldCode.contains(oldCode) && !allNewCode.contains(newCode));
}
@Override
public boolean equals(Object o) {
try {
Middleware m = (Middleware)o;
// duck typing equals check
// if it has the same oldCode, assume it is the same; this is because oldCodes should be unique
// also makes some corner cases easier
return this.oldCode == m.oldCode || this.newCode == m.newCode;
} catch (ClassCastException e) {
return false;
}
}
}