1 11 package org.eclipse.ui.internal.misc; 12 13 import org.eclipse.jface.action.*; 14 import org.eclipse.swt.SWT; 15 import org.eclipse.swt.widgets.*; 16 import java.util.*; 17 18 40 public class AcceleratorHook implements Listener { 41 private ArrayList actionList; 42 43 private class ActionItem { 44 public ActionItem(int accel, IAction act) { 45 accelerator = accel; 46 action = act; 47 } 48 public int accelerator; 49 public IAction action; 50 } 51 52 private class FakeAction extends Action { 53 public FakeAction(String name) { 54 super(name); 55 } 56 public void run() { 57 } 58 } 59 62 public AcceleratorHook(Control ctrl) { 63 actionList = new ArrayList(5); 64 ctrl.addListener(SWT.KeyDown, this); 65 ctrl.addListener(SWT.KeyUp, this); 66 } 67 76 public void add(IAction action) { 77 if (action.getAccelerator() == 0) 78 return; 79 actionList.add(new ActionItem(action.getAccelerator(), action)); 80 } 81 95 public void add(IAction action, String strAccel) { 96 Action fakeAction = new FakeAction("Fake\t"+strAccel); if (fakeAction.getAccelerator() == 0) 98 return; 99 actionList.add(new ActionItem(fakeAction.getAccelerator(), action)); 100 } 101 106 private ActionItem findItem(IAction action) { 107 Iterator iter = actionList.iterator(); 108 while (iter.hasNext()) { 109 ActionItem item = (ActionItem)iter.next(); 110 if (item.action == action) 111 return item; 112 } 113 return null; 114 } 115 121 private ActionItem findItem(Event e) { 122 int accel = getAccel(e); 124 if (accel == 0) 125 return null; 126 127 Iterator iter = actionList.iterator(); 129 while (iter.hasNext()) { 130 ActionItem item = (ActionItem)iter.next(); 131 if (item.accelerator == accel) 133 return item; 134 } 135 return null; 136 } 137 143 private int getAccel(Event e) { 144 151 152 int key = (int)Character.toUpperCase(e.character); 154 int mods = 0; 155 if ((e.stateMask & SWT.ALT) > 0) 156 mods |= SWT.ALT; 157 if ((e.stateMask & SWT.SHIFT) > 0) 158 mods |= SWT.SHIFT; 159 if ((e.stateMask & SWT.CTRL) > 0) { 160 mods |= SWT.CTRL; 161 key = key + 'A' - 1; } 163 int accel = key | mods | e.keyCode; 164 165 169 return accel; 170 } 171 172 181 public void handleEvent(Event event) { 182 ActionItem item = findItem(event); 183 if (item != null) 184 item.action.runWithEvent(event); 185 } 186 187 193 public void remove(IAction action) { 194 ActionItem item = findItem(action); 195 if (item != null) 196 actionList.remove(item); 197 } 198 } 199 | Popular Tags |