file_details_widget.dart 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  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: 24),
  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. _isImage
  191. ? InfoItemWidget(
  192. leadingIcon: Icons.text_snippet_outlined,
  193. title: "EXIF",
  194. subtitleSection: _exifButton(file, _exif),
  195. )
  196. : null,
  197. FeatureFlagService.instance.isInternalUserOrDebugBuild()
  198. ? InfoItemWidget(
  199. key: const ValueKey("Objects"),
  200. leadingIcon: Icons.image_search_outlined,
  201. title: "Objects",
  202. subtitleSection: _objectTags(file),
  203. hasChipButtons: true,
  204. )
  205. : null,
  206. (file.uploadedFileID != null && file.updationTime != null)
  207. ? InfoItemWidget(
  208. key: const ValueKey("Backup date"),
  209. leadingIcon: Icons.backup_outlined,
  210. title: getFullDate(
  211. DateTime.fromMicrosecondsSinceEpoch(file.updationTime!),
  212. ),
  213. subtitleSection: Future.value([
  214. Text(
  215. getTimeIn12hrFormat(dateTimeForUpdationTime) +
  216. " " +
  217. dateTimeForUpdationTime.timeZoneName,
  218. style: subtitleTextTheme,
  219. ),
  220. ]),
  221. )
  222. : null,
  223. InfoItemWidget(
  224. key: const ValueKey("Albums"),
  225. leadingIcon: Icons.folder_outlined,
  226. title: "Albums",
  227. subtitleSection: fileIsBackedup
  228. ? _collectionsListOfFile(allCollectionIDsOfFile, _currentUserID!)
  229. : _deviceFoldersListOfFile(allDeviceFoldersOfFile),
  230. hasChipButtons: true,
  231. ),
  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 Padding(
  268. padding: EdgeInsets.symmetric(vertical: 15.5),
  269. child: DividerWidget(
  270. dividerType: DividerType.menu,
  271. divColorHasBlur: false,
  272. ),
  273. );
  274. } else {
  275. return listTiles[index ~/ 2];
  276. }
  277. },
  278. childCount: (listTiles.length * 2) - 1,
  279. ),
  280. )
  281. ],
  282. ),
  283. ),
  284. ),
  285. );
  286. }
  287. Future<List<InlineButtonWidget>> _exifButton(
  288. File file,
  289. Map<String, IfdTag>? exif,
  290. ) {
  291. late final String label;
  292. late final VoidCallback? onTap;
  293. if (exif == null) {
  294. label = "Loading EXIF data...";
  295. onTap = null;
  296. } else if (exif.isNotEmpty) {
  297. label = "View all EXIF data";
  298. onTap = () => showDialog(
  299. context: context,
  300. builder: (BuildContext context) {
  301. return ExifInfoDialog(file);
  302. },
  303. barrierColor: backdropFaintDark,
  304. );
  305. } else {
  306. label = "No EXIF data";
  307. onTap = () => showShortToast(context, "This image has no exif data");
  308. }
  309. return Future.value([
  310. InlineButtonWidget(
  311. label,
  312. onTap,
  313. )
  314. ]);
  315. }
  316. Future<List<ChipButtonWidget>> _objectTags(File file) async {
  317. try {
  318. final chipButtons = <ChipButtonWidget>[];
  319. final objectTags = await getThumbnail(file).then((data) {
  320. return ObjectDetectionService.instance.predict(data!);
  321. });
  322. for (String objectTag in objectTags) {
  323. chipButtons.add(ChipButtonWidget(objectTag));
  324. }
  325. if (chipButtons.isEmpty) {
  326. return const [
  327. ChipButtonWidget(
  328. "No results",
  329. noChips: true,
  330. )
  331. ];
  332. }
  333. return chipButtons;
  334. } catch (e, s) {
  335. Logger("FileInfoWidget").info(e, s);
  336. return [];
  337. }
  338. }
  339. Future<List<ChipButtonWidget>> _deviceFoldersListOfFile(
  340. Future<Set<String>> allDeviceFoldersOfFile,
  341. ) async {
  342. try {
  343. final chipButtons = <ChipButtonWidget>[];
  344. final List<String> deviceFolders =
  345. (await allDeviceFoldersOfFile).toList();
  346. for (var deviceFolder in deviceFolders) {
  347. chipButtons.add(
  348. ChipButtonWidget(
  349. deviceFolder,
  350. ),
  351. );
  352. }
  353. return chipButtons;
  354. } catch (e, s) {
  355. Logger("FileInfoWidget").info(e, s);
  356. return [];
  357. }
  358. }
  359. Future<List<ChipButtonWidget>> _collectionsListOfFile(
  360. Future<Set<int>> allCollectionIDsOfFile,
  361. int currentUserID,
  362. ) async {
  363. try {
  364. final chipButtons = <ChipButtonWidget>[];
  365. final Set<int> collectionIDs = await allCollectionIDsOfFile;
  366. final collections = <Collection>[];
  367. for (var collectionID in collectionIDs) {
  368. final c = CollectionsService.instance.getCollectionByID(collectionID);
  369. collections.add(c!);
  370. chipButtons.add(
  371. ChipButtonWidget(
  372. c.isHidden() ? "Hidden" : c.name,
  373. onTap: () {
  374. if (c.isHidden()) {
  375. return;
  376. }
  377. routeToPage(
  378. context,
  379. CollectionPage(
  380. CollectionWithThumbnail(c, null),
  381. appBarType: c.isOwner(currentUserID)
  382. ? GalleryType.ownedCollection
  383. : GalleryType.sharedCollection,
  384. ),
  385. );
  386. },
  387. ),
  388. );
  389. }
  390. return chipButtons;
  391. } catch (e, s) {
  392. Logger("FileInfoWidget").info(e, s);
  393. return [];
  394. }
  395. }
  396. Widget addedBy(File file) {
  397. if (file.uploadedFileID == null) {
  398. return const SizedBox.shrink();
  399. }
  400. String? addedBy;
  401. if (file.ownerID == _currentUserID) {
  402. if (file.pubMagicMetadata!.uploaderName != null) {
  403. addedBy = file.pubMagicMetadata!.uploaderName;
  404. }
  405. } else {
  406. final fileOwner = CollectionsService.instance
  407. .getFileOwner(file.ownerID!, file.collectionID);
  408. addedBy = fileOwner.email;
  409. }
  410. if (addedBy == null || addedBy.isEmpty) {
  411. return const SizedBox.shrink();
  412. }
  413. final enteTheme = Theme.of(context).colorScheme.enteTheme;
  414. return Padding(
  415. padding: const EdgeInsets.only(top: 4.0, bottom: 4.0, left: 16),
  416. child: Text(
  417. "Added by $addedBy",
  418. style: enteTheme.textTheme.mini
  419. .copyWith(color: enteTheme.colorScheme.textMuted),
  420. ),
  421. );
  422. }
  423. _generateExifForDetails(Map<String, IfdTag> exif) {
  424. if (exif["EXIF FocalLength"] != null) {
  425. _exifData["focalLength"] =
  426. (exif["EXIF FocalLength"]!.values.toList()[0] as Ratio).numerator /
  427. (exif["EXIF FocalLength"]!.values.toList()[0] as Ratio)
  428. .denominator;
  429. }
  430. if (exif["EXIF FNumber"] != null) {
  431. _exifData["fNumber"] =
  432. (exif["EXIF FNumber"]!.values.toList()[0] as Ratio).numerator /
  433. (exif["EXIF FNumber"]!.values.toList()[0] as Ratio).denominator;
  434. }
  435. final imageWidth = exif["EXIF ExifImageWidth"] ?? exif["Image ImageWidth"];
  436. final imageLength = exif["EXIF ExifImageLength"] ??
  437. exif["Image "
  438. "ImageLength"];
  439. if (imageWidth != null && imageLength != null) {
  440. _exifData["resolution"] = '$imageWidth x $imageLength';
  441. _exifData['megaPixels'] =
  442. ((imageWidth.values.firstAsInt() * imageLength.values.firstAsInt()) /
  443. 1000000)
  444. .toStringAsFixed(1);
  445. } else {
  446. debugPrint("No image width/height");
  447. }
  448. if (exif["Image Make"] != null && exif["Image Model"] != null) {
  449. _exifData["takenOnDevice"] =
  450. exif["Image Make"].toString() + " " + exif["Image Model"].toString();
  451. }
  452. if (exif["EXIF ExposureTime"] != null) {
  453. _exifData["exposureTime"] = exif["EXIF ExposureTime"].toString();
  454. }
  455. if (exif["EXIF ISOSpeedRatings"] != null) {
  456. _exifData['ISO'] = exif["EXIF ISOSpeedRatings"].toString();
  457. }
  458. }
  459. Widget _getFileSize() {
  460. Future<int> fileSizeFuture;
  461. if (widget.file.fileSize != null) {
  462. fileSizeFuture = Future.value(widget.file.fileSize);
  463. } else {
  464. fileSizeFuture = getFile(widget.file).then((f) => f!.length());
  465. }
  466. return FutureBuilder<int>(
  467. future: fileSizeFuture,
  468. builder: (context, snapshot) {
  469. if (snapshot.hasData) {
  470. return Text(
  471. (snapshot.data! / (1024 * 1024)).toStringAsFixed(2) + " MB",
  472. style: getEnteTextTheme(context).smallMuted,
  473. );
  474. } else {
  475. return SizedBox.fromSize(
  476. size: const Size.square(16),
  477. child: EnteLoadingWidget(
  478. is20pts: true,
  479. color: getEnteColorScheme(context).strokeMuted,
  480. ),
  481. );
  482. }
  483. },
  484. );
  485. }
  486. Widget _getVideoDuration() {
  487. if (widget.file.duration != 0) {
  488. return Text(
  489. secondsToHHMMSS(widget.file.duration!),
  490. style: getEnteTextTheme(context).smallMuted,
  491. );
  492. }
  493. return FutureBuilder<AssetEntity?>(
  494. future: widget.file.getAsset,
  495. builder: (context, snapshot) {
  496. if (snapshot.hasData) {
  497. return Text(
  498. snapshot.data!.videoDuration.toString().split(".")[0],
  499. style: getEnteTextTheme(context).smallMuted,
  500. );
  501. } else {
  502. return Center(
  503. child: SizedBox.fromSize(
  504. size: const Size.square(24),
  505. child: const CupertinoActivityIndicator(
  506. radius: 8,
  507. ),
  508. ),
  509. );
  510. }
  511. },
  512. );
  513. }
  514. void _showDateTimePicker(File file) async {
  515. final dateResult = await DatePicker.showDatePicker(
  516. context,
  517. minTime: DateTime(1800, 1, 1),
  518. maxTime: DateTime.now(),
  519. currentTime: DateTime.fromMicrosecondsSinceEpoch(file.creationTime!),
  520. locale: LocaleType.en,
  521. theme: Theme.of(context).colorScheme.dateTimePickertheme,
  522. );
  523. if (dateResult == null) {
  524. return;
  525. }
  526. final dateWithTimeResult = await DatePicker.showTime12hPicker(
  527. context,
  528. showTitleActions: true,
  529. currentTime: dateResult,
  530. locale: LocaleType.en,
  531. theme: Theme.of(context).colorScheme.dateTimePickertheme,
  532. );
  533. if (dateWithTimeResult != null) {
  534. if (await editTime(
  535. context,
  536. List.of([widget.file]),
  537. dateWithTimeResult.microsecondsSinceEpoch,
  538. )) {
  539. widget.file.creationTime = dateWithTimeResult.microsecondsSinceEpoch;
  540. setState(() {});
  541. }
  542. }
  543. }
  544. }