fading_app_bar.dart 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  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. 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. child: Container(
  54. decoration: BoxDecoration(
  55. gradient: LinearGradient(
  56. begin: Alignment.topCenter,
  57. end: Alignment.bottomCenter,
  58. colors: [
  59. Colors.black.withOpacity(0.72),
  60. Colors.black.withOpacity(0.6),
  61. Colors.transparent,
  62. ],
  63. stops: const [0, 0.2, 1],
  64. ),
  65. ),
  66. child: _buildAppBar(),
  67. ),
  68. opacity: _shouldHide ? 0 : 1,
  69. duration: Duration(milliseconds: 150),
  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. Padding(
  113. padding: EdgeInsets.all(8),
  114. ),
  115. 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. Padding(
  137. padding: EdgeInsets.all(8),
  138. ),
  139. 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. Padding(
  157. padding: EdgeInsets.all(8),
  158. ),
  159. 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: IconThemeData(color: Colors.white), //same for both themes
  180. actions: shouldShowActions ? actions : [],
  181. elevation: 0,
  182. backgroundColor: Color(0x00000000),
  183. );
  184. }
  185. Widget _getFavoriteButton() {
  186. return FutureBuilder(
  187. future: FavoritesService.instance.isFavorite(widget.file),
  188. builder: (context, snapshot) {
  189. if (snapshot.hasData) {
  190. return _getLikeButton(widget.file, snapshot.data);
  191. } else {
  192. return _getLikeButton(widget.file, false);
  193. }
  194. },
  195. );
  196. }
  197. Widget _getLikeButton(File file, bool isLiked) {
  198. return LikeButton(
  199. isLiked: isLiked,
  200. onTap: (oldValue) async {
  201. final isLiked = !oldValue;
  202. bool hasError = false;
  203. if (isLiked) {
  204. final shouldBlockUser = file.uploadedFileID == null;
  205. ProgressDialog dialog;
  206. if (shouldBlockUser) {
  207. dialog = createProgressDialog(context, "Adding to favorites...");
  208. await dialog.show();
  209. }
  210. try {
  211. await FavoritesService.instance.addToFavorites(file);
  212. } catch (e, s) {
  213. _logger.severe(e, s);
  214. hasError = true;
  215. showToast(context, "Sorry, could not add this to favorites!");
  216. } finally {
  217. if (shouldBlockUser) {
  218. await dialog.hide();
  219. }
  220. }
  221. } else {
  222. try {
  223. await FavoritesService.instance.removeFromFavorites(file);
  224. } catch (e, s) {
  225. _logger.severe(e, s);
  226. hasError = true;
  227. showToast(context, "Sorry, could not remove this from favorites!");
  228. }
  229. }
  230. return hasError ? oldValue : isLiked;
  231. },
  232. likeBuilder: (isLiked) {
  233. return Icon(
  234. isLiked ? Icons.favorite_rounded : Icons.favorite_border_rounded,
  235. color:
  236. isLiked ? Colors.pinkAccent : Colors.white, //same for both themes
  237. size: 24,
  238. );
  239. },
  240. );
  241. }
  242. void _showDateTimePicker(File file) async {
  243. final dateResult = await DatePicker.showDatePicker(
  244. context,
  245. minTime: DateTime(1800, 1, 1),
  246. maxTime: DateTime.now(),
  247. currentTime: DateTime.fromMicrosecondsSinceEpoch(file.creationTime),
  248. locale: LocaleType.en,
  249. theme: Theme.of(context).colorScheme.dateTimePickertheme,
  250. );
  251. if (dateResult == null) {
  252. return;
  253. }
  254. final dateWithTimeResult = await DatePicker.showTime12hPicker(
  255. context,
  256. showTitleActions: true,
  257. currentTime: dateResult,
  258. locale: LocaleType.en,
  259. theme: Theme.of(context).colorScheme.dateTimePickertheme,
  260. );
  261. if (dateWithTimeResult != null) {
  262. if (await editTime(
  263. context,
  264. List.of([widget.file]),
  265. dateWithTimeResult.microsecondsSinceEpoch,
  266. )) {
  267. widget.file.creationTime = dateWithTimeResult.microsecondsSinceEpoch;
  268. setState(() {});
  269. }
  270. }
  271. }
  272. void _showDeleteSheet(File file) {
  273. final List<Widget> actions = [];
  274. if (file.uploadedFileID == null || file.localID == null) {
  275. actions.add(
  276. CupertinoActionSheetAction(
  277. child: Text("Everywhere"),
  278. isDestructiveAction: true,
  279. onPressed: () async {
  280. await deleteFilesFromEverywhere(context, [file]);
  281. Navigator.of(context, rootNavigator: true).pop();
  282. widget.onFileDeleted(file);
  283. },
  284. ),
  285. );
  286. } else {
  287. // uploaded file which is present locally too
  288. actions.add(
  289. CupertinoActionSheetAction(
  290. child: Text("Device"),
  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. ),
  299. );
  300. actions.add(
  301. CupertinoActionSheetAction(
  302. child: Text("ente"),
  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. ),
  311. );
  312. actions.add(
  313. CupertinoActionSheetAction(
  314. child: Text("Everywhere"),
  315. isDestructiveAction: true,
  316. onPressed: () async {
  317. await deleteFilesFromEverywhere(context, [file]);
  318. Navigator.of(context, rootNavigator: true).pop();
  319. widget.onFileDeleted(file);
  320. },
  321. ),
  322. );
  323. }
  324. final action = CupertinoActionSheet(
  325. title: Text("Delete file?"),
  326. actions: actions,
  327. cancelButton: CupertinoActionSheetAction(
  328. child: Text("Cancel"),
  329. onPressed: () {
  330. Navigator.of(context, rootNavigator: true).pop();
  331. },
  332. ),
  333. );
  334. showCupertinoModalPopup(context: context, builder: (_) => action);
  335. }
  336. Future<void> _download(File file) async {
  337. final dialog = createProgressDialog(context, "Downloading...");
  338. await dialog.show();
  339. FileType type = file.fileType;
  340. // save and track image for livePhoto/image and video for FileType.video
  341. io.File fileToSave = await getFile(file);
  342. final savedAsset = type == FileType.video
  343. ? (await PhotoManager.editor.saveVideo(fileToSave, title: file.title))
  344. : (await PhotoManager.editor
  345. .saveImageWithPath(fileToSave.path, title: file.title));
  346. // immediately track assetID to avoid duplicate upload
  347. await LocalSyncService.instance.trackDownloadedFile(savedAsset.id);
  348. file.localID = savedAsset.id;
  349. await FilesDB.instance.insert(file);
  350. if (type == FileType.livePhoto) {
  351. io.File liveVideo = await getFileFromServer(file, liveVideo: true);
  352. if (liveVideo == null) {
  353. _logger.warning("Failed to find live video" + file.tag());
  354. } else {
  355. final savedAsset = (await PhotoManager.editor.saveVideo(liveVideo));
  356. // in case of livePhoto, file.localID only points the image asset.
  357. // ignore the saved video asset for live photo from future downloads
  358. await LocalSyncService.instance.trackDownloadedFile(savedAsset.id);
  359. }
  360. }
  361. Bus.instance.fire(LocalPhotosUpdatedEvent([file]));
  362. await dialog.hide();
  363. if (file.fileType == FileType.livePhoto) {
  364. showToast(context, "Photo and video saved to gallery");
  365. } else {
  366. showToast(context, "File saved to gallery");
  367. }
  368. }
  369. }