file_details_widget.dart 19 KB

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