UNPKG

@theia/core

Version:

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

1,686 lines • 78.4 kB
// *****************************************************************************
// Copyright (C) 2017 Ericsson 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
// *****************************************************************************

import { enableJSDOM } from './test/jsdom.js';
let disableJSDOM = enableJSDOM();

import { FrontendApplicationConfigProvider } from './frontend-application-config-provider.js';
try {
    FrontendApplicationConfigProvider.get();
} catch {
    FrontendApplicationConfigProvider.set({});
}

import { Container, injectable, ContainerModule } from 'inversify';
import { bindContributionProvider } from '../common/contribution-provider.js';
import { KeyboardLayoutProvider, NativeKeyboardLayout, KeyboardLayoutChangeNotifier } from '../common/keyboard/keyboard-layout-provider.js';
import { ILogger } from '../common/logger.js';
import { KeybindingRegistry, KeybindingContext, KeybindingContribution, KeybindingScope } from './keybinding.js';
import { Keybinding } from '../common/keybinding.js';
import { KeyCode, Key, KeyModifier, KeySequence, NormalizedKeyboardInput } from './keyboard/keys.js';
import { KeyboardLayoutService } from './keyboard/keyboard-layout-service.js';
import { CommandRegistry, CommandService, CommandContribution, Command } from '../common/command.js';
import { LabelParser } from './label-parser.js';
import { MockLogger } from '../common/test/mock-logger.js';
import { FrontendApplicationStateService } from './frontend-application-state.js';
import { ContextKeyService, ContextKeyServiceDummyImpl, ContextMatcher } from './context-key-service.js';
import { CorePreferences } from '../common/core-preferences.js';
import * as chai from 'chai';
import * as sinon from 'sinon';
import { Emitter, Event } from '../common/event.js';
import { bindPreferenceService } from './frontend-application-bindings.js';
import { MarkdownRenderer, MarkdownRendererFactory, MarkdownRendererImpl } from './markdown-rendering/markdown-renderer.js';
import { StatusBar } from './status-bar/index.js';
import deGermanMacLayout from '../common/keyboard/layouts/de-German-mac.json' with { type: 'json' };
import deGermanPcLayout from '../common/keyboard/layouts/de-German-pc.json' with { type: 'json' };
import enUSMacLayout from '../common/keyboard/layouts/en-US-mac.json' with { type: 'json' };
import enUSPcLayout from '../common/keyboard/layouts/en-US-pc.json' with { type: 'json' };
import { OSStub, stubOS } from '../common/test/stub-os.js';

disableJSDOM();

const deGermanMac = deGermanMacLayout as unknown as NativeKeyboardLayout;
const deGermanPc = deGermanPcLayout as unknown as NativeKeyboardLayout;
const enUSMac = enUSMacLayout as unknown as NativeKeyboardLayout;
const enUSPc = enUSPcLayout as unknown as NativeKeyboardLayout;

const expect = chai.expect;

function testKeyboardEvent(input: Partial<KeyboardEvent> = {}): KeyboardEvent {
    let defaultPrevented = false;
    return {
        key: input.key,
        code: input.code,
        keyCode: input.keyCode,
        ctrlKey: input.ctrlKey,
        shiftKey: input.shiftKey,
        altKey: input.altKey,
        metaKey: input.metaKey,
        repeat: input.repeat,
        isComposing: input.isComposing,
        location: input.location,
        timeStamp: input.timeStamp,
        target: input.target,
        get defaultPrevented(): boolean { return defaultPrevented; },
        preventDefault(): void { defaultPrevented = true; },
        stopPropagation(): void { }
    } as KeyboardEvent;
}

let keybindingRegistry: KeybindingRegistry;
let commandRegistry: CommandRegistry;
let testContainer: Container;

let stub: OSStub;
const preferenceChanged = new Emitter<{ preferenceName: string }>();
const corePreferences = {
    'keyboard.dispatch': 'code',
    onPreferenceChanged: preferenceChanged.event
} as unknown as CorePreferences;

const RUSSIAN_LAYOUT: NativeKeyboardLayout = {
    info: { id: 'ru', lang: 'ru' },
    mapping: {
        KeyA: { value: 'ф', withShift: 'Ф', withAltGr: '', withShiftAltGr: '' },
        KeyC: { value: 'с', withShift: 'С', withAltGr: '', withShiftAltGr: '' },
        KeyE: { value: 'у', withShift: 'У', withAltGr: '€', withShiftAltGr: '' },
        KeyV: { value: 'м', withShift: 'М', withAltGr: '', withShiftAltGr: '' },
        KeyS: { value: 'ы', withShift: 'Ы', withAltGr: '', withShiftAltGr: '' },
        Digit8: { value: '8', withShift: '*', withAltGr: '', withShiftAltGr: '' },
        BracketLeft: { value: 'х', withShift: 'Х', withAltGr: '', withShiftAltGr: '' },
        Comma: { value: 'б', withShift: 'Б', withAltGr: '', withShiftAltGr: '' }
    }
};

before(async () => {
    testContainer = new Container();
    const module = new ContainerModule((bind, unbind, isBound, rebind) => {

        /* Mock logger binding*/
        bind(ILogger).to(MockLogger);

        bind(KeyboardLayoutService).toSelf().inSingletonScope();
        bind(MockKeyboardLayoutProvider).toSelf().inSingletonScope();
        bind(KeyboardLayoutProvider).toDynamicValue(ctx => {
            const provider = ctx.container.get(MockKeyboardLayoutProvider);
            return new Proxy(provider, {
                get: (target, property) => property === 'then' ? undefined
                    : property === 'layoutSource' ? 'navigator.keyboard'
                        : property in target ? Reflect.get(target, property) : () => undefined
            });
        });
        bind(MockKeyboardLayoutChangeNotifier).toSelf().inSingletonScope();
        bind(KeyboardLayoutChangeNotifier).toService(MockKeyboardLayoutChangeNotifier);

        bindContributionProvider(bind, KeybindingContext);

        bind(CommandRegistry).toSelf().inSingletonScope();
        bindContributionProvider(bind, CommandContribution);

        bind(KeybindingRegistry).toSelf();
        bindContributionProvider(bind, KeybindingContribution);

        bind(TestContribution).toSelf().inSingletonScope();
        [CommandContribution, KeybindingContribution].forEach(serviceIdentifier =>
            bind(serviceIdentifier).toService(TestContribution)
        );

        bind(KeybindingContext).toConstantValue({
            id: 'testContext',
            isEnabled(arg?: Keybinding): boolean {
                return true;
            }
        });

        bind(StatusBar).toConstantValue({
            setElement: () => Promise.resolve(),
            removeElement: () => Promise.resolve()
        } as unknown as StatusBar);
        bind(MarkdownRendererImpl).toSelf().inSingletonScope();
        bind(MarkdownRenderer).toService(MarkdownRendererImpl);
        bind(MarkdownRendererFactory).toFactory(({ container }) => () => container.get(MarkdownRenderer));

        bind(CommandService).toService(CommandRegistry);
        bind(LabelParser).toSelf().inSingletonScope();
        bind(ContextKeyService).to(MockContextKeyService).inSingletonScope();
        bind(FrontendApplicationStateService).toSelf().inSingletonScope();
        bind(CorePreferences).toConstantValue(corePreferences);
        bindPreferenceService(bind);
    });

    testContainer.load(module);

    commandRegistry = testContainer.get(CommandRegistry);
    commandRegistry.onStart();

});

beforeEach(async function (): Promise<void> {
    if (this.currentTest?.file?.endsWith('keybinding.spec.js')) {
        disableJSDOM();
        disableJSDOM = enableJSDOM();
    }
    stub = stubOS('isOSX', false);
    keybindingRegistry = testContainer.get<KeybindingRegistry>(KeybindingRegistry);
    (corePreferences as unknown as Record<string, unknown>)['keyboard.dispatch'] = 'code';
    await keybindingRegistry.onStart();
});

afterEach(function (): void {
    stub.restore();
    if (this.currentTest?.file?.endsWith('keybinding.spec.js')) {
        disableJSDOM();
    }
});

