Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

14.0 KB
Raw Blame
import 'dart:async';
import 'dart:io';
import 'dart:math' as math;

import 'package:flutter/material.dart';
import 'package:lucide_icons_flutter/lucide_icons.dart';

import 'package:harness_mobile/phone/phone_navigation.dart';
import 'package:harness_mobile/phone/tty.dart';
import 'package:harness_mobile/shared/theme/app_space.dart';
import 'package:harness_mobile/shared/theme/app_theme.dart' show AppControl;
import 'package:harness_mobile/shared/widgets/skeleton.dart';

import 'model.dart';
import 'swarm_attachment_store.dart';
import 'swarm_file_download.dart';
import 'swarm_file_links.dart';
import 'swarm_outgoing_files.dart' show swarmFormAttachmentMaxBytes;
import 'swarm_style.dart';

/// A message's file: a picture on Harness's file storage shows in place
/// ([_Preview]); every other file, a picture that cannot be shown, and one
/// past [swarmFormAttachmentMaxBytes] — which every phone in the chat would
/// otherwise fetch and decode whole — is [chip].
class SwarmAttachment extends StatelessWidget {
  const SwarmAttachment({
    super.key,
    required this.file,
    required this.link,
    required this.chip,
    this.thumb,
    this.store,
    this.fileRef,
  });

  final SuperTabAttachment file;

  /// [file]'s thumbnail link, when it has one that opens now
  /// ([SwarmFileRef.currentThumb]): the chat draws that, and the original
  /// only when the picture is opened full screen.
  final Uri? thumb;

  /// [file]'s link, when it is on Harness's file storage — the only place a
  /// picture is fetched from, as the chip only opens a link from there.
  final Uri? link;
  final Widget chip;

  /// Where a fresh link comes from when [link] is missing or has ended
  /// (swarm_file_links.dart): asked for before the picture is fetched, and
  /// once more when a signed link fails.
  final SwarmFileRef? fileRef;

  /// Where the picture is kept; the app's own ([swarmAttachments]) by default.
  final SwarmAttachmentStore? store;

  @override
  Widget build(BuildContext context) {
    final ref = fileRef;
    if (!file.isImage ||
        (link == null && (ref == null || ref.refused)) ||
        file.size > swarmFormAttachmentMaxBytes) {
      return chip;
    }
    return _Preview(
      file: file,
      url: link,
      thumb: thumb,
      fileRef: ref,
      chip: chip,
      store: store ?? swarmAttachments,
    );
  }
}

/// [file] as [store] keeps it: by the link at hand ([at]), else a fresh one
/// of [ref]; a signed link that fails (it may have ended) is asked for once
/// more, then the failure stands.
Future<File> swarmKeptFile(
  SwarmAttachmentStore store,
  SuperTabAttachment file, {
  Uri? at,
  SwarmFileRef? ref,
}) async {
  // A signed link changes every few minutes; the file it reaches does not,
  // so it is kept by the file's id.
  String keyOf(Uri url) =>
      url.host == swarmFilesHost ? 'swarm-file:${file.id}' : url.toString();
  var url = at ?? await (ref ?? (throw StateError('No link'))).link();
  try {
    return await store.file(url, key: keyOf(url));
  } catch (_) {
    if (ref == null || url.host != swarmFilesHost) rethrow;
    url = await ref.link(stale: true);
    return store.file(url, key: keyOf(url));
  }
}

/// The most a picture shows in a message, each way (Dee, 10-29: Slack's 360).
const _maxSide = 360.0;

/// A picture in its message, as Slack shows one: a skeleton in a 4:3 box
/// while it loads (the backend sends no picture's size), then the picture at
/// its own shape, up to [_maxSide] each way and never wider than the message.
/// The chat is held at its foot, so the newest messages stay put as it takes
/// that shape; the whole picture is a tap away ([SwarmAttachmentViewer]).
class _Preview extends StatefulWidget {
  const _Preview({
    required this.file,
    required this.url,
    required this.thumb,
    required this.fileRef,
    required this.chip,
    required this.store,
  });

  final SuperTabAttachment file;

  /// The link at hand; null when a fresh one is asked of [fileRef] first.
  final Uri? url;

  /// The thumbnail's link at hand, drawn in the chat in place of [url].
  final Uri? thumb;
  final SwarmFileRef? fileRef;
  final Widget chip;
  final SwarmAttachmentStore store;

  @override
  State<_Preview> createState() => _PreviewState();
}

