Skip to content

Commit e1f4cfb

Browse files
[flutter_tools] add toggle b and service extension to change platform brightness (#59571)
A frequent request from the last Flutter developer survey was for an easier method of testing light/dark mode changes. Currently, a user needs to manually change the theme settings or adjust phone settings to see the difference. Instead we should add a toggle from the CLI, and eventually devtools/Intellij/Vscode that allows developers to override the current setting. Fixes #59495 Adds flutter.ext.brightnessOverride service protocol which either queries the current platform brightness, or overrides it to a new value. This accepts either Brightness.light or Brightness.dark as a value. Adds a CLI toggle b which allows the setting to be toggled manually. Requires an update to the MediaQuery, to conditionally use a debug override when not in release mode
1 parent f39ab52 commit e1f4cfb

12 files changed

Lines changed: 282 additions & 24 deletions

File tree

‎packages/flutter/lib/src/foundation/binding.dart‎

Lines changed: 28 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import 'dart:async';
88
import 'dart:convert' show json;
99
import 'dart:developer' as developer;
1010
import 'dart:io' show exit;
11-
import 'dart:ui' as ui show saveCompilationTrace, Window, window;
11+
import 'dart:ui' as ui show Window, window, Brightness;
1212
// Before adding any more dart:ui imports, please read the README.
1313

1414
import 'package:meta/meta.dart';
@@ -143,14 +143,6 @@ abstract class BindingBase {
143143
name: 'exit',
144144
callback: _exitApplication,
145145
);
146-
registerServiceExtension(
147-
name: 'saveCompilationTrace',
148-
callback: (Map<String, String> parameters) async {
149-
return <String, dynamic>{
150-
'value': ui.saveCompilationTrace(),
151-
};
152-
},
153-
);
154146
}
155147