describe('keybindings', () => {

    it('should register the default keybindings', () => {
        const keybinding = keybindingRegistry.getKeybindingsForCommand(TEST_COMMAND.id);
        expect(keybinding).is.not.undefined;

        const keybinding2 = keybindingRegistry.getKeybindingsForCommand('undefined.command');
        expect(keybinding2.length).is.equal(0);
    });

    it('should set a keymap', () => {
        const keybindings: Keybinding[] = [{
            command: TEST_COMMAND.id,
            keybinding: 'ctrl+c'
        }];

        keybindingRegistry.setKeymap(KeybindingScope.USER, keybindings);

        const bindings = keybindingRegistry.getKeybindingsForCommand(TEST_COMMAND.id);
        if (bindings) {
            const keyCode = KeyCode.parse(bindings[0].keybinding);
            expect(keyCode.key).to.be.equal(Key.KEY_C);
            expect(keyCode.ctrl).to.be.true;
        }

    });

    it('should reset to default in case of invalid keybinding', () => {
        const keybindings: Keybinding[] = [{
            command: TEST_COMMAND.id,
            keybinding: 'ctrl+invalid'
        }];

        keybindingRegistry.setKeymap(KeybindingScope.USER, keybindings);

        const bindings = keybindingRegistry.getKeybindingsForCommand(TEST_COMMAND.id);
        if (bindings) {
            const keyCode = KeyCode.parse(bindings[0].keybinding);
            expect(keyCode.key).to.be.equal(Key.KEY_A);
            expect(keyCode.ctrl).to.be.true;
        }
    });

    it('should remove all disabled keybindings from a command that has multiple keybindings', () => {
        const keybindings: Keybinding[] = [{
            command: TEST_COMMAND2.id,
            keybinding: 'F3'
        },
        {
            command: '-' + TEST_COMMAND2.id,
            context: 'testContext',
            keybinding: 'ctrl+f1'
        },
        ];

        keybindingRegistry.setKeymap(KeybindingScope.USER, keybindings);

        const bindings = keybindingRegistry.getKeybindingsForCommand(TEST_COMMAND2.id);
        if (bindings) {
            // a USER one and a DEFAULT one
            expect(bindings.length).to.be.equal(2);
            const keyCode = KeyCode.parse(bindings[0].keybinding);
            expect(keyCode.key).to.be.equal(Key.F3);
            expect(keyCode.ctrl).to.be.false;
            const keyCode2 = KeyCode.parse(bindings[1].keybinding);
            expect(keyCode2.key).to.be.equal(Key.F2);
            expect(keyCode2.ctrl).to.be.true;
        }
    });

    it('should register a keybinding', () => {
        const keybinding: Keybinding = {
            command: TEST_COMMAND2.id,
            keybinding: 'F5'
        };
        expect(isKeyBindingRegistered(keybinding)).to.be.false;

        keybindingRegistry.registerKeybinding(keybinding);

        expect(isKeyBindingRegistered(keybinding)).to.be.true;
    }
    );

    it('should unregister all keybindings from a specific command', () => {
        const otherKeybinding: Keybinding = {
            command: TEST_COMMAND.id,
            keybinding: 'F4'
        };
        keybindingRegistry.registerKeybinding(otherKeybinding);
        expect(isKeyBindingRegistered(otherKeybinding)).to.be.true;

        const keybinding: Keybinding = {
            command: TEST_COMMAND2.id,
            keybinding: 'F5'
        };
        const keybinding2: Keybinding = {
            command: TEST_COMMAND2.id,
            keybinding: 'F6'
        };

        keybindingRegistry.registerKeybinding(keybinding);
        keybindingRegistry.registerKeybinding(keybinding2);
        expect(isKeyBindingRegistered(keybinding)).to.be.true;
        expect(isKeyBindingRegistered(keybinding2)).to.be.true;

        keybindingRegistry.unregisterKeybinding(TEST_COMMAND2);

        expect(isKeyBindingRegistered(keybinding)).to.be.false;
        expect(isKeyBindingRegistered(keybinding2)).to.be.false;
        const bindingsAfterUnregister = keybindingRegistry.getKeybindingsForCommand(TEST_COMMAND2.id);
        expect(bindingsAfterUnregister).not.to.be.undefined;
        expect(bindingsAfterUnregister.length).to.be.equal(0);
        expect(isKeyBindingRegistered(otherKeybinding)).to.be.true;
    });

    it('should unregister a specific keybinding', () => {
        const otherKeybinding: Keybinding = {
            command: TEST_COMMAND2.id,
            keybinding: 'F4'
        };

        keybindingRegistry.registerKeybinding(otherKeybinding);
        const keybinding: Keybinding = {
            command: TEST_COMMAND2.id,
            keybinding: 'F5'
        };

        keybindingRegistry.registerKeybinding(keybinding);

        expect(isKeyBindingRegistered(otherKeybinding)).to.be.true;
        expect(isKeyBindingRegistered(keybinding)).to.be.true;

        keybindingRegistry.unregisterKeybinding(keybinding);

        expect(isKeyBindingRegistered(keybinding)).to.be.false;
        expect(isKeyBindingRegistered(otherKeybinding)).to.be.true;
    }
    );

    it('should unregister a specific key', () => {
        const otherKeybinding: Keybinding = {
            command: TEST_COMMAND.id,
            keybinding: 'F4'
        };

        keybindingRegistry.registerKeybinding(otherKeybinding);
        const testKey = 'F5';
        const keybinding: Keybinding = {
            command: TEST_COMMAND2.id,
            keybinding: testKey
        };

        const keybinding2: Keybinding = {
            command: TEST_COMMAND.id,
            keybinding: testKey
        };

        keybindingRegistry.registerKeybinding(keybinding);
        keybindingRegistry.registerKeybinding(keybinding2);

        expect(isKeyBindingRegistered(otherKeybinding)).to.be.true;
        expect(isKeyBindingRegistered(keybinding)).to.be.true;
        expect(isKeyBindingRegistered(keybinding2)).to.be.true;

        keybindingRegistry.unregisterKeybinding(testKey);

        expect(isKeyBindingRegistered(otherKeybinding)).to.be.true;
        expect(isKeyBindingRegistered(keybinding)).to.be.false;
        expect(isKeyBindingRegistered(keybinding2)).to.be.false;
    }
    );

    it('should register a correct keybinding, then default back to the original for a wrong one after', () => {
        let keybindings: Keybinding[] = [{
            command: TEST_COMMAND.id,
            keybinding: 'ctrl+c'
        }];

        // Get default binding
        const keystroke = keybindingRegistry.getKeybindingsForCommand(TEST_COMMAND.id);

        // Set correct new binding
        keybindingRegistry.setKeymap(KeybindingScope.USER, keybindings);
        const bindings = keybindingRegistry.getKeybindingsForCommand(TEST_COMMAND.id);
        if (bindings) {
            const keyCode = KeyCode.parse(bindings[0].keybinding);
            expect(keyCode.key).to.be.equal(Key.KEY_C);
            expect(keyCode.ctrl).to.be.true;
        }

        // Set invalid binding
        keybindings = [{
            command: TEST_COMMAND.id,
            keybinding: 'ControlLeft+Invalid'
        }];

        keybindingRegistry.setKeymap(KeybindingScope.USER, keybindings);

        const defaultBindings = keybindingRegistry.getKeybindingsForCommand(TEST_COMMAND.id);
        if (defaultBindings) {
            if (keystroke) {
                const keyCode = KeyCode.parse(defaultBindings[0].keybinding);
                const keyStrokeCode = KeyCode.parse(keystroke[0].keybinding);
                expect(keyCode.key).to.be.equal(keyStrokeCode.key);
            }
        }
    });

    it('should only return the more specific keybindings when a keystroke is entered', () => {
        const keybindingsUser: Keybinding[] = [{
            command: TEST_COMMAND.id,
            keybinding: 'ctrl+b'
        }];

        keybindingRegistry.setKeymap(KeybindingScope.USER, keybindingsUser);

        const keybindingsSpecific: Keybinding[] = [{
            command: TEST_COMMAND.id,
            keybinding: 'ctrl+c'
        }];

        const validKeyCode = KeyCode.createKeyCode({ first: Key.KEY_C, modifiers: [KeyModifier.CtrlCmd] });

        keybindingRegistry.setKeymap(KeybindingScope.WORKSPACE, keybindingsSpecific);

        let match = keybindingRegistry.matchKeybinding([KeyCode.createKeyCode({ first: Key.KEY_A, modifiers: [KeyModifier.CtrlCmd] })]);
        expect(match && match.kind).to.be.equal('full');

        match = keybindingRegistry.matchKeybinding([KeyCode.createKeyCode({ first: Key.KEY_B, modifiers: [KeyModifier.CtrlCmd] })]);
        expect(match && match.kind).to.be.equal('full');

        match = keybindingRegistry.matchKeybinding([KeyCode.createKeyCode({ first: Key.KEY_C, modifiers: [KeyModifier.CtrlCmd] })]);
        const keyCode = match && KeyCode.parse(match.runtime.binding.keybinding);
        expect(keyCode?.key).to.be.equal(validKeyCode.key);
    });

    it('should return partial keybinding matches', () => {
        const keybindingsUser: Keybinding[] = [{
            command: TEST_COMMAND.id,
            keybinding: 'ctrlcmd+x t'
        }];

        keybindingRegistry.setKeymap(KeybindingScope.USER, keybindingsUser);

        const validKeyCodes = [];
        validKeyCodes.push(KeyCode.createKeyCode({ first: Key.KEY_C, modifiers: [KeyModifier.CtrlCmd] }));
        validKeyCodes.push(KeyCode.createKeyCode({ first: Key.KEY_T }));

        const match = keybindingRegistry.matchKeybinding(KeySequence.parse('ctrlcmd+x'));
        expect(match && match.kind).to.be.equal('partial');
    });

    it('should possible to override keybinding', () => {
        const overriddenKeybinding = 'ctrlcmd+b a';
        const command = TEST_COMMAND_SHADOW.id;
        const keybindingShadowing: Keybinding[] = [
            {
                command,
                keybinding: overriddenKeybinding
            },
            {
                command,
                keybinding: 'ctrlcmd+b'
            }
        ];

        keybindingRegistry.registerKeybindings(...keybindingShadowing);

        const bindings = keybindingRegistry.getKeybindingsForCommand(command);
        expect(bindings.length).to.be.equal(2);
        expect(bindings[0].keybinding).to.be.equal('ctrlcmd+b');
        expect(bindings[1].keybinding).to.be.equal(overriddenKeybinding);
    });

    it('overridden bindings should be returned last', () => {
        const keyCode = KeyCode.createKeyCode({ first: Key.KEY_A, modifiers: [KeyModifier.Shift] });

        const overriddenDefaultBinding: Keybinding = {
            keybinding: keyCode.toString(),
            command: 'test.overridden-default-command'
        };

        const defaultBinding: Keybinding = {
            keybinding: keyCode.toString(),
            command: 'test.default-command'
        };

        const userBinding: Keybinding = {
            keybinding: keyCode.toString(),
            command: 'test.user-command'
        };

        const workspaceBinding: Keybinding = {
            keybinding: keyCode.toString(),
            command: 'test.workspace-command'
        };

        keybindingRegistry.setKeymap(KeybindingScope.DEFAULT, [overriddenDefaultBinding, defaultBinding]);
        keybindingRegistry.setKeymap(KeybindingScope.USER, [userBinding]);
        keybindingRegistry.setKeymap(KeybindingScope.WORKSPACE, [workspaceBinding]);
        // now WORKSPACE bindings are overriding the other scopes

        let match = keybindingRegistry.matchKeybinding(keybindingRegistry.resolveKeybinding(workspaceBinding));
        expect(match?.kind).to.be.equal('full');
        expect(match?.runtime.binding?.command).to.be.equal(workspaceBinding.command);

        keybindingRegistry.resetKeybindingsForScope(KeybindingScope.WORKSPACE);
        // now it should find USER bindings

        match = keybindingRegistry.matchKeybinding(keybindingRegistry.resolveKeybinding(userBinding));
        expect(match?.kind).to.be.equal('full');
        expect(match?.runtime.binding?.command).to.be.equal(userBinding.command);

        keybindingRegistry.resetKeybindingsForScope(KeybindingScope.USER);
        // and finally it should fallback to DEFAULT bindings.

        match = keybindingRegistry.matchKeybinding(keybindingRegistry.resolveKeybinding(defaultBinding));
        expect(match?.kind).to.be.equal('full');
        expect(match?.runtime.binding?.command).to.be.equal(defaultBinding.command);

        keybindingRegistry.resetKeybindingsForScope(KeybindingScope.DEFAULT);
        // now the registry should be empty

        match = keybindingRegistry.matchKeybinding([keyCode]);
        expect(match).to.be.undefined;

    });

    it('should not match disabled keybindings', () => {
        const keyCode = KeyCode.createKeyCode({ first: Key.KEY_A, modifiers: [KeyModifier.Shift] });

        const defaultBinding: Keybinding = {
            keybinding: keyCode.toString(),
            command: 'test.workspace-command'
        };
        const disableDefaultBinding: Keybinding = {
            keybinding: keyCode.toString(),
            command: '-test.workspace-command'
        };

        keybindingRegistry.setKeymap(KeybindingScope.DEFAULT, [defaultBinding]);
        let match = keybindingRegistry.matchKeybinding(keybindingRegistry.resolveKeybinding(defaultBinding));
        expect(match?.kind).to.be.equal('full');
        expect(match?.runtime.binding?.command).to.be.equal(defaultBinding.command);

        keybindingRegistry.setKeymap(KeybindingScope.USER, [disableDefaultBinding]);
        match = keybindingRegistry.matchKeybinding(keybindingRegistry.resolveKeybinding(defaultBinding));
        expect(match).to.be.undefined;

        keybindingRegistry.resetKeybindingsForScope(KeybindingScope.USER);
        match = keybindingRegistry.matchKeybinding(keybindingRegistry.resolveKeybinding(defaultBinding));
        expect(match?.kind).to.be.equal('full');
        expect(match?.runtime.binding?.command).to.be.equal(defaultBinding.command);
    });

    it('should dispatch already-handled compatibility events to capture listeners', () => {
        const target = document.createElement('iframe');
        document.body.appendChild(target);
        const captured = sinon.spy();
        document.addEventListener('keydown', captured, true);
        const match = sinon.spy(keybindingRegistry, 'matchKeybinding');

        keybindingRegistry.dispatchKeyDown({ key: 'a', code: 'KeyA' }, target, true);

        expect(captured.calledOnce).to.be.true;
        expect(captured.firstCall.args[0].defaultPrevented).to.be.false;
        expect(match.called).to.be.false;
        document.removeEventListener('keydown', captured, true);
        target.remove();
    });

    it('should dispatch normalized keyboard data directly', () => {
        const match = sinon.spy(keybindingRegistry, 'matchKeybinding');

        keybindingRegistry.dispatchNormalizedKeyDown({
            key: 'a',
            code: 'KeyA',
            keyCode: 65,
            ctrlKey: true
        }, new EventTarget());

        expect(match.calledOnce).to.be.true;
        expect(match.firstCall.args[0][0].dispatchString()).to.equal('ctrl+a');
    });

    it('should dispatch a DOM keydown for dispatched commands without executing them twice', async () => {
        const target = document.createElement('div');
        document.body.appendChild(target);
        const captured = sinon.spy();
        const run = (event: KeyboardEvent) => keybindingRegistry.run(event);
        document.addEventListener('keydown', captured, true);
        document.addEventListener('keydown', run, true);
        const match = sinon.spy(keybindingRegistry, 'matchKeybinding');
        const execute = sinon.spy();
        const handler = commandRegistry.registerHandler(TEST_COMMAND.id, { execute });

        try {
            keybindingRegistry.dispatchCommand(TEST_COMMAND.id, target);
            await new Promise(resolve => setTimeout(resolve, 0));

            expect(captured.calledOnce).to.be.true;
            expect(captured.firstCall.args[0].ctrlKey).to.be.true;
            expect(execute.calledOnce).to.be.true;
            expect(match.calledOnce).to.be.true;
        } finally {
            handler.dispose();
            document.removeEventListener('keydown', captured, true);
            document.removeEventListener('keydown', run, true);
            target.remove();
        }
    });

    it('should preserve authored modifiers when dispatching commands through normalized Windows layout modifier data', async () => {
        const windows = stubOS('isWindows', true);
        testContainer.get(MockKeyboardLayoutChangeNotifier).emitter.fire(deGermanPc);
        const dispatch = sinon.spy(keybindingRegistry, 'dispatchNormalizedKeyDown');
        const target = document.createElement('div');
        const cases = [
            { keybinding: '[', ctrlKey: false, altKey: false },
            { keybinding: 'ctrl+[', ctrlKey: true, altKey: false, inactive: true },
            { keybinding: 'alt+[', ctrlKey: false, altKey: true, inactive: true },
            { keybinding: 'ctrl+alt+[', ctrlKey: true, altKey: true, inactive: true }
        ];

        try {
            for (const testCase of cases) {
                const binding = { command: TEST_COMMAND_SHADOW.id, keybinding: testCase.keybinding };
                keybindingRegistry.setKeymap(KeybindingScope.USER, [binding]);
                const execute = sinon.spy();
                const handler = commandRegistry.registerHandler(TEST_COMMAND_SHADOW.id, { execute });
                dispatch.resetHistory();
                try {
                    keybindingRegistry.dispatchCommand(TEST_COMMAND_SHADOW.id, target);
                    await new Promise(resolve => setTimeout(resolve, 0));

                    if (testCase.inactive) {
                        // Windows reports AltGr as Ctrl+Alt, so neither command Ctrl nor Alt can accompany an AltGraph character.
                        expect(keybindingRegistry.isKeybindingInactive(binding)).to.be.true;
                        expect(dispatch.called).to.be.false;
                        expect(execute.called).to.be.false;
                        continue;
                    }
                    expect(dispatch.calledOnce).to.be.true;
                    expect(dispatch.firstCall.args[0]).to.include({
                        key: '[',
                        code: 'Digit8',
                        keyCode: 56,
                        ctrlKey: testCase.ctrlKey,
                        altKey: testCase.altKey,
                        altGraph: true
                    });
                    expect(execute.calledOnce).to.be.true;
                } finally {
                    handler.dispose();
                }
            }
        } finally {
            windows.restore();
        }
    });

    it('should interpret native and transported AltGraph input identically', () => {
        testContainer.get(MockKeyboardLayoutChangeNotifier).emitter.fire(deGermanPc);
        const native = keybindingRegistry.getKeyCodeInterpretations({
            key: '[',
            code: 'Digit8',
            keyCode: 56,
            ctrlKey: true,
            getModifierState: modifier => modifier === 'AltGraph'
        });
        const transported = keybindingRegistry.getKeyCodeInterpretations({
            key: '[',
            code: 'Digit8',
            keyCode: 56,
            ctrlKey: true,
            altGraph: true
        });

        expect(transported.map(code => code.dispatchString())).to.deep.equal(native.map(code => code.dispatchString()));
    });

    it('should log normalized keyboard troubleshooting data when enabled', () => {
        const logger = (keybindingRegistry as unknown as { logger: ILogger }).logger;
        const info = sinon.spy(logger, 'info');
        keybindingRegistry.toggleKeyboardShortcutsTroubleshooting();

        keybindingRegistry.dispatchNormalizedKeyDown({
            key: '[',
            code: 'Digit8',
            keyCode: 56,
            getModifierState: modifier => modifier === 'AltGraph',
            timeStamp: 42
        }, new EventTarget());

        expect(info.calledTwice).to.be.true;
        expect(info.secondCall.args[1].input).to.include({
            key: '[',
            code: 'Digit8',
            altGraph: true,
            timeStamp: 42
        });
        expect(info.secondCall.args[1].layout.source).to.equal('navigator.keyboard');
    });

    it('should skip composing normalized keyboard data', () => {
        const match = sinon.spy(keybindingRegistry, 'matchKeybinding');

        keybindingRegistry.dispatchNormalizedKeyDown({
            key: 'a',
            code: 'KeyA',
            keyCode: 65,
            isComposing: true
        }, new EventTarget());

        expect(match.called).to.be.false;
    });

    it('should exclude inactive bindings and reactivate them after a layout change', () => {
        const binding = { command: TEST_COMMAND.id, keybinding: 'ctrl+[' };
        keybindingRegistry.setKeymap(KeybindingScope.USER, [binding]);
        expect(keybindingRegistry.matchKeybinding(keybindingRegistry.resolveKeybinding(binding))?.kind).to.equal('full');

        const notifier = testContainer.get(MockKeyboardLayoutChangeNotifier);
        notifier.emitter.fire({
            info: { id: 'missing-bracket', lang: 'en' },
            mapping: { KeyA: { value: 'a', withShift: 'A', withAltGr: '', withShiftAltGr: '' } }
        });
        expect(keybindingRegistry.getKeybindingsForCommand(TEST_COMMAND.id).some(candidate => candidate.keybinding === 'ctrl+[')).to.be.true;
        expect(keybindingRegistry.getKeybindingInactiveReason(binding)).to.be.a('string');
        expect(keybindingRegistry.matchKeybinding(KeySequence.parse('ctrl+['))).to.be.undefined;
        expect(keybindingRegistry.containsKeybindingInScope({ command: TEST_COMMAND2.id, keybinding: 'ctrl+[' })).to.be.false;

        notifier.emitter.fire(enUSPc);
        expect(keybindingRegistry.getKeybindingInactiveReason(binding)).to.be.undefined;
        expect(keybindingRegistry.matchKeybinding(keybindingRegistry.resolveKeybinding(binding))?.kind).to.equal('full');
    });

    it('should keep default Latin-letter bindings active on a non-Latin layout', async () => {
        const binding = { command: TEST_COMMAND_SHADOW.id, keybinding: 'ctrl+c' };
        keybindingRegistry.setKeymap(KeybindingScope.USER, [binding]);
        const notifier = testContainer.get(MockKeyboardLayoutChangeNotifier);
        notifier.emitter.fire(RUSSIAN_LAYOUT);
        const execute = sinon.spy();
        const handler = commandRegistry.registerHandler(TEST_COMMAND_SHADOW.id, { execute });

        try {
            expect(keybindingRegistry.isKeybindingInactive(binding)).to.be.false;
            keybindingRegistry.dispatchNormalizedKeyDown({
                key: 'с', code: 'KeyC', ctrlKey: true
            }, new EventTarget());
            await new Promise(resolve => setTimeout(resolve, 0));

            expect(execute.calledOnce).to.be.true;
        } finally {
            handler.dispose();
            notifier.emitter.fire(enUSPc);
        }
    });

    it('should dispatch a shifted Latin-letter binding on a non-Latin layout', async () => {
        const binding = { command: TEST_COMMAND_SHADOW.id, keybinding: 'ctrl+shift+a' };
        keybindingRegistry.setKeymap(KeybindingScope.USER, [binding]);
        const notifier = testContainer.get(MockKeyboardLayoutChangeNotifier);
        notifier.emitter.fire(RUSSIAN_LAYOUT);
        const execute = sinon.spy();
        const handler = commandRegistry.registerHandler(TEST_COMMAND_SHADOW.id, { execute });

        try {
            keybindingRegistry.dispatchNormalizedKeyDown({
                key: 'Ф', code: 'KeyA', ctrlKey: true, shiftKey: true
            }, new EventTarget());
            await new Promise(resolve => setTimeout(resolve, 0));

            expect(execute.calledOnce).to.be.true;
        } finally {
            handler.dispose();
            notifier.emitter.fire(enUSPc);
        }
    });

    it('should dispatch a Shift+punctuation binding from input that reports the base character', async () => {
        keybindingRegistry.setKeymap(KeybindingScope.USER, [{ command: TEST_COMMAND_SHADOW.id, keybinding: 'ctrl+shift+`' }]);
        const execute = sinon.spy();
        const handler = commandRegistry.registerHandler(TEST_COMMAND_SHADOW.id, { execute });

        try {
            keybindingRegistry.dispatchNormalizedKeyDown({
                key: '`', code: 'Backquote', ctrlKey: true, shiftKey: true
            }, new EventTarget());
            await new Promise(resolve => setTimeout(resolve, 0));

            expect(execute.calledOnce).to.be.true;
        } finally {
            handler.dispose();
        }
    });

    it('should keep punctuation bindings inactive on a non-Latin layout', () => {
        const binding = { command: TEST_COMMAND.id, keybinding: 'ctrl+[' };
        keybindingRegistry.setKeymap(KeybindingScope.USER, [binding]);
        const notifier = testContainer.get(MockKeyboardLayoutChangeNotifier);
        notifier.emitter.fire(RUSSIAN_LAYOUT);

        try {
            expect(keybindingRegistry.isKeybindingInactive(binding)).to.be.true;
        } finally {
            notifier.emitter.fire(enUSPc);
        }
    });

    it('should execute an authored Shift command modifier on a non-US logical character', async () => {
        testContainer.get(MockKeyboardLayoutChangeNotifier).emitter.fire(deGermanPc);
        const binding = { command: TEST_COMMAND_SHADOW.id, keybinding: 'ctrl+shift+ü' };
        keybindingRegistry.setKeymap(KeybindingScope.USER, [binding]);
        const execute = sinon.spy();
        const handler = commandRegistry.registerHandler(TEST_COMMAND_SHADOW.id, { execute });

        try {
            keybindingRegistry.dispatchNormalizedKeyDown({
                key: 'Ü', code: 'BracketLeft', ctrlKey: true, shiftKey: true
            }, new EventTarget());
            await new Promise(resolve => setTimeout(resolve, 0));

            expect(execute.calledOnce).to.be.true;
        } finally {
            handler.dispose();
        }
    });

    it('should mark an unmatchable Shift plus AltGraph character binding inactive', async () => {
        testContainer.get(MockKeyboardLayoutChangeNotifier).emitter.fire(deGermanPc);
        const binding = { command: TEST_COMMAND_SHADOW.id, keybinding: 'ctrl+shift+[char:0x7B]' };
        keybindingRegistry.setKeymap(KeybindingScope.USER, [binding]);
        const execute = sinon.spy();
        const handler = commandRegistry.registerHandler(TEST_COMMAND_SHADOW.id, { execute });

        try {
            expect(keybindingRegistry.getKeybindingInactiveReason(binding)).to.be.a('string');
            keybindingRegistry.dispatchNormalizedKeyDown({
                key: '{', code: 'Digit7', ctrlKey: true, shiftKey: true, altGraph: true
            }, new EventTarget());
            await new Promise(resolve => setTimeout(resolve, 0));

            expect(execute.called).to.be.false;
        } finally {
            handler.dispose();
        }
    });

    it('should mark command Alt plus AltGraph character bindings inactive on macOS and Windows', async () => {
        const notifier = testContainer.get(MockKeyboardLayoutChangeNotifier);
        const binding = { command: TEST_COMMAND_SHADOW.id, keybinding: 'alt+[' };
        const execute = sinon.spy();
        const handler = commandRegistry.registerHandler(TEST_COMMAND_SHADOW.id, { execute });
        const windows = stubOS('isWindows', false);
        const dispatch = async (input: NormalizedKeyboardInput) => {
            keybindingRegistry.dispatchNormalizedKeyDown(input, new EventTarget());
            await new Promise(resolve => setTimeout(resolve, 0));
        };

        try {
            stub.value(true);
            notifier.emitter.fire(deGermanMac);
            keybindingRegistry.setKeymap(KeybindingScope.USER, [binding]);
            expect(keybindingRegistry.getKeybindingInactiveReason(binding)).to.be.a('string');
            expect(keybindingRegistry.acceleratorForCommand(TEST_COMMAND_SHADOW.id, undefined, 'physical')).to.deep.equal([]);
            await dispatch({ key: '[', code: 'Digit5', altKey: true });
            expect(execute.called).to.be.false;

            stub.value(false);
            windows.value(true);
            notifier.emitter.fire(deGermanPc);
            keybindingRegistry.setKeymap(KeybindingScope.USER, [binding]);
            expect(keybindingRegistry.getKeybindingInactiveReason(binding)).to.be.a('string');
            await dispatch({ key: '[', code: 'Digit8', ctrlKey: true, altKey: true });
            expect(execute.called).to.be.false;

            windows.value(false);
            notifier.emitter.fire(deGermanPc);
            keybindingRegistry.setKeymap(KeybindingScope.USER, [binding]);
            expect(keybindingRegistry.getKeybindingInactiveReason(binding)).to.be.undefined;
            await dispatch({ key: '[', code: 'Digit8', altKey: true, altGraph: true });
            expect(execute.calledOnce).to.be.true;
        } finally {
            windows.restore();
            handler.dispose();
            notifier.emitter.fire(enUSPc);
        }
    });

    it('should mark command Ctrl plus AltGraph character bindings inactive on Windows', async () => {
        const notifier = testContainer.get(MockKeyboardLayoutChangeNotifier);
        const binding = { command: TEST_COMMAND_SHADOW.id, keybinding: 'ctrl+[' };
        const typed = { command: KeybindingRegistry.PASSTHROUGH_PSEUDO_COMMAND, keybinding: '[' };
        const execute = sinon.spy();
        const handler = commandRegistry.registerHandler(TEST_COMMAND_SHADOW.id, { execute });
        const windows = stubOS('isWindows', true);
        const match = sinon.spy(keybindingRegistry, 'matchKeybinding');
        const dispatch = async (input: NormalizedKeyboardInput) => {
            keybindingRegistry.dispatchNormalizedKeyDown(input, new EventTarget());
            await new Promise(resolve => setTimeout(resolve, 0));
        };

        try {
            notifier.emitter.fire(deGermanPc);
            keybindingRegistry.setKeymap(KeybindingScope.USER, [binding, typed]);
            expect(keybindingRegistry.getKeybindingInactiveReason(binding)).to.be.a('string');
            expect(keybindingRegistry.acceleratorForCommand(TEST_COMMAND_SHADOW.id, undefined, 'physical')).to.deep.equal([]);
            // Chromium reports Ctrl+AltGr+8 on Windows exactly like AltGr+8, so the input types `[`.
            await dispatch({ key: '[', code: 'Digit8', ctrlKey: true, altKey: true, altGraph: true });
            expect(execute.called).to.be.false;
            const fullMatches = match.returnValues.filter(result => result?.kind === 'full').map(result => result!.runtime.binding.keybinding);
            expect(fullMatches).to.deep.equal(['[']);

            windows.value(false);
            notifier.emitter.fire(deGermanPc);
            keybindingRegistry.setKeymap(KeybindingScope.USER, [binding]);
            expect(keybindingRegistry.getKeybindingInactiveReason(binding)).to.be.undefined;
            await dispatch({ key: '[', code: 'Digit8', ctrlKey: true, altGraph: true });
            expect(execute.calledOnce).to.be.true;
        } finally {
            windows.restore();
            handler.dispose();
            notifier.emitter.fire(enUSPc);
        }
    });

    it('should route Windows Ctrl+Alt candidates through the registry with and without reported AltGraph', () => {
        const windows = stubOS('isWindows', true);
        try {
            testContainer.get(MockKeyboardLayoutChangeNotifier).emitter.fire(deGermanPc);
            const match = sinon.spy(keybindingRegistry, 'matchKeybinding');
            const logicalBinding = {
                command: KeybindingRegistry.PASSTHROUGH_PSEUDO_COMMAND,
                keybinding: '[',
                resolved: [new KeyCode({ key: Key.DIGIT8, character: '[', layoutModifiers: 'altGraph' })]
            };
            for (const altGraph of [true, false]) {
                const input = { key: '[', code: 'Digit8', ctrlKey: true, altKey: true, altGraph };
                match.resetHistory();
                keybindingRegistry.setKeymap(KeybindingScope.USER, [logicalBinding]);
                keybindingRegistry.dispatchNormalizedKeyDown(input, new EventTarget());

                expect(match.callCount).to.equal(2);
                expect(match.secondCall.returnValue?.kind).to.equal('full');
                expect(match.secondCall.returnValue?.runtime.binding.keybinding).to.equal('[');

                match.resetHistory();
                keybindingRegistry.setKeymap(KeybindingScope.USER, [
                    logicalBinding,
                    { command: KeybindingRegistry.PASSTHROUGH_PSEUDO_COMMAND, keybinding: 'ctrl+alt+8' }
                ]);
                keybindingRegistry.dispatchNormalizedKeyDown(input, new EventTarget());

                expect(match.callCount).to.equal(2);
                expect(match.firstCall.returnValue?.runtime.binding.keybinding).to.equal('ctrl+alt+8');
            }
        } finally {
            windows.restore();
        }
    });

    it('should prefer a command chord prefix over a layout modifier full match', () => {
        const interpretations = sinon.stub(keybindingRegistry, 'getKeyCodeInterpretations').returns([
            new KeyCode({ key: Key.KEY_A, ctrl: true, interpretation: 'commandModifiers' }),
            new KeyCode({ key: Key.DIGIT8, ctrl: true, layoutModifiers: 'altGraph', interpretation: 'layoutModifiers' })
        ]);
        const commandChord = {
            command: KeybindingRegistry.PASSTHROUGH_PSEUDO_COMMAND,
            keybinding: 'ctrl+a b'
        };
        const layoutFull = {
            command: KeybindingRegistry.PASSTHROUGH_PSEUDO_COMMAND,
            keybinding: 'ctrl+['
        };
        keybindingRegistry.resolveKeybinding(commandChord).splice(0, 2, ...KeySequence.parse('ctrl+a b'));
        keybindingRegistry.resolveKeybinding(layoutFull).splice(0, 1,
            new KeyCode({ key: Key.DIGIT8, ctrl: true, character: '[', layoutModifiers: 'altGraph' }));
        keybindingRegistry.setKeymap(KeybindingScope.USER, [commandChord, layoutFull]);

        const event = testKeyboardEvent({ key: '[', code: 'Digit8' });
        keybindingRegistry.run(event);

        expect(event.defaultPrevented).to.be.true;
        expect((keybindingRegistry as unknown as { keySequenceCandidates: KeySequence[] }).keySequenceCandidates).to.have.length(1);
        expect((keybindingRegistry as unknown as { keySequenceCandidates: KeySequence[] }).keySequenceCandidates[0][0].interpretation).to.equal('commandModifiers');
        interpretations.restore();
    });

    it('should retain alternative interpretation prefixes across a chord', () => {
        const commandPrefix = new KeyCode({ key: Key.KEY_A, ctrl: true, interpretation: 'commandModifiers' });
        const layoutPrefix = new KeyCode({ key: Key.DIGIT8, ctrl: true, layoutModifiers: 'altGraph', interpretation: 'layoutModifiers' });
        const layoutSecond = new KeyCode({ key: Key.KEY_C, interpretation: 'layoutModifiers' });
        const interpretations = sinon.stub(keybindingRegistry, 'getKeyCodeInterpretations');
        interpretations.onFirstCall().returns([commandPrefix, layoutPrefix]);
        interpretations.onSecondCall().returns([
            new KeyCode({ key: Key.KEY_X, interpretation: 'commandModifiers' }),
            layoutSecond
        ]);
        const commandBinding = {
            command: KeybindingRegistry.PASSTHROUGH_PSEUDO_COMMAND,
            keybinding: 'ctrl+a b'
        };
        const layoutBinding = {
            command: KeybindingRegistry.PASSTHROUGH_PSEUDO_COMMAND,
            keybinding: 'ctrl+[ c'
        };
        keybindingRegistry.resolveKeybinding(commandBinding).splice(0, 2, commandPrefix, new KeyCode({ key: Key.KEY_B }));
        keybindingRegistry.resolveKeybinding(layoutBinding).splice(0, 2, layoutPrefix, layoutSecond);
        keybindingRegistry.setKeymap(KeybindingScope.USER, [commandBinding, layoutBinding]);

        keybindingRegistry.run(testKeyboardEvent({ key: '[', code: 'Digit8' }));
        expect((keybindingRegistry as unknown as { keySequenceCandidates: KeySequence[] }).keySequenceCandidates).to.have.length(2);
        const second = testKeyboardEvent({ key: 'c', code: 'KeyC' });
        keybindingRegistry.run(second);

        expect(second.defaultPrevented).to.be.false;
        expect((keybindingRegistry as unknown as { keySequenceCandidates: KeySequence[] }).keySequenceCandidates).to.deep.equal([[]]);
        interpretations.restore();
    });

    it('should decline equal-priority full matches from different interpretations', () => {
        const first = new KeyCode({ key: Key.KEY_A, ctrl: true, interpretation: 'commandModifiers' });
        const second = new KeyCode({ key: Key.KEY_B, ctrl: true, interpretation: 'commandModifiers' });
        const interpretations = sinon.stub(keybindingRegistry, 'getKeyCodeInterpretations').returns([first, second]);
        const troubleshooting = sinon.spy(keybindingRegistry as unknown as {
            logKeyboardTroubleshooting: (input: unknown, keyCode: KeyCode, match: unknown, skipped?: string) => void
        }, 'logKeyboardTroubleshooting');
        const logger = (keybindingRegistry as unknown as { logger: ILogger }).logger;
        const warning = sinon.spy(logger, 'warn');
        const firstBinding = { command: KeybindingRegistry.PASSTHROUGH_PSEUDO_COMMAND, keybinding: 'ctrl+a' };
        const secondBinding = { command: KeybindingRegistry.PASSTHROUGH_PSEUDO_COMMAND, keybinding: 'ctrl+b' };
        keybindingRegistry.resolveKeybinding(firstBinding).splice(0, 1, first);
        keybindingRegistry.resolveKeybinding(secondBinding).splice(0, 1, second);
        keybindingRegistry.setKeymap(KeybindingScope.USER, [firstBinding, secondBinding]);

        keybindingRegistry.run(testKeyboardEvent({ key: 'a', code: 'KeyA' }));

        expect(troubleshooting.lastCall.args[3]).to.equal('ambiguous');
        expect(troubleshooting.lastCall.args[2]).to.be.undefined;
        expect(warning.calledOnce).to.be.true;
        keybindingRegistry.run(testKeyboardEvent({ key: 'a', code: 'KeyA' }));
        expect(warning.calledOnce).to.be.true;
        interpretations.restore();
    });

    it('should canonicalize layout modifier input for recorder persistence', () => {
        const interpretations = sinon.stub(keybindingRegistry, 'getKeyCodeInterpretations').returns([
            new KeyCode({ key: Key.DIGIT8, ctrl: true, alt: true, interpretation: 'commandModifiers' }),
            new KeyCode({ key: Key.DIGIT8, ctrl: true, character: '[', layoutModifiers: 'altGraph', interpretation: 'layoutModifiers' })
        ]);

        expect(keybindingRegistry.authoredKeyCodeForKeyboardInput({ key: '[', code: 'Digit8' })?.toString()).to.equal('ctrl+[');
        interpretations.restore();
    });

    it('should record the Latin fallback letter on a non-Latin layout', () => {
        const notifier = testContainer.get(MockKeyboardLayoutChangeNotifier);
        notifier.emitter.fire(RUSSIAN_LAYOUT);

        expect(keybindingRegistry.authoredKeyCodeForKeyboardInput({
            key: 'с', code: 'KeyC', ctrlKey: true
        })?.toAuthoredKeybindingString()).to.equal('ctrl+c');
        expect(keybindingRegistry.authoredKeyCodeForKeyboardInput({
            key: 'С', code: 'KeyC', ctrlKey: true, shiftKey: true
        })?.toAuthoredKeybindingString()).to.equal('shift+ctrl+c');
        expect(keybindingRegistry.authoredKeyCodeForKeyboardInput({
            key: '€', code: 'KeyE', ctrlKey: true, altGraph: true
        })?.toAuthoredKeybindingString()).to.equal('ctrl+€');
        expect(keybindingRegistry.authoredKeyCodeForKeyboardInput({
            key: 'у', code: 'KeyE', ctrlKey: true
        })?.toAuthoredKeybindingString()).to.equal('ctrl+e');

        notifier.emitter.fire(enUSPc);
        expect(keybindingRegistry.authoredKeyCodeForKeyboardInput({
            key: 'c', code: 'KeyC', ctrlKey: true
        })?.toAuthoredKeybindingString()).to.equal('ctrl+c');
    });

    it('should record legacy Windows AltGraph input as its logical character', () => {
        const windows = stubOS('isWindows', true);
        try {
            testContainer.get(MockKeyboardLayoutChangeNotifier).emitter.fire(deGermanPc);

            for (const altGraph of [true, false]) {
                expect(keybindingRegistry.authoredKeyCodeForKeyboardInput({
                    key: '[', code: 'Digit8', ctrlKey: true, altKey: true, altGraph
                })?.toString()).to.equal('[');
            }
        } finally {
            windows.restore();
        }
    });

    it('should retain command Shift when layout modifier Shift is not the logical binding', () => {
        const interpretations = sinon.stub(keybindingRegistry, 'getKeyCodeInterpretations').returns([
            new KeyCode({ key: Key.KEY_P, ctrl: true, character: 'P', layoutModifiers: 'shift', interpretation: 'layoutModifiers' })
        ]);

        expect(keybindingRegistry.authoredKeyCodeForKeyboardInput({ key: 'P', code: 'KeyP' })?.toString()).to.equal('shift+ctrl+p');
        interpretations.restore();
    });

    it('should persist a parseable logical character produced by Shift', () => {
        const interpretations = sinon.stub(keybindingRegistry, 'getKeyCodeInterpretations').returns([
            new KeyCode({ key: Key.DIGIT7, character: '/', layoutModifiers: 'shift', interpretation: 'layoutModifiers' })
        ]);
        const resolve = sinon.stub(testContainer.get(KeyboardLayoutService), 'resolveKeyCode').callsFake(code => code.key === Key.SLASH
            ? new KeyCode({ key: Key.DIGIT7, character: '/', layoutModifiers: 'shift' })
            : code);

        expect(keybindingRegistry.authoredKeyCodeForKeyboardInput({ key: '/', code: 'Digit7' })?.toString()).to.equal('/');
        resolve.restore();
        interpretations.restore();
    });

    it('should record newly authorable printable characters logically', () => {
        const layoutCode = new KeyCode({ key: Key.SLASH, ctrl: true, character: '?', layoutModifiers: 'shift', interpretation: 'layoutModifiers' });
        const interpretations = sinon.stub(keybindingRegistry, 'getKeyCodeInterpretations').returns([layoutCode]);

        const recorded = keybindingRegistry.authoredKeyCodeForKeyboardInput({ key: '?', code: 'Slash' });
        expect(recorded?.toString()).to.equal('ctrl+?');
        expect(keybindingRegistry.resolveKeybinding({ command: TEST_COMMAND.id, keybinding: recorded!.toString() })[0].dispatchString())
            .to.equal(layoutCode.dispatchString());
        interpretations.restore();
    });

    it('should record logical characters, physical non-printables, and ignore modifier-only input', () => {
        const registry = Object.create(KeybindingRegistry.prototype) as KeybindingRegistry;
        registry.authoredKeyCodeForKeyboardInput = input => {
            if (input.code === 'ControlLeft') {
                return new KeyCode({ ctrl: true });
            }
            if (input.code === 'F1') {
                return new KeyCode({ key: Key.F1, ctrl: true });
            }
            if (input.code === 'Delete') {
                return new KeyCode({ key: Key.DELETE, ctrl: true });
            }
            if (input.code === 'KeyP') {
                return new KeyCode({ key: Key.KEY_P, ctrl: true, shift: true, character: 'P' });
            }
            return new KeyCode({ key: input.code === 'Equal' ? Key.EQUAL : Key.BRACKET_LEFT, ctrl: true, character: input.key });
        };

        expect(registry.authoredKeybindingStringForKeyboardInput({ key: '[', code: 'Digit8', ctrlKey: true })).to.equal('ctrl+[');
        expect(registry.authoredKeybindingStringForKeyboardInput({ key: '+', code: 'Equal', ctrlKey: true })).to.equal('ctrl+[char:0x2B]');
        expect(registry.authoredKeybindingStringForKeyboardInput({ key: 'F1', code: 'F1', ctrlKey: true })).to.equal('ctrl+f1');
        expect(registry.authoredKeybindingStringForKeyboardInput({ key: 'Delete', code: 'Delete', ctrlKey: true })).to.equal('ctrl+delete');
        const shifted = registry.authoredKeybindingStringForKeyboardInput({ key: 'P', code: 'KeyP', ctrlKey: true, shiftKey: true });
        expect(shifted).to.equal('shift+ctrl+p');
        expect(KeyCode.parse(shifted!).dispatchString()).to.equal('shift+ctrl+p');
        expect(registry.authoredKeybindingStringForKeyboardInput({ key: 'Control', code: 'ControlLeft', ctrlKey: true })).to.be.undefined;
    });

    it('should record Space and numpad keys by name', () => {
        expect(keybindingRegistry.authoredKeybindingStringForKeyboardInput({ key: ' ', code: 'Space', ctrlKey: true, shiftKey: true }))
            .to.equal('shift+ctrl+space');
        expect(keybindingRegistry.authoredKeybindingStringForKeyboardInput({ key: '+', code: 'NumpadAdd', ctrlKey: true })).to.equal('ctrl+add');
        expect(keybindingRegistry.authoredKeybindingStringForKeyboardInput({ key: '-', code: 'NumpadSubtract', ctrlKey: true })).to.equal('ctrl+subtract');
        expect(keybindingRegistry.authoredKeybindingStringForKeyboardInput({ key: '.', code: 'NumpadDecimal', ctrlKey: true })).to.equal('ctrl+decimal');
        expect(keybindingRegistry.authoredKeybindingStringForKeyboardInput({ key: '1', code: 'Numpad1', ctrlKey: true })).to.equal('ctrl+1');
    });

    it('should dispatch and record Option bindings as command modifiers on macOS', async () => {
        stub.value(true);
        const notifier = testContainer.get(MockKeyboardLayoutChangeNotifier);
        notifier.emitter.fire(enUSMac);
        const execute = sinon.spy();
        const handler = commandRegistry.registerHandler(TEST_COMMAND_SHADOW.id, { execute });
        try {
            keybindingRegistry.setKeymap(KeybindingScope.USER, [{ command: TEST_COMMAND_SHADOW.id, keybinding: 'shift+alt+p' }]);
            keybindingRegistry.run(testKeyboardEvent({ key: '∏', code: 'KeyP', shiftKey: true, altKey: true }));
            await new Promise(resolve => setTimeout(resolve, 0));

            expect(execute.calledOnce).to.be.true;
            expect(keybindingRegistry.authoredKeybindingStringForKeyboardInput({ key: '∏', code: 'KeyP', shiftKey: true, altKey: true }))
                .to.equal('shift+alt+p');
            expect(keybindingRegistry.authoredKeybindingStringForKeyboardInput({ key: 'π', code: 'KeyP', altKey: true })).to.equal('alt+p');
            expect(keybindingRegistry.authoredKeybindingStringForKeyboardInput({ key: 'P', code: 'KeyP', shiftKey: true })).to.equal('shift+p');
        } finally {
            handler.dispose();
            notifier.emitter.fire(enUSPc);
        }
    });

    it('should dispatch and record dead Option keys as their base character on macOS', async () => {
        stub.value(true);
        const notifier = testContainer.get(MockKeyboardLayoutChangeNotifier);
        notifier.emitter.fire(enUSMac);
        const execute = sinon.spy();
        const handler = commandRegistry.registerHandler(TEST_COMMAND_SHADOW.id, { execute });
        try {
            keybindingRegistry.setKeymap(KeybindingScope.USER, [{ command: TEST_COMMAND_SHADOW.id, keybinding: 'alt+e' }]);
            keybindingRegistry.run(testKeyboardEvent({ key: 'Dead', code: 'KeyE', altKey: true }));
            await new Promise(resolve => setTimeout(resolve, 0));

            expect(execute.calledOnce).to.be.true;
            expect(keybindingRegistry.authoredKeybindingStringForKeyboardInput({ key: 'Dead', code: 'KeyE', altKey: true })).to.equal('alt+e');
            expect(keybindingRegistry.authoredKeybindingStringForKeyboardInput({ key: 'Dead', code: 'KeyE', altKey: true, shiftKey: true }))
                .to.equal('shift+alt+e');
            expect(keybindingRegistry.authoredKeybindingStringForKeyboardInput({ key: 'Dead', code: 'KeyE', altKey: true, metaKey: true }))
                .to.equal('meta+alt+e');
            expect(keybindingRegistry.authoredKeybindingStringForKeyboardInput({ key: 'F1', code: 'F1', altKey: true })).to.equal('alt+f1');

            keybindingRegistry.setKeymap(KeybindingScope.USER, [{ command: TEST_COMMAND_SHADOW.id, keybinding: 'shift+alt+e' }]);
            keybindingRegistry.run(testKeyboardEvent({ key: 'Dead', code: 'KeyE', altKey: true, shiftKey: true }));
            await new Promise(resolve => setTimeout(resolve, 0));
            expect(execute.calledTwice).to.be.true;
        } finally {
            handler.dispose();
            notifier.emitter.fire(enUSPc);
        }
    });

    it('should record Caps Lock input with the layout layer case', async () => {
        const notifier = testContainer.get(MockKeyboardLayoutChangeNotifier);
        const execute = sinon.spy();
        const handler = commandRegistry.registerHandler(TEST_COMMAND_SHADOW.id, { execute });
        try {
            expect(keybindingRegistry.authoredKeybindingStringForKeyboardInput({ key: 'p', code: 'KeyP', ctrlKey: true, shiftKey: true }))
                .to.equal('shift+ctrl+p');

            notifier.emitter.fire(deGermanPc);
            expect(keybindingRegistry.authoredKeybindingStringForKeyboardInput({ key: 'ü', code: 'BracketLeft', ctrlKey: true, shiftKey: true }))
                .to.equal('ctrl+Ü');
            const recorded = keybindingRegistry.authoredKeybindingStringForKeyboardInput({ key: 'Ü', code: 'BracketLeft', ctrlKey: true });
            expect(recorded).to.equal('ctrl+ü');

            keybindingRegistry.setKeymap(KeybindingScope.USER, [{ command: TEST_COMMAND_SHADOW.id, keybinding: recorded! }]);
            keybindingRegistry.dispatchNormalizedKeyDown({ key: 'ü', code: 'BracketLeft', ctrlKey: true }, new EventTarget());
            await new Promise(resolve => setTimeout(resolve, 0));
            expect(execute.calledOnce).to.be.true;

            notifier.emitter.fire({
                info: { id: 'altgraph-letters', lang: 'pl' },
                mapping: { KeyL: { value: 'l', withShift: 'L', withAltGr: 'ł', withShiftAltGr: 'Ł' } }
            });
            expect(keybindingRegistry.authoredKeybindingStringForKeyboardInput({ key: 'Ł', code: 'KeyL', ctrlKey: true, altGraph: true }))
                .to.equal('ctrl+ł');

            stub.value(true);
            notifier.emitter.fire(deGermanMac);
            expect(keybindingRegistry.authoredKeybindingStringForKeyboardInput({ key: 'Å', code: 'KeyA', altKey: true })).to.equal('alt+a');
        } finally {
            handler.dispose();
            notifier.emitter.fire(enUSPc);
        }
    });

    it('should classify interpretation shadowing separately from canonical collisions', () => {
        const logical = {
            command: TEST_COMMAND.id,
            keybinding: 'ctrl+[',
            resolved: [new KeyCode({ key: Key.DIGIT8, ctrl: true, character: '[', layoutModifiers: 'altGraph' })]
        };
        const command = { command: TEST_COMMAND2.id, keybinding: 'ctrl+alt+8' };
        keybindingRegistry.setKeymap(KeybindingScope.USER, [logical, command]);

        const diagnostics = keybindingRegistry.getKeybindingCollisionDiagnostics(logical);
        expect(diagnostics.shadowedBy.map(binding => binding.command)).to.include(TEST_COMMAND2.id);
        expect(diagnostics.authored.full).to.be.empty;
        expect(diagnostics.layoutDerived.full).to.be.empty;
        expect(keybindingRegistry.containsKeybindingInScope(logical)).to.be.false;
    });

    it('should keep shifted printable bindings symmetric in keyCode dispatch mode', () => {
        (corePreferences as unknown as Record<string, unknown>)['keyboard.dispatch'] = 'keyCode';
        const commandPalette = { command: TEST_COMMAND.id, keybinding: 'ctrl+shift+p' };
        const shiftedPrintable = { command: TEST_COMMAND2.id, keybinding: 'shift+/' };
        keybindingRegistry.setKeymap(KeybindingScope.USER, [commandPalette, shiftedPrintable]);

        expect(keybindingRegistry.matchKeybinding(KeySequence.parse('ctrl+shift+p'))?.runtime.binding.command).to.equal(TEST_COMMAND.id);
        expect(keybindingRegistry.matchKeybinding(KeySequence.parse('shift+/'))?.runtime.binding.command).to.equal(TEST_COMMAND2.id);
    });

    it('should mark character-only bindings inactive in keyCode dispatch mode', () => {
        (corePreferences as unknown as Record<string, unknown>)['keyboard.dispatch'] = 'keyCode';
        const characterOnly = { command: TEST_COMMAND.id, keybinding: 'ctrl+ü' };
        const positional = { command: TEST_COMMAND2.id, keybinding: 'ctrl+[' };
        keybindingRegistry.setKeymap(KeybindingScope.USER, [characterOnly, positional]);

        expect(keybindingRegistry.getKeybindingInactiveReason(characterOnly)).to.be.a('string');
        expect(keybindingRegistry.matchKeybinding(keybindingRegistry.resolveKeybinding(characterOnly))).to.be.undefined;
        expect(keybindingRegistry.getKeybindingInactiveReason(positional)).to.be.undefined;
        expect(keybindingRegistry.matchKeybinding(keybindingRegistry.resolveKeybinding(positional))?.kind).to.equal('full');
    });

    it('should require resolved sequences for logical matching in code dispatch mode', () => {
        testContainer.get(MockKeyboardLayoutChangeNotifier).emitter.fire(enUSPc);
        const binding = { command: TEST_COMMAND.id, keybinding: 'ctrl+shift+a' };
        keybindingRegistry.setKeymap(KeybindingScope.USER, [binding]);

        expect(KeySequence.parse('ctrl+shift+a')[0].dispatchString()).to.equal('shift+ctrl+a');
        expect(keybindingRegistry.resolveKeybinding(binding)[0].dispatchString()).to.equal('ctrl+a@shift');
        expect(keybindingRegistry.matchKeybinding(KeySequence.parse('ctrl+shift+a'))).to.be.undefined;
        expect(keybindingRegistry.matchKeybinding(keybindingRegistry.resolveKeybinding(binding))?.kind).to.equal('full');
    });

    it('should invalidate resolved bindings when keyboard dispatch changes', () => {
        const binding = { command: TEST_COMMAND.id, keybinding: 'ctrl+[' };
        keybindingRegistry.setKeymap(KeybindingScope.USER, [binding]);
        expect(keybindingRegistry.getKeybindingInactiveReason(binding)).to.be.undefined;
        const changed = sinon.spy();
        keybindingRegistry.onKeybindingsChanged(changed);

        (corePreferences as unknown as Record<string, unknown>)['keyboard.dispatch'] = 'keyCode';
        preferenceChanged.fire({ preferenceName: 'keyboard.dispatch' });

        expect(changed.calledOnce).to.be.true;
        expect(keybindingRegistry.resolveKeybinding(binding)[0].dispatchString()).to.equal('ctrl+[');
        expect(keybindingRegistry.matchKeybinding(KeySequence.parse('ctrl+['))?.kind).to.equal('full');
    });

    it('should prioritize bindings that use local context keys', () => {
        // Ensure JSDOM is enabled for this test since it uses document
        const disable = enableJSDOM();

        const keyCode = KeyCode.createKeyCode({ first: Key.KEY_A, modifiers: [KeyModifier.Shift] });

        // Register two commands with the same keybinding but different when clauses
        const globalBinding: Keybinding = {
            keybinding: keyCode.toString(),
            command: 'test.global-command',
            when: 'globalContextKey'
        };

        const localBinding: Keybinding = {
            keybinding: keyCode.toString(),
            command: 'test.local-command',
            when: 'localContextKey'
        };

        // Register commands with handlers so they are enabled
        commandRegistry.registerCommand({ id: 'test.global-command' }, { execute: () => { } });
        commandRegistry.registerCommand({ id: 'test.local-command' }, { execute: () => { } });

        // globalBinding is registered first, so without local context prioritization it would win
        keybindingRegistry.setKeymap(KeybindingScope.DEFAULT, [globalBinding, localBinding]);

        // Get the mock context key service
        const contextKeyService = testContainer.get<MockContextKeyService>(ContextKeyService);

        // Set up mock to return 'localContextKey' as a local key
        contextKeyService.setLocalContextKeys(new Set(['localContextKey']));

        // Both when clauses should match
        contextKeyService.setMatchResult(true);

        // Create a mock keyboard event with a target element
        const targetElement = document.createElement('div');
        const mockEvent = new KeyboardEvent('keydown', {
            key: 'A',
            shiftKey: true
        });
        Object.defineProperty(mockEvent, 'target', { value: targetElement });

        const match = keybindingRegistry.matchKeybinding(keybindingRegistry.resolveKeybinding(localBinding), mockEvent);

        // The localBinding should be selected because it uses a local context key
        expect(match?.kind).to.be.equal('full');
        expect(match?.runtime.binding?.command).to.be.equal('test.local-command');

        disable();
    });

    it('should fall back to first binding when no local context keys exist', () => {
        // Ensure JSDOM is enabled for this test since it uses document
        const disable = enableJSDOM();

        const keyCode = KeyCode.createKeyCode({ first: Key.KEY_B, modifiers: [KeyModifier.Shift] });

        const firstBinding: Keybinding = {
            keybinding: keyCode.toString(),
            command: 'test.first-command',
            when: 'someContextKey'
        };

        const secondBinding: Keybinding = {
            keybinding: keyCode.toString(),
            command: 'test.second-command',
            when: 'otherContextKey'
        };

        commandRegistry.registerCommand({ id: 'test.first-command' }, { execute: () => { } });
        commandRegistry.registerCommand({ id: 'test.second-command' }, { execute: () => { } });

        // Note: bindings registered later (later in the array) have higher priority
        // because insertBindingIntoScope inserts them at the front of the scope's keymap
        keybindingRegistry.setKeymap(KeybindingScope.DEFAULT, [firstBinding, secondBinding]);

        const contextKeyService = testContainer.get<MockContextKeyService>(ContextKeyService);

        // No local context keys
        contextKeyService.setLocalContextKeys(new Set());
        contextKeyService.setMatchResult(true);

        const targetElement = document.createElement('div');
        const mockEvent = new KeyboardEvent('keydown', {
            key: 'B',
            shiftKey: true
        });
        Object.defineProperty(mockEvent, 'target', { value: targetElement });

        const match = keybindingRegistry.matchKeybinding(keybindingRegistry.resolveKeybinding(secondBinding), mockEvent);

        // Should fall back to first enabled binding in priority order (secondBinding was registered later, so it wins)
        expect(match?.kind).to.be.equal('full');
        expect(match?.runtime.binding?.command).to.be.equal('test.second-command');

        disable();
    });
});

