From 782679ce66940934e0bc3f9e92659a5a6a275e04 Mon Sep 17 00:00:00 2001 From: Michael Goderbauer Date: Fri, 27 May 2022 09:56:28 -0700 Subject: [PATCH] Move platform-specific stuff from macOS FVC to FlutterEngine (flutter/engine#33234) --- .../macos/framework/Source/FlutterEngine.mm | 140 ++++++++++++- .../framework/Source/FlutterEngineTest.mm | 36 ++++ .../framework/Source/FlutterEngineTestUtils.h | 5 + .../Source/FlutterEngineTestUtils.mm | 24 +++ .../framework/Source/FlutterEngine_Internal.h | 5 + .../Source/FlutterGLCompositorUnittests.mm | 2 +- .../Source/FlutterMetalCompositorUnittests.mm | 6 +- .../Source/FlutterTextInputPlugin.mm | 2 - .../framework/Source/FlutterViewController.mm | 188 +----------------- .../Source/FlutterViewControllerTest.mm | 50 +---- .../Source/FlutterViewControllerTestUtils.h | 7 +- .../Source/FlutterViewControllerTestUtils.mm | 11 +- .../Source/FlutterViewController_Internal.h | 7 +- 13 files changed, 224 insertions(+), 259 deletions(-) diff --git a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine.mm b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine.mm index c33cd93dc9..ab4b8f4e96 100644 --- a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine.mm +++ b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine.mm @@ -13,8 +13,10 @@ #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterDartProject_Internal.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterExternalTextureGL.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterGLCompositor.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterMenuPlugin.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterMetalCompositor.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterMetalRenderer.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterMouseCursorPlugin.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterOpenGLRenderer.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformViewController.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterRenderingBackend.h" @@ -35,6 +37,14 @@ static FlutterLocale FlutterLocaleFromNSLocale(NSLocale* locale) { return flutterLocale; } +/// The private notification for voice over. +static NSString* const kEnhancedUserInterfaceNotification = + @"NSApplicationDidChangeAccessibilityEnhancedUserInterfaceNotification"; +static NSString* const kEnhancedUserInterfaceKey = @"AXEnhancedUserInterface"; + +/// Clipboard plain text format. +constexpr char kTextPlainFormat[] = "text/plain"; + #pragma mark - // Records an active handler of the messenger (FlutterEngine) that listens to @@ -102,6 +112,11 @@ static FlutterLocale FlutterLocaleFromNSLocale(NSLocale* locale) { */ - (void)setUpPlatformViewChannel; +/** + * Handles messages received from the Flutter engine on the _*Channel channels. + */ +- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result; + @end #pragma mark - @@ -206,6 +221,12 @@ static void OnPlatformMessage(const FlutterPlatformMessage* message, FlutterEngi // Used to support creation and deletion of platform views and registering platform view // factories. Lifecycle is tied to the engine. FlutterPlatformViewController* _platformViewController; + + // A message channel for sending user settings to the flutter engine. + FlutterBasicMessageChannel* _settingsChannel; + + // A method channel for miscellaneous platform functionality. + FlutterMethodChannel* _platformChannel; } - (instancetype)initWithName:(NSString*)labelPrefix project:(FlutterDartProject*)project { @@ -241,6 +262,7 @@ static void OnPlatformMessage(const FlutterPlatformMessage* message, FlutterEngi _platformViewController = [[FlutterPlatformViewController alloc] init]; [self setUpPlatformViewChannel]; + [self setUpNotificationCenterListeners]; return self; } @@ -262,7 +284,7 @@ static void OnPlatformMessage(const FlutterPlatformMessage* message, FlutterEngi return NO; } - // TODO(stuartmorgan): Move internal channel registration from FlutterViewController to here. + [self addInternalPlugins]; // The first argument of argv is required to be the executable name. std::vector argv = {[self.executableName UTF8String]}; @@ -354,6 +376,9 @@ static void OnPlatformMessage(const FlutterPlatformMessage* message, FlutterEngi [self sendUserLocales]; [self updateWindowMetrics]; [self updateDisplayConfig]; + // Send the initial user settings such as brightness and text scale factor + // to the engine. + [self sendInitialSettings]; return YES; } @@ -507,6 +532,28 @@ static void OnPlatformMessage(const FlutterPlatformMessage* message, FlutterEngi CVDisplayLinkRelease(displayLinkRef); } +- (void)onSettingsChanged:(NSNotification*)notification { + // TODO(jonahwilliams): https://github.com/flutter/flutter/issues/32015. + NSString* brightness = + [[NSUserDefaults standardUserDefaults] stringForKey:@"AppleInterfaceStyle"]; + [_settingsChannel sendMessage:@{ + @"platformBrightness" : [brightness isEqualToString:@"Dark"] ? @"dark" : @"light", + // TODO(jonahwilliams): https://github.com/flutter/flutter/issues/32006. + @"textScaleFactor" : @1.0, + @"alwaysUse24HourFormat" : @false + }]; +} + +- (void)sendInitialSettings { + // TODO(jonahwilliams): https://github.com/flutter/flutter/issues/32015. + [[NSDistributedNotificationCenter defaultCenter] + addObserver:self + selector:@selector(onSettingsChanged:) + name:@"AppleInterfaceThemeChangedNotification" + object:nil]; + [self onSettingsChanged:nil]; +} + - (FlutterEngineProcTable&)embedderAPI { return _embedderAPI; } @@ -678,6 +725,97 @@ static void OnPlatformMessage(const FlutterPlatformMessage* message, FlutterEngi }]; } +- (void)setUpNotificationCenterListeners { + NSNotificationCenter* center = [NSNotificationCenter defaultCenter]; + // macOS fires this private message when VoiceOver turns on or off. + [center addObserver:self + selector:@selector(onAccessibilityStatusChanged:) + name:kEnhancedUserInterfaceNotification + object:nil]; + [center addObserver:self + selector:@selector(applicationWillTerminate:) + name:NSApplicationWillTerminateNotification + object:nil]; +} + +- (void)addInternalPlugins { + __weak FlutterEngine* weakSelf = self; + [FlutterMouseCursorPlugin registerWithRegistrar:[self registrarForPlugin:@"mousecursor"]]; + [FlutterMenuPlugin registerWithRegistrar:[self registrarForPlugin:@"menu"]]; + _settingsChannel = + [FlutterBasicMessageChannel messageChannelWithName:@"flutter/settings" + binaryMessenger:self.binaryMessenger + codec:[FlutterJSONMessageCodec sharedInstance]]; + _platformChannel = + [FlutterMethodChannel methodChannelWithName:@"flutter/platform" + binaryMessenger:self.binaryMessenger + codec:[FlutterJSONMethodCodec sharedInstance]]; + [_platformChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) { + [weakSelf handleMethodCall:call result:result]; + }]; +} + +- (void)applicationWillTerminate:(NSNotification*)notification { + [self shutDownEngine]; +} + +- (void)onAccessibilityStatusChanged:(NSNotification*)notification { + BOOL enabled = [notification.userInfo[kEnhancedUserInterfaceKey] boolValue]; + [self.viewController onAccessibilityStatusChanged:enabled]; + self.semanticsEnabled = enabled; +} + +- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result { + if ([call.method isEqualToString:@"SystemNavigator.pop"]) { + [NSApp terminate:self]; + result(nil); + } else if ([call.method isEqualToString:@"SystemSound.play"]) { + [self playSystemSound:call.arguments]; + result(nil); + } else if ([call.method isEqualToString:@"Clipboard.getData"]) { + result([self getClipboardData:call.arguments]); + } else if ([call.method isEqualToString:@"Clipboard.setData"]) { + [self setClipboardData:call.arguments]; + result(nil); + } else if ([call.method isEqualToString:@"Clipboard.hasStrings"]) { + result(@{@"value" : @([self clipboardHasStrings])}); + } else { + result(FlutterMethodNotImplemented); + } +} + +- (void)playSystemSound:(NSString*)soundType { + if ([soundType isEqualToString:@"SystemSoundType.alert"]) { + NSBeep(); + } +} + +- (NSDictionary*)getClipboardData:(NSString*)format { + NSPasteboard* pasteboard = self.pasteboard; + if ([format isEqualToString:@(kTextPlainFormat)]) { + NSString* stringInPasteboard = [pasteboard stringForType:NSPasteboardTypeString]; + return stringInPasteboard == nil ? nil : @{@"text" : stringInPasteboard}; + } + return nil; +} + +- (void)setClipboardData:(NSDictionary*)data { + NSPasteboard* pasteboard = self.pasteboard; + NSString* text = data[@"text"]; + [pasteboard clearContents]; + if (text && ![text isEqual:[NSNull null]]) { + [pasteboard setString:text forType:NSPasteboardTypeString]; + } +} + +- (BOOL)clipboardHasStrings { + return [self.pasteboard stringForType:NSPasteboardTypeString].length > 0; +} + +- (NSPasteboard*)pasteboard { + return [NSPasteboard generalPasteboard]; +} + #pragma mark - FlutterBinaryMessenger - (void)sendOnChannel:(nonnull NSString*)channel message:(nullable NSData*)message { diff --git a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngineTest.mm b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngineTest.mm index 2dae75c206..1f9e825176 100644 --- a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngineTest.mm +++ b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngineTest.mm @@ -520,6 +520,42 @@ TEST_F(FlutterEngineTest, MessengerCleanupConnectionWorks) { EXPECT_EQ(record, 21); } +TEST(FlutterEngine, HasStringsWhenPasteboardEmpty) { + id engineMock = CreateMockFlutterEngine(nil); + + // Call hasStrings and expect it to be false. + __block bool calledAfterClear = false; + __block bool valueAfterClear; + FlutterResult resultAfterClear = ^(id result) { + calledAfterClear = true; + NSNumber* valueNumber = [result valueForKey:@"value"]; + valueAfterClear = [valueNumber boolValue]; + }; + FlutterMethodCall* methodCallAfterClear = + [FlutterMethodCall methodCallWithMethodName:@"Clipboard.hasStrings" arguments:nil]; + [engineMock handleMethodCall:methodCallAfterClear result:resultAfterClear]; + EXPECT_TRUE(calledAfterClear); + EXPECT_FALSE(valueAfterClear); +} + +TEST(FlutterEngine, HasStringsWhenPasteboardFull) { + id engineMock = CreateMockFlutterEngine(@"some string"); + + // Call hasStrings and expect it to be true. + __block bool called = false; + __block bool value; + FlutterResult result = ^(id result) { + called = true; + NSNumber* valueNumber = [result valueForKey:@"value"]; + value = [valueNumber boolValue]; + }; + FlutterMethodCall* methodCall = + [FlutterMethodCall methodCallWithMethodName:@"Clipboard.hasStrings" arguments:nil]; + [engineMock handleMethodCall:methodCall result:result]; + EXPECT_TRUE(called); + EXPECT_TRUE(value); +} + } // namespace flutter::testing // NOLINTEND(clang-analyzer-core.StackAddressEscape) diff --git a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngineTestUtils.h b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngineTestUtils.h index 2242165cac..c2396bc0b5 100644 --- a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngineTestUtils.h +++ b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngineTestUtils.h @@ -4,6 +4,7 @@ #import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterEngine.h" +#import #include "flutter/testing/test_dart_native_resolver.h" #include "gtest/gtest.h" @@ -31,4 +32,8 @@ class FlutterEngineTest : public ::testing::Test { FML_DISALLOW_COPY_AND_ASSIGN(FlutterEngineTest); }; +// Returns a mock FlutterEngine that is able to work in environments +// without a real pasteboard. +id CreateMockFlutterEngine(NSString* pasteboardString); + } // namespace flutter::testing diff --git a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngineTestUtils.mm b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngineTestUtils.mm index ede40a79e1..8bc57273ae 100644 --- a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngineTestUtils.mm +++ b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngineTestUtils.mm @@ -5,6 +5,7 @@ #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngineTestUtils.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterDartProject_Internal.h" +#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h" #include "flutter/testing/testing.h" @@ -38,4 +39,27 @@ void FlutterEngineTest::AddNativeCallback(const char* name, Dart_NativeFunction native_resolver_->AddNativeCallback({name}, function); } +id CreateMockFlutterEngine(NSString* pasteboardString) { + { + NSString* fixtures = @(testing::GetFixturesPath()); + FlutterDartProject* project = [[FlutterDartProject alloc] + initWithAssetsPath:fixtures + ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]]; + FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"test" + project:project + allowHeadlessExecution:true]; + + // Mock pasteboard so that this test will work in environments without a + // real pasteboard. + id pasteboardMock = OCMClassMock([NSPasteboard class]); + OCMExpect([pasteboardMock stringForType:[OCMArg any]]).andDo(^(NSInvocation* invocation) { + NSString* returnValue = pasteboardString.length > 0 ? pasteboardString : nil; + [invocation setReturnValue:&returnValue]; + }); + id engineMock = OCMPartialMock(engine); + OCMStub([engineMock pasteboard]).andReturn(pasteboardMock); + return engineMock; + } +} + } // namespace flutter::testing diff --git a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h index 89c05e91ae..1be0f3d886 100644 --- a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h +++ b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h @@ -44,6 +44,11 @@ */ @property(nonatomic, readonly, nonnull) NSString* executableName; +/** + * This just returns the NSPasteboard so that it can be mocked in the tests. + */ +@property(nonatomic, readonly, nonnull) NSPasteboard* pasteboard; + /** * Informs the engine that the associated view controller's view size has changed. */ diff --git a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterGLCompositorUnittests.mm b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterGLCompositorUnittests.mm index e83ebb9b7c..93e76ea5f2 100644 --- a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterGLCompositorUnittests.mm +++ b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterGLCompositorUnittests.mm @@ -11,7 +11,7 @@ namespace flutter::testing { TEST(FlutterGLCompositorTest, TestPresent) { - id mockViewController = CreateMockViewController(nil); + id mockViewController = CreateMockViewController(); std::unique_ptr macos_compositor = std::make_unique(mockViewController, nullptr); diff --git a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterMetalCompositorUnittests.mm b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterMetalCompositorUnittests.mm index 8a94ecd3d6..ac0e033040 100644 --- a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterMetalCompositorUnittests.mm +++ b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterMetalCompositorUnittests.mm @@ -11,7 +11,7 @@ namespace flutter::testing { TEST(FlutterMetalCompositorTest, TestPresent) { - id mockViewController = CreateMockViewController(nil); + id mockViewController = CreateMockViewController(); std::unique_ptr macos_compositor = std::make_unique( @@ -28,7 +28,7 @@ TEST(FlutterMetalCompositorTest, TestPresent) { } TEST(FlutterMetalCompositorTest, TestCreate) { - id mockViewController = CreateMockViewController(nil); + id mockViewController = CreateMockViewController(); [mockViewController loadView]; std::unique_ptr macos_compositor = @@ -50,7 +50,7 @@ TEST(FlutterMetalCompositorTest, TestCreate) { } TEST(FlutterMetalCompositorTest, TestCompositing) { - id mockViewController = CreateMockViewController(nil); + id mockViewController = CreateMockViewController(); [mockViewController loadView]; std::unique_ptr macos_compositor = diff --git a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputPlugin.mm b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputPlugin.mm index 9e730ee35f..9177889952 100644 --- a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputPlugin.mm +++ b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputPlugin.mm @@ -216,8 +216,6 @@ static flutter::TextRange RangeFromBaseExtent(NSNumber* base, _textInputContext = [[NSTextInputContext alloc] initWithClient:unsafeSelf]; _previouslyPressedFlags = 0; - _flutterViewController = viewController; - // Initialize with the zero matrix which is not // an affine transform. _editableTransform = CATransform3D(); diff --git a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController.mm b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController.mm index eef5b279ec..74e09a8904 100644 --- a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController.mm +++ b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController.mm @@ -14,9 +14,7 @@ #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyPrimaryResponder.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardManager.h" -#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterMenuPlugin.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterMetalRenderer.h" -#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterMouseCursorPlugin.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterOpenGLRenderer.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterRenderingBackend.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputSemanticsObject.h" @@ -27,14 +25,6 @@ namespace { using flutter::KeyboardLayoutNotifier; using flutter::LayoutClue; -/// Clipboard plain text format. -constexpr char kTextPlainFormat[] = "text/plain"; - -/// The private notification for voice over. -static NSString* const kEnhancedUserInterfaceNotification = - @"NSApplicationDidChangeAccessibilityEnhancedUserInterfaceNotification"; -static NSString* const kEnhancedUserInterfaceKey = @"AXEnhancedUserInterface"; - // Use different device ID for mouse and pan/zoom events, since we can't differentiate the actual // device (mouse v.s. trackpad). static constexpr int32_t kMousePointerDeviceId = 0; @@ -208,11 +198,6 @@ NSData* currentKeyboardLayoutData() { */ - (void)configureTrackingArea; -/** - * Creates and registers plugins used by this view controller. - */ -- (void)addInternalPlugins; - /** * Creates and registers keyboard related components. */ @@ -235,52 +220,9 @@ NSData* currentKeyboardLayoutData() { */ - (void)dispatchMouseEvent:(nonnull NSEvent*)event phase:(FlutterPointerPhase)phase; -/** - * Initializes the KVO for user settings and passes the initial user settings to the engine. - */ -- (void)sendInitialSettings; - -/** - * Responds to updates in the user settings and passes this data to the engine. - */ -- (void)onSettingsChanged:(NSNotification*)notification; - -/** - * Responds to updates in accessibility. - */ -- (void)onAccessibilityStatusChanged:(NSNotification*)notification; - // TODO - (void)onKeyboardLayoutChanged; -/** - * Handles messages received from the Flutter engine on the _*Channel channels. - */ -- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result; - -/** - * Plays a system sound. |soundType| specifies which system sound to play. Valid - * values can be found in the SystemSoundType enum in the services SDK package. - */ -- (void)playSystemSound:(NSString*)soundType; - -/** - * Reads the data from the clipboard. |format| specifies the media type of the - * data to obtain. - */ -- (NSDictionary*)getClipboardData:(NSString*)format; - -/** - * Clears contents and writes new data into clipboard. |data| is a dictionary where - * the keys are the type of data, and tervalue the data to be stored. - */ -- (void)setClipboardData:(NSDictionary*)data; - -/** - * Returns true iff the clipboard contains nonempty string data. - */ -- (BOOL)clipboardHasStrings; - @end #pragma mark - Private dependant functions @@ -325,12 +267,6 @@ void OnKeyboardLayoutChanged(CFNotificationCenterRef center, @implementation FlutterViewController { // The project to run in this controller's engine. FlutterDartProject* _project; - - // A message channel for sending user settings to the flutter engine. - FlutterBasicMessageChannel* _settingsChannel; - - // A method channel for miscellaneous platform functionality. - FlutterMethodChannel* _platformChannel; } @dynamic view; @@ -346,16 +282,6 @@ static void CommonInit(FlutterViewController* controller) { } controller->_mouseTrackingMode = FlutterMouseTrackingModeInKeyWindow; controller->_textInputPlugin = [[FlutterTextInputPlugin alloc] initWithViewController:controller]; - NSNotificationCenter* center = [NSNotificationCenter defaultCenter]; - // macOS fires this private message when VoiceOver turns on or off. - [center addObserver:controller - selector:@selector(onAccessibilityStatusChanged:) - name:kEnhancedUserInterfaceNotification - object:nil]; - [center addObserver:controller - selector:@selector(applicationWillTerminate:) - name:NSApplicationWillTerminateNotification - object:nil]; // macOS fires this message when changing IMEs. CFNotificationCenterRef cfCenter = CFNotificationCenterGetDistributedCenter(); __weak FlutterViewController* weakSelf = controller; @@ -480,17 +406,12 @@ static void CommonInit(FlutterViewController* controller) { #pragma mark - Private methods - (BOOL)launchEngine { - // Register internal plugins before starting the engine. - [self addInternalPlugins]; + [self initializeKeyboard]; _engine.viewController = self; if (![_engine runWithEntrypoint:nil]) { return NO; } - // Send the initial user settings such as brightness and text scale factor - // to the engine. - // TODO(stuartmorgan): Move this logic to FlutterEngine. - [self sendInitialSettings]; return YES; } @@ -552,29 +473,13 @@ static void CommonInit(FlutterViewController* controller) { } - (void)initializeKeyboard { + // TODO(goderbauer): Seperate keyboard/textinput stuff into ViewController specific and Engine + // global parts. Move the global parts to FlutterEngine. __weak FlutterViewController* weakSelf = self; _textInputPlugin = [[FlutterTextInputPlugin alloc] initWithViewController:weakSelf]; _keyboardManager = [[FlutterKeyboardManager alloc] initWithViewDelegate:weakSelf]; } -- (void)addInternalPlugins { - __weak FlutterViewController* weakSelf = self; - [FlutterMouseCursorPlugin registerWithRegistrar:[self registrarForPlugin:@"mousecursor"]]; - [FlutterMenuPlugin registerWithRegistrar:[self registrarForPlugin:@"menu"]]; - [self initializeKeyboard]; - _settingsChannel = - [FlutterBasicMessageChannel messageChannelWithName:@"flutter/settings" - binaryMessenger:_engine.binaryMessenger - codec:[FlutterJSONMessageCodec sharedInstance]]; - _platformChannel = - [FlutterMethodChannel methodChannelWithName:@"flutter/platform" - binaryMessenger:_engine.binaryMessenger - codec:[FlutterJSONMethodCodec sharedInstance]]; - [_platformChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) { - [weakSelf handleMethodCall:call result:result]; - }]; -} - - (void)dispatchMouseEvent:(nonnull NSEvent*)event { FlutterPointerPhase phase = _mouseState.buttons == 0 ? (_mouseState.flutter_state_is_down ? kUp : kHover) @@ -723,18 +628,7 @@ static void CommonInit(FlutterViewController* controller) { } } -- (void)applicationWillTerminate:(NSNotification*)notification { - if (!_engine) { - return; - } - [_engine shutDownEngine]; -} - -- (void)onAccessibilityStatusChanged:(NSNotification*)notification { - if (!_engine) { - return; - } - BOOL enabled = [notification.userInfo[kEnhancedUserInterfaceKey] boolValue]; +- (void)onAccessibilityStatusChanged:(BOOL)enabled { if (!enabled && self.viewLoaded && [_textInputPlugin isFirstResponder]) { // The client (i.e. the FlutterTextField) of the textInputPlugin is a sibling // of the FlutterView. macOS will pick the ancestor to be the next responder @@ -747,19 +641,6 @@ static void CommonInit(FlutterViewController* controller) { // manually pick the next responder. [self.view.window makeFirstResponder:_flutterView]; } - _engine.semanticsEnabled = [notification.userInfo[kEnhancedUserInterfaceKey] boolValue]; -} - -- (void)onSettingsChanged:(NSNotification*)notification { - // TODO(jonahwilliams): https://github.com/flutter/flutter/issues/32015. - NSString* brightness = - [[NSUserDefaults standardUserDefaults] stringForKey:@"AppleInterfaceStyle"]; - [_settingsChannel sendMessage:@{ - @"platformBrightness" : [brightness isEqualToString:@"Dark"] ? @"dark" : @"light", - // TODO(jonahwilliams): https://github.com/flutter/flutter/issues/32006. - @"textScaleFactor" : @1.0, - @"alwaysUse24HourFormat" : @false - }]; } - (void)onKeyboardLayoutChanged { @@ -769,67 +650,6 @@ static void CommonInit(FlutterViewController* controller) { } } -- (void)sendInitialSettings { - // TODO(jonahwilliams): https://github.com/flutter/flutter/issues/32015. - [[NSDistributedNotificationCenter defaultCenter] - addObserver:self - selector:@selector(onSettingsChanged:) - name:@"AppleInterfaceThemeChangedNotification" - object:nil]; - [self onSettingsChanged:nil]; -} - -- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result { - if ([call.method isEqualToString:@"SystemNavigator.pop"]) { - [NSApp terminate:self]; - result(nil); - } else if ([call.method isEqualToString:@"SystemSound.play"]) { - [self playSystemSound:call.arguments]; - result(nil); - } else if ([call.method isEqualToString:@"Clipboard.getData"]) { - result([self getClipboardData:call.arguments]); - } else if ([call.method isEqualToString:@"Clipboard.setData"]) { - [self setClipboardData:call.arguments]; - result(nil); - } else if ([call.method isEqualToString:@"Clipboard.hasStrings"]) { - result(@{@"value" : @([self clipboardHasStrings])}); - } else { - result(FlutterMethodNotImplemented); - } -} - -- (void)playSystemSound:(NSString*)soundType { - if ([soundType isEqualToString:@"SystemSoundType.alert"]) { - NSBeep(); - } -} - -- (NSDictionary*)getClipboardData:(NSString*)format { - NSPasteboard* pasteboard = self.pasteboard; - if ([format isEqualToString:@(kTextPlainFormat)]) { - NSString* stringInPasteboard = [pasteboard stringForType:NSPasteboardTypeString]; - return stringInPasteboard == nil ? nil : @{@"text" : stringInPasteboard}; - } - return nil; -} - -- (void)setClipboardData:(NSDictionary*)data { - NSPasteboard* pasteboard = self.pasteboard; - NSString* text = data[@"text"]; - [pasteboard clearContents]; - if (text && ![text isEqual:[NSNull null]]) { - [pasteboard setString:text forType:NSPasteboardTypeString]; - } -} - -- (BOOL)clipboardHasStrings { - return [self.pasteboard stringForType:NSPasteboardTypeString].length > 0; -} - -- (NSPasteboard*)pasteboard { - return [NSPasteboard generalPasteboard]; -} - #pragma mark - FlutterViewReshapeListener /** diff --git a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewControllerTest.mm b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewControllerTest.mm index 47eb655fc5..6252453d78 100644 --- a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewControllerTest.mm +++ b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewControllerTest.mm @@ -51,47 +51,8 @@ NSResponder* mockResponder() { } } // namespace -TEST(FlutterViewController, HasStringsWhenPasteboardEmpty) { - // Mock FlutterViewController so that it behaves like the pasteboard is empty. - id viewControllerMock = CreateMockViewController(nil); - - // Call hasStrings and expect it to be false. - __block bool calledAfterClear = false; - __block bool valueAfterClear; - FlutterResult resultAfterClear = ^(id result) { - calledAfterClear = true; - NSNumber* valueNumber = [result valueForKey:@"value"]; - valueAfterClear = [valueNumber boolValue]; - }; - FlutterMethodCall* methodCallAfterClear = - [FlutterMethodCall methodCallWithMethodName:@"Clipboard.hasStrings" arguments:nil]; - [viewControllerMock handleMethodCall:methodCallAfterClear result:resultAfterClear]; - EXPECT_TRUE(calledAfterClear); - EXPECT_FALSE(valueAfterClear); -} - -TEST(FlutterViewController, HasStringsWhenPasteboardFull) { - // Mock FlutterViewController so that it behaves like the pasteboard has a - // valid string. - id viewControllerMock = CreateMockViewController(@"some string"); - - // Call hasStrings and expect it to be true. - __block bool called = false; - __block bool value; - FlutterResult result = ^(id result) { - called = true; - NSNumber* valueNumber = [result valueForKey:@"value"]; - value = [valueNumber boolValue]; - }; - FlutterMethodCall* methodCall = - [FlutterMethodCall methodCallWithMethodName:@"Clipboard.hasStrings" arguments:nil]; - [viewControllerMock handleMethodCall:methodCall result:result]; - EXPECT_TRUE(called); - EXPECT_TRUE(value); -} - TEST(FlutterViewController, HasViewThatHidesOtherViewsInAccessibility) { - FlutterViewController* viewControllerMock = CreateMockViewController(nil); + FlutterViewController* viewControllerMock = CreateMockViewController(); [viewControllerMock loadView]; auto subViews = [viewControllerMock.view subviews]; @@ -131,14 +92,7 @@ TEST(FlutterViewController, SetsFlutterViewFirstResponderWhenAccessibilityDisabl // Makes sure the textInputPlugin can be the first responder. EXPECT_TRUE([window makeFirstResponder:viewController.textInputPlugin]); EXPECT_EQ([window firstResponder], viewController.textInputPlugin); - // Sends a notification to turn off the accessibility. - NSDictionary* userInfo = @{ - @"AXEnhancedUserInterface" : @(NO), - }; - NSNotification* accessibilityOff = [NSNotification notificationWithName:@"" - object:nil - userInfo:userInfo]; - [viewController onAccessibilityStatusChanged:accessibilityOff]; + [viewController onAccessibilityStatusChanged:NO]; // FlutterView becomes the first responder. EXPECT_EQ([window firstResponder], viewController.flutterView); } diff --git a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewControllerTestUtils.h b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewControllerTestUtils.h index cc3c7f2bcf..a86002f4db 100644 --- a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewControllerTestUtils.h +++ b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewControllerTestUtils.h @@ -11,8 +11,7 @@ namespace flutter::testing { -// Returns a mock FlutterViewController that is able to work in environments -// without a real pasteboard. -id CreateMockViewController(NSString* pasteboardString); +// Returns a mock FlutterViewController. +id CreateMockViewController(); -} +} // namespace flutter::testing diff --git a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewControllerTestUtils.mm b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewControllerTestUtils.mm index 4cae427e1e..a1457984a9 100644 --- a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewControllerTestUtils.mm +++ b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewControllerTestUtils.mm @@ -6,23 +6,14 @@ namespace flutter::testing { -id CreateMockViewController(NSString* pasteboardString) { +id CreateMockViewController() { { NSString* fixtures = @(testing::GetFixturesPath()); FlutterDartProject* project = [[FlutterDartProject alloc] initWithAssetsPath:fixtures ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]]; FlutterViewController* viewController = [[FlutterViewController alloc] initWithProject:project]; - - // Mock pasteboard so that this test will work in environments without a - // real pasteboard. - id pasteboardMock = OCMClassMock([NSPasteboard class]); - OCMExpect([pasteboardMock stringForType:[OCMArg any]]).andDo(^(NSInvocation* invocation) { - NSString* returnValue = pasteboardString.length > 0 ? pasteboardString : nil; - [invocation setReturnValue:&returnValue]; - }); id viewControllerMock = OCMPartialMock(viewController); - OCMStub([viewControllerMock pasteboard]).andReturn(pasteboardMock); return viewControllerMock; } } diff --git a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h index 2607242cea..1da1ab3ecb 100644 --- a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h +++ b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h @@ -13,11 +13,6 @@ // The FlutterView for this view controller. @property(nonatomic, readonly, nullable) FlutterView* flutterView; -/** - * This just returns the NSPasteboard so that it can be mocked in the tests. - */ -@property(nonatomic, readonly, nonnull) NSPasteboard* pasteboard; - /** * The text input plugin that handles text editing state for text fields. */ @@ -40,5 +35,5 @@ // Private methods made visible for testing @interface FlutterViewController (TestMethods) -- (void)onAccessibilityStatusChanged:(nonnull NSNotification*)notification; +- (void)onAccessibilityStatusChanged:(BOOL)enabled; @end