import 'dart:async'; import 'package:flutter/material.dart'; import '../../ui/motion/motion.dart'; import '../../ui/motion/surface_visibility.dart'; import 'window_entry.dart'; import 'window_focus.dart'; import 'window_frame.dart'; import 'window_kind.dart'; import 'window_manager.dart'; import 'window_navigator.dart'; import 'window_scope.dart'; /// One window in the host: its card and title bar, its page navigator over /// the card's body, and its resize corner, with the grow-and-fade motion as /// it shows and hides. A hidden window stays built (its content keeps its /// state) but is not painted and takes no input or focus. class WindowLayer extends StatefulWidget { const WindowLayer({ super.key, required this.manager, required this.kind, required this.entry, required this.visible, required this.bounds, required this.focus, }); final WindowManager manager; final WindowKind kind; final WindowEntry entry; final bool visible; final Size bounds; final WindowFocus focus; /// The scale a window grows from as it shows. static const double revealScale = 0.92; @override State createState() => _WindowLayerState(); } class _WindowLayerState extends State with SingleTickerProviderStateMixin { late final AnimationController _reveal = AnimationController( vsync: this, duration: Motion.standard, ); late final CurvedAnimation _curve = CurvedAnimation( parent: _reveal, curve: Motion.curve, reverseCurve: Curves.easeInCubic, ); final GlobalKey _navigator = GlobalKey(); late final LocalKey _rootPage = ValueKey('window-root-${widget.entry.id}'); /// The page-transition theme handed to the window's navigator, rebuilt only /// when the app's theme itself changes. ThemeData? _themeSource; ThemeData? _pageTheme; /// The root page kept across builds: a new page object would rebuild the /// window's content on every move and resize. WindowKind? _pageKind; Page? _page; String get _id => widget.entry.id; @override void initState() { super.initState(); if (widget.visible) { WidgetsBinding.instance.addPostFrameCallback((_) => _run()); } } @override void didUpdateWidget(covariant WindowLayer oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.visible != widget.visible) _run(); } void _run() { if (!mounted) return; _reveal.duration = Motion.of(context, Motion.standard); unawaited(widget.visible ? _reveal.forward() : _reveal.reverse()); } @override void dispose() { _curve.dispose(); _reveal.dispose(); super.dispose(); } Rect get _frame => drawnWindowFrame(widget.entry, widget.bounds, widget.kind.minSize); /// The frame now: several drag events can arrive before a rebuild. Rect get _current { final entry = widget.manager.byId(_id) ?? widget.entry; return drawnWindowFrame(entry, widget.bounds, widget.kind.minSize); } /// Where the pointer is in the host while the title is dragged. Offset? _pointer; /// The frame the current move or resize started from and the pointer delta /// summed since. Every event sets the frame from `start + total`: fitting /// one fractional step after another would round part of the pointer's /// movement away each time and drift, and shifting the fitted frame would /// change its size in its last bits. Rect? _dragStart; Offset _dragTotal = Offset.zero; void _move(Offset delta, Offset globalPosition) { final box = context.findRenderObject(); _pointer = box is RenderBox ? box.globalToLocal(globalPosition) : null; final start = _dragStart ??= _current; _dragTotal += delta; widget.manager.setFrame( _id, fitWindowFrame( start.shift(_dragTotal), widget.bounds, widget.kind.minSize, ), save: false, ); } /// Dropping the title at the app's left or right edge fills that half; /// at the top edge it maximises. void _moveEnded() { final pointer = _pointer; _pointer = null; _endDrag(); final bounds = widget.bounds; final snap = pointer == null ? null : windowSnapFor(pointer, bounds); if (snap == WindowSnap.maximize) { widget.manager.setMaximized(_id, true); return; } if (snap != null) { widget.manager.setFrame( _id, fitWindowFrame( windowSnapRect(snap, bounds), bounds, widget.kind.minSize, ), save: false, ); // A snapped half is not the size to give this kind's next window. widget.manager.commit(); return; } widget.manager.commit(_id); } void _resize(Offset delta) { final start = _dragStart ??= _current; _dragTotal += delta; widget.manager.setFrame( _id, fitWindowFrame( Rect.fromLTWH( start.left, start.top, start.width + _dragTotal.dx, start.height + _dragTotal.dy, ), widget.bounds, widget.kind.minSize, ), save: false, ); } void _resizeEnded() { _endDrag(); widget.manager.commit(_id); } /// A drag ends here even if it is cancelled or another gesture begins. void _endDrag() { _dragStart = null; _dragTotal = Offset.zero; } /// A press brings the window to the top and gives it the keyboard at /// once, before the press does anything else (focus a field, open a /// popup that takes the keyboard itself). void _pressed() { // A new gesture measures from where it starts, even if the last drag was // cancelled before it ended. _endDrag(); if (!widget.focus.has(_id)) widget.focus.focusNow(_id); widget.manager.raise(_id); } ThemeData _pageThemeFor(ThemeData theme) { // Equal to the last theme means the same page theme, even when the app's // animated theme hands over a new but equal `ThemeData` object: a new // page theme would notify every content widget that reads the theme on // every frame of a move. if (theme == _themeSource) return _pageTheme!; _themeSource = theme; return _pageTheme = WindowNavigator.themeData(theme); } Page _rootPageFor(WindowKind kind) { final page = _page; if (page != null && identical(kind, _pageKind)) return page; _pageKind = kind; return _page = MaterialPage( key: _rootPage, child: _WindowContent(kind: kind), ); } @override Widget build(BuildContext context) { final manager = widget.manager; final entry = widget.entry; final kind = widget.kind; final frame = _frame; final titleHeight = windowTitleBarHeight(context).clamp(0.0, frame.height); final body = Rect.fromLTRB( frame.left, frame.top + titleHeight, frame.right, frame.bottom, ); final title = kind.title(context, entry); final pageTheme = _pageThemeFor(Theme.of(context)); final hiding = !widget.visible; final content = Stack( fit: StackFit.expand, children: [ Positioned.fromRect( rect: frame, child: Semantics( container: true, explicitChildNodes: true, label: 'Window: $title', identifier: 'window-${entry.kind}', // Its own layer: moving the window moves the title bar without // repainting it. child: RepaintBoundary( child: WindowFrame( title: title, icon: kind.icon, actions: kind.actions(context, entry), maximized: entry.maximized, onMove: _move, onMoveEnd: _moveEnded, onMinimize: () => manager.setMinimized(_id, true), onToggleMaximized: () => manager.setMaximized(_id, !entry.maximized), onClose: () => manager.close(_id), ), ), ), ), WindowHitRegion( region: body, // Its own semantics container: a route's barrier hides what is // painted before it in its container, which must not be the // title bar or the app. child: Semantics( container: true, explicitChildNodes: true, child: WindowScope( manager: manager, entry: entry, child: WindowBodyScope( body: body, child: ScaffoldMessenger( child: Theme( data: pageTheme, child: WindowNavigator( key: _navigator, pages: [_rootPageFor(kind)], onDidRemovePage: (_) {}, ), ), ), ), ), ), ), if (!entry.maximized) Positioned( right: widget.bounds.width - frame.right, bottom: widget.bounds.height - frame.bottom, child: WindowResizeCorner( onResize: _resize, onResizeEnd: _resizeEnded, ), ), Positioned.fromRect(rect: frame, child: const WindowOutline()), ], ); final center = widget.bounds.center(Offset.zero); final current = ModalRoute.of(context)?.isCurrent ?? true; return AnimatedBuilder( animation: _reveal, builder: (context, child) { final offstage = hiding && _reveal.isDismissed; return Offstage( offstage: offstage, child: TickerMode( enabled: !offstage, child: SurfaceVisibility( shown: !offstage, // Not while a page, sheet or dialog covers the app: the // window's own route is always its navigator's current one. current: !hiding && current, child: IgnorePointer( ignoring: hiding, child: ExcludeFocus(excluding: hiding, child: child!), ), ), ), ); }, child: FadeTransition( opacity: _curve, child: ScaleTransition( scale: Tween( begin: WindowLayer.revealScale, end: 1, ).animate(_curve), // Grows from the window's own centre, not the host's. alignment: Alignment( center.dx == 0 ? 0 : (frame.center.dx - center.dx) / center.dx, center.dy == 0 ? 0 : (frame.center.dy - center.dy) / center.dy, ), child: Listener( behavior: HitTestBehavior.deferToChild, onPointerDown: (_) => _pressed(), child: FocusScope( node: widget.focus.scopeFor(_id), onFocusChange: (focused) { if (focused) manager.raise(_id); }, child: content, ), ), ), ), ); } } /// The kind's content, rebuilt with the window's current entry. class _WindowContent extends StatelessWidget { const _WindowContent({required this.kind}); final WindowKind kind; @override Widget build(BuildContext context) => kind.build(context, WindowScope.of(context).entry); }