vChewing-macOS/Source/Modules/SessionCtl_Core.swift

466 lines
20 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// (c) 2021 and onwards The vChewing Project (MIT-NTL License).
// ====================
// This code is released under the MIT license (SPDX-License-Identifier: MIT)
// ... with NTL restriction stating that:
// No trademark license is granted to use the trade names, trademarks, service
// marks, or product names of Contributor, except as required to fulfill notice
// requirements defined in MIT License.
import CandidateWindow
import CocoaExtension
import IMKUtils
import InputMethodKit
import NotifierUI
import PopupCompositionBuffer
import Shared
import ShiftKeyUpChecker
import TooltipUI
import UpdateSputnik
///
///
/// IMKInputController
///
/// / IMKInputController
/// 調
/// - Remark: IMKServer
/// IMKInputController
@objc(SessionCtl) // ObjC IMK ObjC
public class SessionCtl: IMKInputController {
///
public static var areWeNerfing = false
///
public var previouslyHandledEvents: [NSEvent] = .init()
///
public var candidateUI: CtlCandidateProtocol?
///
public var tooltipInstance = TooltipUI()
///
public var popupCompositionBuffer = PopupCompositionBuffer()
///
public var isActivated = false
/// activateServer 0.1
public private(set) var isBootingUp: Bool = true {
didSet {
guard isBootingUp else { return }
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
self.isBootingUp = false
}
}
}
///
public var isServingIMEItself: Bool = false
/// bundleIdentifier
///
public var clientBundleIdentifier: String = "" {
willSet {
if newValue.isEmpty { return }
Self.recentClientBundleIdentifiers[newValue] = Int(Date().timeIntervalSince1970)
}
}
///
public static var recentClientBundleIdentifiers = [String: Int]() {
didSet {
if recentClientBundleIdentifiers.count < 20 { return }
if recentClientBundleIdentifiers.isEmpty { return }
let x = recentClientBundleIdentifiers.sorted(by: { $0.value < $1.value }).first?.key
guard let x = x else { return }
recentClientBundleIdentifiers[x] = nil
}
}
// MARK: -
/// Caps Lock
public static var isCapsLocked: Bool { NSEvent.keyModifierFlags.contains(.capsLock) }
/// SessionCtl
public var isASCIIMode: Bool {
get {
PrefMgr.shared.shareAlphanumericalModeStatusAcrossClients
? Self.isASCIIModeForAllClients : isASCIIModeForThisClient
}
set {
if PrefMgr.shared.shareAlphanumericalModeStatusAcrossClients {
Self.isASCIIModeForAllClients = newValue
} else {
isASCIIModeForThisClient = newValue
}
resetInputHandler()
setKeyLayout()
}
}
/// isASCIIMode
private static var isASCIIModeForAllClients = false
/// isASCIIMode
private static var isASCIIModeForEachClient: [String: Bool] = [:]
/// isASCIIMode
private var isASCIIModeForThisClient: Bool {
get {
Self.isASCIIModeForEachClient[clientBundleIdentifier] ?? false
}
set {
Self.isASCIIModeForEachClient[clientBundleIdentifier] = newValue
}
}
/// 調
var inputHandler: InputHandlerProtocol?
///
public var state: IMEStateProtocol = IMEState.ofEmpty() {
didSet {
guard oldValue.type != state.type else { return }
if PrefMgr.shared.isDebugModeEnabled {
var stateDescription = state.type.rawValue
if state.type == .ofCommitting { stateDescription += "(\(state.textToCommit))" }
vCLog("Current State: \(stateDescription), client: \(clientBundleIdentifier)")
}
//
// guard state.isCandidateContainer != oldValue.isCandidateContainer else { return }
// if state.isCandidateContainer || oldValue.isCandidateContainer { setKeyLayout() }
}
}
/// Shift
/// - Remark: Struct Caps Lock Shift
public static var theShiftKeyDetector = ShiftKeyUpChecker(
useLShift: PrefMgr.shared.togglingAlphanumericalModeWithLShift,
useRShift: PrefMgr.shared.togglingAlphanumericalModeWithRShift
)
///
public static var isVerticalTyping: Bool = false
public var isVerticalTyping: Bool = false {
didSet {
Self.isVerticalTyping = isVerticalTyping
}
}
private let sharedAlertForInputModeToggling: NSAlert = {
let alert = NSAlert()
alert.alertStyle = .informational
alert.messageText = "Target Input Mode Activation Required".localized
alert.informativeText = "You are proceeding to System Preferences to enable the Input Source which corresponds to the input mode you are going to switch to.".localized
alert.addButton(withTitle: "OK".localized)
return alert
}()
public func updateVerticalTypingStatus() {
guard let client = client() else {
isVerticalTyping = false
return
}
var textFrame = NSRect.seniorTheBeast
let attributes: [AnyHashable: Any]? = client.attributes(
forCharacterIndex: 0, lineHeightRectangle: &textFrame
)
let result = (attributes?["IMKTextOrientation"] as? NSNumber)?.intValue == 0 || false
isVerticalTyping = result
}
///
public var isVerticalCandidateWindow = false
/// InputMode
/// IME UserPrefs
public var inputMode: Shared.InputMode = .imeModeNULL {
willSet {
/// Prefs IMEApp
PrefMgr.shared.mostRecentInputMode = newValue.rawValue
}
didSet {
if PrefMgr.shared.onlyLoadFactoryLangModelsIfNeeded { LMMgr.loadDataModel(inputMode) }
if oldValue != inputMode, inputMode != .imeModeNULL {
/// 調
resetInputHandler()
// ----------------------------
///
inputHandler?.currentLM = LMMgr.currentLM //
inputHandler?.currentUOM = LMMgr.currentUOM
///
inputHandler?.ensureKeyboardParser()
///
syncBaseLMPrefs()
}
}
}
///
override public init() {
super.init()
construct(client: client())
}
///
///
/// inputClient IMKServer IMKTextInput
/// - Remark: IMKInputController client()
/// - Parameters:
/// - server: IMKServer
/// - delegate:
/// - inputClient:
override public init!(server: IMKServer!, delegate: Any!, client inputClient: Any!) {
super.init(server: server, delegate: delegate, client: inputClient)
let theClient = inputClient as? (IMKTextInput & NSObjectProtocol)
construct(client: theClient)
}
/// super.init()
private func construct(client theClient: (IMKTextInput & NSObjectProtocol)? = nil) {
DispatchQueue.main.async { [self] in
inputHandler = InputHandler(
lm: LMMgr.currentLM, uom: LMMgr.currentUOM, pref: PrefMgr.shared
)
inputHandler?.delegate = self
syncBaseLMPrefs()
//
let maybeClient = theClient ?? client()
activateServer(maybeClient)
// GCD didSet
inputMode = .init(rawValue: PrefMgr.shared.mostRecentInputMode) ?? .imeModeNULL
}
}
}
// MARK: -
public extension SessionCtl {
/// 使
func setKeyLayout() {
guard let client = client(), !isServingIMEItself else { return }
DispatchQueue.main.async { [self] in
if isASCIIMode, IMKHelper.isDynamicBasicKeyboardLayoutEnabled {
client.overrideKeyboard(withKeyboardNamed: PrefMgr.shared.alphanumericalKeyboardLayout)
return
}
client.overrideKeyboard(withKeyboardNamed: PrefMgr.shared.basicKeyboardLayout)
}
}
/// 調
func resetInputHandler(forceComposerCleanup forceCleanup: Bool = false) {
guard let inputHandler = inputHandler else { return }
var textToCommit = ""
//
let sansReading: Bool =
(state.type == .ofInputting) && (PrefMgr.shared.trimUnfinishedReadingsOnCommit || forceCleanup)
if state.hasComposition {
textToCommit = inputHandler.generateStateOfInputting(sansReading: sansReading).displayedText
}
// IMKTextInput
// Shift+Delete
switchState(IMEState.ofCommitting(textToCommit: textToCommit))
}
}
// MARK: - IMKStateSetting
public extension SessionCtl {
///
/// - Parameter sender:
override func activateServer(_ sender: Any!) {
super.activateServer(sender)
isBootingUp = true
DispatchQueue.main.async { [self] in
if let senderBundleID: String = (sender as? IMKTextInput)?.bundleIdentifier() {
vCLog("activateServer(\(senderBundleID))")
isServingIMEItself = Bundle.main.bundleIdentifier == senderBundleID
clientBundleIdentifier = senderBundleID
}
}
DispatchQueue.main.async {
//
if !Date.isTodayTheDate(from: 0401), !PrefMgr.shared.shouldNotFartInLieuOfBeep {
PrefMgr.shared.shouldNotFartInLieuOfBeep = true
}
}
DispatchQueue.main.async { [self] in
if inputMode != IMEApp.currentInputMode {
inputMode = IMEApp.currentInputMode
}
}
DispatchQueue.main.async {
//
if self.candidateUI is CtlCandidateTDK {
self.candidateUI = nil
}
CtlCandidateTDK.currentMenu?.cancelTracking()
CtlCandidateTDK.currentMenu = nil
CtlCandidateTDK.currentWindow?.orderOut(nil)
CtlCandidateTDK.currentWindow = nil
}
DispatchQueue.main.async { [self] in
if isActivated { return }
// setValue() IMK activateServer() setValue()
inputHandler = InputHandler(
lm: LMMgr.currentLM, uom: LMMgr.currentUOM, pref: PrefMgr.shared
)
inputHandler?.delegate = self
syncBaseLMPrefs()
Self.theShiftKeyDetector.toggleWithLShift = PrefMgr.shared.togglingAlphanumericalModeWithLShift
Self.theShiftKeyDetector.toggleWithRShift = PrefMgr.shared.togglingAlphanumericalModeWithRShift
if #available(macOS 10.15, *) {
if isASCIIMode, !Self.theShiftKeyDetector.enabled { isASCIIMode = false }
}
DispatchQueue.main.async {
UpdateSputnik.shared.checkForUpdate(forced: false, url: kUpdateInfoSourceURL)
AppDelegate.shared.checkMemoryUsage()
}
state = IMEState.ofEmpty()
isActivated = true //
setKeyLayout()
}
}
///
/// - Parameter sender: 使
override func deactivateServer(_ sender: Any!) {
DispatchQueue.main.async { [self] in
isActivated = false
resetInputHandler() // Empty
switchState(IMEState.ofDeactivated())
inputHandler = nil
// IMK nil IMK
if candidateUI is CtlCandidateTDK {
candidateUI = nil
}
}
super.deactivateServer(sender)
}
///
/// - Remark: activateServer() setValue()
/// activateServer() setValue()
/// - Parameters:
/// - value: identifier bundle identifier info.plist
/// - tag: 使
/// - sender: 使
override func setValue(_ value: Any!, forTag tag: Int, client sender: Any!) {
DispatchQueue.main.async { [self] in
let newMode: Shared.InputMode = .init(rawValue: value as? String ?? PrefMgr.shared.mostRecentInputMode) ?? .imeModeNULL
if inputMode != newMode { inputMode = newMode }
}
super.setValue(value, forTag: tag, client: sender)
}
///
@objc func switchInputMode(_: Any? = nil) {
guard let client: IMKTextInput = client() else { return }
defer { isASCIIMode = false }
let nowMode = IMEApp.currentInputMode
guard nowMode != .imeModeNULL else { return }
modeCheck: for neta in TISInputSource.allRegisteredInstancesOfThisInputMethod {
guard !neta.isActivated else { continue }
osCheck: if #unavailable(macOS 12) {
neta.activate()
if !neta.isActivated {
break osCheck
}
break modeCheck
}
let result = sharedAlertForInputModeToggling.runModal()
NSApp.popup()
if result == NSApplication.ModalResponse.alertFirstButtonReturn {
neta.activate()
}
return
}
let status = "NotificationSwitchRevolver".localized
DispatchQueue.main.async {
if LMMgr.lmCHT.isCoreLMLoaded, LMMgr.lmCHS.isCoreLMLoaded {
Notifier.notify(
message: nowMode.reversed.localizedDescription + "\n" + status
)
}
}
client.selectMode(nowMode.reversed.rawValue)
}
///
func syncBaseLMPrefs() {
LMMgr.currentLM.isPhraseReplacementEnabled = PrefMgr.shared.phraseReplacementEnabled
LMMgr.currentLM.isCNSEnabled = PrefMgr.shared.cns11643Enabled
LMMgr.currentLM.isSymbolEnabled = PrefMgr.shared.symbolInputEnabled
LMMgr.currentLM.isSCPCEnabled = PrefMgr.shared.useSCPCTypingMode
LMMgr.currentLM.isCassetteEnabled = PrefMgr.shared.cassetteEnabled
LMMgr.currentLM.deltaOfCalendarYears = PrefMgr.shared.deltaOfCalendarYears
}
}
// MARK: - IMKServerInput
// handle(_ event:) SessionCtl_HandleEvent.swift
public extension SessionCtl {
///
///
///
/// Swift `NSEvent.EventTypeMask = [.keyDown]` ObjC `NSKeyDownMask`
/// IMK
/// 使
/// `commitComposition(_ message)`
/// - Parameter sender: 使
/// - Returns: uint NSEvent NSEvent.h
override func recognizedEvents(_ sender: Any!) -> Int {
_ = sender //
let events: NSEvent.EventTypeMask = [.keyDown, .flagsChanged, .keyUp]
return Int(events.rawValue)
}
/// App Ctrl+Enter / Shift+Enter
/// handle(event:) Event
/// commitComposition
/// - Parameter sender: 使
override func commitComposition(_ sender: Any!) {
_ = sender //
resetInputHandler()
clearInlineDisplay()
// super.commitComposition(sender) //
}
/// InputMethodKit
/// - Parameter sender: 使
/// - Returns: nil
override func composedString(_ sender: Any!) -> Any! {
_ = sender //
guard state.hasComposition else { return "" }
return state.displayedTextConverted
}
///
/// IMK Bug
override func inputControllerWillClose() {
//
resetInputHandler()
super.inputControllerWillClose()
}
///
override func selectionRange() -> NSRange {
attributedStringSecured.range
}
///
override func hidePalettes() {
candidateUI?.visible = false
popupCompositionBuffer.hide()
tooltipInstance.hide()
}
}