Skip to content

Commit c4a08d9

Browse files
committed
iOS: Stop discarding the GPU state set before an engine runs
Previously, a value assigned to `isGpuDisabled` before the engine ran was silently discarded: `createShell:` sampled the current lifecycle state by assigning to the public property immediately before creating the shell, so the caller's value never reached `Shell::Create`. The sampling is necessary — lifecycle notifications only report transitions, so an engine created while the app is already backgrounded never receives one — but it belongs where its input changes, not where the shell is built. We now sample when the engine is created and when a view controller is attached or detached, and `createShell:` passes `_isGpuDisabled` through untouched. For an app the observable behaviour is unchanged, but a pre-run assignment now survives to the shell and is corrected by the next real lifecycle transition rather than by a write the caller cannot see. Sampling also has to cope with not being able to tell. An app extension has no `UIApplication` to consult, and reaches the scene only through an attached view controller whose view is in a window — which neither `setViewController:` call site has yet. That is also the only configuration in which `setUpLifecycleNotifications:` registers the scene observers, so treating "cannot tell" as "in the foreground" would let an attach undo a `sceneDidEnterBackground:` and re-enable the GPU in the background, which is what gets an app killed. Where neither source is readable we leave `isGpuDisabled` as it stands, the last observed transition being the better answer. The test added in flutter#190836 asserted the old behaviour and is inverted here, so this lands as a behavioural diff. Fixes: flutter#190835 Issue: flutter#112232
1 parent 9d83c36 commit c4a08d9

2 files changed

Lines changed: 170 additions & 25 deletions

File tree

‎engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine.mm‎

Lines changed: 36 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -276,6 +276,7 @@ - (instancetype)initWithName:(NSString*)labelPrefix
276276
object:nil];
277277

278278
[self setUpLifecycleNotifications:center];
279+
[self updateGpuAvailabilityFromLifecycleState];
279280

