fading_app_bar.dart 12 KB

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