gallery.dart 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. import 'dart:async';
  2. import 'dart:math';
  3. import 'package:flutter/cupertino.dart';
  4. import 'package:flutter/material.dart';
  5. import 'package:flutter/services.dart';
  6. import 'package:logging/logging.dart';
  7. import 'package:photos/events/event.dart';
  8. import 'package:photos/models/file.dart';
  9. import 'package:photos/models/selected_files.dart';
  10. import 'package:photos/ui/common_elements.dart';
  11. import 'package:photos/ui/detail_page.dart';
  12. import 'package:photos/ui/draggable_scrollbar.dart';
  13. import 'package:photos/ui/loading_widget.dart';
  14. import 'package:photos/ui/thumbnail_widget.dart';
  15. import 'package:photos/utils/date_time_util.dart';
  16. import 'package:scrollable_positioned_list/scrollable_positioned_list.dart';
  17. class Gallery extends StatefulWidget {
  18. final List<File> Function() syncLoader;
  19. final Future<List<File>> Function(File lastFile, int limit) asyncLoader;
  20. final bool shouldLoadAll;
  21. final Stream<Event> reloadEvent;
  22. final SelectedFiles selectedFiles;
  23. final String tagPrefix;
  24. final Widget headerWidget;
  25. Gallery({
  26. this.syncLoader,
  27. this.asyncLoader,
  28. this.shouldLoadAll = false,
  29. this.reloadEvent,
  30. this.headerWidget,
  31. @required this.selectedFiles,
  32. @required this.tagPrefix,
  33. });
  34. @override
  35. _GalleryState createState() {
  36. return _GalleryState();
  37. }
  38. }
  39. class _GalleryState extends State<Gallery> {
  40. static final int kLoadLimit = 200;
  41. static final int kEagerLoadTrigger = 10;
  42. final Logger _logger = Logger("Gallery");
  43. final List<List<File>> _collatedFiles = List<List<File>>();
  44. final _itemScrollController = ItemScrollController();
  45. final _itemPositionsListener = ItemPositionsListener.create();
  46. final _scrollKey = GlobalKey<DraggableScrollbarState>();
  47. ScrollController _scrollController = ScrollController();
  48. double _scrollOffset = 0;
  49. bool _requiresLoad = false;
  50. bool _hasLoadedAll = false;
  51. bool _isLoadingNext = false;
  52. bool _hasDraggableScrollbar = false;
  53. List<File> _files;
  54. int _lastIndex = 0;
  55. @override
  56. void initState() {
  57. _requiresLoad = true;
  58. if (widget.reloadEvent != null) {
  59. widget.reloadEvent.listen((event) {
  60. if (mounted) {
  61. setState(() {
  62. _requiresLoad = true;
  63. });
  64. }
  65. });
  66. }
  67. widget.selectedFiles.addListener(() {
  68. setState(() {
  69. if (!_hasDraggableScrollbar) {
  70. _saveScrollPosition();
  71. }
  72. });
  73. });
  74. if (widget.asyncLoader == null || widget.shouldLoadAll) {
  75. _hasLoadedAll = true;
  76. }
  77. _itemPositionsListener.itemPositions.addListener(_updateScrollbar);
  78. super.initState();
  79. }
  80. @override
  81. void dispose() {
  82. _itemPositionsListener.itemPositions.removeListener(_updateScrollbar);
  83. super.dispose();
  84. }
  85. @override
  86. Widget build(BuildContext context) {
  87. _logger.info("Building " + widget.tagPrefix);
  88. if (!_requiresLoad) {
  89. return _onDataLoaded();
  90. }
  91. if (widget.syncLoader != null) {
  92. _files = widget.syncLoader();
  93. return _onDataLoaded();
  94. }
  95. return FutureBuilder<List<File>>(
  96. future: widget.asyncLoader(null, kLoadLimit),
  97. builder: (context, snapshot) {
  98. if (snapshot.hasData) {
  99. _requiresLoad = false;
  100. _files = snapshot.data;
  101. return _onDataLoaded();
  102. } else if (snapshot.hasError) {
  103. _requiresLoad = false;
  104. return Center(child: Text(snapshot.error.toString()));
  105. } else {
  106. return Center(child: loadWidget);
  107. }
  108. },
  109. );
  110. }
  111. Widget _onDataLoaded() {
  112. if (_files.isEmpty) {
  113. final children = List<Widget>();
  114. if (widget.headerWidget != null) {
  115. children.add(widget.headerWidget);
  116. }
  117. children.add(Expanded(child: nothingToSeeHere));
  118. return Column(
  119. mainAxisAlignment: MainAxisAlignment.spaceAround,
  120. children: children,
  121. );
  122. }
  123. _collateFiles();
  124. final itemCount =
  125. _collatedFiles.length + (widget.headerWidget == null ? 1 : 2);
  126. _hasDraggableScrollbar = itemCount > 25 || _files.length > 50;
  127. if (!_hasDraggableScrollbar) {
  128. _scrollController = ScrollController(initialScrollOffset: _scrollOffset);
  129. return ListView.builder(
  130. itemCount: itemCount,
  131. itemBuilder: _buildListItem,
  132. controller: _scrollController,
  133. cacheExtent: 1500,
  134. addAutomaticKeepAlives: true,
  135. );
  136. }
  137. return DraggableScrollbar.semicircle(
  138. key: _scrollKey,
  139. initialScrollIndex: _lastIndex,
  140. labelTextBuilder: (position) {
  141. final index =
  142. min((position * itemCount).floor(), _collatedFiles.length - 1);
  143. return Text(
  144. getMonthAndYear(DateTime.fromMicrosecondsSinceEpoch(
  145. _collatedFiles[index][0].creationTime)),
  146. style: TextStyle(
  147. color: Colors.black,
  148. backgroundColor: Colors.white,
  149. fontSize: 14,
  150. ),
  151. );
  152. },
  153. labelConstraints: BoxConstraints.tightFor(width: 100.0, height: 36.0),
  154. onChange: (position) {
  155. final index =
  156. min((position * itemCount).floor(), _collatedFiles.length - 1);
  157. if (index == _lastIndex) {
  158. return;
  159. }
  160. _lastIndex = index;
  161. _itemScrollController.jumpTo(index: index);
  162. },
  163. child: ScrollablePositionedList.builder(
  164. itemCount: itemCount,
  165. itemBuilder: _buildListItem,
  166. itemScrollController: _itemScrollController,
  167. initialScrollIndex: _lastIndex,
  168. minCacheExtent: 1500,
  169. addAutomaticKeepAlives: true,
  170. physics: _MaxVelocityPhysics(velocityThreshold: 128),
  171. itemPositionsListener: _itemPositionsListener,
  172. ),
  173. itemCount: itemCount,
  174. );
  175. }
  176. Widget _buildListItem(BuildContext context, int index) {
  177. if (_shouldLoadNextItems(index)) {
  178. // Eagerly load next batch
  179. _loadNextItems();
  180. }
  181. var fileIndex;
  182. if (widget.headerWidget != null) {
  183. if (index == 0) {
  184. return widget.headerWidget;
  185. }
  186. fileIndex = index - 1;
  187. } else {
  188. fileIndex = index;
  189. }
  190. if (fileIndex == _collatedFiles.length) {
  191. if (widget.asyncLoader != null) {
  192. if (!_hasLoadedAll) {
  193. return loadWidget;
  194. } else {
  195. return Container();
  196. }
  197. }
  198. }
  199. if (fileIndex < 0 || fileIndex >= _collatedFiles.length) {
  200. return Container();
  201. }
  202. var files = _collatedFiles[fileIndex];
  203. return Column(
  204. children: <Widget>[_getDay(files[0].creationTime), _getGallery(files)],
  205. );
  206. }
  207. bool _shouldLoadNextItems(int index) =>
  208. widget.asyncLoader != null &&
  209. !_isLoadingNext &&
  210. (index >= _collatedFiles.length - kEagerLoadTrigger) &&
  211. !_hasLoadedAll;
  212. void _loadNextItems() {
  213. _isLoadingNext = true;
  214. widget.asyncLoader(_files[_files.length - 1], kLoadLimit).then((files) {
  215. setState(() {
  216. _isLoadingNext = false;
  217. _saveScrollPosition();
  218. if (files.length < kLoadLimit) {
  219. _hasLoadedAll = true;
  220. }
  221. _files.addAll(files);
  222. });
  223. });
  224. }
  225. void _saveScrollPosition() {
  226. _scrollOffset = _scrollController.offset;
  227. }
  228. Widget _getDay(int timestamp) {
  229. final date = DateTime.fromMicrosecondsSinceEpoch(timestamp);
  230. final now = DateTime.now();
  231. var title = getDayAndMonth(date);
  232. if (date.year == now.year && date.month == now.month) {
  233. if (date.day == now.day) {
  234. title = "Today";
  235. } else if (date.day == now.day - 1) {
  236. title = "Yesterday";
  237. }
  238. }
  239. if (date.year != DateTime.now().year) {
  240. title += " " + date.year.toString();
  241. }
  242. return Container(
  243. padding: const EdgeInsets.all(8.0),
  244. alignment: Alignment.centerLeft,
  245. child: Text(
  246. title,
  247. style: TextStyle(fontSize: 16),
  248. ),
  249. );
  250. }
  251. Widget _getGallery(List<File> files) {
  252. return GridView.builder(
  253. shrinkWrap: true,
  254. padding: EdgeInsets.only(bottom: 12),
  255. physics:
  256. NeverScrollableScrollPhysics(), // to disable GridView's scrolling
  257. itemBuilder: (context, index) {
  258. return _buildFile(context, files[index]);
  259. },
  260. itemCount: files.length,
  261. gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
  262. crossAxisCount: 4,
  263. ),
  264. );
  265. }
  266. Widget _buildFile(BuildContext context, File file) {
  267. return GestureDetector(
  268. onTap: () {
  269. if (widget.selectedFiles.files.isNotEmpty) {
  270. _selectFile(file);
  271. } else {
  272. _routeToDetailPage(file, context);
  273. }
  274. },
  275. onLongPress: () {
  276. HapticFeedback.lightImpact();
  277. _selectFile(file);
  278. },
  279. child: Container(
  280. margin: const EdgeInsets.all(2.0),
  281. decoration: BoxDecoration(
  282. border: widget.selectedFiles.files.contains(file)
  283. ? Border.all(width: 4.0, color: Colors.blue)
  284. : null,
  285. ),
  286. child: Hero(
  287. tag: widget.tagPrefix + file.tag(),
  288. child: ThumbnailWidget(file),
  289. ),
  290. ),
  291. );
  292. }
  293. void _selectFile(File file) {
  294. widget.selectedFiles.toggleSelection(file);
  295. }
  296. void _routeToDetailPage(File file, BuildContext context) {
  297. final page = DetailPage(
  298. _files,
  299. _files.indexOf(file),
  300. widget.tagPrefix,
  301. );
  302. Navigator.of(context).push(
  303. MaterialPageRoute(
  304. builder: (BuildContext context) {
  305. return page;
  306. },
  307. ),
  308. );
  309. }
  310. void _collateFiles() {
  311. final dailyFiles = List<File>();
  312. final collatedFiles = List<List<File>>();
  313. for (int index = 0; index < _files.length; index++) {
  314. if (index > 0 &&
  315. !_areFilesFromSameDay(_files[index - 1], _files[index])) {
  316. final collatedDailyFiles = List<File>();
  317. collatedDailyFiles.addAll(dailyFiles);
  318. collatedFiles.add(collatedDailyFiles);
  319. dailyFiles.clear();
  320. }
  321. dailyFiles.add(_files[index]);
  322. }
  323. if (dailyFiles.isNotEmpty) {
  324. collatedFiles.add(dailyFiles);
  325. }
  326. _collatedFiles.clear();
  327. _collatedFiles.addAll(collatedFiles);
  328. }
  329. bool _areFilesFromSameDay(File first, File second) {
  330. var firstDate = DateTime.fromMicrosecondsSinceEpoch(first.creationTime);
  331. var secondDate = DateTime.fromMicrosecondsSinceEpoch(second.creationTime);
  332. return firstDate.year == secondDate.year &&
  333. firstDate.month == secondDate.month &&
  334. firstDate.day == secondDate.day;
  335. }
  336. void _updateScrollbar() {
  337. final index = _itemPositionsListener.itemPositions.value.first.index;
  338. _lastIndex = index;
  339. _scrollKey.currentState?.setPosition(index / _collatedFiles.length);
  340. }
  341. }
  342. class _MaxVelocityPhysics extends AlwaysScrollableScrollPhysics {
  343. final double velocityThreshold;
  344. _MaxVelocityPhysics({@required this.velocityThreshold, ScrollPhysics parent})
  345. : super(parent: parent);
  346. @override
  347. bool recommendDeferredLoading(
  348. double velocity, ScrollMetrics metrics, BuildContext context) {
  349. return velocity.abs() > velocityThreshold;
  350. }
  351. @override
  352. _MaxVelocityPhysics applyTo(ScrollPhysics ancestor) {
  353. return _MaxVelocityPhysics(
  354. velocityThreshold: velocityThreshold, parent: buildParent(ancestor));
  355. }
  356. }