fading_app_bar.dart 12 KB

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