Files
pipelines/app/lib/features/chat/workspace/chat_pane_backdrop.dart
T

80 lines
2.3 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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<double> 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;
}