vChewing-macOS/Source/Modules/InputHandler_HandleInput.swift

292 lines
14 KiB
Swift
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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.
/// 調 IMK 調
/// 調
import CocoaExtension
import IMKUtils
import LangModelAssembly
import Shared
// MARK: - § 調 (Handle Input with States)
extension InputHandler {
///
/// - Remark: inputHandler?.handleEvent() IMKCandidates
/// - Parameters:
/// - input:
/// - Returns: IMK
func handleInput(event input: InputSignalProtocol) -> Bool {
// inputTest
//
// delegate
guard !input.text.isEmpty, input.charCode.isPrintable, let delegate = delegate else { return false }
let inputText: String = input.text
var state: IMEStateProtocol { delegate.state } //
// Megrez
if input.isInvalid {
// .Empty(IgnoringPreviousState) .Deactivated
// .Abortion.Empty
if state.type == .ofEmpty || state.type == .ofDeactivated { return false }
delegate.callError("550BCF7B: InputHandler just refused an invalid input.")
return true
}
//
let isFunctionKey: Bool =
input.isControlHotKey || (input.isCommandHold || input.isOptionHotKey || input.isNonLaptopFunctionKey)
if state.type != .ofAssociates, !state.hasComposition, !state.isCandidateContainer, isFunctionKey {
return false
}
// MARK: Caps Lock
/// Caps Lock
/// Caps Lock
if input.isCapsLockOn || state.isASCIIMode {
// macOS 12 CapsLock .ofEmpty()
delegate.switchState(IMEState.ofEmpty())
// Shift
if (input.isUpperCaseASCIILetterKey && state.isASCIIMode)
|| (input.isCapsLockOn && input.isShiftHold)
{
return false
}
/// ASCII 使insertText:replacementRange:
/// ASCII
if input.isASCII, !input.charCode.isPrintableASCII { return false }
//
delegate.switchState(IMEState.ofCommitting(textToCommit: inputText.lowercased()))
return true
}
// MARK: (Numeric Pad Processing)
// isNumericPadKey KeyCode
// 使 Cocoa flags
//
if input.isNumericPadKey {
if ![.ofCandidates, .ofAssociates, .ofSymbolTable].contains(state.type) {
delegate.switchState(IMEState.ofEmpty())
delegate.switchState(IMEState.ofCommitting(textToCommit: inputText.lowercased()))
return true
}
}
// MARK: (Handle Candidates)
if [.ofCandidates, .ofSymbolTable].contains(state.type) { return handleCandidate(input: input) }
// MARK: (Handle Associated Phrases)
if state.type == .ofAssociates {
if handleCandidate(input: input) {
return true
} else {
delegate.switchState(IMEState.ofEmpty())
}
}
// MARK: 便使() (Handle Marking)
if state.type == .ofMarking {
if handleMarkingState(input: input) { return true }
delegate.switchState(state.convertedToInputting)
}
// MARK: (Handle BPMF Keys)
if let compositionHandled = handleComposition(input: input) { return compositionHandled }
// MARK: (Calling candidate window using Up / Down or PageUp / PageDn.)
// state.hasComposition
// !input.isFunctionKeyHold
if state.hasComposition, !compositor.isEmpty, isComposerOrCalligrapherEmpty,
!input.isOptionHold, !input.isShiftHold, !input.isCommandHold, !input.isControlHold,
input.isCursorClockLeft || input.isCursorClockRight || (input.isSpace && prefs.chooseCandidateUsingSpace)
|| input.isPageDown || input.isPageUp || (input.isTab && prefs.specifyShiftTabKeyBehavior)
{
//
let candidateState: IMEStateProtocol = generateStateOfCandidates()
_ = candidateState.candidates.isEmpty ? delegate.callError("3572F238") : delegate.switchState(candidateState)
return true
}
// MARK:
if let keyCodeType = KeyCode(rawValue: input.keyCode) {
switch keyCodeType {
case .kEscape: return handleEsc()
case .kTab: return rotateCandidate(reverseOrder: input.isShiftHold)
case .kUpArrow, .kDownArrow, .kLeftArrow, .kRightArrow:
let rotation: Bool = input.isOptionHold && state.type == .ofInputting
handleArrowKey: switch (keyCodeType, delegate.isVerticalTyping) {
case (.kLeftArrow, false), (.kUpArrow, true): return handleBackward(input: input)
case (.kRightArrow, false), (.kDownArrow, true): return handleForward(input: input)
case (.kUpArrow, false), (.kLeftArrow, true):
return rotation ? rotateCandidate(reverseOrder: true) : handleClockKey()
case (.kDownArrow, false), (.kRightArrow, true):
return rotation ? rotateCandidate(reverseOrder: false) : handleClockKey()
default: break handleArrowKey //
}
case .kHome: return handleHome()
case .kEnd: return handleEnd()
case .kBackSpace: return handleBackSpace(input: input)
case .kWindowsDelete: return handleDelete(input: input)
case .kCarriageReturn, .kLineFeed: // Enter
return (input.isCommandHold && input.isControlHold)
? (input.isOptionHold
? handleCtrlOptionCommandEnter()
: handleCtrlCommandEnter(isShiftPressed: input.isShiftHold))
: handleEnter()
case .kSpace: // Space
//
switch state.type {
case .ofEmpty:
if !input.isOptionHold, !input.isControlHold, !input.isCommandHold {
delegate.switchState(IMEState.ofCommitting(textToCommit: input.isShiftHold ? " " : " "))
return true
}
case .ofInputting:
// Tab Shift+Command+Space /
if input.isShiftHold, !input.isControlHold, !input.isOptionHold {
return rotateCandidate(reverseOrder: input.isCommandHold)
}
if compositor.cursor < compositor.length, compositor.insertKey(" ") {
walk()
// App
let textToCommit = commitOverflownComposition
var inputting = generateStateOfInputting()
inputting.textToCommit = textToCommit
delegate.switchState(inputting)
} else {
let displayedText = state.displayedText
if !displayedText.isEmpty {
delegate.switchState(IMEState.ofCommitting(textToCommit: displayedText))
}
delegate.switchState(IMEState.ofCommitting(textToCommit: " "))
}
return true
default: break
}
default: break
}
}
// MARK: Punctuation list
if input.isSymbolMenuPhysicalKey, !input.isShiftHold, !input.isControlHold, state.type != .ofDeactivated {
if input.isOptionHold {
if currentLM.hasUnigramsFor(keyArray: ["_punctuation_list"]) {
if isComposerOrCalligrapherEmpty, compositor.insertKey("_punctuation_list") {
walk()
// App
let textToCommit = commitOverflownComposition
var inputting = generateStateOfInputting()
inputting.textToCommit = textToCommit
delegate.switchState(inputting)
//
let newState = generateStateOfCandidates()
_ = newState.candidates.isEmpty ? delegate.callError("B5127D8A") : delegate.switchState(newState)
} else { //
delegate.callError("17446655")
}
return true
} else {
let errorMessage =
NSLocalizedString(
"Please manually implement the symbols of this menu \nin the user phrase file with “_punctuation_list” key.",
comment: ""
)
vCLog("8EB3FB1A: " + errorMessage)
delegate.switchState(IMEState.ofEmpty())
let isJIS: Bool = input.keyCode == KeyCode.kSymbolMenuPhysicalKeyJIS.rawValue
delegate.switchState(IMEState.ofCommitting(textToCommit: isJIS ? "_" : "`"))
return true
}
} else {
// commit buffer ESC
delegate.switchState(IMEState.ofCommitting(textToCommit: state.displayedText))
delegate.switchState(IMEState.ofSymbolTable(node: CandidateNode.root))
return true
}
}
// MARK: / (FW / HW Arabic Numbers Input)
if state.type == .ofEmpty {
if input.isMainAreaNumKey, input.modifierFlags == [.shift, .option] {
guard let strRAW = input.mainAreaNumKeyChar else { return false }
let newString =
strRAW.applyingTransform(.fullwidthToHalfwidth, reverse: !prefs.halfWidthPunctuationEnabled) ?? strRAW
delegate.switchState(IMEState.ofCommitting(textToCommit: newString))
return true
}
}
// MARK: Punctuation
///
/// - /
/// -
let punctuationNamePrefix: String = generatePunctuationNamePrefix(withKeyCondition: input)
let parser = currentKeyboardParser
let arrCustomPunctuations: [String] = [punctuationNamePrefix, parser, input.text]
let customPunctuation: String = arrCustomPunctuations.joined()
if handlePunctuation(customPunctuation) { return true }
///
let arrPunctuations: [String] = [punctuationNamePrefix, input.text]
let punctuation: String = arrPunctuations.joined()
if handlePunctuation(punctuation) { return true }
// MARK: Shift+ (Shift+Letter Processing)
if input.isUpperCaseASCIILetterKey, !input.isCommandHold, !input.isControlHold {
if input.isShiftHold { // isOptionHold
switch prefs.upperCaseLetterKeyBehavior {
case 1:
delegate.switchState(IMEState.ofEmpty())
delegate.switchState(IMEState.ofCommitting(textToCommit: inputText.lowercased()))
return true
case 2:
delegate.switchState(IMEState.ofEmpty())
delegate.switchState(IMEState.ofCommitting(textToCommit: inputText.uppercased()))
return true
default: // case 0
let letter = "_letter_\(inputText)"
if handlePunctuation(letter) {
return true
}
}
}
}
// MARK: - (Still Nothing)
/// SessionCtl
///
/// F1-F12
/// 便
if state.hasComposition || !isComposerOrCalligrapherEmpty {
delegate.callError("Blocked data: charCode: \(input.charCode), keyCode: \(input.keyCode), text: \(input.text)")
delegate.callError("A9BFF20E")
return true
}
return false
}
}