describe('keybindings displayed for a command', () => {

    let displayedBinding: Keybinding;

    beforeEach(() => {
        displayedBinding = {
            command: KeybindingRegistry.PASSTHROUGH_PSEUDO_COMMAND,
            keybinding: 'ctrl+v',
            displayFor: TEST_COMMAND_SHADOW.id
        };
        keybindingRegistry.registerKeybinding(displayedBinding);
    });

    it('should show a passthrough keybinding as the accelerator of the command it is displayed for', () => {
        const handler = commandRegistry.registerHandler(TEST_COMMAND_SHADOW.id, { execute: () => { } });

        try {
            expect(keybindingRegistry.acceleratorForCommand(TEST_COMMAND_SHADOW.id, undefined)).to.deep.equal(['Ctrl+V']);
        } finally {
            handler.dispose();
        }
    });

    it('should not show a displayed keybinding for a disabled command', () => {
        const handler = commandRegistry.registerHandler(TEST_COMMAND_SHADOW.id, { execute: () => { }, isEnabled: () => false });

        try {
            expect(keybindingRegistry.acceleratorForCommand(TEST_COMMAND_SHADOW.id, undefined)).to.deep.equal([]);
        } finally {
            handler.dispose();
        }
    });

    it('should not fall back to a displayed keybinding when the command is disabled but has its own keybinding', () => {
        const handler = commandRegistry.registerHandler(TEST_COMMAND_SHADOW.id, { execute: () => { }, isEnabled: () => false });
        keybindingRegistry.registerKeybinding({
            command: TEST_COMMAND_SHADOW.id,
            keybinding: 'ctrl+shift+v'
        });

        try {
            expect(keybindingRegistry.acceleratorForCommand(TEST_COMMAND_SHADOW.id, undefined)).to.deep.equal([]);
        } finally {
            handler.dispose();
        }
    });

    it('should not return a displayed keybinding as a keybinding of the command', () => {
        expect(keybindingRegistry.getKeybindingsForCommand(TEST_COMMAND_SHADOW.id)).to.be.empty;
    });

    it('should let the key pass through instead of executing the command it is displayed for', () => {
        const execute = sinon.spy();
        const handler = commandRegistry.registerHandler(TEST_COMMAND_SHADOW.id, { execute });

        try {
            expect(keybindingRegistry.matchKeybinding(keybindingRegistry.resolveKeybinding(displayedBinding))?.runtime.binding?.command)
                .to.equal(KeybindingRegistry.PASSTHROUGH_PSEUDO_COMMAND);

            const event = testKeyboardEvent({ key: 'v', code: 'KeyV', keyCode: 86, ctrlKey: true });
            keybindingRegistry.run(event);

            expect(execute.called).to.be.false;
            expect(event.defaultPrevented).to.be.false;
        } finally {
            handler.dispose();
        }
    });

    it('should prefer a keybinding that executes the command over a displayed one', () => {
        const handler = commandRegistry.registerHandler(TEST_COMMAND_SHADOW.id, { execute: () => { } });
        keybindingRegistry.registerKeybinding({
            command: TEST_COMMAND_SHADOW.id,
            keybinding: 'ctrl+shift+v'
        });

        try {
            expect(keybindingRegistry.acceleratorForCommand(TEST_COMMAND_SHADOW.id, undefined)).to.deep.equal(['Ctrl+Shift+V']);
        } finally {
            handler.dispose();
        }
    });

    it('should not show a displayed keybinding that the user disabled', () => {
        const handler = commandRegistry.registerHandler(TEST_COMMAND_SHADOW.id, { execute: () => { } });
        keybindingRegistry.setKeymap(KeybindingScope.USER, [{
            command: '-' + KeybindingRegistry.PASSTHROUGH_PSEUDO_COMMAND,
            keybinding: 'ctrl+v'
        }]);

        try {
            expect(keybindingRegistry.acceleratorForCommand(TEST_COMMAND_SHADOW.id, undefined)).to.deep.equal([]);
        } finally {
            handler.dispose();
        }
    });
});

