UNPKG

@theia/core

Version:

Theia is a cloud & desktop IDE framework implemented in TypeScript.

1,141 lines • 53.3 kB
// *****************************************************************************
// Copyright (C) 2017 TypeFox and others.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0.
//
// This Source Code may also be made available under the following Secondary
// Licenses when the conditions for such availability set forth in the Eclipse
// Public License v. 2.0 are satisfied: GNU General Public License, version 2
// with the GNU Classpath Exception which is available at
// https://www.gnu.org/software/classpath/license.html.
//
// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0
// *****************************************************************************
var KeybindingRegistry_1;
import { __decorate } from "tslib";
import { injectable, inject, named } from 'inversify';
import { isOSX, isWindows } from '../common/os.js';
import { Emitter } from '../common/event.js';
import { CommandRegistry, Command } from '../common/command.js';
import { Disposable, DisposableCollection } from '../common/disposable.js';
import { KeyCode, KeySequence, Key, normalizeKeyboardInput, layoutModifiersIncludeAltGraph, layoutModifiersIncludeShift } from './keyboard/keys.js';
import { KeyboardLayoutService } from './keyboard/keyboard-layout-service.js';
import { ContributionProvider } from '../common/contribution-provider.js';
import { ILogger } from '../common/logger.js';
import { StatusBarAlignment, StatusBar } from './status-bar/status-bar.js';
import { ContextKeyService } from './context-key-service.js';
import { CorePreferences } from '../common/core-preferences.js';
import * as common from '../common/keybinding.js';
import { nls } from '../common/nls.js';
import { TernarySearchTree } from '../common/ternary-search-tree.js';
export var KeybindingScope;
(function (KeybindingScope) {
    KeybindingScope[KeybindingScope["DEFAULT"] = 0] = "DEFAULT";
    KeybindingScope[KeybindingScope["USER"] = 1] = "USER";
    KeybindingScope[KeybindingScope["WORKSPACE"] = 2] = "WORKSPACE";
    KeybindingScope[KeybindingScope["END"] = 3] = "END";
})(KeybindingScope || (KeybindingScope = {}));
(function (KeybindingScope) {
    KeybindingScope.length = KeybindingScope.END - KeybindingScope.DEFAULT;
})(KeybindingScope || (KeybindingScope = {}));
export const Keybinding = common.Keybinding;
export const KeybindingContribution = Symbol('KeybindingContribution');
export const KeybindingContext = Symbol('KeybindingContext');
export var KeybindingContexts;
(function (KeybindingContexts) {
    KeybindingContexts.NOOP_CONTEXT = {
        id: 'noop.keybinding.context',
        isEnabled: () => true
    };
    KeybindingContexts.DEFAULT_CONTEXT = {
        id: 'default.keybinding.context',
        isEnabled: () => false
    };
})(KeybindingContexts || (KeybindingContexts = {}));
let KeybindingRegistry = class KeybindingRegistry {
    constructor() {
        this.keySequenceCandidates = [[]];
        /** Whether keyboard shortcut troubleshooting logs are enabled. */
        this.keyboardShortcutsTroubleshooting = false;
        this.contexts = {};
        this.keymaps = [...Array(KeybindingScope.length)].map(() => []);
        this.handledKeyboardEvents = new WeakSet();
        this.warnedAmbiguousSequences = new Set();
        this.keybindingsChanged = new Emitter();
        this.toResetKeymap = new Map();
    }
    static { KeybindingRegistry_1 = this; }
    static { this.PASSTHROUGH_PSEUDO_COMMAND = 'passthrough'; }
    async onStart() {
        await this.keyboardLayoutService.initialize();
        this.keyboardLayoutService.onKeyboardLayoutChanged(() => this.invalidateResolvedKeybindings());
        this.corePreferences.onPreferenceChanged(change => {
            if (change.preferenceName === 'keyboard.dispatch') {
                this.invalidateResolvedKeybindings();
            }
        });
        this.registerContext(KeybindingContexts.NOOP_CONTEXT);
        this.registerContext(KeybindingContexts.DEFAULT_CONTEXT);
        this.registerContext(...this.contextProvider.getContributions());
        for (const contribution of this.contributions.getContributions()) {
            contribution.registerKeybindings(this);
        }
    }
    /**
     * Event that is fired when the resolved keybindings change due to a different keyboard layout
     * or when a new keymap is being set
     */
    get onKeybindingsChanged() {
        return this.keybindingsChanged.event;
    }
    /**
     * Registers the keybinding context arguments into the application. Fails when an already registered
     * context is being registered.
     *
     * @param contexts the keybinding contexts to register into the application.
     */
    registerContext(...contexts) {
        for (const context of contexts) {
            const { id } = context;
            if (this.contexts[id]) {
                this.logger.error(`A keybinding context with ID ${id} is already registered.`);
            }
            else {
                this.contexts[id] = context;
            }
        }
    }
    /**
     * Register a default keybinding to the registry.
     *
     * Keybindings registered later have higher priority during evaluation.
     *
     * @param binding the keybinding to be registered
     */
    registerKeybinding(binding) {
        return this.doRegisterKeybinding(binding);
    }
    /**
     * Register multiple default keybindings to the registry
     *
     * @param bindings An array of keybinding to be registered
     */
    registerKeybindings(...bindings) {
        return this.doRegisterKeybindings(bindings, KeybindingScope.DEFAULT);
    }
    unregisterKeybinding(arg) {
        const keymap = this.keymaps[KeybindingScope.DEFAULT];
        const filter = Command.is(arg)
            ? ({ command }) => command === arg.id
            : ({ keybinding }) => Keybinding.is(arg)
                ? keybinding === arg.keybinding
                : keybinding === arg;
        let removed = false;
        for (const binding of keymap.filter(filter)) {
            const idx = keymap.indexOf(binding);
            if (idx !== -1) {
                keymap.splice(idx, 1);
                removed = true;
            }
        }
        if (removed) {
            this.invalidateKeybindingTree();
        }
    }
    doRegisterKeybindings(bindings, scope = KeybindingScope.DEFAULT) {
        const toDispose = new DisposableCollection();
        for (const binding of bindings) {
            toDispose.push(this.doRegisterKeybinding(binding, scope));
        }
        return toDispose;
    }
    doRegisterKeybinding(binding, scope = KeybindingScope.DEFAULT) {
        try {
            this.resolveKeybinding(binding);
            const scoped = Object.assign(binding, { scope });
            this.insertBindingIntoScope(scoped, scope);
            this.invalidateKeybindingTree();
            return Disposable.create(() => {
                const index = this.keymaps[scope].indexOf(scoped);
                if (index !== -1) {
                    this.keymaps[scope].splice(index, 1);
                    this.invalidateKeybindingTree();
                }
            });
        }
        catch (error) {
            this.logger.warn(`Could not register keybinding:\n  ${common.Keybinding.stringify(binding)}\n${error}`);
            return Disposable.NULL;
        }
    }
    /**
     * Ensures that keybindings are inserted in order of increasing length of binding to ensure that if a
     * user triggers a short keybinding (e.g. ctrl+k), the UI won't wait for a longer one (e.g. ctrl+k enter)
     */
    insertBindingIntoScope(item, scope) {
        const scopedKeymap = this.keymaps[scope];
        const getNumberOfKeystrokes = (binding) => (binding.keybinding.trim().match(/\s/g)?.length ?? 0) + 1;
        const numberOfKeystrokesInBinding = getNumberOfKeystrokes(item);
        const indexOfFirstItemWithEqualStrokes = scopedKeymap.findIndex(existingBinding => getNumberOfKeystrokes(existingBinding) === numberOfKeystrokesInBinding);
        if (indexOfFirstItemWithEqualStrokes > -1) {
            scopedKeymap.splice(indexOfFirstItemWithEqualStrokes, 0, item);
        }
        else {
            scopedKeymap.push(item);
        }
    }
    /**
     * Ensure that the `resolved` property of the given binding is set by calling the KeyboardLayoutService.
     */
    resolveKeybinding(binding) {
        if (!binding.resolved) {
            const sequence = KeySequence.parse(binding.keybinding);
            const resolved = this.corePreferences['keyboard.dispatch'] === 'keyCode'
                ? sequence
                : sequence.map(code => this.keyboardLayoutService.resolveKeyCode(code));
            binding.inactiveReason = this.getInactiveReason(resolved, this.corePreferences['keyboard.dispatch']);
            binding.inactive = binding.inactiveReason !== undefined;
            binding.resolved = resolved;
        }
        return binding.resolved;
    }
    getInactiveReason(sequence, dispatch) {
        if (dispatch === 'keyCode' && sequence.some(code => code.character !== undefined && !code.key)) {
            return nls.localize('theia/core/keybinding/characterRequiresCodeDispatch', 'Character keybindings require the "keyboard.dispatch" preference to be set to "code".');
        }
        if (sequence.some(code => code.shift && layoutModifiersIncludeAltGraph(code.layoutModifiers)
            && !layoutModifiersIncludeShift(code.layoutModifiers))) {
            return nls.localize('theia/core/keybinding/shiftedAltGraphCharacterUnavailable', 'The logical character and Shift command modifier cannot be produced together on the current keyboard layout.');
        }
        // On macOS, Option selects the AltGraph layer. On Windows, AltGr is reported as Ctrl+Alt, so both Ctrl and Alt are
        // consumed by the layout layer. Linux keeps Alt and AltGraph distinct.
        const altGraphCodes = isOSX || isWindows ? sequence.filter(code => layoutModifiersIncludeAltGraph(code.layoutModifiers)) : [];
        const consumedModifier = altGraphCodes.some(code => code.alt) ? (isOSX ? 'Option' : 'Alt')
            : isWindows && altGraphCodes.some(code => code.ctrl) ? 'Ctrl' : undefined;
        if (consumedModifier) {
            return nls.localize('theia/core/keybinding/commandModifierAltGraphCharacterUnavailable', 'The logical character and the {0} command modifier cannot be produced together on the current keyboard layout.', consumedModifier);
        }
        if (sequence.some(code => !code.supportedByLayout)) {
            return nls.localize('theia/core/keybinding/unavailableCharacter', 'The key is not available on the current keyboard layout.');
        }
        return undefined;
    }
    /** Return the localized explanation when a binding is inactive on the current layout. */
    getKeybindingInactiveReason(binding) {
        this.resolveKeybinding(binding);
        return binding.inactiveReason;
    }
    /** Return whether a binding is inactive on the current keyboard layout. */
    isKeybindingInactive(binding) {
        this.resolveKeybinding(binding);
        return !!binding.inactive;
    }
    /** Clear cached resolutions, invalidate the lookup tree, and notify listeners. */
    invalidateResolvedKeybindings() {
        this.clearResolvedKeybindings();
        this.invalidateKeybindingTree();
        this.keybindingsChanged.fire(undefined);
    }
    /**
     * Clear all `resolved` properties of registered keybindings so the keyboard layout service resolves them again.
     */
    clearResolvedKeybindings() {
        for (let i = KeybindingScope.DEFAULT; i < KeybindingScope.END; i++) {
            const bindings = this.keymaps[i];
            for (let j = 0; j < bindings.length; j++) {
                const binding = bindings[j];
                binding.resolved = undefined;
                binding.inactive = undefined;
                binding.inactiveReason = undefined;
            }
        }
    }
    /**
     * Invalidates the keybinding tree, causing it to be rebuilt on next access.
     */
    invalidateKeybindingTree() {
        this.keybindingTree = undefined;
        this.warnedAmbiguousSequences.clear();
    }
    /**
     * Gets or builds the keybinding tree for efficient lookup.
     * The tree maps resolved key sequences to arrays of bindings sorted by scope (highest first).
     */
    getKeybindingTree() {
        if (!this.keybindingTree) {
            this.keybindingTree = this.buildKeybindingTree();
        }
        return this.keybindingTree;
    }
    /**
     * Builds a ternary search tree from all registered keybindings for efficient lookup.
     * Bindings are indexed by their resolved key sequence.
     * Bindings are stored in the order they should be checked: highest scope first,
     * and within the same scope, in the order they appear in keymaps (later-registered first).
     */
    buildKeybindingTree() {
        const tree = TernarySearchTree.forKeySequences();
        // Process scopes from highest to lowest priority (WORKSPACE > USER > DEFAULT)
        // Within each scope, maintain the keymaps order (later-registered bindings are at the front)
        for (let scope = KeybindingScope.END - 1; scope >= KeybindingScope.DEFAULT; scope--) {
            for (const binding of this.keymaps[scope]) {
                try {
                    const resolved = this.resolveKeybinding(binding);
                    if (this.isKeybindingInactive(binding)) {
                        continue;
                    }
                    const runtime = { binding, sequence: resolved };
                    const existing = tree.get(resolved);
                    if (existing) {
                        existing.push(runtime);
                    }
                    else {
                        tree.set(resolved, [runtime]);
                    }
                }
                catch (error) {
                    // Skip bindings that can't be resolved
                    this.logger.warn(`Could not resolve keybinding for tree: ${common.Keybinding.stringify(binding)}`);
                }
            }
        }
        return tree;
    }
    /**
     * Checks whether a colliding {@link common.Keybinding} exists in a specific scope.
     * @param binding the keybinding to check
     * @param scope the keybinding scope to check
     * @returns true if there is a colliding keybinding
     */
    containsKeybindingInScope(binding, scope = KeybindingScope.USER) {
        const diagnostics = this.getKeybindingCollisionDiagnostics(binding, scope);
        return [diagnostics.authored, diagnostics.layoutDerived].some(result => result.full.length > 0 || result.partial.length > 0 || result.shadow.length > 0);
    }
    /** Return authored, layout-resolved, and shadowing collision diagnostics for a binding. */
    getKeybindingCollisionDiagnostics(binding, scope = KeybindingScope.USER) {
        const diagnostics = {
            authored: new KeybindingRegistry_1.KeybindingsResult(),
            layoutDerived: new KeybindingRegistry_1.KeybindingsResult(),
            shadowedBy: []
        };
        const sequence = this.resolveKeybinding(binding);
        if (this.isKeybindingInactive(binding)) {
            return diagnostics;
        }
        const candidates = this.getUsableBindings(this.keymaps[scope]).filter(candidate => candidate !== binding
            && candidate.context === binding.context && !candidate.when && !binding.when);
        for (const candidate of candidates) {
            const resolved = this.resolveKeybinding(candidate);
            const target = resolved.some(code => code.layoutModifiers !== 'none')
                ? diagnostics.layoutDerived
                : diagnostics.authored;
            target.merge(this.getKeySequenceCollisions([candidate], sequence));
        }
        diagnostics.shadowedBy.push(...this.getShadowingKeybindings(binding, scope));
        return diagnostics;
    }
    /** Return bindings whose command-modifier interpretation takes the keystroke instead of the supplied binding. */
    getShadowingKeybindings(binding, scope) {
        const sequence = this.resolveKeybinding(binding);
        if (!sequence.some(code => code.layoutModifiers !== 'none')) {
            return [];
        }
        const commandSequence = sequence.map(code => code.layoutModifiers !== 'none' ? new KeyCode({
            key: code.key,
            ctrl: code.ctrl,
            shift: code.shift || layoutModifiersIncludeShift(code.layoutModifiers),
            alt: code.alt || layoutModifiersIncludeAltGraph(code.layoutModifiers),
            meta: code.meta,
            character: code.key?.easyString,
            interpretation: 'commandModifiers'
        }) : code);
        const result = [];
        const matchesContext = (candidate) => candidate !== binding
            && candidate.context === binding.context && candidate.when === binding.when;
        const firstScope = scope ?? KeybindingScope.END - 1;
        const lastScope = scope ?? KeybindingScope.DEFAULT;
        for (let currentScope = firstScope; currentScope >= lastScope; currentScope--) {
            const collisions = this.getKeySequenceCollisions(this.getUsableBindings(this.keymaps[currentScope]), commandSequence);
            result.push(...collisions.full.filter(matchesContext));
        }
        return result;
    }
    /**
     * Get a user visible representation of a {@link common.Keybinding}.
     * @returns an array of strings representing all elements of the {@link KeySequence} defined by the {@link common.Keybinding}
     * @param keybinding the keybinding
     * @param separator the separator to be used to stringify {@link KeyCode}s that are part of the {@link KeySequence}
     * @param form whether to render logical characters or their physical realization
     */
    acceleratorFor(keybinding, separator = ' ', asciiOnly = false, form = 'logical') {
        const bindingKeySequence = this.resolveKeybinding(keybinding);
        return this.acceleratorForSequence(bindingKeySequence, separator, asciiOnly, form);
    }
    /**
     * Get a user visible representation of a {@link KeySequence}.
     * @returns an array of strings representing all elements of the {@link KeySequence}
     * @param keySequence the keysequence
     * @param separator the separator to be used to stringify {@link KeyCode}s that are part of the {@link KeySequence}
     * @param form whether to render logical characters or their physical realization
     */
    acceleratorForSequence(keySequence, separator = ' ', asciiOnly = false, form = 'logical') {
        return keySequence.map(keyCode => this.acceleratorForKeyCode(keyCode, separator, asciiOnly, form));
    }
    /**
     * Get a user visible representation of a key code (a key with modifiers).
     * @returns a string representing the {@link KeyCode}
     * @param keyCode the keycode
     * @param separator the separator used to separate keys (key and modifiers) in the returning string.
     * Ignored when rendering macOS symbols (i.e. on macOS with `asciiOnly=false`), as the convention is
     * to juxtapose modifier symbols without a separator (e.g. `⌃⌘V`).
     * @param asciiOnly if `true`, no special characters will be substituted into the string returned. Ensures correct keyboard shortcuts in Electron menus.
     * @param form whether to render the logical character or its physical realization
     */
    acceleratorForKeyCode(keyCode, separator = ' ', asciiOnly = false, form = 'logical') {
        const useSymbols = isOSX && !asciiOnly;
        return this.componentsForKeyCode(keyCode, asciiOnly, form).join(useSymbols ? '' : separator);
    }
    componentsForKeyCode(keyCode, asciiOnly = false, form = 'logical') {
        if (form === 'physical') {
            const physical = new KeyCode({
                key: keyCode.key,
                meta: keyCode.meta,
                ctrl: keyCode.ctrl,
                alt: keyCode.alt,
                shift: keyCode.shift || layoutModifiersIncludeShift(keyCode.layoutModifiers)
            });
            const result = this.componentsForKeyCode(physical, asciiOnly);
            if (layoutModifiersIncludeAltGraph(keyCode.layoutModifiers)) {
                const layoutModifier = isOSX ? (asciiOnly ? 'Option' : '⌥') : 'AltGr';
                const keyIndex = result.length - (physical.key ? 1 : 0);
                if (!(isOSX && keyCode.alt)) {
                    result.splice(keyIndex, 0, layoutModifier);
                }
            }
            return result;
        }
        const keyCodeResult = [];
        const useSymbols = isOSX && !asciiOnly;
        if (keyCode.meta && isOSX) {
            keyCodeResult.push(useSymbols ? '⌘' : 'Cmd');
        }
        if (keyCode.ctrl) {
            keyCodeResult.push(useSymbols ? '⌃' : 'Ctrl');
        }
        if (keyCode.alt) {
            keyCodeResult.push(useSymbols ? '⌥' : 'Alt');
        }
        if (this.displaysShift(keyCode)) {
            keyCodeResult.push(useSymbols ? '⇧' : 'Shift');
        }
        if (keyCode.character) {
            keyCodeResult.push(this.acceleratorForCharacter(keyCode.character));
        }
        else if (keyCode.key) {
            keyCodeResult.push(this.acceleratorForKey(keyCode.key, asciiOnly));
        }
        return keyCodeResult;
    }
    /**
     * Whether the logical label of a key code shows Shift: when Shift is a command modifier or produces an uppercase letter.
     * Shift that only selects a layout layer for other characters (e.g. `/` on German layouts) is not shown.
     */
    displaysShift(keyCode) {
        return keyCode.shift || layoutModifiersIncludeShift(keyCode.layoutModifiers) && !!keyCode.character && /^[A-Z]$/.test(keyCode.character);
    }
    acceleratorForCharacter(character) {
        return /^[a-z]$/i.test(character) ? character.toUpperCase() : character;
    }
    /**
     * @param asciiOnly if `true`, no special characters will be substituted into the string returned. Ensures correct keyboard shortcuts in Electron menus.
     *
     * Return a user visible representation of a single key.
     */
    acceleratorForKey(key, asciiOnly = false) {
        if (isOSX && !asciiOnly) {
            if (key === Key.ARROW_LEFT) {
                return '←';
            }
            if (key === Key.ARROW_RIGHT) {
                return '→';
            }
            if (key === Key.ARROW_UP) {
                return '↑';
            }
            if (key === Key.ARROW_DOWN) {
                return '↓';
            }
        }
        const keyString = this.keyboardLayoutService.getKeyboardCharacter(key);
        if (key.keyCode >= Key.KEY_A.keyCode && key.keyCode <= Key.KEY_Z.keyCode ||
            key.keyCode >= Key.F1.keyCode && key.keyCode <= Key.F24.keyCode) {
            return keyString.toUpperCase();
        }
        else if (keyString.length > 1) {
            return keyString.charAt(0).toUpperCase() + keyString.slice(1);
        }
        else {
            return keyString;
        }
    }
    /**
     * Finds collisions for a key sequence inside a list of bindings (error-free)
     *
     * @param bindings the reference bindings
     * @param candidate the sequence to match
     */
    getKeySequenceCollisions(bindings, candidate) {
        const result = new KeybindingRegistry_1.KeybindingsResult();
        for (const binding of bindings) {
            try {
                const bindingKeySequence = this.resolveKeybinding(binding);
                if (this.isKeybindingInactive(binding)) {
                    continue;
                }
                const compareResult = KeySequence.compare(candidate, bindingKeySequence);
                switch (compareResult) {
                    case KeySequence.CompareResult.FULL: {
                        result.full.push(binding);
                        break;
                    }
                    case KeySequence.CompareResult.PARTIAL: {
                        result.partial.push(binding);
                        break;
                    }
                    case KeySequence.CompareResult.SHADOW: {
                        result.shadow.push(binding);
                        break;
                    }
                }
            }
            catch (error) {
                this.logger.warn(error);
            }
        }
        return result;
    }
    /**
     * Get all keybindings associated to a commandId.
     *
     * @param commandId The ID of the command for which we are looking for keybindings.
     * @returns an array of {@link ScopedKeybinding}
     */
    getKeybindingsForCommand(commandId) {
        return this.collectKeybindings(binding => this.commandRegistry.getCommand(binding.command)?.id === commandId);
    }
    /**
     * Get the keybindings that don't execute a command but are shown as its accelerator.
     * See {@link common.Keybinding#displayFor}.
     *
     * @param commandId The ID of the command for which we are looking for keybindings.
     * @returns an array of {@link ScopedKeybinding}
     */
    getDisplayKeybindingsForCommand(commandId) {
        return this.collectKeybindings(binding => binding.displayFor === commandId);
    }
    /**
     * Collect the keybindings of all scopes, highest scope first, that match the given predicate
     * and have not been disabled by a `-command` keybinding of the same or a higher scope.
     */
    collectKeybindings(matches) {
        const result = [];
        const disabledBindings = new Set();
        for (let scope = KeybindingScope.END - 1; scope >= KeybindingScope.DEFAULT; scope--) {
            this.keymaps[scope].forEach(binding => {
                if (binding.command?.startsWith('-')) {
                    disabledBindings.add(JSON.stringify({ command: binding.command.substring(1), binding: binding.keybinding, context: binding.context, when: binding.when }));
                }
                else if (matches(binding)
                    && !disabledBindings.has(JSON.stringify({ command: binding.command, binding: binding.keybinding, context: binding.context, when: binding.when }))) {
                    result.push({ ...binding, scope });
                }
            });
        }
        return result;
    }
    /**
     * Get the accelerator of the first keybinding of a command that is enabled in the given context.
     * If no such keybinding exists and the command is enabled, the first enabled keybinding that is only displayed
     * for the command is used, see {@link common.Keybinding#displayFor}.
     * Physical accelerators (for native menus) are omitted for inactive keybindings.
     */
    acceleratorForCommand(commandId, context, form = 'logical') {
        const isEnabled = (candidate) => this.isEnabledInScope(candidate, context);
        const binding = this.getKeybindingsForCommand(commandId).find(isEnabled)
            ?? (this.commandRegistry.isEnabled(commandId) ? this.getDisplayKeybindingsForCommand(commandId).find(isEnabled) : undefined);
        if (!binding) {
            return [];
        }
        if (form === 'physical') {
            return this.isKeybindingInactive(binding) ? [] : this.acceleratorFor(binding, '+', true, 'physical');
        }
        return this.acceleratorFor(binding, '+');
    }
    isActive(binding) {
        /* Pseudo commands like "passthrough" are always active (and not found
           in the command registry).  */
        if (this.isPseudoCommand(binding.command)) {
            return true;
        }
        const command = this.commandRegistry.getCommand(binding.command);
        return !!command && !!this.commandRegistry.getActiveHandler(command.id);
    }
    /**
     * Tries to execute a keybinding.
     *
     * @param binding to execute
     * @param event keyboard event.
     */
    executeKeyBinding(binding, event) {
        if (this.isPseudoCommand(binding.command)) {
            /* Don't do anything, let the event propagate.  */
        }
        else {
            const command = this.commandRegistry.getCommand(binding.command);
            if (command) {
                if (this.commandRegistry.isEnabled(binding.command, binding.args)) {
                    this.commandRegistry.executeCommand(binding.command, binding.args)
                        .catch(e => this.logger.error('Failed to execute command:', e));
                }
                /* Note that if a keybinding is in context but the command is
                   not active we still stop the processing here.  */
                event.preventDefault();
                event.stopPropagation();
            }
        }
    }
    /**
     * Only execute if it has no context (global context) or if we're in that context.
     */
    isEnabled(binding, event) {
        return this.isEnabledInScope(binding, event.target);
    }
    isEnabledInScope(binding, target) {
        const context = binding.context && this.contexts[binding.context];
        if (binding.command && (!this.isPseudoCommand(binding.command) && !this.commandRegistry.isEnabled(binding.command, binding.args))) {
            return false;
        }
        if (context && !context.isEnabled(binding)) {
            return false;
        }
        if (binding.when && !this.whenContextService.match(binding.when, target)) {
            return false;
        }
        return true;
    }
    /**
     * Executes the command by dispatching its first keybinding: the resolved key codes are matched directly,
     * and a DOM keydown marked as already handled is dispatched to the target for other listeners to observe.
     */
    dispatchCommand(id, target) {
        const keybindings = this.getKeybindingsForCommand(id);
        if (keybindings.length && !this.isKeybindingInactive(keybindings[0])) {
            for (const keyCode of this.resolveKeybinding(keybindings[0])) {
                const input = {
                    key: keyCode.character ?? keyCode.key?.code,
                    code: keyCode.key?.code,
                    keyCode: keyCode.key?.keyCode,
                    ctrlKey: keyCode.ctrl,
                    shiftKey: keyCode.shift || layoutModifiersIncludeShift(keyCode.layoutModifiers),
                    altKey: keyCode.alt,
                    metaKey: keyCode.meta,
                    altGraph: layoutModifiersIncludeAltGraph(keyCode.layoutModifiers)
                };
                this.dispatchNormalizedKeyDown(input, target, [keyCode]);
                this.dispatchKeyDown({ ...input, modifierAltGraph: input.altGraph }, target, true);
            }
        }
    }
    /** Dispatch a DOM keydown, optionally marking it as already handled by direct normalized dispatch. */
    dispatchKeyDown(input, target = document.activeElement || window, alreadyHandled = false) {
        const eventInit = this.asKeyboardEventInit(input);
        const emulatedKeyboardEvent = new KeyboardEvent('keydown', { ...eventInit, cancelable: true });
        if (alreadyHandled) {
            this.handledKeyboardEvents.add(emulatedKeyboardEvent);
        }
        target.dispatchEvent(emulatedKeyboardEvent);
    }
    /**
     * Runs normalized keyboard data directly through keybinding matching without dispatching a DOM event.
     */
    dispatchNormalizedKeyDown(input, target, keyCodes) {
        const normalizedInput = normalizeKeyboardInput(input);
        const eventTarget = target ?? (typeof document === 'undefined' ? new EventTarget() : document.activeElement || window);
        const event = new KeyboardEvent('keydown', this.asKeyboardEventInit(normalizedInput));
        Object.defineProperty(event, 'target', { value: eventTarget });
        this.runNormalizedKeyboardInput(normalizedInput, event, keyCodes);
    }
    isKeyboardShortcutsTroubleshooting() {
        return this.keyboardShortcutsTroubleshooting;
    }
    /**
     * Mirrors VS Code's `workbench.action.toggleKeybindingsLog` command.
     * It logs how each key press was interpreted so keyboard-layout problems can be diagnosed on other machines.
     */
    toggleKeyboardShortcutsTroubleshooting() {
        this.keyboardShortcutsTroubleshooting = !this.keyboardShortcutsTroubleshooting;
        this.logger.info(`Keyboard shortcuts troubleshooting is now ${this.keyboardShortcutsTroubleshooting ? 'active' : 'inactive'}.`);
        return this.keyboardShortcutsTroubleshooting;
    }
    asKeyboardEventInit(input) {
        if (typeof input === 'string') {
            return this.asKeyboardEventInit(KeyCode.createKeyCode(input));
        }
        if (input instanceof KeyCode) {
            return {
                metaKey: input.meta,
                shiftKey: input.shift,
                altKey: input.alt,
                ctrlKey: input.ctrl,
                code: input.key && input.key.code,
                key: (input && input.character) || (input.key && input.key.code),
                keyCode: input.key && input.key.keyCode
            };
        }
        return input;
    }
    registerEventListeners(win) {
        // IME composition tracking for the textarea-based editor input path,
        // where compositionstart/compositionend bubble through the DOM.
        // (For the native EditContext path, these events never reach the DOM;
        // the keydown handler below uses additional checks for that case.)
        let inComposition = false;
        const compositionStart = () => {
            inComposition = true;
        };
        win.document.addEventListener('compositionstart', compositionStart);
        const compositionEnd = () => {
            inComposition = false;
        };
        win.document.addEventListener('compositionend', compositionEnd);
        const keydown = (event) => this.run(event, inComposition);
        win.document.addEventListener('keydown', keydown, true);
        return Disposable.create(() => {
            win.document.removeEventListener('compositionstart', compositionStart);
            win.document.removeEventListener('compositionend', compositionEnd);
            win.document.removeEventListener('keydown', keydown);
        });
    }
    /**
     * Run the command matching to the given keyboard event.
     */
    run(event, inComposition = false) {
        const input = normalizeKeyboardInput(event);
        // The textarea input path reports composition through separate DOM events.
        if (inComposition) {
            this.logKeyboardTroubleshooting(input, undefined, undefined, 'composition');
            return;
        }
        this.runNormalizedKeyboardInput(input, event);
    }
    /** Return all runtime interpretations of normalized keyboard input. */
    getKeyCodeInterpretations(input) {
        return this.keyboardLayoutService.getKeyCodeInterpretations(normalizeKeyboardInput(input), this.corePreferences['keyboard.dispatch']);
    }
    /** Return the authored representation that should be persisted for normalized keyboard input. */
    authoredKeyCodeForKeyboardInput(input) {
        const interpretations = this.getKeyCodeInterpretations(input);
        // macOS Option is recorded as the `alt` command modifier rather than as the character it produces.
        const optionAsCommandModifier = isOSX && !!input.altKey;
        const keyCode = interpretations.find(candidate => candidate.interpretation === 'layoutModifiers' && (!optionAsCommandModifier || candidate.alt))
            ?? interpretations[0];
        if (!keyCode || keyCode.isModifierOnly()) {
            return keyCode;
        }
        const fallbackLetter = keyCode.key && this.keyboardLayoutService.getLatinLetterFallback(keyCode.key);
        if (fallbackLetter && keyCode.character && !layoutModifiersIncludeAltGraph(keyCode.layoutModifiers)
            && keyCode.character.toLocaleLowerCase() !== fallbackLetter) {
            const shift = keyCode.shift || layoutModifiersIncludeShift(keyCode.layoutModifiers);
            return new KeyCode({
                key: keyCode.key,
                ctrl: keyCode.ctrl,
                alt: keyCode.alt,
                meta: keyCode.meta,
                shift,
                character: shift ? fallbackLetter.toLocaleUpperCase() : fallbackLetter
            });
        }
        if (keyCode.interpretation !== 'layoutModifiers' || !keyCode.character) {
            return keyCode;
        }
        try {
            const parsedCharacter = KeyCode.parse(keyCode.character);
            const logical = new KeyCode({
                key: parsedCharacter.key,
                ctrl: keyCode.ctrl,
                shift: keyCode.shift,
                alt: keyCode.alt,
                meta: keyCode.meta,
                character: keyCode.character,
                authoredToken: parsedCharacter.authoredToken
            });
            const persisted = KeyCode.parse(logical.toString());
            if (this.keyboardLayoutService.resolveKeyCode(persisted).dispatchString() === keyCode.dispatchString()) {
                return logical;
            }
            return new KeyCode({
                key: logical.key,
                ctrl: logical.ctrl,
                shift: logical.shift || layoutModifiersIncludeShift(keyCode.layoutModifiers),
                alt: logical.alt,
                meta: logical.meta,
                character: logical.character
            });
        }
        catch {
            return new KeyCode({
                key: keyCode.key,
                ctrl: keyCode.ctrl,
                shift: keyCode.shift || layoutModifiersIncludeShift(keyCode.layoutModifiers),
                alt: keyCode.alt,
                meta: keyCode.meta,
                character: keyCode.key?.easyString
            });
        }
    }
    /** Return the keybinding stroke the keybinding recorder persists for normalized keyboard input, or `undefined` for modifier-only input. */
    authoredKeybindingStringForKeyboardInput(input) {
        const keyCode = this.authoredKeyCodeForKeyboardInput(input);
        return keyCode && !keyCode.isModifierOnly() ? keyCode.toAuthoredKeybindingString() : undefined;
    }
    runNormalizedKeyboardInput(input, event, keyCodesOverride) {
        // Skip IME-related keydowns. `isComposing` and `keyCode === 229` cover the native EditContext path where
        // composition events do not reach the DOM. The keyCode check catches keys that finalize a composition,
        // such as arrow keys, when isComposing is already false.
        if (input.isComposing || input.keyCode === 229) {
            this.logKeyboardTroubleshooting(input, undefined, undefined, 'composition');
            return;
        }
        if (this.handledKeyboardEvents.has(event) || event.defaultPrevented) {
            this.logKeyboardTroubleshooting(input, undefined, undefined, this.handledKeyboardEvents.has(event) ? 'alreadyHandled' : 'defaultPrevented');
            return;
        }
        const keyCodes = keyCodesOverride ?? this.getKeyCodeInterpretations(input);
        const keyCode = keyCodes[0];
        /* Keycode is only a modifier, next keycode will be modifier + key.
           Ignore this one.  */
        if (keyCode.isModifierOnly()) {
            this.logKeyboardTroubleshooting(input, keyCode, undefined, 'modifierOnly');
            return;
        }
        this.keyboardLayoutService.validateKeyCode(keyCode, input);
        const candidates = this.keySequenceCandidates.flatMap(sequence => keyCodes.flatMap(keyCodeCandidate => {
            const candidateSequence = [...sequence, keyCodeCandidate];
            const candidateMatch = this.matchKeybinding(candidateSequence, event);
            return candidateMatch ? [{ sequence: candidateSequence, keyCode: keyCodeCandidate, match: candidateMatch }] : [];
        }));
        const prioritized = candidates.map(candidate => ({ candidate, priority: this.matchPriority(candidate) }))
            .sort((left, right) => right.priority - left.priority);
        const selectedEntry = prioritized[0];
        const selected = selectedEntry?.candidate;
        const equallyPreferred = prioritized.filter(entry => entry.priority === selectedEntry?.priority).map(entry => entry.candidate);
        const ambiguous = selected?.match.kind === 'full'
            && equallyPreferred.some(candidate => candidate.match.kind === 'full'
                && candidate.match.runtime.binding !== selected.match.runtime.binding);
        const match = ambiguous ? undefined : selected?.match;
        if (ambiguous) {
            const sequence = selected.sequence.map(code => code.dispatchString()).join(' ');
            if (!this.warnedAmbiguousSequences.has(sequence)) {
                this.warnedAmbiguousSequences.add(sequence);
                this.logger.warn(`Ambiguous keybinding sequence ignored: ${sequence}`);
            }
        }
        this.logKeyboardTroubleshooting(input, selected?.keyCode ?? keyCode, match, ambiguous ? 'ambiguous' : undefined);
        if (match?.kind === 'partial') {
            this.keySequenceCandidates = candidates.filter(candidate => candidate.match.kind === 'partial').map(candidate => candidate.sequence);
            event.preventDefault();
            event.stopPropagation();
            this.statusBar.setElement('keybinding-status', {
                text: nls.localize('theia/core/keybindingStatus', '{0} was pressed, waiting for more keys', `(${this.acceleratorForSequence(selected.sequence, '+')})`),
                alignment: StatusBarAlignment.LEFT,
                priority: 2
            });
        }
        else {
            if (match?.kind === 'full') {
                this.executeKeyBinding(match.runtime.binding, event);
            }
            this.keySequenceCandidates = [[]];
            this.statusBar.removeElement('keybinding-status');
        }
    }
    /** Higher values win; explicit command modifiers take precedence over layout-modifier interpretations. */
    matchPriority(candidate) {
        const usesLayoutModifiers = candidate.keyCode.interpretation === 'layoutModifiers';
        return (usesLayoutModifiers ? 0 : 2) + (candidate.match.kind === 'full' ? 1 : 0);
    }
    logKeyboardTroubleshooting(input, keyCode, match, skipped) {
        if (!this.keyboardShortcutsTroubleshooting) {
            return;
        }
        this.logger.info('Keyboard shortcut troubleshooting', {
            input: {
                key: input.key,
                code: input.code,
                keyCode: input.keyCode,
                ctrlKey: input.ctrlKey,
                shiftKey: input.shiftKey,
                altKey: input.altKey,
                metaKey: input.metaKey,
                altGraph: input.altGraph,
                controlModifier: input.getModifierState?.('Control'),
                altModifier: input.getModifierState?.('Alt'),
                repeat: input.repeat,
                isComposing: input.isComposing,
                location: input.location,
                timeStamp: input.timeStamp
            },
            normalized: keyCode && {
                key: keyCode.key?.code,
                character: keyCode.character,
                ctrl: keyCode.ctrl,
                shift: keyCode.shift,
                alt: keyCode.alt,
                meta: keyCode.meta,
                layoutModifiers: keyCode.layoutModifiers,
                interpretation: keyCode.interpretation,
                dispatch: keyCode.dispatchString()
            },
            layout: {
                info: this.keyboardLayoutService.layoutInfo,
                source: this.keyboardLayoutService.layoutSource
            },
            match: match && {
                kind: match.kind,
                command: match.runtime.binding.command,
                keybinding: match.runtime.binding.keybinding,
                interpretations: match.runtime.sequence.map(code => code.interpretation)
            },
            skipped
        });
    }
    /**
     * Match first binding in the current context.
     * Keybindings ordered by a scope and by a registration order within the scope.
     *
     * Uses a ternary search tree for efficient O(log n) lookup instead of O(n) iteration.
     * The tree is lazily built and invalidated when keybindings change.
     *
     * `keySequence` must be a resolved sequence from {@link resolveKeybinding} or a runtime interpretation from
     * {@link getKeyCodeInterpretations}. Lookup uses {@link KeyCode.dispatchString} identity, so raw
     * {@link KeySequence.parse} output only matches when parsing and resolution coincide, such as `keyboard.dispatch: 'keyCode'`.
     *
     * When multiple bindings match, bindings that use context keys local to the focused
     * element are given priority over bindings that only use global context keys.
     */
    matchKeybinding(keySequence, event) {
        let disabled;
        const isEnabled = (binding) => {
            const { command, context, when, keybinding } = binding;
            if (!this.isUsable(binding)) {
                disabled = disabled || new Set();
                disabled.add(JSON.stringify({ command: command.substring(1), context, when, keybinding }));
                return false;
            }
            if (event && !this.isEnabled(binding, event)) {
                return false;
            }
            return !disabled?.has(JSON.stringify({ command, context, when, keybinding }));
        };
        const tree = this.getKeybindingTree();
        // Check for exact (FULL) matches first
        const fullMatches = tree.get(keySequence);
        if (fullMatches) {
            const enabledForms = fullMatches.filter(runtimeForm => isEnabled(runtimeForm.binding));
            if (enabledForms.length > 0) {
                const selectedBinding = this.selectBindingByLocalContext(enabledForms.map(candidate => candidate.binding), event);
                const runtimeForm = enabledForms.find(candidate => candidate.binding === selectedBinding);
                return { kind: 'full', runtime: runtimeForm };
            }
        }
        // Check for PARTIAL matches (bindings that start with keySequence but are longer)
        const partialIterator = tree.findSuperstr(keySequence);
        if (partialIterator) {
            const partialForms = [];
            let result = partialIterator.next();
            while (!result.done) {
                partialForms.push(...result.value);
                result = partialIterator.next();
            }
            partialForms.sort((a, b) => b.binding.scope - a.binding.scope);
            const enabledForms = partialForms.filter(runtimeForm => isEnabled(runtimeForm.binding));
            if (enabledForms.length > 0) {
                const selectedBinding = this.selectBindingByLocalContext(enabledForms.map(candidate => candidate.binding), event);
                const runtimeForm = enabledForms.find(candidate => candidate.binding === selectedBinding);
                return { kind: 'partial', runtime: runtimeForm };
            }
        }
        return undefined;
    }
    /**
     * Selects the most appropriate binding from a list of enabled bindings.
     * Prioritizes bindings whose `when` clause uses context keys that are locally
     * defined at the focused element, as these are more specific to the user's
     * current focus context.
     *
     * @param enabledBindings Array of enabled bindings to choose from (must not be empty)
     * @param event Optional keyboard event to get the focused element from
     * @returns The selected binding
     */
    selectBindingByLocalContext(enabledBindings, event) {
        if (enabledBindings.length === 1 || !event) {
            return enabledBindings[0];
        }
        const target = event.target;
        if (!(target instanceof HTMLElement)) {
            return enabledBindings[0];
        }
        // Get context keys that are locally defined at the focused element
        const localKeys = this.whenContextService.getLocalContextKeys(target);
        if (localKeys.size === 0) {
            return enabledBindings[0];
        }
        // Find bindings whose 'when' clause uses any local context key
        // These are considered more specific to the focused element
        for (const binding of enabledBindings) {
            if (binding.when) {
                const usedKeys = this.whenContextService.parseKeys(binding.when);
                if (usedKeys) {
                    for (const key of usedKeys) {
                        if (localKeys.has(key)) {
                            return binding;
                        }
                    }
                }
            }
        }
        // No binding uses local context keys, fall back to first enabled binding
        return enabledBindings[0];
    }
    /**
     * Returns true if the binding is usable
     * @param binding Binding to be checked
     */
    isUsable(binding) {
        return binding.command.charAt(0) !== '-';
    }
    /**
     * Return a new filtered array containing only the usable bindings among the input bindings
     * @param bindings Bindings to filter
     */
    getUsableBindings(bindings) {
        return bindings.filter(binding => this.isUsable(binding));
    }
    /**
     * Return true of string a pseudo-command id, in other words a command id
     * that has a special meaning and that we won't find in the command
     * registry.
     *
     * @param commandId commandId to test
     */
    isPseudoCommand(commandId) {
        return commandId === KeybindingRegistry_1.PASSTHROUGH_PSEUDO_COMMAND;
    }
    /**
     * Sets a new keymap replacing all existing {@link common.Keybinding}s in the given scope.
     * @param scope the keybinding scope
     * @param bindings an array containing the new {@link common.Keybinding}s
     */
    setKeymap(scope, bindings) {
        this.resetKeybindingsForScope(scope);
        this.toResetKeymap.set(scope, this.doRegisterKeybindings(bindings, scope));
        this.invalidateKeybindingTree();
        this.keybindingsChanged.fire(undefined);
    }
    /**
     * Reset keybindings for a specific scope
     * @param scope scope to reset the keybindings for
     */
    resetKeybindingsForScope(scope) {
        const toReset = this.toResetKeymap.get(scope);
        if (toReset) {
            toReset.dispose();
        }
    }
    /**
     * Reset keybindings for all scopes(only leaves the default keybindings mapped)
     */
    resetKeybindings() {
        for (let i = KeybindingScope.DEFAULT + 1; i < KeybindingScope.END; i++) {
            this.keymaps[i] = [];
        }
        this.invalidateKeybindingTree();
    }
    /**
     * Get all {@link common.Keybinding}s for a {@link KeybindingScope}.
     * @returns an array of {@link common.ScopedKeybinding}
     * @param scope the keybinding scope to retrieve the {@link common.Keybinding}s for.
     */
    getKeybindingsByScope(scope) {
        return this.keymaps[scope];
    }
};
__decorate([
    inject(CorePreferences)
], KeybindingRegistry.prototype, "corePreferences", void 0);
__decorate([
    inject(KeyboardLayoutService)
], KeybindingRegistry.prototype, "keyboardLayoutService", void 0);
__decorate([
    inject(ContributionProvider),
    named(KeybindingContext)
], KeybindingRegistry.prototype, "contextProvider", void 0);
__decorate([
    inject(CommandRegistry)
], KeybindingRegistry.prototype, "commandRegistry", void 0);
__decorate([
    inject(ContributionProvider),
    named(KeybindingContribution)
], KeybindingRegistry.prototype, "contributions", void 0);
__decorate([
    inject(StatusBar)
], KeybindingRegistry.prototype, "statusBar", void 0);
__decorate([
    inject(ILogger),
    named('core:KeybindingRegistry')
], KeybindingRegistry.prototype, "logger", void 0);
__decorate([
    inject(ContextKeyService)
], KeybindingRegistry.prototype, "whenContextService", void 0);
KeybindingRegistry = KeybindingRegistry_1 = __decorate([
    injectable()
], KeybindingRegistry);
export { KeybindingRegistry };
(function (KeybindingRegistry) {
    class KeybindingsResult {
        constructor() {
            this.full = [];
            this.partial = [];
            this.shadow = [];
        }
        /**
         * Merge two results together inside `this`
         *
         * @param other the other KeybindingsResult to merge with
         * @return this
         */
        merge(other) {
            this.full.push(...other.full);
            this.partial.push(...other.partial);
            this.shadow.push(...other.shadow);
            return this;
        }
        /**
         * Returns a new filtered KeybindingsResult
         *
         * @param fn callback filter on the results
         * @return filtered new result
         */
        filter(fn) {
            const result = new KeybindingsResult();
            result.full = this.full.filter(fn);
            result.partial = this.partial.filter(fn);
            result.shadow = this.shadow.filter(fn);
            return result;
        }
    }
    KeybindingRegistry.KeybindingsResult = KeybindingsResult;
})(KeybindingRegistry || (KeybindingRegistry = {}));
//# sourceMappingURL=keybinding.js.map