file_details_widget.dart 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. import "package:exif/exif.dart";
  2. import "package:flutter/cupertino.dart";
  3. import "package:flutter/material.dart";
  4. import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
  5. import "package:logging/logging.dart";
  6. import 'package:path/path.dart' as path;
  7. import 'package:photo_manager/photo_manager.dart';
  8. import "package:photos/core/configuration.dart";
  9. import 'package:photos/db/files_db.dart';
  10. import "package:photos/ente_theme_data.dart";
  11. import "package:photos/models/collection.dart";
  12. import "package:photos/models/collection_items.dart";
  13. import "package:photos/models/file.dart";
  14. import "package:photos/models/file_type.dart";
  15. import "package:photos/models/gallery_type.dart";
  16. import 'package:photos/services/collections_service.dart';
  17. import "package:photos/services/feature_flag_service.dart";
  18. import "package:photos/services/object_detection/object_detection_service.dart";
  19. import "package:photos/theme/colors.dart";
  20. import 'package:photos/theme/ente_theme.dart';
  21. import "package:photos/ui/common/loading_widget.dart";
  22. import "package:photos/ui/components/buttons/chip_button_widget.dart";
  23. import 'package:photos/ui/components/buttons/icon_button_widget.dart';
  24. import "package:photos/ui/components/buttons/inline_button_widget.dart";
  25. import 'package:photos/ui/components/divider_widget.dart';
  26. import "package:photos/ui/components/info_item_widget.dart";
  27. import 'package:photos/ui/components/title_bar_widget.dart';
  28. import "package:photos/ui/viewer/file/exif_info_dialog.dart";
  29. import 'package:photos/ui/viewer/file/file_caption_widget.dart';
  30. import "package:photos/ui/viewer/gallery/collection_page.dart";
  31. import "package:photos/utils/date_time_util.dart";
  32. import "package:photos/utils/exif_util.dart";
  33. import "package:photos/utils/file_util.dart";
  34. import "package:photos/utils/magic_util.dart";
  35. import "package:photos/utils/navigation_util.dart";
  36. import "package:photos/utils/thumbnail_util.dart";
  37. import "package:photos/utils/toast_util.dart";
  38. class FileDetailsWidget extends StatefulWidget {
  39. final File file;
  40. const FileDetailsWidget(
  41. this.file, {
  42. Key? key,
  43. }) : super(key: key);
  44. @override
  45. State<FileDetailsWidget> createState() => _FileDetailsWidgetState();
  46. }
  47. class _FileDetailsWidgetState extends State<FileDetailsWidget> {
  48. Map<String, IfdTag>? _exif;
  49. final Map<String, dynamic> _exifData = {
  50. "focalLength": null,
  51. "fNumber": null,
  52. "resolution": null,
  53. "takenOnDevice": null,
  54. "exposureTime": null,
  55. "ISO": null,
  56. "megaPixels": null
  57. };
  58. bool _isImage = false;
  59. int? _currentUserID;
  60. @override
  61. void initState() {
  62. debugPrint('file_info_dialog initState');
  63. _currentUserID = Configuration.instance.getUserID();
  64. _isImage = widget.file.fileType == FileType.image ||
  65. widget.file.fileType == FileType.livePhoto;
  66. if (_isImage) {
  67. getExif(widget.file).then((exif) {
  68. if (mounted) {
  69. setState(() {
  70. _exif = exif;
  71. });
  72. }
  73. });
  74. }
  75. super.initState();
  76. }
  77. @override
  78. Widget build(BuildContext context) {
  79. final subtitleTextTheme = getEnteTextTheme(context).smallMuted;
  80. final file = widget.file;
  81. final fileIsBackedup = file.uploadedFileID == null ? false : true;
  82. final bool isFileOwner =
  83. file.ownerID == null || file.ownerID == _currentUserID;
  84. late Future<Set<int>> allCollectionIDsOfFile;
  85. //Typing this as Future<Set<T>> as it would be easier to implement showing multiple device folders for a file in the future
  86. final Future<Set<String>> allDeviceFoldersOfFile =
  87. Future.sync(() => {file.deviceFolder ?? ''});
  88. if (fileIsBackedup) {
  89. allCollectionIDsOfFile = FilesDB.instance.getAllCollectionIDsOfFile(
  90. file.uploadedFileID!,
  91. );
  92. }
  93. final dateTime = DateTime.fromMicrosecondsSinceEpoch(file.creationTime!);
  94. final dateTimeForUpdationTime =
  95. DateTime.fromMicrosecondsSinceEpoch(file.updationTime!);
  96. if (_isImage && _exif != null) {
  97. _generateExifForDetails(_exif!);
  98. }
  99. final bool showExifListTile = _exifData["focalLength"] != null ||
  100. _exifData["fNumber"] != null ||
  101. _exifData["takenOnDevice"] != null ||
  102. _exifData["exposureTime"] != null ||
  103. _exifData["ISO"] != null;
  104. final bool showDimension =
  105. _exifData["resolution"] != null && _exifData["megaPixels"] != null;
  106. final listTiles = <Widget?>[
  107. !widget.file.isUploaded ||
  108. (!isFileOwner && (widget.file.caption?.isEmpty ?? true))
  109. ? const SizedBox.shrink()
  110. : Padding(
  111. padding: const EdgeInsets.only(top: 8, bottom: 4),
  112. child: isFileOwner
  113. ? FileCaptionWidget(file: widget.file)
  114. : FileCaptionReadyOnly(caption: widget.file.caption!),
  115. ),
  116. InfoItemWidget(
  117. key: const ValueKey("Creation time"),
  118. leadingIcon: Icons.calendar_today_outlined,
  119. title: getFullDate(
  120. DateTime.fromMicrosecondsSinceEpoch(file.creationTime!),
  121. ),
  122. subtitleSection: Future.value([
  123. Text(
  124. getTimeIn12hrFormat(dateTime) + " " + dateTime.timeZoneName,
  125. style: subtitleTextTheme,
  126. ),
  127. ]),
  128. editOnTap: ((widget.file.ownerID == null ||
  129. widget.file.ownerID == _currentUserID) &&
  130. widget.file.uploadedFileID != null)
  131. ? () {
  132. _showDateTimePicker(widget.file);
  133. }
  134. : null,
  135. ),
  136. InfoItemWidget(
  137. key: const ValueKey("File name and info"),
  138. leadingIcon:
  139. _isImage ? Icons.photo_outlined : Icons.video_camera_back_outlined,
  140. title: path.basenameWithoutExtension(file.displayName) +
  141. path.extension(file.displayName).toUpperCase(),
  142. subtitleSection: Future.value([
  143. if (showDimension)
  144. Text(
  145. "${_exifData["megaPixels"]}MP "
  146. "${_exifData["resolution"]} ",
  147. style: subtitleTextTheme,
  148. ),
  149. _getFileSize(),
  150. if ((file.fileType == FileType.video) &&
  151. (file.localID != null || file.duration != 0))
  152. _getVideoDuration(),
  153. ]),
  154. editOnTap: file.uploadedFileID == null || file.ownerID != _currentUserID
  155. ? null
  156. : () async {
  157. await editFilename(context, file);
  158. setState(() {});
  159. },
  160. ),
  161. showExifListTile
  162. ? InfoItemWidget(
  163. key: const ValueKey("Basic EXIF"),
  164. leadingIcon: Icons.camera_outlined,
  165. title: _exifData["takenOnDevice"] ?? "--",
  166. subtitleSection: Future.value([
  167. if (_exifData["fNumber"] != null)
  168. Text(
  169. 'ƒ/' + _exifData["fNumber"].toString(),
  170. style: subtitleTextTheme,
  171. ),
  172. if (_exifData["exposureTime"] != null)
  173. Text(
  174. _exifData["exposureTime"],
  175. style: subtitleTextTheme,
  176. ),
  177. if (_exifData["focalLength"] != null)
  178. Text(
  179. _exifData["focalLength"].toString() + "mm",
  180. style: subtitleTextTheme,
  181. ),
  182. if (_exifData["ISO"] != null)
  183. Text(
  184. "ISO" + _exifData["ISO"].toString(),
  185. style: subtitleTextTheme,
  186. ),
  187. ]),
  188. )
  189. : null,
  190. InfoItemWidget(
  191. key: const ValueKey("Albums"),
  192. leadingIcon: Icons.folder_outlined,
  193. title: "Albums",
  194. subtitleSection: fileIsBackedup
  195. ? _collectionsListOfFile(allCollectionIDsOfFile, _currentUserID!)
  196. : _deviceFoldersListOfFile(allDeviceFoldersOfFile),
  197. hasChipButtons: true,
  198. ),
  199. FeatureFlagService.instance.isInternalUserOrDebugBuild()
  200. ? InfoItemWidget(
  201. key: const ValueKey("Objects"),
  202. leadingIcon: Icons.image_search_outlined,
  203. title: "Objects",
  204. subtitleSection: _objectTags(file),
  205. hasChipButtons: true,
  206. )
  207. : null,
  208. (file.uploadedFileID != null && file.updationTime != null)
  209. ? InfoItemWidget(
  210. key: const ValueKey("Backup date"),
  211. leadingIcon: Icons.backup_outlined,
  212. title: getFullDate(
  213. DateTime.fromMicrosecondsSinceEpoch(file.updationTime!),
  214. ),
  215. subtitleSection: Future.value([
  216. Text(
  217. getTimeIn12hrFormat(dateTimeForUpdationTime) +
  218. " " +
  219. dateTimeForUpdationTime.timeZoneName,
  220. style: subtitleTextTheme,
  221. ),
  222. ]),
  223. )
  224. : null,
  225. _isImage
  226. ? InfoItemWidget(
  227. leadingIcon: Icons.text_snippet_outlined,
  228. title: "EXIF",
  229. subtitleSection: _exifButton(file, _exif),
  230. )
  231. : null,
  232. ];
  233. listTiles.removeWhere(
  234. (element) => element == null,
  235. );
  236. return SafeArea(
  237. top: false,
  238. child: Scrollbar(
  239. thickness: 4,
  240. radius: const Radius.circular(2),
  241. thumbVisibility: true,
  242. child: Padding(
  243. padding: const EdgeInsets.all(8.0),
  244. child: CustomScrollView(
  245. physics: const ClampingScrollPhysics(),
  246. shrinkWrap: true,
  247. slivers: <Widget>[
  248. TitleBarWidget(
  249. isFlexibleSpaceDisabled: true,
  250. title: "Details",
  251. isOnTopOfScreen: false,
  252. backgroundColor: getEnteColorScheme(context).backgroundElevated,
  253. leading: IconButtonWidget(
  254. icon: Icons.expand_more_outlined,
  255. iconButtonType: IconButtonType.primary,
  256. onTap: () => Navigator.pop(context),
  257. ),
  258. ),
  259. SliverToBoxAdapter(child: addedBy(widget.file)),
  260. SliverList(
  261. delegate: SliverChildBuilderDelegate(
  262. (context, index) {
  263. //Dividers occupy odd indexes
  264. if (index.isOdd) {
  265. return index == 1
  266. ? const SizedBox.shrink()
  267. : const DividerWidget(
  268. dividerType: DividerType.menu,
  269. );
  270. } else {
  271. return listTiles[index ~/ 2];
  272. }
  273. },
  274. childCount: (listTiles.length * 2) - 1,
  275. ),
  276. )
  277. ],
  278. ),
  279. ),
  280. ),
  281. );
  282. }
  283. Future<List<InlineButtonWidget>> _exifButton(
  284. File file,
  285. Map<String, IfdTag>? exif,
  286. ) {
  287. late final String label;
  288. late final VoidCallback? onTap;
  289. if (exif == null) {
  290. label = "Loading EXIF data...";
  291. onTap = null;
  292. } else if (exif.isNotEmpty) {
  293. label = "View all EXIF data";
  294. onTap = () => showDialog(
  295. context: context,
  296. builder: (BuildContext context) {
  297. return ExifInfoDialog(file);
  298. },
  299. barrierColor: backdropFaintDark,
  300. );
  301. } else {
  302. label = "No EXIF data";
  303. onTap = () => showShortToast(context, "This image has no exif data");
  304. }
  305. return Future.value([
  306. InlineButtonWidget(
  307. label,
  308. onTap,
  309. )
  310. ]);
  311. }
  312. Future<List<ChipButtonWidget>> _objectTags(File file) async {
  313. try {
  314. final chipButtons = <ChipButtonWidget>[];
  315. final objectTags = await getThumbnail(file).then((data) {
  316. return ObjectDetectionService.instance.predict(data!);
  317. });
  318. for (String objectTag in objectTags) {
  319. chipButtons.add(ChipButtonWidget(objectTag));
  320. }
  321. if (chipButtons.isEmpty) {
  322. return const [
  323. ChipButtonWidget(
  324. "No result",
  325. noChips: true,
  326. )
  327. ];
  328. }
  329. return chipButtons;
  330. } catch (e, s) {
  331. Logger("FileInfoWidget").info(e, s);
  332. return [];
  333. }
  334. }
  335. Future<List<ChipButtonWidget>> _deviceFoldersListOfFile(
  336. Future<Set<String>> allDeviceFoldersOfFile,
  337. ) async {
  338. try {
  339. final chipButtons = <ChipButtonWidget>[];
  340. final List<String> deviceFolders =
  341. (await allDeviceFoldersOfFile).toList();
  342. for (var deviceFolder in deviceFolders) {
  343. chipButtons.add(
  344. ChipButtonWidget(
  345. deviceFolder,
  346. ),
  347. );
  348. }
  349. return chipButtons;
  350. } catch (e, s) {
  351. Logger("FileInfoWidget").info(e, s);
  352. return [];
  353. }
  354. }
  355. Future<List<ChipButtonWidget>> _collectionsListOfFile(
  356. Future<Set<int>> allCollectionIDsOfFile,
  357. int currentUserID,
  358. ) async {
  359. try {
  360. final chipButtons = <ChipButtonWidget>[];
  361. final Set<int> collectionIDs = await allCollectionIDsOfFile;
  362. final collections = <Collection>[];
  363. for (var collectionID in collectionIDs) {
  364. final c = CollectionsService.instance.getCollectionByID(collectionID);
  365. collections.add(c!);
  366. chipButtons.add(
  367. ChipButtonWidget(
  368. c.isHidden() ? "Hidden" : c.name,
  369. onTap: () {
  370. if (c.isHidden()) {
  371. return;
  372. }
  373. routeToPage(
  374. context,
  375. CollectionPage(
  376. CollectionWithThumbnail(c, null),
  377. appBarType: c.isOwner(currentUserID)
  378. ? GalleryType.ownedCollection
  379. : GalleryType.sharedCollection,
  380. ),
  381. );
  382. },
  383. ),
  384. );
  385. }
  386. return chipButtons;
  387. } catch (e, s) {
  388. Logger("FileInfoWidget").info(e, s);
  389. return [];
  390. }
  391. }
  392. Widget addedBy(File file) {
  393. if (file.uploadedFileID == null) {
  394. return const SizedBox.shrink();
  395. }
  396. String? addedBy;
  397. if (file.ownerID == _currentUserID) {
  398. if (file.pubMagicMetadata!.uploaderName != null) {
  399. addedBy = file.pubMagicMetadata!.uploaderName;
  400. }
  401. } else {
  402. final fileOwner = CollectionsService.instance
  403. .getFileOwner(file.ownerID!, file.collectionID);
  404. addedBy = fileOwner.email;
  405. }
  406. if (addedBy == null || addedBy.isEmpty) {
  407. return const SizedBox.shrink();
  408. }
  409. final enteTheme = Theme.of(context).colorScheme.enteTheme;
  410. return Padding(
  411. padding: const EdgeInsets.only(top: 4.0, bottom: 4.0, left: 16),
  412. child: Text(
  413. "Added by $addedBy",
  414. style: enteTheme.textTheme.mini
  415. .copyWith(color: enteTheme.colorScheme.textMuted),
  416. ),
  417. );
  418. }
  419. _generateExifForDetails(Map<String, IfdTag> exif) {
  420. if (exif["EXIF FocalLength"] != null) {
  421. _exifData["focalLength"] =
  422. (exif["EXIF FocalLength"]!.values.toList()[0] as Ratio).numerator /
  423. (exif["EXIF FocalLength"]!.values.toList()[0] as Ratio)
  424. .denominator;
  425. }
  426. if (exif["EXIF FNumber"] != null) {
  427. _exifData["fNumber"] =
  428. (exif["EXIF FNumber"]!.values.toList()[0] as Ratio).numerator /
  429. (exif["EXIF FNumber"]!.values.toList()[0] as Ratio).denominator;
  430. }
  431. final imageWidth = exif["EXIF ExifImageWidth"] ?? exif["Image ImageWidth"];
  432. final imageLength = exif["EXIF ExifImageLength"] ??
  433. exif["Image "
  434. "ImageLength"];
  435. if (imageWidth != null && imageLength != null) {
  436. _exifData["resolution"] = '$imageWidth x $imageLength';
  437. _exifData['megaPixels'] =
  438. ((imageWidth.values.firstAsInt() * imageLength.values.firstAsInt()) /
  439. 1000000)
  440. .toStringAsFixed(1);
  441. } else {
  442. debugPrint("No image width/height");
  443. }
  444. if (exif["Image Make"] != null && exif["Image Model"] != null) {
  445. _exifData["takenOnDevice"] =
  446. exif["Image Make"].toString() + " " + exif["Image Model"].toString();
  447. }
  448. if (exif["EXIF ExposureTime"] != null) {
  449. _exifData["exposureTime"] = exif["EXIF ExposureTime"].toString();
  450. }
  451. if (exif["EXIF ISOSpeedRatings"] != null) {
  452. _exifData['ISO'] = exif["EXIF ISOSpeedRatings"].toString();
  453. }
  454. }
  455. Widget _getFileSize() {
  456. Future<int> fileSizeFuture;
  457. if (widget.file.fileSize != null) {
  458. fileSizeFuture = Future.value(widget.file.fileSize);
  459. } else {
  460. fileSizeFuture = getFile(widget.file).then((f) => f!.length());
  461. }
  462. return FutureBuilder<int>(
  463. future: fileSizeFuture,
  464. builder: (context, snapshot) {
  465. if (snapshot.hasData) {
  466. return Text(
  467. (snapshot.data! / (1024 * 1024)).toStringAsFixed(2) + " MB",
  468. style: getEnteTextTheme(context).smallMuted,
  469. );
  470. } else {
  471. return SizedBox.fromSize(
  472. size: const Size.square(16),
  473. child: EnteLoadingWidget(
  474. is20pts: true,
  475. color: getEnteColorScheme(context).strokeMuted,
  476. ),
  477. );
  478. }
  479. },
  480. );
  481. }
  482. Widget _getVideoDuration() {
  483. if (widget.file.duration != 0) {
  484. return Text(
  485. secondsToHHMMSS(widget.file.duration!),
  486. style: getEnteTextTheme(context).smallMuted,
  487. );
  488. }
  489. return FutureBuilder<AssetEntity?>(
  490. future: widget.file.getAsset,
  491. builder: (context, snapshot) {
  492. if (snapshot.hasData) {
  493. return Text(
  494. snapshot.data!.videoDuration.toString().split(".")[0],
  495. style: getEnteTextTheme(context).smallMuted,
  496. );
  497. } else {
  498. return Center(
  499. child: SizedBox.fromSize(
  500. size: const Size.square(24),
  501. child: const CupertinoActivityIndicator(
  502. radius: 8,
  503. ),
  504. ),
  505. );
  506. }
  507. },
  508. );
  509. }
  510. void _showDateTimePicker(File file) async {
  511. final dateResult = await DatePicker.showDatePicker(
  512. context,
  513. minTime: DateTime(1800, 1, 1),
  514. maxTime: DateTime.now(),
  515. currentTime: DateTime.fromMicrosecondsSinceEpoch(file.creationTime!),
  516. locale: LocaleType.en,
  517. theme: Theme.of(context).colorScheme.dateTimePickertheme,
  518. );
  519. if (dateResult == null) {
  520. return;
  521. }
  522. final dateWithTimeResult = await DatePicker.showTime12hPicker(
  523. context,
  524. showTitleActions: true,
  525. currentTime: dateResult,
  526. locale: LocaleType.en,
  527. theme: Theme.of(context).colorScheme.dateTimePickertheme,
  528. );
  529. if (dateWithTimeResult != null) {
  530. if (await editTime(
  531. context,
  532. List.of([widget.file]),
  533. dateWithTimeResult.microsecondsSinceEpoch,
  534. )) {
  535. widget.file.creationTime = dateWithTimeResult.microsecondsSinceEpoch;
  536. setState(() {});
  537. }
  538. }
  539. }
  540. }