describe('acceleratorForKeyCode', () => {

    const ctrlV = KeyCode.createKeyCode({ key: Key.KEY_V, ctrl: true });
    const metaV = KeyCode.createKeyCode({ key: Key.KEY_V, meta: true });

    it('uses ASCII names with the separator on non-macOS', () => {
        stub.value(false);
        const accelerator = keybindingRegistry.acceleratorForKeyCode(ctrlV, '+');
        expect(accelerator).to.equal('Ctrl+V');
    });

    it('uses macOS symbols without a separator on macOS browser', () => {
        stub.value(true);
        const accelerator = keybindingRegistry.acceleratorForKeyCode(metaV, '+');
        expect(accelerator).to.equal('⌘V');
    });

    it('separates logical labels from physical layout modifier realizations', () => {
        const logicalBracket = new KeyCode({
            key: Key.DIGIT8,
            ctrl: true,
            character: '[',
            layoutModifiers: 'altGraph'
        });
        const logicalSlash = new KeyCode({
            key: Key.DIGIT7,
            character: '/',
            layoutModifiers: 'shift'
        });

        expect(keybindingRegistry.componentsForKeyCode(logicalBracket)).to.deep.equal(['Ctrl', '[']);
        expect(keybindingRegistry.componentsForKeyCode(logicalBracket, false, 'physical')).to.deep.equal(['Ctrl', 'AltGr', '8']);
        expect(keybindingRegistry.acceleratorForKeyCode(logicalBracket, '+', true, 'physical')).to.equal('Ctrl+AltGr+8');
        expect(keybindingRegistry.componentsForKeyCode(logicalSlash)).to.deep.equal(['/']);
        expect(keybindingRegistry.componentsForKeyCode(logicalSlash, false, 'physical')).to.deep.equal(['Shift', '7']);
        expect(keybindingRegistry.acceleratorForKeyCode(logicalSlash, '+', true, 'physical')).to.equal('Shift+7');
    });

    it('keeps command Shift in physical realizations', () => {
        const commandShift = new KeyCode({ key: Key.TAB, ctrl: true, shift: true });
        expect(keybindingRegistry.componentsForKeyCode(commandShift, false, 'physical')).to.deep.equal(['Ctrl', 'Shift', 'Tab']);

        const shiftedLetter = new KeyCode({ key: Key.KEY_P, ctrl: true, character: 'P', layoutModifiers: 'shift' });
        expect(keybindingRegistry.componentsForKeyCode(shiftedLetter)).to.deep.equal(['Ctrl', 'Shift', 'P']);

        const unresolvedCharacter = new KeyCode({ ctrl: true, character: '§', supportedByLayout: false });
        expect(keybindingRegistry.componentsForKeyCode(unresolvedCharacter)).to.deep.equal(['Ctrl', '§']);
    });

    it('deduplicates command Alt and layout modifier Option on macOS', () => {
        stub.value(true);
        const commandAndLayoutOption = new KeyCode({
            key: Key.DIGIT6,
            meta: true,
            ctrl: true,
            alt: true,
            layoutModifiers: 'altGraph'
        });
        const layoutOption = new KeyCode({ key: Key.DIGIT6, layoutModifiers: 'altGraph' });

        expect(keybindingRegistry.componentsForKeyCode(commandAndLayoutOption, false, 'physical')).to.deep.equal(['⌘', '⌃', '⌥', '6']);
        expect(keybindingRegistry.componentsForKeyCode(commandAndLayoutOption, true, 'physical')).to.deep.equal(['Cmd', 'Ctrl', 'Alt', '6']);
        expect(keybindingRegistry.componentsForKeyCode(layoutOption, false, 'physical')).to.deep.equal(['⌥', '6']);
        expect(keybindingRegistry.componentsForKeyCode(layoutOption, true, 'physical')).to.deep.equal(['Option', '6']);
    });

    it('uses ASCII names with the separator on macOS Electron (asciiOnly)', () => {
        stub.value(true);
        const accelerator = keybindingRegistry.acceleratorForKeyCode(metaV, '+', true);
        expect(accelerator).to.equal('Cmd+V');
    });
});

