detail_page.dart 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. import 'package:extended_image/extended_image.dart';
  2. import 'package:flutter/material.dart';
  3. import 'package:flutter/services.dart';
  4. import 'package:logging/logging.dart';
  5. import 'package:photos/core/configuration.dart';
  6. import 'package:photos/core/constants.dart';
  7. import 'package:photos/core/errors.dart';
  8. import "package:photos/generated/l10n.dart";
  9. import 'package:photos/models/file.dart';
  10. import 'package:photos/ui/tools/editor/image_editor_page.dart';
  11. import 'package:photos/ui/viewer/file/fading_app_bar.dart';
  12. import 'package:photos/ui/viewer/file/fading_bottom_bar.dart';
  13. import 'package:photos/ui/viewer/file/file_widget.dart';
  14. import 'package:photos/ui/viewer/gallery/gallery.dart';
  15. import 'package:photos/utils/dialog_util.dart';
  16. import 'package:photos/utils/file_util.dart';
  17. import 'package:photos/utils/navigation_util.dart';
  18. import 'package:photos/utils/toast_util.dart';
  19. enum DetailPageMode {
  20. minimalistic,
  21. full,
  22. }
  23. class DetailPageConfiguration {
  24. final List<File> files;
  25. final GalleryLoader? asyncLoader;
  26. final int selectedIndex;
  27. final String tagPrefix;
  28. final DetailPageMode mode;
  29. final bool sortOrderAsc;
  30. DetailPageConfiguration(
  31. this.files,
  32. this.asyncLoader,
  33. this.selectedIndex,
  34. this.tagPrefix, {
  35. this.mode = DetailPageMode.full,
  36. this.sortOrderAsc = false,
  37. });
  38. DetailPageConfiguration copyWith({
  39. List<File>? files,
  40. GalleryLoader? asyncLoader,
  41. int? selectedIndex,
  42. String? tagPrefix,
  43. bool? sortOrderAsc,
  44. }) {
  45. return DetailPageConfiguration(
  46. files ?? this.files,
  47. asyncLoader ?? this.asyncLoader,
  48. selectedIndex ?? this.selectedIndex,
  49. tagPrefix ?? this.tagPrefix,
  50. sortOrderAsc: sortOrderAsc ?? this.sortOrderAsc,
  51. );
  52. }
  53. }
  54. class DetailPage extends StatefulWidget {
  55. final DetailPageConfiguration config;
  56. const DetailPage(this.config, {key}) : super(key: key);
  57. @override
  58. State<DetailPage> createState() => _DetailPageState();
  59. }
  60. class _DetailPageState extends State<DetailPage> {
  61. static const kLoadLimit = 100;
  62. final _logger = Logger("DetailPageState");
  63. bool _shouldDisableScroll = false;
  64. List<File>? _files;
  65. late PageController _pageController;
  66. int _selectedIndex = 0;
  67. bool _hasPageChanged = false;
  68. bool _hasLoadedTillStart = false;
  69. bool _hasLoadedTillEnd = false;
  70. final _enableFullScreenNotifier = ValueNotifier(false);
  71. @override
  72. void initState() {
  73. super.initState();
  74. _files = [
  75. ...widget.config.files
  76. ]; // Make a copy since we append preceding and succeeding entries to this
  77. _selectedIndex = widget.config.selectedIndex;
  78. _preloadEntries();
  79. _pageController = PageController(initialPage: _selectedIndex);
  80. }
  81. @override
  82. void dispose() {
  83. _pageController.dispose();
  84. SystemChrome.setEnabledSystemUIMode(
  85. SystemUiMode.manual,
  86. overlays: SystemUiOverlay.values,
  87. );
  88. super.dispose();
  89. }
  90. @override
  91. Widget build(BuildContext context) {
  92. _logger.info(
  93. "Opening " +
  94. _files![_selectedIndex].toString() +
  95. ". " +
  96. (_selectedIndex + 1).toString() +
  97. " / " +
  98. _files!.length.toString() +
  99. " files .",
  100. );
  101. return Scaffold(
  102. appBar: FadingAppBar(
  103. _files![_selectedIndex],
  104. _onFileRemoved,
  105. Configuration.instance.getUserID(),
  106. 100,
  107. widget.config.mode == DetailPageMode.full,
  108. enableFullScreenNotifier: _enableFullScreenNotifier,
  109. ),
  110. extendBodyBehindAppBar: true,
  111. resizeToAvoidBottomInset: false,
  112. body: Center(
  113. child: Stack(
  114. children: [
  115. _buildPageView(context),
  116. FadingBottomBar(
  117. _files![_selectedIndex],
  118. _onEditFileRequested,
  119. widget.config.mode == DetailPageMode.minimalistic,
  120. onFileRemoved: _onFileRemoved,
  121. userID: Configuration.instance.getUserID(),
  122. enableFullScreenNotifier: _enableFullScreenNotifier,
  123. ),
  124. ],
  125. ),
  126. ),
  127. );
  128. }
  129. Widget _buildPageView(BuildContext context) {
  130. final bottomPadding = MediaQuery.of(context).padding.bottom;
  131. _logger.info("Building with " + _selectedIndex.toString());
  132. return PageView.builder(
  133. itemBuilder: (context, index) {
  134. final file = _files![index];
  135. final Widget content = FileWidget(
  136. file,
  137. autoPlay: !_hasPageChanged,
  138. tagPrefix: widget.config.tagPrefix,
  139. shouldDisableScroll: (value) {
  140. if (_shouldDisableScroll != value) {
  141. setState(() {
  142. _shouldDisableScroll = value;
  143. });
  144. }
  145. },
  146. //Noticed that when the video is seeked, the video pops and moves the
  147. //seek bar along with it and it happens when bottomPadding is 0. So we
  148. //don't toggle full screen for cases where this issue happens.
  149. playbackCallback: bottomPadding != 0
  150. ? (isPlaying) {
  151. Future.delayed(Duration.zero, () {
  152. _toggleFullScreen();
  153. });
  154. }
  155. : null,
  156. backgroundDecoration: const BoxDecoration(color: Colors.black),
  157. );
  158. _preloadFiles(index);
  159. return GestureDetector(
  160. onTap: () {
  161. _toggleFullScreen();
  162. },
  163. child: content,
  164. );
  165. },
  166. onPageChanged: (index) {
  167. setState(() {
  168. _selectedIndex = index;
  169. _hasPageChanged = true;
  170. });
  171. _preloadEntries();
  172. _preloadFiles(index);
  173. },
  174. physics: _shouldDisableScroll
  175. ? const NeverScrollableScrollPhysics()
  176. : const PageScrollPhysics(),
  177. controller: _pageController,
  178. itemCount: _files!.length,
  179. );
  180. }
  181. void _toggleFullScreen() {
  182. _enableFullScreenNotifier.value = !_enableFullScreenNotifier.value;
  183. Future.delayed(const Duration(milliseconds: 125), () {
  184. SystemChrome.setEnabledSystemUIMode(
  185. //to hide status bar?
  186. SystemUiMode.manual,
  187. overlays: _enableFullScreenNotifier.value ? [] : SystemUiOverlay.values,
  188. );
  189. });
  190. }
  191. Future<void> _preloadEntries() async {
  192. final isSortOrderAsc = widget.config.sortOrderAsc;
  193. if (widget.config.asyncLoader == null) return;
  194. if (_selectedIndex == 0 && !_hasLoadedTillStart) {
  195. await _loadStartEntries(isSortOrderAsc);
  196. }
  197. if (_selectedIndex == _files!.length - 1 && !_hasLoadedTillEnd) {
  198. await _loadEndEntries(isSortOrderAsc);
  199. }
  200. }
  201. Future<void> _loadStartEntries(bool isSortOrderAsc) async {
  202. final result = isSortOrderAsc
  203. ? await widget.config.asyncLoader!(
  204. galleryLoadStartTime,
  205. _files![_selectedIndex].creationTime! - 1,
  206. limit: kLoadLimit,
  207. )
  208. : await widget.config.asyncLoader!(
  209. _files![_selectedIndex].creationTime! + 1,
  210. DateTime.now().microsecondsSinceEpoch,
  211. limit: kLoadLimit,
  212. asc: true,
  213. );
  214. setState(() {
  215. // Returned result could be a subtype of File
  216. // ignore: unnecessary_cast
  217. final files = result.files.reversed.map((e) => e as File).toList();
  218. if (!result.hasMore) {
  219. _hasLoadedTillStart = true;
  220. }
  221. final length = files.length;
  222. files.addAll(_files!);
  223. _files = files;
  224. _pageController.jumpToPage(length);
  225. _selectedIndex = length;
  226. });
  227. }
  228. Future<void> _loadEndEntries(bool isSortOrderAsc) async {
  229. final result = isSortOrderAsc
  230. ? await widget.config.asyncLoader!(
  231. _files![_selectedIndex].creationTime! + 1,
  232. DateTime.now().microsecondsSinceEpoch,
  233. limit: kLoadLimit,
  234. asc: true,
  235. )
  236. : await widget.config.asyncLoader!(
  237. galleryLoadStartTime,
  238. _files![_selectedIndex].creationTime! - 1,
  239. limit: kLoadLimit,
  240. );
  241. setState(() {
  242. if (!result.hasMore) {
  243. _hasLoadedTillEnd = true;
  244. }
  245. _files!.addAll(result.files);
  246. });
  247. }
  248. void _preloadFiles(int index) {
  249. if (index > 0) {
  250. preloadFile(_files![index - 1]);
  251. }
  252. if (index < _files!.length - 1) {
  253. preloadFile(_files![index + 1]);
  254. }
  255. }
  256. Future<void> _onFileRemoved(File file) async {
  257. final totalFiles = _files!.length;
  258. if (totalFiles == 1) {
  259. // Deleted the only file
  260. Navigator.of(context).pop(); // Close pageview
  261. return;
  262. }
  263. if (_selectedIndex == totalFiles - 1) {
  264. // Deleted the last file
  265. await _pageController!.previousPage(
  266. duration: const Duration(milliseconds: 200),
  267. curve: Curves.easeInOut,
  268. );
  269. setState(() {
  270. _files!.remove(file);
  271. });
  272. } else {
  273. await _pageController!.nextPage(
  274. duration: const Duration(milliseconds: 200),
  275. curve: Curves.easeInOut,
  276. );
  277. setState(() {
  278. _selectedIndex--;
  279. _files!.remove(file);
  280. });
  281. }
  282. }
  283. Future<void> _onEditFileRequested(File file) async {
  284. if (file.uploadedFileID != null &&
  285. file.ownerID != Configuration.instance.getUserID()) {
  286. _logger.severe(
  287. "Attempt to edit unowned file",
  288. UnauthorizedEditError(),
  289. StackTrace.current,
  290. );
  291. showErrorDialog(
  292. context,
  293. S.of(context).sorry,
  294. S.of(context).weDontSupportEditingPhotosAndAlbumsThatYouDont,
  295. );
  296. return;
  297. }
  298. final dialog = createProgressDialog(context, S.of(context).pleaseWait);
  299. await dialog.show();
  300. try {
  301. final ioFile = await getFile(file);
  302. if (ioFile == null) {
  303. showShortToast(context, S.of(context).failedToFetchOriginalForEdit);
  304. await dialog.hide();
  305. return;
  306. }
  307. final imageProvider =
  308. ExtendedFileImageProvider(ioFile, cacheRawData: true);
  309. await precacheImage(imageProvider, context);
  310. await dialog.hide();
  311. replacePage(
  312. context,
  313. ImageEditorPage(
  314. imageProvider,
  315. file,
  316. widget.config.copyWith(
  317. files: _files,
  318. selectedIndex: _selectedIndex,
  319. ),
  320. ),
  321. );
  322. } catch (e) {
  323. await dialog.hide();
  324. _logger.warning("Failed to initiate edit", e);
  325. }
  326. }
  327. }