From d36bf1d5e39b6f84a98b7f39b7278e834ef3f5fd Mon Sep 17 00:00:00 2001 From: WenJingRui <2539699336@qq.com> Date: Fri, 19 Aug 2022 06:26:00 +0800 Subject: [PATCH] [iOS] Avoid keyboard animation junk and laggy on Promotion devices. (flutter/engine#34871) --- .../ci/licenses_golden/licenses_flutter | 1 + .../shell/platform/darwin/ios/BUILD.gn | 1 + .../framework/Source/FlutterViewController.mm | 79 ++++++++++++------- .../Source/FlutterViewControllerTest.mm | 17 +++- .../Source/FlutterViewControllerTest_mrc.mm | 59 ++++++++++++++ .../framework/Source/VsyncWaiterIosTest.mm | 21 +++++ .../ios/framework/Source/vsync_waiter_ios.h | 10 +++ .../ios/framework/Source/vsync_waiter_ios.mm | 5 +- .../IosUnitTests.xcodeproj/project.pbxproj | 2 + 9 files changed, 163 insertions(+), 32 deletions(-) create mode 100644 engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewControllerTest_mrc.mm diff --git a/engine/src/flutter/ci/licenses_golden/licenses_flutter b/engine/src/flutter/ci/licenses_golden/licenses_flutter index 14de4f81e9..dfa73e2f41 100644 --- a/engine/src/flutter/ci/licenses_golden/licenses_flutter +++ b/engine/src/flutter/ci/licenses_golden/licenses_flutter @@ -1814,6 +1814,7 @@ FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterView.h FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterView.mm FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController.mm FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterViewControllerTest.mm +FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterViewControllerTest_mrc.mm FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController_Internal.h FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterViewResponder.h FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterViewTest.mm diff --git a/engine/src/flutter/shell/platform/darwin/ios/BUILD.gn b/engine/src/flutter/shell/platform/darwin/ios/BUILD.gn index 74aa338ab2..e3a8339e22 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/BUILD.gn +++ b/engine/src/flutter/shell/platform/darwin/ios/BUILD.gn @@ -201,6 +201,7 @@ source_set("ios_test_flutter_mrc") { "framework/Source/FlutterEngineTest_mrc.mm", "framework/Source/FlutterPlatformPluginTest.mm", "framework/Source/FlutterPlatformViewsTest.mm", + "framework/Source/FlutterViewControllerTest_mrc.mm", "framework/Source/FlutterViewTest.mm", "framework/Source/VsyncWaiterIosTest.mm", "framework/Source/accessibility_bridge_test.mm", diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController.mm b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController.mm index 315611072f..cc7947421f 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController.mm +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController.mm @@ -26,6 +26,7 @@ #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterView.h" #import "flutter/shell/platform/darwin/ios/framework/Source/platform_message_response_darwin.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/vsync_waiter_ios.h" #import "flutter/shell/platform/darwin/ios/platform_view_ios.h" #import "flutter/shell/platform/embedder/embedder.h" @@ -62,7 +63,7 @@ typedef struct MouseState { * Keyboard animation properties */ @property(nonatomic, assign) double targetViewInsetBottom; -@property(nonatomic, retain) CADisplayLink* displayLink; +@property(nonatomic, retain) VSyncClient* keyboardAnimationVSyncClient; /* * Mouse and trackpad gesture recognizers @@ -775,7 +776,7 @@ static void SendFakeTouchEvent(FlutterEngine* engine, - (void)viewDidDisappear:(BOOL)animated { TRACE_EVENT0("flutter", "viewDidDisappear"); if ([_engine.get() viewController] == self) { - [self invalidateDisplayLink]; + [self invalidateKeyboardAnimationVSyncClient]; [self ensureViewportMetricsIsCorrect]; [self surfaceUpdated:NO]; [[_engine.get() lifecycleChannel] sendMessage:@"AppLifecycleState.paused"]; @@ -831,7 +832,7 @@ static void SendFakeTouchEvent(FlutterEngine* engine, [self removeInternalPlugins]; [self deregisterNotifications]; - [_displayLink release]; + [self invalidateKeyboardAnimationVSyncClient]; _scrollView.get().delegate = nil; _hoverGestureRecognizer.delegate = nil; [_hoverGestureRecognizer release]; @@ -1269,19 +1270,16 @@ static flutter::PointerData::DeviceKind DeviceKindFromTouchType(UITouch* touch) } // Remove running animation when start another animation. - // After calling this line,the old display link will invalidate. [[self keyboardAnimationView].layer removeAllAnimations]; // Set animation begin value. [self keyboardAnimationView].frame = CGRectMake(0, _viewportMetrics.physical_view_inset_bottom, 0, 0); - // Invalidate old display link if the old animation is not complete - [self invalidateDisplayLink]; - - self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(onDisplayLink)]; - [self.displayLink addToRunLoop:NSRunLoop.currentRunLoop forMode:NSRunLoopCommonModes]; - __block CADisplayLink* currentDisplayLink = self.displayLink; + // Invalidate old vsync client if old animation is not completed. + [self invalidateKeyboardAnimationVSyncClient]; + [self setupKeyboardAnimationVsyncClient]; + VSyncClient* currentVsyncClient = _keyboardAnimationVSyncClient; [UIView animateWithDuration:duration animations:^{ @@ -1289,19 +1287,54 @@ static flutter::PointerData::DeviceKind DeviceKindFromTouchType(UITouch* touch) [self keyboardAnimationView].frame = CGRectMake(0, self.targetViewInsetBottom, 0, 0); } completion:^(BOOL finished) { - if (self.displayLink == currentDisplayLink) { - // Indicates the displaylink captured by this block is the original one,which also - // indicates the animation has not been interrupted from its beginning. Moreover,indicates - // the animation is over and there is no more animation about to exectute. - [self invalidateDisplayLink]; + if (_keyboardAnimationVSyncClient == currentVsyncClient) { + // Indicates the vsync client captured by this block is the original one, which also + // indicates the animation has not been interrupted from its beginning. Moreover, + // indicates the animation is over and there is no more to execute. + [self invalidateKeyboardAnimationVSyncClient]; [self removeKeyboardAnimationView]; [self ensureViewportMetricsIsCorrect]; } }]; } -- (void)invalidateDisplayLink { - [self.displayLink invalidate]; +- (void)setupKeyboardAnimationVsyncClient { + auto callback = [weakSelf = + [self getWeakPtr]](std::unique_ptr recorder) { + if (!weakSelf) { + return; + } + fml::scoped_nsobject flutterViewController( + [(FlutterViewController*)weakSelf.get() retain]); + if (!flutterViewController) { + return; + } + + if ([flutterViewController keyboardAnimationView].superview == nil) { + // Ensure the keyboardAnimationView is in view hierarchy when animation running. + [flutterViewController.get().view addSubview:[flutterViewController keyboardAnimationView]]; + } + if ([flutterViewController keyboardAnimationView].layer.presentationLayer) { + CGFloat value = + [flutterViewController keyboardAnimationView].layer.presentationLayer.frame.origin.y; + flutterViewController.get()->_viewportMetrics.physical_view_inset_bottom = value; + [flutterViewController updateViewportMetrics]; + } + }; + flutter::Shell& shell = [_engine.get() shell]; + NSAssert(_keyboardAnimationVSyncClient == nil, + @"_keyboardAnimationVSyncClient must be nil when setup"); + _keyboardAnimationVSyncClient = + [[VSyncClient alloc] initWithTaskRunner:shell.GetTaskRunners().GetPlatformTaskRunner() + callback:callback]; + _keyboardAnimationVSyncClient.allowPauseAfterVsync = NO; + [_keyboardAnimationVSyncClient await]; +} + +- (void)invalidateKeyboardAnimationVSyncClient { + [_keyboardAnimationVSyncClient invalidate]; + [_keyboardAnimationVSyncClient release]; + _keyboardAnimationVSyncClient = nil; } - (void)removeKeyboardAnimationView { @@ -1318,18 +1351,6 @@ static flutter::PointerData::DeviceKind DeviceKindFromTouchType(UITouch* touch) } } -- (void)onDisplayLink { - if ([self keyboardAnimationView].superview == nil) { - // Ensure the keyboardAnimationView is in view hierarchy when animation running. - [self.view addSubview:[self keyboardAnimationView]]; - } - if ([self keyboardAnimationView].layer.presentationLayer) { - CGFloat value = [self keyboardAnimationView].layer.presentationLayer.frame.origin.y; - _viewportMetrics.physical_view_inset_bottom = value; - [self updateViewportMetrics]; - } -} - - (void)handlePressEvent:(FlutterUIPressProxy*)press nextAction:(void (^)())next API_AVAILABLE(ios(13.4)) { if (@available(iOS 13.4, *)) { diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewControllerTest.mm b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewControllerTest.mm index 556d87f584..d3f4de66f8 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewControllerTest.mm +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewControllerTest.mm @@ -126,8 +126,9 @@ extern NSNotificationName const FlutterViewControllerWillDealloc; - (void)keyboardWillChangeFrame:(NSNotification*)notification; - (void)keyboardWillBeHidden:(NSNotification*)notification; - (void)startKeyBoardAnimation:(NSTimeInterval)duration; +- (void)setupKeyboardAnimationVsyncClient; - (void)ensureViewportMetricsIsCorrect; -- (void)invalidateDisplayLink; +- (void)invalidateKeyboardAnimationVSyncClient; - (void)addInternalPlugins; - (flutter::PointerData)generatePointerDataForFake; - (void)sharedSetupWithProject:(nullable FlutterDartProject*)project @@ -159,6 +160,18 @@ extern NSNotificationName const FlutterViewControllerWillDealloc; self.messageSent = nil; } +- (void)testStartKeyboardAnimationWillInvokeSetupKeyboardAnimationVsyncClient { + FlutterEngine* engine = [[FlutterEngine alloc] init]; + [engine runWithEntrypoint:nil]; + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine + nibName:nil + bundle:nil]; + FlutterViewController* viewControllerMock = OCMPartialMock(viewController); + viewControllerMock.targetViewInsetBottom = 100; + [viewControllerMock startKeyBoardAnimation:0.25]; + OCMVerify([viewControllerMock setupKeyboardAnimationVsyncClient]); +} + - (void)testkeyboardWillChangeFrameWillStartKeyboardAnimation { FlutterEngine* mockEngine = OCMPartialMock([[FlutterEngine alloc] init]); [mockEngine createShell:@"" libraryURI:@"" initialRoute:nil]; @@ -223,7 +236,7 @@ extern NSNotificationName const FlutterViewControllerWillDealloc; id viewControllerMock = OCMPartialMock(viewController); [viewControllerMock viewDidDisappear:YES]; OCMVerify([viewControllerMock ensureViewportMetricsIsCorrect]); - OCMVerify([viewControllerMock invalidateDisplayLink]); + OCMVerify([viewControllerMock invalidateKeyboardAnimationVSyncClient]); } - (void)testViewDidDisappearDoesntPauseEngineWhenNotTheViewController { diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewControllerTest_mrc.mm b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewControllerTest_mrc.mm new file mode 100644 index 0000000000..f4cc21706e --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewControllerTest_mrc.mm @@ -0,0 +1,59 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#import +#import + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" +#import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterViewController.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/vsync_waiter_ios.h" + +FLUTTER_ASSERT_NOT_ARC + +@interface VSyncClient (Testing) + +- (CADisplayLink*)getDisplayLink; + +@end + +@interface FlutterViewController (Testing) + +@property(nonatomic, assign) double targetViewInsetBottom; +@property(nonatomic, retain) VSyncClient* keyboardAnimationVSyncClient; + +- (void)setupKeyboardAnimationVsyncClient; + +@end + +@interface FlutterViewControllerTest_mrc : XCTestCase +@end + +@implementation FlutterViewControllerTest_mrc + +- (void)testSetupKeyboardAnimationVsyncClientWillCreateNewVsyncClientForFlutterViewController { + id bundleMock = OCMPartialMock([NSBundle mainBundle]); + OCMStub([bundleMock objectForInfoDictionaryKey:@"CADisableMinimumFrameDurationOnPhone"]) + .andReturn(@YES); + id mockDisplayLinkManager = [OCMockObject mockForClass:[DisplayLinkManager class]]; + double maxFrameRate = 120; + [[[mockDisplayLinkManager stub] andReturnValue:@(maxFrameRate)] displayRefreshRate]; + FlutterEngine* engine = [[FlutterEngine alloc] init]; + [engine runWithEntrypoint:nil]; + FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine + nibName:nil + bundle:nil]; + [viewController setupKeyboardAnimationVsyncClient]; + XCTAssertNotNil(viewController.keyboardAnimationVSyncClient); + CADisplayLink* link = [viewController.keyboardAnimationVSyncClient getDisplayLink]; + XCTAssertNotNil(link); + if (@available(iOS 15.0, *)) { + XCTAssertEqual(link.preferredFrameRateRange.maximum, maxFrameRate); + XCTAssertEqual(link.preferredFrameRateRange.preferred, maxFrameRate); + XCTAssertEqual(link.preferredFrameRateRange.minimum, maxFrameRate / 2); + } else { + XCTAssertEqual(link.preferredFramesPerSecond, maxFrameRate); + } +} + +@end diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/VsyncWaiterIosTest.mm b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/VsyncWaiterIosTest.mm index 124bdee2e8..4ac0529808 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/VsyncWaiterIosTest.mm +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/VsyncWaiterIosTest.mm @@ -22,6 +22,7 @@ fml::RefPtr CreateNewThread(std::string name) { @interface VSyncClient (Testing) - (CADisplayLink*)getDisplayLink; +- (void)onDisplayLink:(CADisplayLink*)link; @end @@ -30,6 +31,26 @@ fml::RefPtr CreateNewThread(std::string name) { @implementation VsyncWaiterIosTest +- (void)testSetAllowPauseAfterVsyncCorrect { + auto thread_task_runner = CreateNewThread("VsyncWaiterIosTest"); + VSyncClient* vsyncClient = [[[VSyncClient alloc] + initWithTaskRunner:thread_task_runner + callback:[](std::unique_ptr recorder) {}] + autorelease]; + CADisplayLink* link = [vsyncClient getDisplayLink]; + vsyncClient.allowPauseAfterVsync = NO; + [vsyncClient await]; + [vsyncClient onDisplayLink:link]; + XCTAssertFalse(link.isPaused); + + vsyncClient.allowPauseAfterVsync = YES; + [vsyncClient await]; + [vsyncClient onDisplayLink:link]; + XCTAssertTrue(link.isPaused); + + [vsyncClient release]; +} + - (void)testSetCorrectVariableRefreshRates { auto thread_task_runner = CreateNewThread("VsyncWaiterIosTest"); auto callback = [](std::unique_ptr recorder) {}; diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/vsync_waiter_ios.h b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/vsync_waiter_ios.h index 9b5d5aa519..9185fb0097 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/vsync_waiter_ios.h +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/vsync_waiter_ios.h @@ -30,6 +30,16 @@ @interface VSyncClient : NSObject +//------------------------------------------------------------------------------ +/// @brief Default value is YES. Vsync client will pause vsync callback after receiving +/// a vsync signal. Setting this property to NO can avoid this and vsync client +/// will trigger vsync callback continuously. +/// +/// +/// @param allowPauseAfterVsync Allow vsync client to pause after receiving a vsync signal. +/// +@property(nonatomic, assign) BOOL allowPauseAfterVsync; + - (instancetype)initWithTaskRunner:(fml::RefPtr)task_runner callback:(flutter::VsyncWaiter::Callback)callback; diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/vsync_waiter_ios.mm b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/vsync_waiter_ios.mm index 0e6b2f5e68..439ba868ff 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/vsync_waiter_ios.mm +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/vsync_waiter_ios.mm @@ -57,6 +57,7 @@ double VsyncWaiterIOS::GetRefreshRate() const { if (self) { current_refresh_rate_ = [DisplayLinkManager displayRefreshRate]; + _allowPauseAfterVsync = YES; callback_ = std::move(callback); display_link_ = fml::scoped_nsobject { [[CADisplayLink displayLinkWithTarget:self selector:@selector(onDisplayLink:)] retain] @@ -111,7 +112,9 @@ double VsyncWaiterIOS::GetRefreshRate() const { current_refresh_rate_ = round(1 / (frame_target_time - frame_start_time).ToSecondsF()); recorder->RecordVsync(frame_start_time, frame_target_time); - display_link_.get().paused = YES; + if (_allowPauseAfterVsync) { + display_link_.get().paused = YES; + } callback_(std::move(recorder)); } diff --git a/engine/src/flutter/testing/ios/IosUnitTests/IosUnitTests.xcodeproj/project.pbxproj b/engine/src/flutter/testing/ios/IosUnitTests/IosUnitTests.xcodeproj/project.pbxproj index 3632c55063..b14ff64445 100644 --- a/engine/src/flutter/testing/ios/IosUnitTests/IosUnitTests.xcodeproj/project.pbxproj +++ b/engine/src/flutter/testing/ios/IosUnitTests/IosUnitTests.xcodeproj/project.pbxproj @@ -72,6 +72,7 @@ 689EC1E2281B30D3008FEB58 /* FlutterSpellCheckPluginTest.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = FlutterSpellCheckPluginTest.mm; sourceTree = ""; }; 68B6091227F62F990036AC78 /* VsyncWaiterIosTest.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = VsyncWaiterIosTest.mm; sourceTree = ""; }; 3DD7D38C27D2B81000DA365C /* FlutterUndoManagerPluginTest.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = FlutterUndoManagerPluginTest.mm; sourceTree = ""; }; + 73F12C22288F92FF00AFC3A6 /* FlutterViewControllerTest_mrc.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = FlutterViewControllerTest_mrc.mm; sourceTree = ""; }; F7521D7226BB671E005F15C5 /* libios_test_flutter.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libios_test_flutter.dylib; path = "../../../../out/$(FLUTTER_ENGINE)/libios_test_flutter.dylib"; sourceTree = ""; }; F7521D7526BB673E005F15C5 /* libocmock_shared.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libocmock_shared.dylib; path = "../../../../out/$(FLUTTER_ENGINE)/libocmock_shared.dylib"; sourceTree = ""; }; F77E081726FA9CE6003E6E4C /* Flutter.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Flutter.framework; path = "../../../../out/$(FLUTTER_ENGINE)/Flutter.framework"; sourceTree = ""; }; @@ -112,6 +113,7 @@ 0AC2331224BA71D300A85907 /* FlutterEnginePlatformViewTest.mm */, 0AC2331924BA71D300A85907 /* FlutterPluginAppLifeCycleDelegateTest.mm */, 0AC2332124BA71D300A85907 /* FlutterViewControllerTest.mm */, + 73F12C22288F92FF00AFC3A6 /* FlutterViewControllerTest_mrc.mm */, ); name = Source; path = ../../../shell/platform/darwin/ios/framework/Source;