From 382369390ad0d1f95dfe8451880a8c1779fb0c96 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B1=85=E6=88=8E=E6=B0=8F?= Date: Tue, 27 Feb 2024 12:41:44 +0800 Subject: [PATCH 1/5] chore(deps): update librime for `make install` fix --- librime | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/librime b/librime index 872cecf7f..888e63821 160000 --- a/librime +++ b/librime @@ -1 +1 @@ -Subproject commit 872cecf7f92b6afab7618a4b01e2d8c8f7f7bd7c +Subproject commit 888e638210d3fbf6600395f489647077c523f85a From 3c806fb146a61b0c58c54328e69c66cc8c531dd9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B1=85=E6=88=8E=E6=B0=8F?= Date: Sun, 3 Mar 2024 22:21:52 +0800 Subject: [PATCH 2/5] build(librime): install merged-plugins build --- Makefile | 2 +- librime | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Makefile b/Makefile index 9d1758a9e..c9e48ea01 100644 --- a/Makefile +++ b/Makefile @@ -39,7 +39,7 @@ $(RIME_DEPS): $(MAKE) -C librime deps librime: $(RIME_DEPS) - $(MAKE) -C librime install + $(MAKE) -C librime merged-plugins install $(MAKE) copy-rime-binaries copy-rime-binaries: diff --git a/librime b/librime index 888e63821..33ce2459f 160000 --- a/librime +++ b/librime @@ -1 +1 @@ -Subproject commit 888e638210d3fbf6600395f489647077c523f85a +Subproject commit 33ce2459f82e2e99ac6232a11424d883a4119894 From d376884bcba44c903957781ccc5e2ac8c46d88e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B1=85=E6=88=8E=E6=B0=8F?= Date: Wed, 6 Mar 2024 17:30:41 +0800 Subject: [PATCH 3/5] build(librime): switch to release build dynamic loading plugin libraries from Frameworks/rime-plugins/. --- Makefile | 2 +- librime | 2 +- plum | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Makefile b/Makefile index c9e48ea01..f2314cea0 100644 --- a/Makefile +++ b/Makefile @@ -39,7 +39,7 @@ $(RIME_DEPS): $(MAKE) -C librime deps librime: $(RIME_DEPS) - $(MAKE) -C librime merged-plugins install + $(MAKE) -C librime release install $(MAKE) copy-rime-binaries copy-rime-binaries: diff --git a/librime b/librime index 33ce2459f..102d42174 160000 --- a/librime +++ b/librime @@ -1 +1 @@ -Subproject commit 33ce2459f82e2e99ac6232a11424d883a4119894 +Subproject commit 102d42174c2b2d793096621efa571328525c2ed3 diff --git a/plum b/plum index ff888cbb9..6f502ff6f 160000 --- a/plum +++ b/plum @@ -1 +1 @@ -Subproject commit ff888cbb9fce8c3f5b8b355baeb10685b2052b43 +Subproject commit 6f502ff6fa87789847fa18200415318e705bffa4 From 32d4d88ea947ea73530d9e8f8082a8b3e9edf271 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B1=85=E6=88=8E=E6=B0=8F?= Date: Wed, 6 Mar 2024 17:34:24 +0800 Subject: [PATCH 4/5] Revert "Add App Sandbox support." This reverts commit 28ad0666fb465d5dd71ba3126be8958f6a1cc19b. breaks multiple functions. --- Squirrel.entitlements | 20 -------------------- Squirrel.xcodeproj/project.pbxproj | 4 ---- 2 files changed, 24 deletions(-) delete mode 100644 Squirrel.entitlements diff --git a/Squirrel.entitlements b/Squirrel.entitlements deleted file mode 100644 index 4e847e0c5..000000000 --- a/Squirrel.entitlements +++ /dev/null @@ -1,20 +0,0 @@ - - - - - com.apple.security.temporary-exception.files.home-relative-path.read-write - - /Library/Rime/ - - com.apple.security.temporary-exception.mach-register.global-name - Squirrel_1_Connection - com.apple.security.files.bookmarks.app-scope - - com.apple.security.app-sandbox - - com.apple.security.files.user-selected.read-write - - com.apple.security.network.client - - - diff --git a/Squirrel.xcodeproj/project.pbxproj b/Squirrel.xcodeproj/project.pbxproj index 6ab67cf5d..6898ec0ae 100644 --- a/Squirrel.xcodeproj/project.pbxproj +++ b/Squirrel.xcodeproj/project.pbxproj @@ -232,7 +232,6 @@ 44F84AD614E94C490005D70B /* SquirrelPanel.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SquirrelPanel.m; sourceTree = ""; }; 44FA4D891685997300116C1F /* zh-Hans */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = "zh-Hans"; path = "zh-Hans.lproj/Localizable.strings"; sourceTree = ""; }; 44FA4D8E16859B2900116C1F /* zh-Hant */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = "zh-Hant"; path = "zh-Hant.lproj/Localizable.strings"; sourceTree = ""; }; - 5BCE17192B81D03D008C8D9E /* Squirrel.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Squirrel.entitlements; sourceTree = ""; }; 77AA67DC2588916300A592E2 /* HKVariants.ocd2 */ = {isa = PBXFileReference; lastKnownFileType = file; path = HKVariants.ocd2; sourceTree = ""; }; 77AA67DD2588916300A592E2 /* t2s.json */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.json; path = t2s.json; sourceTree = ""; }; 77AA67DE2588916300A592E2 /* t2tw.json */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.json; path = t2tw.json; sourceTree = ""; }; @@ -349,7 +348,6 @@ 29B97314FDCFA39411CA2CEA /* Squirrel */ = { isa = PBXGroup; children = ( - 5BCE17192B81D03D008C8D9E /* Squirrel.entitlements */, 442C648F1F7A40180027EFBE /* bin */, 44DA7A4214DD598900C1ED3B /* SharedSupport */, 080E96DDFE201D6D7F000001 /* Sources */, @@ -604,7 +602,6 @@ buildSettings = { CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_OBJC_ARC = YES; - CODE_SIGN_ENTITLEMENTS = Squirrel.entitlements; CODE_SIGN_IDENTITY = "-"; COMBINE_HIDPI_IMAGES = YES; COPY_PHASE_STRIP = NO; @@ -655,7 +652,6 @@ buildSettings = { CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_OBJC_ARC = YES; - CODE_SIGN_ENTITLEMENTS = Squirrel.entitlements; CODE_SIGN_IDENTITY = "-"; COMBINE_HIDPI_IMAGES = YES; CURRENT_PROJECT_VERSION = 0.17.2; From baeb4209ab93b183f1049c9459cffb55ffdc30e0 Mon Sep 17 00:00:00 2001 From: groverlynn Date: Mon, 26 Feb 2024 12:17:37 +0100 Subject: [PATCH 5/5] replace deprecated API calls --- .clang-format | 2 +- Squirrel.xcodeproj/project.pbxproj | 4 + SquirrelApplicationDelegate.h | 6 +- SquirrelApplicationDelegate.m | 101 ++++++++++++-------- SquirrelConfig.h | 6 +- SquirrelConfig.m | 62 ++++++------ SquirrelInputController.m | 148 +++++++++++++++-------------- SquirrelPanel.h | 6 +- SquirrelPanel.m | 82 ++++++++-------- input_source.m | 54 ++++++----- main.m | 19 ++-- 11 files changed, 264 insertions(+), 226 deletions(-) diff --git a/.clang-format b/.clang-format index 5cb45537d..f0b9df629 100644 --- a/.clang-format +++ b/.clang-format @@ -1,2 +1,2 @@ BasedOnStyle: Chromium -SortIncludes: false +SortIncludes: false \ No newline at end of file diff --git a/Squirrel.xcodeproj/project.pbxproj b/Squirrel.xcodeproj/project.pbxproj index 6898ec0ae..c1c4c593e 100644 --- a/Squirrel.xcodeproj/project.pbxproj +++ b/Squirrel.xcodeproj/project.pbxproj @@ -84,6 +84,7 @@ A4FC48CB0F6530EF0069BE81 /* Localizable.strings in Resources */ = {isa = PBXBuildFile; fileRef = A4FC48C90F6530EF0069BE81 /* Localizable.strings */; }; D26434552706A15100857391 /* QuartzCore.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = D26434542706A15100857391 /* QuartzCore.framework */; }; E93074B70A5C264700470842 /* InputMethodKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = E93074B60A5C264700470842 /* InputMethodKit.framework */; }; + F45E005F2B8CA81C00179B75 /* UserNotifications.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F45E005E2B8CA81C00179B75 /* UserNotifications.framework */; }; /* End PBXBuildFile section */ /* Begin PBXCopyFilesBuildPhase section */ @@ -278,6 +279,7 @@ A4FC48CA0F6530EF0069BE81 /* en */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.strings; name = en; path = en.lproj/Localizable.strings; sourceTree = ""; }; D26434542706A15100857391 /* QuartzCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = QuartzCore.framework; path = System/Library/Frameworks/QuartzCore.framework; sourceTree = SDKROOT; }; E93074B60A5C264700470842 /* InputMethodKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = InputMethodKit.framework; path = /System/Library/Frameworks/InputMethodKit.framework; sourceTree = ""; }; + F45E005E2B8CA81C00179B75 /* UserNotifications.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UserNotifications.framework; path = System/Library/Frameworks/UserNotifications.framework; sourceTree = SDKROOT; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -287,6 +289,7 @@ files = ( D26434552706A15100857391 /* QuartzCore.framework in Frameworks */, 8D11072F0486CEB800E47090 /* Cocoa.framework in Frameworks */, + F45E005F2B8CA81C00179B75 /* UserNotifications.framework in Frameworks */, E93074B70A5C264700470842 /* InputMethodKit.framework in Frameworks */, A4B8E1B30F645B870094E08B /* Carbon.framework in Frameworks */, 447765C925C30E97002415AF /* Sparkle.framework in Frameworks */, @@ -379,6 +382,7 @@ 29B97323FDCFA39411CA2CEA /* Frameworks */ = { isa = PBXGroup; children = ( + F45E005E2B8CA81C00179B75 /* UserNotifications.framework */, D26434542706A15100857391 /* QuartzCore.framework */, 1058C7A0FEA54F0111CA2CBB /* Linked Frameworks */, 1058C7A2FEA54F0111CA2CBB /* Other Frameworks */, diff --git a/SquirrelApplicationDelegate.h b/SquirrelApplicationDelegate.h index 5708459f8..d6284c10b 100644 --- a/SquirrelApplicationDelegate.h +++ b/SquirrelApplicationDelegate.h @@ -7,9 +7,9 @@ // outlet of NSApp's instance @interface SquirrelApplicationDelegate : NSObject -@property(nonatomic, copy) IBOutlet NSMenu* menu; -@property(nonatomic, strong) IBOutlet SquirrelPanel* panel; -@property(nonatomic, strong) IBOutlet id updater; +@property(nonatomic, weak) IBOutlet NSMenu* menu; +@property(nonatomic, weak) IBOutlet SquirrelPanel* panel; +@property(nonatomic, weak) IBOutlet id updater; @property(nonatomic, readonly, strong) SquirrelConfig* config; @property(nonatomic, readonly) BOOL enableNotifications; diff --git a/SquirrelApplicationDelegate.m b/SquirrelApplicationDelegate.m index 75b0ef619..647f76de0 100644 --- a/SquirrelApplicationDelegate.m +++ b/SquirrelApplicationDelegate.m @@ -3,6 +3,7 @@ #import #import "SquirrelConfig.h" #import "SquirrelPanel.h" +#import static NSString* const kRimeWikiURL = @"https://github.com/rime/home/wiki"; @@ -22,10 +23,9 @@ - (IBAction)syncUserData:(id)sender { - (IBAction)configure:(id)sender { [[NSWorkspace sharedWorkspace] - openURL:[NSURL URLWithString:[@"file://" - stringByAppendingString: - (@"~/Library/Rime") - .stringByStandardizingPath]]]; + openURL:[NSURL fileURLWithPath:@"~/Library/Rime/" + .stringByExpandingTildeInPath + isDirectory:YES]]; } - (IBAction)openWiki:(id)sender { @@ -33,30 +33,50 @@ - (IBAction)openWiki:(id)sender { } void show_message(const char* msg_text, const char* msg_id) { - @autoreleasepool { - id notification = [[NSClassFromString(@"NSUserNotification") alloc] init]; - [notification performSelector:@selector(setTitle:) - withObject:NSLocalizedString(@"Squirrel", nil)]; - [notification performSelector:@selector(setSubtitle:) - withObject:NSLocalizedString(@(msg_text), nil)]; - id notificationCenter = [(id)NSClassFromString(@"NSUserNotificationCenter") - performSelector:@selector(defaultUserNotificationCenter)]; - [notificationCenter - performSelector:@selector(removeAllDeliveredNotifications)]; - [notificationCenter performSelector:@selector(deliverNotification:) - withObject:notification]; - } + UNUserNotificationCenter* center = + UNUserNotificationCenter.currentNotificationCenter; + [center requestAuthorizationWithOptions:UNAuthorizationOptionAlert | + UNAuthorizationOptionProvisional + completionHandler:^(BOOL granted, NSError* error) { + if (error) { + NSLog(@"User notification authorization error: %@", + error.debugDescription); + } + }]; + [center getNotificationSettingsWithCompletionHandler:^( + UNNotificationSettings* settings) { + if ((settings.authorizationStatus == UNAuthorizationStatusAuthorized || + settings.authorizationStatus == UNAuthorizationStatusProvisional) && + (settings.alertSetting == UNNotificationSettingEnabled)) { + UNMutableNotificationContent* content = + [[UNMutableNotificationContent alloc] init]; + content.title = NSLocalizedString(@"Squirrel", nil); + content.subtitle = NSLocalizedString(@(msg_text), nil); + if (@available(macOS 12.0, *)) { + content.interruptionLevel = UNNotificationInterruptionLevelActive; + } + UNNotificationRequest* request = + [UNNotificationRequest requestWithIdentifier:@"SquirrelNotification" + content:content + trigger:nil]; + [center addNotificationRequest:request + withCompletionHandler:^(NSError* error) { + if (error) { + NSLog(@"User notification request error: %@", + error.debugDescription); + } + }]; + } + }]; } static void show_status_message(const char* msg_text_long, const char* msg_text_short, const char* msg_id) { SquirrelPanel* panel = NSApp.squirrelAppDelegate.panel; - if (panel) { - NSString* msgLong = msg_text_long ? @(msg_text_long) : nil; - NSString* msgShort = msg_text_short ? @(msg_text_short) : nil; - [panel updateStatusLong:msgLong statusShort:msgShort]; - } + NSString* msgLong = msg_text_long ? @(msg_text_long) : nil; + NSString* msgShort = msg_text_short ? @(msg_text_short) : nil; + [panel updateStatusLong:msgLong statusShort:msgShort]; } void notification_handler(void* context_object, @@ -74,7 +94,7 @@ void notification_handler(void* context_object, return; } // off? - id app_delegate = (__bridge id)context_object; + SquirrelApplicationDelegate* app_delegate = (__bridge id)context_object; if (app_delegate && ![app_delegate enableNotifications]) { return; } @@ -93,10 +113,10 @@ void notification_handler(void* context_object, const char* option_name = message_value + !state; struct rime_string_slice_t state_label_long = rime_get_api()->get_state_label_abbreviated(session_id, option_name, - state, NO); + state, False); struct rime_string_slice_t state_label_short = rime_get_api()->get_state_label_abbreviated(session_id, option_name, - state, YES); + state, True); if (state_label_long.str || state_label_short.str) { const char* short_message = @@ -109,13 +129,13 @@ void notification_handler(void* context_object, } - (void)setupRime { - NSString* userDataDir = (@"~/Library/Rime").stringByStandardizingPath; + NSString* userDataDir = @"~/Library/Rime".stringByExpandingTildeInPath; NSFileManager* fileManager = [NSFileManager defaultManager]; if (![fileManager fileExistsAtPath:userDataDir]) { if (![fileManager createDirectoryAtPath:userDataDir withIntermediateDirectories:YES attributes:nil - error:NULL]) { + error:nil]) { NSLog(@"Error creating user data directory: %@", userDataDir); } } @@ -127,8 +147,8 @@ - (void)setupRime { squirrel_traits.user_data_dir = userDataDir.UTF8String; squirrel_traits.distribution_code_name = "Squirrel"; squirrel_traits.distribution_name = "鼠鬚管"; - squirrel_traits.distribution_version = - [[NSBundle mainBundle].infoDictionary[@"CFBundleVersion"] UTF8String]; + squirrel_traits.distribution_version = [[[NSBundle mainBundle] + objectForInfoDictionaryKey:(NSString*)kCFBundleVersionKey] UTF8String]; squirrel_traits.app_name = "rime.squirrel"; rime_get_api()->setup(&squirrel_traits); } @@ -187,26 +207,27 @@ - (void)loadSchemaSpecificSettings:(NSString*)schemaId { // prevent freezing the system - (BOOL)problematicLaunchDetected { BOOL detected = NO; - NSString* logfile = [NSTemporaryDirectory() - stringByAppendingPathComponent:@"squirrel_launch.dat"]; + NSURL* logfile = [[NSURL fileURLWithPath:NSTemporaryDirectory() + isDirectory:YES] + URLByAppendingPathComponent:@"squirrel_launch.dat"]; // NSLog(@"[DEBUG] archive: %@", logfile); - NSData* archive = [NSData dataWithContentsOfFile:logfile - options:NSDataReadingUncached - error:nil]; + NSData* archive = [NSData dataWithContentsOfURL:logfile + options:NSDataReadingUncached + error:nil]; if (archive) { NSDate* previousLaunch = [NSKeyedUnarchiver unarchivedObjectOfClass:NSDate.class fromData:archive - error:NULL]; - if (previousLaunch && previousLaunch.timeIntervalSinceNow >= -2) { + error:nil]; + if (previousLaunch.timeIntervalSinceNow >= -2) { detected = YES; } } NSDate* now = [NSDate date]; NSData* record = [NSKeyedArchiver archivedDataWithRootObject:now requiringSecureCoding:NO - error:NULL]; - [record writeToFile:logfile atomically:NO]; + error:nil]; + [record writeToURL:logfile atomically:NO]; return detected; } @@ -259,9 +280,7 @@ - (void)awakeFromNib { - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; [[NSDistributedNotificationCenter defaultCenter] removeObserver:self]; - if (_panel) { - [_panel hide]; - } + [_panel hide]; } @end // SquirrelApplicationDelegate diff --git a/SquirrelConfig.h b/SquirrelConfig.h index 03b229254..baca6c49d 100644 --- a/SquirrelConfig.h +++ b/SquirrelConfig.h @@ -6,8 +6,8 @@ typedef NSMutableDictionary SquirrelMutableAppOptions; @interface SquirrelConfig : NSObject @property(nonatomic, readonly) BOOL isOpen; -@property(nonatomic, copy) NSString* colorSpace; -@property(nonatomic, readonly) NSString* schemaId; +@property(nonatomic, strong) NSString* colorSpace; +@property(nonatomic, strong, readonly) NSString* schemaId; - (BOOL)openBaseConfig; - (BOOL)openWithSchemaId:(NSString*)schemaId baseConfig:(SquirrelConfig*)config; @@ -16,7 +16,7 @@ typedef NSMutableDictionary SquirrelMutableAppOptions; - (BOOL)hasSection:(NSString*)section; - (BOOL)getBool:(NSString*)option; -- (NSInteger)getInt:(NSString*)option; +- (int)getInt:(NSString*)option; - (double)getDouble:(NSString*)option; - (NSNumber*)getOptionalBool:(NSString*)option; - (NSNumber*)getOptionalInt:(NSString*)option; diff --git a/SquirrelConfig.m b/SquirrelConfig.m index 5e868a07b..7d26d75c1 100644 --- a/SquirrelConfig.m +++ b/SquirrelConfig.m @@ -5,28 +5,17 @@ @implementation SquirrelConfig { NSMutableDictionary* _cache; RimeConfig _config; - NSString* _schemaId; SquirrelConfig* _baseConfig; - BOOL _isOpen; } - (instancetype)init { - self = [super init]; - if (self) { + if (self = [super init]) { _cache = [[NSMutableDictionary alloc] init]; + _colorSpace = @"srgb"; } - self.colorSpace = @"srgb"; return self; } -- (BOOL)isOpen { - return _isOpen; -} - -- (NSString*)schemaId { - return _schemaId; -} - - (BOOL)openBaseConfig { [self close]; _isOpen = !!rime_get_api()->config_open("squirrel", &_config); @@ -52,6 +41,10 @@ - (void)close { } } +- (void)dealloc { + [self close]; +} + - (BOOL)hasSection:(NSString*)section { if (_isOpen) { RimeConfigIterator iterator = {0}; @@ -68,8 +61,8 @@ - (BOOL)getBool:(NSString*)option { return [self getOptionalBool:option].boolValue; } -- (NSInteger)getInt:(NSString*)option { - return [self getOptionalInt:option].integerValue; +- (int)getInt:(NSString*)option { + return [self getOptionalInt:option].intValue; } - (double)getDouble:(NSString*)option { @@ -77,8 +70,8 @@ - (double)getDouble:(NSString*)option { } - (NSNumber*)getOptionalBool:(NSString*)option { - NSNumber* cachedValue = [self cachedValueOfClass:[NSNumber class] - forKey:option]; + NSNumber* cachedValue = [self cachedValueOfObjCType:@encode(BOOL) + forKey:option]; if (cachedValue) { return cachedValue; } @@ -91,8 +84,8 @@ - (NSNumber*)getOptionalBool:(NSString*)option { } - (NSNumber*)getOptionalInt:(NSString*)option { - NSNumber* cachedValue = [self cachedValueOfClass:[NSNumber class] - forKey:option]; + NSNumber* cachedValue = [self cachedValueOfObjCType:@encode(int) + forKey:option]; if (cachedValue) { return cachedValue; } @@ -105,8 +98,8 @@ - (NSNumber*)getOptionalInt:(NSString*)option { } - (NSNumber*)getOptionalDouble:(NSString*)option { - NSNumber* cachedValue = [self cachedValueOfClass:[NSNumber class] - forKey:option]; + NSNumber* cachedValue = [self cachedValueOfObjCType:@encode(double) + forKey:option]; if (cachedValue) { return cachedValue; } @@ -167,7 +160,16 @@ - (SquirrelAppOptions*)getAppOptions:(NSString*)appName { - (id)cachedValueOfClass:(Class)aClass forKey:(NSString*)key { id value = [_cache objectForKey:key]; - if (value && [value isKindOfClass:aClass]) { + if ([value isMemberOfClass:aClass]) { + return value; + } + return nil; +} + +- (NSNumber*)cachedValueOfObjCType:(const char*)type forKey:(NSString*)key { + id value = [_cache objectForKey:key]; + if ([value isMemberOfClass:NSNumber.class] && + !strcmp([value objCType], type)) { return value; } return nil; @@ -187,15 +189,15 @@ - (NSColor*)colorFromString:(NSString*)string { sscanf(string.UTF8String, "0x%02x%02x%02x", &b, &g, &r); } if ([self.colorSpace isEqualToString:@"display_p3"]) { - return [NSColor colorWithDisplayP3Red:(CGFloat)r / 255. - green:(CGFloat)g / 255. - blue:(CGFloat)b / 255. - alpha:(CGFloat)a / 255.]; + return [NSColor colorWithDisplayP3Red:r / 255.0 + green:g / 255.0 + blue:b / 255.0 + alpha:a / 255.0]; } else { // sRGB by default - return [NSColor colorWithSRGBRed:(CGFloat)r / 255. - green:(CGFloat)g / 255. - blue:(CGFloat)b / 255. - alpha:(CGFloat)a / 255.]; + return [NSColor colorWithSRGBRed:r / 255.0 + green:g / 255.0 + blue:b / 255.0 + alpha:a / 255.0]; } } diff --git a/SquirrelInputController.m b/SquirrelInputController.m index 8568ae35e..69e9de150 100644 --- a/SquirrelInputController.m +++ b/SquirrelInputController.m @@ -18,12 +18,11 @@ - (void)updateAppOptions; const int N_KEY_ROLL_OVER = 50; @implementation SquirrelInputController { - id _currentClient; NSString* _preeditString; NSRange _selRange; NSUInteger _caretPos; - NSArray* _candidates; - NSUInteger _lastModifier; + NSArray* _candidates; + NSEventModifierFlags _lastModifier; NSEventType _lastEventType; RimeSessionId _session; NSString* _schemaId; @@ -49,9 +48,7 @@ - (BOOL)handleEvent:(NSEvent*)event client:(id)sender { // system will not deliver a key down event to the application. // Returning NO means the original key down will be passed on to the client. - _currentClient = sender; - - NSUInteger modifiers = event.modifierFlags; + NSEventModifierFlags modifiers = event.modifierFlags; BOOL handled = NO; @@ -63,7 +60,7 @@ - (BOOL)handleEvent:(NSEvent*)event client:(id)sender { } } - NSString* app = [_currentClient bundleIdentifier]; + NSString* app = [sender bundleIdentifier]; if (![_currentApp isEqualToString:app]) { _currentApp = [app copy]; @@ -82,15 +79,16 @@ - (BOOL)handleEvent:(NSEvent*)event client:(id)sender { int rime_keycode = 0; // For flags-changed event, keyCode is available since macOS 10.15 // (#715) - Bool keyCodeAvailable = NO; + BOOL keyCodeAvailable = NO; if (@available(macOS 10.15, *)) { keyCodeAvailable = YES; - rime_keycode = osx_keycode_to_rime_keycode(event.keyCode, 0, 0, 0); + rime_keycode = + osx_keycode_to_rime_keycode((int)event.keyCode, 0, 0, 0); // NSLog(@"keyCode: %d", event.keyCode); } int release_mask = 0; NSUInteger changes = _lastModifier ^ modifiers; - if (changes & OSX_CAPITAL_MASK) { + if (changes & NSEventModifierFlagCapsLock) { if (!keyCodeAvailable) { rime_keycode = XK_Caps_Lock; } @@ -100,35 +98,39 @@ - (BOOL)handleEvent:(NSEvent*)event client:(id)sender { rime_modifiers ^= kLockMask; [self processKey:rime_keycode modifiers:rime_modifiers]; } - if (changes & OSX_SHIFT_MASK) { + if (changes & NSEventModifierFlagShift) { if (!keyCodeAvailable) { rime_keycode = XK_Shift_L; } - release_mask = modifiers & OSX_SHIFT_MASK ? 0 : kReleaseMask; + release_mask = + modifiers & NSEventModifierFlagShift ? 0 : kReleaseMask; [self processKey:rime_keycode modifiers:(rime_modifiers | release_mask)]; } - if (changes & OSX_CTRL_MASK) { + if (changes & NSEventModifierFlagControl) { if (!keyCodeAvailable) { rime_keycode = XK_Control_L; } - release_mask = modifiers & OSX_CTRL_MASK ? 0 : kReleaseMask; + release_mask = + modifiers & NSEventModifierFlagControl ? 0 : kReleaseMask; [self processKey:rime_keycode modifiers:(rime_modifiers | release_mask)]; } - if (changes & OSX_ALT_MASK) { + if (changes & NSEventModifierFlagOption) { if (!keyCodeAvailable) { rime_keycode = XK_Alt_L; } - release_mask = modifiers & OSX_ALT_MASK ? 0 : kReleaseMask; + release_mask = + modifiers & NSEventModifierFlagOption ? 0 : kReleaseMask; [self processKey:rime_keycode modifiers:(rime_modifiers | release_mask)]; } - if (changes & OSX_COMMAND_MASK) { + if (changes & NSEventModifierFlagCommand) { if (!keyCodeAvailable) { rime_keycode = XK_Super_L; } - release_mask = modifiers & OSX_COMMAND_MASK ? 0 : kReleaseMask; + release_mask = + modifiers & NSEventModifierFlagCommand ? 0 : kReleaseMask; [self processKey:rime_keycode modifiers:(rime_modifiers | release_mask)]; // do not update UI when using Command key @@ -138,10 +140,11 @@ - (BOOL)handleEvent:(NSEvent*)event client:(id)sender { } break; case NSEventTypeKeyDown: { // ignore Command+X hotkeys. - if (modifiers & OSX_COMMAND_MASK) + if (modifiers & NSEventModifierFlagCommand) { break; + } - int keyCode = event.keyCode; + ushort keyCode = event.keyCode; NSString* keyChars = event.charactersIgnoringModifiers; if (!isalpha(keyChars.UTF8String[0])) { keyChars = event.characters; @@ -152,8 +155,9 @@ - (BOOL)handleEvent:(NSEvent*)event client:(id)sender { // translate osx keyevents to rime keyevents int rime_keycode = osx_keycode_to_rime_keycode( - keyCode, keyChars.UTF8String[0], modifiers & OSX_SHIFT_MASK, - modifiers & OSX_CAPITAL_MASK); + (int)keyCode, (int)keyChars.UTF8String[0], + (int)modifiers & NSEventModifierFlagShift, + (int)modifiers & NSEventModifierFlagCapsLock); if (rime_keycode) { int rime_modifiers = osx_modifiers_to_rime_modifiers(modifiers); handled = [self processKey:rime_keycode modifiers:rime_modifiers]; @@ -175,12 +179,12 @@ - (BOOL)processKey:(int)rime_keycode modifiers:(int)rime_modifiers { // TODO add special key event preprocessing here // with linear candidate list, arrow keys may behave differently. - Bool is_linear = NSApp.squirrelAppDelegate.panel.linear; + Bool is_linear = (Bool)NSApp.squirrelAppDelegate.panel.linear; if (is_linear != rime_get_api()->get_option(_session, "_linear")) { rime_get_api()->set_option(_session, "_linear", is_linear); } // with vertical text, arrow keys may behave differently. - Bool is_vertical = NSApp.squirrelAppDelegate.panel.vertical; + Bool is_vertical = (Bool)NSApp.squirrelAppDelegate.panel.vertical; if (is_vertical != rime_get_api()->get_option(_session, "_vertical")) { rime_get_api()->set_option(_session, "_vertical", is_vertical); } @@ -278,13 +282,13 @@ - (void)updateChord:(int)keycode modifiers:(int)modifiers { _chordModifiers[_chordKeyCount] = modifiers; ++_chordKeyCount; // reset timer - if (_chordTimer && _chordTimer.valid) { + if (_chordTimer.valid) { [_chordTimer invalidate]; } _chordDuration = 0.1; NSNumber* duration = [NSApp.squirrelAppDelegate.config getOptionalDouble:@"chord_duration"]; - if (duration && duration.doubleValue > 0) { + if (duration.doubleValue > 0) { _chordDuration = duration.doubleValue; } _chordTimer = [NSTimer scheduledTimerWithTimeInterval:_chordDuration @@ -296,10 +300,8 @@ - (void)updateChord:(int)keycode modifiers:(int)modifiers { - (void)clearChord { _chordKeyCount = 0; - if (_chordTimer) { - if (_chordTimer.valid) { - [_chordTimer invalidate]; - } + if (_chordTimer.valid) { + [_chordTimer invalidate]; _chordTimer = nil; } } @@ -315,7 +317,7 @@ - (void)activateServer:(id)sender { [NSApp.squirrelAppDelegate.config getString:@"keyboard_layout"]; if ([keyboardLayout isEqualToString:@"last"] || [keyboardLayout isEqualToString:@""]) { - keyboardLayout = NULL; + keyboardLayout = nil; } else if ([keyboardLayout isEqualToString:@"default"]) { keyboardLayout = @"com.apple.keylayout.ABC"; } else if (![keyboardLayout hasPrefix:@"com.apple.keylayout."]) { @@ -335,7 +337,6 @@ - (instancetype)initWithServer:(IMKServer*)server if (self = [super initWithServer:server delegate:delegate client:inputClient]) { - _currentClient = inputClient; [self createSession]; } return self; @@ -343,10 +344,15 @@ - (instancetype)initWithServer:(IMKServer*)server - (void)deactivateServer:(id)sender { // NSLog(@"deactivateServer:"); - [NSApp.squirrelAppDelegate.panel hide]; + [self hidePalettes]; [self commitComposition:sender]; } +- (void)hidePalettes { + [NSApp.squirrelAppDelegate.panel hide]; + [super hidePalettes]; +} + /*! @method @abstract Called when a user action was taken that ends an input session. @@ -410,12 +416,11 @@ - (void)dealloc { - (void)commitString:(NSString*)string { // NSLog(@"commitString:"); - [_currentClient insertText:string - replacementRange:NSMakeRange(NSNotFound, 0)]; + [self.client insertText:string replacementRange:NSMakeRange(NSNotFound, 0)]; _preeditString = @""; - [NSApp.squirrelAppDelegate.panel hide]; + [self hidePalettes]; } - (void)showPreeditString:(NSString*)preedit @@ -424,8 +429,9 @@ - (void)showPreeditString:(NSString*)preedit // NSLog(@"showPreeditString: '%@'", preedit); if ([_preeditString isEqualToString:preedit] && _caretPos == pos && - _selRange.location == range.location && _selRange.length == range.length) + NSEqualRanges(_selRange, range)) { return; + } _preeditString = preedit; _selRange = range; @@ -448,22 +454,22 @@ - (void)showPreeditString:(NSString*)preedit atRange:remainingRange]; [attrString setAttributes:attrs range:remainingRange]; } - [_currentClient setMarkedText:attrString - selectionRange:NSMakeRange(pos, 0) - replacementRange:NSMakeRange(NSNotFound, 0)]; + [self.client setMarkedText:attrString + selectionRange:NSMakeRange(pos, 0) + replacementRange:NSMakeRange(NSNotFound, NSNotFound)]; } - (void)showPanelWithPreedit:(NSString*)preedit selRange:(NSRange)selRange caretPos:(NSUInteger)caretPos - candidates:(NSArray*)candidates - comments:(NSArray*)comments - labels:(NSArray*)labels + candidates:(NSArray*)candidates + comments:(NSArray*)comments + labels:(NSArray*)labels highlighted:(NSUInteger)index { // NSLog(@"showPanelWithPreedit:...:"); _candidates = candidates; NSRect inputPos; - [_currentClient attributesForCharacterIndex:0 lineHeightRectangle:&inputPos]; + [self.client attributesForCharacterIndex:0 lineHeightRectangle:&inputPos]; SquirrelPanel* panel = NSApp.squirrelAppDelegate.panel; panel.position = inputPos; panel.inputController = self; @@ -483,7 +489,7 @@ - (void)showPanelWithPreedit:(NSString*)preedit @implementation SquirrelInputController (Private) - (void)createSession { - NSString* app = [_currentClient bundleIdentifier]; + NSString* app = [self.client bundleIdentifier]; NSLog(@"createSession: %@", app); _currentApp = [app copy]; _session = rime_get_api()->create_session(); @@ -528,10 +534,9 @@ - (void)rimeConsumeCommittedText { } NSString* substr(const char* str, int length) { - char substring[length + 1]; - strncpy(substring, str, length); - substring[length] = '\0'; - return [NSString stringWithCString:substring encoding:NSUTF8StringEncoding]; + return [[NSString alloc] initWithBytes:str + length:(NSUInteger)length + encoding:NSUTF8StringEncoding]; } - (void)rimeUpdate { @@ -590,15 +595,12 @@ - (void)rimeUpdate { if ((NSMaxRange(selRange) < caretPos) && (caretPos > selRange.location)) { candidatePreviewText = [candidatePreviewText - substringWithRange:NSMakeRange( - 0, candidatePreviewText.length - - (caretPos - NSMaxRange(selRange)))]; + substringToIndex:candidatePreviewText.length - (caretPos - end)]; } else if ((NSMaxRange(selRange) < preeditText.length) && (caretPos <= selRange.location)) { candidatePreviewText = [candidatePreviewText - substringWithRange:NSMakeRange(0, candidatePreviewText.length - - (preeditText.length - - NSMaxRange(selRange)))]; + substringToIndex:candidatePreviewText.length - + (preeditText.length - end)]; } [self showPreeditString:candidatePreviewText selRange:NSMakeRange(selRange.location, @@ -612,21 +614,22 @@ - (void)rimeUpdate { selRange:selRange caretPos:caretPos]; } else { - NSRange empty = {0, 0}; // TRICKY: display a non-empty string to prevent iTerm2 from echoing // each character in preedit. note this is a full-shape space U+3000; // using half shape characters like "..." will result in an unstable // baseline when composing Chinese characters. [self showPreeditString:(preedit ? @" " : @"") - selRange:empty + selRange:NSMakeRange(0, 0) caretPos:0]; } } // update candidates - NSMutableArray* candidates = [NSMutableArray array]; - NSMutableArray* comments = [NSMutableArray array]; - NSUInteger i; - for (i = 0; i < ctx.menu.num_candidates; ++i) { + NSUInteger numCandidates = (NSUInteger)ctx.menu.num_candidates; + NSMutableArray* candidates = + [[NSMutableArray alloc] initWithCapacity:numCandidates]; + NSMutableArray* comments = + [[NSMutableArray alloc] initWithCapacity:numCandidates]; + for (NSUInteger i = 0; i < (NSUInteger)ctx.menu.num_candidates; ++i) { [candidates addObject:@(ctx.menu.candidates[i].text)]; if (ctx.menu.candidates[i].comment) { [comments addObject:@(ctx.menu.candidates[i].comment)]; @@ -638,8 +641,10 @@ - (void)rimeUpdate { if (ctx.menu.select_keys) { labels = @[ @(ctx.menu.select_keys) ]; } else if (ctx.select_labels) { - NSMutableArray* selectLabels = [NSMutableArray array]; - for (i = 0; i < ctx.menu.page_size; ++i) { + NSUInteger pageSize = (NSUInteger)ctx.menu.page_size; + NSMutableArray* selectLabels = + [[NSMutableArray alloc] initWithCapacity:pageSize]; + for (NSUInteger i = 0; i < pageSize; ++i) { char* label_str = ctx.select_labels[i]; [selectLabels addObject:@(label_str)]; } @@ -647,16 +652,17 @@ - (void)rimeUpdate { } else { labels = @[]; } - [self showPanelWithPreedit:(_inlinePreedit ? nil : preeditText) - selRange:selRange - caretPos:caretPos - candidates:candidates - comments:comments - labels:labels - highlighted:ctx.menu.highlighted_candidate_index]; + [self + showPanelWithPreedit:(_inlinePreedit ? nil : preeditText) + selRange:selRange + caretPos:caretPos + candidates:candidates + comments:comments + labels:labels + highlighted:(NSUInteger)ctx.menu.highlighted_candidate_index]; rime_get_api()->free_context(&ctx); } else { - [NSApp.squirrelAppDelegate.panel hide]; + [self hidePalettes]; } } diff --git a/SquirrelPanel.h b/SquirrelPanel.h index a65a1e9e2..5844ad7a5 100644 --- a/SquirrelPanel.h +++ b/SquirrelPanel.h @@ -22,9 +22,9 @@ - (void)showPreedit:(NSString*)preedit selRange:(NSRange)selRange caretPos:(NSUInteger)caretPos - candidates:(NSArray*)candidates - comments:(NSArray*)comments - labels:(NSArray*)labels + candidates:(NSArray*)candidates + comments:(NSArray*)comments + labels:(NSArray*)labels highlighted:(NSUInteger)index update:(BOOL)update; diff --git a/SquirrelPanel.m b/SquirrelPanel.m index 88d47677f..a7ec23945 100644 --- a/SquirrelPanel.m +++ b/SquirrelPanel.m @@ -78,14 +78,14 @@ - (void)setCornerRadius:(CGFloat)cornerRadius inlinePreedit:(BOOL)inlinePreedit inlineCandidate:(BOOL)inlineCandidate; -- (void)setAttrs:(NSMutableDictionary*)attrs - highlightedAttrs:(NSMutableDictionary*)highlightedAttrs - labelAttrs:(NSMutableDictionary*)labelAttrs - labelHighlightedAttrs:(NSMutableDictionary*)labelHighlightedAttrs - commentAttrs:(NSMutableDictionary*)commentAttrs - commentHighlightedAttrs:(NSMutableDictionary*)commentHighlightedAttrs - preeditAttrs:(NSMutableDictionary*)preeditAttrs - preeditHighlightedAttrs:(NSMutableDictionary*)preeditHighlightedAttrs; +- (void)setAttrs:(NSDictionary*)attrs + highlightedAttrs:(NSDictionary*)highlightedAttrs + labelAttrs:(NSDictionary*)labelAttrs + labelHighlightedAttrs:(NSDictionary*)labelHighlightedAttrs + commentAttrs:(NSDictionary*)commentAttrs + commentHighlightedAttrs:(NSDictionary*)commentHighlightedAttrs + preeditAttrs:(NSDictionary*)preeditAttrs + preeditHighlightedAttrs:(NSDictionary*)preeditHighlightedAttrs; - (void)setParagraphStyle:(NSParagraphStyle*)paragraphStyle preeditParagraphStyle:(NSParagraphStyle*)preeditParagraphStyle; @@ -145,15 +145,15 @@ - (void)setBackgroundColor:(NSColor*)backgroundColor _borderColor = borderColor; } -- (void)setCornerRadius:(double)cornerRadius - hilitedCornerRadius:(double)hilitedCornerRadius - srdExtraExpansion:(double)surroundingExtraExpansion - shadowSize:(double)shadowSize +- (void)setCornerRadius:(CGFloat)cornerRadius + hilitedCornerRadius:(CGFloat)hilitedCornerRadius + srdExtraExpansion:(CGFloat)surroundingExtraExpansion + shadowSize:(CGFloat)shadowSize edgeInset:(NSSize)edgeInset - borderWidth:(double)borderWidth - linespace:(double)linespace - preeditLinespace:(double)preeditLinespace - alpha:(double)alpha + borderWidth:(CGFloat)borderWidth + linespace:(CGFloat)linespace + preeditLinespace:(CGFloat)preeditLinespace + alpha:(CGFloat)alpha translucency:(BOOL)translucency mutualExclusive:(BOOL)mutualExclusive linear:(BOOL)linear @@ -177,14 +177,14 @@ - (void)setCornerRadius:(double)cornerRadius _inlineCandidate = inlineCandidate; } -- (void)setAttrs:(NSMutableDictionary*)attrs - highlightedAttrs:(NSMutableDictionary*)highlightedAttrs - labelAttrs:(NSMutableDictionary*)labelAttrs - labelHighlightedAttrs:(NSMutableDictionary*)labelHighlightedAttrs - commentAttrs:(NSMutableDictionary*)commentAttrs - commentHighlightedAttrs:(NSMutableDictionary*)commentHighlightedAttrs - preeditAttrs:(NSMutableDictionary*)preeditAttrs - preeditHighlightedAttrs:(NSMutableDictionary*)preeditHighlightedAttrs { +- (void)setAttrs:(NSDictionary*)attrs + highlightedAttrs:(NSDictionary*)highlightedAttrs + labelAttrs:(NSDictionary*)labelAttrs + labelHighlightedAttrs:(NSDictionary*)labelHighlightedAttrs + commentAttrs:(NSDictionary*)commentAttrs + commentHighlightedAttrs:(NSDictionary*)commentHighlightedAttrs + preeditAttrs:(NSDictionary*)preeditAttrs + preeditHighlightedAttrs:(NSDictionary*)preeditHighlightedAttrs { _attrs = attrs; _highlightedAttrs = highlightedAttrs; _labelAttrs = labelAttrs; @@ -587,17 +587,17 @@ void expand(NSMutableArray* vertex, } } -CGPoint direction(CGPoint diff) { - if (diff.y == 0 && diff.x > 0) { - return NSMakePoint(0, 1); - } else if (diff.y == 0 && diff.x < 0) { - return NSMakePoint(0, -1); - } else if (diff.x == 0 && diff.y > 0) { - return NSMakePoint(-1, 0); - } else if (diff.x == 0 && diff.y < 0) { - return NSMakePoint(1, 0); +CGVector direction(CGVector diff) { + if (diff.dy == 0 && diff.dx > 0) { + return CGVectorMake(0, 1); + } else if (diff.dy == 0 && diff.dx < 0) { + return CGVectorMake(0, -1); + } else if (diff.dx == 0 && diff.dy > 0) { + return CGVectorMake(-1, 0); + } else if (diff.dx == 0 && diff.dy < 0) { + return CGVectorMake(1, 0); } else { - return NSMakePoint(0, 0); + return CGVectorMake(0, 0); } } @@ -616,7 +616,7 @@ void enlarge(NSMutableArray* vertex, CGFloat by) { NSPoint nextPoint; NSArray* original = [[NSArray alloc] initWithArray:vertex]; NSPoint newPoint; - NSPoint displacement; + CGVector displacement; for (NSUInteger i = 0; i < original.count; i += 1) { previousPoint = [original[(original.count + i - 1) % original.count] pointValue]; @@ -624,13 +624,13 @@ void enlarge(NSMutableArray* vertex, CGFloat by) { nextPoint = [original[(i + 1) % original.count] pointValue]; newPoint = point; displacement = direction( - NSMakePoint(point.x - previousPoint.x, point.y - previousPoint.y)); - newPoint.x += by * displacement.x; - newPoint.y += by * displacement.y; + CGVectorMake(point.x - previousPoint.x, point.y - previousPoint.y)); + newPoint.x += by * displacement.dx; + newPoint.y += by * displacement.dy; displacement = - direction(NSMakePoint(nextPoint.x - point.x, nextPoint.y - point.y)); - newPoint.x += by * displacement.x; - newPoint.y += by * displacement.y; + direction(CGVectorMake(nextPoint.x - point.x, nextPoint.y - point.y)); + newPoint.x += by * displacement.dx; + newPoint.y += by * displacement.dy; [vertex replaceObjectAtIndex:i withObject:@(newPoint)]; } } diff --git a/input_source.m b/input_source.m index bef223695..6b00be271 100644 --- a/input_source.m +++ b/input_source.m @@ -1,16 +1,17 @@ #import -static const unsigned char kInstallLocation[] = - "/Library/Input Methods/Squirrel.app"; -static NSString* const kHansInputModeID = @"im.rime.inputmethod.Squirrel.Hans"; -static NSString* const kHantInputModeID = @"im.rime.inputmethod.Squirrel.Hant"; +static const char kInstallLocation[] = "/Library/Input Methods/Squirrel.app"; +static const CFStringRef kHansInputModeID = + CFSTR("im.rime.inputmethod.Squirrel.Hans"); +static const CFStringRef kHantInputModeID = + CFSTR("im.rime.inputmethod.Squirrel.Hant"); #define HANS_INPUT_MODE (1 << 0) #define HANT_INPUT_MODE (1 << 1) void RegisterInputSource(void) { CFURLRef installedLocationURL = CFURLCreateFromFileSystemRepresentation( - NULL, kInstallLocation, strlen((const char*)kInstallLocation), NO); + NULL, (UInt8*)kInstallLocation, (CFIndex)strlen(kInstallLocation), false); if (installedLocationURL) { TISRegisterInputSource(installedLocationURL); CFRelease(installedLocationURL); @@ -22,13 +23,13 @@ void ActivateInputSource(int enabled_modes) { CFArrayRef sourceList = TISCreateInputSourceList(NULL, true); for (CFIndex i = 0; i < CFArrayGetCount(sourceList); ++i) { TISInputSourceRef inputSource = - (TISInputSourceRef)(CFArrayGetValueAtIndex(sourceList, i)); - NSString* sourceID = (__bridge NSString*)(TISGetInputSourceProperty( - inputSource, kTISPropertyInputSourceID)); + (TISInputSourceRef)CFArrayGetValueAtIndex(sourceList, i); + CFStringRef sourceID = (CFStringRef)TISGetInputSourceProperty( + inputSource, kTISPropertyInputSourceID); // NSLog(@"Examining input source: %@", sourceID); - if (([sourceID isEqualToString:kHansInputModeID] && + if ((!CFStringCompare(sourceID, kHansInputModeID, 0) && ((enabled_modes & HANS_INPUT_MODE) != 0)) || - ([sourceID isEqualToString:kHantInputModeID] && + (!CFStringCompare(sourceID, kHantInputModeID, 0) && ((enabled_modes & HANT_INPUT_MODE) != 0))) { TISEnableInputSource(inputSource); NSLog(@"Enabled input source: %@", sourceID); @@ -47,14 +48,14 @@ void DeactivateInputSource(void) { CFArrayRef sourceList = TISCreateInputSourceList(NULL, true); for (CFIndex i = CFArrayGetCount(sourceList); i > 0; --i) { TISInputSourceRef inputSource = - (TISInputSourceRef)(CFArrayGetValueAtIndex(sourceList, i - 1)); - NSString* sourceID = (__bridge NSString*)(TISGetInputSourceProperty( - inputSource, kTISPropertyInputSourceID)); + (TISInputSourceRef)CFArrayGetValueAtIndex(sourceList, i - 1); + CFStringRef sourceID = (CFStringRef)TISGetInputSourceProperty( + inputSource, kTISPropertyInputSourceID); // NSLog(@"Examining input source: %@", sourceID); - if ([sourceID isEqualToString:kHansInputModeID] || - [sourceID isEqualToString:kHantInputModeID]) { - CFBooleanRef isEnabled = (CFBooleanRef)(TISGetInputSourceProperty( - inputSource, kTISPropertyInputSourceIsEnabled)); + if (!CFStringCompare(sourceID, kHansInputModeID, 0) || + !CFStringCompare(sourceID, kHantInputModeID, 0)) { + CFBooleanRef isEnabled = (CFBooleanRef)TISGetInputSourceProperty( + inputSource, kTISPropertyInputSourceIsEnabled); if (CFBooleanGetValue(isEnabled)) { TISDisableInputSource(inputSource); NSLog(@"Disabled input source: %@", sourceID); @@ -69,19 +70,20 @@ int GetEnabledInputModes(void) { CFArrayRef sourceList = TISCreateInputSourceList(NULL, true); for (CFIndex i = 0; i < CFArrayGetCount(sourceList); ++i) { TISInputSourceRef inputSource = - (TISInputSourceRef)(CFArrayGetValueAtIndex(sourceList, i)); - NSString* sourceID = (__bridge NSString*)(TISGetInputSourceProperty( - inputSource, kTISPropertyInputSourceID)); + (TISInputSourceRef)CFArrayGetValueAtIndex(sourceList, i); + CFStringRef sourceID = (CFStringRef)TISGetInputSourceProperty( + inputSource, kTISPropertyInputSourceID); // NSLog(@"Examining input source: %@", sourceID); - if ([sourceID isEqualToString:kHansInputModeID] || - [sourceID isEqualToString:kHantInputModeID]) { - CFBooleanRef isEnabled = (CFBooleanRef)(TISGetInputSourceProperty( - inputSource, kTISPropertyInputSourceIsEnabled)); + if (!CFStringCompare(sourceID, kHansInputModeID, 0) || + !CFStringCompare(sourceID, kHantInputModeID, 0)) { + CFBooleanRef isEnabled = (CFBooleanRef)TISGetInputSourceProperty( + inputSource, kTISPropertyInputSourceIsEnabled); if (CFBooleanGetValue(isEnabled)) { - if ([sourceID isEqualToString:kHansInputModeID]) + if (!CFStringCompare(sourceID, kHansInputModeID, 0)) { input_modes |= HANS_INPUT_MODE; - else if ([sourceID isEqualToString:kHantInputModeID]) + } else if (!CFStringCompare(sourceID, kHantInputModeID, 0)) { input_modes |= HANT_INPUT_MODE; + } } } } diff --git a/main.m b/main.m index fca00dd22..53b6491c0 100644 --- a/main.m +++ b/main.m @@ -14,12 +14,12 @@ // Each input method needs a unique connection name. // Note that periods and spaces are not allowed in the connection name. -const NSString* kConnectionName = @"Squirrel_1_Connection"; +static NSString* const kConnectionName = @"Squirrel_1_Connection"; int main(int argc, char* argv[]) { if (argc > 1 && !strcmp("--quit", argv[1])) { NSString* bundleId = [NSBundle mainBundle].bundleIdentifier; - NSArray* runningSquirrels = + NSArray* runningSquirrels = [NSRunningApplication runningApplicationsWithBundleIdentifier:bundleId]; for (NSRunningApplication* squirrelApp in runningSquirrels) { [squirrelApp terminate]; @@ -39,7 +39,7 @@ int main(int argc, char* argv[]) { RegisterInputSource(); int input_modes = GetEnabledInputModes(); DeactivateInputSource(); - ActivateInputSource(input_modes ? input_modes : DEFAULT_INPUT_MODE); + ActivateInputSource(input_modes ?: DEFAULT_INPUT_MODE); return 0; } @@ -65,14 +65,14 @@ int main(int argc, char* argv[]) { // find the bundle identifier and then initialize the input method server NSBundle* main = [NSBundle mainBundle]; IMKServer* server __unused = - [[IMKServer alloc] initWithName:(NSString*)kConnectionName + [[IMKServer alloc] initWithName:kConnectionName bundleIdentifier:main.bundleIdentifier]; // load the bundle explicitly because in this case the input method is a // background only application [main loadNibNamed:@"MainMenu" owner:[NSApplication sharedApplication] - topLevelObjects:NULL]; + topLevelObjects:nil]; // opencc will be configured with relative dictionary paths [[NSFileManager defaultManager] @@ -83,10 +83,15 @@ int main(int argc, char* argv[]) { NSArray* args = @[ @"Problematic launch detected! \ Squirrel may be suffering a crash due to imporper configuration. \ Revert previous modifications to see if the problem recurs." ]; - [NSTask launchedTaskWithLaunchPath:@"/usr/bin/say" arguments:args]; + [NSTask + launchedTaskWithExecutableURL:[NSURL fileURLWithPath:@"/usr/bin/say" + isDirectory:NO] + arguments:args + error:nil + terminationHandler:nil]; } else { [NSApp.squirrelAppDelegate setupRime]; - [NSApp.squirrelAppDelegate startRimeWithFullCheck:NO]; + [NSApp.squirrelAppDelegate startRimeWithFullCheck:false]; [NSApp.squirrelAppDelegate loadSettings]; NSLog(@"Squirrel reporting!"); }