Back to a single macOS input source; show 中/A by the cursor instead

The two input modes (中英自動 / 英文) made English mode a separate input source,
and switching between them still brought up System Settings. Info.plist has one
input source again, the Shift tap no longer calls Text Input Sources, and English
mode is shown by a short 中 / A badge under the cursor. The input menu gets an
英文模式 item. Windows and Linux keep their icon switch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 08:39:24 +08:00
co-authored by Claude Opus 5.5
parent cfd095b3b0
commit fbdf64f64e
10 changed files with 80 additions and 127 deletions
+10 -14
View File
@@ -78,8 +78,8 @@ final class InputController: IMKInputController {
let idle = engine.keys.isEmpty
_ = engine.handle(.shiftTap)
updateComposition(client)
// English mode on/off: switch input mode so the menu-bar icon shows it.
if idle { InputModes.select(english: engine.isEnglishMode) }
// English mode on/off: show 中 / A by the cursor.
if idle { ModeIndicator.show(english: engine.isEnglishMode, client: client) }
}
return false
}
@@ -156,18 +156,6 @@ final class InputController: IMKInputController {
}
}
/// The input mode changed (menu bar, keyboard shortcut, or our own Shift tap).
override func setValue(_ value: Any!, forTag tag: Int, client sender: Any!) {
if tag == kTextServiceInputModePropertyTag, let id = value as? String {
let english = InputModes.isEnglish(id)
if english != engine.isEnglishMode {
commitComposition(sender)
engine.setEnglishMode(english)
}
}
super.setValue(value, forTag: tag, client: sender)
}
override func commitComposition(_ sender: Any!) {
guard let client = sender as? IMKTextInput else { return }
commit(engine.commitAll(), to: client)
@@ -202,6 +190,9 @@ final class InputController: IMKInputController {
override func menu() -> NSMenu! {
let menu = NSMenu()
let english = menu.addItem(withTitle: "英文模式(單按 Shift)", action: #selector(toggleEnglish(_:)), keyEquivalent: "")
english.state = engine.isEnglishMode ? .on : .off
menu.addItem(.separator())
let modes: [(Reranker.Mode, String, Selector)] = [
(.off, "AI 選字:關閉", #selector(aiOff(_:))),
(.saver, "AI 選字:省電", #selector(aiSaver(_:))),
@@ -221,6 +212,11 @@ final class InputController: IMKInputController {
return menu
}
@objc private func toggleEnglish(_ sender: Any?) {
if let client = client() { commitComposition(client) }
engine.setEnglishMode(!engine.isEnglishMode)
}
@objc private func aiOff(_ sender: Any?) { AI.setMode(.off) }
@objc private func aiSaver(_ sender: Any?) { AI.setMode(.saver) }
@objc private func aiStandard(_ sender: Any?) { AI.setMode(.standard) }
-39
View File
@@ -1,39 +0,0 @@
import Carbon
import Foundation
/// The two input modes declared in Info.plist (ComponentInputModeDict). Each has its own
/// menu-bar icon, so switching modes is how the icon shows "中英自動" vs "英文".
enum InputModes {
static let auto = "com.autozhuyin.inputmethod.AutoZhuyin.Auto"
static let english = "com.autozhuyin.inputmethod.AutoZhuyin.English"
static func isEnglish(_ modeID: String) -> Bool { modeID == english }
private static func source(_ id: String) -> TISInputSource? {
let filter = [kTISPropertyInputSourceID as String: id] as CFDictionary
guard let list = TISCreateInputSourceList(filter, true)?.takeRetainedValue() as? [TISInputSource] else { return nil }
return list.first
}
private static func isEnabled(_ src: TISInputSource) -> Bool {
guard let p = TISGetInputSourceProperty(src, kTISPropertyInputSourceIsEnabled) else { return false }
return CFBooleanGetValue(Unmanaged<CFBoolean>.fromOpaque(p).takeUnretainedValue())
}
/// Makes the given mode current. Returns false on failure.
/// Only enables the mode if it is not enabled yet: TISEnableInputSource opens System
/// Settings → Keyboard, even for a source that is already enabled.
@discardableResult
static func select(english: Bool) -> Bool {
guard let src = source(english ? InputModes.english : InputModes.auto) else { return false }
if !isEnabled(src) { TISEnableInputSource(src) }
return TISSelectInputSource(src) == noErr
}
/// Called by `--register`: enable both modes (if not yet) so they are in the input menu.
static func enableAll() {
for id in [auto, english] {
if let src = source(id), !isEnabled(src) { TISEnableInputSource(src) }
}
}
}
+67
View File
@@ -0,0 +1,67 @@
import Cocoa
import InputMethodKit
/// A small "中" / "A" badge shown under the text cursor for a moment when English mode is
/// switched on or off (the menu-bar icon of an input method can't change on its own).
enum ModeIndicator {
private static var panel: NSPanel?
private static var label: NSTextField?
private static var hideWork: DispatchWorkItem?
static func show(english: Bool, client: IMKTextInput) {
let (panel, label) = makePanel()
label.stringValue = english ? "A" : "中"
var lineRect = NSRect.zero
_ = client.attributes(forCharacterIndex: 0, lineHeightRectangle: &lineRect)
let size = panel.frame.size
var origin = NSPoint(x: lineRect.minX, y: lineRect.minY - size.height - 4)
if lineRect == .zero, let screen = NSScreen.main { // the app gave no caret position
origin = NSPoint(x: screen.visibleFrame.midX - size.width / 2, y: screen.visibleFrame.midY)
}
panel.setFrameOrigin(origin)
panel.alphaValue = 1
panel.orderFrontRegardless()
hideWork?.cancel()
let work = DispatchWorkItem {
NSAnimationContext.runAnimationGroup({ ctx in
ctx.duration = 0.25
panel.animator().alphaValue = 0
}, completionHandler: { panel.orderOut(nil) })
}
hideWork = work
DispatchQueue.main.asyncAfter(deadline: .now() + 0.8, execute: work)
}
private static func makePanel() -> (NSPanel, NSTextField) {
if let panel, let label { return (panel, label) }
let side: CGFloat = 28
let p = NSPanel(contentRect: NSRect(x: 0, y: 0, width: side, height: side),
styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: true)
p.level = .popUpMenu
p.isOpaque = false
p.backgroundColor = .clear
p.hasShadow = true
p.ignoresMouseEvents = true
p.collectionBehavior = [.canJoinAllSpaces, .transient, .ignoresCycle]
let background = NSVisualEffectView(frame: p.contentView!.bounds)
background.material = .hudWindow
background.state = .active
background.wantsLayer = true
background.layer?.cornerRadius = 6
background.layer?.masksToBounds = true
background.autoresizingMask = [.width, .height]
let l = NSTextField(labelWithString: "")
l.font = .systemFont(ofSize: 15, weight: .semibold)
l.alignment = .center
l.frame = NSRect(x: 0, y: (side - 20) / 2, width: side, height: 20)
background.addSubview(l)
p.contentView = background
panel = p
label = l
return (p, l)
}
}
-1
View File
@@ -6,7 +6,6 @@ import InputMethodKit
// in System Settings without logging out (used by the installer's postinstall script).
if CommandLine.arguments.contains("--register") {
let status = TISRegisterInputSource(Bundle.main.bundleURL as CFURL)
if status == noErr { InputModes.enableAll() } // "中英自動" and "英文" (menu-bar icons)
print(status == noErr ? "Registered \(Bundle.main.bundlePath)" : "TISRegisterInputSource failed: \(status)")
exit(status == noErr ? 0 : 1)
}