diff --git a/src/main/codex-accounts/runtime-home-service.test.ts b/src/main/codex-accounts/runtime-home-service.test.ts index e6688f390..e07496b9e 100644 --- a/src/main/codex-accounts/runtime-home-service.test.ts +++ b/src/main/codex-accounts/runtime-home-service.test.ts @@ -158,7 +158,6 @@ function createSettings(overrides: TestSettingsOverrides = {}): GlobalSettings { terminalMacOptionAsAlt: 'false', terminalMacOptionAsAltMigrated: true, terminalJISYenToBackslash: false, - terminalKoreanWonToBackquote: false, experimentalMobile: false, mobileAutoRestoreFitMs: null, experimentalPet: false, diff --git a/src/main/codex-accounts/service.test.ts b/src/main/codex-accounts/service.test.ts index 7c55304c5..47fd0c678 100644 --- a/src/main/codex-accounts/service.test.ts +++ b/src/main/codex-accounts/service.test.ts @@ -150,7 +150,6 @@ function createSettings(overrides: Partial = {}): GlobalSettings terminalMacOptionAsAlt: 'false', terminalMacOptionAsAltMigrated: true, terminalJISYenToBackslash: false, - terminalKoreanWonToBackquote: false, experimentalMobile: false, mobileAutoRestoreFitMs: null, experimentalPet: false, diff --git a/src/renderer/src/components/settings/TerminalMacKeyboardSection.tsx b/src/renderer/src/components/settings/TerminalMacKeyboardSection.tsx index f8305030f..0e4036f24 100644 --- a/src/renderer/src/components/settings/TerminalMacKeyboardSection.tsx +++ b/src/renderer/src/components/settings/TerminalMacKeyboardSection.tsx @@ -146,47 +146,6 @@ export function TerminalMacKeyboardSection({ } /> - - {/* Why: with a Korean keyboard input source active, the backquote-position keystroke is rewritten to backquote regardless of the layout's character there. */} - - - updateSettings({ - terminalKoreanWonToBackquote: !settings.terminalKoreanWonToBackquote - }) - } - /> - ) } diff --git a/src/renderer/src/components/settings/terminal-advanced-platform-search.ts b/src/renderer/src/components/settings/terminal-advanced-platform-search.ts index 0e19c8f58..a944ae12f 100644 --- a/src/renderer/src/components/settings/terminal-advanced-platform-search.ts +++ b/src/renderer/src/components/settings/terminal-advanced-platform-search.ts @@ -93,31 +93,6 @@ export const getTerminalMacYenSearchEntries = createLocalizedCatalog(() => [ } ]) -export const getTerminalKoreanWonSearchEntries = createLocalizedCatalog(() => [ - { - title: translate( - 'auto.components.settings.terminal.search.d6756003bf', - 'Korean Won (₩) to Backquote (`)' - ), - description: translate( - 'auto.components.settings.terminal.search.3595f8b54c', - 'Controls whether pressing the Korean Won (₩) key sends a backquote (`) instead when a Korean input source is active.' - ), - keywords: [ - ...translateSearchKeyword('auto.components.settings.terminal.search.f66a7cf715', 'terminal'), - ...translateSearchKeyword('auto.components.settings.terminal.search.5ba707eec2', 'won'), - ...translateSearchKeyword('auto.components.settings.terminal.search.d243131b1a', 'backquote'), - ...translateSearchKeyword('auto.components.settings.terminal.search.2a22983b81', 'backtick'), - ...translateSearchKeyword('auto.components.settings.terminal.search.8f64dd7dc4', 'korean'), - ...translateSearchKeyword('auto.components.settings.terminal.search.84ae68de79', 'hangul'), - ...translateSearchKeyword('auto.components.settings.terminal.search.abaa24752d', 'keyboard'), - ...translateSearchKeyword('auto.components.settings.terminal.search.91cae143ad', 'korea'), - ...translateSearchKeyword('auto.components.settings.terminal.search.b26f68a00c', 'markdown'), - ...translateSearchKeyword('auto.components.settings.terminal.search.4cec42dbf7', 'intl') - ] - } -]) - export const getTerminalGhosttyImportSearchEntries = createLocalizedCatalog(() => [ { title: translate('auto.components.settings.terminal.search.a979df0083', 'Import from Ghostty'), diff --git a/src/renderer/src/components/settings/terminal-search.test.ts b/src/renderer/src/components/settings/terminal-search.test.ts index 51db3139d..b9d1ac769 100644 --- a/src/renderer/src/components/settings/terminal-search.test.ts +++ b/src/renderer/src/components/settings/terminal-search.test.ts @@ -68,20 +68,6 @@ describe('getTerminalPaneSearchEntries', () => { ) }) - it('includes the Korean Won mapping setting only on macOS', () => { - const entriesMac = getTerminalPaneSearchEntries({ isWindows: false, isMac: true }) - const entriesWindows = getTerminalPaneSearchEntries({ isWindows: true, isMac: false }) - const entriesLinux = getTerminalPaneSearchEntries({ isWindows: false, isMac: false }) - - expect(entriesMac.some((entry) => entry.title === 'Korean Won (₩) to Backquote (`)')).toBe(true) - expect(entriesWindows.some((entry) => entry.title === 'Korean Won (₩) to Backquote (`)')).toBe( - false - ) - expect(entriesLinux.some((entry) => entry.title === 'Korean Won (₩) to Backquote (`)')).toBe( - false - ) - }) - it('includes the Manage Sessions entry on all platforms', () => { const entriesWindows = getTerminalPaneSearchEntries({ isWindows: true, isMac: false }) const entriesMac = getTerminalPaneSearchEntries({ isWindows: false, isMac: true }) diff --git a/src/renderer/src/components/settings/terminal-search.ts b/src/renderer/src/components/settings/terminal-search.ts index a14b0f18d..2a460bd64 100644 --- a/src/renderer/src/components/settings/terminal-search.ts +++ b/src/renderer/src/components/settings/terminal-search.ts @@ -2,7 +2,6 @@ import type { SettingsSearchEntry } from './settings-search' import { getTerminalAdvancedSearchEntries, getTerminalGhosttyImportSearchEntries, - getTerminalKoreanWonSearchEntries, getTerminalMacOptionSearchEntries, getTerminalMacYenSearchEntries } from './terminal-advanced-platform-search' @@ -53,7 +52,6 @@ export { } from './terminal-theme-search' export { getTerminalAdvancedSearchEntries, - getTerminalKoreanWonSearchEntries, getTerminalMacOptionSearchEntries, getTerminalMacYenSearchEntries, getTerminalGhosttyImportSearchEntries @@ -122,12 +120,7 @@ export function getTerminalPaneSearchEntries(platform: { ...getManageSessionsSearchEntries(), ...getTerminalAdvancedSearchEntries(), ...(platform.isMac - ? [ - ...getTerminalMacOptionSearchEntries(), - ...getTerminalMacYenSearchEntries(), - // Why: the mapping targets Korean keyboard input on macOS (see korean-input-source.ts), so it is Mac-only like JIS Yen. - ...getTerminalKoreanWonSearchEntries() - ] + ? [...getTerminalMacOptionSearchEntries(), ...getTerminalMacYenSearchEntries()] : []) ] } diff --git a/src/renderer/src/components/terminal-pane/TerminalPane.tsx b/src/renderer/src/components/terminal-pane/TerminalPane.tsx index 1ceb4aa27..36eadb696 100644 --- a/src/renderer/src/components/terminal-pane/TerminalPane.tsx +++ b/src/renderer/src/components/terminal-pane/TerminalPane.tsx @@ -1692,7 +1692,6 @@ function TerminalPane( panePtyBindingsRef, paneCwdRef, fallbackCwd: cwd ?? '', - koreanWonToBackquoteEnabled: settings?.terminalKoreanWonToBackquote === true, expandedPaneIdRef, setExpandedPane, restoreExpandedLayout, diff --git a/src/renderer/src/components/terminal-pane/keyboard-handlers-korean-prefetch-gate.test.tsx b/src/renderer/src/components/terminal-pane/keyboard-handlers-korean-prefetch-gate.test.tsx deleted file mode 100644 index f0cab5549..000000000 --- a/src/renderer/src/components/terminal-pane/keyboard-handlers-korean-prefetch-gate.test.tsx +++ /dev/null @@ -1,86 +0,0 @@ -// @vitest-environment happy-dom -// The Korean input-source probe shells out to `defaults export | plutil | plutil` — four processes -// in the main process — on a 2 s refresh cooldown. terminalKoreanWonToBackquote defaults to off, so -// prefetching it for every macOS user spends that on a feature almost nobody has enabled. -import { cleanup, renderHook } from '@testing-library/react' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const prefetchKoreanInputSource = vi.fn() -const stopKoreanInputSourcePrefetch = vi.fn() -vi.mock('@/lib/keyboard-layout/korean-input-source', () => ({ - prefetchKoreanInputSource: (...args: unknown[]) => prefetchKoreanInputSource(...args), - stopKoreanInputSourcePrefetch: (...args: unknown[]) => stopKoreanInputSourcePrefetch(...args), - isKoreanInputSourceActive: () => false, - isKoreanInputSourceId: () => false -})) - -import { useTerminalKeyboardShortcuts } from './keyboard-handlers' - -type KeyboardHandlersDeps = Parameters[0] - -function deps(koreanWonToBackquoteEnabled: boolean): KeyboardHandlersDeps { - const scope = document.createElement('div') - document.body.appendChild(scope) - return { - tabId: 'tab-1', - worktreeId: 'wt-1', - isActive: true, - keyboardScopeRef: { current: scope }, - managerRef: { current: null }, - paneTransportsRef: { current: new Map() }, - panePtyBindingsRef: { current: new Map() }, - paneCwdRef: { current: new Map() }, - fallbackCwd: '/tmp', - koreanWonToBackquoteEnabled, - expandedPaneIdRef: { current: null }, - setExpandedPane: vi.fn(), - restoreExpandedLayout: vi.fn(), - refreshPaneSizes: vi.fn(), - persistLayoutSnapshot: vi.fn(), - toggleExpandPane: vi.fn(), - setSearchOpen: vi.fn(), - onSearchSelectedText: vi.fn(), - onRequestClosePane: vi.fn(), - onClearPaneScrollback: vi.fn(), - onSetTitle: vi.fn(), - onClearPaneTitle: vi.fn(), - searchOpenRef: { current: false }, - searchStateRef: { current: { query: '', caseSensitive: false, regex: false } }, - macOptionAsAltRef: { current: 'off' }, - paneKittyKeyboardModesRef: { current: null } - } as unknown as KeyboardHandlersDeps -} - -beforeEach(() => { - prefetchKoreanInputSource.mockClear() - stopKoreanInputSourcePrefetch.mockClear() - vi.spyOn(navigator, 'userAgent', 'get').mockReturnValue( - 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)' - ) -}) - -afterEach(() => { - cleanup() - vi.restoreAllMocks() - document.body.replaceChildren() -}) - -describe('Korean input-source prefetch gate', () => { - it('does not probe the input source when the setting is off', () => { - renderHook(() => useTerminalKeyboardShortcuts(deps(false))) - expect(prefetchKoreanInputSource).not.toHaveBeenCalled() - }) - - it('probes once the setting is on', () => { - renderHook(() => useTerminalKeyboardShortcuts(deps(true))) - expect(prefetchKoreanInputSource).toHaveBeenCalled() - }) - - // The probe's listeners are global and its attach is idempotent, so without an explicit - // disposer they outlive the setting being switched off and keep spawning the refresh. - it('detaches the probe when the setting is switched off', () => { - renderHook(() => useTerminalKeyboardShortcuts(deps(false))) - expect(stopKoreanInputSourcePrefetch).toHaveBeenCalled() - expect(prefetchKoreanInputSource).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/components/terminal-pane/keyboard-handlers.ts b/src/renderer/src/components/terminal-pane/keyboard-handlers.ts index 066c2327a..6580bbb81 100644 --- a/src/renderer/src/components/terminal-pane/keyboard-handlers.ts +++ b/src/renderer/src/components/terminal-pane/keyboard-handlers.ts @@ -35,10 +35,6 @@ import { getLayoutBaseCharacterForCode, prefetchLayoutBaseCharacters } from '@/lib/keyboard-layout/layout-base-character' -import { - prefetchKoreanInputSource, - stopKoreanInputSourcePrefetch -} from '@/lib/keyboard-layout/korean-input-source' import { normalizeSelectedTextForFileSearch } from '@/lib/file-search-selection' import { isFindQueryTooLarge } from '@/lib/find-query-bounds' import { handleEmptyFloatingWorkspacePanelCloseShortcut } from '@/lib/floating-workspace-terminal-actions' @@ -213,8 +209,6 @@ type KeyboardHandlersDeps = { paneCwdRef: React.RefObject /** Worktree-root cwd used when OSC 7 and pty.getCwd both fail. */ fallbackCwd: string - /** Gates the Korean input-source probe; its refresh spawns four processes. */ - koreanWonToBackquoteEnabled?: boolean expandedPaneIdRef: React.RefObject setExpandedPane: (paneId: number | null) => void restoreExpandedLayout: () => void @@ -250,7 +244,6 @@ export function useTerminalKeyboardShortcuts({ panePtyBindingsRef, paneCwdRef, fallbackCwd, - koreanWonToBackquoteEnabled, expandedPaneIdRef, setExpandedPane, restoreExpandedLayout, @@ -283,16 +276,6 @@ export function useTerminalKeyboardShortcuts({ // KeyboardLayoutMap; prefetch so the map is cached before the first chord. if (isMac) { prefetchLayoutBaseCharacters() - // Why: the Korean Won rewrite gate reads the active input source ID through the async IPC. - // Gated on the setting because each refresh shells out to `defaults export | plutil | plutil` - // and the default is off, so an ungated prefetch costs every macOS user four processes. - // Synced in the effect body, not its cleanup: cleanup also runs on tab switches and on any - // dep-identity change, so disposing there would reattach and re-probe constantly. - if (koreanWonToBackquoteEnabled) { - prefetchKoreanInputSource() - } else { - stopKoreanInputSourcePrefetch() - } } // Why: KeyboardEvent.location on a character key (e.g. Period) always @@ -986,7 +969,6 @@ export function useTerminalKeyboardShortcuts({ panePtyBindingsRef, paneCwdRef, fallbackCwd, - koreanWonToBackquoteEnabled, expandedPaneIdRef, setExpandedPane, restoreExpandedLayout, diff --git a/src/renderer/src/components/terminal-pane/terminal-korean-won-input.test.ts b/src/renderer/src/components/terminal-pane/terminal-korean-won-input.test.ts deleted file mode 100644 index 1beb8b9a0..000000000 --- a/src/renderer/src/components/terminal-pane/terminal-korean-won-input.test.ts +++ /dev/null @@ -1,99 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - resolveTerminalKoreanWonInput, - type TerminalKoreanWonInputEvent -} from './terminal-korean-won-input' - -function event(overrides: Partial): TerminalKoreanWonInputEvent { - return { - type: 'keydown', - key: '₩', - code: 'Backquote', - metaKey: false, - ctrlKey: false, - altKey: false, - shiftKey: false, - ...overrides - } -} - -describe('resolveTerminalKoreanWonInput', () => { - const enabledOnMacKorean = { enabled: true, isMac: true, isKoreanKeyboard: true } - - it('translates a plain backquote keystroke to backquote on a Korean keyboard', () => { - expect(resolveTerminalKoreanWonInput(event({}), enabledOnMacKorean)).toEqual({ - type: 'input', - data: '`' - }) - }) - - it('rewrites regardless of the character the Korean layout produces at that key', () => { - // Why: the rule keys on the keystroke position alone — 두벌식/세벌식 390 - // produce ₩, 세벌식 최종 produces *, and the English state produces `. - for (const key of ['₩', '*', '`', '~']) { - expect(resolveTerminalKoreanWonInput(event({ key }), enabledOnMacKorean)).toEqual({ - type: 'input', - data: '`' - }) - } - }) - - it('suppresses companion events after the translated keydown', () => { - expect(resolveTerminalKoreanWonInput(event({ type: 'keypress' }), enabledOnMacKorean)).toEqual({ - type: 'suppress' - }) - expect(resolveTerminalKoreanWonInput(event({ type: 'keyup' }), enabledOnMacKorean)).toEqual({ - type: 'suppress' - }) - }) - - it('leaves IME-processed keydowns (keyCode 229) to the IME', () => { - expect(resolveTerminalKoreanWonInput(event({ keyCode: 229 }), enabledOnMacKorean)).toBeNull() - expect( - resolveTerminalKoreanWonInput(event({ type: 'keyup', keyCode: 229 }), enabledOnMacKorean) - ).toBeNull() - }) - - it('does not rewrite other physical keys', () => { - for (const code of ['Backslash', 'KeyY', 'Digit1', 'IntlBackslash']) { - expect(resolveTerminalKoreanWonInput(event({ code }), enabledOnMacKorean)).toBeNull() - } - }) - - it('does not rewrite modified backquote chords', () => { - const modifiedCases = [ - event({ metaKey: true }), - event({ ctrlKey: true }), - event({ altKey: true }), - event({ shiftKey: true }) - ] - - for (const input of modifiedCases) { - expect(resolveTerminalKoreanWonInput(input, enabledOnMacKorean)).toBeNull() - } - }) - - it('is gated by the user setting, macOS, and a Korean keyboard', () => { - expect( - resolveTerminalKoreanWonInput(event({}), { - enabled: false, - isMac: true, - isKoreanKeyboard: true - }) - ).toBeNull() - expect( - resolveTerminalKoreanWonInput(event({}), { - enabled: true, - isMac: false, - isKoreanKeyboard: true - }) - ).toBeNull() - expect( - resolveTerminalKoreanWonInput(event({}), { - enabled: true, - isMac: true, - isKoreanKeyboard: false - }) - ).toBeNull() - }) -}) diff --git a/src/renderer/src/components/terminal-pane/terminal-korean-won-input.ts b/src/renderer/src/components/terminal-pane/terminal-korean-won-input.ts deleted file mode 100644 index de23ced12..000000000 --- a/src/renderer/src/components/terminal-pane/terminal-korean-won-input.ts +++ /dev/null @@ -1,79 +0,0 @@ -/** - * Keydown rewriting for the terminal "Korean Won (₩) to Backquote (`)" setting. - * - * While a Korean input source is active on macOS, the physical backquote key - * (code 'Backquote' — the English QWERTY backquote position) produces a - * character Korean layouts disagree about (₩ under 두벌식/세벌식 390, * under - * 세벌식 최종, ` in the English state). The rewrite keys on the keystroke - * position alone and sends backquote instead, so it needs no per-layout - * knowledge. The gate (setting + macOS + Korean input source) is evaluated by - * the caller before this resolver runs. - */ -export type TerminalKoreanWonInputEvent = { - type: string - key: string - code?: string - keyCode?: number - metaKey: boolean - ctrlKey: boolean - altKey: boolean - shiftKey: boolean -} - -/** Gate flags the caller resolves from live settings and the macOS input - * source tracker before consulting the resolver. */ -export type TerminalKoreanWonInputOptions = { - enabled: boolean - isMac: boolean - /** Whether the active macOS input source is a Korean keyboard (see korean-input-source.ts). */ - isKoreanKeyboard: boolean -} - -/** 'input' feeds the translated character to xterm; 'suppress' swallows the - * companion keypress/keyup so the layout's own character cannot leak through. */ -export type TerminalKoreanWonInputAction = { type: 'input'; data: string } | { type: 'suppress' } - -function isPlainBackquoteKeystroke(event: TerminalKoreanWonInputEvent): boolean { - // Why: the rewrite keys on the keystroke position (the English QWERTY - // backquote key, kVK_ANSI_Grave) alone — Korean layouts disagree about what - // that key produces (두벌식/세벌식 390: ₩, 세벌식 최종: *, English state: `), - // so no character check, no layout-variant knowledge. keyCode 229 means an - // IME owns the press; translating it would race the IME's commit. - return ( - event.keyCode !== 229 && - event.code === 'Backquote' && - !event.metaKey && - !event.ctrlKey && - !event.altKey && - !event.shiftKey - ) -} - -/** Resolves a terminal key event to a backquote input or a suppressed - * companion event, or null when the rewrite does not apply. */ -export function resolveTerminalKoreanWonInput( - event: TerminalKoreanWonInputEvent, - options: TerminalKoreanWonInputOptions -): TerminalKoreanWonInputAction | null { - if ( - !options.enabled || - !options.isMac || - !options.isKoreanKeyboard || - !isPlainBackquoteKeystroke(event) - ) { - return null - } - - if (event.type === 'keydown') { - return { type: 'input', data: '`' } - } - - if (event.type === 'keypress' || event.type === 'keyup') { - // Why: suppress companion events so the translated keydown cannot be - // followed by a browser text event or xterm key-release sequence for the - // layout's own character. - return { type: 'suppress' } - } - - return null -} diff --git a/src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.ts b/src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.ts index b56e025c8..bfc05a5b3 100644 --- a/src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.ts +++ b/src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.ts @@ -82,8 +82,6 @@ import { copyTerminalSelection } from './terminal-selection-copy' import { parseOsc7 } from './parse-osc7' import { guardParserHandler } from './terminal-parser-handler-guard' import { resolveTerminalJisYenInput } from './terminal-jis-yen-input' -import { resolveTerminalKoreanWonInput } from './terminal-korean-won-input' -import { isKoreanInputSourceActive } from '@/lib/keyboard-layout/korean-input-source' import { installTerminalImeCompositionTracker } from './terminal-ime-composition-tracker' import { installTerminalImeLinuxCandidateState } from './terminal-ime-linux-candidate-state' import { @@ -1021,21 +1019,6 @@ export function useTerminalPaneLifecycle({ return false } - // Why: the gate refreshes on focus AND keyboard activity (Caps Lock / - // 한영 switches change the input source while the window keeps focus). - const koreanWonInput = resolveTerminalKoreanWonInput(e, { - enabled: settingsRef.current?.terminalKoreanWonToBackquote === true, - isMac, - isKoreanKeyboard: isKoreanInputSourceActive() - }) - if (koreanWonInput) { - if (koreanWonInput.type === 'input') { - // Why: translated character, not a shortcut — keep it on xterm's onData path so PTY input guards still run. - pane.terminal.input(koreanWonInput.data) - } - return false - } - if (e.type === 'keydown') { const shouldSyncCurrentTerminal = (): boolean => managerRef.current diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 99e6c068c..452150dc2 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -7589,10 +7589,7 @@ "fastDescription": "Extra multiplier while scrolling with a modifier key.", "tui": "TUI", "tuiDescription": "Discrete wheel reports for full-screen terminal apps." - }, - "fc01559dad": "Korean Won (₩) to Backquote (`)", - "f1f43e38f3": "Controls whether pressing the Korean Won (₩) key sends a backquote (`) instead when a Korean input source is active.", - "7f535117e5": "Pressing the Korean Won (₩) key sends a backquote (`) instead when a Korean input source is active." + } }, "TerminalSettingsPreview": { "a63953a48a": "Preview {{value0}} theme", @@ -9217,13 +9214,6 @@ "9c35f56625": "yen", "063914c486": "Controls whether pressing the JIS Yen (¥) key sends a backslash (\\) instead.", "694b8764ac": "JIS Yen (¥) to Backslash (\\)", - "5ba707eec2": "won", - "d243131b1a": "backquote", - "2a22983b81": "backtick", - "8f64dd7dc4": "korean", - "84ae68de79": "hangul", - "91cae143ad": "korea", - "b26f68a00c": "markdown", "fae142a354": "readline", "b3b94cfcb5": "international", "dd4f6cb541": "german", @@ -9326,9 +9316,7 @@ "title": "Theme Mode", "keyword_target": "target", "keyword_editing": "editing" - }, - "d6756003bf": "Korean Won (₩) to Backquote (`)", - "3595f8b54c": "Controls whether pressing the Korean Won (₩) key sends a backquote (`) instead when a Korean input source is active." + } }, "windows": { "search": { diff --git a/src/renderer/src/lib/keyboard-layout/korean-input-source.test.ts b/src/renderer/src/lib/keyboard-layout/korean-input-source.test.ts deleted file mode 100644 index ff8244b65..000000000 --- a/src/renderer/src/lib/keyboard-layout/korean-input-source.test.ts +++ /dev/null @@ -1,296 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { - _resetKoreanInputSourceForTests, - _setKoreanInputSourceForTests, - isKoreanInputSourceActive, - isKoreanInputSourceId, - prefetchKoreanInputSource -} from './korean-input-source' - -type MockWindow = { - addEventListener: (type: string, fn: EventListener, capture?: boolean) => void - removeEventListener: (type: string, fn: EventListener, capture?: boolean) => void - fireFocus: () => void - fireKey: (code: string) => void -} - -function makeMockWindow(): MockWindow { - const focusListeners = new Set() - const keyListeners = new Set() - return { - addEventListener: (type, fn) => { - if (type === 'focus') { - focusListeners.add(fn) - } else if (type === 'keydown' || type === 'keyup') { - keyListeners.add(fn) - } - }, - removeEventListener: (type, fn) => { - if (type === 'focus') { - focusListeners.delete(fn) - } else if (type === 'keydown' || type === 'keyup') { - keyListeners.delete(fn) - } - }, - fireFocus: () => { - for (const listener of focusListeners) { - listener(new Event('focus')) - } - }, - fireKey: (code: string) => { - // Why: the listener reads only event.code; a plain object avoids the - // node test environment's missing KeyboardEvent global. - const event = { code } as KeyboardEvent - for (const listener of keyListeners) { - listener(event) - } - } - } -} - -function deferred(): { - promise: Promise - resolve: (id: string | null) => void -} { - let resolve!: (id: string | null) => void - const promise = new Promise((res) => { - resolve = res - }) - return { promise, resolve } -} - -describe('isKoreanInputSourceId', () => { - it('recognizes every supported Korean input source ID', () => { - const koreanIds = [ - // Input method modes, reported by the selected-source branch. - 'com.apple.inputmethod.Korean.2SetKorean', - 'com.apple.inputmethod.Korean.390Sebulshik', - 'com.apple.inputmethod.Korean.3SetKorean', - 'com.apple.inputmethod.Korean.HNCRomaja', - 'com.apple.inputmethod.Korean.GJCRomaja', - // The IM bundle itself. - 'com.apple.inputmethod.Korean', - // Keyboard layouts, reported by the fallback branch. - 'com.apple.keylayout.2SetHangul', - 'com.apple.keylayout.390Hangul', - 'com.apple.keylayout.3SetHangul', - 'com.apple.keylayout.HNCRomaja', - 'com.apple.keylayout.GJCRomaja' - ] - - for (const id of koreanIds) { - expect(isKoreanInputSourceId(id), id).toBe(true) - } - }) - - it('rejects non-Korean input sources', () => { - for (const id of [ - 'com.apple.keylayout.US', - 'com.apple.keylayout.German', - 'com.apple.inputmethod.ABC', - 'com.apple.inputmethod.SCIM.ITABC' - ]) { - expect(isKoreanInputSourceId(id), id).toBe(false) - } - }) - - it('rejects null and undefined', () => { - expect(isKoreanInputSourceId(null)).toBe(false) - expect(isKoreanInputSourceId(undefined)).toBe(false) - }) -}) - -describe('prefetchKoreanInputSource', () => { - beforeEach(() => { - _resetKoreanInputSourceForTests() - }) - - afterEach(() => { - _resetKoreanInputSourceForTests() - vi.restoreAllMocks() - }) - - it('classifies the active input source after the first probe', async () => { - const reader = vi.fn(async () => 'com.apple.inputmethod.Korean.2SetKorean') - prefetchKoreanInputSource({ win: makeMockWindow(), readInputSourceId: reader }) - - await vi.waitFor(() => expect(isKoreanInputSourceActive()).toBe(true)) - expect(reader).toHaveBeenCalledTimes(1) - }) - - it('stays false when the probe reports a non-Korean input source', async () => { - const reader = vi.fn(async () => 'com.apple.keylayout.US') - prefetchKoreanInputSource({ win: makeMockWindow(), readInputSourceId: reader }) - - await vi.waitFor(() => expect(reader).toHaveBeenCalledTimes(1)) - expect(isKoreanInputSourceActive()).toBe(false) - }) - - it('stays false when the probe reports no input source', async () => { - const reader = vi.fn(async () => null) - prefetchKoreanInputSource({ win: makeMockWindow(), readInputSourceId: reader }) - - await vi.waitFor(() => expect(reader).toHaveBeenCalledTimes(1)) - expect(isKoreanInputSourceActive()).toBe(false) - }) - - it('keeps the last known classification when the reader rejects', async () => { - _setKoreanInputSourceForTests(true) - const reader = vi.fn(async () => { - throw new Error('IPC down') - }) - prefetchKoreanInputSource({ win: makeMockWindow(), readInputSourceId: reader }) - - await vi.waitFor(() => expect(reader).toHaveBeenCalledTimes(1)) - expect(isKoreanInputSourceActive()).toBe(true) - }) - - it('commits only the latest refresh when probes overlap', async () => { - const initialProbe = deferred() - const focusProbe = deferred() - const reader = vi.fn(() => - reader.mock.calls.length === 1 ? initialProbe.promise : focusProbe.promise - ) - const win = makeMockWindow() - prefetchKoreanInputSource({ win, readInputSourceId: reader }) - - win.fireFocus() - await vi.waitFor(() => expect(reader).toHaveBeenCalledTimes(2)) - - // The focus-in probe (current layout) resolves first and commits. - focusProbe.resolve('com.apple.keylayout.US') - await vi.waitFor(() => expect(isKoreanInputSourceActive()).toBe(false)) - - // The stale initial probe resolves last; it must not overwrite the cache. - initialProbe.resolve('com.apple.inputmethod.Korean.2SetKorean') - await Promise.resolve() - expect(isKoreanInputSourceActive()).toBe(false) - }) - - it('refreshes on window focus-in after a layout switch', async () => { - let activeId: string | null = 'com.apple.keylayout.US' - const reader = vi.fn(async () => activeId) - const win = makeMockWindow() - prefetchKoreanInputSource({ win, readInputSourceId: reader }) - - await vi.waitFor(() => expect(reader).toHaveBeenCalledTimes(1)) - expect(isKoreanInputSourceActive()).toBe(false) - - activeId = 'com.apple.inputmethod.Korean.390Sebulshik' - win.fireFocus() - await vi.waitFor(() => expect(reader).toHaveBeenCalledTimes(2)) - expect(isKoreanInputSourceActive()).toBe(true) - }) - - it('refreshes immediately on an input-toggle key even without focus changes', async () => { - let activeId: string | null = 'com.apple.keylayout.US' - const reader = vi.fn(async () => activeId) - const win = makeMockWindow() - prefetchKoreanInputSource({ win, readInputSourceId: reader }) - await vi.waitFor(() => expect(reader).toHaveBeenCalledTimes(1)) - expect(isKoreanInputSourceActive()).toBe(false) - - // Caps Lock switches the input source in place — no blur/refocus. - activeId = 'com.apple.inputmethod.Korean.2SetKorean' - win.fireKey('CapsLock') - await vi.waitFor(() => expect(isKoreanInputSourceActive()).toBe(true)) - }) - - it('refreshes on ordinary keys but throttled by the cooldown', async () => { - vi.useFakeTimers() - try { - let activeId: string | null = 'com.apple.keylayout.US' - const reader = vi.fn(async () => activeId) - const win = makeMockWindow() - prefetchKoreanInputSource({ win, readInputSourceId: reader }) - await vi.waitFor(() => expect(reader).toHaveBeenCalledTimes(1)) - expect(isKoreanInputSourceActive()).toBe(false) - - activeId = 'com.apple.inputmethod.Korean.2SetKorean' - // Within the cooldown: ordinary keys are throttled. - win.fireKey('KeyA') - win.fireKey('KeyB') - await Promise.resolve() - expect(reader).toHaveBeenCalledTimes(1) - - // Past the cooldown: an ordinary key refreshes the gate. - vi.advanceTimersByTime(3000) - win.fireKey('KeyC') - await vi.waitFor(() => expect(reader).toHaveBeenCalledTimes(2)) - expect(isKoreanInputSourceActive()).toBe(true) - } finally { - vi.useRealTimers() - } - }) - - it('is idempotent across calls', async () => { - const reader = vi.fn(async () => 'com.apple.keylayout.2SetHangul') - const win = makeMockWindow() - prefetchKoreanInputSource({ win, readInputSourceId: reader }) - prefetchKoreanInputSource({ win, readInputSourceId: reader }) - - await vi.waitFor(() => expect(reader).toHaveBeenCalledTimes(1)) - expect(isKoreanInputSourceActive()).toBe(true) - }) - - it('reset detaches listeners and invalidates in-flight probes', async () => { - const probe = deferred() - const reader = vi.fn(() => probe.promise) - const win = makeMockWindow() - prefetchKoreanInputSource({ win, readInputSourceId: reader }) - await vi.waitFor(() => expect(reader).toHaveBeenCalledTimes(1)) - - _resetKoreanInputSourceForTests() - win.fireFocus() - win.fireKey('CapsLock') - await vi.waitFor(() => expect(reader).toHaveBeenCalledTimes(1)) - expect(isKoreanInputSourceActive()).toBe(false) - - // A probe still in flight from before the reset must not repopulate the cache. - probe.resolve('com.apple.inputmethod.Korean.2SetKorean') - await Promise.resolve() - expect(isKoreanInputSourceActive()).toBe(false) - - // After reset, prefetch works again on the same window. - prefetchKoreanInputSource({ win, readInputSourceId: reader }) - await vi.waitFor(() => expect(reader).toHaveBeenCalledTimes(2)) - }) -}) - -describe('cold-start probe', () => { - beforeEach(() => { - _resetKoreanInputSourceForTests() - }) - - it('does not cache a null read as a confirmed non-Korean source', async () => { - // Why: on m4air a fresh session sent ₩ for the first presses — the startup - // read returned null (IPC not exposed yet) and was cached as "not Korean". - const win = makeMockWindow() - let call = 0 - const reader = async (): Promise => { - call += 1 - return call === 1 ? null : 'com.apple.inputmethod.Korean.2SetKorean' - } - - prefetchKoreanInputSource({ win, readInputSourceId: reader }) - await vi.waitFor(() => expect(isKoreanInputSourceActive()).toBe(true)) - expect(call).toBeGreaterThan(1) - }) - - it('gives up after a bounded number of probes when the reader never reports', async () => { - const win = makeMockWindow() - let call = 0 - const reader = async (): Promise => { - call += 1 - return null - } - - prefetchKoreanInputSource({ win, readInputSourceId: reader }) - await vi.waitFor(() => expect(call).toBeGreaterThanOrEqual(4), { timeout: 5000 }) - await new Promise((resolve) => setTimeout(resolve, 300)) - // Each probe spawns four processes; an unbounded retry would be worse than - // the cold gate it fixes. - expect(call).toBeLessThanOrEqual(4) - expect(isKoreanInputSourceActive()).toBe(false) - }) -}) diff --git a/src/renderer/src/lib/keyboard-layout/korean-input-source.ts b/src/renderer/src/lib/keyboard-layout/korean-input-source.ts deleted file mode 100644 index 68b7fe88f..000000000 --- a/src/renderer/src/lib/keyboard-layout/korean-input-source.ts +++ /dev/null @@ -1,228 +0,0 @@ -/** - * Gate for the terminal Korean Won (₩) → backquote rewrite. - * - * The rewrite fires when a Korean keyboard input source is active on macOS: - * the physical backquote key (kVK_ANSI_Grave, code 'Backquote' — the English - * QWERTY backquote position) is rewritten to backquote regardless of the - * character the layout produces there. That one position-based rule covers - * every Korean layout variant without enumerating them: 두벌식 and 세벌식 390 - * put ₩ there, 세벌식 최종 puts `*`/※, and the English state puts `` ` ``/`~` — - * none of that matters, the keystroke position alone decides. - * - * Why gate on the input source ID at all: the same physical key produces - * `` ` ``/`~` under the US layout, where the rewrite must not fire. The - * main-process IPC returns the currently *selected* input source - * (AppleSelectedInputSources → Input Mode, falling back to - * AppleCurrentKeyboardLayoutInputSourceID), which resolves to a Korean ID - * only when a Korean input source is active. - * - * Refresh strategy — the gate must track in-place input-source switches: - * Caps Lock / 한영 keys change the input source while the window keeps focus - * (no blur/refocus, so focus events alone go stale). Prefetch once at - * terminal keyboard setup, refresh on window focus-in, AND refresh from - * keyboard activity: input-toggle keys (CapsLock/Lang1/Lang2) refresh - * immediately, other keys at most once per cooldown. - */ -type InputSourceIdReader = () => Promise - -/** Any Korean input method mode: 두벌식 (2SetKorean), 세벌식 390 - * (390Sebulshik), 세벌식 최종 (3SetKorean), Romaja (HNCRomaja/GJCRomaja), - * or the IM bundle itself. */ -const KOREAN_INPUT_METHOD_ID_PREFIX = 'com.apple.inputmethod.korean' - -/** The shipped Korean keyboard layouts, reported by the fallback branch when - * no input method mode is selected. Case-insensitive full-ID match, - * deliberately not prefix-matched. */ -const KOREAN_KEYLAYOUT_IDS: ReadonlySet = new Set([ - 'com.apple.keylayout.2sethangul', - 'com.apple.keylayout.390hangul', - 'com.apple.keylayout.3sethangul', - 'com.apple.keylayout.hncromaja', - 'com.apple.keylayout.gjcromaja' -]) - -/** Physical keys that switch the macOS input source in place (Caps Lock toggling - * to/from ABC, 한/영 and 한자 on Korean keyboards). */ -const INPUT_TOGGLE_KEY_CODES: ReadonlySet = new Set(['CapsLock', 'Lang1', 'Lang2']) - -const KEYBOARD_ACTIVITY_REFRESH_COOLDOWN_MS = 2000 - -/** Bounded so a host that never reports an input source costs four probes, not - * one per keystroke — each probe spawns `defaults export | plutil | plutil`. */ -const INITIAL_PROBE_BACKOFF_MS: readonly number[] = [50, 200, 750] - -export function isKoreanInputSourceId(id: string | null | undefined): boolean { - if (!id) { - return false - } - const normalized = id.toLowerCase() - return ( - normalized.startsWith(KOREAN_INPUT_METHOD_ID_PREFIX) || KOREAN_KEYLAYOUT_IDS.has(normalized) - ) -} - -let cachedIsKorean: boolean | null = null -let refreshGeneration = 0 -let lastRefreshAt = 0 -let listenerAttached = false -let prefetchEpoch = 0 -let focusTarget: Pick | null = null -let focusCallback: (() => void) | null = null -let keyboardActivityCallback: ((event: KeyboardEvent) => void) | null = null - -function defaultInputSourceIdReader(): InputSourceIdReader { - return async () => { - const api = ( - globalThis as { - window?: { api?: { app?: { getKeyboardInputSourceId?: () => Promise } } } - } - ).window?.api - const reader = api?.app?.getKeyboardInputSourceId - if (!reader) { - return null - } - try { - return await reader() - } catch { - // Why: the IPC can transiently reject during main-process teardown; treat - // as no signal so the rewrite stays off instead of guessing. - return null - } - } -} - -async function refreshInputSourceId(readInputSourceId: InputSourceIdReader): Promise { - const generation = ++refreshGeneration - let id: string | null = null - try { - id = await readInputSourceId() - } catch { - // Why: keep the last known classification on reader failure rather than - // dropping layout awareness mid-session. - return - } - if (generation !== refreshGeneration) { - // Why: a newer refresh superseded this one; committing stale state would - // misclassify the active input source until the next refresh. - return - } - if (id === null) { - // Why: the reader returns null for "no signal" (IPC not yet exposed at - // startup, transient rejection) as well as for a genuinely absent source. - // Caching that as false turns an unknown into a confirmed negative, which - // is what left the gate cold for the first keystrokes of a session. - return - } - cachedIsKorean = isKoreanInputSourceId(id) -} - -function requestRefresh(readInputSourceId: InputSourceIdReader, force: boolean): void { - const now = Date.now() - if (!force && now - lastRefreshAt < KEYBOARD_ACTIVITY_REFRESH_COOLDOWN_MS) { - return - } - lastRefreshAt = now - void refreshInputSourceId(readInputSourceId) -} - -type PrefetchKoreanInputSourceOptions = { - /** Test-only: window to observe on. Defaults to the global window. */ - win?: Pick - /** Test-only: injectable input source ID reader. Defaults to the preload IPC. */ - readInputSourceId?: InputSourceIdReader -} - -/** Idempotent. Kicks off the initial probe and keeps the cache fresh across - * layout switches — on focus-in and on keyboard activity (input-toggle keys - * immediately, other keys at most once per cooldown). Call from terminal - * keyboard setup so the classification is cached before the user types; - * until the probe resolves the gate stays false (strict-until-probe). */ -export function prefetchKoreanInputSource(options: PrefetchKoreanInputSourceOptions = {}): void { - if (listenerAttached) { - return - } - const target = options.win ?? (typeof window === 'undefined' ? null : window) - if (!target) { - return - } - listenerAttached = true - focusTarget = target - const readInputSourceId = options.readInputSourceId ?? defaultInputSourceIdReader() - focusCallback = () => { - requestRefresh(readInputSourceId, true) - } - keyboardActivityCallback = (event: KeyboardEvent) => { - requestRefresh(readInputSourceId, INPUT_TOGGLE_KEY_CODES.has(event.code ?? '')) - } - target.addEventListener('focus', focusCallback) - // Why: capture phase so keys pressed inside the terminal still count, and - // both keydown and keyup so a held toggle key still refreshes on release. - target.addEventListener('keydown', keyboardActivityCallback, true) - target.addEventListener('keyup', keyboardActivityCallback, true) - void runInitialProbe(readInputSourceId, ++prefetchEpoch) -} - -/** Why: a keystroke-triggered refresh is async, so it can never classify the - * press that triggered it — the cache has to be warm BEFORE the first key. At - * startup the IPC is not always exposed yet, so retry with backoff until the - * reader yields an ID rather than leaving the gate cold for the session. */ -async function runInitialProbe( - readInputSourceId: InputSourceIdReader, - epoch: number -): Promise { - for (const delayMs of INITIAL_PROBE_BACKOFF_MS) { - // Why: an epoch, not window identity — production always passes the same - // window, so an identity check is dead there and a stop/start would let a - // sleeping loop wake and race the new one. - if (!listenerAttached || epoch !== prefetchEpoch) { - return - } - lastRefreshAt = Date.now() - await refreshInputSourceId(readInputSourceId) - if (cachedIsKorean !== null) { - return - } - await new Promise((resolve) => setTimeout(resolve, delayMs)) - } - if (!listenerAttached || epoch !== prefetchEpoch) { - return - } - lastRefreshAt = Date.now() - await refreshInputSourceId(readInputSourceId) -} - -/** Strict gate: only true when the active macOS input source is known to be a - * Korean input source. Unknown (probe pending, IPC failure, non-Darwin) stays - * false so the rewrite never guesses. */ -export function isKoreanInputSourceActive(): boolean { - return cachedIsKorean === true -} - -/** Test-only: seed or clear the cached classification. */ -export function _setKoreanInputSourceForTests(value: boolean | null): void { - cachedIsKorean = value -} - -/** Test-only: reset cache, detach listeners, and invalidate any in-flight - * refreshes so a stale probe cannot repopulate the cache. */ -/** Detaches the probe. Without this the global listeners outlive the setting - * being switched off and keep spawning the refresh. */ -export function stopKoreanInputSourcePrefetch(): void { - refreshGeneration += 1 - prefetchEpoch += 1 - if (focusTarget && focusCallback && keyboardActivityCallback) { - focusTarget.removeEventListener('focus', focusCallback) - focusTarget.removeEventListener('keydown', keyboardActivityCallback, true) - focusTarget.removeEventListener('keyup', keyboardActivityCallback, true) - } - focusTarget = null - focusCallback = null - keyboardActivityCallback = null - listenerAttached = false - cachedIsKorean = null - lastRefreshAt = 0 -} - -export function _resetKoreanInputSourceForTests(): void { - stopKoreanInputSourcePrefetch() -} diff --git a/src/shared/constants.ts b/src/shared/constants.ts index 5f6f22b86..02f694bbb 100644 --- a/src/shared/constants.ts +++ b/src/shared/constants.ts @@ -346,7 +346,6 @@ export function getDefaultSettings(homedir: string): GlobalSettings { terminalMacOptionAsAlt: 'auto', terminalMacOptionAsAltMigrated: false, terminalJISYenToBackslash: false, - terminalKoreanWonToBackquote: false, experimentalMobile: false, mobileEmulatorEnabled: true, mobileEmulatorDefaultDeviceUdid: null, diff --git a/src/shared/types.ts b/src/shared/types.ts index 092d18e1f..a9da2dc9b 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -3051,8 +3051,6 @@ export type GlobalSettings = { terminalMacOptionAsAltMigrated: boolean /** Whether macOS terminal input maps the physical JIS Yen (¥) key to backslash, per common terminal expectation. */ terminalJISYenToBackslash: boolean - /** Whether terminal input maps the physical Korean Won (₩) key to backquote, so markdown code fences and shell backquotes type directly. */ - terminalKoreanWonToBackquote: boolean experimentalMobile: boolean /** Why: iOS Simulator is default-on for capable macOS hosts; this is the durable off switch (hides UI, blocks CLI attach). */ mobileEmulatorEnabled?: boolean