all files / montage/core/event/ key-manager.js

29.83% Statements 88/295
17.07% Branches 42/246
31.82% Functions 7/22
29.83% Lines 88/295
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      32×                 32× 32×   32× 32×   32× 32× 31× 350× 350×           31× 31×         32× 32×   32×                           13×           13× 13× 13× 13× 192× 192× 13× 13× 13× 13×                                                                                                       86× 86×   71×         27× 27×   23×                                                                                                                                                                                                                                                                                     36×             36×                             36×       36× 36×         36×     36×                                                                                                                                                                     32×                                                                                                                                                                                                                                                                                                                                                                                   36×           36× 36×     36×                               36× 36× 36×   36× 36×     36× 36×             36×                                    
/**
 * @module montage/core/event/key-manager
 * @requires montage/core/core
 */
 
var Montage = require("../core").Montage,
    defaultEventManager = require("./event-manager").defaultEventManager,
    MutableEvent = require("./mutable-event").MutableEvent;
 
var KEYNAMES_TO_KEYCODES = {
    // W3C Key Code
    backspace:              8,
    tab:                    9,
    enter:                  13,
    shift:                  16,
    control:                17,
    alt:                    18,
    capslock:               20,
    escape:                 27,
    space:                  32,
    pageup:                 33,
    pagedown:               34,
    end:                    35,
    home:                   36,
    left:                   37,
    up:                     38,
    right:                  39,
    down:                   40,
    delete:                 46,
 
    //https://www.w3.org/TR/uievents-key/
    arrowup:                38,
    arrowright:             39,
    arrowdown:              40,
    arrowdelete:            46,
 
    // W3C Optional Key Code (mostly for US keyboard layout)
    semicolon:              186,
    colon:                  186,
    equal:                  187,
    plus:                   187,
    comma:                  188,
    less:                   188,
    minus:                  189,
    underscore:             189,
    period:                 190,
    greater:                190,
    slash:                  191,
    questionmark:           191,
    backtick:               192,
    tilde:                  192,
    openingsquarebracket:   219,
    openingcurlybracket:    219,
    backslash:              220,
    pipe:                   220,
    closingsquarebracket:   221,
    closingcurlybracket:    221,
    singlequote:            222,
    doublequote:            222,
 
 
    // Non standard Virtal key code but commonly used
    clear:                  12,
    meta:                   91,
    contextmenu:            93,
    numpad0:                96,
    numpad1:                97,
    numpad2:                98,
    numpad3:                99,
    numpad4:                100,
    numpad5:                101,
    numpad6:                102,
    numpad7:                103,
    numpad8:                104,
    numpad9:                105,
    multiply:               106,
    add:                    107,
    subtract:               109,
    decimal:                110,
    divide:                 111,
    f1:                     112,
    f2:                     113,
    f3:                     114,
    f4:                     115,
    f5:                     116,
    f6:                     117,
    f7:                     118,
    f8:                     119,
    f9:                     120,
    f10:                    121,
    f11:                    122,
    f12:                    123,
    f13:                    124,
    f14:                    125,
    f15:                    126,
    f16:                    127,
    f17:                    128,
    f18:                    129,
    f19:                    130,
    f20:                    131,
    f21:                    132,
    f22:                    133,
    f23:                    134,
    f24:                    135
},
 
KEYCODES_TO_KEYNAMES = null,    // Will be build from the KEYNAMES_TO_KEYCODES dictionary
 
OPERAMAC_KEYNAMES_TO_KEYCODES = {
    meta:                   17,
    control:                57392,
    f17:                    63252,
    f18:                    63253,
    f19:                    63254,
    f20:                    63255,
    f21:                    63256,
    f22:                    63257,
    f23:                    63258,
    f24:                    63259
},
 
FIREFOX_KEYNAMES_TO_KEYCODES = {
    f13:                    44,
    f14:                    145,
    f15:                    19,
    f16:                    63251,
    f17:                    63252,
    f18:                    63253,
    f19:                    63254,
    f20:                    63255,
    f21:                    63256,
    f22:                    63257,
    f23:                    63258,
    f24:                    63259,
    meta:                   224
},
 
KEYNAMES_ALIASES = {
    cmd:        "command",
    ctl:        "control",
    ctrl:       "control",
    win:        "meta",
    windows:    "meta",
    opt:        "alt",
    option:     "alt"
},
 