const TEST_COMMAND: Command = {
    id: 'test.command'
};

const TEST_COMMAND2: Command = {
    id: 'test.command2'
};

const TEST_COMMAND_SHADOW: Command = {
    id: 'test.command-shadow'
};

@injectable()
class MockContextKeyService extends ContextKeyServiceDummyImpl {
    private localKeys: Set<string> = new Set();
    private shouldMatch: boolean = true;
    private parsedKeys: Map<string, Set<string>> = new Map();

    constructor() {
        super();
        // Set up default parsed keys for test expressions
        this.parsedKeys.set('globalContextKey', new Set(['globalContextKey']));
        this.parsedKeys.set('localContextKey', new Set(['localContextKey']));
        this.parsedKeys.set('someContextKey', new Set(['someContextKey']));
        this.parsedKeys.set('otherContextKey', new Set(['otherContextKey']));
    }

    setLocalContextKeys(keys: Set<string>): void {
        this.localKeys = keys;
    }

    setMatchResult(result: boolean): void {
        this.shouldMatch = result;
    }

    override match(expression: string, context?: HTMLElement): boolean {
        return this.shouldMatch;
    }

    override parseKeys(expression: string): Set<string> | undefined {
        return this.parsedKeys.get(expression) || new Set([expression]);
    }

