Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(761)

Side by Side Diff: sdk/lib/html/src/KeyboardEventController.dart

Issue 11416249: Make KeyboardEvent cross-browser consistent. (Closed) Base URL: https://dart.googlecode.com/svn/branches/bleeding_edge/dart
Patch Set: documentation fix Created 8 years ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
(Empty)
1 // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
2 // for details. All rights reserved. Use of this source code is governed by a
3 // BSD-style license that can be found in the LICENSE file.
4
5 part of html;
6
7 /**
8 * Works with KeyboardEvent and KeyEvent to determine how to expose information
9 * about Key(board)Events. This class functions like an EventListenerList, and
10 * provides a consistent interface for the Dart
11 * user, despite the fact that a multitude of browsers that have varying
12 * keyboard default behavior.
13 *
14 * This class is very much a work in progress, and we'd love to get information
15 * on how we can make this class work with as many international keyboards as
16 * possible. Bugs welcome!
17 */
18 class KeyboardEventController {
19 // This code inspired by Closure's KeyHandling library.
20 // http://closure-library.googlecode.com/svn/docs/closure_goog_events_keyhandl er.js.source.html
21
22 /**
23 * The set of keys that have been pressed down without seeing their
24 * corresponding keyup event.
25 */
26 List<KeyboardEvent> keyDownList;
27
28 /** The set of functions that wish to be notified when a KeyEvent happens. */
29 List<Function> _callbacks;
30
31 /** The type of KeyEvent we are tracking (keyup, keydown, keypress). */
32 String _type;
33
34 // The distance to shift from upper case alphabet Roman letters to lower case.
35 const int _ROMAN_ALPHABET_OFFSET = "a".charCodes[0] - "A".charCodes[0];
36
37 /**
38 * An enumeration of key identifiers currently part of the W3C draft for DOM3
39 * and their mappings to keyCodes.
40 * http://www.w3.org/TR/DOM-Level-3-Events/keyset.html#KeySet-Set
41 */
42 static Map<String, int> _keyIdentifier = {
43 'Up': KeyCode.UP,
44 'Down': KeyCode.DOWN,
45 'Left': KeyCode.LEFT,
46 'Right': KeyCode.RIGHT,
47 'Enter': KeyCode.ENTER,
48 'F1': KeyCode.F1,
49 'F2': KeyCode.F2,
50 'F3': KeyCode.F3,
51 'F4': KeyCode.F4,
52 'F5': KeyCode.F5,
53 'F6': KeyCode.F6,
54 'F7': KeyCode.F7,
55 'F8': KeyCode.F8,
56 'F9': KeyCode.F9,
57 'F10': KeyCode.F10,
58 'F11': KeyCode.F11,
59 'F12': KeyCode.F12,
60 'U+007F': KeyCode.DELETE,
61 'Home': KeyCode.HOME,
62 'End': KeyCode.END,
63 'PageUp': KeyCode.PAGE_UP,
64 'PageDown': KeyCode.PAGE_DOWN,
65 'Insert': KeyCode.INSERT
66 };
67
68 /** Named constructor to add an onKeyPress event listener to our handler. */
69 KeyboardEventController.keypress(EventTarget target) {
70 _KeyboardEventController(target, 'keypress');
71 }
72
73 /** Named constructor to add an onKeyUp event listener to our handler. */
74 KeyboardEventController.keyup(EventTarget target) {
75 _KeyboardEventController(target, 'keyup');
76 }
77
78 /** Named constructor to add an onKeyDown event listener to our handler. */
79 KeyboardEventController.keydown(EventTarget target) {
80 _KeyboardEventController(target, 'keydown');
81 }
82
83 /**
84 * General constructor, performs basic initialization for our improved
85 * KeyboardEvent controller.
86 */
87 _KeyboardEventController(EventTarget target, String type) {
88 keyDownList = [];
89 _callbacks = [];
90 _type = type;
91 target.on.keyDown.add(processKeyDown, true);
92 target.on.keyPress.add(processKeyPress, true);
93 target.on.keyUp.add(processKeyUp, true);
94 }
95
96 /** Add a callback that wishes to be notified when a KeyEvent occurs. */
97 void add(Function callback) {
blois 2012/11/29 00:03:12 void callback(KeyEvent)?
Emily Fortuna 2012/11/29 01:10:37 Done.
98 _callbacks.add(callback);
99 }
100
101 /**
102 * Notify all callback listeners that a KeyEvent of the relevant type has
103 * occurred.
104 */
105 bool _dispatch(KeyEvent event) {
106 if (event.type == _type) {
107 for(var callback in _callbacks) {
blois 2012/11/29 00:03:12 Normally need to copy this list to allow removing
Emily Fortuna 2012/11/29 01:10:37 No removing is happening here... just calling the
blois 2012/11/29 17:06:34 Right- if the code being called back removes itsel
Emily Fortuna 2012/11/29 19:19:49 I see. Changed. But how could this happen since Da
blois 2012/11/29 21:04:55 Scenario: user presses the delete button, user cod
108 callback(event);
109 }
110 }
111 }
112
113 /** Remove the given callback from the listeners list. */
114 void remove(Function callback) {
blois 2012/11/29 00:03:12 void callback(KeyEvent)?
Emily Fortuna 2012/11/29 01:10:37 Done.
115 _callbacks = _callbacks.filter((element) => element != callback);
blois 2012/11/29 00:03:12 Not removeAt? This creates a new list... Should p
Emily Fortuna 2012/11/29 01:10:37 Done.
blois 2012/11/29 17:06:34 What I meant by remove all event listeners is that
Emily Fortuna 2012/11/29 19:19:49 sgtm.
116 }
117
118 /** Determine if caps lock is one of the currently depressed keys. */
119 bool get _capsLockOn() =>
120 keyDownList.some((var element) => element.keyCode == KeyCode.CAPS_LOCK);
121
122 /**
123 * Given the previously recorded keydown key codes, see if we can determine
124 * the keycode of this keypress [event]. (Generally browsers only provide
125 * charCode information for keypress events, but with a little
126 * reverse-engineering, we can also determine the keyCode.) Returns
127 * KeyCode.UNKNOWN if the keycode could not be determined.
128 */
129 int _determineKeyCodeForKeypress(KeyboardEvent event) {
130 // Note: This function is a work in progress. We'll expand this function
131 // once we get more information about other keyboards.
132 for (var prevEvent in keyDownList) {
133 if (prevEvent._shadowCharCode == event.charCode) {
134 return prevEvent.keyCode;
135 }
136 if ((event.shiftKey || _capsLockOn) && event.charCode >= "A".charCodes[0]
137 && event.charCode <= "Z".charCodes[0] && event.charCode +
138 _ROMAN_ALPHABET_OFFSET == prevEvent._shadowCharCode) {
139 return prevEvent.keyCode;
140 }
141 }
142 return KeyCode.UNKNOWN;
143 }
144
145 /**
146 * Given the charater code returned from a keyDown [event], try to ascertain
147 * and return the corresponding charCode for the character that was pressed.
148 * This information is not shown to the user, but used to help polyfill
149 * keypress events.
150 */
151 int _findCharCodeKeyDown(KeyboardEvent event) {
152 if (event.keyLocation == 3) { // Numpad keys.
153 switch (event.keyCode) {
154 case KeyCode.NUM_ZERO:
155 // Even though this function returns _charCodes_, for some cases the
156 // KeyCode == the charCode we want, in which case we use the keycode
157 // constant for readability.
158 return KeyCode.ZERO;
159 case KeyCode.NUM_ONE:
160 return KeyCode.ONE;
161 case KeyCode.NUM_TWO:
162 return KeyCode.TWO;
163 case KeyCode.NUM_THREE:
164 return KeyCode.THREE;
165 case KeyCode.NUM_FOUR:
166 return KeyCode.FOUR;
167 case KeyCode.NUM_FIVE:
168 return KeyCode.FIVE;
169 case KeyCode.NUM_SIX:
170 return KeyCode.SIX;
171 case KeyCode.NUM_SEVEN:
172 return KeyCode.SEVEN;
173 case KeyCode.NUM_EIGHT:
174 return KeyCode.EIGHT;
175 case KeyCode.NUM_NINE:
176 return KeyCode.NINE;
177 case KeyCode.NUM_MULTIPLY:
178 return 42; // Char code for *
179 case KeyCode.NUM_PLUS:
180 return 43; // +
181 case KeyCode.NUM_MINUS:
182 return 45; // -
183 case KeyCode.NUM_PERIOD:
184 return 46; // .
185 case KeyCode.NUM_DIVISION:
186 return 47; // /
187 }
188 } else if (event.keyCode >= 65 && event.keyCode <= 90) {
189 // Set the "char code" for key down as the lower case letter. Again, this
190 // will not show up for the user, but will be helpful in estimating
191 // keyCode locations and other information during the keyPress event.
192 return event.keyCode + _ROMAN_ALPHABET_OFFSET;
193 }
194 switch(event.keyCode) {
195 case KeyCode.SEMICOLON:
196 return KeyCode.FF_SEMICOLON;
197 case KeyCode.EQUALS:
198 return KeyCode.FF_EQUALS;
199 case KeyCode.COMMA:
200 return 44; // Ascii value for ,
201 case KeyCode.DASH:
202 return 45; // -
203 case KeyCode.PERIOD:
204 return 46; // .
205 case KeyCode.SLASH:
206 return 47; // /
207 case KeyCode.APOSTROPHE:
208 return 96; // `
209 case KeyCode.OPEN_SQUARE_BRACKET:
210 return 91; // [
211 case KeyCode.BACKSLASH:
212 return 92; // \
213 case KeyCode.CLOSE_SQUARE_BRACKET:
214 return 93; // ]
215 case KeyCode.SINGLE_QUOTE:
216 return 39; // '
217 }
218 return event.keyCode;
219 }
220
221 /**
222 * Returns true if the key fires a keypress event in the current browser.
223 */
224 bool _firesKeyPressEvent(KeyEvent event) {
225 if (!_Device.isIE && !_Device.isWebKit) {
226 return true;
227 }
228
229 if (_Device.userAgent.contains('Mac') && event.altKey) {
230 return KeyCode.isCharacterKey(event.keyCode);
231 }
232
233 // Alt but not AltGr which is represented as Alt+Ctrl.
234 if (event.altKey && !event.ctrlKey) {
235 return false;
236 }
237
238 // Saves Ctrl or Alt + key for IE and WebKit, which won't fire keypress.
239 if (!event.shiftKey &&
240 (keyDownList.last.keyCode == KeyCode.CTRL ||
241 keyDownList.last.keyCode == KeyCode.ALT ||
242 _Device.userAgent.contains('Mac') &&
243 keyDownList.last.keyCode == KeyCode.META)) {
244 return false;
245 }
246
247 // Some keys with Ctrl/Shift do not issue keypress in WebKit.
248 if (_Device.isWebKit && event.ctrlKey && event.shiftKey && (
249 event.keycode == KeyCode.BACKSLASH ||
250 event.keycode == KeyCode.OPEN_SQUARE_BRACKET ||
251 event.keycode == KeyCode.CLOSE_SQUARE_BRACKET ||
252 event.keycode == KeyCode.TILDE ||
253 event.keycode == KeyCode.SEMICOLON || event.keycode == KeyCode.DASH ||
254 event.keycode == KeyCode.EQUALS || event.keycode == KeyCode.COMMA ||
255 event.keycode == KeyCode.PERIOD || event.keycode == KeyCode.SLASH ||
256 event.keycode == KeyCode.APOSTROPHE ||
257 event.keycode == KeyCode.SINGLE_QUOTE)) {
258 return false;
259 }
260
261 switch (event.keyCode) {
262 case KeyCode.ENTER:
263 // IE9 does not fire keypress on ENTER.
264 return !_Device.isIE;
265 case KeyCode.ESC:
266 return !_Device.isWebKit;
267 }
268
269 return KeyCode.isCharacterKey(event.keyCode);
270 }
271
272 /**
273 * Normalize the keycodes to the IE KeyCodes (this is what Chrome, IE, and
274 * Opera all use).
275 */
276 int normalizeKeyCodes(KeyboardEvent event) {
277 // Note: This may change once we get input about non-US keyboards.
278 if (_Device.isFirefox) {
279 switch(event.keyCode) {
280 case KeyCode.FF_EQUALS:
281 return KeyCode.EQUALS;
282 case KeyCode.FF_SEMICOLON:
283 return KeyCode.SEMICOLON;
284 case KeyCode.MAC_FF_META:
285 return KeyCode.META;
286 case KeyCode.WIN_KEY_FF_LINUX:
287 return KeyCode.WIN_KEY;
288 }
289 }
290 return event.keyCode;
291 }
292
293 /** Handle keydown events. */
294 void processKeyDown(KeyboardEvent e) {
295 // Ctrl-Tab and Alt-Tab can cause the focus to be moved to another window
296 // before we've caught a key-up event. If the last-key was one of these
297 // we reset the state.
298 if (keyDownList.length > 0 &&
299 (keyDownList.last.keyCode == KeyCode.CTRL && !e.ctrlKey ||
300 keyDownList.last.keyCode == KeyCode.ALT && !e.altKey ||
301 _Device.userAgent.contains('Mac') &&
302 keyDownList.last.keyCode == KeyCode.META && !e.metaKey)) {
303 keyDownList = [];
304 }
305
306 var event = new KeyEvent(e);
307 event._shadowKeyCode = normalizeKeyCodes(event);
308 // Technically a "keydown" event doesn't have a charCode. This is
309 // calculated nonetheless to provide us with more information in giving
310 // as much information as possible on keypress about keycode and also
311 // charCode.
312 event._shadowCharCode = _findCharCodeKeyDown(event);
313 if (keyDownList.length > 0 && event.keyCode != keyDownList.last.keyCode &&
314 !_firesKeyPressEvent(event)) {
315 // Some browsers have quirks not firing keypress events where all other
316 // browsers do. This makes them more consistent.
317 processKeyPress(event);
318 }
319 keyDownList.add(event);
320 _dispatch(event);
321 }
322
323 /** Handle keypress events. */
324 void processKeyPress(KeyboardEvent event) {
325 var e = new KeyEvent(event);
326 // IE reports the character code in the keyCode field for keypress events.
327 // There are two exceptions however, Enter and Escape.
328 if (_Device.isIE) {
329 if (e.keyCode == KeyCode.ENTER || e.keyCode == KeyCode.ESC) {
330 e._shadowCharCode = 0;
331 } else {
332 e._shadowCharCode = e.keyCode;
333 }
334 } else if (_Device.isOpera) {
335 // Opera reports the character code in the keyCode field.
336 e._shadowCharCode = KeyCode.isCharacterKey(keyCode) ? e.keyCode : 0;
337 }
338 // Now we guestimate about what the keycode is that was actually
339 // pressed, given previous keydown information.
340 e._shadowKeyCode = _determineKeyCodeForKeypress(e);
341
342 // Correct the key value for certain browser-specific quirks.
343 if (e._shadowKeyIdentifier &&
344 _keyIdentifier.contains(e._shadowKeyIdentifier)) {
345 // This is needed for Safari Windows because it currently doesn't give a
346 // keyCode/which for non printable keys.
347 e._shadowKeyCode = _keyIdentifier[keyIdentifier];
348 }
349 e._shadowAltKey = keyDownList.some((var element) => element.altKey);
350 _dispatch(e);
351 }
352
353 /** Handle keyup events. */
354 void processKeyUp(KeyboardEvent event) {
355 var e = new KeyEvent(event);
356 KeyboardEvent toRemove = null;
357 for (var key in keyDownList) {
358 if (key.keyCode == e.keyCode) {
359 toRemove = key;
360 }
361 }
362 if (toRemove != null) {
363 keyDownList = keyDownList.filter((element) => element != toRemove);
364 } else if (keyDownList.length > 0) {
365 // This happens when we've reached some international keyboard case we
366 // haven't accounted for or we haven't correctly eliminated all browser
367 // inconsistencies. Filing bugs on when this is reached is welcome!
368 keyDownList.removeLast();
369 }
370 _dispatch(e);
371 }
372 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698