MODIFIERS = {
    meta:       {name:"meta",    value:1},
    alt:        {name:"alt",     value:2},
    control:    {name:"control", value:4},
    shift:      {name:"shift",   value:8}
},
 
NORMALIZED_KEYS = {
    semicolon:              ";",
    colon:                  ":",
    equal:                  "=",
    plus:                   "+",
    comma:                  ",",
    less:                   "<",
    minus:                  "-",
    underscore:             "_",
    period:                 ".",
    greater:                ">",
    slash:                  "/",
    questionmark:           "?",
    backtick:               "`",
    tilde:                  "~",
    openingsquarebracket:   "[",
    openingcurlybracket:    "{",
    backslash:              "\\",
    pipe:                   "|",
    closingsquarebracket:   "]",
    closingcurlybracket:    "}",
    singlequote:            "'",
    doublequote:            "\"",
    multiply:               "*",
    add:                    "+",
    subtract:               "-",
    decimal:                ".",
    divide:                 "/"
},
 
NORMALIZED_CHARS = null;    // Will be generated from the NORMALIZED_KEYS
 
 
/* Event type dispatched by KeyComposer */
var KEYPRESS_EVENT_TYPE = "keyPress",
    LONGKEYPRESS_EVENT_TYPE = "longKeyPress",
    KEYRELEASE_EVENT_TYPE = "keyRelease";
 
 