    override getLocalContextKeys(element: HTMLElement): Set<string> {
        return this.localKeys;
    }

    override createOverlay(overlay: Iterable<[string, unknown]>): ContextMatcher {
        return this;
    }
}

@injectable()
class MockKeyboardLayoutProvider implements KeyboardLayoutProvider {
    getNativeLayout(): Promise<NativeKeyboardLayout> {
        return Promise.resolve(enUSPc);
    }
}

@injectable()
class MockKeyboardLayoutChangeNotifier implements KeyboardLayoutChangeNotifier {
    readonly emitter = new Emitter<NativeKeyboardLayout>();
    get onDidChangeNativeLayout(): Event<NativeKeyboardLayout> {
        return this.emitter.event;
    }
}

@injectable()
class TestContribution implements CommandContribution, KeybindingContribution {

    registerCommands(commands: CommandRegistry): void {
        commands.registerCommand(TEST_COMMAND);
        commands.registerCommand(TEST_COMMAND2);
        commands.registerCommand(TEST_COMMAND_SHADOW);
    }

    registerKeybindings(keybindings: KeybindingRegistry): void {
        [{
            command: TEST_COMMAND.id,
            context: 'testContext',
            keybinding: 'ctrl+a'
        },
        {
            command: TEST_COMMAND2.id,
            context: 'testContext',
            keybinding: 'ctrl+f1'
        },
        {
            command: TEST_COMMAND2.id,
            context: 'testContext',
            keybinding: 'ctrl+f2'
        },
        ].forEach(binding => {
            keybindings.registerKeybinding(binding);
        });
    }

}

function isKeyBindingRegistered(keybinding: Keybinding): boolean {
    const bindings = keybindingRegistry.getKeybindingsForCommand(keybinding.command);
    expect(bindings).not.to.be.undefined;
    let keyBindingFound = false;
    bindings.forEach(
        (value: Keybinding) => {
            if (value.command === keybinding.command && value.keybinding === keybinding.keybinding) {
                keyBindingFound = true;
            }
        }
    );
    return keyBindingFound;
}