detail_page.dart 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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 _hasLoadedTillStart = false;
  68. bool _hasLoadedTillEnd = false;
  69. final _enableFullScreenNotifier = ValueNotifier(false);
  70. @override
  71. void initState() {
  72. super.initState();
  73. _files = [
  74. ...widget.config.files
  75. ]; // Make a copy since we append preceding and succeeding entries to this
  76. _selectedIndex = widget.config.selectedIndex;
  77. _preloadEntries();
  78. _pageController = PageController(initialPage: _selectedIndex);
  79. }
  80. @override
  81. void dispose() {
  82. _pageController.dispose();
  83. _enableFullScreenNotifier.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. _preloadFiles(index);
  136. return GestureDetector(
  137. onTap: () {
  138. _toggleFullScreen();
  139. },
  140. child: FileWidget(
  141. file,
  142. tagPrefix: widget.config.tagPrefix,
  143. shouldDisableScroll: (value) {
  144. if (_shouldDisableScroll != value) {
  145. setState(() {
  146. _shouldDisableScroll = value;
  147. });
  148. }
  149. },
  150. //Noticed that when the video is seeked, the video pops and moves the
  151. //seek bar along with it and it happens when bottomPadding is 0. So we
  152. //don't toggle full screen for cases where this issue happens.
  153. playbackCallback: bottomPadding != 0
  154. ? (isPlaying) {
  155. Future.delayed(Duration.zero, () {
  156. _toggleFullScreen();
  157. });
  158. }
  159. : null,
  160. backgroundDecoration: const BoxDecoration(color: Colors.black),
  161. ),
  162. );
  163. },
  164. onPageChanged: (index) {
  165. setState(() {
  166. _selectedIndex = index;
  167. });
  168. _preloadEntries();
  169. // _preloadFiles(index);
  170. },
  171. physics: _shouldDisableScroll
  172. ? const NeverScrollableScrollPhysics()
  173. : const PageScrollPhysics(),
  174. controller: _pageController,
  175. itemCount: _files!.length,
  176. );
  177. }
  178. void _toggleFullScreen() {
  179. _enableFullScreenNotifier.value = !_enableFullScreenNotifier.value;
  180. Future.delayed(const Duration(milliseconds: 125), () {
  181. SystemChrome.setEnabledSystemUIMode(
  182. //to hide status bar?
  183. SystemUiMode.manual,
  184. overlays: _enableFullScreenNotifier.value ? [] : SystemUiOverlay.values,
  185. );
  186. });
  187. }
  188. Future<void> _preloadEntries() async {
  189. final isSortOrderAsc = widget.config.sortOrderAsc;
  190. if (widget.config.asyncLoader == null) return;
  191. if (_selectedIndex == 0 && !_hasLoadedTillStart) {
  192. await _loadStartEntries(isSortOrderAsc);
  193. }
  194. if (_selectedIndex == _files!.length - 1 && !_hasLoadedTillEnd) {
  195. await _loadEndEntries(isSortOrderAsc);
  196. }
  197. }
  198. Future<void> _loadStartEntries(bool isSortOrderAsc) async {
  199. final result = isSortOrderAsc
  200. ? await widget.config.asyncLoader!(
  201. galleryLoadStartTime,
  202. _files![_selectedIndex].creationTime! - 1,
  203. limit: kLoadLimit,
  204. )
  205. : await widget.config.asyncLoader!(
  206. _files![_selectedIndex].creationTime! + 1,
  207. DateTime.now().microsecondsSinceEpoch,
  208. limit: kLoadLimit,
  209. asc: true,
  210. );
  211. setState(() {
  212. // Returned result could be a subtype of File
  213. // ignore: unnecessary_cast
  214. final files = result.files.reversed.map((e) => e as File).toList();
  215. if (!result.hasMore) {
  216. _hasLoadedTillStart = true;
  217. }
  218. final length = files.length;
  219. files.addAll(_files!);
  220. _files = files;
  221. _pageController.jumpToPage(length);
  222. _selectedIndex = length;
  223. });
  224. }
  225. Future<void> _loadEndEntries(bool isSortOrderAsc) async {
  226. final result = isSortOrderAsc
  227. ? await widget.config.asyncLoader!(
  228. _files![_selectedIndex].creationTime! + 1,
  229. DateTime.now().microsecondsSinceEpoch,
  230. limit: kLoadLimit,
  231. asc: true,
  232. )
  233. : await widget.config.asyncLoader!(
  234. galleryLoadStartTime,
  235. _files![_selectedIndex].creationTime! - 1,
  236. limit: kLoadLimit,
  237. );
  238. setState(() {
  239. if (!result.hasMore) {
  240. _hasLoadedTillEnd = true;
  241. }
  242. _files!.addAll(result.files);
  243. });
  244. }
  245. void _preloadFiles(int index) {
  246. if (index > 0) {
  247. preloadFile(_files![index - 1]);
  248. }
  249. if (index < _files!.length - 1) {
  250. preloadFile(_files![index + 1]);
  251. }
  252. }
  253. Future<void> _onFileRemoved(File file) async {
  254. final totalFiles = _files!.length;
  255. if (totalFiles == 1) {
  256. // Deleted the only file
  257. Navigator.of(context).pop(); // Close pageview
  258. return;
  259. }
  260. if (_selectedIndex == totalFiles - 1) {
  261. // Deleted the last file
  262. await _pageController!.previousPage(
  263. duration: const Duration(milliseconds: 200),
  264. curve: Curves.easeInOut,
  265. );
  266. setState(() {
  267. _files!.remove(file);
  268. });
  269. } else {
  270. await _pageController!.nextPage(
  271. duration: const Duration(milliseconds: 200),
  272. curve: Curves.easeInOut,
  273. );
  274. setState(() {
  275. _selectedIndex--;
  276. _files!.remove(file);
  277. });
  278. }
  279. }
  280. Future<void> _onEditFileRequested(File file) async {
  281. if (file.uploadedFileID != null &&
  282. file.ownerID != Configuration.instance.getUserID()) {
  283. _logger.severe(
  284. "Attempt to edit unowned file",
  285. UnauthorizedEditError(),
  286. StackTrace.current,
  287. );
  288. showErrorDialog(
  289. context,
  290. S.of(context).sorry,
  291. S.of(context).weDontSupportEditingPhotosAndAlbumsThatYouDont,
  292. );
  293. return;
  294. }
  295. final dialog = createProgressDialog(context, S.of(context).pleaseWait);
  296. await dialog.show();
  297. try {
  298. final ioFile = await getFile(file);
  299. if (ioFile == null) {
  300. showShortToast(context, S.of(context).failedToFetchOriginalForEdit);
  301. await dialog.hide();
  302. return;
  303. }
  304. final imageProvider =
  305. ExtendedFileImageProvider(ioFile, cacheRawData: true);
  306. await precacheImage(imageProvider, context);
  307. await dialog.hide();
  308. replacePage(
  309. context,
  310. ImageEditorPage(
  311. imageProvider,
  312. file,
  313. widget.config.copyWith(
  314. files: _files,
  315. selectedIndex: _selectedIndex,
  316. ),
  317. ),
  318. );
  319. } catch (e) {
  320. await dialog.hide();
  321. _logger.warning("Failed to initiate edit", e);
  322. }
  323. }
  324. }