fading_app_bar.dart 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. import 'dart:io';
  2. import 'dart:io' as io;
  3. import 'package:flutter/cupertino.dart';
  4. import 'package:flutter/material.dart';
  5. import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
  6. import 'package:like_button/like_button.dart';
  7. import 'package:logging/logging.dart';
  8. import 'package:photo_manager/photo_manager.dart';
  9. import 'package:photos/core/event_bus.dart';
  10. import 'package:photos/db/files_db.dart';
  11. import 'package:photos/ente_theme_data.dart';
  12. import 'package:photos/events/local_photos_updated_event.dart';
  13. import 'package:photos/models/file.dart';
  14. import 'package:photos/models/file_type.dart';
  15. import 'package:photos/models/trash_file.dart';
  16. import 'package:photos/services/favorites_service.dart';
  17. import 'package:photos/services/local_sync_service.dart';
  18. import 'package:photos/ui/common/progress_dialog.dart';
  19. import 'package:photos/ui/viewer/file/custom_app_bar.dart';
  20. import 'package:photos/utils/delete_file_util.dart';
  21. import 'package:photos/utils/dialog_util.dart';
  22. import 'package:photos/utils/file_util.dart';
  23. import 'package:photos/utils/magic_util.dart';
  24. import 'package:photos/utils/toast_util.dart';
  25. class FadingAppBar extends StatefulWidget implements PreferredSizeWidget {
  26. final File file;
  27. final Function(File) onFileDeleted;
  28. final double height;
  29. final bool shouldShowActions;
  30. final int userID;
  31. const FadingAppBar(
  32. this.file,
  33. this.onFileDeleted,
  34. this.userID,
  35. this.height,
  36. this.shouldShowActions, {
  37. Key key,
  38. }) : super(key: key);
  39. @override
  40. Size get preferredSize => Size.fromHeight(height);
  41. @override
  42. FadingAppBarState createState() => FadingAppBarState();
  43. }
  44. class FadingAppBarState extends State<FadingAppBar> {
  45. final _logger = Logger("FadingAppBar");
  46. bool _shouldHide = false;
  47. @override
  48. Widget build(BuildContext context) {
  49. return CustomAppBar(
  50. IgnorePointer(
  51. ignoring: _shouldHide,
  52. child: AnimatedOpacity(
  53. opacity: _shouldHide ? 0 : 1,
  54. duration: const Duration(milliseconds: 150),
  55. child: Container(
  56. decoration: BoxDecoration(
  57. gradient: LinearGradient(
  58. begin: Alignment.topCenter,
  59. end: Alignment.bottomCenter,
  60. colors: [
  61. Colors.black.withOpacity(0.72),
  62. Colors.black.withOpacity(0.6),
  63. Colors.transparent,
  64. ],
  65. stops: const [0, 0.2, 1],
  66. ),
  67. ),
  68. child: _buildAppBar(),
  69. ),
  70. ),
  71. ),
  72. height: Platform.isAndroid ? 80 : 96,
  73. );
  74. }
  75. void hide() {
  76. setState(() {
  77. _shouldHide = true;
  78. });
  79. }
  80. void show() {
  81. if (mounted) {
  82. setState(() {
  83. _shouldHide = false;
  84. });
  85. }
  86. }
  87. AppBar _buildAppBar() {
  88. debugPrint("building app bar");
  89. final List<Widget> actions = [];
  90. final isTrashedFile = widget.file is TrashFile;
  91. final shouldShowActions = widget.shouldShowActions && !isTrashedFile;
  92. // only show fav option for files owned by the user
  93. if (widget.file.ownerID == null || widget.file.ownerID == widget.userID) {
  94. actions.add(_getFavoriteButton());
  95. }
  96. actions.add(
  97. PopupMenuButton(
  98. itemBuilder: (context) {
  99. final List<PopupMenuItem> items = [];
  100. if (widget.file.isRemoteFile()) {
  101. items.add(
  102. PopupMenuItem(
  103. value: 1,
  104. child: Row(
  105. children: [
  106. Icon(
  107. Platform.isAndroid
  108. ? Icons.download
  109. : CupertinoIcons.cloud_download,
  110. color: Theme.of(context).iconTheme.color,
  111. ),
  112. const Padding(
  113. padding: EdgeInsets.all(8),
  114. ),
  115. const Text("Download"),
  116. ],
  117. ),
  118. ),
  119. );
  120. }
  121. // options for files owned by the user
  122. if (widget.file.ownerID == null ||
  123. widget.file.ownerID == widget.userID) {
  124. if (widget.file.uploadedFileID != null) {
  125. items.add(
  126. PopupMenuItem(
  127. value: 2,
  128. child: Row(
  129. children: [
  130. Icon(
  131. Platform.isAndroid
  132. ? Icons.access_time_rounded
  133. : CupertinoIcons.time,
  134. color: Theme.of(context).iconTheme.color,
  135. ),
  136. const Padding(
  137. padding: EdgeInsets.all(8),
  138. ),
  139. const Text("Edit time"),
  140. ],
  141. ),
  142. ),
  143. );
  144. }
  145. items.add(
  146. PopupMenuItem(
  147. value: 3,
  148. child: Row(
  149. children: [
  150. Icon(
  151. Platform.isAndroid
  152. ? Icons.delete_outline
  153. : CupertinoIcons.delete,
  154. color: Theme.of(context).iconTheme.color,
  155. ),
  156. const Padding(
  157. padding: EdgeInsets.all(8),
  158. ),
  159. const Text("Delete"),
  160. ],
  161. ),
  162. ),
  163. );
  164. }
  165. return items;
  166. },
  167. onSelected: (value) {
  168. if (value == 1) {
  169. _download(widget.file);
  170. } else if (value == 2) {
  171. _showDateTimePicker(widget.file);
  172. } else if (value == 3) {
  173. _showDeleteSheet(widget.file);
  174. }
  175. },
  176. ),
  177. );
  178. return AppBar(
  179. iconTheme:
  180. const IconThemeData(color: Colors.white), //same for both themes
  181. actions: shouldShowActions ? actions : [],
  182. elevation: 0,
  183. backgroundColor: const Color(0x00000000),
  184. );
  185. }
  186. Widget _getFavoriteButton() {
  187. return FutureBuilder(
  188. future: FavoritesService.instance.isFavorite(widget.file),
  189. builder: (context, snapshot) {
  190. if (snapshot.hasData) {
  191. return _getLikeButton(widget.file, snapshot.data);
  192. } else {
  193. return _getLikeButton(widget.file, false);
  194. }
  195. },
  196. );
  197. }
  198. Widget _getLikeButton(File file, bool isLiked) {
  199. return LikeButton(
  200. isLiked: isLiked,
  201. onTap: (oldValue) async {
  202. final isLiked = !oldValue;
  203. bool hasError = false;
  204. if (isLiked) {
  205. final shouldBlockUser = file.uploadedFileID == null;
  206. ProgressDialog dialog;
  207. if (shouldBlockUser) {
  208. dialog = createProgressDialog(context, "Adding to favorites...");
  209. await dialog.show();
  210. }
  211. try {
  212. await FavoritesService.instance.addToFavorites(file);
  213. } catch (e, s) {
  214. _logger.severe(e, s);
  215. hasError = true;
  216. showToast(context, "Sorry, could not add this to favorites!");
  217. } finally {
  218. if (shouldBlockUser) {
  219. await dialog.hide();
  220. }
  221. }
  222. } else {
  223. try {
  224. await FavoritesService.instance.removeFromFavorites(file);
  225. } catch (e, s) {
  226. _logger.severe(e, s);
  227. hasError = true;
  228. showToast(context, "Sorry, could not remove this from favorites!");
  229. }
  230. }
  231. return hasError ? oldValue : isLiked;
  232. },
  233. likeBuilder: (isLiked) {
  234. return Icon(
  235. isLiked ? Icons.favorite_rounded : Icons.favorite_border_rounded,
  236. color:
  237. isLiked ? Colors.pinkAccent : Colors.white, //same for both themes
  238. size: 24,
  239. );
  240. },
  241. );
  242. }
  243. void _showDateTimePicker(File file) async {
  244. final dateResult = await DatePicker.showDatePicker(
  245. context,
  246. minTime: DateTime(1800, 1, 1),
  247. maxTime: DateTime.now(),
  248. currentTime: DateTime.fromMicrosecondsSinceEpoch(file.creationTime),
  249. locale: LocaleType.en,
  250. theme: Theme.of(context).colorScheme.dateTimePickertheme,
  251. );
  252. if (dateResult == null) {
  253. return;
  254. }
  255. final dateWithTimeResult = await DatePicker.showTime12hPicker(
  256. context,
  257. showTitleActions: true,
  258. currentTime: dateResult,
  259. locale: LocaleType.en,
  260. theme: Theme.of(context).colorScheme.dateTimePickertheme,
  261. );
  262. if (dateWithTimeResult != null) {
  263. if (await editTime(
  264. context,
  265. List.of([widget.file]),
  266. dateWithTimeResult.microsecondsSinceEpoch,
  267. )) {
  268. widget.file.creationTime = dateWithTimeResult.microsecondsSinceEpoch;
  269. setState(() {});
  270. }
  271. }
  272. }
  273. void _showDeleteSheet(File file) {
  274. final List<Widget> actions = [];
  275. if (file.uploadedFileID == null || file.localID == null) {
  276. actions.add(
  277. CupertinoActionSheetAction(
  278. isDestructiveAction: true,
  279. onPressed: () async {
  280. await deleteFilesFromEverywhere(context, [file]);
  281. Navigator.of(context, rootNavigator: true).pop();
  282. widget.onFileDeleted(file);
  283. },
  284. child: const Text("Everywhere"),
  285. ),
  286. );
  287. } else {
  288. // uploaded file which is present locally too
  289. actions.add(
  290. CupertinoActionSheetAction(
  291. isDestructiveAction: true,
  292. onPressed: () async {
  293. await deleteFilesOnDeviceOnly(context, [file]);
  294. showToast(context, "File deleted from device");
  295. Navigator.of(context, rootNavigator: true).pop();
  296. // TODO: Fix behavior when inside a device folder
  297. },
  298. child: const Text("Device"),
  299. ),
  300. );
  301. actions.add(
  302. CupertinoActionSheetAction(
  303. isDestructiveAction: true,
  304. onPressed: () async {
  305. await deleteFilesFromRemoteOnly(context, [file]);
  306. showShortToast(context, "Moved to trash");
  307. Navigator.of(context, rootNavigator: true).pop();
  308. // TODO: Fix behavior when inside a collection
  309. },
  310. child: const Text("ente"),
  311. ),
  312. );
  313. actions.add(
  314. CupertinoActionSheetAction(
  315. isDestructiveAction: true,
  316. onPressed: () async {
  317. await deleteFilesFromEverywhere(context, [file]);
  318. Navigator.of(context, rootNavigator: true).pop();
  319. widget.onFileDeleted(file);
  320. },
  321. child: const Text("Everywhere"),
  322. ),
  323. );
  324. }
  325. final action = CupertinoActionSheet(
  326. title: const Text("Delete file?"),
  327. actions: actions,
  328. cancelButton: CupertinoActionSheetAction(
  329. child: const Text("Cancel"),
  330. onPressed: () {
  331. Navigator.of(context, rootNavigator: true).pop();
  332. },
  333. ),
  334. );
  335. showCupertinoModalPopup(context: context, builder: (_) => action);
  336. }
  337. Future<void> _download(File file) async {
  338. final dialog = createProgressDialog(context, "Downloading...");
  339. await dialog.show();
  340. FileType type = file.fileType;
  341. // save and track image for livePhoto/image and video for FileType.video
  342. io.File fileToSave = await getFile(file);
  343. final savedAsset = type == FileType.video
  344. ? (await PhotoManager.editor.saveVideo(fileToSave, title: file.title))
  345. : (await PhotoManager.editor
  346. .saveImageWithPath(fileToSave.path, title: file.title));
  347. // immediately track assetID to avoid duplicate upload
  348. await LocalSyncService.instance.trackDownloadedFile(savedAsset.id);
  349. file.localID = savedAsset.id;
  350. await FilesDB.instance.insert(file);
  351. if (type == FileType.livePhoto) {
  352. io.File liveVideo = await getFileFromServer(file, liveVideo: true);
  353. if (liveVideo == null) {
  354. _logger.warning("Failed to find live video" + file.tag());
  355. } else {
  356. final savedAsset = (await PhotoManager.editor.saveVideo(liveVideo));
  357. // in case of livePhoto, file.localID only points the image asset.
  358. // ignore the saved video asset for live photo from future downloads
  359. await LocalSyncService.instance.trackDownloadedFile(savedAsset.id);
  360. }
  361. }
  362. Bus.instance.fire(LocalPhotosUpdatedEvent([file]));
  363. await dialog.hide();
  364. if (file.fileType == FileType.livePhoto) {
  365. showToast(context, "Photo and video saved to gallery");
  366. } else {
  367. showToast(context, "File saved to gallery");
  368. }
  369. }
  370. }