class _PreviewState extends State<_Preview> {
  late Future<File> _local;

  /// The store's turn [_local] was asked in ([SwarmAttachmentStore.turns]):
  /// the file is for whoever the store kept files for then, and opens full
  /// screen only while that holds.
  late int _turn;

  /// The picture could not be fetched or decoded: the chip, which still opens it.
  bool _failed = false;

  /// What [_local] holds is the thumbnail, not the original: the viewer then
  /// fetches the original when the picture is opened.
  bool _thumbShown = false;

  @override
  void initState() {
    super.initState();
    widget.store.turns.addListener(_turned);
    _ask();
  }

  @override
  void didUpdateWidget(_Preview old) {
    super.didUpdateWidget(old);
    if (old.url == widget.url &&
        old.thumb == widget.thumb &&
        identical(old.store, widget.store) &&
        identical(old.fileRef?.reader, widget.fileRef?.reader)) {
      return;
    }
    old.store.turns.removeListener(_turned);
    widget.store.turns.addListener(_turned);
    _ask();
  }

  @override
  void dispose() {
    widget.store.turns.removeListener(_turned);
    super.dispose();
  }

  void _ask() {
    _turn = widget.store.turns.value;
    _thumbShown = false;
    final thumb = widget.thumb;
    _local = thumb == null ? _original() : _thumbnailOrOriginal(thumb);
    _failed = false;
  }

  Future<File> _original() => swarmKeptFile(
    widget.store,
    widget.file,
    at: widget.url,
    ref: widget.fileRef,
  );

  /// The thumbnail, kept apart from the original (their addresses and so their
  /// links differ); the original when the thumbnail cannot be had.
  Future<File> _thumbnailOrOriginal(Uri thumb) async {
    try {
      final file = await widget.store.file(
        thumb,
        key: 'swarm-file:${widget.file.id}:thumb',
      );
      _thumbShown = true;
      return file;
    } catch (_) {
      _thumbShown = false;
      return _original();
    }
  }

  /// The files kept changed hands: the picture is asked for again, for
  /// whoever they are kept for now.
  void _turned() {
    if (widget.store.turns.value != _turn) setState(_ask);
  }

  void _fail() {
    if (!mounted || _failed) return;
    setState(() => _failed = true);
  }

  @override
  Widget build(BuildContext context) {
    if (_failed) return widget.chip;
    return LayoutBuilder(
      builder: (context, constraints) {
        final width = math.min(constraints.maxWidth, _maxSide);
        final height = width * 3 / 4;
        final ratio = MediaQuery.devicePixelRatioOf(context);
        final skeleton = Skeleton(
          width: width,
          height: height,
          radius: AppControl.rowRadius,
        );
        return Padding(
          padding: const EdgeInsets.only(top: AppSpace.s),
          child: FutureBuilder<File>(
            future: _local,
            builder: (context, local) {
              if (local.hasError) {
                // After this frame: the chip replaces the whole preview.
                WidgetsBinding.instance.addPostFrameCallback((_) => _fail());
                return skeleton;
              }
              // Only the file this future answered: while a new one is asked
              // (after a turn), the last one is another holder's.
              final file = local.connectionState == ConnectionState.done
                  ? local.data
                  : null;
              return Semantics(
                button: file != null,
                image: true,
                label: 'Picture: ${widget.file.name}',
                excludeSemantics: true,
                child: GestureDetector(
                  key: ValueKey('swarm-attachment-preview-${widget.file.id}'),
                  onTap: file == null ? null : () => _open(context, file),
                  child: ConstrainedBox(
                    constraints: BoxConstraints(
                      maxWidth: width,
                      maxHeight: _maxSide,
                    ),
                    child: file == null
                        ? skeleton
                        : ClipRRect(
                            borderRadius: BorderRadius.circular(
                              AppControl.rowRadius,
                            ),
                            child: Image(
                              // Decoded no larger than it shows, its shape kept.
                              image: ResizeImage(
                                FileImage(file),
                                width: (width * ratio).round(),
                                height: (_maxSide * ratio).round(),
                                policy: ResizeImagePolicy.fit,
                              ),
                              fit: BoxFit.contain,
                              gaplessPlayback: true,
                              frameBuilder: (_, image, frame, synchronous) =>
                                  frame == null && !synchronous
                                  ? skeleton
                                  : image,
                              errorBuilder: (_, _, _) {
                                WidgetsBinding.instance.addPostFrameCallback(
                                  (_) => _fail(),
                                );
                                return skeleton;
                              },
                            ),
                          ),
                  ),
                ),
              );
            },
          ),
        );
      },
    );
  }