156148
assert(() {
@@ -195,6 +187,33 @@ abstract class BindingBase {
195187
};
196188
},
197189
);
190+
191+
const String brightnessOverrideExtensionName = 'brightnessOverride';
192+
registerServiceExtension(
193+
name: brightnessOverrideExtensionName,
194+
callback: (Map<String, String> parameters) async {
195+
if (parameters.containsKey('value')) {
196+
switch (parameters['value']) {
197+
case 'Brightness.light':
198+
debugBrightnessOverride = ui.Brightness.light;
199+
break;
200+
case 'Brightness.dark':
201+
debugBrightnessOverride = ui.Brightness.dark;
202+
break;
203+
default:
204+
debugBrightnessOverride = null;
205+
}
206+
_postExtensionStateChangedEvent(
207+
brightnessOverrideExtensionName,
208+
(debugBrightnessOverride ?? window.platformBrightness).toString(),
209+
);
210+
await reassembleApplication();
211+
}
212+
return <String, dynamic>{
213+
'value': (debugBrightnessOverride ?? window.platformBrightness).toString(),
214+
};
215+
},
216+
);
198217
return true;
199218
}());
200219
assert(() {

‎packages/flutter/lib/src/foundation/debug.dart‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
// @dart = 2.8
66

77
import 'dart:async';
8+
import 'dart:ui' as ui show Brightness;
89

910
import 'assertions.dart';
1011
import 'platform.dart';
@@ -27,7 +28,8 @@ bool debugAssertAllFoundationVarsUnset(String reason, { DebugPrintCallback debug
2728
assert(() {
2829
if (debugPrint != debugPrintOverride ||
2930
debugDefaultTargetPlatformOverride != null ||
30-
debugDoublePrecision != null)
31+
debugDoublePrecision != null ||
32+
debugBrightnessOverride != null)
3133
throw FlutterError(reason);
3234
return true;
3335
}());
@@ -99,3 +101,12 @@ String debugFormatDouble(double value) {
99101
}
100102
return value.toStringAsFixed(1);
101103
}
104+
105+
/// A setting that can be used to override the platform [Brightness] exposed
106+
/// from [BindingBase.window].
107+
///
108+
/// See also:
109+
///
110+
/// * [WidgetsApp], which uses the [debugBrightnessOverride] setting in debug mode
111+
/// to construct a [MediaQueryData].
112+
ui.Brightness debugBrightnessOverride;

‎packages/flutter/lib/src/widgets/app.dart‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1474,8 +1474,12 @@ class _MediaQueryFromWindowsState extends State<_MediaQueryFromWindow> with Widg
14741474

14751475
@override
14761476
Widget build(BuildContext context) {
1477+
MediaQueryData data = MediaQueryData.fromWindow(WidgetsBinding.instance.window);
1478+
if (!kReleaseMode) {
1479+
data = data.copyWith(platformBrightness: debugBrightnessOverride);
1480+
}
14771481
return MediaQuery(
1478-
data: MediaQueryData.fromWindow(WidgetsBinding.instance.window),
1482+
data: data,
14791483
child: widget.child,
14801484
);
14811485
}

‎packages/flutter/test/foundation/service_extensions_test.dart‎

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -167,9 +167,8 @@ void main() {
167167

168168
// The following service extensions are disabled in web:
169169
// 1. exit
170-
// 2. saveCompilationTrace
171-
// 3. showPerformanceOverlay
172-
const int disabledExtensions = kIsWeb ? 3 : 0;
170+
// 2. showPerformanceOverlay
171+
const int disabledExtensions = kIsWeb ? 2 : 0;
173172
// If you add a service extension... TEST IT! :-)
174173
// ...then increment this number.
175174
expect(binding.extensions.length, 28 + widgetInspectorExtensionCount - disabledExtensions);
@@ -711,15 +710,13 @@ void main() {
711710
expect(binding.frameScheduled, isFalse);
712711
});
713712

714-
test('Service extensions - saveCompilationTrace', () async {
713+
test('Service extensions - brightnessOverride', () async {
715714
Map<String, dynamic> result;
716-
result = await binding.testExtension('saveCompilationTrace', <String, String>{});
717-
final String trace = String.fromCharCodes((result['value'] as List<dynamic>).cast<int>());
718-
expect(trace, contains('dart:core,Object,Object.\n'));
719-
expect(trace, contains('package:test_api/test_api.dart,::,test\n'));
720-
expect(trace, contains('service_extensions_test.dart,::,main\n'));
721-
}, skip: isBrowser); // Compilation trace is Dart VM specific and not
722-
// supported in browsers.
715+
result = await binding.testExtension('brightnessOverride', <String, String>{});
716+
final String brightnessValue = result['value'] as String;
717+
718+
expect(brightnessValue, 'Brightness.light');
719+
});
723720

724721
test('Service extensions - fastReassemble', () async {
725722
Map<String, dynamic> result;

‎packages/flutter/test/material/app_test.dart‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ import 'package:flutter/semantics.dart';
88
import 'package:flutter_test/flutter_test.dart';
99
import 'package:flutter/cupertino.dart';
1010
import 'package:flutter/material.dart';
11-
import 'package:mockito/mockito.dart';
1211

1312
class StateMarker extends StatefulWidget {
1413
const StateMarker({ Key key, this.child }) : super(key: key);
@@ -837,4 +836,22 @@ void main() {
837836
});
838837
}
839838

840-
class MockAccessibilityFeature extends Mock implements AccessibilityFeatures {}
839+
class MockAccessibilityFeature implements AccessibilityFeatures {
840+
@override
841+
bool get accessibleNavigation => true;
842+
843+
@override
844+
bool get boldText => true;
845+
846+
@override
847+
bool get disableAnimations => true;
848+
849+
@override
850+
bool get highContrast => true;
851+
852+
@override
853+
bool get invertColors => true;
854+
855+
@override
856+
bool get reduceMotion => true;
857+
}

‎packages/flutter_tools/lib/src/base/command_help.dart‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,13 @@ class CommandHelp {
7676
'debugProfileWidgetBuilds',
7777
);
7878

79+
CommandHelpOption _b;
80+
CommandHelpOption get b => _b ??= _makeOption(
81+
'b',
82+
'Toggle the platform brightness setting (dark and light mode).',
83+
'debugBrightnessOverride',
84+
);
85+
7986
CommandHelpOption _c;
8087
CommandHelpOption get c => _c ??= _makeOption(
8188
'c',

‎packages/flutter_tools/lib/src/build_runner/resident_web_runner.dart‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -264,6 +264,30 @@ abstract class ResidentWebRunner extends ResidentRunner {
264264
}
265265
}
266266

267+
@override
268+
Future<void> debugToggleBrightness() async {
269+
try {
270+
final Brightness currentBrightness = await _vmService
271+
?.flutterBrightnessOverride(
272+
isolateId: null,
273+
);
274+
Brightness next;
275+
if (currentBrightness == Brightness.light) {
276+
next = Brightness.dark;
277+
} else if (currentBrightness == Brightness.dark) {
278+
next = Brightness.light;
279+
}
280+
next = await _vmService
281+
?.flutterBrightnessOverride(
282+
brightness: next,
283+
isolateId: null,
284+
);
285+
globals.logger.printStatus('Changed brightness to $next.');
286+
} on vmservice.RPCError {
287+
return;
288+
}
289+
}
290+
267291
@override
268292
Future<void> stopEchoingDeviceLog() async {
269293
// Do nothing for ResidentWebRunner

‎packages/flutter_tools/lib/src/resident_runner.dart‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -425,6 +425,24 @@ class FlutterDevice {
425425
}
426426
}
427427

428+
Future<Brightness> toggleBrightness({ Brightness current }) async {
429+
final List<FlutterView> views = await vmService.getFlutterViews();
430+
Brightness next;
431+
if (current == Brightness.light) {
432+
next = Brightness.dark;
433+
} else if (current == Brightness.dark) {
434+
next = Brightness.light;
435+
}
436+
437+
for (final FlutterView view in views) {
438+
next = await vmService.flutterBrightnessOverride(
439+
isolateId: view.uiIsolate.id,
440+
brightness: next,
441+
);
442+
}
443+
return next;
444+
}
445+
428446
Future<String> togglePlatform({ String from }) async {
429447
final List<FlutterView> views = await vmService.getFlutterViews();
430448
final String to = nextPlatform(from, featureFlags);
@@ -973,6 +991,17 @@ abstract class ResidentRunner {
973991
}
974992
}
975993

994+
Future<void> debugToggleBrightness() async {
995+
final Brightness brightness = await flutterDevices.first.toggleBrightness();
996+
Brightness next;
997+
for (final FlutterDevice device in flutterDevices) {
998+
next = await device.toggleBrightness(
999+
current: brightness,
1000+
);
1001+
globals.logger.printStatus('Changed brightness to $next.');
1002+
}
1003+
}
1004+
9761005
/// Take a screenshot on the provided [device].
9771006
///
9781007
/// If the device has a connected vmservice, this method will attempt to hide
@@ -1221,6 +1250,7 @@ abstract class ResidentRunner {
12211250
commandHelp.s.print();
12221251
}
12231252
if (supportsServiceProtocol) {
1253+
commandHelp.b.print();
12241254
commandHelp.w.print();
12251255
commandHelp.t.print();
12261256
if (isRunningDebug) {
@@ -1362,6 +1392,9 @@ class TerminalHandler {
13621392
return true;
13631393
}
13641394
return false;
1395+
case 'b':
1396+
await residentRunner.debugToggleBrightness();
1397+
return true;
13651398
case 'c':
13661399
residentRunner.clearScreen();
13671400
return true;

‎packages/flutter_tools/lib/src/vmservice.dart‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -708,6 +708,30 @@ extension FlutterVmService on vm_service.VmService {
708708
return 'unknown';
709709
}
710710

711+
/// Return the current brightness value for the flutter view running with
712+
/// the main isolate [isolateId].
713+
///
714+
/// If a non-null value is provided for [brightness], the brightness override
715+
/// is updated with this value.
716+
Future<Brightness> flutterBrightnessOverride({
717+
Brightness brightness,
718+
@required String isolateId,
719+
}) async {
720+
final Map<String, dynamic> result = await invokeFlutterExtensionRpcRaw(
721+
'ext.flutter.brightnessOverride',
722+
isolateId: isolateId,
723+
args: brightness != null
724+
? <String, dynamic>{'value': brightness.toString()}
725+
: <String, String>{},
726+
);
727+
if (result != null && result['value'] is String) {
728+
return (result['value'] as String) == 'Brightness.light'
729+
? Brightness.light
730+
: Brightness.dark;
731+
}
732+
return null;
733+
}
734+
711735
/// Invoke a flutter extension method, if the flutter extension is not
712736
/// available, returns null.
713737
Future<Map<String, dynamic>> invokeFlutterExtensionRpcRaw(
@@ -860,3 +884,19 @@ Future<String> sharedSkSlWriter(Device device, Map<String, Object> data, {
860884
globals.logger.printStatus('Wrote SkSL data to ${outputFile.path}.');
861885
return outputFile.path;
862886
}
887+
888+
/// A brightness enum that matches the values https://github.com/flutter/engine/blob/3a96741247528133c0201ab88500c0c3c036e64e/lib/ui/window.dart#L1328
889+
/// Describes the contrast of a theme or color palette.
890+
enum Brightness {
891+
/// The color is dark and will require a light text color to achieve readable
892+
/// contrast.
893+
///
894+
/// For example, the color might be dark grey, requiring white text.
895+
dark,
896+
897+
/// The color is light and will require a dark text color to achieve readable
898+
/// contrast.
899+
///
900+
/// For example, the color might be bright white, requiring black text.
901+
light,
902+
}

‎packages/flutter_tools/test/general.shard/resident_runner_test.dart‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -700,6 +700,7 @@ void main() {
700700
commandHelp.c,
701701
commandHelp.q,
702702
commandHelp.s,
703+
commandHelp.b,
703704
commandHelp.w,
704705
commandHelp.t,
705706
commandHelp.L,
@@ -1096,6 +1097,36 @@ void main() {
10961097
verify(mockFlutterDevice.toggleDebugPaintSizeEnabled()).called(1);
10971098
}));
10981099

1100+
testUsingContext('ResidentRunner debugToggleBrightness calls flutter device', () => testbed.run(() async {
1101+
fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
1102+
await residentRunner.debugToggleBrightness();
1103+
1104+
verify(mockFlutterDevice.toggleBrightness()).called(2);
1105+
}));
1106+
1107+
testUsingContext('FlutterDevice.toggleBrightness invokes correct VM service request', () => testbed.run(() async {
1108+
fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
1109+
listViews,
1110+
const FakeVmServiceRequest(
1111+
method: 'ext.flutter.brightnessOverride',
1112+
args: <String, Object>{
1113+
'isolateId': '1',
1114+
},
1115+
jsonResponse: <String, Object>{
1116+
'value': 'Brightness.dark'
1117+
},
1118+
),
1119+
]);
1120+
final FlutterDevice device = FlutterDevice(
1121+
mockDevice,
1122+
buildInfo: BuildInfo.debug,
1123+
);
1124+
device.vmService = fakeVmServiceHost.vmService;
1125+
1126+
expect(await device.toggleBrightness(), Brightness.dark);
1127+
expect(fakeVmServiceHost.hasRemainingExpectations, false);
1128+
}));
1129+
10991130
testUsingContext('ResidentRunner debugToggleDebugCheckElevationsEnabled calls flutter device', () => testbed.run(() async {
11001131
fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
11011132
await residentRunner.debugToggleDebugCheckElevationsEnabled();

0 commit comments

Comments
 (0)