/**
 * The KeyManager dispatches KeyComposer events when it detects a keyComposer
 * has been pressed or released.  Do not create a KeyManager directly but
 * instead require for the defaultKeyManager:
 *
 * ```js
 * require("./key-manager").defaultKeyManager
 * ```
 *
 * @class KeyManager
 * @classdesc Dispatches events to a key composer. There can only be one.
 * @extends Montage
*/
var KeyManager = exports.KeyManager = Montage.specialize(/** @lends KeyManager# */ {
 
    /**
      @private
    */
    _keyEventsListenerInstalled: {
        value: false
    },
 
    /**
      @private
    */
    _composerKeyMap: {
        value: {}
    },
 
    /**
      @private
    */
    _triggeredKeys: {
        value: {}
    },
 
    /**
      @private
    */
    _longPressKeys: {
        value: {}
    },
 
    /**
      @private
    */
    _cleanupTimeout: {
        value: null
    },
 
    /**
      @private
    */
    _cleanupThreshold: {
        value: 2000
    },
 
    /**
      @private
    */
    _longPressThreshold: {
        value: 1000
    },
 
    /**
     * The number of milliseconds a key must be pressed in order to dispatch a
     * longKeyPress event.
     * @type {number}
     * @default 1000
     */
    longPressThreshold: {
        get: function () {
            return this._longPressThreshold;
        },
        set: function (value) {
            if (value > 0 && value !== this._longPressThreshold) {
                this._longPressThreshold = value;
                if (this._longPressThreshold > this._cleanupThreshold - 100) {
                    this._cleanupThreshold = this._longPressThreshold + 100;
                } else {
                    this._cleanupThreshold = 2000;
                }
            }
        }
    },
 
    /**
     * Register a composerKey.
     * @function
     * @param {Object} keyComposer. The key to register.
     */
    registerKey: {
        value: function (keyComposer) {
                // validates the keys:
            var normalizedKeys = this._normalizeKeySequence(keyComposer.keys),
                modifiersAndKey,
                map = this._composerKeyMap,
                mapModifiersEntry,
                mapKeyEntry,
                keyAlreadyRegistered = false,
                entry,
                i;
 
            Eif (normalizedKeys) {
                modifiersAndKey = this._convertKeysToModifiersAndKeyCode(normalizedKeys);
 
                mapModifiersEntry = map[modifiersAndKey.modifiers];
                if (!mapModifiersEntry) {
                    mapModifiersEntry = map[modifiersAndKey.modifiers] = {};
                }
                mapKeyEntry = mapModifiersEntry[modifiersAndKey.keyCode];
                if (mapKeyEntry) {
                    for (i in mapKeyEntry) {
                        entry = mapKeyEntry[i];
                        Iif (entry.object === keyComposer) {
                            entry.refCount ++;
                            keyAlreadyRegistered = true;
                            break;
                        }
                    }
                    Eif (!keyAlreadyRegistered) {
                        mapKeyEntry.push({object: keyComposer, refCount: 1});
                    }
                } else {
                    mapModifiersEntry[modifiersAndKey.keyCode] = [{object: keyComposer, refCount: 1}];
                }
 
                keyComposer._modifiers = modifiersAndKey.modifiers;
                keyComposer._keyCode = modifiersAndKey.keyCode;
 
                this._registerListeners();
            }
        }
    },
 
    /**
     * Unregister a composerKey. if a key has been registered multiple time,
     * unregister must be called the same amount of time before the key is
     * actually unregistered.
     * @function
     * @param {Object} keyComposer The key to unregister.
     */
    unregisterKey: {
        value: function (keyComposer) {
            var map = this._composerKeyMap,
                mapModifiersEntry,
                mapKeyEntry,
                entry,
                i;
 
            mapModifiersEntry = map[keyComposer._modifiers];
            Eif (mapModifiersEntry) {
                mapKeyEntry = mapModifiersEntry[keyComposer._keyCode];
                for (i in mapKeyEntry) {
                    entry = mapKeyEntry[i];
                    if (entry.object === keyComposer) {
                        entry.refCount --;
                        Eif (entry.refCount <= 0) {
                            mapKeyEntry.splice(i, 1);
                            Iif (mapKeyEntry.length === 0) {
                                delete mapModifiersEntry[keyComposer._keyCode];
                                if (Object.keys(mapModifiersEntry).length === 0) {
                                    delete map[keyComposer._modifiers];
                                    if (Object.keys(map).length === 0) {
                                        this._unregisterListeners();
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    },
 
    constructor: {
        value: function () {
            var userAgent = global.navigator ? global.navigator.userAgent : "",
                code;
 
            Iif (_defaultKeyManager) {
                console.warn("Rather than creating a new KeyManager object, you might want to use the default key manager");
            }
 
            // Browser detection
            Iif (userAgent.match(/ firefox\//i)) {
                this._firefox = true;
            } else Eif (userAgent.match(/ appleWebkit\//i)) {
                this._webkit = true;
                Iif (userAgent.match(/ chrome\//i)) {
                    this._chrome = true;
                }
            } else if (userAgent.match(/^opera\//i)) {
                this._opera = true;
            }
 
            // Platform Detection
            Eif (userAgent.match(/macintosh/i)) {
                this._mac = true;
                Iif (this._opera) {
                    this._operaMac = true;
                }
            }
 
            // Handle the platform specific COMMAND modifier
            Eif (this._mac) {
                MODIFIERS.command = MODIFIERS.meta;
            } else {
                MODIFIERS.command = MODIFIERS.control;
            }
 
            // Patch the KeyCode dictionary for Opera or Firefox
            Iif (this._operaMac) {
                for (code in OPERAMAC_KEYNAMES_TO_KEYCODES) {
                    KEYNAMES_TO_KEYCODES[code] = OPERAMAC_KEYNAMES_TO_KEYCODES[code];
                }
            }
            Iif (this._firefox) {
                for (code in FIREFOX_KEYNAMES_TO_KEYCODES) {
                    KEYNAMES_TO_KEYCODES[code] = FIREFOX_KEYNAMES_TO_KEYCODES[code];
                }
            }
 
            // Generate the KEYNAMES dictionary
            KEYCODES_TO_KEYNAMES = {};
            for (var keyName in KEYNAMES_TO_KEYCODES) {
                code = KEYNAMES_TO_KEYCODES[keyName];
                if (KEYCODES_TO_KEYNAMES[code] === undefined) {
                    // If we have more than one name for a keycode, use only the first one
                    KEYCODES_TO_KEYNAMES[code] = keyName;
                }
            }
 
            // Generate the NORMALIZED_CHARS dictionary
            NORMALIZED_CHARS = {};
            for (var keyName in NORMALIZED_KEYS) {
                code = NORMALIZED_KEYS[keyName];
                if (NORMALIZED_CHARS[code] === undefined) {
                    // If we have more than one name for a char, use only the first one
                    NORMALIZED_CHARS[code] = keyName;
                }
            }
 
            this._shiftKey = false;
            this._altKey = false;
            this._metaKey = false;
            this._ctrlKey = false;
        }
    },
 
    captureKeydown: {
        value: function (event) {
            var keyCode,
                identifierCode,
                keyIdentifier = event.key || event.keyIdentifier,
                submap,
                stopped = false;
 
            // console.log("  captureKeydown:", event.keyCode, event.charCode, event.keyIdentifier);
 
            this._preprocessKeyEvent(event);
            // console.log("KEYDOWN MODIFIERS:", this._modifiers, "KEYCODE:", this._keyCode);
 
            submap = this._submap;
            if (submap) {
                keyCode = this._keyCode;
 
                // Check the keyCode for a match...
                if (keyCode && submap[keyCode]) {
                    stopped = this._dispatchComposerKeyMatches(submap[keyCode], event);
                }
 
                // Check the keyIdentifier for a match
                if (!stopped && keyIdentifier) {
                    identifierCode = KEYNAMES_TO_KEYCODES[keyIdentifier.toLowerCase()] ||
                        this._decodeKeyIdentifier(keyIdentifier);
                    if (identifierCode && identifierCode !== keyCode && submap[identifierCode]) {
                        this._dispatchComposerKeyMatches(submap[identifierCode], event);
                    }
                }
            }
 
            this._setupCleanupTimer();
        }
    },
 
    captureKeypress: {
        value: function (event) {
            var charCode = event.charCode,
                keyIdentifier = event.key || event.keyIdentifier,
                keyCode,
                identifierCode,
                submap,
                stopped = false;
 
            // console.log("  captureKeypress:", event.keyCode, event.charCode, event.keyIdentifier, this._modifiers);
            this._preprocessKeyEvent(event);
 
            submap = this._submap;
            // console.log("KEYPRESS MODIFIERS:", this._modifiers, this._keyCode, event.charCode);
 
            if (submap) {
                keyCode = this._keyCode;
 
                // Check the keyCode for a match...
                if (keyCode && submap[keyCode]) {
                    stopped = this._dispatchComposerKeyMatches(submap[keyCode], event);
                }
 
                // Check the charCode for a match...
                if (!stopped && charCode && charCode !== keyCode && submap[charCode]) {
                    stopped = this._dispatchComposerKeyMatches(submap[charCode], event);
                }
 
                // Check the keyIdentifier for a match
                if (!stopped && keyIdentifier) {
                    identifierCode = KEYNAMES_TO_KEYCODES[keyIdentifier.toLowerCase()] ||
                        this._decodeKeyIdentifier(keyIdentifier);
                    if (identifierCode && identifierCode !== keyCode && submap[identifierCode]) {
                        this._dispatchComposerKeyMatches(submap[identifierCode], event);
                    }
                }
            }
 
            this._setupCleanupTimer();
        }
    },
 
    captureKeyup: {
        value: function (event) {
            var keyCode = event.keyCode,
                keyIdentifier = event.key || event.keyIdentifier,
                identifierCode,
                submap,
                dispatchedKeyCode = 0,
                triggeredKey,
                uuid,
                stopped = false;
 
            // Dispatch a keyup event for all composerKey triggered during the keydown/keypress phase
            // and for the current match
 
            // console.log("  captureKeyup:", event.keyCode, event.charCode, event.keyIdentifier);
            this._preprocessKeyEvent(event);
            submap = this._submap;
 
            // console.log("KEYUP MODIFIERS:", this._modifiers, this._keyCode);
            if (submap) {
                keyCode = this._keyCode;
 
                // Check the keyCode for a match...
                if (keyCode && submap[keyCode]) {
                    stopped = this._dispatchComposerKeyMatches(submap[keyCode], event);
                    dispatchedKeyCode = keyCode;
                }
 
                // Check the keyIdentifier for a match
                if (!stopped && keyIdentifier) {
                    identifierCode = KEYNAMES_TO_KEYCODES[keyIdentifier.toLowerCase()] ||
                        this._decodeKeyIdentifier(keyIdentifier);
                    if (identifierCode && identifierCode !== dispatchedKeyCode && submap[identifierCode]) {
                        stopped = this._dispatchComposerKeyMatches(submap[identifierCode], event);
                    }
                }
            }
 
            // In case the user release the modifier key before releasing the main key, we still need to fire a keyup event
            if (!stopped) {
                for (uuid in this._triggeredKeys) {
                    triggeredKey = this._triggeredKeys[uuid];
                    if (triggeredKey._keyCode == keyCode || triggeredKey._keyCode == identifierCode) {
                        this._dispatchComposerKeyMatches([triggeredKey], event);
                    }
                }
            }
 
            this._cleanup();
        }
    },
 
    _normalizeKeySequence: {
        value: function (keySequence) {
            var modifiersOrder = [MODIFIERS.meta.name, MODIFIERS.alt.name, MODIFIERS.control.name, MODIFIERS.shift.name],
                keys = keySequence.toLowerCase().replace(/ /g, "").replace(/\+\+/g, "+add").split("+"),
                nbrKeys = keys.length,
                key,
                normalizedKeys = [],
                i;
 
            for (i = 0; i < nbrKeys - 1; i ++) {
                // convert alias
                key = keys[i];
                key = KEYNAMES_ALIASES[key] || key;
 
                // make sure it's a modifier
                key = MODIFIERS[key];
                if (key) {
                    normalizedKeys.push(key.name);
                } else {
                    console.warn("Invalid key sequence (modifier):", keySequence);
                    return null;
                }
            }
 
            normalizedKeys.sort(function (a, b) {
                return modifiersOrder.indexOf(a) - modifiersOrder.indexOf(b);
            });
 
            key = keys[nbrKeys - 1];
            Iif (key.length > 1 && !KEYNAMES_TO_KEYCODES[key]) {
                console.warn("Invalid key sequence (key):", keySequence, key);
                return null;
            }
 
            Iif (normalizedKeys.length) {
                return normalizedKeys.join("+") + "+" + key;
            } else {
                return key;
            }
        }
    },
 
    _preprocessKeyEvent: {
        value: function (event) {
            var thisRef = this,
                eventType = event.type,
                keyCode = event.keyCode,
                keyIdentifier = event.key || event.keyIdentifier,
                modifiers,
                value;
 
            if (this._operaMac) {
                if (this._operaModifierTimeout) {
                    clearTimeout(this._operaModifierTimeout);
                    this._operaModifierTimeout = null;
                }
            }
 
            if (eventType == "keydown" || eventType == "keyup") {
                if (this._operaMac) {
                    // Opera Mac is not very good at keeping track of which modifiers are pressed or not!
                    value = (eventType == "keydown");
                    if (keyCode == KEYNAMES_TO_KEYCODES.shift) {
                        this._shiftKey = value;
                    } else if (keyCode == KEYNAMES_TO_KEYCODES.alt) {
                        this._altKey = value;
                    } else if (keyCode == KEYNAMES_TO_KEYCODES.meta) {
                        if (this._mac) {
                            this._metaKey = value;
                        }
                    } else if (keyCode == KEYNAMES_TO_KEYCODES.control) {
                        this._ctrlKey = value;
                    }
 
                    if (eventType == "keyup") {
                        // Setup a timeout to force reset the modifier state ~3 seconds after the last key up
                        // This is to recover when we miss a keyup event which seems to occurs once in a while with Opera
                        this._operaModifierTimeout = setTimeout(function (){
                            thisRef._shiftKey = false;
                            thisRef._altKey = false;
                            thisRef._metaKey = false;
                            thisRef._ctrlKey = false;
                            thisRef._operaModifierTimeout = null;
                        }, this._cleanupThreshold + 1000);
                    }
                } else {
                    this._shiftKey = event.shiftKey;
                    this._altKey = event.altKey;
                    this._metaKey = event.metaKey;
                    this._ctrlKey = event.ctrlKey;
                }
            }
 
            if (this._mac && this._webkit && keyCode == KEYNAMES_TO_KEYCODES.contextmenu) {
                // Webkit browsers will interpret the right command key as the window context-menu but will keep the
                // meta modifier on preventing us from having a "context-menu" shortcut. We need to clear the meta flag
                // (the limitation is that we wont be able to support a "META+CONTEXT-MENU" shortcut
                this._metaKey = false;
            }
 
            if (this._chrome) {
                // Chrome (at least on Mac) generate the same keycode for the NumKeyPad = and NumKeyPad +
                if (!this._shiftKey && keyCode == KEYNAMES_TO_KEYCODES.plus && (keyIdentifier === "U+002B" || keyIdentifier === "+")) {
                    event.keyCode = KEYNAMES_TO_KEYCODES.add;
                }
            }
 
            this._modifiers = modifiers = (this._shiftKey ? MODIFIERS.shift.value : 0) +
                (this._altKey ? MODIFIERS.alt.value : 0) +
                (this._metaKey ? MODIFIERS.meta.value : 0) +
                (this._ctrlKey ? MODIFIERS.control.value : 0);
 
            this._submap = this._composerKeyMap[modifiers];
            this._keyCode = event.keyCode;
            this._keyIdentifier = keyIdentifier;
        }
    },
 
    _registerListeners: {
        value: function () {
            if (!this._keyEventsListenerInstalled) {
                window.addEventListener("keydown", this, true);
                window.addEventListener("keypress", this, true);
                window.addEventListener("keyup", this, true);
                this._keyEventsListenerInstalled = true;
            }
        }
    },
 
    _unregisterListeners: {
        value: function () {
            if (this._keyEventsListenerInstalled) {
                window.removeEventListener("keydown", this, true);
                window.removeEventListener("keypress", this, true);
                window.removeEventListener("keyup", this, true);
                this._keyEventsListenerInstalled = false;
            }
        }
    },
 
    _dispatchComposerKeyMatches: {
        value: function (matches, event) {
            var thisRef = this,
                stopped = false,
                keyUp = event.type == "keyup",
                keyDown = event.type == "keydown",
                eventType = keyUp ? KEYRELEASE_EVENT_TYPE : KEYPRESS_EVENT_TYPE,
                nbrMatches = matches.length,
                keyComposer,
                keyComposerEvent,
                triggeredKeys,
                i;
 
            // Slice the array so that keys registered or unregistered during
            // dispatch don't break the dispatching
            matches = matches.slice();
 
            // matches could be either an array of matches or an array of keyComposers
            for (i = 0; i < nbrMatches && !stopped; i ++) {
                keyComposer = matches[i].object || matches[i];
 
                // Make sure keyboard event's target is a descendant of the keyComposer's element
                var target = event.target,
                    element = keyComposer.element,
                    onTarget = (keyComposer.element === window);
 
                while (!onTarget) {
                    onTarget = (target === element);
 
                    if (target == document) {
                        break;
                    } else {
                        target = target.parentElement;
                        if (!target) {
                            target = document;
                        }
                    }
                }
 
                // Most components can't receive key events directly: the events target the window,
                // but we should also fire them on composers of the activeTarget component
                if (!onTarget && defaultEventManager.activeTarget != keyComposer.component) {
                    continue;
                }
 
                if (keyUp) {
                    triggeredKeys = Object.keys(this._triggeredKeys);
                    if (triggeredKeys.indexOf(keyComposer.uuid) == -1) {
                        // Do not generate a keyup event if the composerKey has not been triggered on keydown or keypress
                        continue;
                    }
 
                    if (keyComposer._longPressTimeout) {
                        clearTimeout(keyComposer._longPressTimeout);
                        keyComposer._longPressTimeout = null;
                        delete this._longPressKeys[keyComposer.uuid];
                    }
                } else {
                    if (keyDown) {
                        // Reset trigger
                        delete this._triggeredKeys[keyComposer.uuid];
                    } else if (this._triggeredKeys[keyComposer.uuid]) {
                        // that key has already been triggered, let's ignore it...
                        continue;
                    }
 
                    if (keyComposer._shouldDispatchLongPress && !keyComposer._longPressTimeout) {
                        keyComposer._longPressTimeout = setTimeout(function () {
                            var longPressEvent = MutableEvent.fromEvent(longPressEvent);
                            longPressEvent.type = LONGKEYPRESS_EVENT_TYPE;
                            longPressEvent.activeElement = event.target;
                            longPressEvent.identifier = keyComposer.identifier;
 
                            keyComposer._longPressTimeout = null;
                            keyComposer.dispatchEvent(longPressEvent);
                            delete thisRef._longPressKeys[keyComposer.uuid];
                        }, this._longPressThreshold);
 
                        // Let's remember any longKeyPress key waiting for timeout
                        this._longPressKeys[keyComposer.uuid] = keyComposer;
                    }
                }
                
                keyComposerEvent = MutableEvent.fromEvent(event);
                keyComposerEvent.type = eventType;
                keyComposerEvent.activeElement = event.target;
                keyComposerEvent.identifier = keyComposer.identifier;
                keyComposerEvent.keyComposer = keyComposer;
 
                keyComposer.dispatchEvent(keyComposerEvent);
 
                if (keyComposerEvent.propagationStopped) {
                    stopped = true;
                }
 
                if (keyUp) {
                    // We already dispatched a keyup event for this key, let's remove it
                    delete this._triggeredKeys[keyComposer.uuid];
                } else {
                    // We need to remember any composerKey triggered during the keydown phase in order to generate an equivalent keyup
                    this._triggeredKeys[keyComposer.uuid] = keyComposer;
                }
            }
 
            // if the composer key even has been stopped, we need clean the list of triggered keys as we wont get a keyup event anymore.
            // We need also stop pending longPress key
            if (stopped) {
                for (i = (keyUp ? i : 0); i < nbrMatches; i ++) {
                    keyComposer = matches[i].object || matches[i];
                    delete this._triggeredKeys[keyComposer.uuid];
 
                    if (keyComposer._longPressTimeout) {
                        clearTimeout(keyComposer._longPressTimeout);
                        keyComposer._longPressTimeout = null;
                        delete this._longPressKeys[keyComposer.uuid];
                    }
                }
            }
 
            return stopped;
        }
    },
 
    _cleanup: {
        value: function () {
            var keyComposer,
                i;
 
            if (this._cleanupTimeout) {
                clearTimeout(this._cleanupTimeout);
            }
 
            for (i in this._triggeredKeys) {
                if (this._triggeredKeys.hasOwnProperty(i)) {
                    delete this._triggeredKeys[i];
                }
            }
 
            for (i in this._longPressKeys) {
                if (this._longPressKeys.hasOwnProperty(i)) {
                    keyComposer = this._longPressKeys[i];
                    clearTimeout(keyComposer._longPressTimeout);
                    keyComposer._longPressTimeout = null;
                    delete this._longPressKeys[i];
                }
            }
 
            this._cleanupTimeout = null;
        }
    },
 
    _setupCleanupTimer: {
        value: function () {
            var thisRef = this;
 
            // When a keydown event is stopped, we will not received the corresponding keyup event.
            // If we haven't detected any key events for 2 seconds, let's presume the user is done using the keyboard
            // and do some internal cleanup in case we missed some keyup events.
 
            if (this._cleanupTimeout) {
                clearTimeout(this._cleanupTimeout);
            }
            this._cleanupTimeout = setTimeout(function () {
                thisRef._cleanup();
            }, this._cleanupThreshold);
        }
    },
 
    _convertKeysToModifiersAndKeyCode: {
        value: function (keys) {
            var nbrKeys,
                key,
                i,
                keyCode = 0,
                modifiers = 0;
 
            keys = keys.toLowerCase().replace(/ /g, "").replace(/\+\+/g, "+add").split("+");
            nbrKeys = keys.length;
 
            // Convert the keys into a modifiers mask
            for (i = 0; i < nbrKeys - 1; i ++) {
                // convert alias
                key = keys[i];
                key = KEYNAMES_ALIASES[key] || key;
 
                // make sure it's a modifier
                key = MODIFIERS[key];
                if (key) {
                    modifiers |= key.value;
                } else {
                    console.warn("Invalid Key sequence:", keys);
                    return null;
                }
            }
 
            // Extract the final key
            key = keys[nbrKeys - 1];
            key = NORMALIZED_CHARS[key] || key;
            key = NORMALIZED_KEYS[key] || key;  // This is needed for browsers that don't use W3C Optional Key Codes
 
            Eif (key.length > 1) {
                keyCode = KEYNAMES_TO_KEYCODES[key];
 
                // If the key append to be a modifier, we need adjust modifiers accordingly
                key = MODIFIERS[KEYNAMES_ALIASES[key] || key];
                Iif (key) {
                    modifiers |= key.value;
                }
            } else {
                keyCode = key.toUpperCase().charCodeAt(0);
            }
 
            return {modifiers: modifiers, keyCode: keyCode};
        }
    },
 
    _decodeKeyIdentifier: {
        value: function (identifier) {
            if (identifier.match(/U\+/)) {
                return parseInt(identifier.substring(2), 16);
            }
        }
    }
});
 
var _defaultKeyManager = null;
Montage.defineProperty(exports, "defaultKeyManager", {
    get: function () {
        if (!_defaultKeyManager) {
            _defaultKeyManager = new KeyManager();
        }
        return _defaultKeyManager;
    }
});