vChewing-macOS/Packages/vChewing_MainAssembly/Sources/MainAssembly/InputHandler_HandleCandidat...

285 lines
12 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 InputMethodKit
import Megrez
import Shared
// MARK: - § 調 (Handle Candidate State).
extension InputHandler {
///
/// - Parameter input:
/// - Returns: IMK
func handleCandidate(input: InputSignalProtocol) -> Bool {
guard let delegate = delegate else { return false }
guard var ctlCandidate = delegate.candidateController() else { return false }
let state = delegate.state
guard state.isCandidateContainer else { return false } // isEmpty
guard ctlCandidate.visible else { return false }
// MARK: 使
manipulator: if (delegate as? CtlCandidateDelegate)?.isCandidateContextMenuEnabled ?? false {
let candidates = state.candidates
let highlightedIndex = ctlCandidate.highlightedIndex
if !(0 ..< candidates.count).contains(ctlCandidate.highlightedIndex) { break manipulator }
if candidates[highlightedIndex].keyArray.count < 2 || candidates[highlightedIndex].value.count < 2 {
break manipulator
}
switch input.keyModifierFlags {
case [.option, .command] where input.keyCode == 27: //
ctlCandidate.delegate?.candidatePairRightClicked(at: highlightedIndex, action: .toNerf)
return true
case [.option, .command] where input.keyCode == 24: // JIS ^
ctlCandidate.delegate?.candidatePairRightClicked(at: highlightedIndex, action: .toBoost)
return true
case _ where input.isOptionHold && input.isCommandHold && input.isDelete:
ctlCandidate.delegate?.candidatePairRightClicked(at: highlightedIndex, action: .toFilter)
return true
default: break
}
}
// MARK: BackSpace
if input.isBackSpace, prefs.cassetteEnabled, state.type == .ofInputting {
return handleBackSpace(input: input)
}
// MARK: (Cancel Candidate)
let cancelCandidateKey =
input.isBackSpace || input.isEsc || input.isDelete
|| ((input.isCursorBackward || input.isCursorForward) && input.isShiftHold)
if cancelCandidateKey {
if state.type == .ofAssociates
|| prefs.useSCPCTypingMode
|| compositor.isEmpty
{
//
//
// 使 BackSpace
// compositor.isEmpty
delegate.switchState(IMEState.ofAbortion())
} else {
delegate.switchState(generateStateOfInputting())
if input.isCursorBackward || input.isCursorForward, input.isShiftHold {
return triageInput(event: input)
}
}
if state.type == .ofSymbolTable, let nodePrevious = state.node.previous, !nodePrevious.members.isEmpty {
delegate.switchState(IMEState.ofSymbolTable(node: nodePrevious))
}
return true
}
// MARK:
func confirmHighlightedCandidate() {
delegate.candidateSelectionConfirmedByInputHandler(at: ctlCandidate.highlightedIndex)
}
if let keyCodeType = KeyCode(rawValue: input.keyCode) {
switch keyCodeType {
case .kLineFeed, .kCarriageReturn:
if state.type == .ofAssociates, !(input.isShiftHold || prefs.alsoConfirmAssociatedCandidatesByEnter) {
delegate.switchState(IMEState.ofAbortion())
return true
}
let highlightedCandidate = state.candidates[ctlCandidate.highlightedIndex] //
var handleAssociates = !prefs.useSCPCTypingMode && prefs.associatedPhrasesEnabled //
handleAssociates = handleAssociates && compositor.cursor == compositor.length //
confirmHighlightedCandidate()
//
associatedPhrases: if handleAssociates {
guard handleAssociates else { break associatedPhrases }
guard input.keyModifierFlags == .shift else { break associatedPhrases }
let pair = Megrez.KeyValuePaired(
keyArray: highlightedCandidate.keyArray, value: highlightedCandidate.value
)
let associatedCandidates = generateArrayOfAssociates(withPair: pair)
guard !associatedCandidates.isEmpty else { break associatedPhrases }
delegate.switchState(IMEState.ofCommitting(textToCommit: state.displayedText))
delegate.switchState(IMEState.ofAssociates(candidates: associatedCandidates))
}
return true
case .kTab:
let updated: Bool =
prefs.specifyShiftTabKeyBehavior
? (input.isShiftHold
? ctlCandidate.showPreviousLine()
: ctlCandidate.showNextLine())
: (input.isShiftHold
? ctlCandidate.highlightPreviousCandidate()
: ctlCandidate.highlightNextCandidate())
_ = updated ? {}() : delegate.callError("9B691919")
return true
case .kSpace where state.type != .ofInputting:
guard !(prefs.useSpaceToCommitHighlightedSCPCCandidate && prefs.useSCPCTypingMode) else {
confirmHighlightedCandidate()
return true
}
let updated: Bool =
prefs.specifyShiftSpaceKeyBehavior
? (input.isShiftHold
? ctlCandidate.highlightNextCandidate()
: ctlCandidate.showNextLine())
: (input.isShiftHold
? ctlCandidate.showNextLine()
: ctlCandidate.highlightNextCandidate())
_ = updated ? {}() : delegate.callError("A11C781F")
return true
case .kPageDown:
_ = ctlCandidate.showNextPage() ? {}() : delegate.callError("9B691919")
return true
case .kPageUp:
_ = ctlCandidate.showPreviousPage() ? {}() : delegate.callError("9569955D")
return true
case .kUpArrow, .kDownArrow, .kLeftArrow, .kRightArrow:
handleArrowKey: switch (keyCodeType, ctlCandidate.currentLayout) {
case (.kLeftArrow, .horizontal), (.kUpArrow, .vertical): // Previous Candidate
_ = ctlCandidate.highlightPreviousCandidate()
case (.kRightArrow, .horizontal), (.kDownArrow, .vertical): // Next Candidate
_ = ctlCandidate.highlightNextCandidate()
case (.kUpArrow, .horizontal), (.kLeftArrow, .vertical): // Previous Line
_ = ctlCandidate.showPreviousLine()
case (.kDownArrow, .horizontal), (.kRightArrow, .vertical): // Next Line
_ = ctlCandidate.showNextLine()
default: break handleArrowKey
}
return true
case .kHome:
_ =
(ctlCandidate.highlightedIndex == 0)
? delegate.callError("9B6EDE8D") : (ctlCandidate.highlightedIndex = 0)
return true
case .kEnd:
let maxIndex = state.candidates.count - 1
_ =
(ctlCandidate.highlightedIndex == maxIndex)
? delegate.callError("9B69AAAD") : (ctlCandidate.highlightedIndex = maxIndex)
return true
default: break
}
}
// MARK: (Associated Phrases)
if state.type == .ofAssociates, !input.isShiftHold { return false }
var index: Int?
var shaltShiftHold = [.ofAssociates].contains(state.type)
if [.ofInputting].contains(state.type) {
let cassetteShift = currentLM.areCassetteCandidateKeysShiftHeld
shaltShiftHold = shaltShiftHold || cassetteShift
}
let matched: String = shaltShiftHold ? input.inputTextIgnoringModifiers ?? "" : input.text
checkSelectionKey: for keyPair in delegate.selectionKeys.enumerated() {
guard matched.lowercased() == keyPair.element.lowercased() else { continue }
index = Int(keyPair.offset)
break checkSelectionKey
}
//
if let index = index, let candidateIndex = ctlCandidate.candidateIndexAtKeyLabelIndex(index) {
delegate.candidateSelectionConfirmedByInputHandler(at: candidateIndex)
return true
}
if state.type == .ofAssociates { return false }
// MARK: (SCPC Mode Processing)
// .ofInputting `%quick` /
if prefs.useSCPCTypingMode, state.type != .ofInputting {
///
/// - /
/// -
let punctuationNamePrefix: String = generatePunctuationNamePrefix(withKeyCondition: input)
let parser = currentKeyboardParser
let arrCustomPunctuations: [String] = [
punctuationNamePrefix, parser, input.text,
]
let customPunctuation: String = arrCustomPunctuations.joined()
///
let arrPunctuations: [String] = [
punctuationNamePrefix, input.text,
]
let punctuation: String = arrPunctuations.joined()
let isInputValid: Bool =
prefs.cassetteEnabled
? currentLM.isThisCassetteKeyAllowed(key: input.text) : composer.inputValidityCheck(key: input.charCode)
var shouldAutoSelectCandidate: Bool =
isInputValid || currentLM.hasUnigramsFor(keyArray: [customPunctuation])
|| currentLM.hasUnigramsFor(keyArray: [punctuation])
if !shouldAutoSelectCandidate, input.isUpperCaseASCIILetterKey {
let letter = "_letter_\(input.text)"
if currentLM.hasUnigramsFor(keyArray: [letter]) { shouldAutoSelectCandidate = true }
}
if shouldAutoSelectCandidate {
confirmHighlightedCandidate() //
delegate.switchState(IMEState.ofAbortion())
return triageInput(event: input)
}
}
// MARK: - Flipping pages by using modified bracket keys (when they are not occupied).
// Shift+Command+[] Chrome Ctrl
let ctrlCMD: Bool = input.keyModifierFlags == [.control, .command]
let ctrlShiftCMD: Bool = input.keyModifierFlags == [.control, .command, .shift]
if ctrlShiftCMD || ctrlCMD {
// JIS US
switch (input.keyCode, IMEApp.isKeyboardJIS) {
case (30, true), (33, false):
_ = ctlCandidate.highlightPreviousCandidate() ? {}() : delegate.callError("8B144DCD")
return true
case (42, true), (30, false):
_ = ctlCandidate.highlightNextCandidate() ? {}() : delegate.callError("D2ABB507")
return true
default: break
}
}
// MARK: - Flipping pages by using symbol menu keys (when they are not occupied).
if input.isSymbolMenuPhysicalKey {
switch input.keyModifierFlags {
case .shift, [],
.option where state.type != .ofSymbolTable:
var updated = true
let reverseTrigger = input.isShiftHold || input.isOptionHold
updated = reverseTrigger ? ctlCandidate.showPreviousLine() : ctlCandidate.showNextLine()
if !updated { delegate.callError("66F3477B") }
return true
case .option where state.type == .ofSymbolTable:
return handleHaninKeyboardSymbolModeToggle()
default: break
}
}
if state.type == .ofInputting { return false } // `%quick`
delegate.callError("172A0F81")
return true
}
}