From b13da10ec0316a2df49be570407903faa83e087b Mon Sep 17 00:00:00 2001 From: zonble Date: Fri, 28 Jan 2022 16:16:52 +0800 Subject: [PATCH] Code clean-up. --- Source/InputMethodController.mm | 133 +++++++++++++++----------------- Source/InputState.swift | 32 ++++---- Source/KeyHandler.h | 4 +- Source/KeyHandler.mm | 45 ++++++----- Source/KeyHandlerInput.swift | 82 ++++++++++---------- Source/LanguageModelManager.mm | 9 +-- 6 files changed, 145 insertions(+), 160 deletions(-) diff --git a/Source/InputMethodController.mm b/Source/InputMethodController.mm index 3daf35bf..9c76008f 100644 --- a/Source/InputMethodController.mm +++ b/Source/InputMethodController.mm @@ -76,7 +76,6 @@ static inline NSString *LocalizationNotNeeded(NSString *s) { @implementation McBopomofoInputMethodController - - (id)initWithServer:(IMKServer *)server delegate:(id)delegate client:(id)client { // an instance is initialized whenever a text input client (a Mac app) requires @@ -96,7 +95,7 @@ static inline NSString *LocalizationNotNeeded(NSString *s) { { // a menu instance (autoreleased) is requested every time the user click on the input menu NSMenu *menu = [[NSMenu alloc] initWithTitle:LocalizationNotNeeded(@"Input Method Menu")]; - NSString *inputMode = [_keyHandler inputMode]; + NSString *inputMode = _keyHandler.inputMode; [menu addItemWithTitle:NSLocalizedString(@"McBopomofo Preferences", @"") action:@selector(showPreferences:) keyEquivalent:@""]; @@ -147,12 +146,14 @@ static inline NSString *LocalizationNotNeeded(NSString *s) { // reset the state _currentDeferredClient = nil; _currentCandidateClient = nil; - InputStateEmpty *newState = [[InputStateEmpty alloc] init]; - [self handleState:newState client:client]; + + [_keyHandler clear]; + InputStateEmpty *empty = [[InputStateEmpty alloc] init]; + [self handleState:empty client:client]; // checks and populates the default settings - [_keyHandler synchWithPrefereneces]; - [(AppDelegate * )[NSApp delegate] checkForUpdate]; + [_keyHandler syncWithPreferences]; + [(AppDelegate *) NSApp.delegate checkForUpdate]; } - (void)deactivateServer:(id)client @@ -162,8 +163,8 @@ static inline NSString *LocalizationNotNeeded(NSString *s) { InputStateEmpty *empty = [[InputStateEmpty alloc] init]; [self handleState:empty client:client]; - InputStateDeactive *deactive = [[InputStateDeactive alloc] init]; - [self handleState:deactive client:client]; + InputStateDeactivated *inactive = [[InputStateDeactivated alloc] init]; + [self handleState:inactive client:client]; } - (void)setValue:(id)value forTag:(long)tag client:(id)sender @@ -177,10 +178,10 @@ static inline NSString *LocalizationNotNeeded(NSString *s) { } // Only apply the changes if the value is changed - if (![ [_keyHandler inputMode] isEqualToString:newInputMode]) { + if (![_keyHandler.inputMode isEqualToString:newInputMode]) { [[NSUserDefaults standardUserDefaults] synchronize]; - // Remember to override the keyboard layout again -- treat this as an activate eventy + // Remember to override the keyboard layout again -- treat this as an activate event. NSString *basisKeyboardLayoutID = Preferences.basisKeyboardLayout; [sender overrideKeyboardWithKeyboardNamed:basisKeyboardLayoutID]; [_keyHandler clear]; @@ -194,12 +195,12 @@ static inline NSString *LocalizationNotNeeded(NSString *s) { - (NSUInteger)recognizedEvents:(id)sender { - return NSKeyDownMask | NSFlagsChangedMask; + return NSEventMaskKeyDown | NSEventMaskFlagsChanged; } - (BOOL)handleEvent:(NSEvent *)event client:(id)client { - if ([event type] == NSFlagsChanged) { + if ([event type] == NSEventMaskFlagsChanged) { NSString *functionKeyKeyboardLayoutID = Preferences.functionKeyboardLayout; NSString *basisKeyboardLayoutID = Preferences.basisKeyboardLayout; @@ -210,13 +211,13 @@ static inline NSString *LocalizationNotNeeded(NSString *s) { // Function key pressed. BOOL includeShift = Preferences.functionKeyKeyboardLayoutOverrideIncludeShiftKey; - if (([event modifierFlags] & ~NSEventModifierFlagShift) || (([event modifierFlags] & NSEventModifierFlagShift) && includeShift)) { + if ((event.modifierFlags & ~NSEventModifierFlagShift) || ((event.modifierFlags & NSEventModifierFlagShift) && includeShift)) { // Override the keyboard layout and let the OS do its thing [client overrideKeyboardWithKeyboardNamed:functionKeyKeyboardLayoutID]; return NO; } - // Revert back to the basis layout when the function key is released + // Revert to the basis layout when the function key is released [client overrideKeyboardWithKeyboardNamed:basisKeyboardLayoutID]; return NO; } @@ -227,7 +228,7 @@ static inline NSString *LocalizationNotNeeded(NSString *s) { @try { attributes = [client attributesForCharacterIndex:0 lineHeightRectangle:&textFrame]; - useVerticalMode = [attributes objectForKey:@"IMKTextOrientation"] && [[attributes objectForKey:@"IMKTextOrientation"] integerValue] == 0; + useVerticalMode = attributes[@"IMKTextOrientation"] && [attributes[@"IMKTextOrientation"] integerValue] == 0; } @catch (NSException *e) { // exception may raise while using Twitter.app's search filed. @@ -241,10 +242,9 @@ static inline NSString *LocalizationNotNeeded(NSString *s) { KeyHandlerInput *input = [[KeyHandlerInput alloc] initWithEvent:event isVerticalMode:useVerticalMode]; BOOL result = [_keyHandler handleInput:input state:_state stateCallback:^(InputState *state) { [self handleState:state client:client]; - } candidateSelectionCallback:^{ - NSLog(@"candidateSelectionCallback "); -// [self handleState:self->_state client:(self->_currentCandidateClient ? self->_currentCandidateClient : client)]; - } errorCallback:^{ + } candidateSelectionCallback:^{ + NSLog(@"candidate window updated."); + } errorCallback:^{ NSBeep(); }]; @@ -284,7 +284,7 @@ static inline NSString *LocalizationNotNeeded(NSString *s) { if ([[client bundleIdentifier] isEqualToString:@"com.apple.Terminal"] && ![NSStringFromClass([client class]) isEqualToString:@"IPMDServerClientWrapper"]) { if (_currentDeferredClient) { id currentDeferredClient = _currentDeferredClient; - dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t) (0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [currentDeferredClient insertText:buffer replacementRange:NSMakeRange(NSNotFound, NSNotFound)]; }); } @@ -297,37 +297,37 @@ static inline NSString *LocalizationNotNeeded(NSString *s) { { // NSLog(@"current state: %@ new state: %@", _state, newState ); - // We need to set the state to the member varible since the candidate + // We need to set the state to the member variable since the candidate // window need to read the candidates from it. InputState *previous = _state; _state = newState; - if ([newState isKindOfClass:[InputStateDeactive class]]) { - [self _handleInputStateDeactive:(InputStateDeactive *) newState previous:previous client:client]; + if ([newState isKindOfClass:[InputStateDeactivated class]]) { + [self _handleDeactivated:(InputStateDeactivated *) newState previous:previous client:client]; } else if ([newState isKindOfClass:[InputStateEmpty class]]) { - [self _handleInputStateEmpty:(InputStateEmpty *) newState previous:previous client:client]; + [self _handleEmpty:(InputStateEmpty *) newState previous:previous client:client]; } else if ([newState isKindOfClass:[InputStateEmptyIgnoringPreviousState class]]) { - [self _handleInputStateEmptyIgnoringPrevious:(InputStateEmptyIgnoringPreviousState *) newState previous:previous client:client]; + [self _handleEmptyIgnoringPrevious:(InputStateEmptyIgnoringPreviousState *) newState previous:previous client:client]; } else if ([newState isKindOfClass:[InputStateCommitting class]]) { - [self _handleInputStateCommitting:(InputStateCommitting *) newState previous:previous client:client]; + [self _handleCommitting:(InputStateCommitting *) newState previous:previous client:client]; } else if ([newState isKindOfClass:[InputStateInputting class]]) { - [self _handleInputStateInputting:(InputStateInputting *) newState previous:previous client:client]; + [self _handleInputting:(InputStateInputting *) newState previous:previous client:client]; } else if ([newState isKindOfClass:[InputStateMarking class]]) { - [self _handleInputStateMarking:(InputStateMarking *) newState previous:previous client:client]; + [self _handleMarking:(InputStateMarking *) newState previous:previous client:client]; } else if ([newState isKindOfClass:[InputStateChoosingCandidate class]]) { - [self _handleInputStateChoosingCandidate:(InputStateChoosingCandidate *)newState previous:previous client:client]; + [self _handleChoosingCandidate:(InputStateChoosingCandidate *) newState previous:previous client:client]; } } -- (void)_handleInputStateDeactive:(InputStateDeactive *)state previous:(InputState *)previous client:(id)client +- (void)_handleDeactivated:(InputStateDeactivated *)state previous:(InputState *)previous client:(id)client { // commit any residue in the composing buffer if ([previous isKindOfClass:[InputStateInputting class]]) { - NSString *buffer = [(InputStateInputting *) previous composingBuffer]; + NSString *buffer = ((InputStateInputting *) previous).composingBuffer; [self _commitText:buffer client:client]; } [client setMarkedText:@"" selectionRange:NSMakeRange(0, 0) replacementRange:NSMakeRange(NSNotFound, NSNotFound)]; - + _currentDeferredClient = nil; _currentCandidateClient = nil; @@ -336,11 +336,11 @@ static inline NSString *LocalizationNotNeeded(NSString *s) { [self _hideTooltip]; } -- (void)_handleInputStateEmpty:(InputStateEmpty *)state previous:(InputState *)previous client:(id)client +- (void)_handleEmpty:(InputStateEmpty *)state previous:(InputState *)previous client:(id)client { // commit any residue in the composing buffer if ([previous isKindOfClass:[InputStateInputting class]]) { - NSString *buffer = [(InputStateInputting *) previous composingBuffer]; + NSString *buffer = ((InputStateInputting *) previous).composingBuffer; [self _commitText:buffer client:client]; } @@ -349,31 +349,30 @@ static inline NSString *LocalizationNotNeeded(NSString *s) { [self _hideTooltip]; } -- (void)_handleInputStateEmptyIgnoringPrevious:(InputStateEmptyIgnoringPreviousState *)state previous:(InputState *)previous client:(id)client +- (void)_handleEmptyIgnoringPrevious:(InputStateEmptyIgnoringPreviousState *)state previous:(InputState *)previous client:(id)client { -// [client insertText:@"" replacementRange:NSMakeRange(NSNotFound, NSNotFound)]; [client setMarkedText:@"" selectionRange:NSMakeRange(0, 0) replacementRange:NSMakeRange(NSNotFound, NSNotFound)]; gCurrentCandidateController.visible = NO; [self _hideTooltip]; } -- (void)_handleInputStateCommitting:(InputStateCommitting *)state previous:(InputState *)previous client:(id)client +- (void)_handleCommitting:(InputStateCommitting *)state previous:(InputState *)previous client:(id)client { - NSString *poppedText = [state poppedText]; + NSString *poppedText = state.poppedText; [self _commitText:poppedText client:client]; gCurrentCandidateController.visible = NO; [self _hideTooltip]; } -- (void)_handleInputStateInputting:(InputStateInputting *)state previous:(InputState *)previous client:(id)client +- (void)_handleInputting:(InputStateInputting *)state previous:(InputState *)previous client:(id)client { NSString *poppedText = state.poppedText; if (poppedText.length) { [self _commitText:poppedText client:client]; } - NSUInteger cursorIndex = [state cursorIndex]; - NSAttributedString *attrString = [state attributedString]; + NSUInteger cursorIndex = state.cursorIndex; + NSAttributedString *attrString = state.attributedString; // the selection range is where the cursor is, with the length being 0 and replacement range NSNotFound, // i.e. the client app needs to take care of where to put ths composing buffer @@ -383,10 +382,10 @@ static inline NSString *LocalizationNotNeeded(NSString *s) { [self _hideTooltip]; } -- (void)_handleInputStateMarking:(InputStateMarking *)state previous:(InputState *)previous client:(id)client +- (void)_handleMarking:(InputStateMarking *)state previous:(InputState *)previous client:(id)client { - NSUInteger cursorIndex = [state cursorIndex]; - NSAttributedString *attrString = [state attributedString]; + NSUInteger cursorIndex = state.cursorIndex; + NSAttributedString *attrString = state.attributedString; // the selection range is where the cursor is, with the length being 0 and replacement range NSNotFound, // i.e. the client app needs to take care of where to put ths composing buffer @@ -400,16 +399,16 @@ static inline NSString *LocalizationNotNeeded(NSString *s) { } } -- (void)_handleInputStateChoosingCandidate:(InputStateChoosingCandidate *)state previous:(InputState *)previous client:(id)client +- (void)_handleChoosingCandidate:(InputStateChoosingCandidate *)state previous:(InputState *)previous client:(id)client { - NSUInteger cursorIndex = [state cursorIndex]; - NSAttributedString *attrString = [state attributedString]; + NSUInteger cursorIndex = state.cursorIndex; + NSAttributedString *attrString = state.attributedString; // the selection range is where the cursor is, with the length being 0 and replacement range NSNotFound, // i.e. the client app needs to take care of where to put ths composing buffer [client setMarkedText:attrString selectionRange:NSMakeRange(cursorIndex, 0) replacementRange:NSMakeRange(NSNotFound, NSNotFound)]; - if ([_keyHandler inputMode] == kPlainBopomofoModeIdentifier && [state.candidates count] == 1) { + if (_keyHandler.inputMode == kPlainBopomofoModeIdentifier && state.candidates.count == 1) { NSString *buffer = [self _convertToSimplifiedChineseIfRequired:state.candidates.firstObject]; [client insertText:buffer replacementRange:NSMakeRange(NSNotFound, NSNotFound)]; InputStateEmpty *empty = [[InputStateEmpty alloc] init]; @@ -444,17 +443,17 @@ static inline NSString *LocalizationNotNeeded(NSString *s) { NSString *ctFontName = Preferences.candidateTextFontName; NSString *klFontName = Preferences.candidateKeyLabelFontName; - NSString *ckeys = Preferences.candidateKeys; + NSString *candidateKeys = Preferences.candidateKeys; gCurrentCandidateController.keyLabelFont = klFontName ? [NSFont fontWithName:klFontName size:keyLabelSize] : [NSFont systemFontOfSize:keyLabelSize]; gCurrentCandidateController.candidateFont = ctFontName ? [NSFont fontWithName:ctFontName size:textSize] : [NSFont systemFontOfSize:textSize]; - NSMutableArray *keyLabels = [NSMutableArray arrayWithObjects:@"1", @"2", @"3", @"4", @"5", @"6", @"7", @"8", @"9", nil]; + NSMutableArray *keyLabels = [@[@"1", @"2", @"3", @"4", @"5", @"6", @"7", @"8", @"9"] mutableCopy]; - if ([ckeys length] > 1) { + if (candidateKeys.length > 1) { [keyLabels removeAllObjects]; - for (NSUInteger i = 0, c = [ckeys length]; i < c; i++) { - [keyLabels addObject:[ckeys substringWithRange:NSMakeRange(i, 1)]]; + for (NSUInteger i = 0, c = candidateKeys.length; i < c; i++) { + [keyLabels addObject:[candidateKeys substringWithRange:NSMakeRange(i, 1)]]; } } @@ -465,7 +464,7 @@ static inline NSString *LocalizationNotNeeded(NSString *s) { NSRect lineHeightRect = NSMakeRect(0.0, 0.0, 16.0, 16.0); NSInteger cursor = state.cursorIndex; - if (cursor == [state.composingBuffer length] && cursor != 0) { + if (cursor == state.composingBuffer.length && cursor != 0) { cursor--; } @@ -494,9 +493,7 @@ static inline NSString *LocalizationNotNeeded(NSString *s) { if ([IMKInputController instancesRespondToSelector:@selector(showPreferences:)]) { [super showPreferences:sender]; } else { - [(AppDelegate * )[ - NSApp - delegate] showPreferences]; + [(AppDelegate *) NSApp.delegate showPreferences]; } [[NSApplication sharedApplication] activateIgnoringOtherApps:YES]; } @@ -504,10 +501,7 @@ static inline NSString *LocalizationNotNeeded(NSString *s) { - (void)toggleChineseConverter:(id)sender { BOOL chineseConversionEnabled = [Preferences toggleChineseConversionEnabled]; - [NotifierController notifyWithMessage: - chineseConversionEnabled ? - NSLocalizedString(@"Chinese conversion on", @"") : - NSLocalizedString(@"Chinese conversion off", @"") stay:NO]; + [NotifierController notifyWithMessage:chineseConversionEnabled ? NSLocalizedString(@"Chinese conversion on", @"") : NSLocalizedString(@"Chinese conversion off", @"") stay:NO]; } - (void)toggleHalfWidthPunctuation:(id)sender @@ -527,7 +521,7 @@ static inline NSString *LocalizationNotNeeded(NSString *s) { - (void)checkForUpdate:(id)sender { - [(AppDelegate * )[[NSApplication sharedApplication] delegate] checkForUpdateForced:YES]; + [(AppDelegate *) NSApp.delegate checkForUpdateForced:YES]; } - (BOOL)_checkUserFiles @@ -614,11 +608,11 @@ static inline NSString *LocalizationNotNeeded(NSString *s) { InputStateChoosingCandidate *state = (InputStateChoosingCandidate *) _state; // candidate selected, override the node with selection - string selectedValue = [[state.candidates objectAtIndex:index] UTF8String]; - [_keyHandler fixNodeWithvalue:selectedValue]; + string selectedValue = [state.candidates[index] UTF8String]; + [_keyHandler fixNodeWithValue:selectedValue]; InputStateInputting *inputting = [_keyHandler _buildInputtingState]; - if ([_keyHandler inputMode] == kPlainBopomofoModeIdentifier) { + if (_keyHandler.inputMode == kPlainBopomofoModeIdentifier) { [_keyHandler clear]; InputStateCommitting *committing = [[InputStateCommitting alloc] initWithPoppedText:inputting.composingBuffer]; [self handleState:committing client:_currentCandidateClient]; @@ -644,8 +638,8 @@ static inline NSString *LocalizationNotNeeded(NSString *s) { if (!state.validToWrite) { return NO; } - NSString *userphrase = state.userPhrase; - [LanguageModelManager writeUserPhrase:userphrase]; + NSString *userPhrase = state.userPhrase; + [LanguageModelManager writeUserPhrase:userPhrase]; return YES; } @@ -693,8 +687,8 @@ static inline NSString *LocalizationNotNeeded(NSString *s) { { NSRect lineHeightRect = NSMakeRect(0.0, 0.0, 16.0, 16.0); - NSInteger cursor = cursorIndex; - if (cursor == [composingBuffer length] && cursor != 0) { + NSUInteger cursor = (NSUInteger) cursorIndex; + if (cursor == composingBuffer.length && cursor != 0) { cursor--; } @@ -717,4 +711,3 @@ static inline NSString *LocalizationNotNeeded(NSString *s) { } @end - diff --git a/Source/InputState.swift b/Source/InputState.swift index 0e0d5e9c..506178b2 100644 --- a/Source/InputState.swift +++ b/Source/InputState.swift @@ -27,23 +27,23 @@ import Cocoa class InputState: NSObject { } -/// Represents that the input controller is deactive. -class InputStateDeactive: InputState { +/// Represents that the input controller is deactivated. +class InputStateDeactivated: InputState { override var description: String { - return "" + "" } } /// Represents that the composing buffer is empty. class InputStateEmpty: InputState { - @objc var composingBuffer: String { + @objc var composingBuffer: String { "" } } /// Represents that the composing buffer is empty. class InputStateEmptyIgnoringPreviousState: InputState { - @objc var composingBuffer: String { + @objc var composingBuffer: String { "" } } @@ -58,7 +58,7 @@ class InputStateCommitting: InputState { } override var description: String { - return "" + "" } } @@ -73,14 +73,14 @@ class InputStateNotEmpty: InputState { } override var description: String { - return "" + "" } } /// Represents that the user is inputting text. class InputStateInputting: InputStateNotEmpty { @objc var bpmfReading: String = "" - @objc var bpmfReadingCursotIndex: UInt8 = 0 + @objc var bpmfReadingCursorIndex: UInt8 = 0 @objc var poppedText: String = "" @objc override init(composingBuffer: String, cursorIndex: UInt) { @@ -88,7 +88,7 @@ class InputStateInputting: InputStateNotEmpty { } @objc var attributedString: NSAttributedString { - let attributedSting = NSAttributedString(string: composingBuffer, attributes: [ + let attributedSting = NSAttributedString(string: composingBuffer, attributes: [ .underlineStyle: NSUnderlineStyle.single.rawValue, .markedClauseSegment: 0 ]) @@ -96,7 +96,7 @@ class InputStateInputting: InputStateNotEmpty { } override var description: String { - return "" + "" } } @@ -134,7 +134,7 @@ class InputStateMarking: InputStateNotEmpty { self.markerIndex = markerIndex let begin = min(cursorIndex, markerIndex) let end = max(cursorIndex, markerIndex) - self.markedRange = NSMakeRange(Int(begin), Int(end - begin)) + markedRange = NSMakeRange(Int(begin), Int(end - begin)) super.init(composingBuffer: composingBuffer, cursorIndex: cursorIndex) } @@ -154,12 +154,12 @@ class InputStateMarking: InputStateNotEmpty { .underlineStyle: NSUnderlineStyle.single.rawValue, .markedClauseSegment: 2 ], range: NSRange(location: end, - length: composingBuffer.count - end)) + length: composingBuffer.count - end)) return attributedSting } override var description: String { - return "" + "" } @objc func convertToInputting() -> InputStateInputting { @@ -168,7 +168,7 @@ class InputStateMarking: InputStateNotEmpty { } @objc var validToWrite: Bool { - return self.markedRange.length >= kMinMarkRangeLength && self.markedRange.length <= kMaxMarkRangeLength + markedRange.length >= kMinMarkRangeLength && markedRange.length <= kMaxMarkRangeLength } @objc var userPhrase: String { @@ -192,7 +192,7 @@ class InputStateChoosingCandidate: InputStateNotEmpty { } @objc var attributedString: NSAttributedString { - let attributedSting = NSAttributedString(string: composingBuffer, attributes: [ + let attributedSting = NSAttributedString(string: composingBuffer, attributes: [ .underlineStyle: NSUnderlineStyle.single.rawValue, .markedClauseSegment: 0 ]) @@ -200,6 +200,6 @@ class InputStateChoosingCandidate: InputStateNotEmpty { } override var description: String { - return "" + "" } } diff --git a/Source/KeyHandler.h b/Source/KeyHandler.h index 952a1a2c..ac0e85e8 100644 --- a/Source/KeyHandler.h +++ b/Source/KeyHandler.h @@ -46,8 +46,8 @@ extern NSString *const kPlainBopomofoModeIdentifier; candidateSelectionCallback:(void (^)(void))candidateSelectionCallback errorCallback:(void (^)(void))errorCallback; -- (void)synchWithPrefereneces; -- (void)fixNodeWithvalue:(std::string)value; +- (void)syncWithPreferences; +- (void)fixNodeWithValue:(std::string)value; - (void)clear; - (InputStateInputting *)_buildInputtingState; diff --git a/Source/KeyHandler.mm b/Source/KeyHandler.mm index 97ea7389..bdfb137d 100644 --- a/Source/KeyHandler.mm +++ b/Source/KeyHandler.mm @@ -161,7 +161,7 @@ static NSString *const kGraphVizOutputfile = @"/tmp/McBopomofo-visualization.dot return self; } -- (void)synchWithPrefereneces +- (void)syncWithPreferences { NSInteger layout = Preferences.keyboardLayout; switch (layout) { @@ -190,7 +190,7 @@ static NSString *const kGraphVizOutputfile = @"/tmp/McBopomofo-visualization.dot _languageModel->setExternalConverterEnabled(Preferences.chineseConversionStyle == 1); } -- (void)fixNodeWithvalue:(std::string)value +- (void)fixNodeWithValue:(std::string)value { size_t cursorIndex = [self _actualCandidateCursorIndex]; _builder->grid().fixNodeSelectedCandidate(cursorIndex, value); @@ -226,7 +226,7 @@ static NSString *const kGraphVizOutputfile = @"/tmp/McBopomofo-visualization.dot } // if the composing buffer is empty and there's no reading, and there is some function key combination, we ignore it - BOOL isFunctionKey = ([input isCommandHold] || [input isControlHold] || [input isOptionlHold] || [input isNumericPad]); + BOOL isFunctionKey = ([input isCommandHold] || [input isControlHold] || [input isOptionHold] || [input isNumericPad]); if (![state isKindOfClass:[InputStateNotEmpty class]] && isFunctionKey) { return NO; } @@ -258,7 +258,7 @@ static NSString *const kGraphVizOutputfile = @"/tmp/McBopomofo-visualization.dot } if ([input isNumericPad]) { - if (![input isLeft] && ![input isRight] && ![input isDown] && ![input isUp] && charCode != 32 && isprint(charCode)) { + if (![input isLeft] && ![input isRight] && ![input isDown] && ![input isUp] && charCode != 32 && isprint(charCode)) { [self clear]; InputStateEmpty *emptyState = [[InputStateEmpty alloc] init]; stateCallback(emptyState); @@ -276,8 +276,8 @@ static NSString *const kGraphVizOutputfile = @"/tmp/McBopomofo-visualization.dot // MARK: Handle Marking if ([state isKindOfClass:[InputStateMarking class]]) { - InputStateMarking *marking = (InputStateMarking *)state; - if ([self _handleMarkingState:(InputStateMarking *)state input:input stateCallback:stateCallback candidateSelectionCallback:candidateSelectionCallback errorCallback:errorCallback]) { + InputStateMarking *marking = (InputStateMarking *) state; + if ([self _handleMarkingState:(InputStateMarking *) state input:input stateCallback:stateCallback candidateSelectionCallback:candidateSelectionCallback errorCallback:errorCallback]) { return YES; } state = [marking convertToInputting]; @@ -325,7 +325,7 @@ static NSString *const kGraphVizOutputfile = @"/tmp/McBopomofo-visualization.dot // get user override model suggestion string overrideValue = (_inputMode == kPlainBopomofoModeIdentifier) ? "" : - _userOverrideModel->suggest(_walkedNodes, _builder->cursorIndex(), [[NSDate date] timeIntervalSince1970]); + _userOverrideModel->suggest(_walkedNodes, _builder->cursorIndex(), [[NSDate date] timeIntervalSince1970]); if (!overrideValue.empty()) { size_t cursorIndex = [self _actualCandidateCursorIndex]; @@ -353,15 +353,15 @@ static NSString *const kGraphVizOutputfile = @"/tmp/McBopomofo-visualization.dot // MARK: Space and Down // keyCode 125 = Down, charCode 32 = Space if (_bpmfReadingBuffer->isEmpty() && - [state isKindOfClass:[InputStateNotEmpty class]] && - ([input isExtraChooseCandidateKey] || charCode == 32 || (input.useVerticalMode && ([input isVerticalModeOnlyChooseCandidateKey])))) { + [state isKindOfClass:[InputStateNotEmpty class]] && + ([input isExtraChooseCandidateKey] || charCode == 32 || (input.useVerticalMode && ([input isVerticalModeOnlyChooseCandidateKey])))) { if (charCode == 32) { // if the spacebar is NOT set to be a selection key if ([input isShiftHold] || !Preferences.chooseCandidateUsingSpace) { if (_builder->cursorIndex() >= _builder->length()) { [self clear]; - InputStateCommitting *commiting = [[InputStateCommitting alloc] initWithPoppedText:@" "]; - stateCallback(commiting); + InputStateCommitting *committing = [[InputStateCommitting alloc] initWithPoppedText:@" "]; + stateCallback(committing); InputStateEmpty *empty = [[InputStateEmpty alloc] init]; stateCallback(empty); } else if (_languageModel->hasUnigramsForKey(" ")) { @@ -436,8 +436,7 @@ static NSString *const kGraphVizOutputfile = @"/tmp/McBopomofo-visualization.dot stateCallback(inputting); InputStateChoosingCandidate *choosingCandidate = [self _buildCandidateState:inputting useVerticalMode:input.useVerticalMode]; stateCallback(choosingCandidate); - } - else { // If there is still unfinished bpmf reading, ignore the punctuation + } else { // If there is still unfinished bpmf reading, ignore the punctuation errorCallback(); } return YES; @@ -483,7 +482,7 @@ static NSString *const kGraphVizOutputfile = @"/tmp/McBopomofo-visualization.dot BOOL escToClearInputBufferEnabled = Preferences.escToCleanInputBuffer; if (escToClearInputBufferEnabled) { - // if the optioon is enabled, we clear everythiong including the composing + // if the option is enabled, we clear everything including the composing // buffer, walked nodes and the reading. [self clear]; InputStateEmpty *empty = [[InputStateEmpty alloc] init]; @@ -712,7 +711,7 @@ static NSString *const kGraphVizOutputfile = @"/tmp/McBopomofo-visualization.dot return NO; } - NSString *poppedText = @""; + NSString *poppedText; if (_bpmfReadingBuffer->isEmpty()) { _builder->insertReadingAtCursor(customPunctuation); poppedText = [self _popOverflowComposingTextAndWalk]; @@ -721,6 +720,7 @@ static NSString *const kGraphVizOutputfile = @"/tmp/McBopomofo-visualization.dot stateCallback(state); return YES; } + InputStateInputting *inputting = [self _buildInputtingState]; inputting.poppedText = poppedText; stateCallback(inputting); @@ -750,7 +750,6 @@ static NSString *const kGraphVizOutputfile = @"/tmp/McBopomofo-visualization.dot { UniChar charCode = input.charCode; - if (charCode == 27) { InputStateInputting *inputting = [self _buildInputtingState]; stateCallback(inputting); @@ -770,7 +769,7 @@ static NSString *const kGraphVizOutputfile = @"/tmp/McBopomofo-visualization.dot // Shift + left if (([input isCursorBackward] || input.emacsKey == McBopomofoEmacsKeyBackward) - && ([input isShiftHold])) { + && ([input isShiftHold])) { NSUInteger index = state.markerIndex; if (index > 0) { index -= 1; @@ -786,7 +785,7 @@ static NSString *const kGraphVizOutputfile = @"/tmp/McBopomofo-visualization.dot // Shift + Right if (([input isCursorForward] || input.emacsKey == McBopomofoEmacsKeyForward) - && ([input isShiftHold])) { + && ([input isShiftHold])) { NSUInteger index = state.markerIndex; if (index < state.composingBuffer.length) { index += 1; @@ -814,7 +813,7 @@ static NSString *const kGraphVizOutputfile = @"/tmp/McBopomofo-visualization.dot VTCandidateController *gCurrentCandidateController = [self.delegate candidateControllerForKeyHanlder:self]; BOOL cancelCandidateKey = (charCode == 27) || [input isDelete] || - ((_inputMode == kPlainBopomofoModeIdentifier) && (charCode == 8)); + ((_inputMode == kPlainBopomofoModeIdentifier) && (charCode == 8)); if (cancelCandidateKey) { if (_inputMode == kPlainBopomofoModeIdentifier) { @@ -979,7 +978,7 @@ static NSString *const kGraphVizOutputfile = @"/tmp/McBopomofo-visualization.dot string punctuation = string("_punctuation_") + string(1, (char) charCode); BOOL shouldAutoSelectCandidate = _bpmfReadingBuffer->isValidKey((char) charCode) || _languageModel->hasUnigramsForKey(customPunctuation) || - _languageModel->hasUnigramsForKey(punctuation); + _languageModel->hasUnigramsForKey(punctuation); if (shouldAutoSelectCandidate) { NSUInteger candidateIndex = [gCurrentCandidateController candidateIndexAtKeyLabelIndex:0]; @@ -1026,7 +1025,7 @@ static NSString *const kGraphVizOutputfile = @"/tmp/McBopomofo-visualization.dot // (the actual cursor on the screen) with the builder's logical // cursor (reading) cursor; each built node has a "spanning length" // (e.g. two reading blocks has a spanning length of 2), and we - // accumulate those lengthes to calculate the displayed cursor + // accumulate those lengths to calculate the displayed cursor // index size_t spanningLength = (*wi).spanningLength; if (readingCursorIndex + spanningLength <= builderCursorIndex) { @@ -1083,7 +1082,7 @@ static NSString *const kGraphVizOutputfile = @"/tmp/McBopomofo-visualization.dot // but because the Viterbi algorithm has a complexity of O(N^2), // the walk will become slower as the number of nodes increase, // therefore we need to "pop out" overflown text -- they usually - // lose their influence over the whole MLE anyway -- so tht when + // lose their influence over the whole MLE anyway -- so that when // the user type along, the already composed text at front will // be popped out @@ -1145,7 +1144,7 @@ static NSString *const kGraphVizOutputfile = @"/tmp/McBopomofo-visualization.dot { NSMutableArray *readingsArray = [[NSMutableArray alloc] init]; vector v = _builder->readings(); - for(vector::iterator it_i=v.begin(); it_i!=v.end(); ++it_i) { + for (vector::iterator it_i = v.begin(); it_i != v.end(); ++it_i) { [readingsArray addObject:[NSString stringWithUTF8String:it_i->c_str()]]; } return readingsArray; diff --git a/Source/KeyHandlerInput.swift b/Source/KeyHandlerInput.swift index 7d3183c4..4d3b4cab 100644 --- a/Source/KeyHandlerInput.swift +++ b/Source/KeyHandlerInput.swift @@ -37,7 +37,7 @@ enum KeyCode: UInt16 { case delete = 117 } -@objc class KeyHandlerInput: NSObject { +class KeyHandlerInput: NSObject { @objc private (set) var useVerticalMode: Bool @objc private (set) var inputText: String? @objc private (set) var charCode: UInt16 @@ -55,21 +55,21 @@ enum KeyCode: UInt16 { self.keyCode = keyCode self.charCode = charCode self.flags = flags - self.useVerticalMode = isVerticalMode - self.emacsKey = EmacsKeyHelper.detect(charCode: charCode, flags: flags) - self.cursorForwardKey = useVerticalMode ? .down : .right - self.cursorBackwardKey = useVerticalMode ? .up : .left - self.extraChooseCandidateKey = useVerticalMode ? .left : .down - self.absorbedArrowKey = useVerticalMode ? .right : .up - self.verticalModeOnlyChooseCandidateKey = useVerticalMode ? absorbedArrowKey : .none + useVerticalMode = isVerticalMode + emacsKey = EmacsKeyHelper.detect(charCode: charCode, flags: flags) + cursorForwardKey = useVerticalMode ? .down : .right + cursorBackwardKey = useVerticalMode ? .up : .left + extraChooseCandidateKey = useVerticalMode ? .left : .down + absorbedArrowKey = useVerticalMode ? .right : .up + verticalModeOnlyChooseCandidateKey = useVerticalMode ? absorbedArrowKey : .none super.init() } @objc init(event: NSEvent, isVerticalMode: Bool) { - self.inputText = event.characters - self.keyCode = event.keyCode - self.flags = event.modifierFlags - self.useVerticalMode = isVerticalMode + inputText = event.characters + keyCode = event.keyCode + flags = event.modifierFlags + useVerticalMode = isVerticalMode let charCode: UInt16 = { guard let inputText = event.characters, inputText.count > 0 else { return 0 @@ -78,98 +78,98 @@ enum KeyCode: UInt16 { return first }() self.charCode = charCode - self.emacsKey = EmacsKeyHelper.detect(charCode: charCode, flags: event.modifierFlags) - self.cursorForwardKey = useVerticalMode ? .down : .right - self.cursorBackwardKey = useVerticalMode ? .up : .left - self.extraChooseCandidateKey = useVerticalMode ? .left : .down - self.absorbedArrowKey = useVerticalMode ? .right : .up - self.verticalModeOnlyChooseCandidateKey = useVerticalMode ? absorbedArrowKey : .none + emacsKey = EmacsKeyHelper.detect(charCode: charCode, flags: event.modifierFlags) + cursorForwardKey = useVerticalMode ? .down : .right + cursorBackwardKey = useVerticalMode ? .up : .left + extraChooseCandidateKey = useVerticalMode ? .left : .down + absorbedArrowKey = useVerticalMode ? .right : .up + verticalModeOnlyChooseCandidateKey = useVerticalMode ? absorbedArrowKey : .none super.init() - NSLog("self.keyCode \(self.keyCode)") + NSLog("self.keyCode \(keyCode)") } @objc var isShiftHold: Bool { - self.flags.contains([.shift]) + flags.contains([.shift]) } @objc var isCommandHold: Bool { - self.flags.contains([.command]) + flags.contains([.command]) } @objc var isControlHold: Bool { - self.flags.contains([.control]) + flags.contains([.control]) } - @objc var isOptionlHold: Bool { - self.flags.contains([.option]) + @objc var isOptionHold: Bool { + flags.contains([.option]) } @objc var isCapsLockOn: Bool { - self.flags.contains([.capsLock]) + flags.contains([.capsLock]) } @objc var isNumericPad: Bool { - self.flags.contains([.numericPad]) + flags.contains([.numericPad]) } @objc var isEnter: Bool { - KeyCode(rawValue: self.keyCode) == KeyCode.enter + KeyCode(rawValue: keyCode) == KeyCode.enter } @objc var isUp: Bool { - KeyCode(rawValue: self.keyCode) == KeyCode.up + KeyCode(rawValue: keyCode) == KeyCode.up } @objc var isDown: Bool { - KeyCode(rawValue: self.keyCode) == KeyCode.down + KeyCode(rawValue: keyCode) == KeyCode.down } @objc var isLeft: Bool { - KeyCode(rawValue: self.keyCode) == KeyCode.left + KeyCode(rawValue: keyCode) == KeyCode.left } @objc var isRight: Bool { - KeyCode(rawValue: self.keyCode) == KeyCode.right + KeyCode(rawValue: keyCode) == KeyCode.right } @objc var isPageUp: Bool { - KeyCode(rawValue: self.keyCode) == KeyCode.pageUp + KeyCode(rawValue: keyCode) == KeyCode.pageUp } @objc var isPageDown: Bool { - KeyCode(rawValue: self.keyCode) == KeyCode.pageDown + KeyCode(rawValue: keyCode) == KeyCode.pageDown } @objc var isHome: Bool { - KeyCode(rawValue: self.keyCode) == KeyCode.home + KeyCode(rawValue: keyCode) == KeyCode.home } @objc var isEnd: Bool { - KeyCode(rawValue: self.keyCode) == KeyCode.end + KeyCode(rawValue: keyCode) == KeyCode.end } @objc var isDelete: Bool { - KeyCode(rawValue: self.keyCode) == KeyCode.delete + KeyCode(rawValue: keyCode) == KeyCode.delete } @objc var isCursorBackward: Bool { - KeyCode(rawValue: self.keyCode) == cursorBackwardKey + KeyCode(rawValue: keyCode) == cursorBackwardKey } @objc var isCursorForward: Bool { - KeyCode(rawValue: self.keyCode) == cursorForwardKey + KeyCode(rawValue: keyCode) == cursorForwardKey } @objc var isAbsorbedArrowKey: Bool { - KeyCode(rawValue: self.keyCode) == absorbedArrowKey + KeyCode(rawValue: keyCode) == absorbedArrowKey } @objc var isExtraChooseCandidateKey: Bool { - KeyCode(rawValue: self.keyCode) == extraChooseCandidateKey + KeyCode(rawValue: keyCode) == extraChooseCandidateKey } @objc var isVerticalModeOnlyChooseCandidateKey: Bool { - KeyCode(rawValue: self.keyCode) == verticalModeOnlyChooseCandidateKey + KeyCode(rawValue: keyCode) == verticalModeOnlyChooseCandidateKey } } diff --git a/Source/LanguageModelManager.mm b/Source/LanguageModelManager.mm index b4306bb8..632617da 100644 --- a/Source/LanguageModelManager.mm +++ b/Source/LanguageModelManager.mm @@ -22,20 +22,13 @@ // OTHER DEALINGS IN THE SOFTWARE. #import "LanguageModelManager.h" -#import -#import -#import -#import "OVStringHelper.h" -#import "OVUTF8Helper.h" #import "McBopomofo-Swift.h" @import VXHanConvert; @import OpenCCBridge; using namespace std; -using namespace Formosa::Gramambular; using namespace McBopomofo; -using namespace OpenVanilla; static const int kUserOverrideModelCapacity = 500; static const double kObservedOverrideHalflife = 5400.0; // 1.5 hr. @@ -218,7 +211,7 @@ static void LTLoadLanguageModelFile(NSString *filenameWithoutExtension, McBopomo + (NSString *)dataFolderPath { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDirectory, YES); - NSString *appSupportPath = [paths objectAtIndex:0]; + NSString *appSupportPath = paths[0]; NSString *userDictPath = [appSupportPath stringByAppendingPathComponent:@"McBopomofo"]; return userDictPath; }