fading_app_bar.dart 13 KB

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