  /// Opens [file] full screen, bound to the turn it was asked in, as of the
  /// tap: the viewer is built a frame later, after a change could come.
  void _open(BuildContext context, File file) {
    final turn = _turn;
    if (turn != widget.store.turns.value) return;
    if (!_thumbShown) return _push(context, file, turn);
    unawaited(_openOriginal(context, file, turn));
  }

  /// The viewer shows the original: fetched now, as the thumbnail in the chat is
  /// not what a pinch should zoom into. If it cannot be had, the thumbnail opens.
  Future<void> _openOriginal(BuildContext context, File thumb, int turn) async {
    File shown = thumb;
    try {
      shown = await _original();
    } catch (_) {}
    if (!context.mounted || turn != widget.store.turns.value) return;
    _push(context, shown, turn);
  }

  void _push(BuildContext context, File file, int turn) {
    final name = widget.file.name;
    final store = widget.store;
    unawaited(
      Navigator.of(context).push(
        phoneRoute(
          (_) => SwarmAttachmentViewer(
            name: name,
            file: file,
            store: store,
            turn: turn,
          ),
          listensForItself: true,
        ),
      ),
    );
  }
}

/// A picture full screen, to pinch and zoom; its name, a close and Download
/// ([SwarmDownloadButton]) at the top.
///
/// It shows a file [store] keeps for one account, so it goes when that
/// changes ([SwarmAttachmentStore.turns]: another account, sign-out, Swarm
/// off, a Swarm leaving the list): blank at once, its decoded picture let go,
/// and closed.
class SwarmAttachmentViewer extends StatefulWidget {
  const SwarmAttachmentViewer({
    super.key,
    required this.name,
    required this.file,
    required this.store,
    required this.turn,
  });

  final String name;
  final File file;
  final SwarmAttachmentStore store;

  /// The store's turn [file] was asked in: shown only while it holds, so a
  /// change between the tap and the first frame shows nothing either.
  final int turn;

  @override
  State<SwarmAttachmentViewer> createState() => _ViewerState();
}

class _ViewerState extends State<SwarmAttachmentViewer> {
  /// The decoded picture, as last drawn.
  ImageProvider? _picture;
  bool _gone = false;

  @override
  void initState() {
    super.initState();
    widget.store.turns.addListener(_turned);
    if (widget.store.turns.value != widget.turn) {
      _gone = true;
      WidgetsBinding.instance.addPostFrameCallback((_) => _close());
    }
  }

  @override
  void dispose() {
    widget.store.turns.removeListener(_turned);
    super.dispose();
  }

  void _turned() {
    if (_gone || widget.store.turns.value == widget.turn) return;
    setState(() => _gone = true);
    unawaited(_picture?.evict());
    _close();
  }

  void _close() {
    if (!mounted) return;
    final route = ModalRoute.of(context);
    if (route != null && route.isActive) {
      Navigator.of(context).removeRoute(route);
    }
  }

  @override
  Widget build(BuildContext context) {
    final tty = Tty.of(context);
    final screen = MediaQuery.sizeOf(context).width;
    final ratio = MediaQuery.devicePixelRatioOf(context);
    // Twice the screen, so a zoom stays sharp without holding the picture at
    // its full size.
    final picture = _picture = ResizeImage(
      FileImage(widget.file),
      width: (screen * ratio * 2).round(),
    );
    return Scaffold(
      key: const ValueKey('swarm-attachment-viewer'),
      backgroundColor: tty.ground,
      body: SafeArea(
        child: Column(
          children: [
            SwarmTopBar(
              leading: SwarmIconButton(
                key: const ValueKey('swarm-attachment-close'),
                icon: LucideIcons.x300,
                label: 'Close',
                onPressed: () => Navigator.of(context).maybePop(),
              ),
              title: _gone ? '' : widget.name,
              trailing: SwarmDownloadButton(
                name: widget.name,
                file: _gone ? null : widget.file,
                store: widget.store,
              ),
            ),
            Expanded(
              child: _gone
                  ? const SizedBox.expand()
                  : InteractiveViewer(
                      maxScale: 4,
                      child: Center(
                        child: Image(image: picture, fit: BoxFit.contain),
                      ),
                    ),
            ),
          ],
        ),
      ),
    );
  }
}