Skip to content

Instantly share code, notes, and snippets.

@shiena
Created August 17, 2024 21:05
Show Gist options
  • Save shiena/ef74c4d1b068d4c9e6c040619a3de05c to your computer and use it in GitHub Desktop.
Save shiena/ef74c4d1b068d4c9e6c040619a3de05c to your computer and use it in GitHub Desktop.
print active ime on macOS
import Foundation
import Carbon
import AppKit
func checkInputMonitoringPermission() -> Bool {
let options: NSDictionary = [kAXTrustedCheckOptionPrompt.takeRetainedValue() as NSString: true]
let isTrusted = AXIsProcessTrustedWithOptions(options)
return isTrusted
}
func openSystemPreferencesForInputMonitoring() {
let url = URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_ListenEvent")!
NSWorkspace.shared.open(url)
}
func getActiveIMEName() -> String? {
// 現在のキーボード入力ソースを取得
guard let inputSource = TISCopyCurrentKeyboardInputSource()?.takeRetainedValue() else {
return nil
}
// 入力ソースの名前を取得
guard let name = TISGetInputSourceProperty(inputSource, kTISPropertyLocalizedName) else {
return nil
}
// 名前を文字列に変換
let imeName = Unmanaged<CFString>.fromOpaque(name).takeUnretainedValue() as String
guard let bundleIDRef = TISGetInputSourceProperty(inputSource, kTISPropertyBundleID) else {
return imeName
}
let bundleID = Unmanaged<CFString>.fromOpaque(bundleIDRef).takeUnretainedValue() as String
// バンドルIDからバンドル名(アプリケーション名)を取得
if let bundleURL = NSWorkspace.shared.urlForApplication(withBundleIdentifier: bundleID),
let bundle = Bundle(url: bundleURL),
let bundleName = bundle.object(forInfoDictionaryKey: "CFBundleName") as? String {
return "\(imeName) (\(bundleName))"
}
return imeName
}
// メイン処理
// if checkInputMonitoringPermission() {
if let activeIME = getActiveIMEName() {
print("\(activeIME)")
exit(0)
} else {
exit(1)
}
// } else {
// print("アプリに入力監視権限がありません。システム環境設定を開いて権限を付与してください。")
// openSystemPreferencesForInputMonitoring()
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment