Skip to content

Commit 7880b86

Browse files
fix: stop the macOS app crashing in the background (#4)
## Problem XPath 1.0.0 (54) crashed on macOS 26.7.1 while it was in the background: `EXC_BAD_ACCESS` at `0x0` on `io.flutter.raster`, in `impeller::Canvas::SetupRenderPass()` (canvas.cc:1615), called from `EmbedderExternalViewEmbedder::SubmitFlutterView`. ## Root cause: a Flutter engine bug This is [flutter/flutter#185394](flutter/flutter#185394), "[Impeller] Crash on macOS when app is foregrounded" (open, P2, team-macos). The macOS back-buffer cache (`FlutterBackBufferCache`) can hand back a surface of the wrong size when the window's frame size changes and then changes back (A → B → A). Examples are a display hot-plug or reconfiguration, a Space or full-screen change, a window drag, or bringing the app to the front. Impeller wraps the mismatched `MTLTexture`, the texture invalidates itself, and the render target silently drops it. `SetupRenderPass` then dereferences the null texture. - Fix: [flutter/flutter#192522](flutter/flutter#192522) is still **open** (not merged). It is not in 3.47.7 (the latest stable, per its CHANGELOG) or in the 3.50 beta. - Also reported: #193095 (same stack) and #192829 (Cmd-Tab on macOS 27, closed as a duplicate). **Reproduced on our pinned SDK (3.47.6, release build).** This used a minimal scratch app, not XPath. A Swift timer shrinks the window by 1 pt and restores it every 2.5 s, which is the driver from #192522. The Flutter side redraws a text once a second, the way `XpClock` does: | Renderer | UI | Result | |---|---|---| | Impeller (default) | 1 s ticking text | **SIGSEGV after 5 s, at flip #1.** The stack matches the field crash frame for frame (canvas.cc:1615 / 372, dl_dispatcher.cc:1318, embedder_external_view_embedder.cc:376 / 598). | | Impeller | still UI | survived 60 s (17 flips) | | Skia (`FLTEnableImpeller=false`) | 1 s ticking text | **survived 90 s (36 flips)**, with no validation errors and the log line `Using the Skia rendering backend (Metal).` | ## Changes 1. **`macos/Runner/Info.plist`: `FLTEnableImpeller = false`** (with a comment linking the issues). I checked the 3.47.6 engine source to confirm macOS still reads this key: `FlutterDartProject.enableImpeller` reads it, and `FlutterEngine runWithEntrypoint` then skips `--enable-impeller=true` and uses Skia (Metal). XPath uses no Impeller-only features (no fragment shaders, Flutter GPU or backdrop filters). Goldens and widget tests are unaffected because `flutter test` does not read `Info.plist`. 2. **`XpClock` follows the app lifecycle** using an `AppLifecycleListener`. It ticks only while the app is `resumed`. When the app is `inactive` (visible but not in front), `hidden` (occluded or minimised) or `paused`, the timer stops. On resume, every live duration is rebuilt at once against the current time. The new `XpClock.isLive(context)` tells widgets whether the app is in front. 3. **`XpSpinner`** stands still while `!XpClock.isLive`, as it already does under Reduce Motion. Change 1 is the fix. Changes 2 and 3 mean XPath draws no frames of its own while it is not in front (it used to draw one a second for the clock, and 60 fps per spinner). That lowers the crash exposure and saves CPU and battery. On its own it does **not** fix the engine bug: a display change still causes a frame, and upstream reports idle apps crashing too. ## Tests `apps/xp_desktop/test/widgets/xp_clock_test.dart` drives the real `flutter/lifecycle` platform channel, the same messages the macOS embedder sends: - `XpClock ticks every second while the app is in front` - `XpClock stops while inactive|hidden|paused and catches up on resume` - `XpClock a still clock stays still in front and away` - `XpClock starts still when the app is already away` - `XpClock without a clock above, the system time is live` - `XpClock spinners stand still while the app is away` ## Trade-offs and follow-ups - Skia is Flutter's legacy renderer on macOS. The Flutter docs warn that the Impeller opt-out will be removed in a future release, and with Skia there is no wide-gamut colour. Once a Flutter stable ships #192522, remove the key (the Info.plist comment says so). - While XPath is visible but not in front, elapsed times stay frozen until it comes back to the front, and then catch up at once.
1 parent cb6e796 commit 7880b86

4 files changed

Lines changed: 223 additions & 10 deletions

File tree

‎apps/xp_desktop/lib/widgets/xp_clock.dart‎

Lines changed: 56 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,13 @@ import 'package:flutter/widgets.dart';
88
/// [ticking]. Without an `XpClock` above, the time is the system's and
99
/// nothing ticks, which keeps widget tests still; the app puts a ticking one
1010
/// at its root.
11+
///
12+
/// Live motion only runs while the app is in front (`resumed`): when macOS
13+
/// reports XPath inactive, hidden or minimised, the clock stops and
14+
/// [XpClock.isLive] turns false so spinners stand still, and XPath draws no
15+
/// frames of its own in the background (each one is a chance to hit the
16+
/// Impeller crash of flutter/flutter#185394). Back in front, every live
17+
/// duration is rebuilt at once against the current time.
1118
class XpClock extends StatefulWidget {
1219
const new({
1320
required this.child,
@@ -31,34 +38,66 @@ class XpClock extends StatefulWidget {
3138
return scope == null ? DateTime.now() : scope.now();
3239
}
3340

41+
/// Whether the app is in front, so live motion may run; rebuilds [context]
42+
/// when that changes. True without an `XpClock` above.
43+
static bool isLive(BuildContext context) =>
44+
context.dependOnInheritedWidgetOfExactType<_LiveScope>()?.live ?? true;
45+
3446
@override
3547
State<XpClock> createState() => _XpClockState();
3648
}
3749

3850
class _XpClockState extends State<XpClock> {
51+
late final AppLifecycleListener _lifecycle;
3952
Timer? _timer;
4053
var _tick = 0;
54+
var _live = true;
4155

4256
@override
4357
void initState() {
4458
super.initState();
45-
if (widget.ticking) {
46-
_timer = Timer.periodic(
47-
const Duration(seconds: 1),
48-
(_) => setState(() => _tick++),
49-
);
50-
}
59+
_live = _inFront(WidgetsBinding.instance.lifecycleState);
60+
_lifecycle = AppLifecycleListener(onStateChange: _onLifecycleChanged);
61+
_schedule();
62+
}
63+
64+
/// Before the first lifecycle message the app counts as in front.
65+
static bool _inFront(AppLifecycleState? state) =>
66+
state == null || state == AppLifecycleState.resumed;
67+
68+
void _onLifecycleChanged(AppLifecycleState state) {
69+
final live = _inFront(state);
70+
if (live == _live) return;
71+
setState(() {
72+
_live = live;
73+
// Back in front: show the time that passed while the app was away.
74+
if (live) _tick++;
75+
});
76+
_schedule();
77+
}
78+
79+
void _schedule() {
80+
_timer?.cancel();
81+
_timer = widget.ticking && _live
82+
? Timer.periodic(
83+
const Duration(seconds: 1),
84+
(_) => setState(() => _tick++),
85+
)
86+
: null;
5187
}
5288

5389
@override
5490
void dispose() {
91+
_lifecycle.dispose();
5592
_timer?.cancel();
5693
super.dispose();
5794
}
5895

5996
@override
60-
Widget build(BuildContext context) =>
61-
_ClockScope(now: widget.clock, tick: _tick, child: widget.child);
97+
Widget build(BuildContext context) => _LiveScope(
98+
live: _live,
99+
child: _ClockScope(now: widget.clock, tick: _tick, child: widget.child),
100+
);
62101
}
63102

64103
class _ClockScope extends InheritedWidget {
@@ -71,3 +110,12 @@ class _ClockScope extends InheritedWidget {
71110
bool updateShouldNotify(_ClockScope oldWidget) =>
72111
tick != oldWidget.tick || now != oldWidget.now;
73112
}
113+
114+
class _LiveScope extends InheritedWidget {
115+
const new({required this.live, required super.child});
116+
117+
final bool live;
118+
119+
@override
120+
bool updateShouldNotify(_LiveScope oldWidget) => live != oldWidget.live;
121+
}

‎apps/xp_desktop/lib/widgets/xp_spinner.dart‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
import 'package:material_ui/material_ui.dart';
22
import 'package:xp_desktop/theme/theme.dart';
3+
import 'package:xp_desktop/widgets/xp_clock.dart';
34

45
/// An icon that turns: the running arc once per `motion.duration.spin`, or
56
/// the reconnecting arrows once per `motion.duration.pulse` ([slow]).
67
///
7-
/// Under Reduce Motion it stands still (Status, "Running treatment").
8+
/// Under Reduce Motion it stands still (Status, "Running treatment"), and
9+
/// while the app is not in front (`XpClock.isLive`).
810
class XpSpinner extends StatefulWidget {
911
const new({
1012
required this.icon,
@@ -33,7 +35,8 @@ class _XpSpinnerState extends State<XpSpinner>
3335
void didChangeDependencies() {
3436
super.didChangeDependencies();
3537
final motion = context.xpMotion;
36-
final still = MediaQuery.disableAnimationsOf(context);
38+
final still =
39+
MediaQuery.disableAnimationsOf(context) || !XpClock.isLive(context);
3740
_controller.duration = widget.slow
3841
? motion.durationPulse
3942
: motion.durationSpin;

‎apps/xp_desktop/macos/Runner/Info.plist‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,15 @@
2020
<string>$(FLUTTER_BUILD_NAME)</string>
2121
<key>CFBundleVersion</key>
2222
<string>$(FLUTTER_BUILD_NUMBER)</string>
23+
<!--
24+
Render with Skia (Metal) instead of Impeller. Impeller on macOS crashes
25+
the raster thread (null texture in Canvas::SetupRenderPass) when the
26+
window's frame size changes back and forth, e.g. on a display or Space
27+
change while XPath is in the background: flutter/flutter#185394, fix in
28+
flutter/flutter#192522. Remove this key once a Flutter stable ships it.
29+
-->
30+
<key>FLTEnableImpeller</key>
31+
<false/>
2332
<key>LSMinimumSystemVersion</key>
2433
<string>$(MACOSX_DEPLOYMENT_TARGET)</string>
2534
<key>NSHumanReadableCopyright</key>
Lines changed: 153 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,153 @@
1+
import 'package:flutter/services.dart';
2+
import 'package:flutter_test/flutter_test.dart';
3+
import 'package:material_ui/material_ui.dart';
4+
import 'package:xp_desktop/theme/theme.dart';
5+
import 'package:xp_desktop/widgets/widgets.dart';
6+
7+
import '../helpers/pump_app.dart';
8+
9+
/// Sends [state] the way the macOS embedder does: a message on the
10+
/// lifecycle channel, from which Flutter derives the transitions.
11+
Future<void> lifecycle(WidgetTester tester, AppLifecycleState state) async {
12+
await tester.binding.defaultBinaryMessenger.handlePlatformMessage(
13+
SystemChannels.lifecycle.name,
14+
SystemChannels.lifecycle.codec.encodeMessage(state.toString()),
15+
(_) {},
16+
);
17+
}
18+
19+
/// What the clock shows: the seconds of the current time, and whether live
20+
/// motion runs.
21+
class _Readout extends StatelessWidget {
22+
const new();
23+
24+
@override
25+
Widget build(BuildContext context) => Text(
26+
'${XpClock.now(context).second} ${XpClock.isLive(context)}',
27+
textDirection: TextDirection.ltr,
28+
);
29+
}
30+
31+
void main() {
32+
group('XpClock', () {
33+
late DateTime now;
34+
35+
setUp(() => now = DateTime(2026, 10, 13, 14, 8));
36+
37+
Future<void> pumpClock(WidgetTester tester, {bool ticking = true}) async {
38+
await lifecycle(tester, AppLifecycleState.resumed);
39+
addTearDown(() => lifecycle(tester, AppLifecycleState.resumed));
40+
await tester.pumpWidget(
41+
XpClock(clock: () => now, ticking: ticking, child: const _Readout()),
42+
);
43+
}
44+
45+
/// Moves the fake clock and the test's timers on by [seconds].
46+
Future<void> wait(WidgetTester tester, int seconds) async {
47+
now = now.add(Duration(seconds: seconds));
48+
await tester.pump(Duration(seconds: seconds));
49+
}
50+
51+
testWidgets('ticks every second while the app is in front', (tester) async {
52+
await pumpClock(tester);
53+
expect(find.text('0 true'), findsOneWidget);
54+
55+
await wait(tester, 1);
56+
expect(find.text('1 true'), findsOneWidget);
57+
await wait(tester, 1);
58+
expect(find.text('2 true'), findsOneWidget);
59+
});
60+
61+
for (final away in [
62+
AppLifecycleState.inactive,
63+
AppLifecycleState.hidden,
64+
AppLifecycleState.paused,
65+
]) {
66+
testWidgets('stops while ${away.name} and catches up on resume', (
67+
tester,
68+
) async {
69+
await pumpClock(tester);
70+
await lifecycle(tester, away);
71+
await tester.pump();
72+
expect(find.text('0 false'), findsOneWidget);
73+
74+
await wait(tester, 5);
75+
expect(find.text('0 false'), findsOneWidget, reason: 'no tick');
76+
77+
await lifecycle(tester, AppLifecycleState.resumed);
78+
await tester.pump();
79+
expect(find.text('5 true'), findsOneWidget, reason: 'fresh time');
80+
81+
await wait(tester, 1);
82+
expect(find.text('6 true'), findsOneWidget, reason: 'ticks again');
83+
});
84+
}
85+
86+
testWidgets('a still clock stays still in front and away', (tester) async {
87+
await pumpClock(tester, ticking: false);
88+
await wait(tester, 2);
89+
expect(find.text('0 true'), findsOneWidget);
90+
91+
await lifecycle(tester, AppLifecycleState.inactive);
92+
await lifecycle(tester, AppLifecycleState.resumed);
93+
await tester.pump();
94+
expect(find.text('2 true'), findsOneWidget, reason: 'resume rebuilds');
95+
});
96+
97+
testWidgets('starts still when the app is already away', (tester) async {
98+
// Inactive, not hidden: Flutter draws no frames at all while hidden.
99+
await lifecycle(tester, AppLifecycleState.inactive);
100+
addTearDown(() => lifecycle(tester, AppLifecycleState.resumed));
101+
await tester.pumpWidget(
102+
XpClock(clock: () => now, child: const _Readout()),
103+
);
104+
await wait(tester, 3);
105+
expect(find.text('0 false'), findsOneWidget);
106+
107+
await lifecycle(tester, AppLifecycleState.resumed);
108+
await tester.pump();
109+
expect(find.text('3 true'), findsOneWidget);
110+
});
111+
112+
testWidgets('without a clock above, the system time is live', (
113+
tester,
114+
) async {
115+
await tester.pumpWidget(
116+
Builder(
117+
builder: (context) => Text(
118+
'${XpClock.isLive(context)}',
119+
textDirection: TextDirection.ltr,
120+
),
121+
),
122+
);
123+
expect(find.text('true'), findsOneWidget);
124+
});
125+
126+
testWidgets('spinners stand still while the app is away', (tester) async {
127+
await lifecycle(tester, AppLifecycleState.resumed);
128+
addTearDown(() => lifecycle(tester, AppLifecycleState.resumed));
129+
await tester.pumpWidget(
130+
themed(
131+
const XpSpinner(
132+
icon: PhosphorIconsRegular.circleNotch,
133+
size: 14,
134+
color: Color(0xFF000000),
135+
),
136+
),
137+
);
138+
Animation<double> turns() => tester
139+
.widget<RotationTransition>(find.byType(RotationTransition))
140+
.turns;
141+
expect(turns().isAnimating, isTrue);
142+
143+
await lifecycle(tester, AppLifecycleState.inactive);
144+
await tester.pump();
145+
expect(turns().isAnimating, isFalse);
146+
147+
await lifecycle(tester, AppLifecycleState.resumed);
148+
await tester.pump();
149+
expect(turns().isAnimating, isTrue);
150+
await tester.pumpWidget(const SizedBox());
151+
});
152+
});
153+
}

0 commit comments

Comments
 (0)