From 61bb2f9df1411a4576cec6635a08ef48c7e6b087 Mon Sep 17 00:00:00 2001 From: Jinjing <6427696+AmethystLiang@users.noreply.github.com> Date: Sun, 28 Jun 2026 21:32:13 -0700 Subject: [PATCH] Fix macOS IME input mode detection (#6699) * Gate punctuation forwarding on input source feature Ensure ASCII and CJK direct punctuation keys are only treated as keydown candidates if `forwardAsciiPunctuation` is enabled in the current input source features. This avoids forwarding punctuation when the feature is disabled, satisfying requirements where certain input methods (such as Vietnamese) should not have punctuation forwarding enabled. * Fix macOS IME input mode detection --- src/main/ipc/app.test.ts | 69 +++++++++++- src/main/ipc/app.ts | 105 ++++++++++++++---- src/preload/api-types.ts | 9 +- src/preload/index.ts | 7 +- .../terminal-ime-input-source.test.ts | 64 +++++++++++ .../terminal-ime-input-source.ts | 53 ++++++++- ...terminal-ime-native-text-forwarder.test.ts | 24 ++-- .../terminal-ime-native-text-forwarder.ts | 10 +- 8 files changed, 299 insertions(+), 42 deletions(-) diff --git a/src/main/ipc/app.test.ts b/src/main/ipc/app.test.ts index 1718134d4..e1149d1b6 100644 --- a/src/main/ipc/app.test.ts +++ b/src/main/ipc/app.test.ts @@ -175,7 +175,70 @@ describe('registerAppHandlers', () => { expect(appExitMock).not.toHaveBeenCalled() }) - it('falls back when the macOS keyboard layout probe never reports completion', async () => { + it('returns the selected macOS input mode before the keyboard layout fallback', async () => { + Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true }) + execFileMock.mockImplementation((_command, _args, _options, callback) => { + callback( + null, + JSON.stringify([ + { 'Bundle ID': 'com.apple.PressAndHold', InputSourceKind: 'Non Keyboard Input Method' }, + { + 'Bundle ID': 'com.apple.inputmethod.SCIM', + 'Input Mode': 'com.apple.inputmethod.SCIM.ITABC', + InputSourceKind: 'Input Mode' + } + ]) + ) + return { kill: vi.fn() } + }) + registerAppHandlers({} as never) + + await expect(handlers.get('app:getKeyboardInputSourceId')?.(null)).resolves.toBe( + 'com.apple.inputmethod.SCIM.ITABC' + ) + expect(execFileMock).toHaveBeenCalledTimes(1) + expect(execFileMock).toHaveBeenCalledWith( + '/usr/bin/plutil', + expect.arrayContaining(['AppleSelectedInputSources']), + expect.any(Object), + expect.any(Function) + ) + }) + + it('falls back to the keyboard layout when no keyboard input mode is selected', async () => { + Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true }) + execFileMock + .mockImplementationOnce((_command, _args, _options, callback) => { + callback( + null, + JSON.stringify([ + { + 'Bundle ID': 'com.apple.PressAndHold', + InputSourceKind: 'Non Keyboard Input Method' + } + ]) + ) + return { kill: vi.fn() } + }) + .mockImplementationOnce((_command, _args, _options, callback) => { + callback(null, 'com.apple.keylayout.ABC\n') + return { kill: vi.fn() } + }) + registerAppHandlers({} as never) + + await expect(handlers.get('app:getKeyboardInputSourceId')?.(null)).resolves.toBe( + 'com.apple.keylayout.ABC' + ) + expect(execFileMock).toHaveBeenCalledTimes(2) + expect(execFileMock).toHaveBeenLastCalledWith( + '/usr/bin/defaults', + ['read', 'com.apple.HIToolbox', 'AppleCurrentKeyboardLayoutInputSourceID'], + expect.any(Object), + expect.any(Function) + ) + }) + + it('falls back when macOS keyboard input source probes never report completion', async () => { Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true }) const killMock = vi.fn() execFileMock.mockImplementation(() => ({ kill: killMock })) @@ -189,11 +252,11 @@ describe('registerAppHandlers', () => { return result }) - await vi.advanceTimersByTimeAsync(500) + await vi.advanceTimersByTimeAsync(1000) expect(settled).toBe(true) await expect(resultPromise).resolves.toBeNull() - expect(killMock).toHaveBeenCalled() + expect(killMock).toHaveBeenCalledTimes(2) }) it('picks an existing floating workspace directory without enabling native directory creation', async () => { diff --git a/src/main/ipc/app.ts b/src/main/ipc/app.ts index be33ef389..e17e86d7b 100644 --- a/src/main/ipc/app.ts +++ b/src/main/ipc/app.ts @@ -1,5 +1,6 @@ import { execFile } from 'node:child_process' import { existsSync } from 'node:fs' +import { homedir } from 'node:os' import path from 'node:path' import { pathToFileURL } from 'node:url' import { app, BrowserWindow, dialog, ipcMain, type IpcMainInvokeEvent } from 'electron' @@ -22,6 +23,13 @@ import { import { isMarkdownDocumentName, markdownDocumentFromFilePath } from './markdown-documents' const KEYBOARD_INPUT_SOURCE_TIMEOUT_MS = 500 +const MAC_HITOOLBOX_DOMAIN = 'com.apple.HIToolbox' +const MAC_HITOOLBOX_PREFERENCES_PATH = path.join( + homedir(), + 'Library', + 'Preferences', + `${MAC_HITOOLBOX_DOMAIN}.plist` +) type RegisterAppHandlersOptions = { onBeforeRelaunch?: () => void | Promise @@ -103,7 +111,11 @@ function resolveDevFeatureWallAssetDir(): string { return candidates.find((candidate) => existsSync(candidate)) ?? candidates[0] } -function readKeyboardInputSourceId(): Promise { +function readCommandStdout( + command: string, + args: string[], + timeoutMessage: string +): Promise { return new Promise((resolve, reject) => { let settled = false let child: ReturnType | undefined @@ -113,7 +125,7 @@ function readKeyboardInputSourceId(): Promise { } settled = true child?.kill() - reject(new Error('Keyboard input source probe timed out')) + reject(new Error(timeoutMessage)) }, KEYBOARD_INPUT_SOURCE_TIMEOUT_MS) const settle = (callback: () => void): void => { @@ -129,9 +141,9 @@ function readKeyboardInputSourceId(): Promise { // never arrives, window-focus keyboard probes would remain pending. try { child = execFile( - '/usr/bin/defaults', - ['read', 'com.apple.HIToolbox', 'AppleCurrentKeyboardLayoutInputSourceID'], - // Why: short timeout so a wedged defaults binary (corporate-managed + command, + args, + // Why: short timeout so a wedged macOS preference probe (corporate-managed // config, sandbox policy, ...) never holds the handle indefinitely. // Fall through to the fingerprint on timeout. { encoding: 'utf8', timeout: KEYBOARD_INPUT_SOURCE_TIMEOUT_MS }, @@ -140,7 +152,7 @@ function readKeyboardInputSourceId(): Promise { settle(() => reject(error)) return } - settle(() => resolve(String(stdout))) + settle(() => resolve(String(stdout ?? ''))) } ) } catch (error) { @@ -149,6 +161,67 @@ function readKeyboardInputSourceId(): Promise { }) } +function readSelectedInputSourceIdFromJson(stdout: string): string | null { + let records: unknown + try { + records = JSON.parse(stdout) + } catch { + return null + } + if (!Array.isArray(records)) { + return null + } + + for (const record of records.slice().reverse()) { + if (!record || typeof record !== 'object') { + continue + } + const fields = record as Record + const kind = typeof fields.InputSourceKind === 'string' ? fields.InputSourceKind : '' + if (kind.toLowerCase().includes('non keyboard')) { + continue + } + const inputMode = fields['Input Mode'] + if (typeof inputMode === 'string' && inputMode.trim()) { + return inputMode.trim() + } + const bundleId = fields['Bundle ID'] + if (typeof bundleId === 'string' && bundleId.trim()) { + return bundleId.trim() + } + } + return null +} + +async function readSelectedKeyboardInputSourceId(): Promise { + try { + const stdout = await readCommandStdout( + '/usr/bin/plutil', + ['-extract', 'AppleSelectedInputSources', 'json', '-o', '-', MAC_HITOOLBOX_PREFERENCES_PATH], + 'Selected keyboard input source probe timed out' + ) + return readSelectedInputSourceIdFromJson(stdout) + } catch { + return null + } +} + +function readKeyboardLayoutInputSourceId(): Promise { + return readCommandStdout( + '/usr/bin/defaults', + ['read', MAC_HITOOLBOX_DOMAIN, 'AppleCurrentKeyboardLayoutInputSourceID'], + 'Keyboard layout input source probe timed out' + ) +} + +async function readKeyboardInputSourceId(): Promise { + const selectedInputSourceId = await readSelectedKeyboardInputSourceId() + if (selectedInputSourceId) { + return selectedInputSourceId + } + return readKeyboardLayoutInputSourceId() +} + export function registerAppHandlers(store: Store, options: RegisterAppHandlersOptions = {}): void { ipcMain.handle('app:getFeatureWallAssetBaseUrl', (): string => getFeatureWallAssetBaseUrl()) @@ -175,20 +248,12 @@ export function registerAppHandlers(store: Store, options: RegisterAppHandlersOp // — the layout-fingerprint probe in the renderer therefore classifies // them as 'us' and flips macOptionIsMeta=true, silently swallowing every // Option+letter composition (#1205: Option+A → å / ą is dropped). The - // macOS-shipped `com.apple.HIToolbox` preference - // `AppleCurrentKeyboardLayoutInputSourceID` names the actual layout + // macOS-shipped `com.apple.HIToolbox` preferences name the actual input + // mode when one is selected, falling back to the keyboard layout ID // (e.g. `com.apple.keylayout.ABC` vs `com.apple.keylayout.US`), which // the renderer uses as an authoritative override. Non-Darwin platforms // have no equivalent and return null so the fingerprint stays the only // signal. - // - // Why `defaults read` and not systemPreferences - // .getUserDefault: getUserDefault only reads from NSGlobalDomain and the - // current app's own domain. The keyboard layout ID lives in the - // `com.apple.HIToolbox` domain, which getUserDefault cannot reach — - // observed to return null even when the preference is set. The `defaults` - // CLI reads any domain and is the same mechanism Apple documents for - // this value. ipcMain.handle('app:getKeyboardInputSourceId', async (): Promise => { if (process.platform !== 'darwin') { return null @@ -199,12 +264,12 @@ export function registerAppHandlers(store: Store, options: RegisterAppHandlersOp // and a blocking execFileSync would briefly stall unrelated IPC each // time the user Alt-Tabbed back into the app. const stdout = await readKeyboardInputSourceId() - const trimmed = stdout.trim() + const trimmed = stdout?.trim() ?? '' return trimmed.length > 0 ? trimmed : null } catch { - // Why: defaults exits non-zero when the key is absent (first boot - // before any input-source interaction), or when sandboxed. Treat - // that as "no signal" — the fingerprint still runs as fallback. + // Why: macOS preference probes can fail when keys are absent (first boot + // before any input-source interaction), or when sandboxed. Treat that as + // "no signal" — the fingerprint still runs as fallback. return null } }) diff --git a/src/preload/api-types.ts b/src/preload/api-types.ts index 4fa7e1c37..75b2d1cd0 100644 --- a/src/preload/api-types.ts +++ b/src/preload/api-types.ts @@ -799,10 +799,11 @@ export type AppApi = { /** Resolves when the daemon PTY provider and hook receiver have either * started or failed open for the first BrowserWindow. */ awaitFirstWindowStartupServices: () => Promise - /** Returns the macOS `AppleCurrentKeyboardLayoutInputSourceID` when - * available (e.g. `com.apple.keylayout.PolishPro`). Used by the - * keyboard-layout probe to distinguish layouts whose base layer matches - * US QWERTY but whose Option layer composes characters (issue #1205). + /** Returns the macOS active input mode, or layout ID when no IME mode is + * selected (e.g. `com.apple.keylayout.PolishPro`). Used by the + * keyboard-layout probe to distinguish CJK IMEs and layouts whose base + * layer matches US QWERTY but whose Option layer composes characters + * (issue #1205). * Returns null on non-Darwin platforms or when the defaults read fails. */ getKeyboardInputSourceId: () => Promise /** Updates the macOS Dock unread badge. No-op on Windows/Linux. */ diff --git a/src/preload/index.ts b/src/preload/index.ts index 7bbcc6d8e..e6c7a3079 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -451,10 +451,9 @@ const api = { reload: (): Promise => ipcRenderer.invoke('app:reload'), awaitFirstWindowStartupServices: (): Promise => ipcRenderer.invoke('app:awaitFirstWindowStartupServices'), - // Why: on macOS this returns AppleCurrentKeyboardLayoutInputSourceID so - // the renderer's keyboard-layout probe can distinguish Polish Pro / US - // Extended / ABC Extended / IME Roman modes from plain US QWERTY (see - // src/renderer/src/lib/keyboard-layout/input-source-id.ts, issue #1205). + // Why: on macOS this returns the active input mode, or the layout ID when + // no IME mode is selected, so renderer keyboard workarounds can distinguish + // CJK IMEs and compose layouts from plain US QWERTY (see issue #1205). // Returns null on non-Darwin or when the defaults read fails. getKeyboardInputSourceId: (): Promise => ipcRenderer.invoke('app:getKeyboardInputSourceId'), diff --git a/src/renderer/src/components/terminal-pane/terminal-ime-input-source.test.ts b/src/renderer/src/components/terminal-pane/terminal-ime-input-source.test.ts index 9b2668244..40cf41087 100644 --- a/src/renderer/src/components/terminal-pane/terminal-ime-input-source.test.ts +++ b/src/renderer/src/components/terminal-pane/terminal-ime-input-source.test.ts @@ -12,6 +12,7 @@ describe('getMacNativeTextInputSourceFeatures', () => { for (const sourceId of [ 'com.apple.inputmethod.SCIM.ITABC', 'com.apple.inputmethod.TCIM.Pinyin', + 'com.apple.keylayout.PinyinKeyboard', 'com.apple.inputmethod.Kotoeri.RomajiTyping.Japanese', 'com.apple.inputmethod.Korean.2SetKorean' ]) { @@ -126,6 +127,69 @@ describe('createMacNativeTextInputSourceTracker', () => { tracker.dispose() }) + it('refreshes on keydown so focused input source switches are picked up', async () => { + let sourceId = 'com.apple.keylayout.ABC' + const tracker = createMacNativeTextInputSourceTracker(window, { + readInputSourceId: async () => sourceId + }) + await tracker.refresh() + expect(tracker.isActive()).toBe(false) + + sourceId = 'com.apple.inputmethod.SCIM.ITABC' + window.dispatchEvent(new KeyboardEvent('keydown', { key: 'd' })) + + await vi.waitFor(() => + expect(tracker.getFeatures()).toEqual({ + forwardAsciiPunctuation: true, + forwardShortTextReplacements: false + }) + ) + tracker.dispose() + }) + + it('throttles ordinary key refreshes while input-source features are disabled', async () => { + let sourceId = 'com.apple.keylayout.ABC' + const readInputSourceId = vi.fn(async () => sourceId) + const tracker = createMacNativeTextInputSourceTracker(window, { readInputSourceId }) + await tracker.refresh() + readInputSourceId.mockClear() + + const now = vi.spyOn(Date, 'now').mockReturnValue(1000) + try { + window.dispatchEvent(new KeyboardEvent('keydown', { key: 'a' })) + await vi.waitFor(() => expect(readInputSourceId).toHaveBeenCalledTimes(1)) + + window.dispatchEvent(new KeyboardEvent('keydown', { key: 'b' })) + window.dispatchEvent(new KeyboardEvent('keyup', { key: 'b' })) + await Promise.resolve() + expect(readInputSourceId).toHaveBeenCalledTimes(1) + + sourceId = 'com.apple.inputmethod.SCIM.ITABC' + now.mockReturnValue(2001) + window.dispatchEvent(new KeyboardEvent('keydown', { key: 'c' })) + await vi.waitFor(() => expect(readInputSourceId).toHaveBeenCalledTimes(2)) + expect(tracker.isActive()).toBe(true) + } finally { + now.mockRestore() + tracker.dispose() + } + }) + + it('refreshes on modifier keyup so active sources can become disabled while focused', async () => { + let sourceId = 'com.apple.inputmethod.SCIM.ITABC' + const tracker = createMacNativeTextInputSourceTracker(window, { + readInputSourceId: async () => sourceId + }) + await tracker.refresh() + expect(tracker.isActive()).toBe(true) + + sourceId = 'com.apple.keylayout.ABC' + window.dispatchEvent(new KeyboardEvent('keyup', { key: ' ', ctrlKey: true })) + + await vi.waitFor(() => expect(tracker.isActive()).toBe(false)) + tracker.dispose() + }) + it('keeps the singleton reusable for terminal lifecycle code', () => { const first = getMacNativeTextInputSourceTracker() const second = getMacNativeTextInputSourceTracker() diff --git a/src/renderer/src/components/terminal-pane/terminal-ime-input-source.ts b/src/renderer/src/components/terminal-pane/terminal-ime-input-source.ts index b8fd3327b..d4e49dad1 100644 --- a/src/renderer/src/components/terminal-pane/terminal-ime-input-source.ts +++ b/src/renderer/src/components/terminal-pane/terminal-ime-input-source.ts @@ -56,6 +56,8 @@ const CJK_INPUT_SOURCE_TERMS = [ const VIETNAMESE_INPUT_SOURCE_TERMS = ['telex', 'unikey', 'vietnam', 'vni'] as const +const KEYBOARD_ACTIVITY_REFRESH_COOLDOWN_MS = 1000 + function defaultKeyboardInputSourceReader(): KeyboardInputSourceReader { return async () => { const api = ( @@ -105,6 +107,9 @@ export function createMacNativeTextInputSourceTracker( let features: MacNativeTextInputSourceFeatures = DISABLED_MAC_NATIVE_TEXT_INPUT_SOURCE_FEATURES let disposed = false let refreshGeneration = 0 + let refreshInFlight = false + let refreshQueued = false + let lastKeyboardActivityRefreshAt: number | null = null const refresh = async (): Promise => { const generation = ++refreshGeneration @@ -120,12 +125,54 @@ export function createMacNativeTextInputSourceTracker( features = getMacNativeTextInputSourceFeatures(inputSourceId) } + const requestRefresh = (): void => { + if (refreshInFlight) { + refreshQueued = true + return + } + refreshInFlight = true + void refresh().finally(() => { + refreshInFlight = false + if (!disposed && refreshQueued) { + refreshQueued = false + requestRefresh() + } + }) + } + const onFocus = (): void => { - void refresh() + requestRefresh() + } + + const requestKeyboardActivityRefresh = (force: boolean): void => { + const now = Date.now() + if ( + !force && + lastKeyboardActivityRefreshAt !== null && + now - lastKeyboardActivityRefreshAt < KEYBOARD_ACTIVITY_REFRESH_COOLDOWN_MS + ) { + return + } + lastKeyboardActivityRefreshAt = now + requestRefresh() + } + + const onKeyboardActivity = (event: KeyboardEvent): void => { + if (event.ctrlKey || event.altKey || event.metaKey) { + requestKeyboardActivityRefresh(true) + return + } + if (!features.forwardAsciiPunctuation && !features.forwardShortTextReplacements) { + requestKeyboardActivityRefresh(false) + } } win.addEventListener('focus', onFocus) - void refresh() + // Why: macOS input-source changes can happen while the terminal keeps focus; + // refresh from keyboard activity so CJK punctuation gates do not stay stale. + win.addEventListener('keydown', onKeyboardActivity, true) + win.addEventListener('keyup', onKeyboardActivity, true) + requestRefresh() return { isActive: () => features.forwardAsciiPunctuation || features.forwardShortTextReplacements, @@ -134,6 +181,8 @@ export function createMacNativeTextInputSourceTracker( dispose: () => { disposed = true win.removeEventListener('focus', onFocus) + win.removeEventListener('keydown', onKeyboardActivity, true) + win.removeEventListener('keyup', onKeyboardActivity, true) } } } diff --git a/src/renderer/src/components/terminal-pane/terminal-ime-native-text-forwarder.test.ts b/src/renderer/src/components/terminal-pane/terminal-ime-native-text-forwarder.test.ts index 01e7153c8..87dec7d67 100644 --- a/src/renderer/src/components/terminal-pane/terminal-ime-native-text-forwarder.test.ts +++ b/src/renderer/src/components/terminal-pane/terminal-ime-native-text-forwarder.test.ts @@ -46,9 +46,9 @@ describe('isImeNativeTextKeydownCandidate', () => { } }) - it('accepts unmodified ASCII punctuation keydown without an input source gate', () => { + it('rejects unmodified ASCII punctuation keydown without an input source gate', () => { expect(isImeNativeTextKeydownCandidate(keyEvent({ key: '.' }), false, DISABLED_FEATURES)).toBe( - true + false ) }) @@ -58,7 +58,17 @@ describe('isImeNativeTextKeydownCandidate', () => { } }) - it('accepts Vietnamese short replacement keys while punctuation stays source-independent', () => { + it('accepts direct CJK punctuation keydown when the input source probe is stale', () => { + expect( + isImeNativeTextKeydownCandidate( + keyEvent({ key: ',', code: 'Comma' }), + false, + DISABLED_FEATURES + ) + ).toBe(true) + }) + + it('accepts Vietnamese short replacement keys without enabling punctuation', () => { expect( isImeNativeTextKeydownCandidate( keyEvent({ key: 'a', code: 'KeyA' }), @@ -82,7 +92,7 @@ describe('isImeNativeTextKeydownCandidate', () => { ).toBe(true) expect( isImeNativeTextKeydownCandidate(keyEvent({ key: ',' }), false, VIETNAMESE_FEATURES) - ).toBe(true) + ).toBe(false) }) it('accepts synthesized Unicode text keydowns without an input source gate', () => { @@ -588,7 +598,7 @@ describe('installTerminalImeNativeTextForwarder', () => { expect(() => forwarder.dispose()).not.toThrow() }) - it('still forwards punctuation when input-source features are disabled', () => { + it('does not forward punctuation when input-source features are disabled', () => { const sendInput = vi.fn() const forwarder = installTerminalImeNativeTextForwarder({ terminalElement: element, @@ -597,9 +607,9 @@ describe('installTerminalImeNativeTextForwarder', () => { getInputSourceFeatures: () => DISABLED_FEATURES }) - expect(forwarder.claimKeyEvent(keyEvent({ key: ',' }))).toBe(true) + expect(forwarder.claimKeyEvent(keyEvent({ key: ',' }))).toBe(false) dispatchInsertText(textarea, ',') - expect(sendInput).toHaveBeenCalledExactlyOnceWith(',') + expect(sendInput).not.toHaveBeenCalled() }) it('can become enabled after the input source changes to a Vietnamese IME', () => { diff --git a/src/renderer/src/components/terminal-pane/terminal-ime-native-text-forwarder.ts b/src/renderer/src/components/terminal-pane/terminal-ime-native-text-forwarder.ts index df5c889aa..99f69ed45 100644 --- a/src/renderer/src/components/terminal-pane/terminal-ime-native-text-forwarder.ts +++ b/src/renderer/src/components/terminal-pane/terminal-ime-native-text-forwarder.ts @@ -162,7 +162,10 @@ export function isImeNativeTextKeydownCandidate( if (isSyntheticUnicodeTextKey(event)) { return true } - if (isAsciiPunctuationKey(event.key) || isCjkDirectPunctuationKey(event.key)) { + if (isCjkDirectPunctuationKey(event.key)) { + return true + } + if (inputSourceFeatures.forwardAsciiPunctuation && isAsciiPunctuationKey(event.key)) { return true } return ( @@ -275,7 +278,10 @@ export function installTerminalImeNativeTextForwarder(args: { } const forwardCommittedText = (event: Event): void => { - if (!pendingForward || !(event instanceof InputEvent)) { + if (!(event instanceof InputEvent)) { + return + } + if (!pendingForward) { return } if (event.inputType !== 'insertText') {