fluffychat/lib/pages/chat/events/image_bubble.dart

488 lines
16 KiB
Dart
Raw Normal View History

2021-07-11 14:30:39 +02:00
import 'dart:typed_data';
2021-10-26 18:50:34 +02:00
import 'package:flutter/material.dart';
2020-09-07 17:08:01 +02:00
import 'package:cached_network_image/cached_network_image.dart';
2021-10-26 18:50:34 +02:00
import 'package:flutter_blurhash/flutter_blurhash.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
2021-10-26 18:50:34 +02:00
import 'package:flutter_gen/gen_l10n/l10n.dart';
import 'package:flutter_svg/flutter_svg.dart';
2021-07-11 14:30:39 +02:00
import 'package:lottie/lottie.dart';
2021-10-26 18:50:34 +02:00
import 'package:matrix/matrix.dart';
2021-11-09 21:32:16 +01:00
import 'package:fluffychat/pages/image_viewer/image_viewer.dart';
import 'package:fluffychat/widgets/matrix.dart';
import '../../../utils/matrix_sdk_extensions.dart/event_extension.dart';
2020-04-28 14:11:56 +02:00
2020-04-02 14:05:32 +02:00
class ImageBubble extends StatefulWidget {
final Event event;
2020-05-16 08:02:33 +02:00
final bool tapToView;
2020-05-16 09:16:46 +02:00
final BoxFit fit;
2020-05-20 19:29:26 +02:00
final bool maxSize;
2022-01-29 12:35:03 +01:00
final Color? backgroundColor;
2020-09-03 12:58:54 +02:00
final bool thumbnailOnly;
final bool animated;
2021-07-19 18:23:47 +02:00
final double width;
final double height;
2022-01-29 12:35:03 +01:00
final void Function()? onLoaded;
final void Function()? onTap;
2020-04-02 14:05:32 +02:00
2020-05-16 09:16:46 +02:00
const ImageBubble(
this.event, {
this.tapToView = true,
2020-05-20 19:29:26 +02:00
this.maxSize = true,
this.backgroundColor,
2020-05-16 09:16:46 +02:00
this.fit = BoxFit.cover,
2020-09-03 12:58:54 +02:00
this.thumbnailOnly = true,
this.onLoaded,
2021-07-19 18:23:47 +02:00
this.width = 400,
this.height = 300,
this.animated = false,
this.onTap,
2022-01-29 12:35:03 +01:00
Key? key,
2020-05-16 09:16:46 +02:00
}) : super(key: key);
2020-04-02 14:05:32 +02:00
@override
_ImageBubbleState createState() => _ImageBubbleState();
}
class _ImageBubbleState extends State<ImageBubble> {
// for plaintext: holds the http URL for the thumbnail
2022-01-29 12:35:03 +01:00
String? thumbnailUrl;
// for plaintext. holds the http URL for the thumbnial, without the animated flag
2022-01-29 12:35:03 +01:00
String? thumbnailUrlNoAnimated;
// for plaintext: holds the http URL of the original
2022-01-29 12:35:03 +01:00
String? attachmentUrl;
MatrixFile? _file;
MatrixFile? _thumbnail;
bool _requestedThumbnailOnFailure = false;
// In case we have animated = false, this will hold the first frame so that we make
// sure that things are never animated
2022-01-29 12:35:03 +01:00
Widget? _firstFrame;
// the mimetypes that we know how to render, from the flutter Image widget
final _knownMimetypes = <String>{
'image/jpg',
'image/jpeg',
'image/png',
'image/apng',
'image/webp',
'image/gif',
'image/bmp',
'image/x-bmp',
};
2021-07-11 14:30:39 +02:00
// overrides for certain mimetypes if they need different images to render
// memory are for in-memory renderers (e2ee rooms), network for network url renderers.
// The map values themself are set in initState() as they need to be able to access
// `this`.
final _contentRenderers = <String, _ImageBubbleContentRenderer>{};
String getMimetype([bool thumbnail = false]) => thumbnail
? widget.event.thumbnailMimetype.toLowerCase()
: widget.event.attachmentMimetype.toLowerCase();
2022-01-29 12:35:03 +01:00
MatrixFile? get _displayFile => _file ?? _thumbnail;
String? get displayUrl => widget.thumbnailOnly ? thumbnailUrl : attachmentUrl;
dynamic _error;
2020-09-03 12:58:54 +02:00
Future<void> _requestFile({bool getThumbnail = false}) async {
try {
final res = await widget.event
.downloadAndDecryptAttachmentCached(getThumbnail: getThumbnail);
2022-05-12 11:25:34 +02:00
WidgetsBinding.instance.addPostFrameCallback((_) {
if (getThumbnail) {
if (mounted) {
setState(() => _thumbnail = res);
}
} else {
if (widget.onLoaded != null) {
2022-01-29 12:35:03 +01:00
widget.onLoaded!();
}
if (mounted) {
setState(() => _file = res);
}
}
});
} catch (err) {
2022-05-12 11:25:34 +02:00
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) {
setState(() => _error = err);
}
});
2020-09-03 12:58:54 +02:00
}
}
2022-01-29 12:35:03 +01:00
Widget frameBuilder(_, Widget child, int? frame, __) {
// as servers might return animated gifs as thumbnails and we want them to *not* play
// animated, we'll have to store the first frame in a variable and display that instead
if (widget.animated) {
return child;
}
if (frame == 0) {
_firstFrame = child;
}
return _firstFrame ?? child;
}
@override
void initState() {
// add the custom renderers for other mimetypes
2021-07-11 14:30:39 +02:00
_contentRenderers['image/svg+xml'] = _ImageBubbleContentRenderer(
memory: (Uint8List bytes, String key) => SvgPicture.memory(
bytes,
key: ValueKey(key),
fit: widget.fit,
),
2022-01-29 12:35:03 +01:00
network: (String? url) => url == null
? Container()
: SvgPicture.network(
url,
key: ValueKey(url),
placeholderBuilder: (context) => getPlaceholderWidget(),
fit: widget.fit,
),
2021-07-11 14:30:39 +02:00
);
_contentRenderers['image/lottie+json'] = _ImageBubbleContentRenderer(
memory: (Uint8List bytes, String key) => Lottie.memory(
bytes,
key: ValueKey(key),
fit: widget.fit,
errorBuilder: (context, error, stacktrace) =>
getErrorWidget(context, error),
animate: widget.animated,
2021-07-11 14:30:39 +02:00
),
2022-01-29 12:35:03 +01:00
network: (String? url) => url == null
? Container()
: Lottie.network(
url,
key: ValueKey(url),
fit: widget.fit,
errorBuilder: (context, error, stacktrace) =>
getErrorWidget(context, error),
animate: widget.animated,
),
2021-07-11 14:30:39 +02:00
);
// add all the custom content renderer mimetypes to the known mimetypes set
for (final key in _contentRenderers.keys) {
_knownMimetypes.add(key);
}
2021-04-21 14:19:54 +02:00
thumbnailUrl = widget.event
.getAttachmentUrl(getThumbnail: true, animated: widget.animated)
2021-04-23 15:58:12 +02:00
?.toString();
thumbnailUrlNoAnimated = widget.event
.getAttachmentUrl(getThumbnail: true, animated: false)
?.toString();
attachmentUrl =
widget.event.getAttachmentUrl(animated: widget.animated)?.toString();
if (thumbnailUrl == null) {
_requestFile(getThumbnail: true);
2020-09-03 12:58:54 +02:00
}
if (!widget.thumbnailOnly && attachmentUrl == null) {
_requestFile();
} else {
// if the full attachment is cached, we might as well fetch it anyways.
// no need to stick with thumbnail only, since we don't do any networking
widget.event.isAttachmentCached().then((cached) {
if (cached) {
_requestFile();
}
});
}
super.initState();
2020-04-09 10:00:18 +02:00
}
Widget getErrorWidget(BuildContext context, [dynamic error]) {
final String filename = widget.event.content.containsKey('filename')
? widget.event.content['filename']
: widget.event.body;
2021-11-19 10:01:35 +01:00
return getPlaceholderWidget(
child: Column(
2021-11-19 10:01:35 +01:00
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: [
2021-11-19 10:01:35 +01:00
OutlinedButton.icon(
style: OutlinedButton.styleFrom(
backgroundColor: Theme.of(context).scaffoldBackgroundColor,
2022-01-29 12:35:03 +01:00
primary: Theme.of(context).textTheme.bodyText1!.color,
),
2021-11-19 10:01:35 +01:00
icon: const Icon(Icons.download_outlined),
onPressed: () => widget.event.saveFile(context),
2021-11-19 10:01:35 +01:00
label: Text(
filename,
overflow: TextOverflow.fade,
softWrap: false,
maxLines: 1,
),
),
2021-11-19 10:01:35 +01:00
const SizedBox(height: 8),
2022-01-29 12:35:03 +01:00
if (widget.event.sizeString != null) Text(widget.event.sizeString!),
2021-10-14 18:09:30 +02:00
const SizedBox(height: 8),
Text((error ?? _error).toString()),
],
),
);
}
2020-04-02 14:05:32 +02:00
2022-01-29 12:35:03 +01:00
Widget getPlaceholderWidget({Widget? child}) {
Widget? blurhash;
if (widget.event.infoMap['xyz.amorgan.blurhash'] is String) {
final ratio =
widget.event.infoMap['w'] is int && widget.event.infoMap['h'] is int
? widget.event.infoMap['w'] / widget.event.infoMap['h']
: 1.0;
var width = 32;
var height = 32;
if (ratio > 1.0) {
height = (width / ratio).round();
} else {
width = (height * ratio).round();
}
blurhash = BlurHash(
hash: widget.event.infoMap['xyz.amorgan.blurhash'],
decodingWidth: width,
decodingHeight: height,
imageFit: widget.fit,
);
}
return Stack(
children: <Widget>[
if (blurhash != null) blurhash,
Center(
2021-10-16 09:59:38 +02:00
child:
child ?? const CircularProgressIndicator.adaptive(strokeWidth: 2),
),
],
);
2020-09-03 12:58:54 +02:00
}
// Build a memory file (e2ee)
Widget getMemoryWidget() {
final isOriginal = _file != null ||
widget.event.attachmentOrThumbnailMxcUrl(getThumbnail: true) ==
widget.event.attachmentMxcUrl;
final key = isOriginal
2021-08-29 15:18:02 +02:00
? widget.event.attachmentMxcUrl.toString()
: widget.event.thumbnailMxcUrl.toString();
2021-07-11 14:30:39 +02:00
final mimetype = getMimetype(!isOriginal);
if (_contentRenderers.containsKey(mimetype)) {
2022-01-29 12:35:03 +01:00
return _contentRenderers[mimetype]!.memory!(_displayFile!.bytes, key);
} else {
return Image.memory(
2022-01-29 12:35:03 +01:00
_displayFile!.bytes,
key: ValueKey(key),
fit: widget.fit,
2021-08-08 17:55:00 +02:00
errorBuilder: (context, error, stacktrace) {
if (widget.event.hasThumbnail && !_requestedThumbnailOnFailure) {
_requestedThumbnailOnFailure = true;
2022-05-12 11:25:34 +02:00
WidgetsBinding.instance.addPostFrameCallback((_) {
2021-08-08 17:55:00 +02:00
setState(() {
_file = null;
_requestFile(getThumbnail: true);
});
});
return getPlaceholderWidget();
}
return getErrorWidget(context, error);
},
frameBuilder: frameBuilder,
);
}
}
// build a network file (plaintext)
Widget getNetworkWidget() {
// For network files we try to utilize server-side thumbnailing as much as possible.
// Thus, we do the following logic:
// - try to display our URL
// - on failure: Attempt to display the in-event thumbnail instead
// - on failrue / non-existance: Display button to download or view in-app
final mimetype = getMimetype(_requestedThumbnailOnFailure);
if (displayUrl == attachmentUrl &&
2021-07-11 14:30:39 +02:00
_contentRenderers.containsKey(mimetype)) {
2022-01-29 12:35:03 +01:00
return _contentRenderers[mimetype]!.network!(displayUrl);
} else {
return CachedNetworkImage(
// as we change the url on-error we need a key so that the widget actually updates
key: ValueKey(displayUrl),
2022-01-29 12:35:03 +01:00
imageUrl: displayUrl!,
placeholder: (context, url) {
if (!widget.thumbnailOnly &&
displayUrl != thumbnailUrl &&
displayUrl == attachmentUrl) {
// we have to display the thumbnail while loading
return FutureBuilder<bool>(
future: (() async {
return await DefaultCacheManager()
2022-01-29 12:35:03 +01:00
.getFileFromCache(thumbnailUrl!) !=
null;
})(),
builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
if (!snapshot.hasData) {
return getPlaceholderWidget();
}
final effectiveUrl = snapshot.data == true
2022-01-29 12:35:03 +01:00
? thumbnailUrl!
: thumbnailUrlNoAnimated!;
return CachedNetworkImage(
key: ValueKey(effectiveUrl),
imageUrl: effectiveUrl,
placeholder: (c, u) => getPlaceholderWidget(),
imageBuilder: (context, imageProvider) => Image(
image: imageProvider,
frameBuilder: frameBuilder,
fit: widget.fit,
),
);
},
);
}
return getPlaceholderWidget();
},
imageBuilder: (context, imageProvider) => Image(
image: imageProvider,
frameBuilder: frameBuilder,
fit: widget.fit,
),
errorWidget: (context, url, error) {
if (widget.event.hasThumbnail && !_requestedThumbnailOnFailure) {
// the image failed to load but the event has a thumbnail attached....so we can
// try to load this one!
_requestedThumbnailOnFailure = true;
2022-05-12 11:25:34 +02:00
WidgetsBinding.instance.addPostFrameCallback((_) {
setState(() {
2021-04-21 14:19:54 +02:00
thumbnailUrl = widget.event
.getAttachmentUrl(
getThumbnail: true,
useThumbnailMxcUrl: true,
animated: widget.animated)
2021-04-23 15:58:12 +02:00
?.toString();
thumbnailUrlNoAnimated = widget.event
.getAttachmentUrl(
getThumbnail: true,
useThumbnailMxcUrl: true,
animated: false)
?.toString();
attachmentUrl = widget.event
.getAttachmentUrl(
useThumbnailMxcUrl: true, animated: widget.animated)
2021-04-23 15:58:12 +02:00
?.toString();
});
});
return getPlaceholderWidget();
} else if (widget.thumbnailOnly &&
displayUrl != attachmentUrl &&
_knownMimetypes.contains(mimetype)) {
// Okay, the thumbnail failed to load, but we do know how to render the image
// ourselves. Let's offer the user a button to view it.
return getPlaceholderWidget(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
2021-11-19 10:01:35 +01:00
OutlinedButton(
style: OutlinedButton.styleFrom(
backgroundColor: Theme.of(context).scaffoldBackgroundColor,
2022-01-29 12:35:03 +01:00
primary: Theme.of(context).textTheme.bodyText1!.color,
),
onPressed: () => onTap(context),
child: Text(
2022-01-29 12:35:03 +01:00
L10n.of(context)!.tapToShowImage,
overflow: TextOverflow.fade,
softWrap: false,
maxLines: 1,
),
),
2021-11-19 10:01:35 +01:00
if (widget.event.sizeString != null) ...[
const SizedBox(height: 8),
2022-01-29 12:35:03 +01:00
Text(widget.event.sizeString!),
2021-11-19 10:01:35 +01:00
]
],
));
}
return getErrorWidget(context, error);
},
);
}
2020-04-02 14:05:32 +02:00
}
@override
Widget build(BuildContext context) {
Widget content;
String key;
if (_error != null) {
content = getErrorWidget(context);
key = 'error';
} else if (_displayFile != null) {
content = getMemoryWidget();
key = 'memory-' + (content.key as ValueKey).value;
} else if (displayUrl != null) {
content = getNetworkWidget();
key = 'network-' + (content.key as ValueKey).value;
} else {
content = getPlaceholderWidget();
key = 'placeholder';
}
if (widget.maxSize) {
content = AspectRatio(
aspectRatio: widget.width / widget.height,
child: content,
);
}
2021-11-13 20:17:11 +01:00
return InkWell(
onTap: () => onTap(context),
child: Hero(
tag: widget.event.eventId,
child: AnimatedSwitcher(
duration: const Duration(milliseconds: 1000),
child: Container(
key: ValueKey(key),
constraints: widget.maxSize
? BoxConstraints.loose(Size(
widget.width,
widget.height,
))
: null,
child: content,
),
2020-04-02 14:05:32 +02:00
),
),
);
}
void onTap(BuildContext context) {
if (widget.onTap != null) {
2022-01-29 12:35:03 +01:00
widget.onTap!();
return;
}
if (!widget.tapToView) return;
showDialog(
context: Matrix.of(context).navigatorContext,
useRootNavigator: false,
builder: (_) => ImageViewer(widget.event, onLoaded: () {
// If the original file didn't load yet, we want to do that now.
// This is so that the original file displays after going on the image viewer,
// waiting for it to load, and then hitting back. This ensures that we always
// display the best image available, with requiring as little network as possible
if (_file == null) {
widget.event.isAttachmentCached().then((cached) {
if (cached) {
_requestFile();
}
});
}
}),
);
}
2020-04-02 14:05:32 +02:00
}
2021-07-11 14:30:39 +02:00
class _ImageBubbleContentRenderer {
2022-01-29 12:35:03 +01:00
final Widget Function(Uint8List, String)? memory;
final Widget Function(String?)? network;
2021-07-11 14:30:39 +02:00
_ImageBubbleContentRenderer({this.memory, this.network});
}