// Establishes key-code definitions. /// // Defines our generalized "KeyEvent" class. /// // Defines default key handling behaviors. /// namespace com.keyman.text { export class LegacyKeyEvent { Ltarg: HTMLElement; Lcode: number; Lmodifiers: number; LisVirtualKey: number; } export class Processor { // Tracks the simulated value for supported state keys, allowing the OSK to mirror a physical keyboard for them. // Using the exact keyCode name from the Codes definitions will allow for certain optimizations elsewhere in the code. stateKeys = { "K_CAPS":false, "K_NUMLOCK":false, "K_SCROLL":false }; // Tracks the most recent modifier state information in order to quickly detect changes // in keyboard state not otherwise captured by the hosting page in the browser. // Needed for AltGr simulation. modStateFlags: number = 0; // Denotes whether or not KMW needs to 'swallow' the next keypress. swallowKeypress: boolean = false; /** * Get the default RuleBehavior for the specified key, attempting to mimic standard browser defaults * where and when appropriate. * * @param {object} Lkc The pre-analyzed key event object * @param {number} keyShiftState * @param {boolean} usingOSK * @return {string} */ defaultRuleBehavior(Lkc: KeyEvent, keyShiftState: number, usingOSK: boolean): RuleBehavior { let keyman = com.keyman.singleton; let outputTarget = Lkc.Ltarg; let preInput = Mock.from(outputTarget); let ruleBehavior = new RuleBehavior(); // check if exact match to SHIFT's code. Only the 'default' and 'shift' layers should have default key outputs. if (keyShiftState == Codes.modifierCodes['SHIFT']) { keyShiftState = 1; // It's used as an index in some called methods. } let matched = false; var char = ''; var special: EmulationKeystrokes; if(usingOSK || outputTarget.isSynthetic) { matched = true; // All the conditions below result in matches until the final else, which restores the expected default // if no match occurs. if(DefaultOutput.isCommand(Lkc)) { // Note this in the rule behavior, return successfully. We'll consider applying it later. ruleBehavior.triggersDefaultCommand = true; // We'd rather let the browser handle these keys, but we're using emulated keystrokes, forcing KMW // to emulate default behavior here. } else if(special = DefaultOutput.forSpecialEmulation(Lkc)) { switch(special) { case EmulationKeystrokes.Backspace: keyman.interface.defaultBackspace(outputTarget); break; case EmulationKeystrokes.Enter: outputTarget.handleNewlineAtCaret(); break; case EmulationKeystrokes.Space: keyman.interface.output(0, outputTarget, ' '); break; // case '\u007f': // K_DEL // // For (possible) future implementation. // // Would recommend (conceptually) equaling K_RIGHT + K_BKSP, the former of which would technically be a 'command'. default: // In case we extend the allowed set, but forget to implement its handling case above. ruleBehavior.errorLog = "Unexpected 'special emulation' character (\\u" + (special as String).kmwCharCodeAt(0).toString(16) + ") went unhandled!"; } } else { // Back to the standard default, pending normal matching. matched = false; } } if(!matched) { if(char = DefaultOutput.forAny(Lkc, keyShiftState)) { if(char == '\b') { // physical keystrokes. keyman.interface.defaultBackspace(outputTarget); } else { keyman.interface.output(0, outputTarget, char); } } else { // No match, no default RuleBehavior. return null; } } // Shortcut things immediately if there were issues generating this rule behavior. if(ruleBehavior.errorLog) { return ruleBehavior; } let transcription = outputTarget.buildTranscriptionFrom(preInput, Lkc); ruleBehavior.transcription = transcription; return ruleBehavior; } static getOutputTarget(Lelem?: HTMLElement): OutputTarget { let keyman = com.keyman.singleton; if(!Lelem && !keyman.isHeadless) { Lelem = keyman.domManager.getLastActiveElement(); if(!Lelem) { // If we're trying to find an active target but one doesn't exist, just return null. return null; } } // If we were provided an element or found an active element but it's improperly attached, that should cause an error. if(Lelem._kmwAttachment && Lelem._kmwAttachment.interface) { return Lelem._kmwAttachment.interface; } else { throw new Error("OSK could not find element output target data!"); } } _GetClickEventProperties(e: osk.ActiveKey, Lelem: HTMLElement): KeyEvent { let keyman = com.keyman.singleton; var activeKeyboard = keyman.keyboardManager.activeKeyboard; let formFactor = keyman.util.device.formFactor; // Get key name and keyboard shift state (needed only for default layouts and physical keyboard handling) // Note - virtual keys should be treated case-insensitive, so we force uppercasing here. var layer = e.layer || e.displayLayer || '', keyName=e.id.toUpperCase(); // Start: mirrors _GetKeyEventProperties // Override key shift state if specified for key in layout (corrected for popup keys KMEW-93) var keyShiftState = this.getModifierState(layer); // First check the virtual key, and process shift, control, alt or function keys var Lkc: KeyEvent = { Ltarg: Processor.getOutputTarget(Lelem), Lmodifiers: keyShiftState, Lstates: 0, Lcode: Codes.keyCodes[keyName], LisVirtualKey: true, vkCode: 0, kName: keyName, kLayer: layer, kbdLayer: e.displayLayer, kNextLayer: e.nextlayer }; // If it's actually a state key modifier, trigger its effects immediately, as KeyboardEvents would do the same. switch(keyName) { case 'K_CAPS': case 'K_NUMLOCK': case 'K_SCROLL': this.stateKeys[keyName] = ! this.stateKeys[keyName]; } // Performs common pre-analysis for both 'native' and 'embedded' OSK key & subkey input events. this.commonClickEventPreprocessing(Lkc); // End - mirrors _GetKeyEventProperties // Include *limited* support for mnemonic keyboards (Sept 2012) // If a touch layout has been defined for a mnemonic keyout, do not perform mnemonic mapping for rules on touch devices. if(activeKeyboard && activeKeyboard['KM'] && !(activeKeyboard['KVKL'] && formFactor != 'desktop')) { if(Lkc.Lcode != Codes.keyCodes['K_SPACE']) { // exception required, March 2013 // Jan 2019 - interesting that 'K_SPACE' also affects the caps-state check... Lkc.vkCode = Lkc.Lcode; this.setMnemonicCode(Lkc, layer.indexOf('shift') != -1, this.stateKeys['K_CAPS']); } } else { Lkc.vkCode=Lkc.Lcode; } // Support version 1.0 KeymanWeb keyboards that do not define positional vs mnemonic if(typeof activeKeyboard['KM'] == 'undefined') { Lkc.Lcode=keyman.keyMapManager._USKeyCodeToCharCode(Lkc); Lkc.LisVirtualKey=false; } return Lkc; } commonClickEventPreprocessing(Lkc: KeyEvent) { // Set the flags for the state keys. Lkc.Lstates |= this.stateKeys['K_CAPS'] ? Codes.modifierCodes['CAPS'] : Codes.modifierCodes['NO_CAPS']; Lkc.Lstates |= this.stateKeys['K_NUMLOCK'] ? Codes.modifierCodes['NUM_LOCK'] : Codes.modifierCodes['NO_NUM_LOCK']; Lkc.Lstates |= this.stateKeys['K_SCROLL'] ? Codes.modifierCodes['SCROLL_LOCK'] : Codes.modifierCodes['NO_SCROLL_LOCK']; // Set LisVirtualKey to false to ensure that nomatch rule does fire for U_xxxx keys if(Lkc.kName.substr(0,2) == 'U_') { Lkc.LisVirtualKey=false; } // Get code for non-physical keys (T_KOKAI, U_05AB etc) if(typeof Lkc.Lcode == 'undefined') { Lkc.Lcode = this.getVKDictionaryCode(Lkc.kName);// Updated for Build 347 if(!Lkc.Lcode) { // Special case for U_xxxx keys. This vk code will never be used // in a keyboard, so we use this to ensure that keystroke processing // occurs for the key. Lkc.Lcode = 1; } } // Handles modifier states when the OSK is emulating rightalt through the leftctrl-leftalt layer. if((Lkc.Lmodifiers & Codes.modifierBitmasks['ALT_GR_SIM']) == Codes.modifierBitmasks['ALT_GR_SIM'] && osk.Layouts.emulatesAltGr()) { Lkc.Lmodifiers &= ~Codes.modifierBitmasks['ALT_GR_SIM']; Lkc.Lmodifiers |= Codes.modifierCodes['RALT']; } } processKeystroke(keyEvent: KeyEvent, outputTarget: OutputTarget, fromOSK: boolean): RuleBehavior { let keyman = com.keyman.singleton; var activeKeyboard = keyman.keyboardManager.activeKeyboard; let kbdInterface = keyman.interface; let keyMapManager = keyman.keyMapManager; if(!keyman.isEmbedded && !fromOSK && keyman.util.device.browser == 'firefox') { // I1466 - Convert the - keycode on mnemonic as well as positional layouts // FireFox, Mozilla Suite if(keyMapManager.browserMap.FF['k'+keyEvent.Lcode]) { keyEvent.Lcode=keyMapManager.browserMap.FF['k'+keyEvent.Lcode]; } } var matchBehavior: RuleBehavior; this.swallowKeypress = false; // Pass this key code and state to the keyboard program if(activeKeyboard && keyEvent.Lcode != 0) { matchBehavior = kbdInterface.processKeystroke(fromOSK ? keyman.util.device : keyman.util.physicalDevice, outputTarget, keyEvent); } if(!matchBehavior) { // Restore the virtual key code if a mnemonic keyboard is being used // If no vkCode value was stored, maintain the original Lcode value. keyEvent.Lcode=keyEvent.vkCode || keyEvent.Lcode; // Handle unmapped keys, including special keys // The following is physical layout dependent, so should be avoided if possible. All keys should be mapped. kbdInterface.activeTargetOutput = outputTarget; // Match against the 'default keyboard' - rules to mimic the default string output when typing in a browser. // Many keyboards rely upon these 'implied rules'. matchBehavior = this.defaultRuleBehavior(keyEvent, keyEvent.Lmodifiers, fromOSK); kbdInterface.activeTargetOutput = null; } return matchBehavior; } /** * Simulate a keystroke according to the touched keyboard button element * * Handles default output and keyboard processing for both OSK and physical keystrokes. * * @param {Object} e The abstracted KeyEvent to use for keystroke processing */ processKeyEvent(keyEvent: KeyEvent, e?: osk.KeyElement | boolean): boolean { let keyman = com.keyman.singleton; // Determine the current target for text output and create a "mock" backup // of its current, pre-input state. let outputTarget = keyEvent.Ltarg; let fromOSK = !!e; // If specified, it's from the OSK. // Enables embedded-path OSK sourcing detection. if(typeof e == 'boolean') { e = null as osk.KeyElement; // Cast is necessary for TS type-checking later in the method. } let formFactor = keyman.util.device.formFactor; let keyMapManager = keyman.keyMapManager; this.swallowKeypress = false; if(fromOSK && !keyman.isEmbedded) { keyman.domManager.initActiveElement(keyEvent.Ltarg.getElement()); // Turn off key highlighting (or preview) keyman['osk'].vkbd.highlightKey(e,false); } // Exclude menu and OSK hide keys from normal click processing if(keyEvent.kName == 'K_LOPT' || keyEvent.kName == 'K_ROPT') { keyman['osk'].vkbd.optionKey(e, keyEvent.kName, true); return true; } // The default OSK layout for desktop devices does not include nextlayer info, relying on modifier detection here. // It's the OSK equivalent to doModifierPress on 'desktop' form factors. if((formFactor == 'desktop' || keyman.keyboardManager.layoutIsDesktopBased()) && fromOSK) { // If it's a desktop OSK style and this triggers a layer change, // a modifier key was clicked. No output expected, so it's safe to instantly exit. if(this.selectLayer(keyEvent.kName, keyEvent.kNextLayer)) { return true; } } // Will handle keystroke-based non-layer change modifier & state keys, mapping them through the physical keyboard's version // of state management. if(!fromOSK && this.doModifierPress(keyEvent, !fromOSK)) { return true; } if(!keyman.isEmbedded && !fromOSK && keyman.util.device.browser == 'firefox') { // I1466 - Convert the - keycode on mnemonic as well as positional layouts // FireFox, Mozilla Suite if(keyMapManager.browserMap.FF['k'+keyEvent.Lcode]) { keyEvent.Lcode=keyMapManager.browserMap.FF['k'+keyEvent.Lcode]; } } //else //{ // Safari, IE, Opera? //} // If suggestions exist AND space is pressed, accept the suggestion and do not process the keystroke. // If a suggestion was just accepted AND backspace is pressed, revert the change and do not process the backspace. // We check the first condition here, while the prediction UI handles the second through the try__() methods below. if(keyman.modelManager.enabled) { // The following code relies on JS's logical operator "short-circuit" properties to prevent unwanted triggering of the second condition. // Can the suggestion UI revert a recent suggestion? If so, do that and swallow the backspace. if((keyEvent.kName == "K_BKSP" || keyEvent.Lcode == Codes.keyCodes["K_BKSP"]) && keyman.modelManager.tryRevertSuggestion()) { return; // Can the suggestion UI accept an existing suggestion? If so, do that and swallow the space character. } else if((keyEvent.kName == "K_SPACE" || keyEvent.Lcode == Codes.keyCodes["K_SPACE"]) && keyman.modelManager.tryAcceptSuggestion('space')) { return; } } if(fromOSK && !keyman.isEmbedded) { keyman.uiManager.setActivatingUI(true); com.keyman.DOMEventHandlers.states._IgnoreNextSelChange = 100; keyman.domManager.focusLastActiveElement(); com.keyman.DOMEventHandlers.states._IgnoreNextSelChange = 0; } // // ...end I3363 (Build 301) let preInputMock = Mock.from(outputTarget); let ruleBehavior = this.processKeystroke(keyEvent, outputTarget, fromOSK); // Swap layer as appropriate. if(keyEvent.kNextLayer) { this.selectLayer(keyEvent.kName, keyEvent.kNextLayer); } // Should we swallow any further processing of keystroke events for this keydown-keypress sequence? if(ruleBehavior != null) { let alternates: Alternate[]; // If we're performing a 'default command', it's not a standard 'typing' event - don't do fat-finger stuff. // Also, don't do fat-finger stuff if predictive text isn't enabled. if(keyman.modelManager.enabled && !ruleBehavior.triggersDefaultCommand) { // Note - we don't yet do fat-fingering with longpress keys. if(keyEvent.keyDistribution && keyEvent.kbdLayer) { let activeLayout = keyman['osk'].vkbd.layout as osk.ActiveLayout; alternates = []; for(let pair of keyEvent.keyDistribution) { let mock = Mock.from(preInputMock); let altKey = activeLayout.getLayer(keyEvent.kbdLayer).getKey(pair.keyId); if(!altKey) { console.warn("Potential fat-finger key could not be found in layer!"); continue; } let altEvent = this._GetClickEventProperties(altKey, keyEvent.Ltarg.getElement()); altEvent.Ltarg = mock; let alternateBehavior = this.processKeystroke(altEvent, mock, fromOSK); if(alternateBehavior) { // TODO: if alternateBehavior.beep == true, set 'p' to 0. It's a disallowed key sequence, // so a user should never have intended to type it. Should probably renormalize // the distribution afterward, though... let transform: Transform = alternateBehavior.transcription.transform; // Ensure that the alternate's token id matches that of the current keystroke, as we only // record the matched rule's context (since they match) transform.id = ruleBehavior.transcription.token; alternates.push({sample: transform, 'p': pair.p}); } } } } // - start: application of 'delayed' effects specified by RuleBehaviors - if(ruleBehavior.beep) { // TODO: Must be relocated further 'out' to complete the full, planned web-core refactor. // We're still referencing the DOM, even if only the manager object. (It's an improvement, at least.) keyman.domManager.doBeep(outputTarget); } for(let storeID in ruleBehavior.setStore) { // TODO: Must be relocated further 'out' to complete the full, planned web-core refactor. // `Processor` shouldn't be directly setting anything on the OSK when the refactor is complete. // How would this be handled in an eventual headless mode? switch(Number.parseInt(storeID)) { // Because the number was converted into a String for 'dictionary' use. case KeyboardInterface.TSS_LAYER: keyman.osk.vkbd.showLayer(ruleBehavior.setStore[storeID]); //Build 350, osk reference now OK, so should work break; case KeyboardInterface.TSS_PLATFORM: console.error("Rule attempted to perform illegal operation - 'platform' may not be changed."); break; default: console.warn("Unknown store affected by keyboard rule: " + storeID); } } if(ruleBehavior.triggersDefaultCommand) { let keyEvent = ruleBehavior.transcription.keystroke; DefaultOutput.applyCommand(keyEvent, keyEvent.Lmodifiers); } if(ruleBehavior.warningLog) { console.warn(ruleBehavior.warningLog); } else if(ruleBehavior.errorLog) { console.error(ruleBehavior.errorLog); } // - end section // If the transform isn't empty, we've changed text - which should produce a 'changed' event in the DOM. // // TODO: This check should be done IN a dom module, not here in web-core space. This place is closer // to that goal than it previously was, at least. let ruleTransform = ruleBehavior.transcription.transform; if(ruleTransform.insert != "" || ruleTransform.deleteLeft > 0 || ruleTransform.deleteRight > 0) { if(outputTarget.getElement() == DOMEventHandlers.states.activeElement) { DOMEventHandlers.states.changed = true; } } // -- All keystroke (and 'alternate') processing is now complete. Time to finalize everything! -- // Notify the ModelManager of new input - it's predictive text time! ruleBehavior.transcription.alternates = alternates; // Yes, even for ruleBehavior.triggersDefaultCommand. Those tend to change the context. keyman.modelManager.predict(ruleBehavior.transcription); // KMEA and KMEI (embedded mode) use direct insertion of the character string if(keyman.isEmbedded) { // A special embedded callback used to setup direct callbacks to app-native code. keyman['oninserttext'](ruleTransform.deleteLeft, ruleTransform.insert, ruleTransform.deleteRight); } // Since this method now performs changes for 'default' keystrokes, synthetic 'change' event generation // belongs here, rather than only in interface.processKeystroke() as in versions pre-12. if(outputTarget.getElement()) { keyman['interface'].doInputEvent(outputTarget.getElement()); } this.swallowKeypress = (e && keyEvent.Lcode != 8 ? keyEvent.Lcode != 0 : false); if(keyEvent.Lcode == 8) { this.swallowKeypress = false; } return false; } else { this.swallowKeypress = false; } /* I732 END - 13/03/2007 MCD: End Positional Layout support in OSK */ if(fromOSK && !keyman.isEmbedded) { keyman.uiManager.setActivatingUI(false); // I2498 - KeymanWeb OSK does not accept clicks in FF when using automatic UI } // Special case for embedded to pass K_TAB back to device to process if(keyman.isEmbedded && (keyEvent.Lcode == Codes.keyCodes["K_TAB"] || keyEvent.Lcode == Codes.keyCodes["K_TABBACK"] || keyEvent.Lcode == Codes.keyCodes["K_TABFWD"])) { return false; } // TODO: rework the return value to be `ruleBehavior` instead. Functions that call this one are // the ones that should worry about event handler returns, etc. Not this one. // // They should also be the ones to handle the TODOs seen earlier in this function - // once THOSE are properly relocated. (They're too DOM-heavy to remain in web-core.) // Only return true (for the eventual event handler's return value) if we didn't match a rule. return ruleBehavior == null; } /** * Simulate a keystroke according to the touched keyboard button element * * Note that the test-case oriented 'recorder' stubs this method to facilitate OSK-based input * recording for use in test cases. If changing this function, please ensure the recorder is * not affected. * * @param {Object} e element touched (or clicked) */ clickKey(e: osk.KeyElement, touch?: Touch, layerId?: string, keyDistribution?: KeyDistribution) { let keyman = com.keyman.singleton; var Lelem = keyman.domManager.getLastActiveElement(); if(Lelem != null) { // Handle any DOM state management related to click inputs. let outputTarget = Processor.getOutputTarget(Lelem); keyman.domManager.initActiveElement(Lelem); // Turn off key highlighting (or preview) keyman['osk'].vkbd.highlightKey(e,false); // Clear any cached codepoint data; we can rebuild it if it's unchanged. outputTarget.invalidateSelection(); // Deadkey matching continues to be troublesome. // Deleting matched deadkeys here seems to correct some of the issues. (JD 6/6/14) outputTarget.deadkeys().deleteMatched(); // Delete any matched deadkeys before continuing let Lkc = this._GetClickEventProperties(e['key'].spec as osk.ActiveKey, Lelem); if(keyman.modelManager.enabled) { Lkc.source = touch; Lkc.keyDistribution = keyDistribution; } return this.processKeyEvent(Lkc, e); } else { return true; } } // FIXME: makes some bad assumptions. setMnemonicCode(Lkc: KeyEvent, shifted: boolean, capsActive: boolean) { // K_SPACE is not handled by defaultKeyOutput for physical keystrokes unless using touch-aliased elements. // It's also a "exception required, March 2013" for clickKey, so at least they both have this requirement. if(Lkc.Lcode != Codes.keyCodes['K_SPACE']) { // So long as the key name isn't prefixed with 'U_', we'll get a default mapping based on the Lcode value. // We need to determine the mnemonic base character - for example, SHIFT + K_PERIOD needs to map to '>'. let mappingEvent: KeyEvent = new KeyEvent(); for(var key in Lkc) { mappingEvent[key] = Lkc[key]; } // To facilitate storing relevant commands, we should probably reverse-lookup // the actual keyname instead. mappingEvent.kName = 'K_xxxx'; mappingEvent.Ltarg = new Mock(); // helps prevent breakage for mnemonics. var mappedChar: string = DefaultOutput.forAny(mappingEvent, (shifted ? 0x10 : 0)); /* First, save a backup of the original code. This one won't needlessly trigger keyboard * rules, but allows us to replicate/emulate commands after rule processing if needed. * (Like backspaces) */ Lkc.vkCode = Lkc.Lcode; if(mappedChar) { // Will return 96 for 'a', which is a keycode corresponding to Codes.keyCodes('K_NP1') - a numpad key. // That stated, we're in mnemonic mode - this keyboard's rules are based on the char codes. Lkc.Lcode = mappedChar.charCodeAt(0); } else { // Don't let command-type keys (like K_DEL, which will output '.' otherwise!) // trigger keyboard rules. delete Lkc.Lcode; } } if(capsActive) { // TODO: Needs fixing - does not properly mirror physical keystrokes, as Lcode range 96-111 corresponds // to numpad keys! (Physical keyboard section has its own issues here.) if((Lkc.Lcode >= 65 && Lkc.Lcode <= 90) /* 'A' - 'Z' */ || (Lkc.Lcode >= 97 && Lkc.Lcode <= 122) /* 'a' - 'z' */) { Lkc.Lmodifiers ^= 0x10; // Flip the 'shifted' bit, so it'll act as the opposite key. Lkc.Lcode ^= 0x20; // Flips the 'upper' vs 'lower' bit for the base 'a'-'z' ASCII alphabetics. } } } /** * Get modifier key state from layer id * * @param {string} layerId layer id (e.g. ctrlshift) * @return {number} modifier key state (desktop keyboards) */ getModifierState(layerId: string): number { var modifier=0; if(layerId.indexOf('shift') >= 0) { modifier |= Codes.modifierCodes['SHIFT']; } // The chiral checks must not be directly exclusive due each other to visual OSK feedback. var ctrlMatched=false; if(layerId.indexOf('leftctrl') >= 0) { modifier |= Codes.modifierCodes['LCTRL']; ctrlMatched=true; } if(layerId.indexOf('rightctrl') >= 0) { modifier |= Codes.modifierCodes['RCTRL']; ctrlMatched=true; } if(layerId.indexOf('ctrl') >= 0 && !ctrlMatched) { modifier |= Codes.modifierCodes['CTRL']; } var altMatched=false; if(layerId.indexOf('leftalt') >= 0) { modifier |= Codes.modifierCodes['LALT']; altMatched=true; } if(layerId.indexOf('rightalt') >= 0) { modifier |= Codes.modifierCodes['RALT']; altMatched=true; } if(layerId.indexOf('alt') >= 0 && !altMatched) { modifier |= Codes.modifierCodes['ALT']; } return modifier; } /** * @summary Look up a custom virtual key code in the virtual key code dictionary KVKD. On first run, will build the dictionary. * * `VKDictionary` is constructed from the keyboard's `KVKD` member. This list is constructed * at compile-time and is a list of 'additional' virtual key codes, starting at 256 (i.e. * outside the range of standard virtual key codes). These additional codes are both * `[T_xxx]` and `[U_xxxx]` custom key codes from the Keyman keyboard language. However, * `[U_xxxx]` keys only generate an entry in `KVKD` if there is a corresponding rule that * is associated with them in the keyboard rules. If the `[U_xxxx]` key code is only * referenced as the id of a key in the touch layout, then it does not get an entry in * the `KVKD` property. * * @private * @param {string} keyName custom virtual key code to lookup in the dictionary * @return {number} key code > 255 on success, or 0 if not found */ getVKDictionaryCode(keyName: string) { let keyman = com.keyman.singleton; var activeKeyboard = keyman.keyboardManager.activeKeyboard; if(!activeKeyboard['VKDictionary']) { var a=[]; if(typeof activeKeyboard['KVKD'] == 'string') { // Build the VK dictionary // TODO: Move the dictionary build into the compiler -- so compiler generates code such as following. // Makes the VKDictionary member unnecessary. // this.KVKD={"K_ABC":256,"K_DEF":257,...}; var s=activeKeyboard['KVKD'].split(' '); for(var i=0; i} KMW keyboard event object: * Description Get object with target element, key code, shift state, virtual key state * Ltarg=target element * Lcode=keyCode * Lmodifiers=shiftState * LisVirtualKeyCode e.g. ctrl/alt key * LisVirtualKey e.g. Virtual key or non-keypress event */ _GetKeyEventProperties(e: KeyboardEvent, keyState?: boolean): KeyEvent { let keyman = com.keyman.singleton; var s = new KeyEvent(); e = keyman._GetEventObject(e); // I2404 - Manage IE events in IFRAMEs if(e.cancelBubble === true) { return null; // I2457 - Facebook meta-event generation mess -- two events generated for a keydown in Facebook contentEditable divs } let target = keyman.util.eventTarget(e) as HTMLElement; if (target == null) { return null; } else if (target.nodeType == 3) {// defeat Safari bug target = target.parentNode as HTMLElement; } s.Ltarg = Processor.getOutputTarget(target); s.Lcode = this._GetEventKeyCode(e); if (s.Lcode == null) { return null; } // Stage 1 - track the true state of the keyboard's modifiers. var prevModState = this.modStateFlags, curModState = 0x0000; var ctrlEvent = false, altEvent = false; let keyCodes = Codes.keyCodes; switch(s.Lcode) { case keyCodes['K_CTRL']: // The 3 shorter "K_*CTRL" entries exist in some legacy keyboards. case keyCodes['K_LCTRL']: case keyCodes['K_RCTRL']: case keyCodes['K_CONTROL']: case keyCodes['K_LCONTROL']: case keyCodes['K_RCONTROL']: ctrlEvent = true; break; case keyCodes['K_LMENU']: // The 2 "K_*MENU" entries exist in some legacy keyboards. case keyCodes['K_RMENU']: case keyCodes['K_ALT']: case keyCodes['K_LALT']: case keyCodes['K_RALT']: altEvent = true; break; } /** * Two separate conditions exist that should trigger chiral modifier detection. Examples below use CTRL but also work for ALT. * * 1. The user literally just pressed CTRL, so the event has a valid `location` property we can utilize. * Problem: its layer isn't presently activated within the OSK. * * 2. CTRL has been held a while, so the OSK layer is valid, but the key event doesn't tell us the chirality of the active CTRL press. * Bonus issue: RAlt simulation may cause erasure of this location property, but it should ONLY be empty if pressed in this case. * We default to the 'left' variants since they're more likely to exist and cause less issues with RAlt simulation handling. * * In either case, `e.getModifierState("Control")` is set to true, but as a result does nothing to tell us which case is active. * * `e.location != 0` if true matches condition 1 and matches condition 2 if false. */ curModState |= (e.getModifierState("Shift") ? 0x10 : 0); let modifierCodes = Codes.modifierCodes; if(e.getModifierState("Control")) { curModState |= ((e.location != 0 && ctrlEvent) ? (e.location == 1 ? modifierCodes['LCTRL'] : modifierCodes['RCTRL']) : // Condition 1 prevModState & 0x0003); // Condition 2 } if(e.getModifierState("Alt")) { curModState |= ((e.location != 0 && altEvent) ? (e.location == 1 ? modifierCodes['LALT'] : modifierCodes['RALT']) : // Condition 1 prevModState & 0x000C); // Condition 2 } // Stage 2 - detect state key information. It can be looked up per keypress with no issue. s.Lstates = 0; s.Lstates |= e.getModifierState('CapsLock') ? modifierCodes['CAPS'] : modifierCodes['NO_CAPS']; s.Lstates |= e.getModifierState('NumLock') ? modifierCodes['NUM_LOCK'] : modifierCodes['NO_NUM_LOCK']; s.Lstates |= (e.getModifierState('ScrollLock') || e.getModifierState("Scroll")) // "Scroll" for IE9. ? modifierCodes['SCROLL_LOCK'] : modifierCodes['NO_SCROLL_LOCK']; // We need these states to be tracked as well for proper OSK updates. curModState |= s.Lstates; // Stage 3 - Set our modifier state tracking variable and perform basic AltGr-related management. s.LmodifierChange = this.modStateFlags != curModState; this.modStateFlags = curModState; // For European keyboards, not all browsers properly send both key-up events for the AltGr combo. var altGrMask = modifierCodes['RALT'] | modifierCodes['LCTRL']; if((prevModState & altGrMask) == altGrMask && (curModState & altGrMask) != altGrMask) { // We just released AltGr - make sure it's all released. curModState &= ~ altGrMask; } // Perform basic filtering for Windows-based ALT_GR emulation on European keyboards. if(curModState & modifierCodes['RALT']) { curModState &= ~modifierCodes['LCTRL']; } let modifierBitmasks = Codes.modifierBitmasks; // Stage 4 - map the modifier set to the appropriate keystroke's modifiers. if(keyman.keyboardManager.isChiral()) { s.Lmodifiers = curModState & modifierBitmasks.CHIRAL; // Note for future - embedding a kill switch here or in keymanweb.osk.emulatesAltGr would facilitate disabling // AltGr / Right-alt simulation. if(osk.Layouts.emulatesAltGr() && (s.Lmodifiers & modifierBitmasks['ALT_GR_SIM']) == modifierBitmasks['ALT_GR_SIM']) { s.Lmodifiers ^= modifierBitmasks['ALT_GR_SIM']; s.Lmodifiers |= modifierCodes['RALT']; } } else { // No need to sim AltGr here; we don't need chiral ALTs. s.Lmodifiers = (curModState & 0x10) | // SHIFT ((curModState & (modifierCodes['LCTRL'] | modifierCodes['RCTRL'])) ? 0x20 : 0) | ((curModState & (modifierCodes['LALT'] | modifierCodes['RALT'])) ? 0x40 : 0); } // Mnemonic handling. var activeKeyboard = keyman.keyboardManager.activeKeyboard; if(activeKeyboard && activeKeyboard['KM']) { // The following will never set a code corresponding to a modifier key, so it's fine to do this, // which may change the value of Lcode, here. this.setMnemonicCode(s, e.getModifierState("Shift"), e.getModifierState("CapsLock")); } // The 0x6F used to be 0x60 - this adjustment now includes the chiral alt and ctrl modifiers in that check. var LisVirtualKeyCode = (typeof e.charCode != 'undefined' && e.charCode != null && (e.charCode == 0 || (s.Lmodifiers & 0x6F) != 0)); s.LisVirtualKey = LisVirtualKeyCode || e.type != 'keypress'; let keyMapManager = keyman.keyMapManager; // Other minor physical-keyboard adjustments if(activeKeyboard && !activeKeyboard['KM']) { // Positional Layout /* 13/03/2007 MCD: Swedish: Start mapping of keystroke to US keyboard */ var Lbase=keyMapManager.languageMap[com.keyman.osk.Layouts._BaseLayout]; if(Lbase && Lbase['k'+s.Lcode]) { s.Lcode=Lbase['k'+s.Lcode]; } /* 13/03/2007 MCD: Swedish: End mapping of keystroke to US keyboard */ if(typeof(activeKeyboard['KM'])=='undefined' && !(s.Lmodifiers & 0x60)) { // Support version 1.0 KeymanWeb keyboards that do not define positional vs mnemonic s = { Lcode: keyMapManager._USKeyCodeToCharCode(s), Ltarg: s.Ltarg, Lmodifiers: 0, LisVirtualKey: false, vkCode: s.Lcode, // Helps to merge OSK and physical keystroke control paths. Lstates: s.Lstates, kName: '' }; } } return s; } /** * Function keyDown * Scope Public * Description Processes keydown event and passes data to keyboard. * * Note that the test-case oriented 'recorder' stubs this method to facilitate keystroke * recording for use in test cases. If changing this function, please ensure the recorder is * not affected. */ keyDown(e: KeyboardEvent): boolean { this.swallowKeypress = false; // Get event properties var Levent = this._GetKeyEventProperties(e, true); if(Levent == null) { return true; } var LeventMatched = !this.processKeyEvent(Levent); if(LeventMatched) { if(e && e.preventDefault) { e.preventDefault(); e.stopPropagation(); } } return !LeventMatched; } // KeyUp basically exists for two purposes: // 1) To detect browser form submissions (handled in kmwdomevents.ts) // 2) To detect modifier state changes. keyUp(e: KeyboardEvent): boolean { var Levent = this._GetKeyEventProperties(e, false); if(Levent == null) { return true; } return this.doModifierPress(Levent, false); } keyPress(e: KeyboardEvent): boolean { let keyman = com.keyman.singleton; var Levent = this._GetKeyEventProperties(e); if(Levent == null || Levent.LisVirtualKey) { return true; } // _Debug('KeyPress code='+Levent.Lcode+'; Ltarg='+Levent.Ltarg.tagName+'; LisVirtualKey='+Levent.LisVirtualKey+'; _KeyPressToSwallow='+keymanweb._KeyPressToSwallow+'; keyCode='+(e?e.keyCode:'nothing')); /* I732 START - 13/03/2007 MCD: Swedish: Start positional keyboard layout code: prevent keystroke */ if(!keyman.keyboardManager.activeKeyboard['KM']) { if(!this.swallowKeypress) { return true; } if(Levent.Lcode < 0x20 || ((keyman)._BrowserIsSafari && (Levent.Lcode > 0xF700 && Levent.Lcode < 0xF900))) { return true; } e = keyman._GetEventObject(e); // I2404 - Manage IE events in IFRAMEs if(e) { e.returnValue = false; } return false; } /* I732 END - 13/03/2007 MCD: Swedish: End positional keyboard layout code */ let outputTarget = Levent.Ltarg; // Only reached if it's a mnemonic keyboard. if(this.swallowKeypress || keyman['interface'].processKeystroke(keyman.util.physicalDevice, Levent.Ltarg, Levent)) { this.swallowKeypress = false; if(e && e.preventDefault) { e.preventDefault(); e.stopPropagation(); } return false; } this.swallowKeypress = false; return true; } } }