import 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'native_channel_binding.dart'; class NativeFullscreenSession { NativeFullscreenSession({required this.onExit}); static const _channel = MethodChannel('cutdex_native/fullscreen'); static Future? _request; final void Function() onExit; final _binding = NativeChannelBinding(_channel); bool _disposed = false; void attach() { if (_disposed) { throw StateError('Cannot attach a disposed fullscreen session'); } _binding.bind((call) async { if (_binding.isOwner && call.method == 'exited') onExit(); }); } Future setFullscreen(bool enabled) => _enqueue(enabled); Future _enqueue(bool enabled, {bool restoring = false}) { // AppKit completes a request after its window transition. Serialize across // owners so retiring and newly mounted routes cannot overlap transitions. Future invoke() async { if (restoring ? _binding.hasOwner : _disposed || !_binding.isOwner) { return; } await _channel.invokeMethod('setFullscreen', enabled); } final previous = _request; final request = previous == null ? invoke() : previous.then( (_) => invoke(), onError: (Object _, StackTrace _) => invoke(), ); _request = request; // A failed transition must not poison the next owner's request queue. void clear() { if (identical(_request, request)) _request = null; } unawaited( request.then( (_) => clear(), onError: (Object _, StackTrace _) => clear(), ), ); return request; } void dispose({bool exitFullscreen = false}) { if (_disposed) return; _disposed = true; if (_binding.unbind() && exitFullscreen) { unawaited( _enqueue(false, restoring: true).catchError((Object error) { debugPrint('Could not restore native fullscreen: $error'); }), ); } } }