fading_app_bar.dart 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  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:like_button/like_button.dart';
  6. import 'package:logging/logging.dart';
  7. import 'package:media_extension/media_extension.dart';
  8. import 'package:path/path.dart' as file_path;
  9. import 'package:photo_manager/photo_manager.dart';
  10. import 'package:photos/core/event_bus.dart';
  11. import 'package:photos/db/files_db.dart';
  12. import 'package:photos/events/local_photos_updated_event.dart';
  13. import "package:photos/generated/l10n.dart";
  14. import 'package:photos/models/file.dart';
  15. import 'package:photos/models/file_type.dart';
  16. import 'package:photos/models/ignored_file.dart';
  17. import "package:photos/models/magic_metadata.dart";
  18. import 'package:photos/models/selected_files.dart';
  19. import 'package:photos/models/trash_file.dart';
  20. import 'package:photos/services/collections_service.dart';
  21. import 'package:photos/services/favorites_service.dart';
  22. import 'package:photos/services/hidden_service.dart';
  23. import 'package:photos/services/ignored_files_service.dart';
  24. import 'package:photos/services/local_sync_service.dart';
  25. import 'package:photos/ui/collection_action_sheet.dart';
  26. import 'package:photos/ui/common/progress_dialog.dart';
  27. import 'package:photos/ui/viewer/file/custom_app_bar.dart';
  28. import "package:photos/ui/viewer/file_details/upload_icon_widget.dart";
  29. import 'package:photos/utils/dialog_util.dart';
  30. import 'package:photos/utils/file_util.dart';
  31. import "package:photos/utils/magic_util.dart";
  32. import 'package:photos/utils/toast_util.dart';
  33. class FadingAppBar extends StatefulWidget implements PreferredSizeWidget {
  34. final File file;
  35. final Function(File) onFileRemoved;
  36. final double height;
  37. final bool shouldShowActions;
  38. final int? userID;
  39. const FadingAppBar(
  40. this.file,
  41. this.onFileRemoved,
  42. this.userID,
  43. this.height,
  44. this.shouldShowActions, {
  45. Key? key,
  46. }) : super(key: key);
  47. @override
  48. Size get preferredSize => Size.fromHeight(height);
  49. @override
  50. FadingAppBarState createState() => FadingAppBarState();
  51. }
  52. class FadingAppBarState extends State<FadingAppBar> {
  53. final _logger = Logger("FadingAppBar");
  54. bool _shouldHide = false;
  55. @override
  56. Widget build(BuildContext context) {
  57. return CustomAppBar(
  58. IgnorePointer(
  59. ignoring: _shouldHide,
  60. child: AnimatedOpacity(
  61. opacity: _shouldHide ? 0 : 1,
  62. duration: const Duration(milliseconds: 150),
  63. child: Container(
  64. decoration: BoxDecoration(
  65. gradient: LinearGradient(
  66. begin: Alignment.topCenter,
  67. end: Alignment.bottomCenter,
  68. colors: [
  69. Colors.black.withOpacity(0.72),
  70. Colors.black.withOpacity(0.6),
  71. Colors.transparent,
  72. ],
  73. stops: const [0, 0.2, 1],
  74. ),
  75. ),
  76. child: _buildAppBar(),
  77. ),
  78. ),
  79. ),
  80. Size.fromHeight(Platform.isAndroid ? 80 : 96),
  81. );
  82. }
  83. void hide() {
  84. setState(() {
  85. _shouldHide = true;
  86. });
  87. }
  88. void show() {
  89. if (mounted) {
  90. setState(() {
  91. _shouldHide = false;
  92. });
  93. }
  94. }
  95. AppBar _buildAppBar() {
  96. debugPrint("building app bar");
  97. final List<Widget> actions = [];
  98. final isTrashedFile = widget.file is TrashFile;
  99. final shouldShowActions = widget.shouldShowActions && !isTrashedFile;
  100. final bool isOwnedByUser =
  101. widget.file.ownerID == null || widget.file.ownerID == widget.userID;
  102. final bool isFileUploaded = widget.file.isUploaded;
  103. bool isFileHidden = false;
  104. if (isOwnedByUser && isFileUploaded) {
  105. isFileHidden = CollectionsService.instance
  106. .getCollectionByID(widget.file.collectionID!)
  107. ?.isHidden() ??
  108. false;
  109. }
  110. // only show fav option for files owned by the user
  111. if (isOwnedByUser && !isFileHidden && isFileUploaded) {
  112. actions.add(_getFavoriteButton());
  113. }
  114. if (!isFileUploaded) {
  115. actions.add(
  116. UploadIconWidget(
  117. file: widget.file,
  118. key: ValueKey(widget.file.tag),
  119. ),
  120. );
  121. }
  122. actions.add(
  123. PopupMenuButton(
  124. itemBuilder: (context) {
  125. final List<PopupMenuItem> items = [];
  126. if (widget.file.isRemoteFile) {
  127. items.add(
  128. PopupMenuItem(
  129. value: 1,
  130. child: Row(
  131. children: [
  132. Icon(
  133. Platform.isAndroid
  134. ? Icons.download
  135. : CupertinoIcons.cloud_download,
  136. color: Theme.of(context).iconTheme.color,
  137. ),
  138. const Padding(
  139. padding: EdgeInsets.all(8),
  140. ),
  141. Text(S.of(context).download),
  142. ],
  143. ),
  144. ),
  145. );
  146. }
  147. // options for files owned by the user
  148. if (isOwnedByUser && !isFileHidden) {
  149. final bool isArchived =
  150. widget.file.magicMetadata.visibility == visibilityArchive;
  151. items.add(
  152. PopupMenuItem(
  153. value: 2,
  154. child: Row(
  155. children: [
  156. Icon(
  157. isArchived ? Icons.unarchive : Icons.archive_outlined,
  158. color: Theme.of(context).iconTheme.color,
  159. ),
  160. const Padding(
  161. padding: EdgeInsets.all(8),
  162. ),
  163. Text(
  164. isArchived
  165. ? S.of(context).unarchive
  166. : S.of(context).archive,
  167. ),
  168. ],
  169. ),
  170. ),
  171. );
  172. }
  173. if ((widget.file.fileType == FileType.image ||
  174. widget.file.fileType == FileType.livePhoto) &&
  175. Platform.isAndroid) {
  176. items.add(
  177. PopupMenuItem(
  178. value: 3,
  179. child: Row(
  180. children: [
  181. Icon(
  182. Icons.wallpaper_outlined,
  183. color: Theme.of(context).iconTheme.color,
  184. ),
  185. const Padding(
  186. padding: EdgeInsets.all(8),
  187. ),
  188. Text(S.of(context).setAs),
  189. ],
  190. ),
  191. ),
  192. );
  193. }
  194. if (isOwnedByUser && widget.file.isUploaded) {
  195. if (!isFileHidden) {
  196. items.add(
  197. PopupMenuItem(
  198. value: 4,
  199. child: Row(
  200. children: [
  201. Icon(
  202. Icons.visibility_off,
  203. color: Theme.of(context).iconTheme.color,
  204. ),
  205. const Padding(
  206. padding: EdgeInsets.all(8),
  207. ),
  208. Text(S.of(context).hide),
  209. ],
  210. ),
  211. ),
  212. );
  213. } else {
  214. items.add(
  215. PopupMenuItem(
  216. value: 5,
  217. child: Row(
  218. children: [
  219. Icon(
  220. Icons.visibility,
  221. color: Theme.of(context).iconTheme.color,
  222. ),
  223. const Padding(
  224. padding: EdgeInsets.all(8),
  225. ),
  226. Text(S.of(context).unhide),
  227. ],
  228. ),
  229. ),
  230. );
  231. }
  232. }
  233. return items;
  234. },
  235. onSelected: (dynamic value) async {
  236. if (value == 1) {
  237. _download(widget.file);
  238. } else if (value == 2) {
  239. await _toggleFileArchiveStatus(widget.file);
  240. } else if (value == 3) {
  241. _setAs(widget.file);
  242. } else if (value == 4) {
  243. _handleHideRequest(context);
  244. } else if (value == 5) {
  245. _handleUnHideRequest(context);
  246. }
  247. },
  248. ),
  249. );
  250. return AppBar(
  251. iconTheme:
  252. const IconThemeData(color: Colors.white), //same for both themes
  253. actions: shouldShowActions ? actions : [],
  254. elevation: 0,
  255. backgroundColor: const Color(0x00000000),
  256. );
  257. }
  258. Future<void> _handleHideRequest(BuildContext context) async {
  259. try {
  260. final hideResult =
  261. await CollectionsService.instance.hideFiles(context, [widget.file]);
  262. if (hideResult) {
  263. widget.onFileRemoved(widget.file);
  264. }
  265. } catch (e, s) {
  266. _logger.severe("failed to update file visibility", e, s);
  267. await showGenericErrorDialog(context: context);
  268. }
  269. }
  270. Future<void> _handleUnHideRequest(BuildContext context) async {
  271. final selectedFiles = SelectedFiles();
  272. selectedFiles.files.add(widget.file);
  273. showCollectionActionSheet(
  274. context,
  275. selectedFiles: selectedFiles,
  276. actionType: CollectionActionType.unHide,
  277. );
  278. }
  279. Widget _getFavoriteButton() {
  280. return FutureBuilder<bool>(
  281. future: FavoritesService.instance.isFavorite(widget.file),
  282. builder: (context, snapshot) {
  283. if (snapshot.hasData) {
  284. return _getLikeButton(widget.file, snapshot.data);
  285. } else {
  286. return _getLikeButton(widget.file, false);
  287. }
  288. },
  289. );
  290. }
  291. Widget _getLikeButton(File file, bool? isLiked) {
  292. return LikeButton(
  293. isLiked: isLiked,
  294. onTap: (oldValue) async {
  295. final isLiked = !oldValue;
  296. bool hasError = false;
  297. if (isLiked) {
  298. final shouldBlockUser = file.uploadedFileID == null;
  299. late ProgressDialog dialog;
  300. if (shouldBlockUser) {
  301. dialog =
  302. createProgressDialog(context, S.of(context).addingToFavorites);
  303. await dialog.show();
  304. }
  305. try {
  306. await FavoritesService.instance.addToFavorites(context, file);
  307. } catch (e, s) {
  308. _logger.severe(e, s);
  309. hasError = true;
  310. showToast(context, S.of(context).sorryCouldNotAddToFavorites);
  311. } finally {
  312. if (shouldBlockUser) {
  313. await dialog.hide();
  314. }
  315. }
  316. } else {
  317. try {
  318. await FavoritesService.instance.removeFromFavorites(context, file);
  319. } catch (e, s) {
  320. _logger.severe(e, s);
  321. hasError = true;
  322. showToast(context, S.of(context).sorryCouldNotRemoveFromFavorites);
  323. }
  324. }
  325. return hasError ? oldValue : isLiked;
  326. },
  327. likeBuilder: (isLiked) {
  328. return Icon(
  329. isLiked ? Icons.favorite_rounded : Icons.favorite_border_rounded,
  330. color:
  331. isLiked ? Colors.pinkAccent : Colors.white, //same for both themes
  332. size: 24,
  333. );
  334. },
  335. );
  336. }
  337. Future<void> _toggleFileArchiveStatus(File file) async {
  338. final bool isArchived =
  339. widget.file.magicMetadata.visibility == visibilityArchive;
  340. await changeVisibility(
  341. context,
  342. [widget.file],
  343. isArchived ? visibilityVisible : visibilityArchive,
  344. );
  345. if (mounted) {
  346. setState(() {});
  347. }
  348. }
  349. Future<void> _download(File file) async {
  350. final dialog = createProgressDialog(context, "Downloading...");
  351. await dialog.show();
  352. try {
  353. final FileType type = file.fileType;
  354. final bool downloadLivePhotoOnDroid =
  355. type == FileType.livePhoto && Platform.isAndroid;
  356. AssetEntity? savedAsset;
  357. final io.File? fileToSave = await getFile(file);
  358. //Disabling notifications for assets changing to insert the file into
  359. //files db before triggering a sync.
  360. PhotoManager.stopChangeNotify();
  361. if (type == FileType.image) {
  362. savedAsset = await PhotoManager.editor
  363. .saveImageWithPath(fileToSave!.path, title: file.title!);
  364. } else if (type == FileType.video) {
  365. savedAsset = await PhotoManager.editor
  366. .saveVideo(fileToSave!, title: file.title!);
  367. } else if (type == FileType.livePhoto) {
  368. final io.File? liveVideoFile =
  369. await getFileFromServer(file, liveVideo: true);
  370. if (liveVideoFile == null) {
  371. throw AssertionError("Live video can not be null");
  372. }
  373. if (downloadLivePhotoOnDroid) {
  374. await _saveLivePhotoOnDroid(fileToSave!, liveVideoFile, file);
  375. } else {
  376. savedAsset = await PhotoManager.editor.darwin.saveLivePhoto(
  377. imageFile: fileToSave!,
  378. videoFile: liveVideoFile,
  379. title: file.title!,
  380. );
  381. }
  382. }
  383. if (savedAsset != null) {
  384. file.localID = savedAsset.id;
  385. await FilesDB.instance.insert(file);
  386. Bus.instance.fire(
  387. LocalPhotosUpdatedEvent(
  388. [file],
  389. source: "download",
  390. ),
  391. );
  392. } else if (!downloadLivePhotoOnDroid && savedAsset == null) {
  393. _logger.severe('Failed to save assert of type $type');
  394. }
  395. showToast(context, S.of(context).fileSavedToGallery);
  396. await dialog.hide();
  397. } catch (e) {
  398. _logger.warning("Failed to save file", e);
  399. await dialog.hide();
  400. showGenericErrorDialog(context: context);
  401. } finally {
  402. PhotoManager.startChangeNotify();
  403. LocalSyncService.instance.checkAndSync().ignore();
  404. }
  405. }
  406. Future<void> _saveLivePhotoOnDroid(
  407. io.File image,
  408. io.File video,
  409. File enteFile,
  410. ) async {
  411. debugPrint("Downloading LivePhoto on Droid");
  412. AssetEntity? savedAsset = await (PhotoManager.editor
  413. .saveImageWithPath(image.path, title: enteFile.title!));
  414. if (savedAsset == null) {
  415. throw Exception("Failed to save image of live photo");
  416. }
  417. IgnoredFile ignoreVideoFile = IgnoredFile(
  418. savedAsset.id,
  419. savedAsset.title ?? '',
  420. savedAsset.relativePath ?? 'remoteDownload',
  421. "remoteDownload",
  422. );
  423. await IgnoredFilesService.instance.cacheAndInsert([ignoreVideoFile]);
  424. final videoTitle = file_path.basenameWithoutExtension(enteFile.title!) +
  425. file_path.extension(video.path);
  426. savedAsset = (await (PhotoManager.editor.saveVideo(
  427. video,
  428. title: videoTitle,
  429. )));
  430. if (savedAsset == null) {
  431. throw Exception("Failed to save video of live photo");
  432. }
  433. ignoreVideoFile = IgnoredFile(
  434. savedAsset.id,
  435. savedAsset.title ?? videoTitle,
  436. savedAsset.relativePath ?? 'remoteDownload',
  437. "remoteDownload",
  438. );
  439. await IgnoredFilesService.instance.cacheAndInsert([ignoreVideoFile]);
  440. }
  441. Future<void> _setAs(File file) async {
  442. final dialog = createProgressDialog(context, S.of(context).pleaseWait);
  443. await dialog.show();
  444. try {
  445. final io.File? fileToSave = await (getFile(file));
  446. if (fileToSave == null) {
  447. throw Exception("Fail to get file for setAs operation");
  448. }
  449. final m = MediaExtension();
  450. final bool result = await m.setAs("file://${fileToSave.path}", "image/*");
  451. if (result == false) {
  452. showShortToast(context, S.of(context).somethingWentWrong);
  453. }
  454. dialog.hide();
  455. } catch (e) {
  456. dialog.hide();
  457. _logger.severe("Failed to use as", e);
  458. showGenericErrorDialog(context: context);
  459. }
  460. }
  461. }