Add ability to send images over lora

This commit is contained in:
Zach committed 2026-08-10 23:20:46 -07:00
1 parent 736eb064bf
commit eee72b4c65
129 files changed
+27099 -58

No files matched your search

+25
View File
@@ -0,0 +1,25 @@
import 'package:flutter/material.dart';
import '../l10n/l10n.dart';
class ImageSendButton extends StatelessWidget {
final bool enabled;
final VoidCallback onPressed;
final String? tooltip;
const ImageSendButton({
super.key,
required this.enabled,
required this.onPressed,
this.tooltip,
});
@override
Widget build(BuildContext context) {
return IconButton(
icon: Icon(enabled ? Icons.image : Icons.image_outlined),
onPressed: enabled ? onPressed : null,
tooltip: tooltip ?? context.l10n.chat_sendImage,
);
}
}
+160
View File
@@ -0,0 +1,160 @@
import 'dart:typed_data';
/// Minimal, dependency-free abstraction over the neural image codec used by
/// [ImageSendPreviewSheet].
///
/// The real implementation lives in `lib/services/image_codec_service.dart`
/// (`ImageCodecService implements ImageSendCodec`) and
/// `lib/services/image_chunk_transport.dart`. This file deliberately does NOT
/// import them, so the preview sheet can be built, analyzed and previewed on
/// its own and so the service depends on the UI contract rather than the other
/// way round.
///
// Packet-count and airtime maths deliberately live in
// `lib/utils/lora_airtime.dart`, not here.
/// Hard minimum resolution for the codec. Images are centre-cropped to this
/// square before encoding; the decoder collapses below it.
const int kImageCodecSquareSize = 512;
/// Availability of the image codec, as far as the UI is concerned.
enum ImageCodecAvailability {
/// The feature is switched off in app settings.
disabled,
/// The codec model is being fetched; the feature is temporarily unusable.
downloading,
/// The codec is usable right now.
ready,
/// The codec cannot run on this device/platform at all.
unavailable,
}
/// Rate points the wire format can express.
///
/// The shipping build encodes at [standard] (`ft32`) only — see
/// [kImageSendRatePoint]. The enum keeps more than one value because the rate
/// point is written into the chunk-0 metadata byte by
/// `image_chunk_transport.dart`, so the ordinals are part of the wire format and
/// must stay stable even for rate points the UI never offers. Removing [high]
/// would renumber nothing today but would make a future rate point silently
/// reuse ordinal 1 and be decoded as ft16 by older builds.
enum ImageCodecRatePoint {
/// `ft32` — the only rate point this build sends. Measured 110-209 B
/// (mean 156 B) over 26 images, i.e. 1-2 data chunks plus parity.
standard,
/// `ft16` — larger, higher fidelity. **Not offered in the UI**: the model
/// registry ships ft32 weights only. Retained so the ordinal stays reserved
/// and so bitstreams produced elsewhere can still be identified on the wire.
high,
}
/// The single rate point the compose UI encodes at.
///
/// The quality selector was removed once ft32 became the only shipping model;
/// every send goes out at this rate. Named rather than inlined so a future
/// second rate point has one place to come back to.
const ImageCodecRatePoint kImageSendRatePoint = ImageCodecRatePoint.standard;
/// Measured payload statistics for a rate point, in bytes.
///
/// These are real measurements over 26 images of rANS bitstreams produced by
/// the codec at 512x512, not estimates. They let the sheet show a plausible
/// range instantly, before an encode has finished.
class ImageCodecRateStats {
final int meanBytes;
final int minBytes;
final int maxBytes;
const ImageCodecRateStats({
required this.meanBytes,
required this.minBytes,
required this.maxBytes,
});
static const ImageCodecRateStats standard = ImageCodecRateStats(
meanBytes: 156,
minBytes: 110,
maxBytes: 209,
);
/// Retained for [ImageCodecRatePoint.high], which the UI no longer offers.
static const ImageCodecRateStats high = ImageCodecRateStats(
meanBytes: 288,
minBytes: 176,
maxBytes: 409,
);
static ImageCodecRateStats forRate(ImageCodecRatePoint rate) {
switch (rate) {
case ImageCodecRatePoint.standard:
return standard;
case ImageCodecRatePoint.high:
return high;
}
}
}
/// The encode interface the preview sheet consumes.
abstract class ImageSendCodec {
/// Current availability. The sheet renders a non-interactive explanation for
/// anything other than [ImageCodecAvailability.ready].
ImageCodecAvailability get availability;
/// Why [availability] is [ImageCodecAvailability.unavailable], as one
/// user-facing sentence, or null when the codec is not permanently
/// unavailable.
///
/// This is the sentence the compose sheet shows in place of its generic
/// "not available on this device" string: `unavailable` is a permanent
/// property of the build (no native runtime, no entropy path, backend failed
/// to load) and the only useful thing the UI can do is say WHICH one it hit.
/// Implementations must not return an empty string; return null instead.
String? get unavailableReason;
/// Encode [imageBytes] (any common still format) at [rate], returning the
/// compressed bitstream that will be chunked onto the air.
///
/// Implementations are expected to centre-crop to
/// [kImageCodecSquareSize] square first.
Future<Uint8List> encode(Uint8List imageBytes, ImageCodecRatePoint rate);
}
/// A deterministic stand-in used for widget previews and tests.
///
/// It produces a buffer of the measured mean size for the requested rate point
/// so the sheet can be exercised end-to-end without the real codec.
class FakeImageSendCodec implements ImageSendCodec {
@override
final ImageCodecAvailability availability;
/// Mirrors `ImageCodecService.unavailableReason`; null unless a test wants to
/// exercise the "why can't I send?" path.
@override
final String? unavailableReason;
final Duration latency;
const FakeImageSendCodec({
this.availability = ImageCodecAvailability.ready,
this.unavailableReason,
this.latency = const Duration(milliseconds: 250),
});
@override
Future<Uint8List> encode(
Uint8List imageBytes,
ImageCodecRatePoint rate,
) async {
if (latency > Duration.zero) {
await Future<void>.delayed(latency);
}
final size = ImageCodecRateStats.forRate(rate).meanBytes;
return Uint8List.fromList(
List<int>.generate(size, (i) => (i * 31 + rate.index) & 0xFF),
);
}
}
+782
View File
@@ -0,0 +1,782 @@
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../connector/meshcore_connector.dart';
import '../l10n/l10n.dart';
import '../utils/lora_airtime.dart';
import 'image_send_codec_binding.dart';
/// Estimated wall clock above which the sheet warns the user explicitly.
const Duration kImageSendLongAirtime = Duration(seconds: 5);
/// What the user committed to when they tapped Send.
class ImageSendPreviewResult {
/// The encoded bitstream, ready to be chunked onto the air.
final Uint8List payload;
/// The rate point the payload was encoded at. Always [kImageSendRatePoint] in
/// this build; carried through because the transport writes it on the wire.
final ImageCodecRatePoint rate;
/// Whether an XOR parity packet should be appended.
final bool includeParity;
/// Packets that will actually be transmitted, parity included.
final int packetCount;
/// Estimated transmitter occupancy, or null if the radio settings were
/// unknown. This is *not* how long the send takes — see [wallClock].
final Duration? airtime;
/// Estimated wall clock including per-chunk pacing — the figure the user was
/// actually shown. Null when the radio settings were unknown.
final Duration? wallClock;
const ImageSendPreviewResult({
required this.payload,
required this.rate,
required this.includeParity,
required this.packetCount,
required this.airtime,
required this.wallClock,
});
}
/// Shows the pre-send image preview.
///
/// Returns null if the user cancelled, or an [ImageSendPreviewResult] carrying
/// the encoded payload if they confirmed. The caller owns the actual send.
///
/// [imageBytes] is the raw picked file (JPEG/PNG/…). [originalFileBytes] is its
/// on-disk size, shown against the transmitted size.
///
/// [radio] overrides the live radio parameters; when omitted they are read from
/// the [MeshCoreConnector] in the widget tree. Pass it explicitly to preview
/// this sheet without a connector.
///
/// There is no quality/rate argument: ft32 ([kImageSendRatePoint]) is the only
/// shipping model, so the sheet no longer offers a choice.
Future<ImageSendPreviewResult?> showImageSendPreviewSheet({
required BuildContext context,
required Uint8List imageBytes,
required int originalFileBytes,
required ImageSendCodec codec,
ImageSendRadio? radio,
bool initialParity = true,
}) {
return showModalBottomSheet<ImageSendPreviewResult>(
context: context,
isScrollControlled: true,
useSafeArea: true,
builder: (context) => ImageSendPreviewSheet(
imageBytes: imageBytes,
originalFileBytes: originalFileBytes,
codec: codec,
radio: radio,
initialParity: initialParity,
),
);
}
class ImageSendPreviewSheet extends StatefulWidget {
final Uint8List imageBytes;
final int originalFileBytes;
final ImageSendCodec codec;
final ImageSendRadio? radio;
final bool initialParity;
const ImageSendPreviewSheet({
super.key,
required this.imageBytes,
required this.originalFileBytes,
required this.codec,
this.radio,
this.initialParity = true,
});
@override
State<ImageSendPreviewSheet> createState() => _ImageSendPreviewSheetState();
}
/// The live radio parameters, exactly as the connector exposes them: each may
/// be null before the device has reported its SELF_INFO frame.
class ImageSendRadio {
final int? spreadingFactor;
final int? bandwidthHz;
/// Raw firmware coding rate; [estimateSendFromRadioParams] normalises it.
final int? rawCodingRate;
const ImageSendRadio({
this.spreadingFactor,
this.bandwidthHz,
this.rawCodingRate,
});
bool get isKnown =>
spreadingFactor != null && bandwidthHz != null && rawCodingRate != null;
}
/// Packet/byte/airtime figures for one rate point.
///
/// Before an encode has finished the payload size is only known as a measured
/// range, so [best] and [worst] differ; afterwards they are identical.
class _RateEstimate {
/// Exact payload size once encoded, null while still estimating.
final int? payloadBytes;
final SendEstimate best;
final SendEstimate worst;
const _RateEstimate({
required this.payloadBytes,
required this.best,
required this.worst,
});
bool get isExact => payloadBytes != null;
}
class _ImageSendPreviewSheetState extends State<ImageSendPreviewSheet> {
/// The encoded ft32 bitstream, once the encode finishes.
Uint8List? _encoded;
late bool _parity;
bool _encoding = false;
bool _sending = false;
bool _failed = false;
/// Latest radio params seen in build; used by [_onSend] so the confirm path
/// does not have to touch an InheritedWidget after an await.
ImageSendRadio? _radio;
@override
void initState() {
super.initState();
_parity = widget.initialParity;
if (widget.codec.availability == ImageCodecAvailability.ready) {
_encode();
}
}
Future<Uint8List?> _encode() async {
final cached = _encoded;
if (cached != null) return cached;
setState(() {
_encoding = true;
_failed = false;
});
try {
final bytes =
await widget.codec.encode(widget.imageBytes, kImageSendRatePoint);
if (!mounted) return bytes;
setState(() {
_encoded = bytes;
_encoding = false;
});
return bytes;
} catch (_) {
if (!mounted) return null;
setState(() {
_encoding = false;
_failed = true;
});
return null;
}
}
ImageSendRadio _radioParams(BuildContext context) {
final override = widget.radio;
if (override != null) return override;
final connector = context.watch<MeshCoreConnector>();
return ImageSendRadio(
spreadingFactor: connector.currentSf,
bandwidthHz: connector.currentBwHz,
rawCodingRate: connector.currentCr,
);
}
_RateEstimate _estimateFor(ImageSendRadio radio) {
final bytes = _encoded;
if (bytes != null) {
final exact = _estimate(bytes.length, radio);
return _RateEstimate(
payloadBytes: bytes.length,
best: exact,
worst: exact,
);
}
// Nothing encoded yet: show the measured ft32 range so the user sees a
// figure immediately rather than a spinner.
final stats = ImageCodecRateStats.forRate(kImageSendRatePoint);
return _RateEstimate(
payloadBytes: null,
best: _estimate(stats.minBytes, radio),
worst: _estimate(stats.maxBytes, radio),
);
}
SendEstimate _estimate(int payloadBytes, ImageSendRadio radio) {
return estimateSendFromRadioParams(
payloadBytes: payloadBytes,
spreadingFactor: radio.spreadingFactor,
bandwidthHz: radio.bandwidthHz,
codingRate: radio.rawCodingRate,
parity: _parity,
);
}
Future<void> _onSend() async {
setState(() => _sending = true);
final payload = await _encode();
if (!mounted) return;
if (payload == null) {
setState(() => _sending = false);
return;
}
final radio = _radio ?? const ImageSendRadio();
final estimate = _estimate(payload.length, radio);
Navigator.of(context).pop(
ImageSendPreviewResult(
payload: payload,
rate: kImageSendRatePoint,
includeParity: estimate.includesParity,
packetCount: estimate.chunkCount,
airtime: estimate.totalAirtime,
wallClock: estimate.pacedWallClock,
),
);
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final colors = theme.colorScheme;
final l10n = context.l10n;
final radio = _radioParams(context);
_radio = radio;
final selected = _estimateFor(radio);
final ready = widget.codec.availability == ImageCodecAvailability.ready;
return SafeArea(
top: false,
child: DraggableScrollableSheet(
expand: false,
initialChildSize: 0.9,
minChildSize: 0.5,
maxChildSize: 0.95,
builder: (context, scrollController) => Column(
mainAxisSize: MainAxisSize.min,
children: [
_grabHandle(colors),
Padding(
padding: const EdgeInsets.fromLTRB(16, 0, 8, 8),
child: Row(
children: [
Expanded(
child: Text(
l10n.imageSend_title,
style: theme.textTheme.titleLarge,
),
),
IconButton(
icon: const Icon(Icons.close),
tooltip: l10n.imageSend_cancel,
onPressed: _sending
? null
: () => Navigator.of(context).maybePop(),
),
],
),
),
Expanded(
child: ListView(
controller: scrollController,
padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
children: [
_preview(theme, colors),
const SizedBox(height: 16),
if (!ready) _unavailableBanner(theme, colors),
if (ready) ...[
// Packet count and time on air lead: with the quality
// selector gone they are the only decision the user makes.
_headlineStats(theme, colors, selected),
const SizedBox(height: 16),
_sizeRow(theme, colors, selected),
const SizedBox(height: 12),
// Warnings sit directly under the figures they qualify.
..._warnings(theme, colors, radio, selected),
const SizedBox(height: 4),
_parityTile(theme, colors),
if (_failed) ...[
const SizedBox(height: 12),
_banner(
colors: colors,
theme: theme,
icon: Icons.error_outline,
background: colors.errorContainer,
foreground: colors.onErrorContainer,
title: l10n.imageSend_encodeFailed,
body: null,
),
],
],
],
),
),
_actions(theme, ready),
],
),
),
);
}
Widget _grabHandle(ColorScheme colors) => Container(
width: 36,
height: 4,
margin: const EdgeInsets.symmetric(vertical: 12),
decoration: BoxDecoration(
color: colors.onSurfaceVariant.withValues(alpha: 0.4),
borderRadius: BorderRadius.circular(2),
),
);
/// The square render. [BoxFit.fill] on a 1:1 box is exactly the 512x512
/// centre crop the codec will take, so what is shown is what is sent.
///
/// The preview is deliberately capped in height: the packet count and airtime
/// below it are the reason this screen exists and must not be pushed off the
/// first screenful by a full-width square.
Widget _preview(ThemeData theme, ColorScheme colors) {
final maxSide = MediaQuery.sizeOf(context).height * 0.28;
return Column(
children: [
ConstrainedBox(
constraints: BoxConstraints(maxHeight: maxSide, maxWidth: maxSide),
child: ClipRRect(
borderRadius: BorderRadius.circular(12),
child: AspectRatio(
aspectRatio: 1,
child: Container(
color: colors.surfaceContainerHighest,
child: Image.memory(
widget.imageBytes,
fit: BoxFit.fill,
alignment: Alignment.center,
gaplessPlayback: true,
errorBuilder: (context, error, stack) => Center(
child: Icon(
Icons.broken_image_outlined,
size: 48,
color: colors.onSurfaceVariant,
),
),
),
),
),
),
),
const SizedBox(height: 8),
Text(
context.l10n.imageSend_cropNote,
textAlign: TextAlign.center,
style: theme.textTheme.bodySmall?.copyWith(
color: colors.onSurfaceVariant,
),
),
],
);
}
Widget _sizeRow(
ThemeData theme,
ColorScheme colors,
_RateEstimate estimate,
) {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
_sizeChip(
theme,
colors,
context.l10n.imageSend_originalSize,
_formatBytes(widget.originalFileBytes),
strikethrough: true,
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 12),
child: Icon(Icons.arrow_forward, size: 18, color: colors.onSurfaceVariant),
),
_sizeChip(
theme,
colors,
context.l10n.imageSend_onAirSize,
_onAirBytesText(estimate),
emphasised: true,
),
],
);
}
Widget _sizeChip(
ThemeData theme,
ColorScheme colors,
String label,
String value, {
bool strikethrough = false,
bool emphasised = false,
}) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
label,
style: theme.textTheme.labelSmall?.copyWith(
color: colors.onSurfaceVariant,
),
),
Text(
value,
style: theme.textTheme.titleMedium?.copyWith(
color: emphasised ? colors.primary : colors.onSurface,
decoration: strikethrough ? TextDecoration.lineThrough : null,
),
),
],
);
}
/// The point of the whole screen: what this send costs, in big type.
///
/// Only two figures, both large: the packet count and the realistic time the
/// send will take. The byte sizes moved down to [_sizeRow] — with the quality
/// selector gone there is room to give these two the whole width.
Widget _headlineStats(
ThemeData theme,
ColorScheme colors,
_RateEstimate estimate,
) {
final localizations = context.l10n;
return Container(
padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 12),
decoration: BoxDecoration(
color: colors.surfaceContainerHighest,
borderRadius: BorderRadius.circular(12),
),
child: Row(
children: [
Expanded(
child: _stat(
theme,
colors,
localizations.imageSend_packetsLabel,
_packetCountText(estimate),
),
),
_statDivider(colors),
Expanded(
child: _stat(
theme,
colors,
localizations.imageSend_airtimeLabel,
_airtimeText(estimate),
emphasised: true,
),
),
],
),
);
}
Widget _statDivider(ColorScheme colors) => Container(
width: 1,
height: 44,
color: colors.outlineVariant,
);
Widget _stat(
ThemeData theme,
ColorScheme colors,
String label,
String value, {
bool emphasised = false,
}) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
value,
textAlign: TextAlign.center,
style: theme.textTheme.headlineSmall?.copyWith(
color: emphasised ? colors.primary : colors.onSurface,
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: 2),
Text(
label,
textAlign: TextAlign.center,
style: theme.textTheme.labelSmall?.copyWith(
color: colors.onSurfaceVariant,
),
),
],
);
}
Widget _parityTile(ThemeData theme, ColorScheme colors) {
final localizations = context.l10n;
return SwitchListTile(
contentPadding: EdgeInsets.zero,
value: _parity,
onChanged: _sending ? null : (v) => setState(() => _parity = v),
secondary: const Icon(Icons.shield_outlined, size: 20),
title: Text(localizations.imageSend_parityTitle),
subtitle: Text(
localizations.imageSend_paritySubtitle,
style: theme.textTheme.bodySmall?.copyWith(
color: colors.onSurfaceVariant,
),
),
);
}
List<Widget> _warnings(
ThemeData theme,
ColorScheme colors,
ImageSendRadio radio,
_RateEstimate estimate,
) {
final localizations = context.l10n;
final widgets = <Widget>[];
if (!radio.isKnown) {
widgets.add(
_banner(
colors: colors,
theme: theme,
icon: Icons.settings_input_antenna,
background: colors.errorContainer,
foreground: colors.onErrorContainer,
title: localizations.imageSend_radioUnknownTitle,
body: localizations.imageSend_radioUnknownBody,
),
);
} else {
// Compared against the paced wall clock, not raw airtime: the warning is
// about how long the user waits, which is the figure shown above it.
final worst = estimate.worst.pacedWallClock;
if (worst != null && worst >= kImageSendLongAirtime) {
widgets.add(
_banner(
colors: colors,
theme: theme,
icon: Icons.hourglass_bottom,
background: colors.tertiaryContainer,
foreground: colors.onTertiaryContainer,
title: localizations.imageSend_longSendTitle,
body: localizations.imageSend_longSendBody(
_formatDuration(worst),
),
),
);
}
widgets.add(const SizedBox(height: 8));
widgets.add(
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(Icons.hub_outlined, size: 16, color: colors.onSurfaceVariant),
const SizedBox(width: 8),
Expanded(
child: Text(
localizations.imageSend_floodNote,
style: theme.textTheme.bodySmall?.copyWith(
color: colors.onSurfaceVariant,
),
),
),
],
),
);
}
return widgets;
}
/// The "why can't I send?" banner.
///
/// For [ImageCodecAvailability.unavailable] the generic localised string says
/// only that the codec cannot run, which leaves the user with no idea whether
/// to wait, download something, or give up. The codec knows exactly which
/// permanent property of the build it hit, so
/// [ImageSendCodec.unavailableReason] REPLACES the generic string whenever it
/// is non-empty. It falls back to the localised generic only when the codec
/// declined to say why.
Widget _unavailableBanner(ThemeData theme, ColorScheme colors) {
final localizations = context.l10n;
final String message;
switch (widget.codec.availability) {
case ImageCodecAvailability.disabled:
message = localizations.imageSend_codecDisabled;
break;
case ImageCodecAvailability.downloading:
message = localizations.imageSend_codecDownloading;
break;
case ImageCodecAvailability.unavailable:
final reason = widget.codec.unavailableReason?.trim();
message = (reason == null || reason.isEmpty)
? localizations.imageSend_codecUnavailable
: reason;
break;
case ImageCodecAvailability.ready:
return const SizedBox.shrink();
}
return _banner(
colors: colors,
theme: theme,
icon: Icons.info_outline,
background: colors.surfaceContainerHighest,
foreground: colors.onSurfaceVariant,
title: message,
body: null,
);
}
Widget _banner({
required ColorScheme colors,
required ThemeData theme,
required IconData icon,
required Color background,
required Color foreground,
required String title,
required String? body,
}) {
return Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: background,
borderRadius: BorderRadius.circular(12),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(icon, size: 20, color: foreground),
const SizedBox(width: 10),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
title,
style: theme.textTheme.titleSmall?.copyWith(
color: foreground,
),
),
if (body != null) ...[
const SizedBox(height: 2),
Text(
body,
style: theme.textTheme.bodySmall?.copyWith(
color: foreground,
),
),
],
],
),
),
],
),
);
}
Widget _actions(ThemeData theme, bool ready) {
final localizations = context.l10n;
final busy = _sending || _encoding;
return Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 16),
child: Row(
children: [
Expanded(
child: OutlinedButton(
onPressed:
_sending ? null : () => Navigator.of(context).maybePop(),
child: Text(localizations.imageSend_cancel),
),
),
const SizedBox(width: 12),
Expanded(
child: FilledButton.icon(
onPressed: (!ready || busy) ? null : _onSend,
icon: busy
? const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Icon(Icons.send),
label: Text(localizations.imageSend_send),
),
),
],
),
);
}
/// Total bytes actually put on the air (headers + payload + parity).
String _onAirBytesText(_RateEstimate estimate) {
final lo = estimate.best.totalBytes;
final hi = estimate.worst.totalBytes;
if (lo == hi) return _formatBytes(lo);
return _rangeText(_formatBytes(lo), _formatBytes(hi));
}
/// Bare packet count, e.g. "3" or "2–3".
String _packetCountText(_RateEstimate estimate) {
final lo = estimate.best.chunkCount;
final hi = estimate.worst.chunkCount;
if (lo == hi) return '$lo';
return _rangeText('$lo', '$hi');
}
/// The headline time figure.
///
/// This is [SendEstimate.pacedWallClock], NOT raw airtime: a 2-3 packet image
/// is paced, so raw transmitter occupancy would understate the wait the user
/// is being asked to accept. Renders `imageSend_unknownValue`
/// ("—") whenever the radio parameters are unknown — areLoRaParamsValid() has
/// already forced the estimate's time fields to null in that case, and a
/// fabricated ETA is worse than none on a screen whose whole purpose is
/// informed consent.
String _airtimeText(_RateEstimate estimate) {
final l10n = context.l10n;
final min = estimate.best.pacedWallClock;
final max = estimate.worst.pacedWallClock;
if (min == null || max == null) return l10n.imageSend_unknownValue;
if (min == max) return _formatDuration(max);
return _rangeText(_formatDuration(min), _formatDuration(max));
}
String _rangeText(String min, String max) =>
context.l10n.imageSend_range(min, max);
String _formatDuration(Duration d) {
final l10n = context.l10n;
final totalSeconds = d.inMilliseconds / 1000.0;
if (totalSeconds < 60) {
final text = totalSeconds < 10
? totalSeconds.toStringAsFixed(1)
: totalSeconds.round().toString();
return l10n.imageSend_secondsValue(text);
}
final minutes = d.inMinutes;
final seconds = d.inSeconds - minutes * 60;
return l10n.imageSend_minutesSecondsValue('$minutes', '$seconds');
}
String _formatBytes(int bytes) {
if (bytes < 1024) return '$bytes B';
if (bytes < 1024 * 1024) return '${(bytes / 1024).toStringAsFixed(1)} kB';
return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB';
}
}
+652
View File
@@ -0,0 +1,652 @@
/// In-bubble renderer for AEIC images received over the mesh.
///
/// Mirrors `lib/widgets/gif_message.dart`: a fixed-size box (so the reversed
/// `ListView` never jumps as chunks land), one widget per message, all state
/// pulled from [ReceivedImageStore].
///
/// ## RISK R6 — permanent synthesized-content label
///
/// A 156-byte AEIC bitstream decoded by a one-step diffusion model is not a
/// photograph. On the measurement corpus this decoder turned a fox into a
/// sharp, natural, artefact-free sheep. Every decoded image therefore carries
/// TWO provenance elements that no caller can influence:
///
/// * [_SyntheticBanner] — a band burnt into the bottom of the image itself,
/// inside the `ClipRRect`, inside the `Stack`. It is
/// part of the pixels the user sees and part of any
/// screenshot that contains the image at all.
/// * [_SyntheticCaption] — a line of text immediately under the image.
///
/// Both are private to this file, are not parameterised, and are reused
/// verbatim by the full-screen viewer this widget opens on tap, so there is no
/// route in the app that can show the pixels without them. The only case in
/// which they are absent is [ReceivedImageEntry.isOutgoing], where the PNG is
/// the sender's own 512x512 crop and the label would be a falsehood — that is
/// read from the store's sidecar, never from a constructor argument.
///
/// The widget deliberately exposes no share/save action: an exported raster
/// would have to have the caption composited into it first, and that belongs
/// with whoever implements export, not here.
library;
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../services/received_image_store.dart';
import 'image_send_codec_binding.dart' show ImageCodecAvailability;
/// User-visible strings for the NON-decoded states.
///
/// Exists so the wiring agent can hand in `AppLocalizations` values once the
/// `receivedImage_*` ARB keys land (they do not exist yet, so English defaults
/// ship inline). Deliberately contains no field for the R6 badge or caption:
/// those must not be overridable, shortenable or blankable.
@immutable
class ReceivedImageStrings {
final String Function(int received, int total) incoming;
final String queued;
final String tapToDecode;
/// Headline of the awaiting-action placeholder: how big the bitstream is and
/// how many packets carried it, e.g. "156 bytes · 2 packets".
final String Function(int bytes, int packets) awaiting;
/// The affordance on the awaiting-action placeholder.
final String tapToProcess;
final String decoding;
final String Function(int received, int total) incomplete;
final String corrupt;
final String decoderMissing;
final String evicted;
final String retry;
final String decodeAgain;
final String openSettings;
const ReceivedImageStrings({
required this.incoming,
required this.queued,
required this.tapToDecode,
// Optional on purpose: `channel_chat_screen.dart` builds this object and is
// owned by another workstream, so the two tap-to-process strings must not
// break that call site before the `receivedImage_*` ARB keys land.
this.awaiting = _defaultAwaiting,
this.tapToProcess = 'Tap to process',
required this.decoding,
required this.incomplete,
required this.corrupt,
required this.decoderMissing,
required this.evicted,
required this.retry,
required this.decodeAgain,
required this.openSettings,
});
// TODO(l10n): replace with context.l10n.receivedImage_* once app_en.arb has
// the keys listed in section 5(k) of the receive spec.
static ReceivedImageStrings english = ReceivedImageStrings(
incoming: (received, total) => '$received of $total packets',
queued: 'Waiting to decode',
tapToDecode: 'Tap to decode',
awaiting: _defaultAwaiting,
tapToProcess: 'Tap to process',
decoding: 'Reconstructing… about 1 s',
incomplete: (received, total) =>
'Image incomplete — $received of $total packets arrived',
corrupt: 'Image could not be reconstructed',
decoderMissing: 'Image received — image decoding is off',
evicted: 'Image no longer stored',
retry: 'Try again',
decodeAgain: 'Decode again',
openSettings: 'Set up',
);
}
/// English default for [ReceivedImageStrings.awaiting]. A top-level function so
/// it can be a `const` default value on the constructor.
String _defaultAwaiting(int bytes, int packets) =>
'$bytes bytes · $packets packets';
/// Text of the R6 label. Private and const: not injectable, not localisable
/// yet, and never empty.
const String _kSyntheticBadge = 'AI-reconstructed';
/// The caption is built from the ACTUAL bitstream size, never a nominal one:
/// quoting a fixed "~156 bytes" under an image that took 209 is its own small
/// dishonesty, in a label whose whole job is honesty.
String _syntheticCaptionFor(int bytes) =>
'Reconstructed by an AI model from $bytes bytes. '
'Fine detail is generated, not transmitted.';
class ReceivedImageMessage extends StatefulWidget {
/// 14 hex chars, as parsed out of the message text by
/// [ReceivedImageRef.parse].
final String streamId;
/// True for the local user's own message. Not an R6 escape hatch: the label is
/// driven by [ReceivedImageEntry.synthesized], which is derived in the store.
final bool isOutgoing;
/// Colour for the explanatory text inside a chat bubble.
final Color fallbackTextColor;
final double maxSize;
/// Test/preview override. Normally resolved from the widget tree.
final ReceivedImageStore? store;
final ReceivedImageStrings? strings;
/// Route to the image-messages settings page (offered only when the decoder
/// is missing because no weights are downloaded).
final VoidCallback? onOpenCodecSettings;
const ReceivedImageMessage({
super.key,
required this.streamId,
required this.isOutgoing,
required this.fallbackTextColor,
this.maxSize = 200,
this.store,
this.strings,
this.onOpenCodecSettings,
});
@override
State<ReceivedImageMessage> createState() => _ReceivedImageMessageState();
}
class _ReceivedImageMessageState extends State<ReceivedImageMessage> {
ReceivedImageStore? _store;
/// Which stream we have already asked the store to page in. Keyed by id, not
/// a bare bool: a `ListView` recycles this State object across messages, and
/// a bool left over from the previous stream meant the new one's pixels were
/// never requested and the bubble sat on a spinner forever.
String? _pngRequestedFor;
ReceivedImageStore? _resolveStore() {
final injected = widget.store;
if (injected != null) return injected;
try {
return Provider.of<ReceivedImageStore>(context, listen: false);
} on ProviderNotFoundException {
// The receive service is not registered (e.g. a screen test); render the
// "no decoder" state rather than crashing the whole message list.
return null;
}
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
_store = _resolveStore();
_maybeLoadPng();
}
@override
void didUpdateWidget(covariant ReceivedImageMessage oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.streamId != widget.streamId) {
_pngRequestedFor = null;
_store = _resolveStore();
_maybeLoadPng();
}
}
void _maybeLoadPng() {
final store = _store;
if (store == null) return;
if (_pngRequestedFor == widget.streamId) return;
final entry = store.entryFor(widget.streamId);
if (entry == null) return;
if (entry.state != ReceivedImageState.decoded) return;
if (entry.pngBytes != null) return;
_pngRequestedFor = widget.streamId;
store.ensurePng(widget.streamId);
}
@override
Widget build(BuildContext context) {
final store = _store;
if (store == null) {
return _box(context, _unavailableBody(context, null));
}
return ValueListenableBuilder<ReceivedImageEntry?>(
valueListenable: store.listenableFor(widget.streamId),
builder: (context, _, _) {
final entry = store.entryFor(widget.streamId);
_maybeLoadPng();
if (entry == null) {
return _box(context, _unavailableBody(context, null));
}
return _buildForEntry(context, store, entry);
},
);
}
ReceivedImageStrings get _s => widget.strings ?? ReceivedImageStrings.english;
Widget _buildForEntry(
BuildContext context,
ReceivedImageStore store,
ReceivedImageEntry entry,
) {
switch (entry.state) {
case ReceivedImageState.decoded:
final png = entry.pngBytes;
if (png == null) {
return _box(
context,
_progressBody(
context,
progress: null,
label: _s.decoding,
),
);
}
return _decodedBody(context, entry, png);
case ReceivedImageState.receiving:
final total = entry.totalChunks <= 0 ? 1 : entry.totalChunks;
return _box(
context,
_progressBody(
context,
progress: (entry.receivedChunks / total).clamp(0.0, 1.0),
label: _s.incoming(entry.receivedChunks, total),
),
);
// "Bitstream complete, not decoded". Two shades of it, distinguished by
// queue membership rather than by a fourth enum value:
// needsManualDecode -> parked, waiting for a tap (the setting is off,
// or the burst cap trimmed it)
// !needsManualDecode -> already in the store's decode queue
// Both are tappable. The second one deliberately so: a sidecar restored
// by load() is never re-enqueued, so without a tap target a restored
// "Waiting to decode" card would be dead forever.
case ReceivedImageState.reassembled:
return _box(
context,
_iconBody(
context,
icon: entry.needsManualDecode
? Icons.image_outlined
: Icons.hourglass_empty,
label: entry.needsManualDecode
? _s.awaiting(entry.bitstreamByteCount, entry.totalChunks)
: _s.queued,
action: entry.needsManualDecode
? _ActionSpec(
_s.tapToProcess,
() => _onProcessTap(store, entry),
)
: null,
),
onTap: () => _onProcessTap(store, entry),
);
case ReceivedImageState.decoding:
return _box(
context,
_progressBody(context, progress: null, label: _s.decoding),
);
case ReceivedImageState.failedIncomplete:
return _box(
context,
_iconBody(
context,
icon: Icons.broken_image_outlined,
label: _s.incomplete(entry.receivedChunks, entry.totalChunks),
isError: true,
),
);
case ReceivedImageState.failedCorrupt:
return _box(
context,
_iconBody(
context,
icon: Icons.error_outline,
label: _s.corrupt,
isError: true,
action: entry.canRetryDecode
? _ActionSpec(_s.retry, () => store.requestDecode(entry.streamId))
: null,
),
);
case ReceivedImageState.decoderUnavailable:
return _box(context, _unavailableBody(context, entry));
case ReceivedImageState.evicted:
return _box(
context,
_iconBody(
context,
icon: Icons.delete_outline,
label: _s.evicted,
action: entry.canRetryDecode
? _ActionSpec(
_s.decodeAgain,
() => store.requestDecode(entry.streamId),
)
: null,
),
);
}
}
/// Availability of the store's decoder seam.
///
/// Read through the store's public `decoder` field rather than importing
/// `ImageCodecService`: the bubble only needs to know whether a tap would
/// reach a working codec.
ImageCodecAvailability _availability(ReceivedImageStore store) =>
store.decoder?.availability ?? ImageCodecAvailability.unavailable;
/// The one tap handler for the awaiting-action card.
///
/// With no model installed, going through [ReceivedImageStore.requestDecode]
/// would cost the user two taps: the entry would flip to
/// `decoderUnavailable`, and only *then* would the card offer a "Set up"
/// button. So when the codec is not ready and the host screen gave us a route
/// to the image-messages setting, go straight there.
void _onProcessTap(ReceivedImageStore store, ReceivedImageEntry entry) {
final openSettings = widget.onOpenCodecSettings;
if (_availability(store) != ImageCodecAvailability.ready &&
openSettings != null) {
openSettings();
return;
}
store.requestDecode(entry.streamId);
}
// ---- bodies --------------------------------------------------------------
/// 4:3 placeholder box, same discipline as `GifMessage`, so a bubble does not
/// resize as an image progresses.
Widget _box(BuildContext context, Widget child, {VoidCallback? onTap}) {
final theme = Theme.of(context);
final box = Container(
width: widget.maxSize,
height: widget.maxSize * 0.75,
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.4),
borderRadius: BorderRadius.circular(8),
),
child: Center(child: child),
);
if (onTap == null) return box;
return GestureDetector(onTap: onTap, child: box);
}
Widget _progressBody(
BuildContext context, {
required double? progress,
required String label,
}) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: [
SizedBox(
width: 22,
height: 22,
child: CircularProgressIndicator(strokeWidth: 2, value: progress),
),
const SizedBox(height: 8),
_label(context, label),
],
);
}
Widget _iconBody(
BuildContext context, {
required IconData icon,
required String label,
bool isError = false,
_ActionSpec? action,
}) {
final color = isError
? Theme.of(context).colorScheme.error
: widget.fallbackTextColor;
return Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, size: 22, color: color),
const SizedBox(height: 6),
_label(context, label, color: color),
if (action != null)
TextButton(
onPressed: action.onPressed,
style: TextButton.styleFrom(
padding: const EdgeInsets.symmetric(horizontal: 8),
minimumSize: const Size(0, 28),
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
),
child: Text(action.label, style: const TextStyle(fontSize: 12)),
),
],
);
}
Widget _unavailableBody(BuildContext context, ReceivedImageEntry? entry) {
final canSetUp = widget.onOpenCodecSettings != null;
return _iconBody(
context,
icon: Icons.visibility_off_outlined,
label: _s.decoderMissing,
action: canSetUp
? _ActionSpec(_s.openSettings, widget.onOpenCodecSettings!)
: (entry != null && entry.canRetryDecode && _store != null
? _ActionSpec(
_s.retry,
() => _store!.requestDecode(entry.streamId),
)
: null),
);
}
Widget _label(BuildContext context, String text, {Color? color}) {
return Text(
text,
textAlign: TextAlign.center,
maxLines: 3,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 11, color: color ?? widget.fallbackTextColor),
);
}
// ---- decoded (R6) --------------------------------------------------------
Widget _decodedBody(
BuildContext context,
ReceivedImageEntry entry,
Uint8List png,
) {
final size = widget.maxSize;
return GestureDetector(
onTap: () => _openViewer(context, entry, png),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ClipRRect(
borderRadius: BorderRadius.circular(8),
child: SizedBox(
width: size,
// The codec always produces a 512x512 square because the sender
// stretched the whole frame into it. entry.displayAspectRatio is
// the shape it started as, so undo the stretch here rather than
// showing a widened photo. Null means square or unknown.
height: entry.displayAspectRatio == null
? size
: size / entry.displayAspectRatio!,
child: Stack(
children: [
Positioned.fill(
// fill, not contain: the pixels ARE the stretched square,
// so mapping them onto the original aspect box is exactly
// the inverse of what the sender did.
child: Image.memory(png, fit: BoxFit.fill),
),
if (entry.synthesized)
const Positioned(
left: 0,
right: 0,
bottom: 0,
child: _SyntheticBanner(),
),
],
),
),
),
if (entry.synthesized)
SizedBox(
width: size,
child: _SyntheticCaption(bytes: entry.bitstreamByteCount),
),
],
),
);
}
void _openViewer(
BuildContext context,
ReceivedImageEntry entry,
Uint8List png,
) {
Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (_) => _ReceivedImageViewer(
png: png,
synthesized: entry.synthesized,
bytes: entry.bitstreamByteCount,
),
),
);
}
}
class _ActionSpec {
final String label;
final VoidCallback onPressed;
const _ActionSpec(this.label, this.onPressed);
}
/// R6, part 1: a band composited over the bottom of the image.
class _SyntheticBanner extends StatelessWidget {
const _SyntheticBanner();
@override
Widget build(BuildContext context) {
return Container(
height: 18,
alignment: Alignment.center,
color: Colors.black.withValues(alpha: 0.62),
padding: const EdgeInsets.symmetric(horizontal: 4),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.auto_awesome, size: 11, color: Colors.white),
const SizedBox(width: 4),
Text(
_kSyntheticBadge,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontSize: 10, color: Colors.white),
),
],
),
);
}
}
/// R6, part 2: the full sentence, immediately under the image.
class _SyntheticCaption extends StatelessWidget {
/// Contrast variant only. The TEXT is the same const in both cases; there is
/// no parameter that can shorten, blank or restyle it away.
final bool onDark;
/// Size of the bitstream this image was reconstructed from.
final int bytes;
const _SyntheticCaption({required this.bytes, this.onDark = false});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(top: 4),
child: Text(
_syntheticCaptionFor(bytes),
// No maxLines: the bubble is narrow and the sentence must never be
// truncated. A label that reads "Details are invented. Not a" is worse
// than none — it clips exactly where the warning was going.
softWrap: true,
style: TextStyle(
fontSize: 10,
color: onDark
? Colors.white70
: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
);
}
}
/// Full-screen view. Private to this file so no other widget can present the
/// pixels without the two R6 elements.
class _ReceivedImageViewer extends StatelessWidget {
final Uint8List png;
final bool synthesized;
/// Bitstream size, so the full-screen caption quotes the same real number as
/// the one in the transcript.
final int bytes;
const _ReceivedImageViewer({
required this.png,
required this.synthesized,
required this.bytes,
});
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.black,
appBar: AppBar(backgroundColor: Colors.black, foregroundColor: Colors.white),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Flexible(
child: Stack(
children: [
InteractiveViewer(child: Image.memory(png)),
if (synthesized)
const Positioned(
left: 0,
right: 0,
bottom: 0,
child: _SyntheticBanner(),
),
],
),
),
if (synthesized)
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: _SyntheticCaption(bytes: bytes, onDark: true),
),
],
),
),
);
}
}