ente/lib/ui/huge_listview/lazy_loading_gallery.dart

347 lines
9.7 KiB
Dart
Raw Normal View History

import 'dart:async';
2021-04-20 12:26:42 +00:00
import 'dart:math';
2021-04-27 20:02:39 +00:00
import 'package:flutter/foundation.dart';
2021-04-20 12:26:42 +00:00
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:logging/logging.dart';
import 'package:photos/events/files_updated_event.dart';
2021-04-20 12:26:42 +00:00
import 'package:photos/models/file.dart';
2021-04-23 19:55:50 +00:00
import 'package:photos/models/selected_files.dart';
2021-04-21 08:41:58 +00:00
import 'package:photos/ui/detail_page.dart';
import 'package:photos/ui/gallery.dart';
2021-04-20 12:26:42 +00:00
import 'package:photos/ui/huge_listview/place_holder_widget.dart';
import 'package:photos/ui/thumbnail_widget.dart';
import 'package:photos/utils/date_time_util.dart';
import 'package:photos/utils/navigation_util.dart';
2021-04-20 12:26:42 +00:00
import 'package:visibility_detector/visibility_detector.dart';
2021-04-23 19:55:50 +00:00
class LazyLoadingGallery extends StatefulWidget {
final List<File> files;
final int index;
final Stream<FilesUpdatedEvent> reloadEvent;
final GalleryLoader asyncLoader;
2021-04-23 19:55:50 +00:00
final SelectedFiles selectedFiles;
final String tag;
final Stream<int> currentIndexStream;
2021-04-23 19:55:50 +00:00
2021-05-06 21:15:40 +00:00
LazyLoadingGallery(
this.files,
this.index,
this.reloadEvent,
this.asyncLoader,
this.selectedFiles,
this.tag,
this.currentIndexStream, {
Key key,
2021-05-07 12:14:51 +00:00
}) : super(key: key ?? UniqueKey());
2021-04-20 12:26:42 +00:00
2021-04-23 19:55:50 +00:00
@override
_LazyLoadingGalleryState createState() => _LazyLoadingGalleryState();
}
class _LazyLoadingGalleryState extends State<LazyLoadingGallery> {
static const kSubGalleryItemLimit = 80;
2021-05-06 21:31:31 +00:00
static const kRecycleLimit = 400;
2021-04-23 19:55:50 +00:00
static const kMicroSecondsInADay = 86400000000;
static const kNumberOfDaysToRenderBeforeAndAfter = 8;
2021-04-23 19:55:50 +00:00
static final Logger _logger = Logger("LazyLoadingGallery");
List<File> _files;
StreamSubscription<FilesUpdatedEvent> _reloadEventSubscription;
StreamSubscription<int> _currentIndexSubscription;
bool _shouldRender;
2021-04-23 19:55:50 +00:00
@override
void initState() {
super.initState();
_init();
}
void _init() {
_shouldRender = true;
2021-04-23 19:55:50 +00:00
_files = widget.files;
2021-05-06 21:15:40 +00:00
_reloadEventSubscription = widget.reloadEvent.listen((e) => _onReload(e));
_currentIndexSubscription =
widget.currentIndexStream.listen((currentIndex) {
2021-05-06 21:15:40 +00:00
bool shouldRender = (currentIndex - widget.index).abs() <
kNumberOfDaysToRenderBeforeAndAfter;
if (mounted && shouldRender != _shouldRender) {
setState(() {
_shouldRender = shouldRender;
});
}
});
2021-04-23 19:55:50 +00:00
}
2021-05-06 21:15:40 +00:00
Future _onReload(FilesUpdatedEvent event) async {
final galleryDate =
DateTime.fromMicrosecondsSinceEpoch(_files[0].creationTime);
final filesUpdatedThisDay = event.updatedFiles
.where((file) =>
file.creationTime !=
null) // Filtering out noise of deleted files diff from server
.where((file) {
final fileDate = DateTime.fromMicrosecondsSinceEpoch(file.creationTime);
return fileDate.year == galleryDate.year &&
fileDate.month == galleryDate.month &&
fileDate.day == galleryDate.day;
});
if (filesUpdatedThisDay.isNotEmpty) {
_logger.info(filesUpdatedThisDay.length.toString() +
" files were updated on " +
getDayTitle(galleryDate.microsecondsSinceEpoch));
if (event.type == EventType.added_or_updated) {
final dayStartTime =
DateTime(galleryDate.year, galleryDate.month, galleryDate.day);
final files = await widget.asyncLoader(
dayStartTime.microsecondsSinceEpoch,
dayStartTime.microsecondsSinceEpoch + kMicroSecondsInADay - 1);
if (files.isEmpty) {
// All files on this day were deleted, let gallery trigger the reload
} else {
if (mounted) {
setState(() {
_files = files;
});
}
}
} else {
// Files were deleted
final updateFileIDs = Set<int>();
for (final file in filesUpdatedThisDay) {
updateFileIDs.add(file.generatedID);
}
final List<File> files = [];
files.addAll(_files);
files.removeWhere((file) => updateFileIDs.contains(file.generatedID));
if (files.isNotEmpty && mounted) {
// If all files on this day were deleted, ignore and let the gallery reload itself
setState(() {
_files = files;
});
}
}
}
}
@override
void dispose() {
_reloadEventSubscription.cancel();
_currentIndexSubscription.cancel();
super.dispose();
}
@override
void didUpdateWidget(LazyLoadingGallery oldWidget) {
super.didUpdateWidget(oldWidget);
2021-04-27 20:02:39 +00:00
if (!listEquals(_files, widget.files)) {
2021-05-07 20:32:33 +00:00
_reloadEventSubscription.cancel();
_init();
}
}
2021-04-20 12:26:42 +00:00
@override
Widget build(BuildContext context) {
if (_files.length == 0) {
return Container();
}
return Padding(
padding: const EdgeInsets.only(bottom: 12),
child: Column(
children: [
getDayWidget(_files[0].creationTime),
_shouldRender ? _getGallery() : PlaceHolderWidget(_files.length),
],
),
2021-04-20 12:26:42 +00:00
);
}
2021-04-23 19:55:50 +00:00
Widget _getGallery() {
2021-04-20 12:26:42 +00:00
List<Widget> childGalleries = [];
2021-04-23 19:55:50 +00:00
for (int index = 0; index < _files.length; index += kSubGalleryItemLimit) {
2021-04-20 12:26:42 +00:00
childGalleries.add(LazyLoadingGridView(
2021-04-23 19:55:50 +00:00
widget.tag,
_files.sublist(index, min(index + kSubGalleryItemLimit, _files.length)),
widget.asyncLoader,
2021-04-23 19:55:50 +00:00
widget.selectedFiles,
2021-04-24 07:44:56 +00:00
index == 0,
2021-05-06 21:31:31 +00:00
_files.length > kRecycleLimit,
2021-04-20 12:26:42 +00:00
));
}
return Column(
children: childGalleries,
2021-04-20 12:26:42 +00:00
);
}
}
class LazyLoadingGridView extends StatefulWidget {
static const kThumbnailDiskLoadDeferDuration = Duration(milliseconds: 40);
2021-04-26 07:46:36 +00:00
static const kThumbnailServerLoadDeferDuration = Duration(milliseconds: 80);
2021-04-27 14:26:11 +00:00
2021-04-25 11:39:04 +00:00
final String tag;
final List<File> files;
final GalleryLoader asyncLoader;
2021-04-25 11:39:04 +00:00
final SelectedFiles selectedFiles;
2021-05-06 21:17:38 +00:00
final bool shouldRender;
2021-05-06 21:31:31 +00:00
final bool shouldRecycle;
2021-04-20 12:26:42 +00:00
2021-05-04 15:49:11 +00:00
LazyLoadingGridView(
2021-05-06 21:15:40 +00:00
this.tag,
this.files,
this.asyncLoader,
2021-05-06 21:15:40 +00:00
this.selectedFiles,
2021-05-06 21:31:31 +00:00
this.shouldRender,
this.shouldRecycle, {
2021-05-06 21:15:40 +00:00
Key key,
2021-05-07 12:14:51 +00:00
}) : super(key: key ?? UniqueKey());
2021-04-20 12:26:42 +00:00
@override
_LazyLoadingGridViewState createState() => _LazyLoadingGridViewState();
}
class _LazyLoadingGridViewState extends State<LazyLoadingGridView> {
2021-05-06 21:17:38 +00:00
bool _shouldRender;
2021-04-25 11:39:04 +00:00
2021-04-24 07:44:56 +00:00
@override
void initState() {
super.initState();
2021-05-06 21:17:38 +00:00
_shouldRender = widget.shouldRender;
widget.selectedFiles.addListener(() {
bool shouldRefresh = false;
for (final file in widget.files) {
if (widget.selectedFiles.lastSelections.contains(file)) {
shouldRefresh = true;
}
}
if (shouldRefresh && mounted) {
setState(() {});
}
});
2021-04-24 07:44:56 +00:00
}
2021-04-20 12:26:42 +00:00
2021-04-27 20:02:39 +00:00
@override
void didUpdateWidget(LazyLoadingGridView oldWidget) {
super.didUpdateWidget(oldWidget);
if (!listEquals(widget.files, oldWidget.files)) {
2021-05-07 20:32:33 +00:00
_shouldRender = widget.shouldRender;
2021-04-27 20:02:39 +00:00
}
}
2021-04-20 12:26:42 +00:00
@override
Widget build(BuildContext context) {
2021-05-06 21:31:31 +00:00
if (widget.shouldRecycle) {
return _getRecyclableView();
} else {
return _getNonRecyclableView();
}
}
Widget _getRecyclableView() {
return VisibilityDetector(
2021-05-07 12:14:51 +00:00
key: UniqueKey(),
2021-05-06 21:31:31 +00:00
onVisibilityChanged: (visibility) {
final shouldRender = visibility.visibleFraction > 0;
if (mounted && shouldRender != _shouldRender) {
setState(() {
_shouldRender = shouldRender;
});
}
},
child: _shouldRender
? _getGridView()
: PlaceHolderWidget(widget.files.length),
);
}
Widget _getNonRecyclableView() {
2021-05-06 21:17:38 +00:00
if (!_shouldRender) {
2021-04-20 12:26:42 +00:00
return VisibilityDetector(
2021-05-07 12:14:51 +00:00
key: UniqueKey(),
2021-04-20 12:26:42 +00:00
onVisibilityChanged: (visibility) {
2021-05-06 21:31:31 +00:00
if (mounted && visibility.visibleFraction > 0 && !_shouldRender) {
2021-04-20 12:26:42 +00:00
setState(() {
2021-05-06 21:17:38 +00:00
_shouldRender = true;
2021-04-20 12:26:42 +00:00
});
}
},
child: PlaceHolderWidget(widget.files.length),
);
} else {
2021-05-06 21:31:31 +00:00
return _getGridView();
2021-04-20 12:26:42 +00:00
}
}
2021-05-06 21:31:31 +00:00
Widget _getGridView() {
return GridView.builder(
shrinkWrap: true,
physics:
NeverScrollableScrollPhysics(), // to disable GridView's scrolling
itemBuilder: (context, index) {
return _buildFile(context, widget.files[index]);
},
itemCount: widget.files.length,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 4,
),
padding: EdgeInsets.all(0),
);
}
2021-04-20 12:26:42 +00:00
Widget _buildFile(BuildContext context, File file) {
return GestureDetector(
onTap: () {
if (widget.selectedFiles.files.isNotEmpty) {
_selectFile(file);
} else {
_routeToDetailPage(file, context);
}
},
onLongPress: () {
HapticFeedback.lightImpact();
_selectFile(file);
},
child: Container(
margin: const EdgeInsets.all(2.0),
decoration: BoxDecoration(
border: widget.selectedFiles.files.contains(file)
? Border.all(
width: 4.0,
color: Theme.of(context).accentColor,
)
: null,
),
child: Hero(
tag: widget.tag + file.tag(),
2021-04-26 07:29:01 +00:00
child: ThumbnailWidget(
file,
2021-04-27 14:26:11 +00:00
diskLoadDeferDuration:
LazyLoadingGridView.kThumbnailDiskLoadDeferDuration,
serverLoadDeferDuration:
LazyLoadingGridView.kThumbnailServerLoadDeferDuration,
2021-05-08 18:05:51 +00:00
key: Key(widget.tag + file.tag()),
2021-04-26 07:29:01 +00:00
),
2021-04-20 12:26:42 +00:00
),
),
);
}
void _selectFile(File file) {
widget.selectedFiles.toggleSelection(file);
}
void _routeToDetailPage(File file, BuildContext context) {
2021-04-21 08:41:58 +00:00
final page = DetailPage(
widget.files,
widget.asyncLoader,
widget.files.indexOf(file),
2021-04-21 08:41:58 +00:00
widget.tag,
);
routeToPage(context, page);
2021-04-20 12:26:42 +00:00
}
}