release: iriz 0.2.0 - диктовка на своем Маке
This commit is contained in:
@@ -0,0 +1,141 @@
|
||||
// Основано на RuSwitcher (MIT, © 2025 Rashns), коммит 8c45253.
|
||||
import Carbon
|
||||
import Foundation
|
||||
|
||||
/// Управление раскладками через TIS API
|
||||
public enum LayoutSwitcher {
|
||||
/// Возвращает ID текущей раскладки
|
||||
public static func currentLayoutID() -> String {
|
||||
guard let source = TISCopyCurrentKeyboardInputSource()?.takeRetainedValue() else {
|
||||
return ""
|
||||
}
|
||||
return sourceID(source)
|
||||
}
|
||||
|
||||
/// Код языка ТЕКУЩЕЙ раскладки (BCP-47, например "ru"/"en"). nil если недоступен.
|
||||
/// Надёжнее парсинга ID: тот же признак, что использует сама ОС.
|
||||
public static func currentLanguageCode() -> String? {
|
||||
guard let source = TISCopyCurrentKeyboardInputSource()?.takeRetainedValue() else {
|
||||
return nil
|
||||
}
|
||||
return languageCode(source)
|
||||
}
|
||||
|
||||
/// Переключает на противоположную раскладку (из настроенной пары)
|
||||
public static func switchToOpposite() {
|
||||
let current = currentLayoutID()
|
||||
let settings = SettingsManager.shared
|
||||
let sources = installedLayouts()
|
||||
|
||||
let id1 = settings.layout1ID.isEmpty ? autoDetectID1(from: sources) : settings.layout1ID
|
||||
let id2 = settings.layout2ID.isEmpty ? autoDetectID2(from: sources) : settings.layout2ID
|
||||
|
||||
let targetID = (current == id1) ? id2 : id1
|
||||
|
||||
if let target = sources.first(where: { sourceID($0) == targetID }) {
|
||||
select(target)
|
||||
}
|
||||
}
|
||||
|
||||
/// Переключает на конкретную раскладку по точному ID
|
||||
public static func switchTo(layoutID: String) {
|
||||
let sources = installedLayouts()
|
||||
if let target = sources.first(where: { sourceID($0) == layoutID }) {
|
||||
select(target)
|
||||
}
|
||||
}
|
||||
|
||||
/// issue #19: выбирает источник, вызывая TISEnableInputSource ТОЛЬКО если он
|
||||
/// реально выключен. На сторонних раскладках (напр. «Ilya Birman Typography»)
|
||||
/// enable уже включённого источника даёт системный запрос безопасности на КАЖДОЕ
|
||||
/// переключение. Наш `installedLayouts()` через TISCreateInputSourceList(_, false)
|
||||
/// и так отдаёт только включённые источники, так что обычно enable не нужен вовсе.
|
||||
private static func select(_ source: TISInputSource) {
|
||||
if let ptr = TISGetInputSourceProperty(source, kTISPropertyInputSourceIsEnabled),
|
||||
Unmanaged<CFBoolean>.fromOpaque(ptr).takeUnretainedValue() != kCFBooleanTrue {
|
||||
TISEnableInputSource(source)
|
||||
}
|
||||
TISSelectInputSource(source)
|
||||
}
|
||||
|
||||
/// Все установленные раскладки
|
||||
public static func installedLayouts() -> [TISInputSource] {
|
||||
let conditions: CFDictionary = [
|
||||
kTISPropertyInputSourceCategory as String: kTISCategoryKeyboardInputSource as Any,
|
||||
kTISPropertyInputSourceIsSelectCapable as String: true as Any,
|
||||
] as CFDictionary
|
||||
|
||||
guard let list = TISCreateInputSourceList(conditions, false)?.takeRetainedValue() as? [TISInputSource] else {
|
||||
return []
|
||||
}
|
||||
return list
|
||||
}
|
||||
|
||||
/// ID раскладки (например "com.apple.keylayout.Russian")
|
||||
public static func sourceID(_ source: TISInputSource) -> String {
|
||||
guard let ptr = TISGetInputSourceProperty(source, kTISPropertyInputSourceID) else {
|
||||
return ""
|
||||
}
|
||||
return Unmanaged<CFString>.fromOpaque(ptr).takeUnretainedValue() as String
|
||||
}
|
||||
|
||||
/// Локализованное имя раскладки (например "Русская")
|
||||
public static func sourceName(_ source: TISInputSource) -> String {
|
||||
guard let ptr = TISGetInputSourceProperty(source, kTISPropertyLocalizedName) else {
|
||||
return sourceID(source)
|
||||
}
|
||||
return Unmanaged<CFString>.fromOpaque(ptr).takeUnretainedValue() as String
|
||||
}
|
||||
|
||||
/// Код языка раскладки (BCP-47, например "ru", "en"), из kTISPropertyInputSourceLanguages
|
||||
public static func languageCode(_ source: TISInputSource) -> String? {
|
||||
guard let ptr = TISGetInputSourceProperty(source, kTISPropertyInputSourceLanguages) else {
|
||||
return nil
|
||||
}
|
||||
let langs = Unmanaged<CFArray>.fromOpaque(ptr).takeUnretainedValue() as? [String]
|
||||
return langs?.first
|
||||
}
|
||||
|
||||
/// Коды языков текущей и противоположной раскладок (для авто-детекта раскладки).
|
||||
public static func currentAndOppositeLanguage() -> (current: String, opposite: String)? {
|
||||
let settings = SettingsManager.shared
|
||||
let sources = installedLayouts()
|
||||
let currentID = currentLayoutID()
|
||||
let id1 = settings.layout1ID.isEmpty ? autoDetectID1(from: sources) : settings.layout1ID
|
||||
let id2 = settings.layout2ID.isEmpty ? autoDetectID2(from: sources) : settings.layout2ID
|
||||
let targetID = (currentID == id1) ? id2 : id1
|
||||
guard let cur = sources.first(where: { sourceID($0) == currentID }),
|
||||
let tgt = sources.first(where: { sourceID($0) == targetID }),
|
||||
let curLang = languageCode(cur), let tgtLang = languageCode(tgt) else {
|
||||
return nil
|
||||
}
|
||||
return (curLang, tgtLang)
|
||||
}
|
||||
|
||||
// MARK: - Auto-detect
|
||||
|
||||
/// Авто-определение «английской» раскладки (используется и из DynamicKeyMapping).
|
||||
static func autoDetectID1(from sources: [TISInputSource]) -> String {
|
||||
// Ищем английскую
|
||||
for source in sources {
|
||||
let id = sourceID(source)
|
||||
if id.contains("ABC") || id.contains("US") || id.contains("British") {
|
||||
return id
|
||||
}
|
||||
}
|
||||
return sources.first.map { sourceID($0) } ?? ""
|
||||
}
|
||||
|
||||
/// Авто-определение второй (не-английской) раскладки.
|
||||
static func autoDetectID2(from sources: [TISInputSource]) -> String {
|
||||
let id1 = autoDetectID1(from: sources)
|
||||
// Ищем вторую (не английскую)
|
||||
for source in sources {
|
||||
let id = sourceID(source)
|
||||
if id != id1 {
|
||||
return id
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user