diff --git a/app/ios/Runner.xcodeproj/project.pbxproj b/app/ios/Runner.xcodeproj/project.pbxproj index 17ec55b9..358c030a 100644 --- a/app/ios/Runner.xcodeproj/project.pbxproj +++ b/app/ios/Runner.xcodeproj/project.pbxproj @@ -12,6 +12,7 @@ 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; 7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */; }; + 7884E86A2EC3CC0700C636F2 /* WindowControlsPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7884E8692EC3CC0400C636F2 /* WindowControlsPlugin.swift */; }; 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; }; 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; @@ -50,6 +51,7 @@ 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; + 7884E8692EC3CC0400C636F2 /* WindowControlsPlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WindowControlsPlugin.swift; sourceTree = ""; }; 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; sourceTree = ""; }; 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; @@ -123,6 +125,7 @@ 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */, + 7884E8692EC3CC0400C636F2 /* WindowControlsPlugin.swift */, 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, ); path = Runner; @@ -284,6 +287,7 @@ 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, 7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */, + 7884E86A2EC3CC0700C636F2 /* WindowControlsPlugin.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/app/ios/Runner/AppDelegate.swift b/app/ios/Runner/AppDelegate.swift index c30b367e..289378ba 100644 --- a/app/ios/Runner/AppDelegate.swift +++ b/app/ios/Runner/AppDelegate.swift @@ -12,5 +12,8 @@ import UIKit func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) { GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry) + if let registrar = engineBridge.pluginRegistry.registrar(forPlugin: "WindowControlsPlugin") { + WindowControlsPlugin.register(with: registrar) + } } } diff --git a/app/ios/Runner/WindowControlsPlugin.swift b/app/ios/Runner/WindowControlsPlugin.swift new file mode 100644 index 00000000..26015d3a --- /dev/null +++ b/app/ios/Runner/WindowControlsPlugin.swift @@ -0,0 +1,131 @@ +import Flutter +import UIKit + +/// Reports where iPadOS 26's window controls (the close/minimise/zoom +/// buttons of a windowed app) cover the Flutter view, so the app's top bar +/// can keep its leading pieces clear of them. +/// +/// Flutter's view padding is UIKit's plain safe area, which does not include +/// the controls. iOS 26 exposes them through corner-adapted layout regions: +/// the safe area adapted horizontally ends beside the controls, the one +/// adapted vertically ends below them (in a window on the iPadOS 26.4 +/// simulator: safe area top 10, adapted left 66 and top 53). The rect is sent +/// in the view's points (Flutter's logical pixels) as +/// `{left, top, right, bottom}`, or `nil` when there are none (full screen +/// in portrait, iOS before 26). UIKit reports nothing for an app it scales +/// into a compatibility window (`UIRequiresFullScreen`). +/// +/// Dart calls `start` (answered with the current rect) and then receives +/// `changed` whenever it moves, e.g. as the window is resized or leaves or +/// enters full screen. See lib/ui/adaptive/window_controls.dart. +final class WindowControlsPlugin: NSObject { + static let channelName = "pipelines/window_controls" + + private let channel: FlutterMethodChannel + private weak var registrar: FlutterPluginRegistrar? + private var probe: WindowControlsProbe? + private var last: [String: Double]? + + static func register(with registrar: FlutterPluginRegistrar) { + let instance = WindowControlsPlugin(registrar: registrar) + instance.channel.setMethodCallHandler { [weak instance] call, result in + instance?.handle(call, result: result) + } + // The registrar does not keep the instance; the channel handler holds it + // weakly, so the registry does. + registrar.publish(instance) + } + + private init(registrar: FlutterPluginRegistrar) { + self.registrar = registrar + channel = FlutterMethodChannel( + name: Self.channelName, binaryMessenger: registrar.messenger()) + } + + private func handle(_ call: FlutterMethodCall, result: FlutterResult) { + guard call.method == "start" else { + result(FlutterMethodNotImplemented) + return + } + attachProbe() + last = probe?.controlsRect() + result(last) + } + + /// Adds an invisible view filling the Flutter view; UIKit lays it out (and + /// updates its safe area) whenever the window's size or controls change. + /// Until the engine has its view controller, it tries again shortly. + private func attachProbe(attempts: Int = 20) { + guard probe == nil else { return } + guard let view = registrar?.viewController?.view else { + if attempts > 0 { + DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) { [weak self] in + self?.attachProbe(attempts: attempts - 1) + self?.report() + } + } + return + } + let probe = WindowControlsProbe(frame: view.bounds) + probe.onChange = { [weak self] in self?.report() } + view.addSubview(probe) + self.probe = probe + } + + private func report() { + let rect = probe?.controlsRect() + guard rect != last else { return } + last = rect + channel.invokeMethod("changed", arguments: rect) + } +} + +/// A transparent, untouchable view that fills its superview and tells its +/// owner when its layout or safe area changes. +private final class WindowControlsProbe: UIView { + var onChange: (() -> Void)? + + override init(frame: CGRect) { + super.init(frame: frame) + autoresizingMask = [.flexibleWidth, .flexibleHeight] + isUserInteractionEnabled = false + isAccessibilityElement = false + backgroundColor = .clear + } + + required init?(coder: NSCoder) { fatalError("init(coder:) is not used") } + + override func layoutSubviews() { + super.layoutSubviews() + onChange?() + } + + override func safeAreaInsetsDidChange() { + super.safeAreaInsetsDidChange() + onChange?() + } + + /// The corner the window controls cover, or nil when there are none. + /// + /// The horizontally adapted safe area also steps in a few points for a + /// rounded display or window corner, on both sides and at full screen; + /// only the controls also push the vertically adapted top below the plain + /// safe area, so both must grow. They sit on the side that grows most. + func controlsRect() -> [String: Double]? { + guard #available(iOS 26.0, *) else { return nil } + let safe = safeAreaInsets + let beside = edgeInsets(for: .safeArea(cornerAdaptation: .horizontal)) + let below = edgeInsets(for: .safeArea(cornerAdaptation: .vertical)) + let left = beside.left - safe.left + let right = beside.right - safe.right + guard below.top > safe.top, max(left, right) > 0 else { return nil } + let width = Double(bounds.width) + let bottom = Double(below.top) + if left >= right { + return ["left": 0, "top": 0, "right": Double(beside.left), "bottom": bottom] + } + return [ + "left": width - Double(beside.right), "top": 0, "right": width, "bottom": bottom, + ] + } +} diff --git a/app/lib/ui/adaptive/segmented_bar.dart b/app/lib/ui/adaptive/segmented_bar.dart index 34fc4bd7..69f507d7 100644 --- a/app/lib/ui/adaptive/segmented_bar.dart +++ b/app/lib/ui/adaptive/segmented_bar.dart @@ -7,6 +7,7 @@ import 'pop_entrance.dart'; import 'segmented_bar_entrance.dart'; import 'segmented_bar_motion.dart'; import 'segmented_bar_pieces.dart'; +import 'window_controls.dart'; export 'segmented_bar_pieces.dart' show SegmentedBackButton, SegmentedPill; @@ -30,7 +31,8 @@ export 'segmented_bar_pieces.dart' show SegmentedBackButton, SegmentedPill; /// [CupertinoPageScaffold.navigationBar], which inset the content by the /// bar's height through [MediaQuery.paddingOf], so a page keeps its /// scaffold's structure; [SegmentedBarOverlay] does the same anywhere else. -/// It handles the top safe area itself. +/// It handles the top safe area itself, and keeps its pieces clear of the +/// system's window controls ([WindowControlsClearance]). class SegmentedBar extends StatefulWidget implements ObstructingPreferredSizeWidget { const SegmentedBar({ @@ -477,9 +479,13 @@ class _SegmentedBarState extends State { 12, bottomPadding, ), - child: MediaQuery.withClampedTextScaling( - maxScaleFactor: SegmentedBar.maxTextScale, - child: BackdropGroup(backdropKey: _piecesBackdrop, child: bar), + // In a window, iPadOS draws its window controls over the top + // corner, outside the safe area: the pieces move clear of them. + child: WindowControlsClearance( + child: MediaQuery.withClampedTextScaling( + maxScaleFactor: SegmentedBar.maxTextScale, + child: BackdropGroup(backdropKey: _piecesBackdrop, child: bar), + ), ), ), ), diff --git a/app/lib/ui/adaptive/window_controls.dart b/app/lib/ui/adaptive/window_controls.dart new file mode 100644 index 00000000..e5b7c2b9 --- /dev/null +++ b/app/lib/ui/adaptive/window_controls.dart @@ -0,0 +1,166 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; + +/// Where the system's window controls cover the app, in global logical +/// pixels: the close/minimise/zoom buttons iPadOS 26 draws over a windowed +/// app's top corner. Null when there are none (full screen, other platforms). +/// +/// Flutter's [MediaQuery] padding is the plain safe area, which leaves the +/// controls out, so the app's top bar asks this instead (see +/// [WindowControlsClearance]). On iOS the rect comes from the Runner's +/// `WindowControlsPlugin` (ios/Runner/WindowControlsPlugin.swift) and follows +/// the window as it is resized; elsewhere it stays null. +class WindowControls { + WindowControls._(); + + static const channel = MethodChannel('pipelines/window_controls'); + + static ValueNotifier? _platform; + + /// The rect for [context]: a [WindowControlsScope]'s when there is one + /// (tests), else the platform's. + static ValueListenable of(BuildContext context) => + context.dependOnInheritedWidgetOfExactType()?.rect ?? + (_platform ??= _listen()); + + /// Forgets the platform's rect, so the next [of] asks the host again. + @visibleForTesting + static void debugReset() { + _platform?.dispose(); + _platform = null; + channel.setMethodCallHandler(null); + } + + static ValueNotifier _listen() { + final rect = ValueNotifier(null); + if (kIsWeb || defaultTargetPlatform != TargetPlatform.iOS) return rect; + channel.setMethodCallHandler((call) async { + if (call.method == 'changed') rect.value = _decode(call.arguments); + }); + channel + .invokeMethod('start') + .then((value) => rect.value = _decode(value)) + // An iOS host without the plugin (a widget test, an app extension) + // reports no controls; other failures surface. + .catchError((Object _) {}, test: (e) => e is MissingPluginException); + return rect; + } + + static Rect? _decode(Object? value) { + if (value is! Map) return null; + double side(String key) => (value[key] as num?)?.toDouble() ?? 0; + final rect = Rect.fromLTRB( + side('left'), + side('top'), + side('right'), + side('bottom'), + ); + return rect.isEmpty ? null : rect; + } +} + +/// Supplies the [WindowControls] rect to its subtree instead of the +/// platform's (a fake in tests). +class WindowControlsScope extends InheritedWidget { + const WindowControlsScope({ + super.key, + required this.rect, + required super.child, + }); + + final ValueListenable rect; + + @override + bool updateShouldNotify(WindowControlsScope oldWidget) => + rect != oldWidget.rect; +} + +/// Pads [child] at the side where the [WindowControls] overlap it, so its +/// leading (or trailing) piece starts [gap] clear of the controls; no +/// padding where they do not reach it. +/// +/// The overlap depends on where [child] sits in the window, which is only +/// known after layout, so it is measured after each frame that rebuilds it +/// and again when its route finishes a transition (a pushed page slides in +/// from off screen). +class WindowControlsClearance extends StatefulWidget { + const WindowControlsClearance({super.key, required this.child, this.gap = 8}); + + final Widget child; + + /// The space kept between the controls and [child]'s content. + final double gap; + + @override + State createState() => + _WindowControlsClearanceState(); +} + +class _WindowControlsClearanceState extends State { + ValueListenable? _controls; + Animation? _route; + EdgeInsets _padding = EdgeInsets.zero; + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + final controls = WindowControls.of(context); + if (controls != _controls) { + _controls?.removeListener(_schedule); + _controls = controls..addListener(_schedule); + } + final route = ModalRoute.of(context)?.animation; + if (route != _route) { + _route?.removeStatusListener(_onRouteStatus); + _route = route?..addStatusListener(_onRouteStatus); + } + } + + @override + void dispose() { + _controls?.removeListener(_schedule); + _route?.removeStatusListener(_onRouteStatus); + super.dispose(); + } + + void _onRouteStatus(AnimationStatus status) { + if (!status.isAnimating) _schedule(); + } + + void _schedule() { + WidgetsBinding.instance + ..addPostFrameCallback((_) => _measure()) + ..ensureVisualUpdate(); + } + + void _measure() { + if (!mounted) return; + final box = context.findRenderObject(); + if (box is! RenderBox || !box.attached || !box.hasSize) return; + final padding = _clearance(box); + if (padding != _padding) setState(() => _padding = padding); + } + + /// The padding that keeps [box]'s content clear of the controls. It is + /// measured from [box]'s own bounds (the padding included), so it does not + /// depend on the padding it sets. + EdgeInsets _clearance(RenderBox box) { + final controls = _controls?.value; + if (controls == null) return EdgeInsets.zero; + final bounds = box.localToGlobal(Offset.zero) & box.size; + if (!controls.overlaps(bounds)) return EdgeInsets.zero; + if (controls.center.dx < bounds.center.dx) { + final left = controls.right + widget.gap - bounds.left; + return EdgeInsets.only(left: left > 0 ? left : 0); + } + final right = bounds.right - (controls.left - widget.gap); + return EdgeInsets.only(right: right > 0 ? right : 0); + } + + @override + Widget build(BuildContext context) { + _schedule(); + return Padding(padding: _padding, child: widget.child); + } +} diff --git a/app/notes/window-controls-inset.md b/app/notes/window-controls-inset.md new file mode 100644 index 00000000..d0ecb040 --- /dev/null +++ b/app/notes/window-controls-inset.md @@ -0,0 +1,52 @@ +# Window controls inset (iPadOS 26 windowed apps) + +Fixes finding 1 of `notes/ipad-layout-review.md`: in a window, the system +window controls covered the list pane's title pill and took its taps. + +## How the inset is obtained + +Flutter's `MediaQuery` padding is UIKit's plain safe area, which never +includes the controls (in a window on the simulator: top 10, left 0). iOS 26 +reports them through corner-adapted layout regions instead: +`edgeInsets(for: .safeArea(cornerAdaptation: .horizontal))` gives left 66 and +`.vertical` gives top 53 while the controls are shown. The horizontal region +also grows a few points for rounded corners (5.5–9.5 at full screen and on the +window's other side), so a corner counts as the controls only when both +regions grow. + +- `ios/Runner/WindowControlsPlugin.swift` (registered in `AppDelegate`) adds + an invisible probe view over the Flutter view and sends the rect on the + `pipelines/window_controls` method channel: `start` returns it, `changed` + follows window resizes and full screen. Nil before iOS 26 and at portrait + full screen. UIKit reports nothing for a `UIRequiresFullScreen` + compatibility window, which the system scales instead. +- `lib/ui/adaptive/window_controls.dart`: `WindowControls.of` (platform rect; + a null notifier off iOS), `WindowControlsScope` (fake for tests) and + `WindowControlsClearance`, which measures its global position after layout + (and when its route finishes a transition) and pads the side the controls + overlap, keeping 8 pt clear of them. +- `SegmentedBar` wraps its row of pieces in `WindowControlsClearance`, so + every top bar at the window's top corner (the shell's list pane, a page + pushed at compact width) moves its leading piece right of the controls; + bars elsewhere (a detail pane) are not touched. + +## Verification + +iPad Air 13-inch (M4) simulators only, iOS 26.4 and 27.0, fixture entry +`tool/search_selection_probe_entry.dart` with +`route=/chat/perf-chat-0&chats=8&colors=1&msgs=60,20&rich=1&links=1&tasks=4`. +`simctl` cannot resize a window; a throwaway XCUITest (outside the repo) +dragged the window's resize grip. + +- `window-controls-inset/air26-window.jpg`, `-crop.jpg`: 1024x1053 window, + list beside chat; "Chat" starts right of the controls (was under them: + `ipad-layout-review/air-win-chat0-crop.jpg`). +- `air26-window-compact.jpg`, `-crop.jpg`: 519x775 window, the pushed chat's + Back button starts right of the controls. +- `air26-fullscreen.jpg`, `-crop.jpg`: the same run dragged back to full + screen; the pill returns to its 12 pt margin. +- `ios27-window.jpg`: the same on iOS 27.0. + +On the iOS 27.0 runtime at landscape full screen UIKit also reports the +(hidden) controls corner (left 66, top 53 under a top safe area of 10), so the +list pane's title moves right there too, as UIKit asks. diff --git a/app/notes/window-controls-inset/air26-fullscreen-crop.jpg b/app/notes/window-controls-inset/air26-fullscreen-crop.jpg new file mode 100644 index 00000000..28eed09c Binary files /dev/null and b/app/notes/window-controls-inset/air26-fullscreen-crop.jpg differ diff --git a/app/notes/window-controls-inset/air26-fullscreen.jpg b/app/notes/window-controls-inset/air26-fullscreen.jpg new file mode 100644 index 00000000..ff16a4ae Binary files /dev/null and b/app/notes/window-controls-inset/air26-fullscreen.jpg differ diff --git a/app/notes/window-controls-inset/air26-window-compact-crop.jpg b/app/notes/window-controls-inset/air26-window-compact-crop.jpg new file mode 100644 index 00000000..0e467861 Binary files /dev/null and b/app/notes/window-controls-inset/air26-window-compact-crop.jpg differ diff --git a/app/notes/window-controls-inset/air26-window-compact.jpg b/app/notes/window-controls-inset/air26-window-compact.jpg new file mode 100644 index 00000000..a821c8ec Binary files /dev/null and b/app/notes/window-controls-inset/air26-window-compact.jpg differ diff --git a/app/notes/window-controls-inset/air26-window-crop.jpg b/app/notes/window-controls-inset/air26-window-crop.jpg new file mode 100644 index 00000000..4c257e1e Binary files /dev/null and b/app/notes/window-controls-inset/air26-window-crop.jpg differ diff --git a/app/notes/window-controls-inset/air26-window.jpg b/app/notes/window-controls-inset/air26-window.jpg new file mode 100644 index 00000000..2d06ed9c Binary files /dev/null and b/app/notes/window-controls-inset/air26-window.jpg differ diff --git a/app/notes/window-controls-inset/ios27-window.jpg b/app/notes/window-controls-inset/ios27-window.jpg new file mode 100644 index 00000000..e91ce2de Binary files /dev/null and b/app/notes/window-controls-inset/ios27-window.jpg differ diff --git a/app/test/ui/adaptive/window_controls_test.dart b/app/test/ui/adaptive/window_controls_test.dart new file mode 100644 index 00000000..9ea8abdd --- /dev/null +++ b/app/test/ui/adaptive/window_controls_test.dart @@ -0,0 +1,223 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/ui/adaptive/segmented_bar.dart'; +import 'package:pipelines_app/ui/adaptive/segmented_bar_pieces.dart'; +import 'package:pipelines_app/ui/adaptive/window_controls.dart'; + +/// Where UIKit put iPadOS 26.4's window controls in a window on the +/// simulator: safe area top 10, adapted left 66 and top 53. +const _controls = Rect.fromLTRB(0, 0, 66, 53); + +void _window(WidgetTester tester, {double top = 10, double width = 800}) { + tester.view.physicalSize = Size(width, 700); + tester.view.devicePixelRatio = 1; + tester.view.padding = FakeViewPadding(top: top); + addTearDown(tester.view.reset); +} + +SegmentedBar _bar({String title = 'Chat', List actions = const []}) => + SegmentedBar(cupertino: false, title: title, actions: actions); + +Widget _page(SegmentedBar bar, {ValueListenable? controls}) { + final page = Scaffold( + extendBodyBehindAppBar: true, + appBar: bar, + body: const SizedBox.expand(), + ); + return MaterialApp( + home: controls == null + ? page + : WindowControlsScope(rect: controls, child: page), + ); +} + +double _titleLeft(WidgetTester tester) => + tester.getTopLeft(find.byType(SegmentedTitlePill)).dx; + +void main() { + testWidgets('without window controls the title pill keeps its margin', ( + tester, + ) async { + _window(tester); + await tester.pumpWidget(_page(_bar(), controls: ValueNotifier(null))); + await tester.pumpAndSettle(); + expect(_titleLeft(tester), 12); + }); + + testWidgets('the title pill starts clear of the window controls', ( + tester, + ) async { + _window(tester); + await tester.pumpWidget(_page(_bar(), controls: ValueNotifier(_controls))); + await tester.pumpAndSettle(); + expect(_titleLeft(tester), _controls.right + 8); + // The pill keeps its height and row; only its leading edge moves. + expect(tester.getTopLeft(find.byType(SegmentedTitlePill)).dy, 18); + }); + + testWidgets('the clearance follows the controls as the window changes', ( + tester, + ) async { + _window(tester); + final controls = ValueNotifier(null); + await tester.pumpWidget(_page(_bar(), controls: controls)); + await tester.pumpAndSettle(); + expect(_titleLeft(tester), 12); + + controls.value = _controls; + await tester.pumpAndSettle(); + expect(_titleLeft(tester), 74); + + // Back to full screen. + controls.value = null; + await tester.pumpAndSettle(); + expect(_titleLeft(tester), 12); + }); + + testWidgets('controls above the bar (below the status bar) leave it be', ( + tester, + ) async { + _window(tester, top: 60); + await tester.pumpWidget(_page(_bar(), controls: ValueNotifier(_controls))); + await tester.pumpAndSettle(); + expect(_titleLeft(tester), 12); + }); + + testWidgets('a bar away from the controls, such as a detail pane\'s, keeps ' + 'its margin', (tester) async { + _window(tester); + await tester.pumpWidget( + MaterialApp( + home: WindowControlsScope( + rect: ValueNotifier(_controls), + child: Row( + children: [ + const SizedBox(width: 300), + Expanded( + child: Scaffold( + extendBodyBehindAppBar: true, + appBar: _bar(title: 'Release notes'), + body: const SizedBox.expand(), + ), + ), + ], + ), + ), + ), + ); + await tester.pumpAndSettle(); + expect(_titleLeft(tester), 312); + }); + + testWidgets('controls at the trailing corner keep the actions clear', ( + tester, + ) async { + _window(tester); + const trailing = Rect.fromLTRB(734, 0, 800, 53); + await tester.pumpWidget( + _page( + _bar( + actions: [IconButton(onPressed: () {}, icon: const Icon(Icons.add))], + ), + controls: ValueNotifier(trailing), + ), + ); + await tester.pumpAndSettle(); + expect(_titleLeft(tester), 12); + expect( + tester.getTopRight(find.byIcon(Icons.add)).dx, + lessThanOrEqualTo(trailing.left - 8), + ); + }); + + testWidgets('a pushed page\'s Back clears the controls once it has slid in', ( + tester, + ) async { + _window(tester); + final navigator = GlobalKey(); + await tester.pumpWidget( + MaterialApp( + navigatorKey: navigator, + builder: (context, child) => + WindowControlsScope(rect: ValueNotifier(_controls), child: child!), + home: const SizedBox.expand(), + ), + ); + navigator.currentState!.push( + MaterialPageRoute( + builder: (_) => Scaffold( + extendBodyBehindAppBar: true, + appBar: _bar(title: 'Release notes'), + body: const SizedBox.expand(), + ), + ), + ); + await tester.pumpAndSettle(); + expect(tester.getTopLeft(find.byType(BackButton)).dx, greaterThan(66)); + }); + + group('platform rect', () { + setUp(WindowControls.debugReset); + tearDown(() { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(WindowControls.channel, null); + WindowControls.debugReset(); + }); + + testWidgets( + 'comes from the iOS host and follows its updates', + (tester) async { + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + messenger.setMockMethodCallHandler(WindowControls.channel, ( + call, + ) async { + expect(call.method, 'start'); + return {'left': 0, 'top': 0, 'right': 66, 'bottom': 53}; + }); + late ValueListenable rect; + await tester.pumpWidget( + Builder( + builder: (context) { + rect = WindowControls.of(context); + return const SizedBox(); + }, + ), + ); + await tester.pump(); + expect(rect.value, _controls); + + // The host reports the window going full screen. + await messenger.handlePlatformMessage( + WindowControls.channel.name, + WindowControls.channel.codec.encodeMethodCall( + const MethodCall('changed'), + ), + (_) {}, + ); + expect(rect.value, isNull); + }, + variant: TargetPlatformVariant.only(TargetPlatform.iOS), + ); + + testWidgets( + 'an iOS host without the plugin reports none', + (tester) async { + late ValueListenable rect; + await tester.pumpWidget( + Builder( + builder: (context) { + rect = WindowControls.of(context); + return const SizedBox(); + }, + ), + ); + await tester.pump(); + expect(rect.value, isNull); + }, + variant: TargetPlatformVariant.only(TargetPlatform.iOS), + ); + }); +}