280281
[center addObserver:self
281282
selector:@selector(onLocaleUpdated:)
@@ -292,6 +293,31 @@ + (FlutterEngine*)engineForIdentifier:(int64_t)identifier {
292293
return (__bridge FlutterEngine*)reinterpret_cast<void*>(identifier);
293294
}
294295

296+
// Updates `isGpuDisabled` from the current lifecycle state and propagates to shell if available.
297+
//
298+
// The state has to be manually read at points where we don't receive a state transition:
299+
// * When the engine is created, to determine if background or foreground.
300+
// * In app extensions, when a view controller is attached or detached.
301+
//
302+
// In an app extension, the state may be unreadable: there is no `UIApplication`, and the scene is
303+
// nil until the attached view controller's view is attached to a window's view hierarchy. In these
304+
// cases, we leave `isGpuDisabled` unmodified. This avoids the possibility of a crash from
305+
// incorrectly re-enabling the GPU on an engine that was disabled during backgrounding.
306+
- (void)updateGpuAvailabilityFromLifecycleState {
307+
// When UIApplication.sharedApplication is available, it's authoritative.
308+
UIApplication* application = FlutterSharedApplication.application;
309+
if (application) {
310+
self.isGpuDisabled = application.applicationState == UIApplicationStateBackground;
311+
return;
312+
}
313+
314+
// Otherwise, check if the view is attached to a Window, and query the scene.
315+
UIWindowScene* scene = self.viewController.viewIfLoaded.window.windowScene;
316+
if (scene) {
317+
self.isGpuDisabled = scene.activationState == UISceneActivationStateBackground;
318+
}
319+
}
320+
295321
- (void)setUpLifecycleNotifications:(NSNotificationCenter*)center {
296322
// If the application is not available, use the scene for lifecycle notifications if available.
297323
[center addObserver:self
@@ -520,6 +546,10 @@ - (void)ensureSemanticsEnabled {
520546
- (void)setViewController:(FlutterViewController*)viewController {
521547
FML_DCHECK(self.platformView);
522548
_viewController = viewController;
549+
550+
// Attaching a view controller makes it possible for app extensions to check GPU availability.
551+
[self updateGpuAvailabilityFromLifecycleState];
552+
523553
self.platformView->SetOwnerViewController(_viewController);
524554
[self maybeSetupPlatformViewChannels];
525555
[self updateDisplays];
@@ -928,13 +958,6 @@ - (BOOL)createShell:(NSString*)entrypoint
928958
_threadHost->io_thread->GetTaskRunner() // io
929959
);
930960

931-
// Disable GPU if the app or scene is running in the background.
932-
self.isGpuDisabled = self.viewController
933-
? self.viewController.stateIsBackground
934-
: FlutterSharedApplication.application &&
935-
FlutterSharedApplication.application.applicationState ==
936-
UIApplicationStateBackground;
937-
938961
// Create the shell. This is a blocking operation.
939962
std::unique_ptr<flutter::Shell> shell = flutter::Shell::Create(
940963
/*platform_data=*/platformData,
@@ -1474,6 +1497,12 @@ - (void)onMemoryWarning:(NSNotification*)notification {
14741497
}
14751498

14761499
- (void)setIsGpuDisabled:(BOOL)value {
1500+
// `fml::SyncSwitch::SetSwitch` notifies its observers whether or not the value changed and is a
1501+
// blocking call. The Metal backend observes it to drain pending image uploads or flush tasks
1502+
// awaiting the GPU. Bail out early if unchanged so we only propagate state changes.
1503+
if (value == _isGpuDisabled) {
1504+
return;
1505+
}
14771506
if (_shell) {
14781507
_shell->SetGpuAvailability(value ? flutter::GpuAvailability::kUnavailable
14791508
: flutter::GpuAvailability::kAvailable);

‎engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEngineTest.mm‎

Lines changed: 134 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -544,35 +544,85 @@ - (void)testLifeCycleNotificationWillEnterForegroundForScene {
544544
[mockBundle stopMocking];
545545
}
546546

547-
// Locks in current behaviour for GPU state reset, which is arguably wrong.
547+
// Verifies a value assigned to `isGpuDisabled` before the engine runs is set on the shell.
548548
//
549-
// If `isGpuDisabled` is set before the engine runs, it is silently discarded, because
550-
// `createShell:` assigns to the property from the live view controller or application state
551-
// immediately before creating the shell.
549+
// The property is public and readwrite, so an embedder that knows it is starting an engine into the
550+
// background can set it before `run`. Reading the lifecycle state anywhere on the creation path
551+
// would overwrite that assignment, and the caller has no way to observe it happening.
552552
//
553-
// `createShell:` *does* need to sample the current lifecycle state there. Background/foreground
554-
// notifications only fire on transitions, so an engine created while the app is already
555-
// backgrounded would otherwise never know about it. However, this sampling is implemented as an
556-
// unconditional assignment to a public readwrite property, so it also destroys any state previously
557-
// set by the caller.
553+
// See: https://github.com/flutter/flutter/issues/190835
554+
- (void)testGpuStateSetBeforeRunIsAppliedToShell {
555+
FlutterDartProject* project = [[FlutterDartProject alloc] init];
556+
FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:project];
557+
558+
engine.isGpuDisabled = YES;
559+
XCTAssertTrue(engine.isGpuDisabled);
560+
561+
[engine run];
562+
563+
XCTAssertTrue(engine.isGpuDisabled);
564+
565+
BOOL gpuDisabled = NO;
566+
[engine shell].GetIsGpuDisabledSyncSwitch()->Execute(
567+
fml::SyncSwitch::Handlers().SetIfTrue([&] { gpuDisabled = YES; }).SetIfFalse([&] {
568+
gpuDisabled = NO;
569+
}));
570+
XCTAssertTrue(gpuDisabled);
571+
}
572+
573+
// Verifies an engine created while the application is backgrounded starts with the GPU disabled.
558574
//
559-
// TODO(cbracken): https://github.com/flutter/flutter/issues/190835
575+
// Lifecycle notifications only report transitions. Verify that we explicitly check GPU state on
576+
// creation.
560577
//
561-
// Move this sampling to `init` and `setViewController:` and stop `createShell:` from clobbering
562-
// this state, then change this test to asserts the opposite of what it currently does.
563-
- (void)testGpuStateIsDerivedFromApplicationStateWhenShellIsCreated {
578+
// See: https://github.com/flutter/flutter/issues/190835
579+
- (void)testGpuIsDisabledWhenCreatedWhileBackgrounded {
580+
id mockApplication = OCMClassMock([UIApplication class]);
581+
OCMStub([mockApplication sharedApplication]).andReturn(mockApplication);
582+
OCMStub([mockApplication applicationState]).andReturn(UIApplicationStateBackground);
583+
[self addTeardownBlock:^{
584+
[mockApplication stopMocking];
585+
}];
586+
564587
FlutterDartProject* project = [[FlutterDartProject alloc] init];
565588
FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:project];
566589

567-
// Claim the GPU is disabled before the shell exists.
568-
//
569-
// There is no view controller and the test host is foregrounded, so creating the shell must
570-
// overwrite this with NO.
571-
engine.isGpuDisabled = YES;
590+
// Read at init. No notification could have arrived yet.
572591
XCTAssertTrue(engine.isGpuDisabled);
573592

574593
[engine run];
575594

595+
BOOL gpuDisabled = NO;
596+
[engine shell].GetIsGpuDisabledSyncSwitch()->Execute(
597+
fml::SyncSwitch::Handlers().SetIfTrue([&] { gpuDisabled = YES; }).SetIfFalse([&] {
598+
gpuDisabled = NO;
599+
}));
600+
XCTAssertTrue(gpuDisabled);
601+
}
602+
603+
// Verifies an engine created while the app is foregrounded starts with the GPU available, and that
604+
// detaching a view controller re-enables the GPU on an engine that currently has it disabled.
605+
//
606+
// Attaching or detaching a view controller must re-read the lifecycle state and update the current
607+
// engine GPU state. An engine disabled by an earlier background transition must come back up with
608+
// the GPU available once the application reads as foregrounded.
609+
//
610+
// This is specifically testing *app* scenarios, where `UIApplication.sharedApplication` is
611+
// available.
612+
//
613+
// See: https://github.com/flutter/flutter/issues/190835
614+
- (void)testGpuIsEnabledWhenCreatedWhileForegrounded {
615+
id mockApplication = OCMClassMock([UIApplication class]);
616+
OCMStub([mockApplication sharedApplication]).andReturn(mockApplication);
617+
OCMStub([mockApplication applicationState]).andReturn(UIApplicationStateActive);
618+
[self addTeardownBlock:^{
619+
[mockApplication stopMocking];
620+
}];
621+
622+
FlutterDartProject* project = [[FlutterDartProject alloc] init];
623+
FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:project];
624+
[engine run];
625+
576626
XCTAssertFalse(engine.isGpuDisabled);
577627

578628
BOOL gpuDisabled = YES;
@@ -581,6 +631,72 @@ - (void)testGpuStateIsDerivedFromApplicationStateWhenShellIsCreated {
581631
gpuDisabled = NO;
582632
}));
583633
XCTAssertFalse(gpuDisabled);
634+
635+
// Detaching re-reads the lifecycle state. The application is readable, so the read must overwrite
636+
// this rather than preserve it.
637+
engine.isGpuDisabled = YES;
638+
engine.viewController = nil;
639+
640+
XCTAssertFalse(engine.isGpuDisabled);
641+
642+
gpuDisabled = YES;
643+
[engine shell].GetIsGpuDisabledSyncSwitch()->Execute(
644+
fml::SyncSwitch::Handlers().SetIfTrue([&] { gpuDisabled = YES; }).SetIfFalse([&] {
645+
gpuDisabled = NO;
646+
}));
647+
XCTAssertFalse(gpuDisabled);
648+
}
649+
650+
// Verifies that detaching a view controller leaves the GPU disabled when the lifecycle state cannot
651+
// be read.
652+
//
653+
// Attaching or detaching a view controller re-reads the lifecycle state. In an app extension, there
654+
// is no `UIApplication`, and no scene without a view controller whose view is attached to a
655+
// window's view hierarchy, so we have no source to check. The value determined by the last scene
656+
// notification is the only information available, so we preserve that.
657+
//
658+
// In particular, an engine disabled while its scene is backgrounded must stay disabled, since
659+
// rendering in the background will result in app termination.
660+
//
661+
// See: https://github.com/flutter/flutter/issues/190835
662+
- (void)testGpuStateIsPreservedWhenLifecycleStateIsUnknown {
663+
// Declaring `NSExtension` puts `FlutterSharedApplication` into its app extension configuration
664+
// rather than stubbing its result.
665+
//
666+
// `isAvailable` is NO, `application` returns nil without touching `UIApplication`, and the engine
667+
// registers the scene observers rather than the application ones.
668+
id mockBundle = OCMPartialMock([NSBundle mainBundle]);
669+
OCMStub([mockBundle objectForInfoDictionaryKey:@"NSExtension"]).andReturn(@{
670+
@"NSExtensionPointIdentifier" : @"com.apple.share-services"
671+
});
672+
[self addTeardownBlock:^{
673+
[mockBundle stopMocking];
674+
}];
675+
XCTAssertNil(FlutterSharedApplication.application);
676+
677+
FlutterDartProject* project = [[FlutterDartProject alloc] init];
678+
FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"foobar" project:project];
679+
[engine run];
680+
681+
// The scene notification is the only signal available in this configuration, and the engine is
682+
// observing for it because the bundle declares an extension.
683+
[[NSNotificationCenter defaultCenter]
684+
postNotification:[NSNotification notificationWithName:UISceneDidEnterBackgroundNotification
685+
object:nil
686+
userInfo:nil]];
687+
XCTAssertTrue(engine.isGpuDisabled);
688+
689+
// Detaching re-reads the lifecycle state, and must find no source to overwrite the above with.
690+
engine.viewController = nil;
691+
692+
XCTAssertTrue(engine.isGpuDisabled);
693+
694+
BOOL gpuDisabled = NO;
695+
[engine shell].GetIsGpuDisabledSyncSwitch()->Execute(
696+
fml::SyncSwitch::Handlers().SetIfTrue([&] { gpuDisabled = YES; }).SetIfFalse([&] {
697+
gpuDisabled = NO;
698+
}));
699+
XCTAssertTrue(gpuDisabled);
584700
}
585701

586702
// Verifies a handler registered against a background FlutterTaskQueue runs off the platform thread.

0 commit comments

Comments
 (0)