import 'dart:ui' as ui; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; /// One bounded, temporary picture for the outgoing tape segment. It avoids a /// second live chat tree or per-frame capture. Every old image is released /// after its last painted frame. Pixel scale is capped at two (~9 MB at 560×1000). class ChatPaneBackdrop extends ChangeNotifier { ChatPaneBackdrop(this.motion) { motion.addStatusListener(_settled); } final Animation motion; final pictureKey = GlobalKey(); ui.Image? image; bool _scheduled = false; bool _disposed = false; bool capture(BuildContext context) { final boundary = pictureKey.currentContext?.findRenderObject(); if (boundary is! _PictureBoundary || !boundary.hasPicture) { return false; } var ready = true; assert(() { ready = !boundary.debugNeedsPaint; return true; }()); if (!ready) return false; final old = image; try { image = boundary.toImageSync( pixelRatio: MediaQuery.devicePixelRatioOf(context).clamp(1, 2), ); } on Object { return false; } if (old != null) _release(old); return true; } void _settled(AnimationStatus status) { if (status != AnimationStatus.completed || _scheduled || image == null) { return; } _scheduled = true; WidgetsBinding.instance.addPostFrameCallback((_) { _scheduled = false; if (_disposed || motion.status != AnimationStatus.completed) return; final old = image; image = null; notifyListeners(); if (old != null) _release(old); }); } void _release(ui.Image old) => WidgetsBinding.instance.addPostFrameCallback((_) => old.dispose()); @override void dispose() { _disposed = true; motion.removeStatusListener(_settled); image?.dispose(); image = null; super.dispose(); } } /// RepaintBoundary with a release-safe check for an already painted layer. class ChatPanePicture extends RepaintBoundary { const ChatPanePicture({super.key, required super.child}); @override RenderRepaintBoundary createRenderObject(BuildContext context) => _PictureBoundary(); } class _PictureBoundary extends RenderRepaintBoundary { bool get hasPicture => attached && hasSize && layer != null; }