diff options
| author | mirror <mirror@localhost> | 2026-11-22 08:41:00 +0900 |
|---|---|---|
| committer | mirror <mirror@localhost> | 2026-11-22 08:41:00 +0900 |
| commit | 449d8b74bd6d9dae98a07254cdfad677b920e7b0 (patch) | |
| tree | c131c3528c4d517f56e19b854a7453fedb097d40 /lib/widgets | |
| download | aves-src-master.tar.gz aves-src-master.zip | |
Diffstat (limited to 'lib/widgets')
458 files changed, 72001 insertions, 0 deletions
diff --git a/lib/widgets/about/about_mobile_page.dart b/lib/widgets/about/about_mobile_page.dart new file mode 100644 index 0000000..53aee33 --- /dev/null +++ b/lib/widgets/about/about_mobile_page.dart @@ -0,0 +1,53 @@ +import 'package:aves/widgets/about/app_ref.dart'; +import 'package:aves/widgets/about/bug_report.dart'; +import 'package:aves/widgets/about/credits.dart'; +import 'package:aves/widgets/about/data_usage.dart'; +import 'package:aves/widgets/about/licenses.dart'; +import 'package:aves/widgets/about/translators.dart'; +import 'package:aves/widgets/common/basic/insets.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:flutter/material.dart'; + +class AboutMobilePage extends StatelessWidget { + const AboutMobilePage({super.key}); + + @override + Widget build(BuildContext context) { + return AvesScaffold( + appBar: AppBar( + title: Text(context.l10n.aboutPageTitle), + ), + body: GestureAreaProtectorStack( + child: SafeArea( + bottom: false, + child: CustomScrollView( + slivers: [ + SliverPadding( + padding: const EdgeInsets.only(top: 16), + sliver: SliverList( + delegate: SliverChildListDelegate( + [ + const AppReference(), + const Divider(), + const BugReport(), + const Divider(), + const AboutDataUsage(), + const Divider(), + const AboutCredits(), + const Divider(), + const AboutTranslators(), + const Divider(), + ], + ), + ), + ), + const Licenses(), + const BottomPaddingSliver(), + ], + ), + ), + ), + ); + } +} diff --git a/lib/widgets/about/about_page.dart b/lib/widgets/about/about_page.dart new file mode 100644 index 0000000..10388dc --- /dev/null +++ b/lib/widgets/about/about_page.dart @@ -0,0 +1,19 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/widgets/about/about_mobile_page.dart'; +import 'package:aves/widgets/about/about_tv_page.dart'; +import 'package:flutter/material.dart'; + +class AboutPage extends StatelessWidget { + static const routeName = '/about'; + + const AboutPage({super.key}); + + @override + Widget build(BuildContext context) { + if (settings.useTvLayout) { + return const AboutTvPage(); + } else { + return const AboutMobilePage(); + } + } +} diff --git a/lib/widgets/about/about_tv_page.dart b/lib/widgets/about/about_tv_page.dart new file mode 100644 index 0000000..34b8333 --- /dev/null +++ b/lib/widgets/about/about_tv_page.dart @@ -0,0 +1,211 @@ +import 'package:aves/model/device.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/widgets/about/app_ref.dart'; +import 'package:aves/widgets/about/credits.dart'; +import 'package:aves/widgets/about/translators.dart'; +import 'package:aves/widgets/about/tv_license_page.dart'; +import 'package:aves/widgets/common/basic/insets.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/behaviour/pop/scope.dart'; +import 'package:aves/widgets/common/behaviour/pop/tv_navigation.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/buttons/outlined_button.dart'; +import 'package:aves/widgets/navigation/tv_rail.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class AboutTvPage extends StatelessWidget { + const AboutTvPage({super.key}); + + @override + Widget build(BuildContext context) { + return AvesScaffold( + body: AvesPopScope( + handlers: [tvNavigationPopHandler], + child: Row( + children: [ + TvRail( + controller: context.read<TvRailController>(), + ), + Expanded( + child: Column( + children: [ + const SizedBox(height: 8), + DirectionalSafeArea( + start: false, + bottom: false, + child: AppBar( + automaticallyImplyLeading: false, + title: Text(context.l10n.aboutPageTitle), + elevation: 0, + primary: false, + ), + ), + Expanded( + child: MediaQuery.removePadding( + context: context, + removeLeft: true, + removeTop: true, + removeRight: true, + removeBottom: true, + child: const _Content(), + ), + ), + ], + ), + ), + ], + ), + ), + ); + } +} + +class _Content extends StatefulWidget { + const _Content(); + + @override + State<_Content> createState() => _ContentState(); +} + +enum _Section { links, credits, translators, licenses } + +class _ContentState extends State<_Content> { + final FocusNode _railFocusNode = FocusNode(); + final ValueNotifier<int> _railIndexNotifier = ValueNotifier(0); + + static const double railWidth = 256; + + @override + void dispose() { + _railIndexNotifier.dispose(); + _railFocusNode.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return ValueListenableBuilder<int>( + valueListenable: _railIndexNotifier, + builder: (context, selectedIndex, child) { + final rail = Focus( + focusNode: _railFocusNode, + skipTraversal: true, + canRequestFocus: false, + child: ConstrainedBox( + constraints: BoxConstraints.loose(const Size.fromWidth(railWidth)), + child: Center( + child: ListView.builder( + itemBuilder: (context, index) { + final isSelected = index == selectedIndex; + final theme = Theme.of(context); + final colors = theme.colorScheme; + return ListTile( + title: DefaultTextStyle( + style: theme.textTheme.bodyLarge!.copyWith( + color: isSelected ? colors.primary : colors.onSurface.withValues(alpha: .64), + ), + child: _getTitle(_Section.values[index]), + ), + selected: isSelected, + contentPadding: const EdgeInsets.symmetric(vertical: 8, horizontal: 24), + onTap: () => _railIndexNotifier.value = index, + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(123)), + ), + ); + }, + itemCount: _Section.values.length, + ), + ), + ), + ); + + return Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + rail, + Expanded( + child: MediaQuery.removePadding( + context: context, + removeLeft: !context.isRtl, + removeRight: context.isRtl, + child: _getBody(_Section.values[selectedIndex]), + ), + ), + ], + ); + }, + ); + } + + Widget _getTitle(_Section key) { + switch (key) { + case _Section.links: + return Text('${context.l10n.appName} ${device.packageVersion}'); + case _Section.credits: + return Text(context.l10n.aboutCreditsSectionTitle); + case _Section.translators: + return Text(context.l10n.aboutTranslatorsSectionTitle); + case _Section.licenses: + return Text(context.l10n.aboutLicensesSectionTitle); + } + } + + Widget _getBody(_Section key) { + switch (key) { + case _Section.links: + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: AppReference.buildLinks(context) + .map((v) => Padding( + padding: const EdgeInsets.all(16), + child: v, + )) + .toList(), + ); + case _Section.credits: + return Padding( + padding: const EdgeInsets.all(16), + child: AboutCredits.buildBody(context), + ); + case _Section.translators: + return Padding( + padding: const EdgeInsets.all(16), + child: AboutTranslators.buildBody(context), + ); + case _Section.licenses: + return Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(context.l10n.aboutLicensesBanner), + const SizedBox(height: 16), + Center( + child: AvesOutlinedButton( + label: context.l10n.aboutLicensesShowAllButtonLabel, + onPressed: () => Navigator.maybeOf(context)?.push( + MaterialPageRoute( + builder: (context) { + final theme = Theme.of(context); + final listTileTheme = theme.listTileTheme; + return Theme( + data: theme.copyWith( + listTileTheme: listTileTheme.copyWith( + tileColor: Themes.firstLayerColor(context), + ), + ), + child: const TvLicensePage(), + ); + }, + ), + ), + ), + ), + ], + ), + ); + } + } +} diff --git a/lib/widgets/about/app_ref.dart b/lib/widgets/about/app_ref.dart new file mode 100644 index 0000000..d45aa94 --- /dev/null +++ b/lib/widgets/about/app_ref.dart @@ -0,0 +1,101 @@ +import 'package:aves/model/device.dart'; +import 'package:aves/ref/locales.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/about/policy_page.dart'; +import 'package:aves/widgets/common/basic/link_chip.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/aves_logo.dart'; +import 'package:flutter/material.dart'; + +class AppReference extends StatelessWidget { + static const avesGithub = 'https://github.com/deckerst/aves'; + + const AppReference({super.key}); + + @override + Widget build(BuildContext context) { + return Center( + child: Column( + children: [ + _buildAvesLine(context), + const SizedBox(height: 16), + Wrap( + alignment: WrapAlignment.center, + spacing: 16, + crossAxisAlignment: WrapCrossAlignment.center, + children: AppReference.buildLinks(context), + ), + ], + ), + ); + } + + Widget _buildAvesLine(BuildContext context) { + final locale = context.locale; + final textScaler = MediaQuery.textScalerOf(context); + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + AvesLogo( + size: textScaler.scale(_getAppTitleStyle(locale).fontSize!) * 1.3, + ), + const SizedBox(width: 8), + Text( + context.l10n.appName, + style: _getAppTitleStyle(locale), + ), + const SizedBox(width: 8), + Text( + device.packageVersion, + style: _getAppTitleStyle(locale), + ), + ], + ); + } + + TextStyle _getAppTitleStyle(String locale) => TextStyle( + fontSize: 20, + fontWeight: FontWeight.normal, + letterSpacing: canHaveLetterSpacing(locale) ? 1 : 0, + fontFeatures: const [FontFeature.enable('smcp')], + ); + + static List<Widget> buildLinks(BuildContext context) { + final l10n = context.l10n; + return [ + LinkChip( + leading: Icon( + AIcons.github, + size: 24, + ), + text: 'GitHub', + urlString: AppReference.avesGithub, + ), + LinkChip( + leading: Icon( + AIcons.legal, + size: 22, + ), + text: l10n.aboutLinkLicense, + urlString: '${AppReference.avesGithub}/blob/main/LICENSE', + ), + LinkChip( + leading: const Icon( + AIcons.privacy, + size: 22, + ), + text: l10n.aboutLinkPolicy, + onTap: () => _goToPolicyPage(context), + ), + ]; + } + + static void _goToPolicyPage(BuildContext context) { + Navigator.maybeOf(context)?.push( + MaterialPageRoute( + settings: const RouteSettings(name: PolicyPage.routeName), + builder: (context) => const PolicyPage(), + ), + ); + } +} diff --git a/lib/widgets/about/bug_report.dart b/lib/widgets/about/bug_report.dart new file mode 100644 index 0000000..694ef02 --- /dev/null +++ b/lib/widgets/about/bug_report.dart @@ -0,0 +1,220 @@ +import 'dart:convert'; +import 'dart:io'; +import 'dart:ui' as ui; + +import 'package:aves/app_flavor.dart'; +import 'package:aves/flutter_version.dart'; +import 'package:aves/model/device.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/ref/locales.dart'; +import 'package:aves/ref/mime_types.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/theme/colors.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/styles.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/widgets/about/app_ref.dart'; +import 'package:aves/widgets/aves_app.dart'; +import 'package:aves/widgets/common/action_mixins/feedback.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/fx/borders.dart'; +import 'package:aves/widgets/common/identity/aves_filter_chip.dart'; +import 'package:aves/widgets/common/identity/buttons/outlined_button.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:connectivity_plus/connectivity_plus.dart'; +import 'package:device_info_plus/device_info_plus.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:intl/intl.dart'; +import 'package:package_info_plus/package_info_plus.dart'; +import 'package:provider/provider.dart'; + +class BugReport extends StatefulWidget { + const BugReport({super.key}); + + @override + State<BugReport> createState() => _BugReportState(); +} + +class _BugReportState extends State<BugReport> { + bool _showInstructions = false; + + @override + Widget build(BuildContext context) { + final animationDuration = context.select<DurationsData, Duration>((v) => v.expansionTileAnimation); + return ExpansionPanelList( + expansionCallback: (index, isExpanded) { + setState(() => _showInstructions = isExpanded); + }, + animationDuration: animationDuration, + expandedHeaderPadding: EdgeInsets.zero, + elevation: 0, + children: [ + ExpansionPanel( + headerBuilder: (context, isExpanded) => ConstrainedBox( + constraints: const BoxConstraints(minHeight: kMinInteractiveDimension), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 16), + alignment: AlignmentDirectional.centerStart, + child: Text(context.l10n.aboutBugSectionTitle, style: AStyles.knownTitleText), + ), + ), + body: const BugReportContent(), + isExpanded: _showInstructions, + canTapOnHeader: true, + backgroundColor: Colors.transparent, + ), + ], + ); + } +} + +class BugReportContent extends StatefulWidget { + const BugReportContent({super.key}); + + @override + State<BugReportContent> createState() => _BugReportContentState(); +} + +class _BugReportContentState extends State<BugReportContent> with FeedbackMixin { + late Future<String> _infoLoader; + static const bugReportUrl = '${AppReference.avesGithub}/issues/new?labels=type%3Abug&template=bug_report.md'; + + @override + void initState() { + super.initState(); + _infoLoader = _getInfo(context); + } + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildStep(1, l10n.aboutBugSaveLogInstruction, l10n.saveTooltip, _saveLogs), + _buildStep(2, l10n.aboutBugCopyInfoInstruction, l10n.aboutBugCopyInfoButton, _copySystemInfo), + FutureBuilder<String>( + future: _infoLoader, + builder: (context, snapshot) { + final info = snapshot.data; + if (info == null) return const SizedBox(); + + return Container( + decoration: BoxDecoration( + color: Themes.secondLayerColor(context), + border: Border.all( + color: Theme.of(context).dividerColor, + width: AvesBorder.curvedBorderWidth(context), + ), + borderRadius: const BorderRadius.all(Radius.circular(16)), + ), + constraints: const BoxConstraints(maxHeight: 100), + margin: const EdgeInsets.symmetric(vertical: 8), + clipBehavior: Clip.antiAlias, + child: SingleChildScrollView( + padding: const EdgeInsets.all(8), + // to show a scroll bar, we would need to provide a scroll controller + // to both the `Scrollable` and the `Scrollbar`, but + // as of Flutter v3.0.0, `SelectableText` does not allow passing the `scrollController` + child: SelectableText( + info, + textDirection: ui.TextDirection.ltr, + style: Theme.of(context).textTheme.bodySmall, + ), + ), + ); + }, + ), + _buildStep(3, l10n.aboutBugReportInstruction, l10n.aboutBugReportButton, _goToGithub), + const SizedBox(height: 8), + ], + ), + ); + } + + Widget _buildStep(int step, String text, String buttonText, VoidCallback onPressed) { + final isMonochrome = settings.themeColorMode == AvesThemeColorMode.monochrome; + return Padding( + padding: const EdgeInsets.symmetric(vertical: 4), + child: Row( + children: [ + Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + border: Border.fromBorderSide(BorderSide( + color: isMonochrome ? context.select<AvesColorsData, Color>((v) => v.neutral) : Theme.of(context).colorScheme.primary, + width: AvesFilterChip.outlineWidth, + )), + shape: BoxShape.circle, + ), + child: Text(NumberFormat('0', context.locale).format(step)), + ), + const SizedBox(width: 8), + Expanded(child: Text(text)), + const SizedBox(width: 8), + AvesOutlinedButton( + label: buttonText, + onPressed: onPressed, + ), + ], + ), + ); + } + + Future<String> _getInfo(BuildContext context) async { + final flavor = context.read<AppFlavor>().toString().split('.')[1]; + final packageInfo = await PackageInfo.fromPlatform(); + final androidInfo = await DeviceInfoPlugin().androidInfo; + final mediaQuery = MediaQuery.of(context); + final view = View.of(context); + final supportsHdr = await windowService.supportsHdr(); + final supportsWideGamut = await windowService.supportsWideGamut(); + final connections = await Connectivity().checkConnectivity(); + final storageVolumes = await storageService.getStorageVolumes(); + final storageGrants = await storageService.getGrantedDirectories(); + return [ + 'Package: ${device.packageName}', + 'Installer: ${packageInfo.installerStore}', + 'Aves version: ${device.packageVersion}-$flavor, build ${packageInfo.buildNumber}', + 'Flutter: ${version['channel']} ${version['frameworkVersion']}', + 'Android version: ${androidInfo.version.release}, API ${androidInfo.version.sdkInt}', + 'Android build: ${androidInfo.display}', + 'Device: ${androidInfo.manufacturer} ${androidInfo.model}', + 'Display: pixel ratio=${view.devicePixelRatio}, logical=${mediaQuery.size.width}x${mediaQuery.size.height}, physical=${view.physicalSize.width}x${view.physicalSize.height}', + 'Support: dynamic colors=${device.isDynamicColorAvailable}, geocoder=${device.hasGeocoder}, HDR=$supportsHdr, wide gamut=$supportsWideGamut', + 'Mobile services: ${mobileServices.isServiceAvailable ? 'ready' : 'not available'}', + 'Connectivity: ${connections.map((v) => v.name).join(', ')}', + 'System locales: ${WidgetsBinding.instance.platformDispatcher.locales.join(', ')}', + 'Storage volumes: ${storageVolumes.map((v) => v.path).join(', ')}', + 'Storage grants: ${storageGrants.join(', ')}', + 'Error reporting: ${settings.isErrorReportingAllowed}', + ].join('\n'); + } + + Future<void> _saveLogs() async { + final result = await Process.run('logcat', ['-d']); + final logs = result.stdout; + final success = await storageService.createFile( + 'aves-logs-${DateFormat('yyyyMMdd_HHmmss', asciiLocale).format(DateTime.now())}.txt', + MimeTypes.plainText, + Uint8List.fromList(utf8.encode(logs)), + ); + if (success != null) { + if (success) { + showFeedback(context, FeedbackType.info, context.l10n.genericSuccessFeedback); + } else { + showFeedback(context, FeedbackType.warn, context.l10n.genericFailureFeedback); + } + } + } + + Future<void> _copySystemInfo() async { + await Clipboard.setData(ClipboardData(text: await _infoLoader)); + showFeedback(context, FeedbackType.info, context.l10n.genericSuccessFeedback); + } + + Future<void> _goToGithub() => AvesApp.launchUrl(bugReportUrl); +} diff --git a/lib/widgets/about/credits.dart b/lib/widgets/about/credits.dart new file mode 100644 index 0000000..1aa6e61 --- /dev/null +++ b/lib/widgets/about/credits.dart @@ -0,0 +1,44 @@ +import 'package:aves/widgets/about/title.dart'; +import 'package:aves/widgets/common/basic/link_chip.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:flutter/material.dart'; + +class AboutCredits extends StatelessWidget { + const AboutCredits({super.key}); + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + AboutSectionTitle(text: context.l10n.aboutCreditsSectionTitle), + const SizedBox(height: 8), + buildBody(context), + const SizedBox(height: 8), + ], + ), + ); + } + + static Widget buildBody(BuildContext context) { + final l10n = context.l10n; + return Text.rich( + TextSpan( + children: [ + TextSpan(text: l10n.aboutCreditsWorldAtlas1), + const WidgetSpan( + child: LinkChip( + text: 'World Atlas', + urlString: 'https://github.com/topojson/world-atlas', + textStyle: TextStyle(fontWeight: FontWeight.bold), + ), + alignment: PlaceholderAlignment.middle, + ), + TextSpan(text: l10n.aboutCreditsWorldAtlas2), + ], + ), + ); + } +} diff --git a/lib/widgets/about/data_usage.dart b/lib/widgets/about/data_usage.dart new file mode 100644 index 0000000..67d5d52 --- /dev/null +++ b/lib/widgets/about/data_usage.dart @@ -0,0 +1,179 @@ +import 'package:aves/ref/brand_colors.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/theme/colors.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/styles.dart'; +import 'package:aves/utils/file_utils.dart'; +import 'package:aves/widgets/common/action_mixins/feedback.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/aves_donut.dart'; +import 'package:aves/widgets/common/identity/buttons/outlined_button.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class AboutDataUsage extends StatefulWidget { + const AboutDataUsage({super.key}); + + @override + State<AboutDataUsage> createState() => _AboutDataUsageState(); +} + +class _AboutDataUsageState extends State<AboutDataUsage> with FeedbackMixin { + late Future<Map<String, int>> _loader; + bool _isExpanded = false; + + @override + void initState() { + super.initState(); + _reload(); + } + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + final animationDuration = context.select<DurationsData, Duration>((v) => v.expansionTileAnimation); + return ExpansionPanelList( + expansionCallback: (index, isExpanded) { + setState(() => _isExpanded = isExpanded); + }, + animationDuration: animationDuration, + expandedHeaderPadding: EdgeInsets.zero, + elevation: 0, + children: [ + ExpansionPanel( + headerBuilder: (context, isExpanded) => ConstrainedBox( + constraints: const BoxConstraints(minHeight: kMinInteractiveDimension), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 16), + alignment: AlignmentDirectional.centerStart, + child: Text(l10n.aboutDataUsageSectionTitle, style: AStyles.knownTitleText), + ), + ), + body: FutureBuilder<Map<String, int>>( + future: _loader, + builder: (context, snapshot) { + final data = snapshot.data; + if (data == null) return const SizedBox(); + + final dataMap = { + DataUsageDonut.bin: data['trash'] ?? 0, + DataUsageDonut.database: data['database'] ?? 0, + DataUsageDonut.vaults: data['vaults'] ?? 0, + DataUsageDonut.misc: data['miscData'] ?? 0, + }; + final flutter = data['flutter'] ?? 0; + if (flutter > 0) { + dataMap[DataUsageDonut.flutter] = flutter; + } + final cacheMap = { + DataUsageDonut.internal: data['internalCache'] ?? 0, + DataUsageDonut.external: data['externalCache'] ?? 0, + }; + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + DataUsageDonut( + title: l10n.aboutDataUsageData, + byTypes: dataMap, + animationDuration: animationDuration, + ), + DataUsageDonut( + title: l10n.aboutDataUsageCache, + byTypes: cacheMap, + animationDuration: animationDuration, + ), + Center( + child: AvesOutlinedButton( + label: context.l10n.aboutDataUsageClearCache, + onPressed: () async { + await storageService.deleteTempDirectory(); + await storageService.deleteExternalCache(); + await mediaFetchService.clearImageDiskCache(); + imageCache.clear(); + _reload(); + setState(() {}); + }, + ), + ), + ], + ); + }, + ), + isExpanded: _isExpanded, + canTapOnHeader: true, + backgroundColor: Colors.transparent, + ), + ], + ); + } + + void _reload() { + _loader = storageService.getDataUsage(); + } +} + +class DataUsageDonut extends StatelessWidget { + final String title; + final Map<String, int> byTypes; + final Duration animationDuration; + + // data + static const String bin = 'bin'; + static const String database = 'database'; + static const String flutter = 'flutter'; + static const String vaults = 'vaults'; + static const String misc = 'misc'; + + // cache + static const String internal = 'internal'; + static const String external = 'external'; + + const DataUsageDonut({ + super.key, + required this.title, + required this.byTypes, + required this.animationDuration, + }); + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + final locale = context.locale; + + return AvesDonut( + title: Text(title), + byTypes: byTypes, + animationDuration: animationDuration, + formatKey: (d) { + switch (d.key) { + case bin: + return l10n.binPageTitle; + case database: + return l10n.aboutDataUsageDatabase; + case flutter: + return 'Flutter'; + case vaults: + return l10n.albumTierVaults; + case misc: + return l10n.aboutDataUsageMisc; + case internal: + return l10n.aboutDataUsageInternal; + case external: + return l10n.aboutDataUsageExternal; + default: + return d.key; + } + }, + formatValue: (v) => formatFileSize(locale, v, round: 0), + colorize: (context, d) { + final colors = context.read<AvesColorsData>(); + Color? color; + switch (d.key) { + case flutter: + color = colors.fromBrandColor(BrandColors.flutter); + } + return color ?? colors.fromString(d.key); + }, + ); + } +} diff --git a/lib/widgets/about/licenses.dart b/lib/widgets/about/licenses.dart new file mode 100644 index 0000000..3661364 --- /dev/null +++ b/lib/widgets/about/licenses.dart @@ -0,0 +1,139 @@ +import 'package:aves/app_flavor.dart'; +import 'package:aves/model/app/dependencies.dart'; +import 'package:aves/ref/brand_colors.dart'; +import 'package:aves/theme/colors.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/widgets/about/title.dart'; +import 'package:aves/widgets/common/basic/link_chip.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/aves_expansion_tile.dart'; +import 'package:aves/widgets/common/identity/buttons/outlined_button.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class Licenses extends StatefulWidget { + const Licenses({super.key}); + + @override + State<Licenses> createState() => _LicensesState(); +} + +class _LicensesState extends State<Licenses> { + final ValueNotifier<String?> _expandedNotifier = ValueNotifier(null); + late List<Dependency> _platform, _flutterPlugins, _flutterPackages, _dartPackages; + + @override + void initState() { + super.initState(); + _platform = List<Dependency>.from(Dependencies.androidDependencies); + _flutterPlugins = List<Dependency>.from(Dependencies.flutterPlugins(context.read<AppFlavor>())); + _flutterPackages = List<Dependency>.from(Dependencies.flutterPackages); + _dartPackages = List<Dependency>.from(Dependencies.dartPackages); + _sortPackages(); + } + + @override + void dispose() { + _expandedNotifier.dispose(); + super.dispose(); + } + + void _sortPackages() { + int compare(Dependency a, Dependency b) => compareAsciiUpperCase(a.name, b.name); + _platform.sort(compare); + _flutterPlugins.sort(compare); + _flutterPackages.sort(compare); + _dartPackages.sort(compare); + } + + @override + Widget build(BuildContext context) { + final colors = context.watch<AvesColorsData>(); + return SliverPadding( + padding: const EdgeInsets.symmetric(horizontal: 8), + sliver: SliverList( + delegate: SliverChildListDelegate( + [ + _buildHeader(), + const SizedBox(height: 16), + AvesExpansionTile( + title: context.l10n.aboutLicensesAndroidLibrariesSectionTitle, + highlightColor: colors.fromBrandColor(BrandColors.android), + expandedNotifier: _expandedNotifier, + children: _platform.map((package) => _LicenseRow(package: package)).toList(), + ), + AvesExpansionTile( + title: context.l10n.aboutLicensesFlutterPluginsSectionTitle, + highlightColor: colors.fromBrandColor(BrandColors.flutter), + expandedNotifier: _expandedNotifier, + children: _flutterPlugins.map((package) => _LicenseRow(package: package)).toList(), + ), + AvesExpansionTile( + title: context.l10n.aboutLicensesFlutterPackagesSectionTitle, + highlightColor: colors.fromBrandColor(BrandColors.flutter), + expandedNotifier: _expandedNotifier, + children: _flutterPackages.map((package) => _LicenseRow(package: package)).toList(), + ), + AvesExpansionTile( + title: context.l10n.aboutLicensesDartPackagesSectionTitle, + highlightColor: colors.fromBrandColor(BrandColors.flutter), + expandedNotifier: _expandedNotifier, + children: _dartPackages.map((package) => _LicenseRow(package: package)).toList(), + ), + Center( + child: AvesOutlinedButton( + label: context.l10n.aboutLicensesShowAllButtonLabel, + onPressed: () => Navigator.maybeOf(context)?.push( + MaterialPageRoute( + builder: (context) => Theme( + data: Theme.of(context).copyWith( + // as of Flutter v3.22.0, `cardColor` is used as a background color by `LicensePage` + cardColor: Themes.firstLayerColor(context), + ), + child: const LicensePage(), + ), + ), + ), + ), + ), + const SizedBox(height: 16), + ], + ), + ), + ); + } + + Widget _buildHeader() { + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + AboutSectionTitle(text: context.l10n.aboutLicensesSectionTitle), + const SizedBox(height: 8), + Text(context.l10n.aboutLicensesBanner), + ], + ), + ); + } +} + +class _LicenseRow extends StatelessWidget { + final Dependency package; + + const _LicenseRow({ + required this.package, + }); + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 4, horizontal: 8), + child: LinkChip( + text: package.name, + urlString: package.sourceUrl, + ), + ); + } +} diff --git a/lib/widgets/about/policy_page.dart b/lib/widgets/about/policy_page.dart new file mode 100644 index 0000000..0621368 --- /dev/null +++ b/lib/widgets/about/policy_page.dart @@ -0,0 +1,64 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/widgets/common/basic/markdown_container.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +class PolicyPage extends StatefulWidget { + static const routeName = '/about/policy'; + + const PolicyPage({super.key}); + + @override + State<PolicyPage> createState() => _PolicyPageState(); +} + +class _PolicyPageState extends State<PolicyPage> { + late Future<String> _termsLoader; + + static const termsPath = 'assets/terms.md'; + static const termsDirection = TextDirection.ltr; + + @override + void initState() { + super.initState(); + _termsLoader = rootBundle.loadString(termsPath); + } + + @override + Widget build(BuildContext context) { + return AvesScaffold( + appBar: AppBar( + automaticallyImplyLeading: !settings.useTvLayout, + title: Text(context.l10n.policyPageTitle), + ), + body: SafeArea( + child: FocusableActionDetector( + autofocus: true, + shortcuts: const { + SingleActivator(LogicalKeyboardKey.arrowUp): ScrollIntent(direction: AxisDirection.up, type: ScrollIncrementType.page), + SingleActivator(LogicalKeyboardKey.arrowDown): ScrollIntent(direction: AxisDirection.down, type: ScrollIncrementType.page), + }, + child: Center( + child: FutureBuilder<String>( + future: _termsLoader, + builder: (context, snapshot) { + if (snapshot.hasError || snapshot.connectionState != ConnectionState.done) return const SizedBox(); + final terms = snapshot.data!; + return Padding( + padding: const EdgeInsets.symmetric(vertical: 8), + child: MarkdownContainer( + scrollController: PrimaryScrollController.of(context), + data: terms, + textDirection: termsDirection, + ), + ); + }, + ), + ), + ), + ), + ); + } +} diff --git a/lib/widgets/about/title.dart b/lib/widgets/about/title.dart new file mode 100644 index 0000000..ece76b3 --- /dev/null +++ b/lib/widgets/about/title.dart @@ -0,0 +1,37 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/styles.dart'; +import 'package:flutter/material.dart'; + +class AboutSectionTitle extends StatelessWidget { + final String text; + + const AboutSectionTitle({ + super.key, + required this.text, + }); + + @override + Widget build(BuildContext context) { + Widget child = Container( + alignment: AlignmentDirectional.centerStart, + constraints: const BoxConstraints(minHeight: kMinInteractiveDimension), + child: Text(text, style: AStyles.knownTitleText), + ); + + if (settings.useTvLayout) { + child = InkWell( + borderRadius: const BorderRadius.all(Radius.circular(123)), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + child, + ], + ), + ), + ); + } + return child; + } +} diff --git a/lib/widgets/about/translators.dart b/lib/widgets/about/translators.dart new file mode 100644 index 0000000..6f935e2 --- /dev/null +++ b/lib/widgets/about/translators.dart @@ -0,0 +1,121 @@ +import 'dart:math'; + +import 'package:aves/model/app/contributors.dart'; +import 'package:aves/theme/text.dart'; +import 'package:aves/widgets/about/title.dart'; +import 'package:aves/widgets/common/basic/text/change_highlight.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; + +class AboutTranslators extends StatelessWidget { + const AboutTranslators({super.key}); + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + AboutSectionTitle(text: context.l10n.aboutTranslatorsSectionTitle), + const SizedBox(height: 8), + buildBody(context), + const SizedBox(height: 16), + ], + ), + ); + } + + static Widget buildBody(BuildContext context) { + return _RandomTextSpanHighlighter( + spans: Contributors.translators.map((v) => v.name).toList(), + color: Theme.of(context).colorScheme.onSurface, + ); + } +} + +class _RandomTextSpanHighlighter extends StatefulWidget { + final List<String> spans; + final Color color; + + const _RandomTextSpanHighlighter({ + required this.spans, + required this.color, + }); + + @override + State<_RandomTextSpanHighlighter> createState() => _RandomTextSpanHighlighterState(); +} + +class _RandomTextSpanHighlighterState extends State<_RandomTextSpanHighlighter> with SingleTickerProviderStateMixin { + late final AnimationController _controller; + late final CurvedAnimation _animation; + late final Animation<TextStyle> _animatedStyle; + late final TextStyle _baseStyle; + int _highlightedIndex = 0; + + @override + void initState() { + super.initState(); + + final color = widget.color; + _baseStyle = TextStyle( + color: color.withValues(alpha: .7), + shadows: [ + Shadow( + color: color.withValues(alpha: 0), + blurRadius: 0, + ) + ], + ); + final highlightStyle = TextStyle( + color: color.withValues(alpha: 1), + shadows: [ + Shadow( + color: color.withValues(alpha: 1), + blurRadius: 3, + ) + ], + ); + + _controller = AnimationController( + duration: const Duration(seconds: 1), + vsync: this, + ) + ..addListener(() => setState(() {})) + ..addStatusListener((status) { + if (status == AnimationStatus.forward) { + _highlightedIndex = Random().nextInt(widget.spans.length); + } + }) + ..repeat(reverse: true); + _animation = CurvedAnimation( + parent: _controller, + curve: Curves.easeInOutCubic, + ); + _animatedStyle = ShadowedTextStyleTween(begin: _baseStyle, end: highlightStyle).animate(_animation); + } + + @override + void dispose() { + _animation.dispose(); + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Text.rich( + TextSpan( + children: [ + ...widget.spans.expandIndexed((i, v) => [ + if (i != 0) const TextSpan(text: AText.separator), + TextSpan(text: '${Unicode.FSI}$v${Unicode.PDI}', style: i == _highlightedIndex ? _animatedStyle.value : _baseStyle), + ]) + ], + ), + ); + } +} diff --git a/lib/widgets/about/tv_license_page.dart b/lib/widgets/about/tv_license_page.dart new file mode 100644 index 0000000..7efb673 --- /dev/null +++ b/lib/widgets/about/tv_license_page.dart @@ -0,0 +1,396 @@ +import 'dart:developer' show Flow, Timeline; + +import 'package:aves/theme/themes.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/behaviour/intents.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart' hide Flow; +import 'package:flutter/scheduler.dart'; +import 'package:flutter/services.dart'; + +// as of Flutter v3.7.7, `LicensePage` is not designed for Android TV +// and gets rejected from Google Play review: +// ``` +// Your app’s text is cut off at the edge of the screen. +// Apps should not display any text or functionality that is partially cut off by the edges of the screen. +// For example, your app (version code 94) in the "Show All Licenses" section text is cut off from the bottom of the screen. +// ``` +class TvLicensePage extends StatefulWidget { + const TvLicensePage({super.key}); + + @override + State<TvLicensePage> createState() => _TvLicensePageState(); +} + +class _TvLicensePageState extends State<TvLicensePage> { + final FocusNode _railFocusNode = FocusNode(); + final ScrollController _detailsScrollController = ScrollController(); + final ValueNotifier<int> _railIndexNotifier = ValueNotifier(0); + + static const double railWidth = 256; + + final Future<_LicenseData> licenses = LicenseRegistry.licenses + .fold<_LicenseData>( + _LicenseData(), + (prev, license) => prev..addLicense(license), + ) + .then((licenseData) => licenseData..sortPackages()); + + @override + void dispose() { + _railIndexNotifier.dispose(); + _railFocusNode.dispose(); + _detailsScrollController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return AvesScaffold( + appBar: AppBar( + automaticallyImplyLeading: false, + title: Text(MaterialLocalizations.of(context).licensesPageTitle), + ), + body: ValueListenableBuilder<int>( + valueListenable: _railIndexNotifier, + builder: (context, selectedIndex, child) { + return FutureBuilder<_LicenseData>( + future: licenses, + builder: (context, snapshot) { + final data = snapshot.data; + if (data == null) { + return const Center( + child: CircularProgressIndicator(), + ); + } + + final packages = data.packages; + final rail = Focus( + focusNode: _railFocusNode, + skipTraversal: true, + canRequestFocus: false, + child: ConstrainedBox( + constraints: BoxConstraints.loose(const Size.fromWidth(railWidth)), + child: ListView.builder( + itemBuilder: (context, index) { + final packageName = packages[index]; + final bindings = data.packageLicenseBindings[packageName]!; + final isSelected = index == selectedIndex; + final theme = Theme.of(context); + return Ink( + color: isSelected ? theme.highlightColor : Themes.firstLayerColor(context), + child: ListTile( + title: Text(packageName), + subtitle: Text(MaterialLocalizations.of(context).licensesPackageDetailText(bindings.length)), + selected: isSelected, + onTap: () => _railIndexNotifier.value = index, + ), + ); + }, + itemCount: packages.length, + ), + ), + ); + + final packageName = packages[selectedIndex]; + final bindings = data.packageLicenseBindings[packageName]!; + + return SafeArea( + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const SizedBox(width: 16), + rail, + Expanded( + child: FocusableActionDetector( + shortcuts: const { + SingleActivator(LogicalKeyboardKey.arrowUp): ScrollIntent(direction: AxisDirection.up, type: ScrollIncrementType.page), + SingleActivator(LogicalKeyboardKey.arrowDown): ScrollIntent(direction: AxisDirection.down, type: ScrollIncrementType.page), + }, + actions: { + ScrollIntent: ScrollControllerAction(scrollController: _detailsScrollController), + }, + child: KeyedSubtree( + key: Key(packageName), + child: _PackageLicensePage( + packageName: packageName, + licenseEntries: bindings.map((i) => data.licenses[i]).toList(growable: false), + scrollController: _detailsScrollController, + ), + ), + ), + ), + ], + ), + ); + }, + ); + }, + ), + ); + } +} + +// adapted from Flutter `_LicenseData` in `/material/about.dart` +class _LicenseData { + final List<LicenseEntry> licenses = <LicenseEntry>[]; + final Map<String, List<int>> packageLicenseBindings = <String, List<int>>{}; + final List<String> packages = <String>[]; + + // Special treatment for the first package since it should be the package + // for delivered application. + String? firstPackage; + + void addLicense(LicenseEntry entry) { + // Before the license can be added, we must first record the packages to + // which it belongs. + for (final String package in entry.packages) { + _addPackage(package); + // Bind this license to the package using the next index value. This + // creates a contract that this license must be inserted at this same + // index value. + packageLicenseBindings[package]!.add(licenses.length); + } + licenses.add(entry); // Completion of the contract above. + } + + /// Add a package and initialize package license binding. This is a no-op if + /// the package has been seen before. + void _addPackage(String package) { + if (!packageLicenseBindings.containsKey(package)) { + packageLicenseBindings[package] = <int>[]; + firstPackage ??= package; + packages.add(package); + } + } + + /// Sort the packages using some comparison method, or by the default manner, + /// which is to put the application package first, followed by every other + /// package in case-insensitive alphabetical order. + void sortPackages([int Function(String a, String b)? compare]) { + packages.sort(compare ?? + (a, b) { + // Based on how LicenseRegistry currently behaves, the first package + // returned is the end user application license. This should be + // presented first in the list. So here we make sure that first package + // remains at the front regardless of alphabetical sorting. + if (a == firstPackage) { + return -1; + } + if (b == firstPackage) { + return 1; + } + return a.toLowerCase().compareTo(b.toLowerCase()); + }); + } +} + +// adapted from Flutter `_PackageLicensePage` in `/material/about.dart` +class _PackageLicensePage extends StatefulWidget { + const _PackageLicensePage({ + required this.packageName, + required this.licenseEntries, + required this.scrollController, + }); + + final String packageName; + final List<LicenseEntry> licenseEntries; + final ScrollController? scrollController; + + @override + _PackageLicensePageState createState() => _PackageLicensePageState(); +} + +class _PackageLicensePageState extends State<_PackageLicensePage> { + @override + void initState() { + super.initState(); + _initLicenses(); + } + + final List<Widget> _licenses = <Widget>[]; + bool _loaded = false; + + Future<void> _initLicenses() async { + int debugFlowId = -1; + assert(() { + final Flow flow = Flow.begin(); + Timeline.timeSync('_initLicenses()', () {}, flow: flow); + debugFlowId = flow.id; + return true; + }()); + for (final LicenseEntry license in widget.licenseEntries) { + if (!mounted) return; + assert(() { + Timeline.timeSync('_initLicenses()', () {}, flow: Flow.step(debugFlowId)); + return true; + }()); + final List<LicenseParagraph> paragraphs = await SchedulerBinding.instance.scheduleTask<List<LicenseParagraph>>( + license.paragraphs.toList, + Priority.animation, + debugLabel: 'License', + ); + if (!mounted) return; + setState(() { + _licenses.add(const Padding( + padding: EdgeInsets.all(18), + child: Divider(), + )); + for (final LicenseParagraph paragraph in paragraphs) { + if (paragraph.indent == LicenseParagraph.centeredIndent) { + _licenses.add(Padding( + padding: const EdgeInsets.only(top: 16), + child: Text( + paragraph.text, + style: const TextStyle(fontWeight: FontWeight.bold), + textAlign: TextAlign.center, + ), + )); + } else { + assert(paragraph.indent >= 0); + _licenses.add(Padding( + padding: EdgeInsetsDirectional.only(top: 8, start: 16.0 * paragraph.indent), + child: Text(paragraph.text), + )); + } + } + }); + } + setState(() { + _loaded = true; + }); + assert(() { + Timeline.timeSync('Build scheduled', () {}, flow: Flow.end(debugFlowId)); + return true; + }()); + } + + @override + Widget build(BuildContext context) { + assert(debugCheckHasMaterialLocalizations(context)); + final MaterialLocalizations localizations = MaterialLocalizations.of(context); + final ThemeData theme = Theme.of(context); + final String title = widget.packageName; + final String subtitle = localizations.licensesPackageDetailText(widget.licenseEntries.length); + final double pad = _getGutterSize(context); + final EdgeInsets padding = EdgeInsets.only(left: pad, right: pad, bottom: pad); + final List<Widget> listWidgets = <Widget>[ + ..._licenses, + if (!_loaded) + const Padding( + padding: EdgeInsets.symmetric(vertical: 24), + child: Center( + child: CircularProgressIndicator(), + ), + ), + ]; + + final Widget page; + if (widget.scrollController == null) { + page = Scaffold( + appBar: AppBar( + title: _PackageLicensePageTitle( + title: title, + subtitle: subtitle, + theme: theme.useMaterial3 ? theme.textTheme : theme.primaryTextTheme, + titleTextStyle: theme.appBarTheme.titleTextStyle, + foregroundColor: theme.appBarTheme.foregroundColor, + ), + ), + body: Center( + child: Material( + color: Themes.firstLayerColor(context), + elevation: 4.0, + child: Container( + constraints: BoxConstraints.loose(const Size.fromWidth(600.0)), + child: Localizations.override( + locale: const Locale('en', 'US'), + context: context, + child: ScrollConfiguration( + // A Scrollbar is built-in below. + behavior: ScrollConfiguration.of(context).copyWith(scrollbars: false), + child: Scrollbar( + child: ListView( + primary: true, + padding: padding, + children: listWidgets, + ), + ), + ), + ), + ), + ), + ), + ); + } else { + page = CustomScrollView( + controller: widget.scrollController, + slivers: <Widget>[ + SliverAppBar( + automaticallyImplyLeading: false, + pinned: true, + backgroundColor: Themes.firstLayerColor(context), + title: _PackageLicensePageTitle( + title: title, + subtitle: subtitle, + theme: theme.textTheme, + titleTextStyle: theme.textTheme.titleLarge, + ), + ), + SliverPadding( + padding: padding, + sliver: SliverList( + delegate: SliverChildBuilderDelegate( + (context, index) => Localizations.override( + locale: const Locale('en', 'US'), + context: context, + child: listWidgets[index], + ), + childCount: listWidgets.length, + ), + ), + ), + ], + ); + } + return DefaultTextStyle( + style: theme.textTheme.bodySmall!, + child: page, + ); + } +} + +class _PackageLicensePageTitle extends StatelessWidget { + const _PackageLicensePageTitle({ + required this.title, + required this.subtitle, + required this.theme, + this.titleTextStyle, + this.foregroundColor, + }); + + final String title; + final String subtitle; + final TextTheme theme; + final TextStyle? titleTextStyle; + final Color? foregroundColor; + + @override + Widget build(BuildContext context) { + final TextStyle? effectiveTitleTextStyle = titleTextStyle ?? theme.titleLarge; + return Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.start, + children: <Widget>[ + Text(title, style: effectiveTitleTextStyle?.copyWith(color: foregroundColor)), + Text(subtitle, style: theme.titleSmall?.copyWith(color: foregroundColor)), + ], + ); + } +} + +const int _materialGutterThreshold = 720; +const double _wideGutterSize = 24.0; +const double _narrowGutterSize = 12.0; + +double _getGutterSize(BuildContext context) => MediaQuery.sizeOf(context).width >= _materialGutterThreshold ? _wideGutterSize : _narrowGutterSize; diff --git a/lib/widgets/aves_app.dart b/lib/widgets/aves_app.dart new file mode 100644 index 0000000..2f4f64b --- /dev/null +++ b/lib/widgets/aves_app.dart @@ -0,0 +1,747 @@ +import 'dart:async'; +import 'dart:math'; + +import 'package:aves/app_flavor.dart'; +import 'package:aves/app_mode.dart'; +import 'package:aves/geo/uri.dart'; +import 'package:aves/l10n/l10n.dart'; +import 'package:aves/model/app/intent.dart'; +import 'package:aves/model/app_inventory.dart'; +import 'package:aves/model/device.dart'; +import 'package:aves/model/filters/recent.dart'; +import 'package:aves/model/settings/defaults.dart'; +import 'package:aves/model/settings/enums/display_refresh_rate_mode.dart'; +import 'package:aves/model/settings/enums/screen_on.dart'; +import 'package:aves/model/settings/enums/theme_brightness.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/model/source/media_store_source.dart'; +import 'package:aves/ref/locales.dart'; +import 'package:aves/services/accessibility_service.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/theme/colors.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/theme/styles.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/widgets/collection/collection_grid.dart'; +import 'package:aves/widgets/collection/collection_page.dart'; +import 'package:aves/widgets/common/basic/derived_material_localization.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/behaviour/pop/scope.dart'; +import 'package:aves/widgets/common/behaviour/route_tracker.dart'; +import 'package:aves/widgets/common/behaviour/routes.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/providers/durations_provider.dart'; +import 'package:aves/widgets/common/providers/highlight_info_provider.dart'; +import 'package:aves/widgets/common/providers/media_query_data_provider.dart'; +import 'package:aves/widgets/common/providers/viewer_entry_provider.dart'; +import 'package:aves/widgets/dialogs/entry_editors/edit_location_dialog.dart'; +import 'package:aves/widgets/home/home_page.dart'; +import 'package:aves/widgets/navigation/tv_page_transitions.dart'; +import 'package:aves/widgets/navigation/tv_rail.dart'; +import 'package:aves/widgets/welcome_page.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:aves_utils/aves_utils.dart'; +import 'package:collection/collection.dart'; +import 'package:dynamic_color/dynamic_color.dart'; +import 'package:equatable/equatable.dart'; +import 'package:event_bus/event_bus.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_localizations_plus/flutter_localizations_plus.dart'; +import 'package:intl/intl.dart'; +import 'package:latlong2/latlong.dart'; +import 'package:overlay_support/overlay_support.dart'; +import 'package:provider/provider.dart'; +import 'package:screen_brightness/screen_brightness.dart'; +import 'package:url_launcher/url_launcher.dart' as ul; + +class AvesApp extends StatefulWidget { + final AppFlavor flavor; + final Map? debugIntentData; + + // temporary exclude locales not ready yet for prime time + // `ckb`: add `flutter_ckb_localization` and necessary app localization delegates when ready + static final _unsupportedLocales = { + 'az', // Azerbaijani + 'bn', // Bengali + 'ckb', // Kurdish (Central) + 'he', // Hebrew + 'hi', // Hindi + 'kmr', // Kurdish (Northern) + 'ml', // Malayalam + 'my', // Burmese + 'ne', // Nepali + 'or', // Odia + 'sat', // Santali + 'sl', // Slovenian + 'sr', // Serbian + 'th', // Thai + 'ur', // Urdu + }.map(Locale.new).toSet(); + static final List<Locale> supportedLocales = AppLocalizations.supportedLocales.where((v) => !_unsupportedLocales.contains(v)).toList(); + static final ValueNotifier<bool> canGestureToOtherApps = ValueNotifier(false); + static final ValueNotifier<EdgeInsets> cutoutInsetsNotifier = ValueNotifier(EdgeInsets.zero); + + // children widgets registering as `WidgetsBinding` observers and implementing `didChangeAppLifecycleState` + // do not receive events fast enough for time sensitive actions (like PiP when leaving by gesture to home) + // so we use this notifier to propagate events as soon as received by the top widget `AvesApp` + static final ValueNotifier<AppLifecycleState> lifecycleStateNotifier = ValueNotifier(AppLifecycleState.detached); + + // do not monitor all `ModalRoute`s, which would include popup menus, + // so that we can react to fullscreen `PageRoute`s only + static final RouteObserver<PageRoute> pageRouteObserver = RouteObserver<PageRoute>(); + + static ScreenBrightness? get screenBrightness => _AvesAppState._screenBrightness; + + static EventBus get intentEventBus => _AvesAppState._intentEventBus; + + const AvesApp({ + super.key, + required this.flavor, + this.debugIntentData, + }); + + @override + State<AvesApp> createState() => _AvesAppState(); + + static void setSystemUIStyle(ThemeData theme) { + final style = systemUIStyleForBrightness(theme.brightness, theme.colorScheme.surfaceContainer); + SystemChrome.setSystemUIOverlayStyle(style); + } + + static SystemUiOverlayStyle systemUIStyleForBrightness(Brightness themeBrightness, Color backgroundColor) { + final barBrightness = themeBrightness == Brightness.dark ? Brightness.light : Brightness.dark; + const statusBarColor = Colors.transparent; + // as of Flutter v3.3.0-0.2.pre, setting `SystemUiOverlayStyle` (whether manually or automatically because of `AppBar`) + // prevents the canvas from drawing behind the nav bar on Android <10 (API <29), + // so the nav bar is opaque, even when requesting `SystemUiMode.edgeToEdge` from Flutter + // or setting `android:windowTranslucentNavigation` in Android themes. + final navBarColor = device.supportEdgeToEdgeUIMode ? Colors.transparent : backgroundColor; + return SystemUiOverlayStyle( + systemNavigationBarColor: navBarColor, + systemNavigationBarDividerColor: navBarColor, + systemNavigationBarIconBrightness: barBrightness, + // shows background scrim when using navigation buttons, but not when using gesture navigation + systemNavigationBarContrastEnforced: true, + statusBarColor: statusBarColor, + statusBarBrightness: barBrightness, + statusBarIconBrightness: barBrightness, + systemStatusBarContrastEnforced: false, + ); + } + + static Future<void> showSystemUI() async { + if (device.supportEdgeToEdgeUIMode) { + await SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge); + } else { + await SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: SystemUiOverlay.values); + } + } + + static Future<void> hideSystemUI() async { + await SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersive); + } + + static Future<void> launchUrl(String? urlString) async { + if (urlString != null) { + final url = Uri.parse(urlString); + if (await ul.canLaunchUrl(url)) { + // address `TV-WB` requirement from https://developer.android.com/docs/quality-guidelines/tv-app-quality + final mode = device.isTelevision ? ul.LaunchMode.inAppWebView : ul.LaunchMode.externalApplication; + try { + await ul.launchUrl(url, mode: mode); + } catch (error, stack) { + debugPrint('failed to open url=$urlString with error=$error\n$stack'); + } + } + } + } +} + +class _AvesAppState extends State<AvesApp> with WidgetsBindingObserver { + final Set<StreamSubscription> _subscriptions = {}; + late final Future<void> _appSetup; + late final Future<bool> _shouldUseBoldFontLoader; + final TvRailController _tvRailController = TvRailController(); + final MediaStoreSource _mediaStoreSource = MediaStoreSource(); + Size? _screenSize; + + final ValueNotifier<PageTransitionsBuilder> _pageTransitionsBuilderNotifier = ValueNotifier(_defaultPageTransitionsBuilder); + final ValueNotifier<TvMediaQueryModifier?> _tvMediaQueryModifierNotifier = ValueNotifier(null); + final ValueNotifier<AppMode> _appModeNotifier = ValueNotifier(AppMode.initialization); + + // observers are not registered when using the same list object with different items + // the list itself needs to be reassigned + List<NavigatorObserver> _navigatorObservers = [AvesApp.pageRouteObserver]; + final EventChannel _mediaStoreChangeChannel = const OptionalEventChannel('deckers.thibault/aves/media_store_change'); + final EventChannel _newIntentChannel = const OptionalEventChannel('deckers.thibault/aves/new_intent_stream'); + final EventChannel _analysisCompletionChannel = const OptionalEventChannel('deckers.thibault/aves/analysis_events'); + final EventChannel _errorChannel = const OptionalEventChannel('deckers.thibault/aves/error'); + final EventChannel _platformWindowChangeChannel = const OptionalEventChannel('deckers.thibault/aves/window_change'); + + // Flutter has various page transition implementations for Android: + // - `FadeUpwardsPageTransitionsBuilder` on Oreo / Android 8 / API 27 and below + // - `OpenUpwardsPageTransitionsBuilder` on Pie / Android 9 / API 28 + // - `ZoomPageTransitionsBuilder` on Q / Android 10 / API 29 (default in Flutter v3.22.0) + // - `FadeForwardsPageTransitionsBuilder` on U / Android 14 / API 34 + // - `PredictiveBackPageTransitionsBuilder` for Android 15 / API 35 intra-app predictive back (default to `ZoomPageTransitionsBuilder`) + static const _defaultPageTransitionsBuilder = FadeUpwardsPageTransitionsBuilder(); + static final GlobalKey<NavigatorState> _navigatorKey = GlobalKey(debugLabel: 'app-navigator'); + static ScreenBrightness? _screenBrightness; + static bool _exitedMainByPop = false; + static final EventBus _intentEventBus = EventBus(); + + @override + void initState() { + super.initState(); + EquatableConfig.stringify = true; + _appSetup = _setup(); + _shouldUseBoldFontLoader = AccessibilityService.shouldUseBoldFont(); + _subscriptions.add(_mediaStoreChangeChannel.receiveBroadcastStream().listen((event) => _mediaStoreSource.onStoreChanged(event as String?))); + _subscriptions.add(_newIntentChannel.receiveBroadcastStream().listen((event) => _onNewIntent(event as Map?))); + _subscriptions.add(_analysisCompletionChannel.receiveBroadcastStream().listen((event) => _onAnalysisCompletion())); + _subscriptions.add(_errorChannel.receiveBroadcastStream().listen((event) => _onError(event as String?))); + _subscriptions.add(_platformWindowChangeChannel.receiveBroadcastStream().listen((event) => _updateWindowMode())); + _updateCutoutInsets(); + _updateWindowMode(); + _appModeNotifier.addListener(_onAppModeChanged); + + debugPrint('start listening to app lifecycle'); + WidgetsBinding.instance.addObserver(this); + AvesApp.lifecycleStateNotifier.value = WidgetsBinding.instance.lifecycleState ?? AppLifecycleState.detached; + } + + @override + void dispose() { + _subscriptions + ..forEach((sub) => sub.cancel()) + ..clear(); + + debugPrint('stop listening to app lifecycle'); + WidgetsBinding.instance.removeObserver(this); + + _pageTransitionsBuilderNotifier.dispose(); + _tvMediaQueryModifierNotifier.dispose(); + _appModeNotifier.dispose(); + _mediaStoreSource.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + // remember screen size to use it later, when `context` and `window` are no longer reliable + _screenSize ??= _getScreenSize(context); + + // place the settings provider above `MaterialApp` + // so it can be used during navigation transitions + return MultiProvider( + providers: [ + Provider<AppFlavor>.value(value: widget.flavor), + ChangeNotifierProvider<Settings>.value(value: settings), + ListenableProvider<ValueNotifier<AppMode>>.value(value: _appModeNotifier), + Provider<CollectionSource>.value(value: _mediaStoreSource), + Provider<TvRailController>.value(value: _tvRailController), + DurationsProvider(), + HighlightInfoProvider(), + ViewerEntryProvider(), + ], + child: NotificationListener<PopExitNotification>( + onNotification: (notification) { + if (_appModeNotifier.value == AppMode.main) { + _exitedMainByPop = true; + } + return true; + }, + child: OverlaySupport( + child: FutureBuilder<void>( + future: _appSetup, + builder: (context, snapshot) { + final initialized = !snapshot.hasError && snapshot.connectionState == ConnectionState.done; + if (initialized) { + AvesApp.showSystemUI(); + } + final home = initialized + ? _getFirstPage(intentData: widget.debugIntentData) + : AvesScaffold( + body: snapshot.hasError ? _buildError(snapshot.error!) : const SizedBox(), + ); + return Selector<Settings, (Locale?, AvesThemeBrightness, bool)>( + selector: (context, s) => ( + s.locale, + s.initialized ? s.themeBrightness : SettingsDefaults.themeBrightness, + s.initialized ? s.enableDynamicColor : SettingsDefaults.enableDynamicColor, + ), + builder: (context, s, child) { + final (settingsLocale, themeBrightness, enableDynamicColor) = s; + return DynamicColorBuilder( + builder: (lightScheme, darkScheme) { + const defaultAccent = AvesColorsData.defaultAccent; + Color lightAccent = defaultAccent, darkAccent = defaultAccent; + if (enableDynamicColor) { + lightAccent = lightScheme?.primary ?? lightAccent; + darkAccent = darkScheme?.primary ?? darkAccent; + } + final lightTheme = Themes.lightTheme(lightAccent, initialized); + final darkTheme = themeBrightness == AvesThemeBrightness.black ? Themes.blackTheme(darkAccent, initialized) : Themes.darkTheme(darkAccent, initialized); + return Shortcuts( + shortcuts: { + // handle Android TV remote `select` button (KEYCODE_DPAD_CENTER) + // the following keys are already handled by default: + // KEYCODE_ENTER, KEYCODE_BUTTON_A, KEYCODE_NUMPAD_ENTER + LogicalKeySet(LogicalKeyboardKey.select): const ActivateIntent(), + }, + child: Builder( + builder: (context) { + return MediaQuery( + data: MediaQuery.of(context).copyWith( + // disable accessible navigation, as it impacts snack bar action timer + // for all users of apps registered as accessibility services, + // even though they are not for accessibility purposes (like TalkBack is) + accessibleNavigation: false, + ), + child: MaterialApp( + navigatorKey: _navigatorKey, + home: home, + navigatorObservers: _navigatorObservers, + builder: (context, child) => _decorateAppChild( + context: context, + initialized: initialized, + child: child, + ), + onGenerateTitle: (context) => context.l10n.appName, + theme: lightTheme, + darkTheme: darkTheme, + themeMode: themeBrightness.appThemeMode, + locale: settingsLocale, + localizationsDelegates: const [ + // order matters for resolution of sublocales (e.g. `en_Shaw` before `en`) + ...LocalizationsEnShaw.delegates, + ...LocalizationsNn.delegates, + ...AppLocalizations.localizationsDelegates, + ], + supportedLocales: AvesApp.supportedLocales, + scrollBehavior: AvesScrollBehavior(), + ), + ); + }, + ), + ); + }, + ); + }, + ); + }, + ), + ), + ), + ); + } + + Widget _decorateAppChild({ + required BuildContext context, + required bool initialized, + required Widget? child, + }) { + if (initialized) { + WidgetsBinding.instance.addPostFrameCallback((_) => AvesApp.setSystemUIStyle(Theme.of(context))); + } + return Selector<Settings, bool>( + selector: (context, s) => s.initialized ? s.animate : true, + builder: (context, areAnimationsEnabled, child) { + return MaterialLocalizationsRegionalizer( + child: FutureBuilder<bool>( + future: _shouldUseBoldFontLoader, + builder: (context, snapshot) { + // Flutter v3.4 already checks the system `Configuration.fontWeightAdjustment` to update `MediaQuery` + // but we need to also check the non-standard Samsung field `bf` representing the bold font toggle + final shouldUseBoldFont = snapshot.data ?? false; + final mq = MediaQuery.of(context).copyWith( + boldText: shouldUseBoldFont, + ); + return ValueListenableBuilder<TvMediaQueryModifier?>( + valueListenable: _tvMediaQueryModifierNotifier, + builder: (context, modifier, child) { + return MediaQuery( + data: modifier?.call(mq) ?? mq, + child: AvesColorsProvider( + child: ValueListenableBuilder<PageTransitionsBuilder>( + valueListenable: _pageTransitionsBuilderNotifier, + builder: (context, pageTransitionsBuilder, child) { + final theme = Theme.of(context); + return Theme( + data: theme.copyWith( + pageTransitionsTheme: areAnimationsEnabled + ? PageTransitionsTheme(builders: {TargetPlatform.android: pageTransitionsBuilder}) + // strip page transitions used by `MaterialPageRoute` + : const DirectPageTransitionsTheme(), + splashFactory: areAnimationsEnabled ? theme.splashFactory : NoSplash.splashFactory, + ), + child: MediaQueryDataProvider(child: child!), + ); + }, + child: child, + ), + ), + ); + }, + child: child, + ); + }, + ), + ); + }, + child: child, + ); + } + + Widget _buildError(Object error) { + return Container( + alignment: Alignment.center, + padding: const EdgeInsets.all(16), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const Icon(AIcons.error), + const SizedBox(height: 16), + Text(error.toString()), + ], + ), + ); + } + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + reportService.log('Lifecycle ${state.name}'); + AvesApp.lifecycleStateNotifier.value = state; + switch (state) { + case AppLifecycleState.inactive: + switch (_appModeNotifier.value) { + case AppMode.main: + case AppMode.pickSingleMediaExternal: + case AppMode.pickMultipleMediaExternal: + _saveTopEntries(); + default: + break; + } + case AppLifecycleState.resumed: + availability.onResume(); + RecentlyAddedFilter.updateNow(); + _mediaStoreSource.checkForChanges(); + default: + break; + } + } + + @override + void didChangeMetrics() => _updateCutoutInsets(); + + @override + void didChangeLocales(List<Locale>? locales) => _applyLocale(); + + Future<void> _updateCutoutInsets() async { + if (await windowService.isCutoutAware()) { + AvesApp.cutoutInsetsNotifier.value = await windowService.getCutoutInsets(); + } + } + + Future<void> _updateWindowMode() async { + AvesApp.canGestureToOtherApps.value = await windowService.isInMultiWindowMode() && !(await windowService.isInPictureInPictureMode()); + } + + void _applyLocale() { + settings.resetAppliedLocale(); + + final appliedLocale = settings.appliedLocale; + AStyles.updateStylesForLocale(appliedLocale); + + Locale? countrifiedLocale; + if (appliedLocale.countryCode == null) { + final languageCode = appliedLocale.languageCode; + countrifiedLocale = WidgetsBinding.instance.platformDispatcher.locales.firstWhereOrNull((v) => v.languageCode == languageCode); + } + + final useNativeDigits = !settings.forceWesternArabicNumerals && shouldUseNativeDigits(countrifiedLocale); + DateFormat.useNativeDigitsByDefaultFor(appliedLocale.toString(), useNativeDigits); + DateFormat.useNativeDigitsByDefaultFor(countrifiedLocale.toString(), useNativeDigits); + } + + Widget _getFirstPage({Map? intentData}) => settings.hasAcceptedTerms ? HomePage(intentData: intentData) : const WelcomePage(); + + Size? _getScreenSize(BuildContext context) { + final view = View.of(context); + final physicalSize = view.physicalSize; + final ratio = view.devicePixelRatio; + return physicalSize > Size.zero && ratio > 0 ? physicalSize / ratio : null; + } + + // save IDs of entries visible at the top of the collection page with current layout settings + void _saveTopEntries() { + if (!settings.initialized) return; + + final screenSize = _screenSize; + if (screenSize == null) return; + + var tileExtent = settings.getTileExtent(CollectionPage.routeName); + if (tileExtent == 0) { + tileExtent = screenSize.shortestSide / CollectionGrid.columnCountDefault; + } + final rows = (screenSize.height / tileExtent).ceil(); + final columns = (screenSize.width / tileExtent).ceil(); + final count = rows * columns; + final collection = CollectionLens(source: _mediaStoreSource, listenToSource: false); + settings.topEntryIds = collection.sortedEntries.take(count).map((entry) => entry.id).toList(); + collection.dispose(); + } + + // setup before the first page is displayed. keep it short + Future<void> _setup() async { + final stopwatch = Stopwatch()..start(); + + await device.init(); + await mobileServices.init(); + await settings.init(monitorPlatformSettings: true); + settings.isRotationLocked = await windowService.isRotationLocked(); + settings.longPressTimeoutMillis = await AccessibilityService.getLongPressTimeout(); + settings.areAnimationsRemoved = await AccessibilityService.areAnimationsRemoved(); + await _onTvLayoutChanged(); + _monitorSettings(); + videoControllerFactory.init(); + videoMetadataFetcher.init(); + + unawaited(deviceService.setLocaleConfig(AvesApp.supportedLocales)); + unawaited(storageService.deleteTempDirectory()); + unawaited(_setupErrorReporting()); + + debugPrint('App setup in ${stopwatch.elapsed.inMilliseconds}ms'); + } + + Future<void> _onTvLayoutChanged() async { + if (settings.useTvLayout) { + settings.applyTvSettings(); + + _pageTransitionsBuilderNotifier.value = const TvPageTransitionsBuilder(); + _tvMediaQueryModifierNotifier.value = (mq) { + // cf https://developer.android.com/training/tv/start/layouts.html#overscan + final screenSize = mq.size; + const overscanFactor = .05; + final overscanInsets = EdgeInsets.symmetric( + vertical: screenSize.shortestSide * overscanFactor, + horizontal: screenSize.longestSide * overscanFactor, + ); + final oldViewPadding = mq.viewPadding; + final newViewPadding = EdgeInsets.only( + top: max(oldViewPadding.top, overscanInsets.top), + right: max(oldViewPadding.right, overscanInsets.right), + bottom: max(oldViewPadding.bottom, overscanInsets.bottom), + left: max(oldViewPadding.left, overscanInsets.left), + ); + var newPadding = newViewPadding - mq.viewInsets; + newPadding = EdgeInsets.only( + top: max(0.0, newPadding.top), + right: max(0.0, newPadding.right), + bottom: max(0.0, newPadding.bottom), + left: max(0.0, newPadding.left), + ); + + return mq.copyWith( + textScaler: const TextScaler.linear(1.1), + padding: newPadding, + viewPadding: newViewPadding, + navigationMode: NavigationMode.directional, + ); + }; + if (settings.forceTvLayout) { + await windowService.requestOrientation(Orientation.landscape); + } + } else { + _pageTransitionsBuilderNotifier.value = _defaultPageTransitionsBuilder; + _tvMediaQueryModifierNotifier.value = null; + await windowService.requestOrientation(null); + } + } + + void _monitorSettings() { + void _applyIsInstalledAppAccessAllowed() { + if (settings.isInstalledAppAccessAllowed) { + appInventory.initAppNames(); + } else { + appInventory.resetAppNames(); + } + } + + void _applyDisplayRefreshRateMode() => settings.displayRefreshRateMode.apply(); + + void _applyMaxBrightness() { + try { + switch (settings.maxBrightness) { + case MaxBrightness.never: + case MaxBrightness.viewerOnly: + AvesApp.screenBrightness?.resetApplicationScreenBrightness(); + case MaxBrightness.always: + AvesApp.screenBrightness?.setApplicationScreenBrightness(1); + } + } on PlatformException catch (e, stack) { + // `screen_brightness` plugin may fail + reportService.recordError(e, stack); + } + } + + void _applyKeepScreenOn() => settings.keepScreenOn.apply(); + + void _applyIsRotationLocked() { + if (!settings.isRotationLocked && !settings.useTvLayout) { + windowService.requestOrientation(); + } + } + + void applyForceTvLayout() { + _onTvLayoutChanged(); + unawaited(_navigatorKey.currentState!.pushAndRemoveUntil( + MaterialPageRoute( + settings: const RouteSettings(name: HomePage.routeName), + builder: (_) => _getFirstPage(), + ), + (route) => false, + )); + } + + final settingStream = settings.updateStream; + // app + settingStream.where((event) => event.key == SettingKeys.isInstalledAppAccessAllowedKey).listen((_) => _applyIsInstalledAppAccessAllowed()); + settingStream.where((event) => event.key == SettingKeys.localeKey || event.key == SettingKeys.forceWesternArabicNumeralsKey).listen((_) => _applyLocale()); + // display + settingStream.where((event) => event.key == SettingKeys.displayRefreshRateModeKey).listen((_) => _applyDisplayRefreshRateMode()); + settingStream.where((event) => event.key == SettingKeys.maxBrightnessKey).listen((_) => _applyMaxBrightness()); + settingStream.where((event) => event.key == SettingKeys.forceTvLayoutKey).listen((_) => applyForceTvLayout()); + // navigation + settingStream.where((event) => event.key == SettingKeys.keepScreenOnKey).listen((_) => _applyKeepScreenOn()); + // platform settings + settingStream.where((event) => event.key == SettingKeys.platformAccelerometerRotationKey).listen((_) => _applyIsRotationLocked()); + + _applyLocale(); + _applyDisplayRefreshRateMode(); + _applyMaxBrightness(); + _applyKeepScreenOn(); + _applyIsRotationLocked(); + } + + Future<void> _setupErrorReporting() async { + await reportService.init(); + settings.updateStream.where((event) => event.key == SettingKeys.isErrorReportingAllowedKey).listen( + (_) => reportService.setCollectionEnabled(settings.isErrorReportingAllowed), + ); + await reportService.setCollectionEnabled(settings.isErrorReportingAllowed); + + FlutterError.onError = reportService.recordFlutterError; + final now = DateTime.now(); + await reportService.setCustomKeys({ + 'build_mode': kReleaseMode + ? 'release' + : kProfileMode + ? 'profile' + : 'debug', + 'has_mobile_services': mobileServices.isServiceAvailable, + 'is_television': device.isTelevision, + 'locales': WidgetsBinding.instance.platformDispatcher.locales.join(', '), + 'time_zone': '${now.timeZoneName} (${now.timeZoneOffset})', + }); + await reportService.log('Launch'); + setState(() => _navigatorObservers = [ + AvesApp.pageRouteObserver, + ReportingRouteTracker(), + ]); + } + + // at this level `ModalRoute.of(context)` is null, + // so we use the global navigator as a workaround + String? getCurrentRouteName() { + String? currentRoute; + _navigatorKey.currentState?.popUntil((route) { + currentRoute = route.settings.name; + return true; + }); + return currentRoute; + } + + void _onNewIntent(Map? intentData) { + reportService.log('New intent data=$intentData'); + + if (_appModeNotifier.value == AppMode.main) { + // do not reset when relaunching the app, except when exiting by pop + final shouldReset = _exitedMainByPop; + _exitedMainByPop = false; + + if (!shouldReset && (intentData ?? {}).values.nonNulls.isEmpty) { + reportService.log('Relaunch'); + return; + } + } + + if (intentData != null) { + final intentAction = intentData[IntentDataKeys.action] as String?; + if (intentAction == IntentActions.viewGeo) { + final locationZoom = parseGeoUri(intentData[IntentDataKeys.uri] as String?); + if (locationZoom != null && getCurrentRouteName() == EditEntryLocationDialog.routeName) { + // do not push a new route but pass the provided location to the dialog + final location = locationZoom.$1; + debugPrint('Use received location $location for input'); + _intentEventBus.fire(LocationReceivedEvent(location)); + return; + } + } + } + + _navigatorKey.currentState!.pushReplacement(DirectMaterialPageRoute( + settings: const RouteSettings(name: HomePage.routeName), + builder: (_) => _getFirstPage(intentData: intentData), + )); + } + + Future<void> _onAnalysisCompletion() async { + debugPrint('Analysis completed'); + await _mediaStoreSource.loadCatalogMetadata(); + await _mediaStoreSource.loadAddresses(); + _mediaStoreSource.updateDerivedFilters(); + } + + void _onError(String? error) => reportService.recordError(error); + + void _onAppModeChanged() { + final appMode = _appModeNotifier.value; + debugPrint('App mode set to $appMode'); + switch (appMode) { + case AppMode.screenSaver: + // we cannot modify brightness without access to the activity + _screenBrightness = null; + default: + _screenBrightness = ScreenBrightness(); + } + } +} + +// Flutter has various overscroll indicator implementations for Android: +// - `StretchingOverscrollIndicator`, default when using Material 3 +// - `GlowingOverscrollIndicator`, default when not using Material 3 +class AvesScrollBehavior extends MaterialScrollBehavior { + @override + Widget buildOverscrollIndicator(BuildContext context, Widget child, ScrollableDetails details) { + final animate = context.select<Settings, bool>((v) => v.animate); + return animate + ? StretchingOverscrollIndicator( + axisDirection: details.direction, + child: child, + ) + : child; + } +} + +typedef TvMediaQueryModifier = MediaQueryData Function(MediaQueryData); + +class LocationReceivedEvent { + final LatLng location; + + const LocationReceivedEvent(this.location); +} diff --git a/lib/widgets/collection/app_bar.dart b/lib/widgets/collection/app_bar.dart new file mode 100644 index 0000000..0bf518f --- /dev/null +++ b/lib/widgets/collection/app_bar.dart @@ -0,0 +1,797 @@ +import 'dart:async'; +import 'dart:math'; + +import 'package:aves/app_mode.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/filters/container/dynamic_album.dart'; +import 'package:aves/model/filters/container/set_and.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/filters/query.dart'; +import 'package:aves/model/filters/trash.dart'; +import 'package:aves/model/query.dart'; +import 'package:aves/model/selection.dart'; +import 'package:aves/model/settings/enums/accessibility_animations.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/aves_app.dart'; +import 'package:aves/widgets/collection/collection_page.dart'; +import 'package:aves/widgets/collection/entry_set_action_delegate.dart'; +import 'package:aves/widgets/collection/filter_bar.dart'; +import 'package:aves/widgets/collection/query_bar.dart'; +import 'package:aves/widgets/common/action_controls/quick_choosers/move_button.dart'; +import 'package:aves/widgets/common/action_controls/quick_choosers/rate_button.dart'; +import 'package:aves/widgets/common/action_controls/quick_choosers/tag_button.dart'; +import 'package:aves/widgets/common/action_controls/togglers/favourite.dart'; +import 'package:aves/widgets/common/action_controls/togglers/title_search.dart'; +import 'package:aves/widgets/common/app_bar/app_bar_subtitle.dart'; +import 'package:aves/widgets/common/app_bar/app_bar_title.dart'; +import 'package:aves/widgets/common/basic/popup/container.dart'; +import 'package:aves/widgets/common/basic/popup/expansion_panel.dart'; +import 'package:aves/widgets/common/basic/popup/menu_row.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/aves_app_bar.dart'; +import 'package:aves/widgets/common/identity/buttons/captioned_button.dart'; +import 'package:aves/widgets/common/search/route.dart'; +import 'package:aves/widgets/common/tile_extent_controller.dart'; +import 'package:aves/widgets/dialogs/tile_view_dialog.dart'; +import 'package:aves/widgets/search/collection_search_delegate.dart'; +import 'package:aves/widgets/viewer/controls/notifications.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:provider/provider.dart'; + +class CollectionAppBar extends StatefulWidget { + final ValueNotifier<double> appBarHeightNotifier; + final ScrollController scrollController; + final CollectionLens collection; + + const CollectionAppBar({ + super.key, + required this.appBarHeightNotifier, + required this.scrollController, + required this.collection, + }); + + @override + State<CollectionAppBar> createState() => _CollectionAppBarState(); +} + +class _CollectionAppBarState extends State<CollectionAppBar> with RouteAware, SingleTickerProviderStateMixin, WidgetsBindingObserver { + final Set<StreamSubscription> _subscriptions = {}; + final EntrySetActionDelegate _actionDelegate = EntrySetActionDelegate(); + late AnimationController _browseToSelectAnimation; + final ValueNotifier<bool> _isSelectingNotifier = ValueNotifier(false); + final FocusNode _queryBarFocusNode = FocusNode(); + late final Listenable _queryFocusRequestNotifier; + double _statusBarHeight = 0; + + CollectionLens get collection => widget.collection; + + bool get isTrash => collection.filters.contains(TrashFilter.instance); + + CollectionSource get source => collection.source; + + Set<CollectionFilter> get visibleFilters => collection.filters.where((v) => !(v is QueryFilter && v.live) && v is! TrashFilter).toSet(); + + bool get showFilterBar => visibleFilters.isNotEmpty; + + static const _sortOptions = [ + EntrySortFactor.date, + EntrySortFactor.size, + EntrySortFactor.name, + EntrySortFactor.rating, + EntrySortFactor.duration, + EntrySortFactor.path, + ]; + + static const _sectionOptions = [ + EntrySectionFactor.album, + EntrySectionFactor.month, + EntrySectionFactor.day, + EntrySectionFactor.none, + ]; + + static const _layoutOptions = [ + TileLayout.mosaic, + TileLayout.grid, + TileLayout.list, + ]; + + static const _trashSelectionQuickActions = [ + EntrySetAction.delete, + EntrySetAction.restore, + ]; + + @override + void initState() { + super.initState(); + final query = context.read<Query>(); + _subscriptions.add(query.enabledStream.listen((e) => _updateAppBarHeight())); + _queryFocusRequestNotifier = query.focusRequestNotifier; + _queryFocusRequestNotifier.addListener(_onQueryFocusRequest); + _queryBarFocusNode.addListener(_onQueryBarFocusChanged); + _browseToSelectAnimation = AnimationController( + duration: context.read<DurationsData>().iconAnimation, + vsync: this, + ); + _isSelectingNotifier.addListener(_onActivityChanged); + _registerWidget(widget); + WidgetsBinding.instance.addObserver(this); + WidgetsBinding.instance.addPostFrameCallback((_) { + _updateStatusBarHeight(); + _onFilterChanged(); + }); + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + final route = ModalRoute.of(context); + if (route is PageRoute) { + AvesApp.pageRouteObserver.subscribe(this, route); + } + } + + @override + void didUpdateWidget(covariant CollectionAppBar oldWidget) { + super.didUpdateWidget(oldWidget); + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + + @override + void dispose() { + _unregisterWidget(widget); + _queryBarFocusNode.dispose(); + _queryFocusRequestNotifier.removeListener(_onQueryFocusRequest); + _queryBarFocusNode.removeListener(_onQueryBarFocusChanged); + _isSelectingNotifier.dispose(); + _browseToSelectAnimation.dispose(); + _subscriptions + ..forEach((sub) => sub.cancel()) + ..clear(); + WidgetsBinding.instance.removeObserver(this); + AvesApp.pageRouteObserver.unsubscribe(this); + super.dispose(); + } + + void _registerWidget(CollectionAppBar widget) { + widget.collection.filterChangeNotifier.addListener(_onFilterChanged); + } + + void _unregisterWidget(CollectionAppBar widget) { + widget.collection.filterChangeNotifier.removeListener(_onFilterChanged); + } + + @override + void didPushNext() { + // unfocus when navigating away, so that when navigating back, + // the query bar does not get back focus and bring the keyboard + _queryBarFocusNode.unfocus(); + } + + @override + void didChangeMetrics() { + // when top padding or text scale factor change + WidgetsBinding.instance.addPostFrameCallback((_) => _updateStatusBarHeight()); + } + + @override + Widget build(BuildContext context) { + final appMode = context.watch<ValueNotifier<AppMode>>().value; + final selection = context.watch<Selection<AvesEntry>>(); + final isSelecting = selection.isSelecting; + _isSelectingNotifier.value = isSelecting; + return NotificationListener<ScrollNotification>( + // cancel notification bubbling so that the draggable scroll bar + // does not misinterpret filter bar scrolling for collection scrolling + onNotification: (notification) => true, + child: AnimatedBuilder( + animation: collection.filterChangeNotifier, + builder: (context, child) { + final canRemoveFilters = appMode != AppMode.pickFilteredMediaInternal; + return Selector<Query, bool>( + selector: (context, query) => query.enabled, + builder: (context, queryEnabled, child) { + return Selector<Settings, List<EntrySetAction>>( + selector: (context, s) => s.collectionBrowsingQuickActions, + builder: (context, _, child) { + final useTvLayout = settings.useTvLayout; + final onFilterTap = canRemoveFilters ? collection.removeFilter : null; + return AvesAppBar( + contentHeight: appBarContentHeight, + pinned: context.select<Selection<AvesEntry>, bool>((selection) => selection.isSelecting), + leading: _buildAppBarLeading( + hasDrawer: appMode.canNavigate, + isSelecting: isSelecting, + ), + title: _buildAppBarTitle(isSelecting), + actions: (context, maxWidth) => useTvLayout ? [] : _buildActions(context, selection, maxWidth), + bottom: Column( + children: [ + if (useTvLayout) + SizedBox( + height: CaptionedButton.getTelevisionButtonHeight(context), + child: ListView( + padding: const EdgeInsets.symmetric(horizontal: 8), + scrollDirection: Axis.horizontal, + children: _buildActions(context, selection, double.infinity), + ), + ), + if (showFilterBar) + NotificationListener( + onNotification: (notification) { + if (notification is SelectFilterNotification) { + collection.addFilters({notification.filter}); + return true; + } else if (notification is DecomposeFilterNotification) { + final filter = notification.filter; + if (filter is DynamicAlbumFilter) { + final innerFilter = filter.filter; + final newFilters = innerFilter is SetAndFilter ? innerFilter.innerFilters : {innerFilter}; + collection.addFilters(newFilters); + collection.removeFilter(filter); + return true; + } + } + return false; + }, + child: FilterBar( + filters: visibleFilters, + onTap: onFilterTap, + onRemove: onFilterTap, + ), + ), + if (queryEnabled) + EntryQueryBar( + queryNotifier: context.select<Query, ValueNotifier<String>>((query) => query.queryNotifier), + focusNode: _queryBarFocusNode, + ), + ], + ), + transitionKey: isSelecting, + ); + }, + ); + }, + ); + }, + ), + ); + } + + double get appBarContentHeight { + final textScaler = MediaQuery.textScalerOf(context); + double height = textScaler.scale(kToolbarHeight); + if (settings.useTvLayout) { + height += CaptionedButton.getTelevisionButtonHeight(context); + } + if (showFilterBar) { + height += FilterBar.preferredHeight; + } + if (context.read<Query>().enabled) { + height += EntryQueryBar.getPreferredHeight(textScaler); + } + return height; + } + + Widget? _buildAppBarLeading({required bool hasDrawer, required bool isSelecting}) { + if (settings.useTvLayout) return null; + + if (!hasDrawer) { + return const CloseButton(); + } + + VoidCallback? onPressed; + String? tooltip; + if (isSelecting) { + onPressed = () => context.read<Selection<AvesEntry>>().browse(); + tooltip = MaterialLocalizations.of(context).backButtonTooltip; + } else { + onPressed = Scaffold.of(context).openDrawer; + tooltip = MaterialLocalizations.of(context).openAppDrawerTooltip; + } + return IconButton( + // key is expected by test driver + key: const Key('appbar-leading-button'), + icon: AnimatedIcon( + icon: AnimatedIcons.menu_arrow, + progress: _browseToSelectAnimation, + ), + onPressed: onPressed, + tooltip: tooltip, + ); + } + + Widget _buildAppBarTitle(bool isSelecting) { + final l10n = context.l10n; + + if (isSelecting) { + // `Selection` may not be available during hero + return Selector<Selection<AvesEntry>?, int>( + selector: (context, selection) => selection?.selectedItems.length ?? 0, + builder: (context, count, child) => Text( + count == 0 ? l10n.collectionSelectPageTitle : l10n.itemCount(count), + softWrap: false, + overflow: TextOverflow.fade, + maxLines: 1, + ), + ); + } else { + final appMode = context.watch<ValueNotifier<AppMode>>().value; + Widget title = Text( + appMode.isPickingMedia ? l10n.collectionPickPageTitle : (isTrash ? l10n.binPageTitle : l10n.collectionPageTitle), + softWrap: false, + overflow: TextOverflow.fade, + maxLines: 1, + ); + if (appMode == AppMode.main) { + title = SourceStateAwareAppBarTitle( + title: title, + source: source, + ); + } + return InteractiveAppBarTitle( + onTap: appMode.canNavigate ? _goToSearch : null, + child: title, + ); + } + } + + List<Widget> _buildActions(BuildContext context, Selection<AvesEntry> selection, double maxWidth) { + final appMode = context.watch<ValueNotifier<AppMode>>().value; + final isSelecting = selection.isSelecting; + final selectedItemCount = selection.selectedItems.length; + + bool isVisible(EntrySetAction action) => _actionDelegate.isVisible( + action, + appMode: appMode, + isSelecting: isSelecting, + itemCount: collection.entryCount, + selectedItemCount: selectedItemCount, + isTrash: isTrash, + ); + bool canApply(EntrySetAction action) => _actionDelegate.canApply( + action, + isSelecting: isSelecting, + collection: collection, + selectedItemCount: selectedItemCount, + ); + + return settings.useTvLayout + ? _buildTelevisionActions( + context: context, + appMode: appMode, + selection: selection, + isVisible: isVisible, + canApply: canApply, + ) + : _buildMobileActions( + context: context, + appMode: appMode, + selection: selection, + maxWidth: maxWidth, + isVisible: isVisible, + canApply: canApply, + ); + } + + List<Widget> _buildTelevisionActions({ + required BuildContext context, + required AppMode appMode, + required Selection<AvesEntry> selection, + required bool Function(EntrySetAction action) isVisible, + required bool Function(EntrySetAction action) canApply, + }) { + final isSelecting = selection.isSelecting; + + return [ + ...EntrySetActions.general, + ...isSelecting ? EntrySetActions.pageSelection : EntrySetActions.pageBrowsing, + ].nonNulls.where(isVisible).map((action) { + final enabled = canApply(action); + return CaptionedButton( + iconButtonBuilder: (context, focusNode) => _buildButtonIcon( + context, + action, + enabled: enabled, + selection: selection, + focusNode: focusNode, + ), + captionText: _buildButtonCaption(context, action, enabled: enabled), + onPressed: enabled ? () => _onActionSelected(action) : null, + ); + }).toList(); + } + + static double _iconButtonWidth(BuildContext context) { + const defaultPadding = EdgeInsets.all(8); + const defaultIconSize = 24.0; + return defaultPadding.horizontal + MediaQuery.textScalerOf(context).scale(defaultIconSize); + } + + List<Widget> _buildMobileActions({ + required BuildContext context, + required AppMode appMode, + required Selection<AvesEntry> selection, + required double maxWidth, + required bool Function(EntrySetAction action) isVisible, + required bool Function(EntrySetAction action) canApply, + }) { + final availableCount = (maxWidth / _iconButtonWidth(context)).floor(); + + final isSelecting = selection.isSelecting; + final selectedItemCount = selection.selectedItems.length; + final hasSelection = selectedItemCount > 0; + + final browsingQuickActions = settings.collectionBrowsingQuickActions; + final selectionQuickActions = isTrash ? _trashSelectionQuickActions : settings.collectionSelectionQuickActions; + final quickActions = (isSelecting ? selectionQuickActions : browsingQuickActions).take(max(0, availableCount - 1)).toList(); + final quickActionButtons = quickActions.where(isVisible).map( + (action) => _buildButtonIcon(context, action, enabled: canApply(action), selection: selection), + ); + + final animations = context.select<Settings, AccessibilityAnimations>((v) => v.accessibilityAnimations); + return [ + ...quickActionButtons, + PopupMenuButton<EntrySetAction>( + // key is expected by test driver + key: const Key('appbar-menu-button'), + itemBuilder: (context) { + bool _isValidForMenu(EntrySetAction? v) => v == null || (!quickActions.contains(v) && isVisible(v)); + final generalMenuItems = EntrySetActions.general.where(_isValidForMenu).map( + (action) => _toMenuItem(action, enabled: canApply(action), selection: selection), + ); + + final allContextualActions = isSelecting ? EntrySetActions.pageSelection : EntrySetActions.pageBrowsing; + final contextualMenuActions = allContextualActions.where(_isValidForMenu).fold(<EntrySetAction?>[], (prev, v) { + if (v == null && (prev.isEmpty || prev.last == null)) return prev; + return [...prev, v]; + }); + if (contextualMenuActions.isNotEmpty && contextualMenuActions.last == null) { + contextualMenuActions.removeLast(); + } + + final contextualMenuItems = <PopupMenuEntry<EntrySetAction>>[ + ...contextualMenuActions.map( + (action) { + if (action == null) return const PopupMenuDivider(); + return _toMenuItem(action, enabled: canApply(action), selection: selection); + }, + ), + if (isSelecting && !settings.isReadOnly && appMode == AppMode.main && !isTrash) + PopupMenuExpansionPanel<EntrySetAction>( + enabled: hasSelection, + value: 'edit', + icon: AIcons.edit, + title: context.l10n.collectionActionEdit, + items: [ + _buildRotateAndFlipMenuItems(context, canApply: canApply), + ...EntrySetActions.edit.where((v) => isVisible(v) && !quickActions.contains(v)).map((action) => _toMenuItem(action, enabled: canApply(action), selection: selection)), + ], + ), + ]; + + return [ + ...generalMenuItems, + if (contextualMenuItems.isNotEmpty) ...[ + const PopupMenuDivider(), + ...contextualMenuItems, + ], + ]; + }, + onSelected: (action) async { + // wait for the popup menu to hide before proceeding with the action + await Future.delayed(animations.popUpAnimationDelay * timeDilation); + await _onActionSelected(action); + }, + popUpAnimationStyle: animations.popUpAnimationStyle, + ), + ]; + } + + Set<AvesEntry> _getExpandedSelectedItems(Selection<AvesEntry> selection) { + return selection.selectedItems.expand((entry) => entry.stackedEntries ?? {entry}).toSet(); + } + + // key is expected by test driver + Key _getActionKey(EntrySetAction action) => Key('menu-${action.name}'); + + Widget _buildButtonIcon( + BuildContext context, + EntrySetAction action, { + required bool enabled, + FocusNode? focusNode, + required Selection<AvesEntry> selection, + }) { + final blurred = settings.enableBlurEffect; + final onPressed = enabled ? () => _onActionSelected(action) : null; + switch (action) { + case EntrySetAction.toggleTitleSearch: + // `Query` may not be available during hero + return Selector<Query?, bool>( + selector: (context, query) => query?.enabled ?? false, + builder: (context, queryEnabled, child) { + return TitleSearchToggler( + queryEnabled: queryEnabled, + onPressed: onPressed, + focusNode: focusNode, + ); + }, + ); + case EntrySetAction.copy: + return MoveButton( + copy: true, + blurred: blurred, + onChooserValue: (album) => _actionDelegate.quickMove(context, album, copy: true), + onPressed: onPressed, + ); + case EntrySetAction.move: + return MoveButton( + copy: false, + blurred: blurred, + onChooserValue: (album) => _actionDelegate.quickMove(context, album, copy: false), + onPressed: onPressed, + ); + case EntrySetAction.editRating: + return RateButton( + blurred: blurred, + onChooserValue: (rating) => _actionDelegate.quickRate(context, rating), + focusNode: focusNode, + onPressed: onPressed, + ); + case EntrySetAction.editTags: + return TagButton( + blurred: blurred, + onChooserValue: (filter) => _actionDelegate.quickTag(context, filter), + focusNode: focusNode, + onPressed: onPressed, + ); + case EntrySetAction.toggleFavourite: + return FavouriteToggler( + entries: _getExpandedSelectedItems(selection), + focusNode: focusNode, + onPressed: onPressed, + ); + default: + return IconButton( + key: _getActionKey(action), + icon: action.getIcon(), + onPressed: onPressed, + focusNode: focusNode, + tooltip: action.getText(context), + ); + } + } + + Widget _buildButtonCaption( + BuildContext context, + EntrySetAction action, { + required bool enabled, + }) { + switch (action) { + case EntrySetAction.toggleTitleSearch: + return TitleSearchTogglerCaption( + enabled: enabled, + ); + default: + return CaptionedButtonText( + text: action.getText(context), + enabled: enabled, + ); + } + } + + PopupMenuItem<EntrySetAction> _toMenuItem(EntrySetAction action, {required bool enabled, required Selection<AvesEntry> selection}) { + late Widget child; + switch (action) { + case EntrySetAction.toggleTitleSearch: + child = TitleSearchToggler( + queryEnabled: context.read<Query>().enabled, + isMenuItem: true, + ); + case EntrySetAction.toggleFavourite: + child = FavouriteToggler( + entries: _getExpandedSelectedItems(selection), + isMenuItem: true, + ); + default: + child = MenuRow(text: action.getText(context), icon: action.getIcon()); + } + return PopupMenuItem( + key: _getActionKey(action), + value: action, + enabled: enabled, + child: child, + ); + } + + PopupMenuEntry<EntrySetAction> _buildRotateAndFlipMenuItems( + BuildContext context, { + required bool Function(EntrySetAction action) canApply, + }) { + Widget buildDivider() => const SizedBox( + height: 16, + child: VerticalDivider( + width: 1, + thickness: 1, + ), + ); + + Widget buildItem(EntrySetAction action) => Expanded( + child: Material( + color: Colors.transparent, + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(8)), + ), + clipBehavior: Clip.antiAlias, + child: PopupMenuItem( + value: action, + enabled: canApply(action), + child: Tooltip( + message: action.getText(context), + child: Center(child: action.getIcon()), + ), + ), + ), + ); + + return PopupMenuItemContainer( + child: Row( + children: [ + buildDivider(), + buildItem(EntrySetAction.rotateCCW), + buildDivider(), + buildItem(EntrySetAction.rotateCW), + buildDivider(), + buildItem(EntrySetAction.flip), + buildDivider(), + ], + ), + ); + } + + void _onActivityChanged() { + if (context.read<Selection<AvesEntry>>().isSelecting) { + _browseToSelectAnimation.forward(); + } else { + _browseToSelectAnimation.reverse(); + } + } + + void _onFilterChanged() { + _updateAppBarHeight(); + + final filters = collection.filters; + if (filters.isNotEmpty) { + final selection = context.read<Selection<AvesEntry>>(); + if (selection.isSelecting) { + final toRemove = selection.selectedItems.where((entry) => !filters.every((f) => f.test(entry))).toSet(); + selection.removeFromSelection(toRemove); + } + } + } + + void _onQueryFocusRequest() => _queryBarFocusNode.requestFocus(); + + void _onQueryBarFocusChanged() { + if (_queryBarFocusNode.hasFocus) { + // the query bar is in the top sliver of the page scrollable, + // so when the bar text field gets focus and requests to be on screen, + // it will scroll to show it by default, but it may not end at the very top, + // so we do it manually for a more predicable end position + _scrollToTop(); + } + } + + void _scrollToTop() => widget.scrollController.jumpTo(0); + + void _updateStatusBarHeight() { + if (!mounted) { + return; + } + _statusBarHeight = MediaQuery.paddingOf(context).top; + _updateAppBarHeight(); + } + + void _updateAppBarHeight() { + widget.appBarHeightNotifier.value = _statusBarHeight + AvesAppBar.appBarHeightForContentHeight(appBarContentHeight); + } + + Future<void> _onActionSelected(EntrySetAction action) async { + switch (action) { + // general + case EntrySetAction.configureView: + await _configureView(); + case EntrySetAction.select: + context.read<Selection<AvesEntry>>().select(); + case EntrySetAction.selectAll: + context.read<Selection<AvesEntry>>().addToSelection(collection.sortedEntries); + case EntrySetAction.selectNone: + context.read<Selection<AvesEntry>>().clearSelection(); + // browsing + case EntrySetAction.searchCollection: + case EntrySetAction.toggleTitleSearch: + case EntrySetAction.addDynamicAlbum: + case EntrySetAction.addShortcut: + case EntrySetAction.setHome: + // browsing or selecting + case EntrySetAction.map: + case EntrySetAction.slideshow: + case EntrySetAction.stats: + case EntrySetAction.rescan: + case EntrySetAction.emptyBin: + // selecting + case EntrySetAction.share: + case EntrySetAction.delete: + case EntrySetAction.restore: + case EntrySetAction.copy: + case EntrySetAction.move: + case EntrySetAction.rename: + case EntrySetAction.convert: + case EntrySetAction.toggleFavourite: + case EntrySetAction.rotateCCW: + case EntrySetAction.rotateCW: + case EntrySetAction.flip: + case EntrySetAction.editDate: + case EntrySetAction.editLocation: + case EntrySetAction.editTitleDescription: + case EntrySetAction.editRating: + case EntrySetAction.editTags: + case EntrySetAction.removeMetadata: + _actionDelegate.onActionSelected(context, action); + } + } + + Future<void> _configureView() async { + final initialValue = ( + settings.collectionSortFactor, + settings.collectionSectionFactor, + settings.getTileLayout(CollectionPage.routeName), + settings.collectionSortReverse, + ); + final extentController = context.read<TileExtentController>(); + final value = await showDialog<(EntrySortFactor?, EntrySectionFactor?, TileLayout?, bool)>( + context: context, + builder: (context) { + return TileViewDialog<EntrySortFactor, EntrySectionFactor, TileLayout>( + initialValue: initialValue, + sortOptions: _sortOptions.map((v) => TileViewDialogOption(value: v, title: v.getName(context), icon: v.icon)).toList(), + sectionOptions: _sectionOptions.map((v) => TileViewDialogOption(value: v, title: v.getName(context), icon: v.icon)).toList(), + layoutOptions: _layoutOptions.map((v) => TileViewDialogOption(value: v, title: v.getName(context), icon: v.icon)).toList(), + sortOrder: (factor, reverse) => factor.getOrderName(context, reverse), + canSection: (s, g, l) => s == EntrySortFactor.date, + tileExtentController: extentController, + ); + }, + routeSettings: const RouteSettings(name: TileViewDialog.routeName), + ); + // wait for the dialog to hide + await Future.delayed(ADurations.dialogTransitionLoose * timeDilation); + if (value != null && initialValue != value) { + settings.collectionSortFactor = value.$1!; + settings.collectionSectionFactor = value.$2!; + settings.setTileLayout(CollectionPage.routeName, value.$3!); + settings.collectionSortReverse = value.$4; + } + } + + void _goToSearch() { + Navigator.maybeOf(context)?.push( + SearchPageRoute( + delegate: CollectionSearchDelegate( + searchFieldLabel: context.l10n.searchCollectionFieldHint, + searchFieldStyle: Themes.searchFieldStyle(context), + source: collection.source, + parentCollection: collection, + ), + ), + ); + } +} diff --git a/lib/widgets/collection/collection_grid.dart b/lib/widgets/collection/collection_grid.dart new file mode 100644 index 0000000..3926a66 --- /dev/null +++ b/lib/widgets/collection/collection_grid.dart @@ -0,0 +1,736 @@ +import 'dart:async'; + +import 'package:aves/app_mode.dart'; +import 'package:aves/model/app/permissions.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/favourites.dart'; +import 'package:aves/model/filters/favourite.dart'; +import 'package:aves/model/filters/mime.dart'; +import 'package:aves/model/selection.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/model/source/section_keys.dart'; +import 'package:aves/ref/mime_types.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/utils/time_utils.dart'; +import 'package:aves/widgets/collection/app_bar.dart'; +import 'package:aves/widgets/collection/draggable_thumb_label.dart'; +import 'package:aves/widgets/collection/grid/list_details_theme.dart'; +import 'package:aves/widgets/collection/grid/section_layout.dart'; +import 'package:aves/widgets/collection/grid/tile.dart'; +import 'package:aves/widgets/collection/loading.dart'; +import 'package:aves/widgets/common/basic/draggable_scrollbar/scrollbar.dart'; +import 'package:aves/widgets/common/basic/insets.dart'; +import 'package:aves/widgets/common/behaviour/routes.dart'; +import 'package:aves/widgets/common/behaviour/sloppy_scroll_physics.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/extensions/media_query.dart'; +import 'package:aves/widgets/common/grid/draggable_thumb_label.dart'; +import 'package:aves/widgets/common/grid/item_tracker.dart'; +import 'package:aves/widgets/common/grid/scaling.dart'; +import 'package:aves/widgets/common/grid/sections/fixed/scale_grid.dart'; +import 'package:aves/widgets/common/grid/sections/list_layout.dart'; +import 'package:aves/widgets/common/grid/sections/section_layout.dart'; +import 'package:aves/widgets/common/grid/selector.dart'; +import 'package:aves/widgets/common/grid/sliver.dart'; +import 'package:aves/widgets/common/grid/theme.dart'; +import 'package:aves/widgets/common/identity/buttons/outlined_button.dart'; +import 'package:aves/widgets/common/identity/empty.dart'; +import 'package:aves/widgets/common/identity/scroll_thumb.dart'; +import 'package:aves/widgets/common/providers/tile_extent_controller_provider.dart'; +import 'package:aves/widgets/common/providers/viewer_entry_provider.dart'; +import 'package:aves/widgets/common/thumbnail/decorated.dart'; +import 'package:aves/widgets/common/thumbnail/image.dart'; +import 'package:aves/widgets/common/thumbnail/notifications.dart'; +import 'package:aves/widgets/common/tile_extent_controller.dart'; +import 'package:aves/widgets/navigation/nav_bar/nav_bar.dart'; +import 'package:aves/widgets/viewer/entry_viewer_page.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:flutter_staggered_animations/flutter_staggered_animations.dart'; +import 'package:intl/intl.dart'; +import 'package:permission_handler/permission_handler.dart'; +import 'package:provider/provider.dart'; + +class CollectionGrid extends StatefulWidget { + final String settingsRouteKey; + + static const double extentMin = 46; + static const double extentMax = 300; + static const double fixedExtentLayoutSpacing = 2; + static const double mosaicLayoutSpacing = 4; + + static int get columnCountDefault => settings.useTvLayout ? 6 : 4; + + const CollectionGrid({ + super.key, + required this.settingsRouteKey, + }); + + @override + State<CollectionGrid> createState() => _CollectionGridState(); +} + +class _CollectionGridState extends State<CollectionGrid> { + TileExtentController? _tileExtentController; + + String get settingsRouteKey => widget.settingsRouteKey; + + @override + void dispose() { + _tileExtentController?.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final spacing = context.select<Settings, double>((v) => v.getTileLayout(settingsRouteKey) == TileLayout.mosaic ? CollectionGrid.mosaicLayoutSpacing : CollectionGrid.fixedExtentLayoutSpacing); + if (_tileExtentController?.spacing != spacing) { + _tileExtentController = TileExtentController( + settingsRouteKey: settingsRouteKey, + columnCountDefault: CollectionGrid.columnCountDefault, + extentMin: CollectionGrid.extentMin, + extentMax: CollectionGrid.extentMax, + spacing: spacing, + horizontalPadding: 2, + ); + } + return TileExtentControllerProvider( + controller: _tileExtentController!, + child: const _CollectionGridContent(), + ); + } +} + +class _CollectionGridContent extends StatefulWidget { + const _CollectionGridContent(); + + @override + State<_CollectionGridContent> createState() => _CollectionGridContentState(); +} + +class _CollectionGridContentState extends State<_CollectionGridContent> { + final ValueNotifier<AvesEntry?> _focusedItemNotifier = ValueNotifier(null); + final ValueNotifier<bool> _isScrollingNotifier = ValueNotifier(false); + final ValueNotifier<AppMode> _selectingAppModeNotifier = ValueNotifier(AppMode.pickFilteredMediaInternal); + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addPostFrameCallback((_) => context.read<ViewerEntryNotifier>().value = null); + } + + @override + void dispose() { + _focusedItemNotifier.dispose(); + _isScrollingNotifier.dispose(); + _selectingAppModeNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final selectable = context.select<ValueNotifier<AppMode>, bool>((v) => v.value.canSelectMedia); + final settingsRouteKey = context.read<TileExtentController>().settingsRouteKey; + final tileLayout = context.select<Settings, TileLayout>((v) => v.getTileLayout(settingsRouteKey)); + return Consumer<CollectionLens>( + builder: (context, collection, child) { + final sectionedListLayoutProvider = ValueListenableBuilder<double>( + valueListenable: context.select<TileExtentController, ValueNotifier<double>>((controller) => controller.extentNotifier), + builder: (context, thumbnailExtent, child) { + assert(thumbnailExtent > 0); + return Selector<TileExtentController, (double, int, double, double)>( + selector: (context, c) => (c.viewportSize.width, c.columnCount, c.spacing, c.horizontalPadding), + builder: (context, c, child) { + final (scrollableWidth, columnCount, tileSpacing, horizontalPadding) = c; + final source = collection.source; + return GridTheme( + extent: thumbnailExtent, + child: EntryListDetailsTheme( + extent: thumbnailExtent, + child: ValueListenableBuilder<SourceState>( + valueListenable: source.stateNotifier, + builder: (context, sourceState, child) { + late final Duration tileAnimationDelay; + if (sourceState == SourceState.ready) { + // do not listen for animation delay change + final target = context.read<DurationsData>().staggeredAnimationPageTarget; + tileAnimationDelay = context.read<TileExtentController>().getTileAnimationDelay(target); + } else { + tileAnimationDelay = Duration.zero; + } + + return NotificationListener<OpenViewerNotification>( + onNotification: (notification) { + _goToViewer(collection, notification.entry); + return true; + }, + child: StreamBuilder( + stream: source.eventBus.on<AspectRatioChangedEvent>(), + builder: (context, snapshot) => SectionedEntryListLayoutProvider( + collection: collection, + selectable: selectable, + scrollableWidth: scrollableWidth, + tileLayout: tileLayout, + columnCount: columnCount, + spacing: tileSpacing, + horizontalPadding: horizontalPadding, + tileExtent: thumbnailExtent, + tileBuilder: (entry, tileSize) { + final extent = tileSize.shortestSide; + return AnimatedBuilder( + animation: favourites, + builder: (context, child) { + Widget tile = InteractiveTile( + key: ValueKey(entry.id), + collection: collection, + entry: entry, + thumbnailExtent: extent, + tileLayout: tileLayout, + isScrollingNotifier: _isScrollingNotifier, + ); + if (!settings.useTvLayout) return tile; + + return Focus( + onFocusChange: (focused) { + if (focused) { + _focusedItemNotifier.value = entry; + } else if (_focusedItemNotifier.value == entry) { + _focusedItemNotifier.value = null; + } + }, + child: ValueListenableBuilder<AvesEntry?>( + valueListenable: _focusedItemNotifier, + builder: (context, focusedItem, child) { + return AnimatedScale( + scale: focusedItem == entry ? 1 : .9, + curve: Curves.fastOutSlowIn, + duration: context.select<DurationsData, Duration>((v) => v.tvImageFocusAnimation), + child: child!, + ); + }, + child: tile, + ), + ); + }, + ); + }, + tileAnimationDelay: tileAnimationDelay, + child: child!, + ), + ), + ); + }, + child: child, + ), + ), + ); + }, + child: child, + ); + }, + child: _CollectionSectionedContent( + collection: collection, + isScrollingNotifier: _isScrollingNotifier, + scrollController: PrimaryScrollController.of(context), + tileLayout: tileLayout, + selectable: selectable, + ), + ); + return sectionedListLayoutProvider; + }, + ); + } + + Future<void> _goToViewer(CollectionLens collection, AvesEntry entry) async { + // track viewer entry for dynamic hero placeholder + final viewerEntryNotifier = context.read<ViewerEntryNotifier>(); + + // prevent navigating again to the same entry until fully back, + // as a workaround for the hero pop/push diversion animation issue + // (cf `ThumbnailImage` `Hero` usage) + if (viewerEntryNotifier.value == entry) return; + WidgetsBinding.instance.addPostFrameCallback((_) => viewerEntryNotifier.value = entry); + + final selection = context.read<Selection<AvesEntry>>(); + await Navigator.maybeOf(context)?.push( + TransparentMaterialPageRoute( + settings: const RouteSettings(name: EntryViewerPage.routeName), + pageBuilder: (context, a, sa) { + final viewerCollection = collection.copyWith( + listenToSource: false, + ); + Widget child = EntryViewerPage( + collection: viewerCollection, + initialEntry: entry, + ); + + if (selection.isSelecting) { + child = MultiProvider( + providers: [ + ListenableProvider<ValueNotifier<AppMode>>.value(value: _selectingAppModeNotifier), + ChangeNotifierProvider<Selection<AvesEntry>>.value(value: selection), + ], + child: child, + ); + } + + return child; + }, + ), + ); + + // reset track viewer entry + final animate = context.read<Settings>().animate; + if (animate) { + // TODO TLAD fix timing when transition is incomplete, e.g. when going back while going to the viewer + await Future.delayed(ADurations.pageTransitionExact * timeDilation); + } + viewerEntryNotifier.value = null; + } +} + +class _CollectionSectionedContent extends StatefulWidget { + final CollectionLens collection; + final ValueNotifier<bool> isScrollingNotifier; + final ScrollController scrollController; + final TileLayout tileLayout; + final bool selectable; + + const _CollectionSectionedContent({ + required this.collection, + required this.isScrollingNotifier, + required this.scrollController, + required this.tileLayout, + required this.selectable, + }); + + @override + State<_CollectionSectionedContent> createState() => _CollectionSectionedContentState(); +} + +class _CollectionSectionedContentState extends State<_CollectionSectionedContent> { + final ValueNotifier<double> _appBarHeightNotifier = ValueNotifier(0); + final GlobalKey _scrollableKey = GlobalKey(debugLabel: 'thumbnail-collection-scrollable'); + + CollectionLens get collection => widget.collection; + + TileLayout get tileLayout => widget.tileLayout; + + ScrollController get scrollController => widget.scrollController; + + @override + void initState() { + super.initState(); + _appBarHeightNotifier.addListener(_onAppBarHeightChanged); + } + + @override + void dispose() { + _appBarHeightNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final scrollView = AnimationLimiter( + child: _CollectionScrollView( + scrollableKey: _scrollableKey, + collection: collection, + appBar: CollectionAppBar( + appBarHeightNotifier: _appBarHeightNotifier, + scrollController: scrollController, + collection: collection, + ), + appBarHeightNotifier: _appBarHeightNotifier, + isScrollingNotifier: widget.isScrollingNotifier, + scrollController: scrollController, + ), + ); + + final scaler = _CollectionScaler( + scrollableKey: _scrollableKey, + appBarHeightNotifier: _appBarHeightNotifier, + tileLayout: tileLayout, + child: scrollView, + ); + + final selector = GridSelectionGestureDetector<AvesEntry>( + scrollableKey: _scrollableKey, + selectable: widget.selectable, + items: collection.sortedEntries, + scrollController: scrollController, + appBarHeightNotifier: _appBarHeightNotifier, + child: scaler, + ); + + return GridItemTracker<AvesEntry>( + scrollableKey: _scrollableKey, + tileLayout: tileLayout, + appBarHeightNotifier: _appBarHeightNotifier, + scrollController: scrollController, + child: selector, + ); + } + + void _onAppBarHeightChanged() => setState(() {}); +} + +class _CollectionScaler extends StatelessWidget { + final GlobalKey scrollableKey; + final ValueNotifier<double> appBarHeightNotifier; + final TileLayout tileLayout; + final Widget child; + + const _CollectionScaler({ + required this.scrollableKey, + required this.appBarHeightNotifier, + required this.tileLayout, + required this.child, + }); + + @override + Widget build(BuildContext context) { + final (tileSpacing, horizontalPadding) = context.select<TileExtentController, (double, double)>((v) => (v.spacing, v.horizontalPadding)); + final brightness = Theme.of(context).brightness; + final borderColor = DecoratedThumbnail.borderColor(context); + final borderWidth = DecoratedThumbnail.borderWidth(context); + return GridScaleGestureDetector<AvesEntry>( + scrollableKey: scrollableKey, + tileLayout: tileLayout, + heightForWidth: (width) => width, + gridBuilder: (center, tileSize, child) => CustomPaint( + painter: FixedExtentGridPainter( + tileLayout: tileLayout, + tileCenter: center, + tileSize: tileSize, + spacing: tileSpacing, + horizontalPadding: horizontalPadding, + borderWidth: borderWidth, + borderRadius: Radius.zero, + color: borderColor, + textDirection: Directionality.of(context), + ), + child: child, + ), + scaledItemBuilder: (entry, tileSize) => EntryListDetailsTheme( + extent: tileSize.height, + child: Tile( + entry: entry, + thumbnailExtent: context.read<TileExtentController>().effectiveExtentMax, + tileLayout: tileLayout, + ), + ), + mosaicItemBuilder: (index, targetExtent) => DecoratedBox( + decoration: BoxDecoration( + color: ThumbnailImage.computeLoadingBackgroundColor(index * 10, brightness).withValues(alpha: .9), + border: Border.all( + color: borderColor, + width: borderWidth, + ), + ), + ), + child: child, + ); + } +} + +class _CollectionScrollView extends StatefulWidget { + final GlobalKey scrollableKey; + final CollectionLens collection; + final Widget appBar; + final ValueNotifier<double> appBarHeightNotifier; + final ValueNotifier<bool> isScrollingNotifier; + final ScrollController scrollController; + + const _CollectionScrollView({ + required this.scrollableKey, + required this.collection, + required this.appBar, + required this.appBarHeightNotifier, + required this.isScrollingNotifier, + required this.scrollController, + }); + + @override + State<_CollectionScrollView> createState() => _CollectionScrollViewState(); +} + +class _CollectionScrollViewState extends State<_CollectionScrollView> with WidgetsBindingObserver { + Timer? _scrollMonitoringTimer; + bool _checkingStoragePermission = false; + + @override + void initState() { + super.initState(); + _registerWidget(widget); + WidgetsBinding.instance.addObserver(this); + } + + @override + void didUpdateWidget(covariant _CollectionScrollView oldWidget) { + super.didUpdateWidget(oldWidget); + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + + @override + void dispose() { + WidgetsBinding.instance.removeObserver(this); + _unregisterWidget(widget); + _stopScrollMonitoringTimer(); + super.dispose(); + } + + void _registerWidget(_CollectionScrollView widget) { + widget.collection.filterChangeNotifier.addListener(_scrollToTop); + widget.collection.sortSectionChangeNotifier.addListener(_scrollToTop); + widget.scrollController.addListener(_onScrollChanged); + } + + void _unregisterWidget(_CollectionScrollView widget) { + widget.collection.filterChangeNotifier.removeListener(_scrollToTop); + widget.collection.sortSectionChangeNotifier.removeListener(_scrollToTop); + widget.scrollController.removeListener(_onScrollChanged); + } + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + if (state == AppLifecycleState.resumed && _checkingStoragePermission) { + _checkingStoragePermission = false; + _isStoragePermissionGranted.then((granted) { + if (granted) { + widget.collection.source.init(scope: CollectionSource.fullScope); + } + }); + } + } + + @override + Widget build(BuildContext context) { + final scrollView = _buildScrollView(widget.appBar, widget.collection); + return settings.useTvLayout ? scrollView : _buildDraggableScrollView(scrollView, widget.collection); + } + + Widget _buildDraggableScrollView(Widget scrollView, CollectionLens collection) { + return ValueListenableBuilder<double>( + valueListenable: widget.appBarHeightNotifier, + builder: (context, appBarHeight, child) { + return Selector<MediaQueryData, double>( + selector: (context, mq) => mq.effectiveBottomPadding, + builder: (context, mqPaddingBottom, child) { + return Selector<Settings, bool>( + selector: (context, s) => s.enableBottomNavigationBar, + builder: (context, enableBottomNavigationBar, child) { + final canNavigate = context.select<ValueNotifier<AppMode>, bool>((v) => v.value.canNavigate); + final showBottomNavigationBar = canNavigate && enableBottomNavigationBar; + final navBarHeight = showBottomNavigationBar ? AppBottomNavBar.height : 0; + return Selector<SectionedListLayout<AvesEntry>, List<SectionLayout>>( + selector: (context, layout) => layout.sectionLayouts, + builder: (context, sectionLayouts, child) { + final scrollController = widget.scrollController; + final offsetIncrementSnapThreshold = context.select<TileExtentController, double>((v) => (v.extentNotifier.value + v.spacing) / 4); + return DraggableScrollbar( + backgroundColor: Colors.white, + scrollThumbSize: Size(avesScrollThumbWidth, avesScrollThumbHeight), + scrollThumbBuilder: avesScrollThumbBuilder( + height: avesScrollThumbHeight, + backgroundColor: Colors.white, + ), + controller: scrollController, + dragOffsetSnapper: (scrollOffset, offsetIncrement) { + if (offsetIncrement > offsetIncrementSnapThreshold && scrollOffset < scrollController.position.maxScrollExtent) { + final section = sectionLayouts.firstWhereOrNull((section) => section.hasChildAtOffset(scrollOffset)); + if (section != null) { + if (section.maxOffset - section.minOffset < scrollController.position.viewportDimension) { + // snap to section header + return section.minOffset; + } else { + // snap to content row + final index = section.getMinChildIndexForScrollOffset(scrollOffset); + return section.indexToLayoutOffset(index); + } + } + } + return scrollOffset; + }, + crumbsBuilder: () => _getCrumbs(sectionLayouts), + padding: EdgeInsets.only( + // padding to keep scroll thumb between app bar above and nav bar below + top: appBarHeight, + bottom: navBarHeight + mqPaddingBottom, + ), + labelTextBuilder: (offsetY) => CollectionDraggableThumbLabel( + collection: collection, + offsetY: offsetY, + ), + crumbTextBuilder: (label) => DraggableCrumbLabel(label: label), + child: scrollView, + ); + }, + ); + }, + ); + }, + ); + }, + ); + } + + Widget _buildScrollView(Widget appBar, CollectionLens collection) { + return CustomScrollView( + key: widget.scrollableKey, + primary: true, + // workaround to prevent scrolling the app bar away + // when there is no content and we use `SliverFillRemaining` + physics: collection.isEmpty + ? const NeverScrollableScrollPhysics() + : SloppyScrollPhysics( + gestureSettings: MediaQuery.gestureSettingsOf(context), + parent: const AlwaysScrollableScrollPhysics(), + ), + cacheExtent: context.select<TileExtentController, double>((controller) => controller.effectiveExtentMax), + slivers: [ + appBar, + collection.isEmpty + ? SliverFillRemaining( + hasScrollBody: false, + child: _buildEmptyContent(collection), + ) + : const SectionedListSliver<AvesEntry>(), + const NavBarPaddingSliver(), + const BottomPaddingSliver(), + const TvTileGridBottomPaddingSliver(), + ], + ); + } + + Widget _buildEmptyContent(CollectionLens collection) { + final source = collection.source; + return ValueListenableBuilder<SourceState>( + valueListenable: source.stateNotifier, + builder: (context, sourceState, child) { + if (sourceState == SourceState.loading) { + return LoadingEmptyContent(source: source); + } + + return FutureBuilder<bool>( + future: _isStoragePermissionGranted, + builder: (context, snapshot) { + final granted = snapshot.data ?? true; + Widget? bottom = granted + ? null + : Padding( + padding: const EdgeInsets.only(top: 16), + child: AvesOutlinedButton( + label: context.l10n.collectionEmptyGrantAccessButtonLabel, + onPressed: () async { + if (await openAppSettings()) { + _checkingStoragePermission = true; + } + }, + ), + ); + + if (collection.filters.any((filter) => filter is FavouriteFilter)) { + return EmptyContent( + icon: AIcons.favourite, + text: context.l10n.collectionEmptyFavourites, + bottom: bottom, + ); + } + if (collection.filters.any((filter) => filter is MimeFilter && filter.mime == MimeTypes.anyVideo)) { + return EmptyContent( + icon: AIcons.video, + text: context.l10n.collectionEmptyVideos, + bottom: bottom, + ); + } + return EmptyContent( + icon: AIcons.image, + text: context.l10n.collectionEmptyImages, + bottom: bottom, + ); + }, + ); + }, + ); + } + + void _scrollToTop() => widget.scrollController.jumpTo(0); + + void _onScrollChanged() { + widget.isScrollingNotifier.value = true; + _stopScrollMonitoringTimer(); + _scrollMonitoringTimer = Timer(ADurations.collectionScrollMonitoringTimerDelay, () { + widget.isScrollingNotifier.value = false; + }); + } + + void _stopScrollMonitoringTimer() => _scrollMonitoringTimer?.cancel(); + + Map<double, String> _getCrumbs(List<SectionLayout> sectionLayouts) { + final crumbs = <double, String>{}; + if (sectionLayouts.length <= 1) return crumbs; + + final maxOffset = sectionLayouts.last.maxOffset; + void addAlbums(CollectionLens collection, List<SectionLayout> sectionLayouts, Map<double, String> crumbs) { + final source = collection.source; + sectionLayouts.forEach((section) { + final directory = (section.sectionKey as EntryAlbumSectionKey).directory; + if (directory != null) { + final label = source.getStoredAlbumDisplayName(context, directory); + crumbs[section.minOffset / maxOffset] = label; + } + }); + } + + final collection = widget.collection; + switch (collection.sortFactor) { + case EntrySortFactor.date: + switch (collection.sectionFactor) { + case EntrySectionFactor.album: + addAlbums(collection, sectionLayouts, crumbs); + case EntrySectionFactor.month: + case EntrySectionFactor.day: + final firstKey = sectionLayouts.first.sectionKey; + final lastKey = sectionLayouts.last.sectionKey; + if (firstKey is EntryDateSectionKey && lastKey is EntryDateSectionKey) { + final newest = firstKey.date; + final oldest = lastKey.date; + if (newest != null && oldest != null) { + final locale = context.locale; + final dateFormat = (newest.difference(oldest).inHumanDays).abs() > 365 ? DateFormat.y(locale) : DateFormat.MMM(locale); + String? lastLabel; + sectionLayouts.forEach((section) { + final date = (section.sectionKey as EntryDateSectionKey).date; + if (date != null) { + final label = dateFormat.format(date); + if (label != lastLabel) { + crumbs[section.minOffset / maxOffset] = label; + lastLabel = label; + } + } + }); + } + } + case EntrySectionFactor.none: + break; + } + case EntrySortFactor.name: + case EntrySortFactor.path: + addAlbums(collection, sectionLayouts, crumbs); + case EntrySortFactor.rating: + case EntrySortFactor.size: + case EntrySortFactor.duration: + break; + } + return crumbs; + } + + Future<bool> get _isStoragePermissionGranted => Future.wait(Permissions.storage.map((v) => v.status)).then((v) => v.any((status) => status.isGranted)); +} diff --git a/lib/widgets/collection/collection_page.dart b/lib/widgets/collection/collection_page.dart new file mode 100644 index 0000000..3d4d958 --- /dev/null +++ b/lib/widgets/collection/collection_page.dart @@ -0,0 +1,230 @@ +import 'dart:async'; + +import 'package:aves/app_mode.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/filters/query.dart'; +import 'package:aves/model/filters/trash.dart'; +import 'package:aves/model/highlight.dart'; +import 'package:aves/model/selection.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/services/app_service.dart'; +import 'package:aves/services/intent_service.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/widgets/collection/collection_grid.dart'; +import 'package:aves/widgets/common/basic/draggable_scrollbar/notifications.dart'; +import 'package:aves/widgets/common/basic/insets.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/behaviour/pop/double_back.dart'; +import 'package:aves/widgets/common/behaviour/pop/scope.dart'; +import 'package:aves/widgets/common/behaviour/pop/tv_navigation.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/aves_fab.dart'; +import 'package:aves/widgets/common/providers/query_provider.dart'; +import 'package:aves/widgets/common/providers/selection_provider.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:aves/widgets/navigation/drawer/app_drawer.dart'; +import 'package:aves/widgets/navigation/nav_bar/nav_bar.dart'; +import 'package:aves/widgets/navigation/tv_rail.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class CollectionPage extends StatefulWidget { + static const routeName = '/collection'; + + final CollectionSource source; + final Set<CollectionFilter?>? filters; + final bool Function(AvesEntry element)? highlightTest; + + const CollectionPage({ + super.key, + required this.source, + required this.filters, + this.highlightTest, + }); + + @override + State<CollectionPage> createState() => _CollectionPageState(); +} + +class _CollectionPageState extends State<CollectionPage> { + final Set<StreamSubscription> _subscriptions = {}; + late CollectionLens _collection; + final StreamController<DraggableScrollbarEvent> _draggableScrollBarEventStreamController = StreamController.broadcast(); + + @override + void initState() { + // do not seed this widget with the collection, but control its lifecycle here instead, + // as the collection properties may change and they should not be reset by a widget update (e.g. with theme change) + _collection = CollectionLens( + source: widget.source, + filters: widget.filters, + ); + super.initState(); + _subscriptions.add(settings.updateStream.where((event) => event.key == SettingKeys.enableBinKey).listen((_) { + if (!settings.enableBin) { + _collection.removeFilter(TrashFilter.instance); + } + })); + WidgetsBinding.instance.addPostFrameCallback((_) => _checkInitHighlight()); + } + + @override + void dispose() { + _subscriptions + ..forEach((sub) => sub.cancel()) + ..clear(); + _collection.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final useTvLayout = settings.useTvLayout; + final liveFilter = _collection.filters.firstWhereOrNull((v) => v is QueryFilter && v.live) as QueryFilter?; + return SelectionProvider<AvesEntry>( + child: Selector<Selection<AvesEntry>, bool>( + selector: (context, selection) => selection.selectedItems.isNotEmpty, + builder: (context, hasSelection, child) { + final body = QueryProvider( + startEnabled: settings.getShowTitleQuery(context.currentRouteName!), + initialQuery: liveFilter?.query, + child: Builder( + builder: (context) { + return AvesPopScope( + handlers: [ + APopHandler( + canPop: (context) => context.select<Selection<AvesEntry>, bool>((v) => !v.isSelecting), + onPopBlocked: (context) => context.read<Selection<AvesEntry>>().browse(), + ), + tvNavigationPopHandler, + doubleBackPopHandler, + ], + child: GestureAreaProtectorStack( + child: DirectionalSafeArea( + start: !useTvLayout, + top: false, + bottom: false, + child: const CollectionGrid( + // key is expected by test driver + key: Key('collection-grid'), + settingsRouteKey: CollectionPage.routeName, + ), + ), + ), + ); + }, + ), + ); + + Widget page; + if (useTvLayout) { + page = AvesScaffold( + body: Row( + children: [ + TvRail( + controller: context.read<TvRailController>(), + currentCollection: _collection, + ), + Expanded(child: body), + ], + ), + resizeToAvoidBottomInset: false, + extendBody: true, + ); + } else { + page = Selector<Settings, bool>( + selector: (context, s) => s.enableBottomNavigationBar, + builder: (context, enableBottomNavigationBar, child) { + final canNavigate = context.select<ValueNotifier<AppMode>, bool>((v) => v.value.canNavigate); + final showBottomNavigationBar = canNavigate && enableBottomNavigationBar; + + return NotificationListener<DraggableScrollbarNotification>( + onNotification: (notification) { + _draggableScrollBarEventStreamController.add(notification.event); + return false; + }, + child: AvesScaffold( + body: body, + floatingActionButton: _buildFab(context, hasSelection), + drawer: canNavigate ? AppDrawer(currentCollection: _collection) : null, + bottomNavigationBar: showBottomNavigationBar + ? AppBottomNavBar( + events: _draggableScrollBarEventStreamController.stream, + currentCollection: _collection, + ) + : null, + resizeToAvoidBottomInset: false, + extendBody: true, + ), + ); + }, + ); + } + // this provider should be above `TvRail` + return ChangeNotifierProvider<CollectionLens>.value( + value: _collection, + child: page, + ); + }, + ), + ); + } + + Widget? _buildFab(BuildContext context, bool hasSelection) { + final appMode = context.watch<ValueNotifier<AppMode>>().value; + switch (appMode) { + case AppMode.pickMultipleMediaExternal: + return hasSelection + ? AvesFab( + tooltip: context.l10n.pickTooltip, + onPressed: () async { + final items = context.read<Selection<AvesEntry>>().selectedItems; + final uris = items.map((entry) => entry.uri).toList(); + try { + await IntentService.submitPickedItems(uris); + } on TooManyItemsException catch (_) { + await showDialog( + context: context, + builder: (context) => AvesDialog( + content: Text(context.l10n.tooManyItemsErrorDialogMessage), + actions: const [OkButton()], + ), + routeSettings: const RouteSettings(name: AvesDialog.warningRouteName), + ); + } + }, + ) + : null; + case AppMode.pickCollectionFiltersExternal: + return AvesFab( + tooltip: context.l10n.pickTooltip, + onPressed: () { + final filters = _collection.filters; + IntentService.submitPickedCollectionFilters(filters); + }, + ); + default: + return null; + } + } + + Future<void> _checkInitHighlight() async { + final highlightTest = widget.highlightTest; + if (highlightTest == null) return; + + final item = _collection.sortedEntries.firstWhereOrNull(highlightTest); + if (item == null) return; + + final delayDuration = context.read<DurationsData>().staggeredAnimationPageTarget; + await Future.delayed(delayDuration + ADurations.highlightScrollInitDelay); + + if (!mounted) return; + final animate = context.read<Settings>().animate; + context.read<HighlightInfo>().trackItem(item, animate: animate, highlightItem: item); + } +} diff --git a/lib/widgets/collection/draggable_thumb_label.dart b/lib/widgets/collection/draggable_thumb_label.dart new file mode 100644 index 0000000..1361316 --- /dev/null +++ b/lib/widgets/collection/draggable_thumb_label.dart @@ -0,0 +1,83 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/filters/rating.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/utils/file_utils.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/grid/draggable_thumb_label.dart'; +import 'package:aves/widgets/common/grid/sections/list_layout.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class CollectionDraggableThumbLabel extends StatelessWidget { + final CollectionLens collection; + final double offsetY; + + const CollectionDraggableThumbLabel({ + super.key, + required this.collection, + required this.offsetY, + }); + + @override + Widget build(BuildContext context) { + return DraggableThumbLabel<AvesEntry>( + offsetY: offsetY, + lineBuilder: (context, entry) { + switch (collection.sortFactor) { + case EntrySortFactor.date: + final date = entry.bestDate; + switch (collection.sectionFactor) { + case EntrySectionFactor.album: + return [ + DraggableThumbLabel.formatMonthThumbLabel(context, date), + if (_showAlbumName(context, entry)) _getAlbumName(context, entry), + ]; + case EntrySectionFactor.month: + case EntrySectionFactor.none: + return [ + DraggableThumbLabel.formatMonthThumbLabel(context, date), + ]; + case EntrySectionFactor.day: + return [ + DraggableThumbLabel.formatDayThumbLabel(context, date), + ]; + } + case EntrySortFactor.name: + final entryTitle = entry.bestTitle; + return [ + if (_showAlbumName(context, entry)) _getAlbumName(context, entry), + if (entryTitle != null) entryTitle, + ]; + case EntrySortFactor.rating: + return [ + RatingFilter.formatRating(context, entry.rating), + DraggableThumbLabel.formatMonthThumbLabel(context, entry.bestDate), + ]; + case EntrySortFactor.size: + final sizeBytes = entry.sizeBytes; + return [ + if (sizeBytes != null) formatFileSize(context.locale, sizeBytes, round: 0), + ]; + case EntrySortFactor.duration: + return [ + if (entry.durationMillis != null) entry.durationText, + ]; + case EntrySortFactor.path: + final entryFilename = entry.filenameWithoutExtension; + return [ + if (_showAlbumName(context, entry)) _getAlbumName(context, entry), + if (entryFilename != null) entryFilename, + ]; + } + }, + ); + } + + bool _hasMultipleSections(BuildContext context) => context.read<SectionedListLayout<AvesEntry>>().sections.length > 1; + + bool _showAlbumName(BuildContext context, AvesEntry entry) => _hasMultipleSections(context) && entry.directory != null; + + String _getAlbumName(BuildContext context, AvesEntry entry) => context.read<CollectionSource>().getStoredAlbumDisplayName(context, entry.directory!); +} diff --git a/lib/widgets/collection/entry_set_action_delegate.dart b/lib/widgets/collection/entry_set_action_delegate.dart new file mode 100644 index 0000000..89520bf --- /dev/null +++ b/lib/widgets/collection/entry_set_action_delegate.dart @@ -0,0 +1,885 @@ +import 'dart:async'; + +import 'package:aves/app_mode.dart'; +import 'package:aves/model/device.dart'; +import 'package:aves/model/dynamic_albums.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/favourites.dart'; +import 'package:aves/model/entry/extensions/metadata_edition.dart'; +import 'package:aves/model/entry/extensions/multipage.dart'; +import 'package:aves/model/entry/extensions/props.dart'; +import 'package:aves/model/favourites.dart'; +import 'package:aves/model/filters/container/dynamic_album.dart'; +import 'package:aves/model/filters/container/set_and.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/grouping/common.dart'; +import 'package:aves/model/highlight.dart'; +import 'package:aves/model/metadata/date_modifier.dart'; +import 'package:aves/model/naming_pattern.dart'; +import 'package:aves/model/query.dart'; +import 'package:aves/model/selection.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/analysis_controller.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/model/vaults/vaults.dart'; +import 'package:aves/services/app_service.dart'; +import 'package:aves/services/common/image_op_events.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/services/media/media_edit_service.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/utils/collection_utils.dart'; +import 'package:aves/utils/mime_utils.dart'; +import 'package:aves/widgets/collection/collection_page.dart'; +import 'package:aves/widgets/common/action_mixins/entry_editor.dart'; +import 'package:aves/widgets/common/action_mixins/entry_storage.dart'; +import 'package:aves/widgets/common/action_mixins/feedback.dart'; +import 'package:aves/widgets/common/action_mixins/permission_aware.dart'; +import 'package:aves/widgets/common/action_mixins/size_aware.dart'; +import 'package:aves/widgets/common/action_mixins/vault_aware.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/search/route.dart'; +import 'package:aves/widgets/dialogs/add_shortcut_dialog.dart'; +import 'package:aves/widgets/dialogs/aves_confirmation_dialog.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:aves/widgets/dialogs/convert_entry_dialog.dart'; +import 'package:aves/widgets/dialogs/entry_editors/rename_entry_set_page.dart'; +import 'package:aves/widgets/dialogs/filter_editors/create_dynamic_album_dialog.dart'; +import 'package:aves/widgets/dialogs/pick_dialogs/location_pick_page.dart'; +import 'package:aves/widgets/filter_grids/albums_page.dart'; +import 'package:aves/widgets/map/map_page.dart'; +import 'package:aves/widgets/search/collection_search_delegate.dart'; +import 'package:aves/widgets/stats/stats_page.dart'; +import 'package:aves/widgets/viewer/slideshow_page.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:latlong2/latlong.dart'; +import 'package:provider/provider.dart'; + +class EntrySetActionDelegate with FeedbackMixin, PermissionAwareMixin, SizeAwareMixin, EntryEditorMixin, EntryStorageMixin, VaultAwareMixin { + bool isVisible( + EntrySetAction action, { + required AppMode appMode, + required bool isSelecting, + required int itemCount, + required int selectedItemCount, + required bool isTrash, + }) { + final canWrite = !settings.isReadOnly; + final isMain = appMode == AppMode.main; + final useTvLayout = settings.useTvLayout; + switch (action) { + // general + case EntrySetAction.configureView: + return true; + case EntrySetAction.select: + return appMode.canSelectMedia && !isSelecting; + case EntrySetAction.selectAll: + return (isSelecting && selectedItemCount < itemCount) || (!isSelecting && settings.collectionBrowsingQuickActions.contains(action)); + case EntrySetAction.selectNone: + return isSelecting && selectedItemCount == itemCount; + // browsing + case EntrySetAction.searchCollection: + return appMode.canNavigate && !isSelecting && !useTvLayout; + case EntrySetAction.toggleTitleSearch: + return !isSelecting && !useTvLayout; + case EntrySetAction.addShortcut: + return isMain && !isSelecting && !isTrash && device.canPinShortcut; + case EntrySetAction.addDynamicAlbum: + case EntrySetAction.setHome: + return isMain && !isSelecting && !isTrash && !useTvLayout; + case EntrySetAction.emptyBin: + return isMain && isTrash && canWrite; + // browsing or selecting + case EntrySetAction.map: + case EntrySetAction.slideshow: + case EntrySetAction.stats: + return isMain; + case EntrySetAction.rescan: + return isMain && isSelecting && !useTvLayout; + // selecting + case EntrySetAction.share: + case EntrySetAction.toggleFavourite: + return isMain && isSelecting && !isTrash; + case EntrySetAction.delete: + return isMain && isSelecting && canWrite; + case EntrySetAction.copy: + case EntrySetAction.move: + case EntrySetAction.rename: + case EntrySetAction.convert: + case EntrySetAction.rotateCCW: + case EntrySetAction.rotateCW: + case EntrySetAction.flip: + case EntrySetAction.editDate: + case EntrySetAction.editLocation: + case EntrySetAction.editTitleDescription: + case EntrySetAction.editRating: + case EntrySetAction.editTags: + case EntrySetAction.removeMetadata: + return isMain && isSelecting && !isTrash && canWrite; + case EntrySetAction.restore: + return isMain && isSelecting && isTrash && canWrite; + } + } + + bool canApply( + EntrySetAction action, { + required bool isSelecting, + required CollectionLens collection, + required int selectedItemCount, + }) { + final itemCount = collection.entryCount; + final hasItems = itemCount > 0; + final hasSelection = selectedItemCount > 0; + + switch (action) { + case EntrySetAction.configureView: + return true; + case EntrySetAction.select: + return hasItems; + case EntrySetAction.selectAll: + return selectedItemCount < itemCount || (!isSelecting && settings.collectionBrowsingQuickActions.contains(action)); + case EntrySetAction.selectNone: + return hasSelection; + case EntrySetAction.searchCollection: + case EntrySetAction.toggleTitleSearch: + case EntrySetAction.addShortcut: + case EntrySetAction.setHome: + return true; + case EntrySetAction.addDynamicAlbum: + return collection.filters.isNotEmpty; + case EntrySetAction.emptyBin: + return !isSelecting && hasItems; + case EntrySetAction.map: + case EntrySetAction.slideshow: + case EntrySetAction.stats: + case EntrySetAction.rescan: + return (!isSelecting && hasItems) || (isSelecting && hasSelection); + // selecting + case EntrySetAction.share: + case EntrySetAction.delete: + case EntrySetAction.restore: + case EntrySetAction.copy: + case EntrySetAction.move: + case EntrySetAction.rename: + case EntrySetAction.convert: + case EntrySetAction.toggleFavourite: + case EntrySetAction.rotateCCW: + case EntrySetAction.rotateCW: + case EntrySetAction.flip: + case EntrySetAction.editDate: + case EntrySetAction.editLocation: + case EntrySetAction.editTitleDescription: + case EntrySetAction.editRating: + case EntrySetAction.editTags: + case EntrySetAction.removeMetadata: + return hasSelection; + } + } + + void onActionSelected(BuildContext context, EntrySetAction action) { + reportService.log('$runtimeType handles $action'); + switch (action) { + // general + case EntrySetAction.configureView: + case EntrySetAction.select: + case EntrySetAction.selectAll: + case EntrySetAction.selectNone: + break; + // browsing + case EntrySetAction.searchCollection: + _goToSearch(context); + case EntrySetAction.toggleTitleSearch: + final routeName = context.currentRouteName!; + settings.setShowTitleQuery(routeName, !settings.getShowTitleQuery(routeName)); + context.read<Query>().toggle(); + case EntrySetAction.addDynamicAlbum: + _addDynamicAlbum(context); + case EntrySetAction.addShortcut: + _addShortcut(context); + case EntrySetAction.setHome: + _setHome(context); + // browsing or selecting + case EntrySetAction.map: + _goToMap(context); + case EntrySetAction.slideshow: + _goToSlideshow(context); + case EntrySetAction.stats: + _goToStats(context); + case EntrySetAction.rescan: + _rescan(context); + // selecting + case EntrySetAction.share: + _share(context); + case EntrySetAction.delete: + case EntrySetAction.emptyBin: + _delete(context); + case EntrySetAction.restore: + _move(context, moveType: MoveType.fromBin); + case EntrySetAction.copy: + _move(context, moveType: MoveType.copy); + case EntrySetAction.move: + _move(context, moveType: MoveType.move); + case EntrySetAction.rename: + _rename(context); + case EntrySetAction.convert: + _convert(context); + case EntrySetAction.toggleFavourite: + _toggleFavourite(context); + case EntrySetAction.rotateCCW: + _rotate(context, clockwise: false); + case EntrySetAction.rotateCW: + _rotate(context, clockwise: true); + case EntrySetAction.flip: + _flip(context); + case EntrySetAction.editDate: + editDate(context); + case EntrySetAction.editLocation: + _editLocation(context); + case EntrySetAction.editTitleDescription: + _editTitleDescription(context); + case EntrySetAction.editRating: + _editRating(context); + case EntrySetAction.editTags: + _editTags(context); + case EntrySetAction.removeMetadata: + _removeMetadata(context); + } + } + + void _browse(BuildContext context) { + context.read<Selection<AvesEntry>?>()?.browse(); + } + + Set<AvesEntry> _getTargetItems(BuildContext context) { + final selection = context.read<Selection<AvesEntry>>(); + final groupedEntries = (selection.isSelecting ? selection.selectedItems : context.read<CollectionLens>().sortedEntries); + return groupedEntries.expand((entry) => entry.stackedEntries ?? {entry}).toSet(); + } + + Future<void> _share(BuildContext context) async { + final entries = _getTargetItems(context); + try { + if (!await appService.shareEntries(entries)) { + await showNoMatchingAppDialog(context); + } + } on TooManyItemsException catch (_) { + await showDialog( + context: context, + builder: (context) => AvesDialog( + content: Text(context.l10n.tooManyItemsErrorDialogMessage), + actions: const [OkButton()], + ), + routeSettings: const RouteSettings(name: AvesDialog.warningRouteName), + ); + } + } + + void _rescan(BuildContext context) { + final entries = _getTargetItems(context); + + final controller = AnalysisController(canStartService: true, force: true); + final collection = context.read<CollectionLens>(); + collection.source.analyze(controller, entries: entries).then((_) => controller.dispose()); + + _browse(context); + } + + Future<void> _delete(BuildContext context) async { + final entries = _getTargetItems(context); + final byBinUsage = groupBy<AvesEntry, bool>(entries, (entry) { + final details = vaults.getVault(entry.directory); + return details?.useBin ?? settings.enableBin; + }); + var completed = true; + await Future.forEach(byBinUsage.entries, (kv) async { + completed &= await doDelete( + context: context, + entries: kv.value.toSet(), + enableBin: kv.key, + ); + }); + + if (completed) { + _browse(context); + } + } + + // returns whether it completed the action (with or without failures) + Future<bool> doDelete({ + required BuildContext context, + required Set<AvesEntry> entries, + required bool enableBin, + }) async { + final pureTrash = entries.every((entry) => entry.trashed); + if (enableBin && !pureTrash) { + return await doMove(context, moveType: MoveType.toBin, entries: entries); + } + + final l10n = context.l10n; + final source = context.read<CollectionSource>(); + final storageDirs = entries.map((e) => e.storageDirectory).nonNulls.toSet(); + final todoCount = entries.length; + + if (!await showSkippableConfirmationDialog( + context: context, + type: ConfirmationDialog.deleteForever, + message: l10n.deleteEntriesConfirmationDialogMessage(todoCount), + confirmationButtonLabel: l10n.deleteButtonLabel, + )) { + return false; + } + + if (!await checkStoragePermissionForAlbums(context, storageDirs, entries: entries)) return false; + + source.pauseMonitoring(); + final opId = mediaEditService.newOpId; + await showOpReport<ImageOpEvent>( + context: context, + opStream: mediaEditService.delete(opId: opId, entries: entries), + itemCount: todoCount, + onCancel: () => mediaEditService.cancelFileOp(opId), + onDone: (processed) async { + final successOps = processed.where((op) => op.success).toSet(); + final deletedOps = successOps.where((op) => !op.skipped).toSet(); + final deletedUris = deletedOps.map((op) => op.uri).toSet(); + await source.removeEntries(deletedUris, includeTrash: true); + source.resumeMonitoring(); + + final successCount = successOps.length; + if (successCount < todoCount) { + final count = todoCount - successCount; + showFeedback(context, FeedbackType.warn, context.l10n.collectionDeleteFailureFeedback(count)); + } + + // cleanup + await storageService.deleteEmptyRegularDirectories(storageDirs); + }, + ); + return true; + } + + Future<void> quickMove(BuildContext context, String destinationAlbum, {required bool copy}) async { + if (!await unlockAlbum(context, destinationAlbum)) return; + + final entries = _getTargetItems(context); + final completed = await doQuickMove( + context, + moveType: copy ? MoveType.copy : MoveType.move, + entriesByDestination: { + destinationAlbum: entries, + }, + ); + + if (completed) { + _browse(context); + } + } + + Future<void> _move(BuildContext context, {required MoveType moveType}) async { + final entries = _getTargetItems(context); + final completed = await doMove(context, moveType: moveType, entries: entries); + + if (completed) { + _browse(context); + } + } + + Future<void> _rename(BuildContext context) async { + final entries = _getTargetItems(context).toList(); + + final pattern = await Navigator.maybeOf(context)?.push<NamingPattern>( + MaterialPageRoute( + settings: const RouteSettings(name: RenameEntrySetPage.routeName), + builder: (context) => RenameEntrySetPage( + entries: entries, + ), + ), + ); + if (pattern == null) return; + + final namingFutures = entries.mapIndexed((index, entry) async { + final newName = await pattern.apply(entry, index); + return MapEntry(entry, '$newName${entry.extension}'); + }); + final entriesToNewName = Map.fromEntries(await Future.wait(namingFutures)).whereNotNullValue(); + final completed = await rename(context, entriesToNewName: entriesToNewName, persist: true); + + if (completed) { + _browse(context); + } + } + + Future<void> _convert(BuildContext context) async { + final entries = _getTargetItems(context); + + final options = await showDialog<EntryConvertOptions>( + context: context, + builder: (context) => ConvertEntryDialog(entries: entries), + routeSettings: const RouteSettings(name: ConvertEntryDialog.routeName), + ); + if (options == null) return; + + switch (options.action) { + case EntryConvertAction.convert: + final completed = await doExport(context, entries, options); + if (completed) { + _browse(context); + } + case EntryConvertAction.convertMotionPhotoToStillImage: + final todoItems = entries.where((entry) => entry.isMotionPhoto).toSet(); + await _edit(context, todoItems, (entry) => entry.removeTrailerVideo()); + } + } + + Future<void> _toggleFavourite(BuildContext context) async { + final entries = _getTargetItems(context); + if (entries.every((entry) => entry.isFavourite)) { + await favourites.removeEntries(entries); + } else { + await favourites.add(entries); + } + + _browse(context); + } + + Future<void> _edit( + BuildContext context, + Set<AvesEntry> todoItems, + Future<Set<EntryDataType>> Function(AvesEntry entry) op, { + bool showResult = true, + }) async { + final selectionDirs = todoItems.map((e) => e.directory).nonNulls.toSet(); + final todoCount = todoItems.length; + + if (!await checkStoragePermissionForAlbums(context, selectionDirs, entries: todoItems)) return; + + Set<String> obsoleteTags = todoItems.expand((entry) => entry.tags).toSet(); + Set<String> obsoleteCountryCodes = todoItems.where((entry) => entry.hasAddress).map((entry) => entry.addressDetails?.countryCode).nonNulls.toSet(); + Set<String> obsoleteStateCodes = todoItems.where((entry) => entry.hasAddress).map((entry) => entry.addressDetails?.stateCode).nonNulls.toSet(); + + final dataTypes = <EntryDataType>{}; + final source = context.read<CollectionSource>(); + source.pauseMonitoring(); + var cancelled = false; + await showOpReport<ImageOpEvent>( + context: context, + opStream: Stream.fromIterable(todoItems).asyncMap((entry) async { + if (cancelled) { + return ImageOpEvent(success: true, skipped: true, uri: entry.uri); + } else { + final opDataTypes = await op(entry); + dataTypes.addAll(opDataTypes); + return ImageOpEvent(success: opDataTypes.isNotEmpty, skipped: false, uri: entry.uri); + } + }).asBroadcastStream(), + itemCount: todoCount, + onCancel: () => cancelled = true, + onDone: (processed) async { + final successOps = processed.where((op) => op.success).toSet(); + final editedOps = successOps.where((op) => !op.skipped).toSet(); + source.resumeMonitoring(); + + unawaited(source.refreshUris(editedOps.map((op) => op.uri).toSet()).then((_) { + // invalidate filters derived from values before edition + // this invalidation must happen after the source is refreshed, + // otherwise filter chips may eagerly rebuild in between with the old state + if (obsoleteCountryCodes.isNotEmpty) { + source.invalidateCountryFilterSummary(countryCodes: obsoleteCountryCodes); + } + if (obsoleteStateCodes.isNotEmpty) { + source.invalidateStateFilterSummary(stateCodes: obsoleteStateCodes); + } + if (obsoleteTags.isNotEmpty) { + source.invalidateTagFilterSummary(tags: obsoleteTags); + } + })); + + if (dataTypes.contains(EntryDataType.aspectRatio)) { + source.onAspectRatioChanged(); + } + + if (showResult) { + final l10n = context.l10n; + final successCount = successOps.length; + if (successCount < todoCount) { + final count = todoCount - successCount; + showFeedback(context, FeedbackType.warn, l10n.collectionEditFailureFeedback(count)); + } else { + final count = editedOps.length; + showFeedback(context, FeedbackType.info, l10n.collectionEditSuccessFeedback(count)); + } + } + }, + ); + _browse(context); + } + + Future<Set<AvesEntry>?> _getEditableTargetItems( + BuildContext context, { + required bool Function(AvesEntry entry) canEdit, + }) => + _getEditableItems(context, _getTargetItems(context), canEdit: canEdit); + + Future<Set<AvesEntry>?> _getEditableItems( + BuildContext context, + Set<AvesEntry> entries, { + required bool Function(AvesEntry entry) canEdit, + }) async { + final bySupported = groupBy<AvesEntry, bool>(entries, canEdit); + final supported = (bySupported[true] ?? []).toSet(); + final unsupported = (bySupported[false] ?? []).toSet(); + + if (unsupported.isEmpty) return supported; + + final unsupportedTypes = unsupported.map((entry) => entry.mimeType).toSet().map(MimeUtils.displayType).toList()..sort(); + final l10n = context.l10n; + final confirmed = await showDialog<bool>( + context: context, + builder: (context) => AvesDialog( + content: Text(l10n.unsupportedTypeDialogMessage(unsupportedTypes.length, unsupportedTypes.join(', '))), + actions: [ + const CancelButton(), + if (supported.isNotEmpty) + TextButton( + onPressed: () => Navigator.maybeOf(context)?.pop(true), + child: Text(l10n.continueButtonLabel), + ), + ], + ), + routeSettings: const RouteSettings(name: AvesDialog.warningRouteName), + ); + if (confirmed == null || !confirmed) return null; + + // wait for the dialog to hide + await Future.delayed(ADurations.dialogTransitionLoose * timeDilation); + return supported; + } + + Future<void> _rotate(BuildContext context, {required bool clockwise}) async { + final entries = await _getEditableTargetItems(context, canEdit: (entry) => entry.canRotate); + if (entries == null || entries.isEmpty) return; + + await _edit(context, entries, (entry) => entry.rotate(clockwise: clockwise)); + } + + Future<void> _flip(BuildContext context) async { + final entries = await _getEditableTargetItems(context, canEdit: (entry) => entry.canFlip); + if (entries == null || entries.isEmpty) return; + + await _edit(context, entries, (entry) => entry.flip()); + } + + Future<void> editDate(BuildContext context, {Set<AvesEntry>? entries, DateModifier? modifier, bool showResult = true}) async { + entries ??= await _getEditableTargetItems(context, canEdit: (entry) => entry.canEditDate); + if (entries == null || entries.isEmpty) return; + + if (modifier == null) { + final collection = context.read<CollectionLens>(); + modifier = await selectDateModifier(context, entries, collection); + } + if (modifier == null) return; + + await _edit(context, entries, (entry) => entry.editDate(modifier!), showResult: showResult); + } + + Future<void> _editLocation(BuildContext context) async { + final entries = await _getEditableTargetItems(context, canEdit: (entry) => entry.canEditLocation); + if (entries == null || entries.isEmpty) return; + + final collection = context.read<CollectionLens>(); + final locationByEntry = await selectLocation(context, entries, collection); + if (locationByEntry == null) return; + + await _edit(context, locationByEntry.keys.toSet(), (entry) => entry.editLocation(locationByEntry[entry])); + } + + Future<LatLng?> editLocationByMap(BuildContext context, Set<AvesEntry> entries, LatLng clusterLocation, CollectionLens mapCollection) async { + final editableEntries = await _getEditableItems(context, entries, canEdit: (entry) => entry.canEditLocation); + if (editableEntries == null || editableEntries.isEmpty) return null; + + final location = await Navigator.maybeOf(context)?.push( + MaterialPageRoute( + settings: const RouteSettings(name: LocationPickPage.routeName), + builder: (context) => LocationPickPage( + collection: mapCollection, + initialLocation: clusterLocation, + ), + fullscreenDialog: true, + ), + ); + if (location == null) return null; + + await _edit(context, editableEntries, (entry) => entry.editLocation(location)); + return location; + } + + Future<void> removeLocation(BuildContext context, Set<AvesEntry> entries) async { + final l10n = context.l10n; + final confirmed = await showDialog<bool>( + context: context, + builder: (context) => AvesDialog( + content: Text(l10n.genericDangerWarningDialogMessage), + actions: [ + const CancelButton(), + TextButton( + onPressed: () => Navigator.maybeOf(context)?.pop(true), + child: Text(l10n.applyButtonLabel), + ), + ], + ), + routeSettings: const RouteSettings(name: AvesDialog.warningRouteName), + ); + if (confirmed == null || !confirmed) return; + + final editableEntries = await _getEditableItems(context, entries, canEdit: (entry) => entry.canEditLocation); + if (editableEntries == null || editableEntries.isEmpty) return; + + await _edit(context, editableEntries, (entry) => entry.editLocation(ExtraAvesEntryMetadataEdition.removalLocation)); + } + + Future<void> _editTitleDescription(BuildContext context) async { + final entries = await _getEditableTargetItems(context, canEdit: (entry) => entry.canEditTitleDescription); + if (entries == null || entries.isEmpty) return; + + final modifier = await selectTitleDescriptionModifier(context, entries); + if (modifier == null) return; + + await _edit(context, entries, (entry) => entry.editTitleDescription(modifier)); + } + + Future<void> quickRate(BuildContext context, int rating) => _editRating(context, rating: rating); + + Future<void> _editRating(BuildContext context, {int? rating}) async { + final entries = await _getEditableTargetItems(context, canEdit: (entry) => entry.canEditRating); + if (entries == null || entries.isEmpty) return; + + rating ??= await selectRating(context, entries); + if (rating == null) return; + + await _edit(context, entries, (entry) => entry.editRating(rating)); + } + + Future<void> quickTag(BuildContext context, CollectionFilter filter) async { + final entries = await _getEditableTargetItems(context, canEdit: (entry) => entry.canEditTags); + if (entries == null || entries.isEmpty) return; + + final newTagsByEntry = <AvesEntry, Set<String>>{}; + await Future.forEach(entries, (entry) async { + newTagsByEntry[entry] = { + ...entry.tags, + ...await getTagsFromFilters({filter}, entry), + }; + }); + + await _doEditTags(context, newTagsByEntry); + } + + Future<void> _editTags(BuildContext context) async { + final entries = await _getEditableTargetItems(context, canEdit: (entry) => entry.canEditTags); + if (entries == null || entries.isEmpty) return; + + final newTagsByEntry = await selectTags(context, entries); + if (newTagsByEntry == null) return; + + await _doEditTags(context, newTagsByEntry); + } + + Future<void> _doEditTags(BuildContext context, Map<AvesEntry, Set<String>> newTagsByEntry) async { + final entries = newTagsByEntry.keys.toSet(); + + // only process modified items + entries.removeWhere((entry) { + final newTags = newTagsByEntry[entry] ?? entry.tags; + final currentTags = entry.tags; + return newTags.length == currentTags.length && newTags.every(currentTags.contains); + }); + if (entries.isEmpty) return; + + await _edit(context, entries, (entry) => entry.editTags(newTagsByEntry[entry]!)); + } + + Future<void> removeTags(BuildContext context, {required Set<AvesEntry> entries, required Set<String> tags}) async { + final newTagsByEntry = Map.fromEntries(entries.map((v) { + return MapEntry(v, v.tags.whereNot(tags.contains).toSet()); + })); + + await _edit(context, entries, (entry) => entry.editTags(newTagsByEntry[entry]!)); + } + + Future<void> _removeMetadata(BuildContext context) async { + final entries = await _getEditableTargetItems(context, canEdit: (entry) => entry.isMetadataRemovalSupported); + if (entries == null || entries.isEmpty) return; + + final types = await selectMetadataToRemove(context, entries); + if (types == null || types.isEmpty) return; + + await _edit(context, entries, (entry) => entry.removeMetadata(types)); + } + + Future<void> _goToMap(BuildContext context) async { + final collection = context.read<CollectionLens>(); + final entries = _getTargetItems(context); + + // need collection with fresh ID to prevent hero from scroller on Map page to Collection page + final mapCollection = CollectionLens( + source: collection.source, + filters: collection.filters, + fixedSelection: entries.where((entry) => entry.hasGps).toList(), + ); + await Navigator.maybeOf(context)?.push( + MaterialPageRoute( + settings: const RouteSettings(name: MapPage.routeName), + builder: (context) => MapPage(collection: mapCollection), + ), + ); + } + + void _goToSlideshow(BuildContext context) { + final collection = context.read<CollectionLens>(); + final entries = _getTargetItems(context); + + Navigator.maybeOf(context)?.push( + MaterialPageRoute( + settings: const RouteSettings(name: SlideshowPage.routeName), + builder: (context) { + return SlideshowPage( + collection: CollectionLens( + source: collection.source, + filters: collection.filters, + fixedSelection: entries.toList(), + ), + ); + }, + ), + ); + } + + void _goToStats(BuildContext context) { + final collection = context.read<CollectionLens>(); + final entries = _getTargetItems(context); + + Navigator.maybeOf(context)?.push( + MaterialPageRoute( + settings: const RouteSettings(name: StatsPage.routeName), + builder: (context) => StatsPage( + entries: entries, + source: collection.source, + parentCollection: collection, + ), + ), + ); + } + + void _goToSearch(BuildContext context) { + final collection = context.read<CollectionLens>(); + + Navigator.maybeOf(context)?.push( + SearchPageRoute( + delegate: CollectionSearchDelegate( + searchFieldLabel: context.l10n.searchCollectionFieldHint, + searchFieldStyle: Themes.searchFieldStyle(context), + source: collection.source, + parentCollection: collection, + ), + ), + ); + } + + static String? _getDefaultNameForFilters(BuildContext context, Set<CollectionFilter> filters) { + String? defaultName; + if (filters.isNotEmpty) { + // we compute the default name beforehand + // because some filter labels need localization + final sortedFilters = List<CollectionFilter>.from(filters)..sort(); + defaultName = sortedFilters.first.getLabel(context).replaceAll('\n', ' '); + } + return defaultName; + } + + Future<void> _addDynamicAlbum(BuildContext context) async { + final l10n = context.l10n; + final collection = context.read<CollectionLens>(); + final filters = collection.filters; + if (filters.isEmpty) return; + + // get navigator beforehand because + // local context may be deactivated when action is triggered after navigation + final navigator = Navigator.maybeOf(context); + + final name = await showDialog<String>( + context: context, + builder: (context) => const CreateDynamicAlbumDialog(), + routeSettings: const RouteSettings(name: CreateDynamicAlbumDialog.routeName), + ); + if (name == null) return; + + final existingAlbum = dynamicAlbums.get(name); + if (existingAlbum != null) { + // album already exists, so we just need to highlight it + await _showDynamicAlbum(navigator, existingAlbum); + } else { + final album = DynamicAlbumFilter(name, filters.length == 1 ? filters.first : SetAndFilter(filters)); + await dynamicAlbums.add(album); + + final showAction = SnackBarAction( + label: l10n.showButtonLabel, + onPressed: () => _showDynamicAlbum(navigator, album), + ); + showFeedback(context, FeedbackType.info, l10n.genericSuccessFeedback, showAction); + } + } + + Future<void> _showDynamicAlbum(NavigatorState? navigator, DynamicAlbumFilter albumFilter) async { + // local context may be deactivated when action is triggered after navigation + if (navigator != null) { + final context = navigator.context; + final highlightInfo = context.read<HighlightInfo>(); + if (context.currentRouteName == AlbumListPage.routeName) { + highlightInfo.trackItem(FilterGridItem(albumFilter, null), highlightItem: albumFilter); + } else { + highlightInfo.set(albumFilter); + final initialGroup = albumGrouping.getFilterParent(albumFilter); + await navigator.pushAndRemoveUntil( + MaterialPageRoute( + settings: const RouteSettings(name: AlbumListPage.routeName), + builder: (_) => AlbumListPage(initialGroup: initialGroup), + ), + (route) => false, + ); + } + } + } + + Future<void> _addShortcut(BuildContext context) async { + final collection = context.read<CollectionLens>(); + final filters = collection.filters; + + String? defaultName = _getDefaultNameForFilters(context, filters); + final result = await showDialog<(AvesEntry?, String)>( + context: context, + builder: (context) => AddShortcutDialog( + defaultName: defaultName ?? '', + collection: collection, + ), + routeSettings: const RouteSettings(name: AddShortcutDialog.routeName), + ); + if (result == null) return; + + final (coverEntry, name) = result; + if (name.isEmpty) return; + + await appService.pinToHomeScreen(name, coverEntry, route: CollectionPage.routeName, filters: filters); + if (!device.showPinShortcutFeedback) { + showFeedback(context, FeedbackType.info, context.l10n.genericSuccessFeedback); + } + } + + void _setHome(BuildContext context) async { + settings.setHome(HomePageSetting.collection, customCollection: context.read<CollectionLens>().filters); + showFeedback(context, FeedbackType.info, context.l10n.genericSuccessFeedback); + } +} diff --git a/lib/widgets/collection/filter_bar.dart b/lib/widgets/collection/filter_bar.dart new file mode 100644 index 0000000..b565d7b --- /dev/null +++ b/lib/widgets/collection/filter_bar.dart @@ -0,0 +1,163 @@ +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/widgets/common/identity/aves_app_bar.dart'; +import 'package:aves/widgets/common/identity/aves_filter_chip.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class FilterBar extends StatefulWidget { + static const EdgeInsets chipPadding = EdgeInsets.symmetric(horizontal: 4); + static const EdgeInsets rowPadding = EdgeInsets.symmetric(horizontal: 4); + static const EdgeInsets padding = EdgeInsets.only(top: 4, bottom: 8); + static final double preferredHeight = AvesFilterChip.minChipHeight + padding.vertical; + + final List<CollectionFilter> filters; + final bool interactive; + final AFilterCallback? onTap, onRemove; + + FilterBar({ + super.key, + required Set<CollectionFilter> filters, + this.interactive = true, + this.onTap, + this.onRemove, + }) : filters = List<CollectionFilter>.from(filters)..sort(); + + @override + State<FilterBar> createState() => _FilterBarState(); +} + +class _FilterBarState extends State<FilterBar> { + final GlobalKey<AnimatedListState> _animatedListKey = GlobalKey(debugLabel: 'filter-bar-animated-list'); + CollectionFilter? _userTappedFilter; + + List<CollectionFilter> get filters => widget.filters; + + @override + void didUpdateWidget(covariant FilterBar oldWidget) { + super.didUpdateWidget(oldWidget); + final current = widget.filters; + final existing = oldWidget.filters; + final removed = existing.where((filter) => !current.contains(filter)).toList(); + final added = current.where((filter) => !existing.contains(filter)).toList(); + final listState = _animatedListKey.currentState; + removed.forEach((filter) { + final index = existing.indexOf(filter); + existing.removeAt(index); + // only animate item removal when triggered by a user interaction with the chip, + // not from automatic chip replacement following chip selection + final animate = context.read<Settings>().animate && _userTappedFilter == filter; + listState!.removeItem( + index, + animate + ? (context, animation) { + animation = animation.drive(CurveTween(curve: Curves.easeInOutBack)); + return FadeTransition( + opacity: animation, + child: SizeTransition( + axis: Axis.horizontal, + sizeFactor: animation, + child: ScaleTransition( + scale: animation, + child: _buildChip(filter), + ), + ), + ); + } + : (context, animation) => const SizedBox(), + duration: animate ? ADurations.filterBarRemovalAnimation : Duration.zero, + ); + }); + added.forEach((filter) { + final index = current.indexOf(filter); + listState!.insertItem( + index, + duration: Duration.zero, + ); + }); + _userTappedFilter = null; + } + + @override + Widget build(BuildContext context) { + return Container( + // specify transparent as a workaround to prevent + // chip border clipping when the floating app bar is fading + padding: FilterBar.padding, + color: Colors.transparent, + height: FilterBar.preferredHeight, + child: AnimatedList( + key: _animatedListKey, + initialItemCount: filters.length, + scrollDirection: Axis.horizontal, + padding: FilterBar.rowPadding, + itemBuilder: (context, index, animation) { + if (index >= filters.length) return const SizedBox(); + return _buildChip(filters.toList()[index]); + }, + ), + ); + } + + Widget _buildChip(CollectionFilter filter) { + final onTap = widget.onTap != null + ? (filter) { + _userTappedFilter = filter; + widget.onTap?.call(filter); + } + : null; + final onRemove = widget.onRemove != null + ? (filter) { + _userTappedFilter = filter; + widget.onRemove?.call(filter); + } + : null; + return _Chip( + filter: filter, + single: filters.length == 1, + interactive: widget.interactive, + onTap: onTap, + onRemove: onRemove, + ); + } +} + +class _Chip extends StatelessWidget { + final CollectionFilter filter; + final bool single, interactive; + final AFilterCallback? onTap, onRemove; + + const _Chip({ + required this.filter, + required this.single, + required this.interactive, + required this.onTap, + required this.onRemove, + }); + + @override + Widget build(BuildContext context) { + return Padding( + padding: FilterBar.chipPadding, + child: Center( + child: AvesFilterChip( + key: ValueKey(filter), + filter: filter, + maxWidth: single + ? AvesFilterChip.computeMaxWidthForRow( + context, + minChipPerRow: 1, + chipPadding: FilterBar.chipPadding.horizontal, + rowPadding: FilterBar.rowPadding.horizontal + AvesFloatingBar.margin.horizontal, + ) + : null, + heroType: HeroType.always, + onTap: onTap, + onRemove: onRemove, + onLongPress: interactive ? AvesFilterChip.showDefaultLongPressMenu : null, + ), + ), + ); + } +} diff --git a/lib/widgets/collection/grid/headers/album.dart b/lib/widgets/collection/grid/headers/album.dart new file mode 100644 index 0000000..8adb22f --- /dev/null +++ b/lib/widgets/collection/grid/headers/album.dart @@ -0,0 +1,61 @@ +import 'package:aves/model/covers.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/model/source/section_keys.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/utils/android_file_utils.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/grid/header.dart'; +import 'package:aves/widgets/common/identity/aves_icons.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; + +class AlbumSectionHeader extends StatelessWidget { + final String? directory, albumName; + final bool selectable; + + const AlbumSectionHeader({ + super.key, + required this.directory, + required this.albumName, + required this.selectable, + }); + + @override + Widget build(BuildContext context) { + Widget? albumIcon; + final _directory = directory; + if (_directory != null) { + albumIcon = IconUtils.getAlbumIcon(context: context, albumPath: _directory); + if (albumIcon != null) { + albumIcon = RepaintBoundary( + child: albumIcon, + ); + } + } + return SectionHeader<AvesEntry>( + sectionKey: EntryAlbumSectionKey(_directory), + leading: albumIcon, + title: albumName ?? context.l10n.sectionUnknown, + trailing: _directory != null && androidFileUtils.isOnRemovableStorage(_directory) + ? const Icon( + AIcons.storageCard, + size: 16, + color: Color(0xFF757575), + ) + : null, + selectable: selectable, + ); + } + + static double getPreferredHeight(BuildContext context, double maxWidth, CollectionSource source, EntryAlbumSectionKey sectionKey) { + final directory = sectionKey.directory ?? context.l10n.sectionUnknown; + return SectionHeader.getPreferredHeight( + context: context, + maxWidth: maxWidth, + title: source.getStoredAlbumDisplayName(context, directory), + hasLeading: covers.effectiveAlbumType(directory) != AlbumType.regular, + hasTrailing: androidFileUtils.isOnRemovableStorage(directory), + ); + } +} diff --git a/lib/widgets/collection/grid/headers/any.dart b/lib/widgets/collection/grid/headers/any.dart new file mode 100644 index 0000000..0360041 --- /dev/null +++ b/lib/widgets/collection/grid/headers/any.dart @@ -0,0 +1,98 @@ +import 'dart:math'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/model/source/section_keys.dart'; +import 'package:aves/widgets/collection/grid/headers/album.dart'; +import 'package:aves/widgets/collection/grid/headers/date.dart'; +import 'package:aves/widgets/collection/grid/headers/rating.dart'; +import 'package:aves/widgets/common/grid/header.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; + +class CollectionSectionHeader extends StatelessWidget { + final CollectionLens collection; + final SectionKey sectionKey; + final double height; + final bool selectable; + + const CollectionSectionHeader({ + super.key, + required this.collection, + required this.sectionKey, + required this.height, + required this.selectable, + }); + + @override + Widget build(BuildContext context) { + final header = _buildHeader(context); + return header != null + ? SizedBox( + height: height, + child: header, + ) + : const SizedBox(); + } + + Widget? _buildHeader(BuildContext context) { + switch (collection.sortFactor) { + case EntrySortFactor.date: + switch (collection.sectionFactor) { + case EntrySectionFactor.album: + return _buildAlbumHeader(context); + case EntrySectionFactor.month: + return MonthSectionHeader<AvesEntry>( + key: ValueKey(sectionKey), + date: (sectionKey as EntryDateSectionKey).date, + selectable: selectable, + ); + case EntrySectionFactor.day: + return DaySectionHeader<AvesEntry>( + key: ValueKey(sectionKey), + date: (sectionKey as EntryDateSectionKey).date, + selectable: selectable, + ); + case EntrySectionFactor.none: + break; + } + case EntrySortFactor.name: + case EntrySortFactor.path: + return _buildAlbumHeader(context); + case EntrySortFactor.rating: + return RatingSectionHeader<AvesEntry>( + key: ValueKey(sectionKey), + rating: (sectionKey as EntryRatingSectionKey).rating, + selectable: selectable, + ); + case EntrySortFactor.size: + case EntrySortFactor.duration: + break; + } + return null; + } + + Widget _buildAlbumHeader(BuildContext context) { + final source = collection.source; + final directory = (sectionKey as EntryAlbumSectionKey).directory; + return AlbumSectionHeader( + key: ValueKey(sectionKey), + directory: directory, + albumName: directory != null ? source.getStoredAlbumDisplayName(context, directory) : null, + selectable: selectable, + ); + } + + static double getPreferredHeight(BuildContext context, double maxWidth, CollectionSource source, SectionKey sectionKey) { + var headerExtent = 0.0; + if (sectionKey is EntryAlbumSectionKey) { + // only compute height for album headers, as they're the only likely ones to split on multiple lines + headerExtent = AlbumSectionHeader.getPreferredHeight(context, maxWidth, source, sectionKey); + } + + final textScaler = MediaQuery.textScalerOf(context); + headerExtent = max(headerExtent, textScaler.scale(SectionHeader.leadingSize.height)) + SectionHeader.padding.vertical + SectionHeader.margin.vertical; + return headerExtent; + } +} diff --git a/lib/widgets/collection/grid/headers/date.dart b/lib/widgets/collection/grid/headers/date.dart new file mode 100644 index 0000000..2dd5138 --- /dev/null +++ b/lib/widgets/collection/grid/headers/date.dart @@ -0,0 +1,87 @@ +import 'package:aves/model/source/section_keys.dart'; +import 'package:aves/utils/time_utils.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/grid/header.dart'; +import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; + +class DaySectionHeader<T> extends StatelessWidget { + final DateTime? date; + final bool selectable; + + const DaySectionHeader({ + super.key, + required this.date, + required this.selectable, + }); + + // Examples (en_US): + // `MMMMd`: `April 15` + // `yMMMMd`: `April 15, 2020` + // `MMMEd`: `Wed, Apr 15` + // `yMMMEd`: `Wed, Apr 15, 2020` + // `MMMMEEEEd`: `Wednesday, April 15` + // `yMMMMEEEEd`: `Wednesday, April 15, 2020` + // `MEd`: `Wed, 4/15` + // `yMEd`: `Wed, 4/15/2020` + + // Examples (ko): + // `MMMMd`: `1월 26일` + // `yMMMMd`: `2021년 1월 26일` + // `MMMEd`: `1월 26일 (화)` + // `yMMMEd`: `2021년 1월 26일 (화)` + // `MMMMEEEEd`: `1월 26일 화요일` + // `yMMMMEEEEd`: `2021년 1월 26일 화요일` + // `MEd`: `1. 26. (화)` + // `yMEd`: `2021. 1. 26. (화)` + + static String _formatDate(BuildContext context, DateTime? date) { + final l10n = context.l10n; + if (date == null) return l10n.sectionUnknown; + if (date.isToday) return l10n.dateToday; + if (date.isYesterday) return l10n.dateYesterday; + + final locale = context.locale; + if (date.isThisYear) return '${DateFormat.MMMMd(locale).format(date)} (${DateFormat.E(locale).format(date)})'; + return '${DateFormat.yMMMMd(locale).format(date)} (${DateFormat.E(locale).format(date)})'; + } + + @override + Widget build(BuildContext context) { + return SectionHeader<T>( + sectionKey: EntryDateSectionKey(date), + title: _formatDate(context, date), + selectable: selectable, + ); + } +} + +class MonthSectionHeader<T> extends StatelessWidget { + final DateTime? date; + final bool selectable; + + const MonthSectionHeader({ + super.key, + required this.date, + required this.selectable, + }); + + static String _formatDate(BuildContext context, DateTime? date) { + final l10n = context.l10n; + if (date == null) return l10n.sectionUnknown; + if (date.isThisMonth) return l10n.dateThisMonth; + + final locale = context.locale; + final localized = date.isThisYear ? DateFormat.MMMM(locale).format(date) : DateFormat.yMMMM(locale).format(date); + return '${localized.substring(0, 1).toUpperCase()}${localized.substring(1)}'; + } + + @override + Widget build(BuildContext context) { + return SectionHeader<T>( + sectionKey: EntryDateSectionKey(date), + title: _formatDate(context, date), + selectable: selectable, + ); + } +} diff --git a/lib/widgets/collection/grid/headers/rating.dart b/lib/widgets/collection/grid/headers/rating.dart new file mode 100644 index 0000000..4cdfc3e --- /dev/null +++ b/lib/widgets/collection/grid/headers/rating.dart @@ -0,0 +1,24 @@ +import 'package:aves/model/filters/rating.dart'; +import 'package:aves/model/source/section_keys.dart'; +import 'package:aves/widgets/common/grid/header.dart'; +import 'package:flutter/material.dart'; + +class RatingSectionHeader<T> extends StatelessWidget { + final int rating; + final bool selectable; + + const RatingSectionHeader({ + super.key, + required this.rating, + required this.selectable, + }); + + @override + Widget build(BuildContext context) { + return SectionHeader<T>( + sectionKey: EntryRatingSectionKey(rating), + title: RatingFilter.formatRating(context, rating), + selectable: selectable, + ); + } +} diff --git a/lib/widgets/collection/grid/list_details.dart b/lib/widgets/collection/grid/list_details.dart new file mode 100644 index 0000000..0c30a73 --- /dev/null +++ b/lib/widgets/collection/grid/list_details.dart @@ -0,0 +1,109 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/location.dart'; +import 'package:aves/model/settings/enums/coordinate_format.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/format.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/theme/text.dart'; +import 'package:aves/utils/collection_utils.dart'; +import 'package:aves/utils/file_utils.dart'; +import 'package:aves/widgets/collection/grid/list_details_theme.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/fx/borders.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class EntryListDetails extends StatelessWidget { + final AvesEntry entry; + + const EntryListDetails({ + super.key, + required this.entry, + }); + + @override + Widget build(BuildContext context) { + final detailsTheme = context.watch<EntryListDetailsThemeData>(); + + return Container( + padding: EntryListDetailsTheme.contentPadding, + foregroundDecoration: BoxDecoration( + border: Border(top: AvesBorder.straightSide(context)), + ), + margin: EntryListDetailsTheme.contentMargin, + child: IconTheme.merge( + data: detailsTheme.iconTheme, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + entry.bestTitle ?? context.l10n.viewerInfoUnknown, + style: detailsTheme.titleStyle, + softWrap: false, + overflow: detailsTheme.titleMaxLines == 1 ? TextOverflow.fade : TextOverflow.ellipsis, + maxLines: detailsTheme.titleMaxLines, + ), + const SizedBox(height: EntryListDetailsTheme.titleDetailPadding), + if (detailsTheme.showDate) _buildDateRow(context, detailsTheme.captionStyle), + if (detailsTheme.showLocation && entry.hasGps) _buildLocationRow(context, detailsTheme.captionStyle), + ], + ), + ), + ); + } + + Widget _buildRow(List<InlineSpan> spans, TextStyle style) { + return Text.rich( + TextSpan( + children: spans, + ), + style: style, + softWrap: false, + overflow: TextOverflow.fade, + ); + } + + WidgetSpan _buildIconSpan(IconData icon, {EdgeInsetsDirectional padding = EdgeInsetsDirectional.zero}) { + return WidgetSpan( + alignment: PlaceholderAlignment.middle, + child: Padding( + padding: const EdgeInsetsDirectional.only(end: 8, bottom: 1) + padding, + child: Icon(icon), + ), + ); + } + + Widget _buildDateRow(BuildContext context, TextStyle style) { + final locale = context.locale; + final use24hour = MediaQuery.alwaysUse24HourFormatOf(context); + final date = entry.bestDate; + final dateText = date != null ? formatDateTime(date, locale, use24hour) : AText.valueNotAvailable; + + final size = entry.stackedEntries?.map((v) => v.sizeBytes).sum ?? entry.sizeBytes; + final sizeText = size != null ? formatFileSize(locale, size) : AText.valueNotAvailable; + + return Wrap( + spacing: 8, + children: [ + _buildRow( + [_buildIconSpan(AIcons.date), TextSpan(text: dateText)], + style, + ), + _buildRow( + [_buildIconSpan(AIcons.size), TextSpan(text: sizeText)], + style, + ), + ], + ); + } + + Widget _buildLocationRow(BuildContext context, TextStyle style) { + final location = entry.hasAddress ? entry.shortAddress : settings.coordinateFormat.format(context, entry.latLng!); + + return _buildRow( + [_buildIconSpan(AIcons.location), TextSpan(text: location)], + style, + ); + } +} diff --git a/lib/widgets/collection/grid/list_details_theme.dart b/lib/widgets/collection/grid/list_details_theme.dart new file mode 100644 index 0000000..bc93023 --- /dev/null +++ b/lib/widgets/collection/grid/list_details_theme.dart @@ -0,0 +1,113 @@ +import 'package:aves/theme/format.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/tile_extent_controller.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:provider/provider.dart'; + +class EntryListDetailsTheme extends StatelessWidget { + final double extent; + final Widget child; + + static const EdgeInsets contentMargin = EdgeInsets.symmetric(horizontal: 8); + static const EdgeInsets contentPadding = EdgeInsets.symmetric(vertical: 4); + static const double titleDetailPadding = 6; + + const EntryListDetailsTheme({ + super.key, + required this.extent, + required this.child, + }); + + @override + Widget build(BuildContext context) { + return ProxyProvider<MediaQueryData, EntryListDetailsThemeData>( + update: (context, mq, previous) { + final use24hour = mq.alwaysUse24HourFormat; + final textScaler = mq.textScaler; + + final textTheme = Theme.of(context).textTheme; + var titleStyle = textTheme.bodyMedium!; + var captionStyle = textTheme.bodySmall!; + // specify `height` for accurate paragraph height measurement + final defaultTextHeight = DefaultTextStyle.of(context).style.height; + titleStyle = titleStyle.copyWith(height: titleStyle.height ?? defaultTextHeight); + captionStyle = captionStyle.copyWith(height: captionStyle.height ?? defaultTextHeight); + + final titleLineHeightParagraph = RenderParagraph( + TextSpan( + text: 'Fake Title', + style: titleStyle, + ), + textDirection: TextDirection.ltr, + textScaler: textScaler, + )..layout(const BoxConstraints(), parentUsesSize: true); + final titleLineHeight = titleLineHeightParagraph.getMaxIntrinsicHeight(double.infinity); + titleLineHeightParagraph.dispose(); + + final captionLineHeightParagraph = RenderParagraph( + TextSpan( + text: formatDateTime(DateTime.now(), context.locale, use24hour), + style: captionStyle, + ), + textDirection: TextDirection.ltr, + textScaler: textScaler, + )..layout(const BoxConstraints(), parentUsesSize: true); + final captionLineHeight = captionLineHeightParagraph.getMaxIntrinsicHeight(double.infinity); + + var titleMaxLines = 1; + var showDate = false; + var showLocation = false; + + final gridExtentMin = context.read<TileExtentController>().effectiveExtentMin; + final isMinExtent = (extent - gridExtentMin).abs() < precisionErrorTolerance; + + var availableHeight = extent - contentMargin.vertical - contentPadding.vertical; + if (availableHeight >= titleLineHeight + titleDetailPadding + captionLineHeight) { + showDate = true; + availableHeight -= titleLineHeight + titleDetailPadding + captionLineHeight; + if (availableHeight >= captionLineHeight) { + showLocation = true; + availableHeight -= captionLineHeight; + titleMaxLines += availableHeight ~/ titleLineHeight; + } + } + + return EntryListDetailsThemeData( + extent: extent, + titleMaxLines: titleMaxLines, + isMinExtent: isMinExtent, + showDate: showDate, + showLocation: showLocation, + titleStyle: titleStyle, + captionStyle: captionStyle, + iconTheme: IconThemeData( + color: captionStyle.color, + size: textScaler.scale(captionStyle.fontSize!), + ), + ); + }, + child: child, + ); + } +} + +class EntryListDetailsThemeData { + final double extent; + final int titleMaxLines; + final bool isMinExtent, showDate, showLocation; + final TextStyle titleStyle, captionStyle; + final IconThemeData iconTheme; + + const EntryListDetailsThemeData({ + required this.extent, + required this.titleMaxLines, + required this.isMinExtent, + required this.showDate, + required this.showLocation, + required this.titleStyle, + required this.captionStyle, + required this.iconTheme, + }); +} diff --git a/lib/widgets/collection/grid/section_layout.dart b/lib/widgets/collection/grid/section_layout.dart new file mode 100644 index 0000000..1156b61 --- /dev/null +++ b/lib/widgets/collection/grid/section_layout.dart @@ -0,0 +1,51 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/model/source/section_keys.dart'; +import 'package:aves/widgets/collection/grid/headers/any.dart'; +import 'package:aves/widgets/common/grid/sections/provider.dart'; +import 'package:flutter/material.dart'; + +class SectionedEntryListLayoutProvider extends SectionedListLayoutProvider<AvesEntry> { + final CollectionLens collection; + final bool selectable; + + SectionedEntryListLayoutProvider({ + super.key, + required this.collection, + required this.selectable, + required super.scrollableWidth, + required super.tileLayout, + required super.columnCount, + required super.spacing, + required super.horizontalPadding, + required double tileExtent, + required super.tileBuilder, + required super.tileAnimationDelay, + required super.child, + }) : super( + tileWidth: tileExtent, + tileHeight: tileExtent, + coverRatioResolver: (item) => item.displayAspectRatio, + ); + + @override + bool get showHeaders => collection.showHeaders; + + @override + Map<SectionKey, List<AvesEntry>> get sections => collection.sections; + + @override + double getHeaderExtent(BuildContext context, SectionKey sectionKey) { + return CollectionSectionHeader.getPreferredHeight(context, scrollableWidth, collection.source, sectionKey); + } + + @override + Widget buildHeader(BuildContext context, SectionKey sectionKey, double headerExtent) { + return CollectionSectionHeader( + collection: collection, + sectionKey: sectionKey, + height: headerExtent, + selectable: selectable, + ); + } +} diff --git a/lib/widgets/collection/grid/tile.dart b/lib/widgets/collection/grid/tile.dart new file mode 100644 index 0000000..c9400c7 --- /dev/null +++ b/lib/widgets/collection/grid/tile.dart @@ -0,0 +1,144 @@ +import 'package:aves/app_mode.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/selection.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/services/intent_service.dart'; +import 'package:aves/widgets/collection/grid/list_details.dart'; +import 'package:aves/widgets/collection/grid/list_details_theme.dart'; +import 'package:aves/widgets/common/grid/scaling.dart'; +import 'package:aves/widgets/common/providers/viewer_entry_provider.dart'; +import 'package:aves/widgets/common/thumbnail/decorated.dart'; +import 'package:aves/widgets/common/thumbnail/notifications.dart'; +import 'package:aves/widgets/viewer/hero.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class InteractiveTile extends StatelessWidget { + final CollectionLens collection; + final AvesEntry entry; + final double thumbnailExtent; + final TileLayout tileLayout; + final ValueNotifier<bool>? isScrollingNotifier; + + const InteractiveTile({ + super.key, + required this.collection, + required this.entry, + required this.thumbnailExtent, + required this.tileLayout, + this.isScrollingNotifier, + }); + + @override + Widget build(BuildContext context) { + return InkWell( + onTap: () { + final appMode = context.read<ValueNotifier<AppMode>>().value; + switch (appMode) { + case AppMode.main: + final selection = context.read<Selection<AvesEntry>>(); + if (selection.isSelecting) { + selection.toggleSelection(entry); + } else { + OpenViewerNotification(entry).dispatch(context); + } + case AppMode.pickSingleMediaExternal: + IntentService.submitPickedItems([entry.uri]); + case AppMode.pickMultipleMediaExternal: + final selection = context.read<Selection<AvesEntry>>(); + selection.toggleSelection(entry); + case AppMode.pickFilteredMediaInternal: + case AppMode.pickUnfilteredMediaInternal: + Navigator.maybeOf(context)?.pop(entry); + default: + break; + } + }, + child: MetaData( + metaData: ScalerMetadata(entry), + child: Tile( + entry: entry, + thumbnailExtent: thumbnailExtent, + tileLayout: tileLayout, + selectable: true, + highlightable: true, + isScrollingNotifier: isScrollingNotifier, + heroTagger: () => EntryHeroInfo(collection, entry).tag, + ), + ), + ); + } +} + +class Tile extends StatelessWidget { + final AvesEntry entry; + final double thumbnailExtent; + final TileLayout tileLayout; + final bool selectable, highlightable; + final ValueNotifier<bool>? isScrollingNotifier; + final Object? Function()? heroTagger; + + const Tile({ + super.key, + required this.entry, + required this.thumbnailExtent, + required this.tileLayout, + this.selectable = false, + this.highlightable = false, + this.isScrollingNotifier, + this.heroTagger, + }); + + @override + Widget build(BuildContext context) { + switch (tileLayout) { + case TileLayout.mosaic: + case TileLayout.grid: + return _buildThumbnail(); + case TileLayout.list: + return Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + SizedBox.square( + dimension: context.select<EntryListDetailsThemeData, double>((v) => v.extent), + child: _buildThumbnail(), + ), + Expanded( + child: EntryListDetails( + entry: entry, + ), + ), + ], + ); + } + } + + Widget _buildThumbnail() => DecoratedThumbnail( + entry: entry, + tileExtent: thumbnailExtent, + isMosaic: tileLayout == TileLayout.mosaic, + // when the user is scrolling faster than we can retrieve the thumbnails, + // the retrieval task queue can pile up for thumbnails that got disposed + // in this case we pause the image retrieval task to get it out of the queue + cancellableNotifier: isScrollingNotifier, + selectable: selectable, + highlightable: highlightable, + heroTagger: heroTagger, + // do not use a hero placeholder but hide the thumbnail matching the viewer entry, + // so that it can hero out on an entry and come back with a hero to a different entry + heroPlaceholderBuilder: (context, heroSize, child) => child, + imageDecorator: (context, child) { + return Selector<ViewerEntryNotifier, bool>( + selector: (context, v) => v.value == entry, + builder: (context, isViewerEntry, child) { + return Visibility.maintain( + visible: !isViewerEntry, + child: child!, + ); + }, + child: child, + ); + }, + ); +} diff --git a/lib/widgets/collection/loading.dart b/lib/widgets/collection/loading.dart new file mode 100644 index 0000000..390752e --- /dev/null +++ b/lib/widgets/collection/loading.dart @@ -0,0 +1,50 @@ +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/model/source/events.dart'; +import 'package:aves/widgets/common/action_mixins/feedback.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/empty.dart'; +import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; + +class LoadingEmptyContent extends StatelessWidget { + final CollectionSource source; + + const LoadingEmptyContent({ + super.key, + required this.source, + }); + + @override + Widget build(BuildContext context) { + final countFormatter = NumberFormat.decimalPattern(context.locale); + final progressTextStyle = TextStyle( + color: Theme.of(context).colorScheme.primary.withValues(alpha: .5), + fontSize: 18, + ); + + return EmptyContent( + text: context.l10n.sourceStateLoading, + bottom: Padding( + padding: const EdgeInsets.only(top: 16), + child: Stack( + alignment: Alignment.center, + children: [ + const ReportProgressIndicator(), + ValueListenableBuilder<ProgressEvent>( + valueListenable: source.progressNotifier, + builder: (context, progress, snapshot) { + final done = progress.done; + return done > 0 + ? Text( + countFormatter.format(done), + style: progressTextStyle, + ) + : const SizedBox(); + }, + ), + ], + ), + ), + ); + } +} diff --git a/lib/widgets/collection/query_bar.dart b/lib/widgets/collection/query_bar.dart new file mode 100644 index 0000000..cc50804 --- /dev/null +++ b/lib/widgets/collection/query_bar.dart @@ -0,0 +1,75 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/selection.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/widgets/common/basic/query_bar.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class EntryQueryBar extends StatefulWidget { + final ValueNotifier<String> queryNotifier; + final FocusNode focusNode; + + const EntryQueryBar({ + super.key, + required this.queryNotifier, + required this.focusNode, + }); + + @override + State<EntryQueryBar> createState() => _EntryQueryBarState(); + + static double getPreferredHeight(TextScaler textScaler) => QueryBar.getPreferredHeight(textScaler); +} + +class _EntryQueryBarState extends State<EntryQueryBar> { + @override + void initState() { + super.initState(); + _registerWidget(widget); + } + + @override + void didUpdateWidget(covariant EntryQueryBar oldWidget) { + super.didUpdateWidget(oldWidget); + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + + @override + void dispose() { + _unregisterWidget(widget); + super.dispose(); + } + + void _registerWidget(EntryQueryBar widget) { + widget.queryNotifier.addListener(_onQueryChanged); + } + + void _unregisterWidget(EntryQueryBar widget) { + widget.queryNotifier.removeListener(_onQueryChanged); + } + + @override + Widget build(BuildContext context) { + final textScaler = MediaQuery.textScalerOf(context); + return Container( + height: EntryQueryBar.getPreferredHeight(textScaler), + alignment: Alignment.topCenter, + child: Selector<Selection<AvesEntry>, bool>( + selector: (context, selection) => !selection.isSelecting, + builder: (context, editable, child) => QueryBar( + queryNotifier: widget.queryNotifier, + focusNode: widget.focusNode, + hintText: context.l10n.collectionSearchTitlesHintText, + editable: editable, + ), + ), + ); + } + + void _onQueryChanged() { + final query = widget.queryNotifier.value; + context.read<CollectionLens>().setLiveQuery(query); + } +} diff --git a/lib/widgets/common/action_controls/quick_choosers/album_chooser.dart b/lib/widgets/common/action_controls/quick_choosers/album_chooser.dart new file mode 100644 index 0000000..da5a017 --- /dev/null +++ b/lib/widgets/common/action_controls/quick_choosers/album_chooser.dart @@ -0,0 +1,51 @@ +import 'dart:async'; + +import 'package:aves/model/filters/covered/stored_album.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/widgets/common/action_controls/quick_choosers/common/menu.dart'; +import 'package:aves/widgets/common/action_controls/quick_choosers/filter_quick_chooser_mixin.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class AlbumQuickChooser extends StatelessWidget with FilterQuickChooserMixin<String> { + final ValueNotifier<String?> valueNotifier; + @override + final List<String> options; + final bool blurred; + final PopupMenuPosition chooserPosition; + final Stream<Offset> pointerGlobalPosition; + + const AlbumQuickChooser({ + super.key, + required this.valueNotifier, + required this.options, + required this.blurred, + required this.chooserPosition, + required this.pointerGlobalPosition, + }); + + @override + Widget build(BuildContext context) { + return MenuQuickChooser<String>( + valueNotifier: valueNotifier, + options: options, + autoReverse: true, + blurred: blurred, + chooserPosition: chooserPosition, + pointerGlobalPosition: pointerGlobalPosition, + maxTotalOptionCount: FilterQuickChooserMixin.maxTotalOptionCount, + itemHeight: computeItemHeight(context), + contentWidth: computeLargestItemWidth, + itemBuilder: itemBuilder, + emptyBuilder: (context) => Text(context.l10n.albumEmpty), + ); + } + + @override + CollectionFilter buildFilter(BuildContext context, String option) { + final source = context.read<CollectionSource>(); + return StoredAlbumFilter(option, source.getStoredAlbumDisplayName(context, option)); + } +} diff --git a/lib/widgets/common/action_controls/quick_choosers/common/button.dart b/lib/widgets/common/action_controls/quick_choosers/common/button.dart new file mode 100644 index 0000000..fadcaa8 --- /dev/null +++ b/lib/widgets/common/action_controls/quick_choosers/common/button.dart @@ -0,0 +1,150 @@ +import 'dart:async'; + +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/widgets/common/action_controls/quick_choosers/common/route_layout.dart'; +import 'package:aves/widgets/common/basic/gestures/gesture_detector.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +abstract class ChooserQuickButton<T> extends StatefulWidget { + final bool blurred; + final ValueSetter<T>? onChooserValue; + final FocusNode? focusNode; + final VoidCallback? onPressed; + + const ChooserQuickButton({ + super.key, + required this.blurred, + this.onChooserValue, + this.focusNode, + required this.onPressed, + }); +} + +abstract class ChooserQuickButtonState<T extends ChooserQuickButton<U>, U> extends State<T> with SingleTickerProviderStateMixin { + AnimationController? _animationController; + CurvedAnimation? _animation; + OverlayEntry? _chooserOverlayEntry; + final ValueNotifier<U?> _chooserValueNotifier = ValueNotifier(null); + final StreamController<LongPressMoveUpdateDetails> _moveUpdateStreamController = StreamController.broadcast(); + + Widget get icon; + + String get tooltip; + + U? get defaultValue => null; + + Duration get animationDuration => context.read<DurationsData>().quickChooserAnimation; + + Curve get animationCurve => Curves.easeOutQuad; + + bool get hasChooser => widget.onChooserValue != null; + + Widget buildChooser(Animation<double> animation, PopupMenuPosition chooserPosition); + + ValueNotifier<U?> get chooserValueNotifier => _chooserValueNotifier; + + Stream<Offset> get pointerGlobalPosition => _moveUpdateStreamController.stream.map((event) => event.globalPosition); + + @override + void dispose() { + _animation?.dispose(); + _animationController?.dispose(); + _clearChooserOverlayEntry(); + _chooserValueNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final _hasChooser = hasChooser; + + Widget child = IconButton( + icon: icon, + onPressed: widget.onPressed, + focusNode: widget.focusNode, + tooltip: _hasChooser ? null : tooltip, + ); + if (_hasChooser) { + child = Semantics( + tooltip: tooltip, + child: child, + ); + } + + final theme = Theme.of(context); + final colorScheme = theme.colorScheme; + return Theme( + data: theme.copyWith( + colorScheme: colorScheme.copyWith( + onSurfaceVariant: colorScheme.onSurface, + ), + ), + child: AGestureDetector( + behavior: HitTestBehavior.opaque, + onLongPressStart: _hasChooser ? _showChooser : null, + onLongPressMoveUpdate: _hasChooser ? _moveUpdateStreamController.add : null, + onLongPressEnd: _hasChooser + ? (details) { + _clearChooserOverlayEntry(); + final selectedValue = _chooserValueNotifier.value; + if (selectedValue != null) { + widget.onChooserValue?.call(selectedValue); + } + } + : null, + onLongPressCancel: _clearChooserOverlayEntry, + longPressTimeout: settings.longPressTimeout, + child: child, + ), + ); + } + + void _clearChooserOverlayEntry() { + _chooserOverlayEntry + ?..remove() + ..dispose(); + _chooserOverlayEntry = null; + } + + void _showChooser(LongPressStartDetails details) { + final overlay = Overlay.of(context); + final triggerBox = context.findRenderObject() as RenderBox; + final overlayBox = overlay.context.findRenderObject() as RenderBox; + final triggerRect = RelativeRect.fromRect( + triggerBox.localToGlobal(Offset.zero, ancestor: overlayBox) & triggerBox.size, + Offset.zero & overlayBox.size, + ); + + _chooserValueNotifier.value = defaultValue; + _chooserOverlayEntry = OverlayEntry( + builder: (context) { + final mq = MediaQuery.of(context); + final chooserPosition = (details.globalPosition.dy > mq.size.height / 2) ? PopupMenuPosition.over : PopupMenuPosition.under; + return CustomSingleChildLayout( + delegate: QuickChooserRouteLayout( + triggerRect, + chooserPosition, + mq.padding, + DisplayFeatureSubScreen.avoidBounds(mq).toSet(), + ), + child: buildChooser(_animation!, chooserPosition), + ); + }, + ); + if (_animationController == null) { + _animationController = AnimationController( + duration: animationDuration, + vsync: this, + ); + _animation = CurvedAnimation( + parent: _animationController!, + curve: animationCurve, + ); + } + _animationController!.reset(); + overlay.insert(_chooserOverlayEntry!); + _animationController!.forward(); + } +} diff --git a/lib/widgets/common/action_controls/quick_choosers/common/menu.dart b/lib/widgets/common/action_controls/quick_choosers/common/menu.dart new file mode 100644 index 0000000..6866085 --- /dev/null +++ b/lib/widgets/common/action_controls/quick_choosers/common/menu.dart @@ -0,0 +1,318 @@ +import 'dart:async'; +import 'dart:math'; + +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/action_controls/quick_choosers/common/quick_chooser.dart'; +import 'package:aves_ui/aves_ui.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:flutter_staggered_animations/flutter_staggered_animations.dart'; +import 'package:provider/provider.dart'; + +class MenuQuickChooser<T> extends StatefulWidget { + final ValueNotifier<T?> valueNotifier; + final List<T> options; + final bool autoReverse; + final bool blurred; + final PopupMenuPosition chooserPosition; + final Stream<Offset> pointerGlobalPosition; + final int maxTotalOptionCount; + final double itemHeight; + final double? Function(BuildContext context)? contentWidth; + final Widget Function(BuildContext context, T menuItem) itemBuilder; + final WidgetBuilder? emptyBuilder; + + static const int maxVisibleOptionCount = 5; + + MenuQuickChooser({ + super.key, + required this.valueNotifier, + required List<T> options, + required this.autoReverse, + required this.blurred, + required this.chooserPosition, + required this.pointerGlobalPosition, + this.maxTotalOptionCount = maxVisibleOptionCount, + this.itemHeight = kMinInteractiveDimension, + this.contentWidth, + required this.itemBuilder, + this.emptyBuilder, + }) : options = options.take(maxTotalOptionCount).toList(); + + @override + State<MenuQuickChooser<T>> createState() => _MenuQuickChooserState<T>(); +} + +class _MenuQuickChooserState<T> extends State<MenuQuickChooser<T>> { + final Set<StreamSubscription> _subscriptions = {}; + final ValueNotifier<Rect> _selectedRowRect = ValueNotifier(Rect.zero); + final ScrollController _scrollController = ScrollController(); + int _scrollDirection = 0; + Timer? _scrollUpdateTimer; + Offset _globalPosition = Offset.zero; + + ValueNotifier<T?> get valueNotifier => widget.valueNotifier; + + List<T> get options => widget.options; + + bool get reversed => widget.autoReverse && widget.chooserPosition == PopupMenuPosition.over; + + bool get scrollable => options.length > MenuQuickChooser.maxVisibleOptionCount; + + int get visibleOptionCount => min(MenuQuickChooser.maxVisibleOptionCount, options.length); + + double get itemHeight => widget.itemHeight; + + double get contentHeight => max(0, itemHeight * visibleOptionCount + _intraPadding * (visibleOptionCount - 1)); + + static const double _selectorMargin = 24; + static const double _intraPadding = 8; + static const double _nonScrollablePaddingHeight = _intraPadding; + static const double _scrollerAreaHeight = kMinInteractiveDimension; + static const double scrollMaxPixelPerSecond = 600.0; + static const Duration scrollUpdateInterval = Duration(milliseconds: 100); + + @override + void initState() { + super.initState(); + _registerWidget(widget); + WidgetsBinding.instance.addPostFrameCallback((_) => setState(() {})); + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + _selectedRowRect.value = Rect.fromLTWH(0, MediaQuery.sizeOf(context).height * (reversed ? 1 : -1), 0, 0); + } + + @override + void didUpdateWidget(covariant MenuQuickChooser<T> oldWidget) { + super.didUpdateWidget(oldWidget); + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + + @override + void dispose() { + _unregisterWidget(widget); + _selectedRowRect.dispose(); + _scrollController.dispose(); + _scrollUpdateTimer?.cancel(); + super.dispose(); + } + + void _registerWidget(MenuQuickChooser<T> widget) { + _subscriptions.add(widget.pointerGlobalPosition.listen(_onPointerMove)); + } + + void _unregisterWidget(MenuQuickChooser<T> widget) { + _subscriptions + ..forEach((sub) => sub.cancel()) + ..clear(); + } + + @override + Widget build(BuildContext context) { + return QuickChooser( + blurred: widget.blurred, + child: ValueListenableBuilder<T?>( + valueListenable: valueNotifier, + builder: (context, selectedValue, child) { + final durations = context.watch<DurationsData>(); + + if (options.isEmpty) { + return Padding( + padding: const EdgeInsets.all(16), + child: widget.emptyBuilder?.call(context) ?? const SizedBox(), + ); + } + + return Stack( + children: [ + ValueListenableBuilder<Rect>( + valueListenable: _selectedRowRect, + builder: (context, selectedRowRect, child) { + Widget child = const Center(child: AvesDot()); + child = AnimatedOpacity( + opacity: selectedValue != null ? 1 : 0, + curve: Curves.easeInOutCubic, + duration: const Duration(milliseconds: 200), + child: child, + ); + child = AnimatedPositioned( + top: selectedRowRect.top, + height: selectedRowRect.height, + curve: Curves.easeInOutCubic, + duration: const Duration(milliseconds: 200), + child: child, + ); + return child; + }, + ), + Container( + width: widget.contentWidth?.call(context), + margin: const EdgeInsetsDirectional.only(start: _selectorMargin), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + scrollable + ? ListenableBuilder( + listenable: _scrollController, + builder: (context, child) => Opacity( + opacity: canGoUp ? 1 : .5, + child: child, + ), + child: _buildScrollerArea(AIcons.up), + ) + : const SizedBox(height: _nonScrollablePaddingHeight), + ConstrainedBox( + constraints: BoxConstraints.tightFor(height: contentHeight), + child: ListView.separated( + reverse: reversed, + controller: _scrollController, + shrinkWrap: true, + padding: EdgeInsets.zero, + itemBuilder: (context, index) { + final child = Container( + alignment: AlignmentDirectional.centerStart, + constraints: BoxConstraints.tightFor(height: itemHeight), + child: widget.itemBuilder(context, options[index]), + ); + if (index < MenuQuickChooser.maxVisibleOptionCount) { + // only animate items visible on first render + return AnimationConfiguration.staggeredList( + position: index, + duration: durations.staggeredAnimation * .5, + delay: durations.staggeredAnimationDelay * .5 * timeDilation, + child: SlideAnimation( + verticalOffset: 50.0 * (widget.chooserPosition == PopupMenuPosition.over ? 1 : -1), + child: FadeInAnimation( + child: child, + ), + ), + ); + } else { + return child; + } + }, + separatorBuilder: (context, index) => const SizedBox(height: _intraPadding), + itemCount: options.length, + ), + ), + scrollable + ? ListenableBuilder( + listenable: _scrollController, + builder: (context, child) => Opacity( + opacity: canGoDown ? 1 : .5, + child: child, + ), + child: _buildScrollerArea(AIcons.down), + ) + : const SizedBox(height: _nonScrollablePaddingHeight), + ], + ), + ), + ], + ); + }, + ), + ); + } + + bool get canGoUp { + if (!_scrollController.hasClients) return false; + final position = _scrollController.position; + if (!position.hasContentDimensions) return false; + return reversed ? position.pixels < position.maxScrollExtent : 0 < position.pixels; + } + + bool get canGoDown { + if (!_scrollController.hasClients) return false; + final position = _scrollController.position; + if (!position.hasContentDimensions) return false; + return reversed ? 0 < position.pixels : position.pixels < position.maxScrollExtent; + } + + Widget _buildScrollerArea(IconData icon) { + return Container( + alignment: Alignment.center, + height: _scrollerAreaHeight, + margin: const EdgeInsetsDirectional.only(end: _selectorMargin), + child: Icon(icon), + ); + } + + void _onPointerMove(Offset globalPosition) { + _globalPosition = globalPosition; + final chooserBox = context.findRenderObject() as RenderBox?; + if (chooserBox == null) return; + + final chooserSize = chooserBox.size; + final contentWidth = chooserSize.width; + final chooserBoxEdgeHeight = (QuickChooser.margin.vertical + QuickChooser.padding.vertical) / 2; + + final localPosition = chooserBox.globalToLocal(globalPosition); + final dx = localPosition.dx; + if (!(0 < dx && dx < contentWidth)) { + valueNotifier.value = null; + return; + } + + double dy = localPosition.dy - chooserBoxEdgeHeight; + int scrollDirection = 0; + if (scrollable) { + dy -= _scrollerAreaHeight; + if (-_scrollerAreaHeight < dy && dy < 0) { + scrollDirection = reversed ? 1 : -1; + } else if (contentHeight < dy && dy < contentHeight + _scrollerAreaHeight) { + scrollDirection = reversed ? -1 : 1; + } + _scroll(scrollDirection); + } else { + dy -= _nonScrollablePaddingHeight; + } + + T? selectedValue; + if (scrollDirection == 0 && 0 < dy && dy < contentHeight) { + final visibleOffset = reversed ? contentHeight - dy : dy; + final fullItemHeight = itemHeight + _intraPadding; + final scrollOffset = _scrollController.offset; + final index = (visibleOffset + _intraPadding + scrollOffset) ~/ (fullItemHeight); + if (0 <= index && index < options.length) { + selectedValue = options[index]; + double fromEdge = fullItemHeight * index; + fromEdge += (scrollable ? _scrollerAreaHeight - scrollOffset : _nonScrollablePaddingHeight); + final top = reversed ? chooserSize.height - chooserBoxEdgeHeight - fromEdge - fullItemHeight : fromEdge; + _selectedRowRect.value = Rect.fromLTWH(0, top, contentWidth, itemHeight); + } + } + valueNotifier.value = selectedValue; + } + + void _scroll(int scrollDirection) { + if (scrollDirection == _scrollDirection) return; + _scrollDirection = scrollDirection; + _scrollUpdateTimer?.cancel(); + + final current = _scrollController.offset; + if (scrollDirection == 0) { + _scrollController.jumpTo(current); + return; + } + + final target = scrollDirection > 0 ? _scrollController.position.maxScrollExtent : .0; + if (target != current) { + final distance = target - current; + final millis = distance * 1000 / scrollMaxPixelPerSecond / scrollDirection; + _scrollController.animateTo( + target, + duration: Duration(milliseconds: millis.round()), + curve: Curves.linear, + ); + // use a timer to update the selection, because `_onPointerMove` + // is not called when the pointer stays still while the view is scrolling + _scrollUpdateTimer = Timer.periodic(scrollUpdateInterval, (_) => _onPointerMove(_globalPosition)); + } + } +} diff --git a/lib/widgets/common/action_controls/quick_choosers/common/quick_chooser.dart b/lib/widgets/common/action_controls/quick_choosers/common/quick_chooser.dart new file mode 100644 index 0000000..b1430d8 --- /dev/null +++ b/lib/widgets/common/action_controls/quick_choosers/common/quick_chooser.dart @@ -0,0 +1,47 @@ +import 'package:aves/theme/themes.dart'; +import 'package:aves/widgets/common/fx/blurred.dart'; +import 'package:aves/widgets/common/fx/borders.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:flutter/material.dart'; + +class QuickChooser extends StatelessWidget { + final bool blurred; + final Widget child; + + static const margin = EdgeInsets.all(8); + static const padding = EdgeInsets.symmetric(horizontal: 8); + + const QuickChooser({ + super.key, + required this.blurred, + required this.child, + }); + + @override + Widget build(BuildContext context) { + final brightness = Theme.of(context).brightness; + final backgroundColor = blurred ? Themes.overlayBackgroundColor(brightness: brightness, blurred: blurred) : null; + const borderRadius = BorderRadius.all(AvesDialog.cornerRadius); + return Padding( + padding: margin, + child: BlurredRRect( + enabled: blurred, + borderRadius: borderRadius, + child: Material( + borderRadius: borderRadius, + color: backgroundColor, + child: Ink( + decoration: BoxDecoration( + border: AvesBorder.border(context), + borderRadius: borderRadius, + ), + child: Padding( + padding: padding, + child: child, + ), + ), + ), + ), + ); + } +} diff --git a/lib/widgets/common/action_controls/quick_choosers/common/route_layout.dart b/lib/widgets/common/action_controls/quick_choosers/common/route_layout.dart new file mode 100644 index 0000000..835f691 --- /dev/null +++ b/lib/widgets/common/action_controls/quick_choosers/common/route_layout.dart @@ -0,0 +1,80 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; + +// adapted from Flutter `_PopupMenuRouteLayout` in `/material/popup_menu.dart` +class QuickChooserRouteLayout extends SingleChildLayoutDelegate { + final RelativeRect triggerRect; + final PopupMenuPosition menuPosition; + final EdgeInsets padding; + final Set<Rect> avoidBounds; + + static const double _kMenuScreenPadding = 8.0; + + QuickChooserRouteLayout( + this.triggerRect, + this.menuPosition, + this.padding, + this.avoidBounds, + ); + + @override + BoxConstraints getConstraintsForChild(BoxConstraints constraints) { + return BoxConstraints.loose(constraints.biggest).deflate( + const EdgeInsets.all(_kMenuScreenPadding) + padding, + ); + } + + @override + Offset getPositionForChild(Size size, Size childSize) { + // size: The size of the overlay. + // childSize: The size of the menu, when fully open, as determined by getConstraintsForChild. + + double y; + switch (menuPosition) { + case PopupMenuPosition.over: + y = triggerRect.top - childSize.height; + case PopupMenuPosition.under: + y = size.height - triggerRect.bottom; + } + double x = (triggerRect.left + (size.width - triggerRect.right) - childSize.width) / 2; + final wantedPosition = Offset(x, y); + final originCenter = triggerRect.toRect(Offset.zero & size).center; + final subScreens = DisplayFeatureSubScreen.subScreensInBounds(Offset.zero & size, avoidBounds); + final subScreen = _closestScreen(subScreens, originCenter); + return _fitInsideScreen(subScreen, childSize, wantedPosition); + } + + Rect _closestScreen(Iterable<Rect> screens, Offset point) { + Rect closest = screens.first; + for (final Rect screen in screens) { + if ((screen.center - point).distance < (closest.center - point).distance) { + closest = screen; + } + } + return closest; + } + + Offset _fitInsideScreen(Rect screen, Size childSize, Offset wantedPosition) { + double x = wantedPosition.dx; + double y = wantedPosition.dy; + // Avoid going outside an area defined as the rectangle 8.0 pixels from the + // edge of the screen in every direction. + if (x < screen.left + _kMenuScreenPadding + padding.left) { + x = screen.left + _kMenuScreenPadding + padding.left; + } else if (x + childSize.width > screen.right - _kMenuScreenPadding - padding.right) { + x = screen.right - childSize.width - _kMenuScreenPadding - padding.right; + } + if (y < screen.top + _kMenuScreenPadding + padding.top) { + y = _kMenuScreenPadding + padding.top; + } else if (y + childSize.height > screen.bottom - _kMenuScreenPadding - padding.bottom) { + y = screen.bottom - childSize.height - _kMenuScreenPadding - padding.bottom; + } + + return Offset(x, y); + } + + @override + bool shouldRelayout(QuickChooserRouteLayout oldDelegate) { + return triggerRect != oldDelegate.triggerRect || padding != oldDelegate.padding || !setEquals(avoidBounds, oldDelegate.avoidBounds); + } +} diff --git a/lib/widgets/common/action_controls/quick_choosers/filter_quick_chooser_mixin.dart b/lib/widgets/common/action_controls/quick_choosers/filter_quick_chooser_mixin.dart new file mode 100644 index 0000000..93c9eeb --- /dev/null +++ b/lib/widgets/common/action_controls/quick_choosers/filter_quick_chooser_mixin.dart @@ -0,0 +1,56 @@ +import 'dart:math'; + +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/settings/modules/app.dart'; +import 'package:aves/widgets/common/identity/aves_filter_chip.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; + +mixin FilterQuickChooserMixin<T> { + List<T> get options; + + static const int maxTotalOptionCount = AppSettings.recentFilterHistoryMax; + static const double _chipPadding = AvesFilterChip.defaultPadding; + static const bool _chipAllowGenericIcon = false; + + CollectionFilter buildFilter(BuildContext context, T option); + + Widget itemBuilder(BuildContext context, T option) { + return AvesFilterChip( + filter: buildFilter(context, option), + allowGenericIcon: _chipAllowGenericIcon, + padding: _chipPadding, + maxWidth: double.infinity, + ); + } + + double computeItemHeight(BuildContext context) => AvesFilterChip.minChipHeight; + + double? computeLargestItemWidth(BuildContext context) { + if (options.isEmpty) return null; + + final textStyle = DefaultTextStyle.of(context).style.copyWith( + fontSize: AvesFilterChip.fontSize, + ); + final textDirection = Directionality.of(context); + final textScaler = MediaQuery.textScalerOf(context); + final iconSize = textScaler.scale(AvesFilterChip.iconSize); + + return options.map((option) { + final filter = buildFilter(context, option); + final icon = filter.iconBuilder(context, iconSize, allowGenericIcon: _chipAllowGenericIcon); + final label = filter.getLabel(context); + final paragraph = RenderParagraph( + TextSpan(text: label, style: textStyle), + textDirection: textDirection, + textScaler: textScaler, + )..layout(const BoxConstraints(), parentUsesSize: true); + final labelWidth = paragraph.getMaxIntrinsicWidth(double.infinity); + double chipWidth = labelWidth + _chipPadding * 4; + if (icon != null) { + chipWidth += iconSize + _chipPadding; + } + return max(AvesFilterChip.minChipWidth, chipWidth); + }).reduce(max); + } +} diff --git a/lib/widgets/common/action_controls/quick_choosers/move_button.dart b/lib/widgets/common/action_controls/quick_choosers/move_button.dart new file mode 100644 index 0000000..a3cc61b --- /dev/null +++ b/lib/widgets/common/action_controls/quick_choosers/move_button.dart @@ -0,0 +1,70 @@ +import 'package:aves/model/filters/covered/stored_album.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/action_controls/quick_choosers/album_chooser.dart'; +import 'package:aves/widgets/common/action_controls/quick_choosers/common/button.dart'; +import 'package:aves/widgets/common/action_controls/quick_choosers/filter_quick_chooser_mixin.dart'; +import 'package:aves/widgets/common/providers/media_query_data_provider.dart'; +import 'package:aves/widgets/filter_grids/common/filter_nav_page.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class MoveButton extends ChooserQuickButton<String> { + final bool copy; + + const MoveButton({ + super.key, + required this.copy, + required super.blurred, + super.onChooserValue, + required super.onPressed, + }); + + @override + State<MoveButton> createState() => _MoveButtonState(); +} + +class _MoveButtonState extends ChooserQuickButtonState<MoveButton, String> { + EntryAction get action => widget.copy ? EntryAction.copy : EntryAction.move; + + @override + Widget get icon => action.getIcon(); + + @override + String get tooltip => action.getText(context); + + @override + Widget buildChooser(Animation<double> animation, PopupMenuPosition chooserPosition) { + final source = context.read<CollectionSource>(); + final rawAlbums = source.rawAlbums; + final options = settings.recentDestinationAlbums.where(rawAlbums.contains).toList(); + final takeCount = FilterQuickChooserMixin.maxTotalOptionCount - options.length; + if (takeCount > 0) { + final filters = rawAlbums.whereNot(options.contains).map((album) => StoredAlbumFilter(album, null)).toSet(); + final allMapEntries = filters.map((filter) => FilterGridItem(filter, source.recentEntry(filter))).toList(); + allMapEntries.sort(FilterNavigationPage.compareFiltersByDate); + options.addAll(allMapEntries.take(takeCount).map((v) => v.filter.album)); + } + + return MediaQueryDataProvider( + child: FadeTransition( + opacity: animation, + child: ScaleTransition( + scale: animation, + alignment: chooserPosition == PopupMenuPosition.over ? Alignment.bottomCenter : Alignment.topCenter, + child: AlbumQuickChooser( + valueNotifier: chooserValueNotifier, + options: options, + blurred: widget.blurred, + chooserPosition: chooserPosition, + pointerGlobalPosition: pointerGlobalPosition, + ), + ), + ), + ); + } +} diff --git a/lib/widgets/common/action_controls/quick_choosers/rate_button.dart b/lib/widgets/common/action_controls/quick_choosers/rate_button.dart new file mode 100644 index 0000000..874e2bf --- /dev/null +++ b/lib/widgets/common/action_controls/quick_choosers/rate_button.dart @@ -0,0 +1,47 @@ +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/action_controls/quick_choosers/common/button.dart'; +import 'package:aves/widgets/common/action_controls/quick_choosers/rate_chooser.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; + +class RateButton extends ChooserQuickButton<int> { + const RateButton({ + super.key, + required super.blurred, + super.onChooserValue, + super.focusNode, + required super.onPressed, + }); + + @override + State<RateButton> createState() => _RateButtonState(); +} + +class _RateButtonState extends ChooserQuickButtonState<RateButton, int> { + static const _action = EntryAction.editRating; + + @override + Widget get icon => _action.getIcon(); + + @override + String get tooltip => _action.getText(context); + + @override + int? get defaultValue => 3; + + @override + Widget buildChooser(Animation<double> animation, PopupMenuPosition chooserPosition) { + return FadeTransition( + opacity: animation, + child: ScaleTransition( + scale: animation, + alignment: chooserPosition == PopupMenuPosition.over ? Alignment.bottomCenter : Alignment.topCenter, + child: RateQuickChooser( + blurred: widget.blurred, + valueNotifier: chooserValueNotifier, + pointerGlobalPosition: pointerGlobalPosition, + ), + ), + ); + } +} diff --git a/lib/widgets/common/action_controls/quick_choosers/rate_chooser.dart b/lib/widgets/common/action_controls/quick_choosers/rate_chooser.dart new file mode 100644 index 0000000..687d4ea --- /dev/null +++ b/lib/widgets/common/action_controls/quick_choosers/rate_chooser.dart @@ -0,0 +1,100 @@ +import 'dart:async'; + +import 'package:aves/theme/colors.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/action_controls/quick_choosers/common/quick_chooser.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:flutter/material.dart'; + +class RateQuickChooser extends StatefulWidget { + final bool blurred; + final ValueNotifier<int?> valueNotifier; + final Stream<Offset> pointerGlobalPosition; + + const RateQuickChooser({ + super.key, + required this.blurred, + required this.valueNotifier, + required this.pointerGlobalPosition, + }); + + @override + State<RateQuickChooser> createState() => _RateQuickChooserState(); +} + +class _RateQuickChooserState extends State<RateQuickChooser> { + final Set<StreamSubscription> _subscriptions = {}; + + ValueNotifier<int?> get valueNotifier => widget.valueNotifier; + + @override + void initState() { + super.initState(); + _registerWidget(widget); + } + + @override + void didUpdateWidget(covariant RateQuickChooser oldWidget) { + super.didUpdateWidget(oldWidget); + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + + @override + void dispose() { + _unregisterWidget(widget); + super.dispose(); + } + + void _registerWidget(RateQuickChooser widget) { + _subscriptions.add(widget.pointerGlobalPosition.listen(_onPointerMove)); + } + + void _unregisterWidget(RateQuickChooser widget) { + _subscriptions + ..forEach((sub) => sub.cancel()) + ..clear(); + } + + @override + Widget build(BuildContext context) { + return QuickChooser( + blurred: widget.blurred, + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 8), + child: ValueListenableBuilder<int?>( + valueListenable: valueNotifier, + builder: (context, selectedValue, child) { + final _rating = selectedValue ?? 0; + return Row( + mainAxisSize: MainAxisSize.min, + children: List.generate(5, (i) { + final disabled = _rating < i + 1; + return Padding( + padding: const EdgeInsets.all(4), + child: Icon( + AIcons.rating, + fill: disabled ? 0 : 1, + color: disabled ? AColors.starDisabled : AColors.starEnabled, + ), + ); + }).toList(), + ); + }, + ), + ), + ); + } + + void _onPointerMove(Offset globalPosition) { + final padding = QuickChooser.margin.horizontal + QuickChooser.padding.horizontal; + + final chooserBox = context.findRenderObject() as RenderBox; + final chooserSize = chooserBox.size; + final contentWidth = chooserSize.width - padding; + + final local = chooserBox.globalToLocal(globalPosition); + final t = (local.dx - padding / 2) / contentWidth; + valueNotifier.value = (5 * (context.isRtl ? 1 - t : t)).ceil().clamp(0, 5); + } +} diff --git a/lib/widgets/common/action_controls/quick_choosers/share_button.dart b/lib/widgets/common/action_controls/quick_choosers/share_button.dart new file mode 100644 index 0000000..df22d7b --- /dev/null +++ b/lib/widgets/common/action_controls/quick_choosers/share_button.dart @@ -0,0 +1,61 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/multipage.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/action_controls/quick_choosers/common/button.dart'; +import 'package:aves/widgets/common/action_controls/quick_choosers/share_chooser.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; + +class ShareButton extends ChooserQuickButton<ShareAction> { + final Set<AvesEntry> entries; + + const ShareButton({ + super.key, + required super.blurred, + required this.entries, + super.onChooserValue, + super.focusNode, + required super.onPressed, + }); + + @override + State<ShareButton> createState() => _ShareButtonState(); +} + +class _ShareButtonState extends ChooserQuickButtonState<ShareButton, ShareAction> { + EntryAction get action => EntryAction.share; + + @override + Widget get icon => action.getIcon(); + + @override + String get tooltip => action.getText(context); + + @override + bool get hasChooser => super.hasChooser && options.isNotEmpty; + + List<ShareAction> get options => [ + if (widget.entries.any((entry) => entry.isMotionPhoto)) ...[ + ShareAction.imageOnly, + ShareAction.videoOnly, + ], + ]; + + @override + Widget buildChooser(Animation<double> animation, PopupMenuPosition chooserPosition) { + return FadeTransition( + opacity: animation, + child: ScaleTransition( + scale: animation, + alignment: chooserPosition == PopupMenuPosition.over ? Alignment.bottomCenter : Alignment.topCenter, + child: ShareQuickChooser( + valueNotifier: chooserValueNotifier, + options: options, + blurred: widget.blurred, + chooserPosition: chooserPosition, + pointerGlobalPosition: pointerGlobalPosition, + ), + ), + ); + } +} diff --git a/lib/widgets/common/action_controls/quick_choosers/share_chooser.dart b/lib/widgets/common/action_controls/quick_choosers/share_chooser.dart new file mode 100644 index 0000000..43ffbea --- /dev/null +++ b/lib/widgets/common/action_controls/quick_choosers/share_chooser.dart @@ -0,0 +1,69 @@ +import 'dart:async'; +import 'dart:math'; + +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/action_controls/quick_choosers/common/menu.dart'; +import 'package:aves/widgets/common/basic/popup/menu_row.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; + +class ShareQuickChooser extends StatelessWidget { + final ValueNotifier<ShareAction?> valueNotifier; + final List<ShareAction> options; + final bool blurred; + final PopupMenuPosition chooserPosition; + final Stream<Offset> pointerGlobalPosition; + + static const _itemPadding = EdgeInsetsDirectional.only(end: 8); + + const ShareQuickChooser({ + super.key, + required this.valueNotifier, + required this.options, + required this.blurred, + required this.chooserPosition, + required this.pointerGlobalPosition, + }); + + @override + Widget build(BuildContext context) { + return MenuQuickChooser<ShareAction>( + valueNotifier: valueNotifier, + options: options, + autoReverse: false, + blurred: blurred, + chooserPosition: chooserPosition, + pointerGlobalPosition: pointerGlobalPosition, + itemHeight: kMinInteractiveDimension, + contentWidth: _computeLargestItemWidth, + itemBuilder: (context, action) => Padding( + padding: _itemPadding, + child: MenuRow( + text: action.getText(context), + icon: action.getIcon(), + ), + ), + ); + } + + double? _computeLargestItemWidth(BuildContext context) { + if (options.isEmpty) return null; + + final textStyle = DefaultTextStyle.of(context).style; + final textDirection = Directionality.of(context); + final textScaler = MediaQuery.textScalerOf(context); + final iconSize = IconTheme.of(context).size ?? 24; + + return options.map((action) { + final text = action.getText(context); + final paragraph = RenderParagraph( + TextSpan(text: text, style: textStyle), + textDirection: textDirection, + textScaler: textScaler, + )..layout(const BoxConstraints(), parentUsesSize: true); + final labelWidth = paragraph.getMaxIntrinsicWidth(double.infinity); + return iconSize + MenuRow.leadingPadding.horizontal + labelWidth + _itemPadding.horizontal; + }).reduce(max); + } +} diff --git a/lib/widgets/common/action_controls/quick_choosers/tag_button.dart b/lib/widgets/common/action_controls/quick_choosers/tag_button.dart new file mode 100644 index 0000000..8de2068 --- /dev/null +++ b/lib/widgets/common/action_controls/quick_choosers/tag_button.dart @@ -0,0 +1,76 @@ +import 'package:aves/model/filters/covered/tag.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/action_controls/quick_choosers/common/button.dart'; +import 'package:aves/widgets/common/action_controls/quick_choosers/filter_quick_chooser_mixin.dart'; +import 'package:aves/widgets/common/action_controls/quick_choosers/tag_chooser.dart'; +import 'package:aves/widgets/common/providers/media_query_data_provider.dart'; +import 'package:aves/widgets/filter_grids/common/filter_nav_page.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class TagButton extends ChooserQuickButton<CollectionFilter> { + const TagButton({ + super.key, + required super.blurred, + super.onChooserValue, + super.focusNode, + required super.onPressed, + }); + + @override + State<TagButton> createState() => _TagButtonState(); +} + +class _TagButtonState extends ChooserQuickButtonState<TagButton, CollectionFilter> { + EntryAction get action => EntryAction.editTags; + + @override + Widget get icon => action.getIcon(); + + @override + String get tooltip => action.getText(context); + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addPostFrameCallback((_) { + final source = context.read<CollectionSource?>(); + settings.removeObsoleteRecentTags(source); + }); + } + + @override + Widget buildChooser(Animation<double> animation, PopupMenuPosition chooserPosition) { + final options = settings.recentTags; + final takeCount = FilterQuickChooserMixin.maxTotalOptionCount - options.length; + if (takeCount > 0) { + final source = context.read<CollectionSource>(); + final filters = source.sortedTags.map(TagFilter.new).whereNot(options.contains).toSet(); + final allMapEntries = filters.map((filter) => FilterGridItem(filter, source.recentEntry(filter))).toList(); + allMapEntries.sort(FilterNavigationPage.compareFiltersByDate); + options.addAll(allMapEntries.take(takeCount).map((v) => v.filter)); + } + + return MediaQueryDataProvider( + child: FadeTransition( + opacity: animation, + child: ScaleTransition( + scale: animation, + alignment: chooserPosition == PopupMenuPosition.over ? Alignment.bottomCenter : Alignment.topCenter, + child: TagQuickChooser( + valueNotifier: chooserValueNotifier, + options: options, + blurred: widget.blurred, + chooserPosition: chooserPosition, + pointerGlobalPosition: pointerGlobalPosition, + ), + ), + ), + ); + } +} diff --git a/lib/widgets/common/action_controls/quick_choosers/tag_chooser.dart b/lib/widgets/common/action_controls/quick_choosers/tag_chooser.dart new file mode 100644 index 0000000..1b139e5 --- /dev/null +++ b/lib/widgets/common/action_controls/quick_choosers/tag_chooser.dart @@ -0,0 +1,45 @@ +import 'dart:async'; + +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/widgets/common/action_controls/quick_choosers/common/menu.dart'; +import 'package:aves/widgets/common/action_controls/quick_choosers/filter_quick_chooser_mixin.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:flutter/material.dart'; + +class TagQuickChooser extends StatelessWidget with FilterQuickChooserMixin<CollectionFilter> { + final ValueNotifier<CollectionFilter?> valueNotifier; + @override + final List<CollectionFilter> options; + final bool blurred; + final PopupMenuPosition chooserPosition; + final Stream<Offset> pointerGlobalPosition; + + const TagQuickChooser({ + super.key, + required this.valueNotifier, + required this.options, + required this.blurred, + required this.chooserPosition, + required this.pointerGlobalPosition, + }); + + @override + Widget build(BuildContext context) { + return MenuQuickChooser<CollectionFilter>( + valueNotifier: valueNotifier, + options: options, + autoReverse: true, + blurred: blurred, + chooserPosition: chooserPosition, + pointerGlobalPosition: pointerGlobalPosition, + maxTotalOptionCount: FilterQuickChooserMixin.maxTotalOptionCount, + itemHeight: computeItemHeight(context), + contentWidth: computeLargestItemWidth, + itemBuilder: itemBuilder, + emptyBuilder: (context) => Text(context.l10n.tagEmpty), + ); + } + + @override + CollectionFilter buildFilter(BuildContext context, CollectionFilter option) => option; +} diff --git a/lib/widgets/common/action_controls/togglers/favourite.dart b/lib/widgets/common/action_controls/togglers/favourite.dart new file mode 100644 index 0000000..cfc28d7 --- /dev/null +++ b/lib/widgets/common/action_controls/togglers/favourite.dart @@ -0,0 +1,162 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/favourites.dart'; +import 'package:aves/model/favourites.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/colors.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/basic/popup/menu_row.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/fx/sweeper.dart'; +import 'package:aves/widgets/common/identity/buttons/captioned_button.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class FavouriteToggler extends StatefulWidget { + final Set<AvesEntry> entries; + final bool isMenuItem; + final FocusNode? focusNode; + final VoidCallback? onPressed; + + const FavouriteToggler({ + super.key, + required this.entries, + this.isMenuItem = false, + this.focusNode, + this.onPressed, + }); + + @override + State<FavouriteToggler> createState() => _FavouriteTogglerState(); +} + +class _FavouriteTogglerState extends State<FavouriteToggler> { + final ValueNotifier<bool> _isFavouriteNotifier = ValueNotifier(false); + + Set<AvesEntry> get entries => widget.entries; + + static const isFavouriteIcon = Icon(AIcons.favourite, fill: 1); + static const isNotFavouriteIcon = Icon(AIcons.favourite, fill: 0); + + @override + void initState() { + super.initState(); + favourites.addListener(_onChanged); + _onChanged(); + } + + @override + void didUpdateWidget(covariant FavouriteToggler oldWidget) { + super.didUpdateWidget(oldWidget); + _onChanged(); + } + + @override + void dispose() { + favourites.removeListener(_onChanged); + _isFavouriteNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return ValueListenableBuilder<bool>( + valueListenable: _isFavouriteNotifier, + builder: (context, isFavourite, child) { + if (widget.isMenuItem) { + return isFavourite + ? MenuRow( + text: context.l10n.entryActionRemoveFavourite, + icon: isFavouriteIcon, + ) + : MenuRow( + text: context.l10n.entryActionAddFavourite, + icon: isNotFavouriteIcon, + ); + } + final animate = context.select<Settings, bool>((v) => v.animate); + return Stack( + alignment: Alignment.center, + children: [ + IconButton( + icon: isFavourite ? isFavouriteIcon : isNotFavouriteIcon, + onPressed: widget.onPressed, + focusNode: widget.focusNode, + tooltip: isFavourite ? context.l10n.entryActionRemoveFavourite : context.l10n.entryActionAddFavourite, + ), + if (animate) + Sweeper( + key: ValueKey(entries.length == 1 ? entries.first : entries.length), + builder: (context) => Icon( + AIcons.favourite, + fill: 0, + color: context.select<AvesColorsData, Color>((v) => v.favourite), + ), + toggledNotifier: _isFavouriteNotifier, + ), + ], + ); + }, + ); + } + + void _onChanged() { + _isFavouriteNotifier.value = entries.isNotEmpty && entries.every((entry) => entry.isFavourite); + } +} + +class FavouriteTogglerCaption extends StatefulWidget { + final Set<AvesEntry> entries; + final bool enabled; + + const FavouriteTogglerCaption({ + super.key, + required this.entries, + required this.enabled, + }); + + @override + State<FavouriteTogglerCaption> createState() => _FavouriteTogglerCaptionState(); +} + +class _FavouriteTogglerCaptionState extends State<FavouriteTogglerCaption> { + final ValueNotifier<bool> _isFavouriteNotifier = ValueNotifier(false); + + Set<AvesEntry> get entries => widget.entries; + + @override + void initState() { + super.initState(); + favourites.addListener(_onChanged); + _onChanged(); + } + + @override + void didUpdateWidget(covariant FavouriteTogglerCaption oldWidget) { + super.didUpdateWidget(oldWidget); + _onChanged(); + } + + @override + void dispose() { + favourites.removeListener(_onChanged); + _isFavouriteNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return ValueListenableBuilder<bool>( + valueListenable: _isFavouriteNotifier, + builder: (context, isFavourite, child) { + return CaptionedButtonText( + text: isFavourite ? context.l10n.entryActionRemoveFavourite : context.l10n.entryActionAddFavourite, + enabled: widget.enabled, + ); + }, + ); + } + + void _onChanged() { + _isFavouriteNotifier.value = entries.isNotEmpty && entries.every((entry) => entry.isFavourite); + } +} diff --git a/lib/widgets/common/action_controls/togglers/mute.dart b/lib/widgets/common/action_controls/togglers/mute.dart new file mode 100644 index 0000000..caff772 --- /dev/null +++ b/lib/widgets/common/action_controls/togglers/mute.dart @@ -0,0 +1,87 @@ +import 'dart:async'; + +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/basic/popup/menu_row.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/buttons/captioned_button.dart'; +import 'package:aves_utils/aves_utils.dart'; +import 'package:aves_video/aves_video.dart'; +import 'package:flutter/material.dart'; + +class MuteToggler extends StatelessWidget { + final AvesVideoController? controller; + final bool isMenuItem; + final FocusNode? focusNode; + final VoidCallback? onPressed; + + const MuteToggler({ + super.key, + required this.controller, + this.isMenuItem = false, + this.focusNode, + this.onPressed, + }); + + bool get isMuted => controller?.isMuted ?? false; + + @override + Widget build(BuildContext context) { + return NullableValueListenableBuilder<bool>( + valueListenable: controller?.canMuteNotifier, + builder: (context, value, child) { + final canDo = value ?? false; + return StreamBuilder<double>( + stream: controller?.volumeStream ?? Stream.value(1.0), + builder: (context, snapshot) { + final icon = Icon(isMuted ? AIcons.unmute : AIcons.mute); + final text = isMuted ? context.l10n.videoActionUnmute : context.l10n.videoActionMute; + + return isMenuItem + ? MenuRow( + text: text, + icon: icon, + ) + : IconButton( + icon: icon, + onPressed: canDo ? onPressed : null, + focusNode: focusNode, + tooltip: text, + ); + }, + ); + }, + ); + } +} + +class MuteTogglerCaption extends StatelessWidget { + final AvesVideoController? controller; + final bool enabled; + + const MuteTogglerCaption({ + super.key, + required this.controller, + required this.enabled, + }); + + bool get isMuted => controller?.isMuted ?? false; + + @override + Widget build(BuildContext context) { + return NullableValueListenableBuilder<bool>( + valueListenable: controller?.canMuteNotifier, + builder: (context, value, child) { + final canDo = value ?? false; + return StreamBuilder<double>( + stream: controller?.volumeStream ?? Stream.value(1.0), + builder: (context, snapshot) { + return CaptionedButtonText( + text: isMuted ? context.l10n.videoActionUnmute : context.l10n.videoActionMute, + enabled: canDo && enabled, + ); + }, + ); + }, + ); + } +} diff --git a/lib/widgets/common/action_controls/togglers/play.dart b/lib/widgets/common/action_controls/togglers/play.dart new file mode 100644 index 0000000..67c5a5b --- /dev/null +++ b/lib/widgets/common/action_controls/togglers/play.dart @@ -0,0 +1,130 @@ +import 'dart:async'; + +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/basic/popup/menu_row.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/buttons/captioned_button.dart'; +import 'package:aves_video/aves_video.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class PlayToggler extends StatefulWidget { + final AvesVideoController? controller; + final bool isMenuItem; + final FocusNode? focusNode; + final VoidCallback? onPressed; + + const PlayToggler({ + super.key, + required this.controller, + this.isMenuItem = false, + this.focusNode, + this.onPressed, + }); + + @override + State<PlayToggler> createState() => _PlayTogglerState(); +} + +class _PlayTogglerState extends State<PlayToggler> with SingleTickerProviderStateMixin { + final Set<StreamSubscription> _subscriptions = {}; + late AnimationController _playPauseAnimation; + + AvesVideoController? get controller => widget.controller; + + bool get isPlaying => controller?.isPlaying ?? false; + + @override + void initState() { + super.initState(); + _playPauseAnimation = AnimationController( + duration: context.read<DurationsData>().iconAnimation, + vsync: this, + ); + _registerWidget(widget); + } + + @override + void didUpdateWidget(covariant PlayToggler oldWidget) { + super.didUpdateWidget(oldWidget); + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + + @override + void dispose() { + _unregisterWidget(widget); + _playPauseAnimation.dispose(); + super.dispose(); + } + + void _registerWidget(PlayToggler widget) { + final controller = widget.controller; + if (controller != null) { + _subscriptions.add(controller.statusStream.listen(_onStatusChanged)); + _onStatusChanged(controller.status); + } + } + + void _unregisterWidget(PlayToggler widget) { + _subscriptions + ..forEach((sub) => sub.cancel()) + ..clear(); + } + + @override + Widget build(BuildContext context) { + final text = isPlaying ? context.l10n.videoActionPause : context.l10n.videoActionPlay; + + return widget.isMenuItem + ? MenuRow( + text: text, + icon: Icon(isPlaying ? AIcons.pause : AIcons.play), + ) + : IconButton( + icon: AnimatedIcon( + icon: AnimatedIcons.play_pause, + progress: _playPauseAnimation, + ), + onPressed: widget.onPressed, + focusNode: widget.focusNode, + tooltip: text, + ); + } + + void _onStatusChanged(VideoStatus status) { + final status = _playPauseAnimation.status; + if (isPlaying && !status.isForwardOrCompleted) { + _playPauseAnimation.forward(); + } else if (!isPlaying && status.isForwardOrCompleted) { + _playPauseAnimation.reverse(); + } + } +} + +class PlayTogglerCaption extends StatelessWidget { + final AvesVideoController? controller; + final bool enabled; + + const PlayTogglerCaption({ + super.key, + required this.controller, + required this.enabled, + }); + + bool get isPlaying => controller?.isPlaying ?? false; + + @override + Widget build(BuildContext context) { + return StreamBuilder<VideoStatus>( + stream: controller?.statusStream ?? Stream.value(VideoStatus.idle), + builder: (context, snapshot) { + return CaptionedButtonText( + text: isPlaying ? context.l10n.videoActionPause : context.l10n.videoActionPlay, + enabled: enabled, + ); + }, + ); + } +} diff --git a/lib/widgets/common/action_controls/togglers/title_search.dart b/lib/widgets/common/action_controls/togglers/title_search.dart new file mode 100644 index 0000000..b7badcd --- /dev/null +++ b/lib/widgets/common/action_controls/togglers/title_search.dart @@ -0,0 +1,61 @@ +import 'package:aves/model/query.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/basic/popup/menu_row.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/buttons/captioned_button.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class TitleSearchToggler extends StatelessWidget { + final bool queryEnabled, isMenuItem; + final FocusNode? focusNode; + final VoidCallback? onPressed; + + const TitleSearchToggler({ + super.key, + required this.queryEnabled, + this.isMenuItem = false, + this.focusNode, + this.onPressed, + }); + + @override + Widget build(BuildContext context) { + final icon = Icon(queryEnabled ? AIcons.filterOff : AIcons.filter); + final text = queryEnabled ? context.l10n.collectionActionHideTitleSearch : context.l10n.collectionActionShowTitleSearch; + return isMenuItem + ? MenuRow( + text: text, + icon: icon, + ) + : IconButton( + icon: icon, + onPressed: onPressed, + focusNode: focusNode, + tooltip: text, + ); + } +} + +class TitleSearchTogglerCaption extends StatelessWidget { + final bool enabled; + + const TitleSearchTogglerCaption({ + super.key, + required this.enabled, + }); + + @override + Widget build(BuildContext context) { + // `Query` may not be available during hero + return Selector<Query?, bool>( + selector: (context, query) => query?.enabled ?? false, + builder: (context, queryEnabled, child) { + return CaptionedButtonText( + text: queryEnabled ? context.l10n.collectionActionHideTitleSearch : context.l10n.collectionActionShowTitleSearch, + enabled: enabled, + ); + }, + ); + } +} diff --git a/lib/widgets/common/action_mixins/entry_editor.dart b/lib/widgets/common/action_mixins/entry_editor.dart new file mode 100644 index 0000000..4e3c937 --- /dev/null +++ b/lib/widgets/common/action_mixins/entry_editor.dart @@ -0,0 +1,144 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/metadata_edition.dart'; +import 'package:aves/model/entry/extensions/multipage.dart'; +import 'package:aves/model/filters/covered/tag.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/filters/placeholder.dart'; +import 'package:aves/model/metadata/date_modifier.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/ref/mime_types.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:aves/widgets/dialogs/entry_editors/edit_date_dialog.dart'; +import 'package:aves/widgets/dialogs/entry_editors/edit_description_dialog.dart'; +import 'package:aves/widgets/dialogs/entry_editors/edit_location_dialog.dart'; +import 'package:aves/widgets/dialogs/entry_editors/edit_rating_dialog.dart'; +import 'package:aves/widgets/dialogs/entry_editors/remove_metadata_dialog.dart'; +import 'package:aves/widgets/dialogs/entry_editors/tag_editor_page.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; + +mixin EntryEditorMixin { + Future<DateModifier?> selectDateModifier(BuildContext context, Set<AvesEntry> entries, CollectionLens? collection) async { + if (entries.isEmpty) return null; + + return showDialog<DateModifier>( + context: context, + builder: (context) => EditEntryDateDialog( + entry: entries.first, + collection: collection, + ), + routeSettings: const RouteSettings(name: EditEntryDateDialog.routeName), + ); + } + + Future<LocationEditActionResult?> selectLocation(BuildContext context, Set<AvesEntry> entries, CollectionLens? collection) async { + if (entries.isEmpty) return null; + + return showDialog<LocationEditActionResult>( + context: context, + builder: (context) => EditEntryLocationDialog( + entries: entries, + collection: collection, + ), + routeSettings: const RouteSettings(name: EditEntryLocationDialog.routeName), + ); + } + + Future<Map<DescriptionField, String?>?> selectTitleDescriptionModifier(BuildContext context, Set<AvesEntry> entries) async { + if (entries.isEmpty) return null; + + final entry = entries.first; + final initialTitle = entry.catalogMetadata?.xmpTitle ?? ''; + final fields = await metadataFetchService.getOverlayMetadata(entry, {MetadataSyntheticField.description}); + final initialDescription = fields.description ?? ''; + + return showDialog<Map<DescriptionField, String?>>( + context: context, + builder: (context) => EditEntryTitleDescriptionDialog( + initialTitle: initialTitle, + initialDescription: initialDescription, + ), + routeSettings: const RouteSettings(name: EditEntryTitleDescriptionDialog.routeName), + ); + } + + Future<int?> selectRating(BuildContext context, Set<AvesEntry> entries) async { + if (entries.isEmpty) return null; + + return showDialog<int>( + context: context, + builder: (context) => EditEntryRatingDialog( + entry: entries.first, + ), + routeSettings: const RouteSettings(name: EditEntryRatingDialog.routeName), + ); + } + + Future<Map<AvesEntry, Set<String>>?> selectTags(BuildContext context, Set<AvesEntry> entries) async { + if (entries.isEmpty) return null; + + final oldTagsByEntry = Map.fromEntries(entries.map((v) { + return MapEntry(v, v.tags.map(TagFilter.new).toSet()); + })); + final filtersByEntry = await Navigator.maybeOf(context)?.push<Map<AvesEntry, Set<CollectionFilter>>>( + MaterialPageRoute( + settings: const RouteSettings(name: TagEditorPage.routeName), + builder: (context) => TagEditorPage( + tagsByEntry: oldTagsByEntry, + ), + ), + ) ?? + oldTagsByEntry; + + final newTagsByEntry = <AvesEntry, Set<String>>{}; + await Future.forEach(filtersByEntry.entries, (kv) async { + final entry = kv.key; + final filters = kv.value; + newTagsByEntry[entry] = await getTagsFromFilters(filters, entry); + }); + + return newTagsByEntry; + } + + Future<Set<String>> getTagsFromFilters(Set<CollectionFilter> filters, AvesEntry entry) async { + final tags = filters.whereType<TagFilter>().map((v) => v.tag).toSet(); + final placeholderTags = await Future.wait(filters.whereType<PlaceholderFilter>().map((v) => v.toTag(entry))); + tags.addAll(placeholderTags.nonNulls.where((v) => v.isNotEmpty)); + return tags; + } + + Future<Set<MetadataType>?> selectMetadataToRemove(BuildContext context, Set<AvesEntry> entries) async { + if (entries.isEmpty) return null; + + final types = await showDialog<Set<MetadataType>>( + context: context, + builder: (context) => RemoveEntryMetadataDialog( + showJpegTypes: entries.any((entry) => entry.mimeType == MimeTypes.jpeg), + ), + routeSettings: const RouteSettings(name: RemoveEntryMetadataDialog.routeName), + ); + if (types == null || types.isEmpty) return null; + + if (entries.any((entry) => entry.isMotionPhoto) && types.contains(MetadataType.xmp)) { + final confirmed = await showDialog<bool>( + context: context, + builder: (context) => AvesDialog( + content: Text(context.l10n.removeEntryMetadataMotionPhotoXmpWarningDialogMessage), + actions: [ + const CancelButton(), + TextButton( + onPressed: () => Navigator.maybeOf(context)?.pop(true), + child: Text(context.l10n.applyButtonLabel), + ), + ], + ), + routeSettings: const RouteSettings(name: AvesDialog.warningRouteName), + ); + if (confirmed == null || !confirmed) return null; + } + + return types; + } +} diff --git a/lib/widgets/common/action_mixins/entry_storage.dart b/lib/widgets/common/action_mixins/entry_storage.dart new file mode 100644 index 0000000..a3505e1 --- /dev/null +++ b/lib/widgets/common/action_mixins/entry_storage.dart @@ -0,0 +1,563 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:aves/app_mode.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/favourites.dart'; +import 'package:aves/model/entry/extensions/keys.dart'; +import 'package:aves/model/entry/extensions/multipage.dart'; +import 'package:aves/model/entry/extensions/props.dart'; +import 'package:aves/model/favourites.dart'; +import 'package:aves/model/filters/covered/stored_album.dart'; +import 'package:aves/model/filters/trash.dart'; +import 'package:aves/model/highlight.dart'; +import 'package:aves/model/metadata/date_modifier.dart'; +import 'package:aves/model/multipage.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/ref/mime_types.dart'; +import 'package:aves/services/common/image_op_events.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/services/media/enums.dart'; +import 'package:aves/services/media/media_edit_service.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/utils/android_file_utils.dart'; +import 'package:aves/widgets/collection/collection_page.dart'; +import 'package:aves/widgets/collection/entry_set_action_delegate.dart'; +import 'package:aves/widgets/common/action_mixins/feedback.dart'; +import 'package:aves/widgets/common/action_mixins/permission_aware.dart'; +import 'package:aves/widgets/common/action_mixins/size_aware.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/dialogs/aves_confirmation_dialog.dart'; +import 'package:aves/widgets/dialogs/pick_dialogs/album_pick_page.dart'; +import 'package:aves/widgets/dialogs/selection_dialogs/single_selection.dart'; +import 'package:aves/widgets/filter_grids/common/enums.dart'; +import 'package:aves/widgets/viewer/controls/notifications.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +mixin EntryStorageMixin on FeedbackMixin, PermissionAwareMixin, SizeAwareMixin { + // returns whether it completed the action (with or without failures) + Future<bool> doExport(BuildContext context, Set<AvesEntry> targetEntries, EntryConvertOptions options) async { + final destinationAlbumFilter = await pickAlbum( + context: context, + moveType: MoveType.export, + chipTypes: {AlbumChipType.stored}, + initialGroup: null, + ); + if (destinationAlbumFilter == null || destinationAlbumFilter is! StoredAlbumFilter) return false; + + final destinationAlbum = destinationAlbumFilter.album; + if (!await checkStoragePermissionForAlbums(context, {destinationAlbum})) return false; + + if (!await checkFreeSpaceForMove(context, targetEntries, destinationAlbum, MoveType.export)) return false; + + final transientMultiPageInfo = <MultiPageInfo>{}; + final selection = <AvesEntry>{}; + await Future.forEach(targetEntries, (targetEntry) async { + if (targetEntry.isMultiPage) { + final multiPageInfo = await targetEntry.getMultiPageInfo(); + if (multiPageInfo != null) { + transientMultiPageInfo.add(multiPageInfo); + if (targetEntry.isMotionPhoto) { + await multiPageInfo.extractMotionPhotoVideo(); + } + if (multiPageInfo.pageCount > 1) { + selection.addAll(multiPageInfo.exportEntries); + } + } + } else { + selection.add(targetEntry); + } + }); + + final l10n = context.l10n; + + var nameConflictStrategy = NameConflictStrategy.rename; + final destinationDirectory = Directory(destinationAlbum); + final destinationExtension = MimeTypes.extensionFor(options.mimeType); + final names = [ + ...selection.map((v) => '${v.filenameWithoutExtension}$destinationExtension'), + // do not guard up front based on directory existence, + // as conflicts could be within moved entries scattered across multiple albums + if (await destinationDirectory.exists()) ...destinationDirectory.listSync().map((v) => pContext.basename(v.path)), + ].map((v) => v.toLowerCase()).toList(); + // case insensitive comparison + final uniqueNames = names.toSet(); + if (uniqueNames.length < names.length) { + final value = await showDialog<NameConflictStrategy>( + context: context, + builder: (context) => AvesSingleSelectionDialog<NameConflictStrategy>( + initialValue: nameConflictStrategy, + options: Map.fromEntries(NameConflictStrategy.values.map((v) => MapEntry(v, v.getName(context)))), + message: l10n.nameConflictDialogSingleSourceMessage, + confirmationButtonLabel: l10n.continueButtonLabel, + ), + routeSettings: const RouteSettings(name: AvesSingleSelectionDialog.routeName), + ); + if (value == null) return false; + nameConflictStrategy = value; + } + + final selectionCount = selection.length; + final source = context.read<CollectionSource>(); + source.pauseMonitoring(); + await showOpReport<ExportOpEvent>( + context: context, + opStream: mediaEditService.export( + selection, + options: options, + destinationAlbum: destinationAlbum, + nameConflictStrategy: nameConflictStrategy, + ), + itemCount: selectionCount, + onDone: (processed) async { + final successOps = processed.where((op) => op.success).toSet(); + final exportedOps = successOps.where((op) => !op.skipped && op.newFields[EntryFields.uri] != null).toSet(); + final newUris = exportedOps.map((op) => op.newFields[EntryFields.uri] as String).toSet(); + final isMainMode = context.read<ValueNotifier<AppMode>>().value == AppMode.main; + + // check source favourite status + final favouriteSourceUris = selection.where((entry) => entry.isFavourite).map((entry) => entry.uri).toSet(); + final favouriteNewUris = <String>{}; + exportedOps.forEach((op) { + final sourceUri = op.uri; + if (favouriteSourceUris.contains(sourceUri)) { + final newUri = op.newFields[EntryFields.uri] as String; + favouriteNewUris.add(newUri); + } + }); + + source.resumeMonitoring(); + unawaited(source.refreshUris(newUris).then((_) { + // transfer favourite status on exports + final newFavouriteEntries = source.allEntries.where((entry) => favouriteNewUris.contains(entry.uri)).toSet(); + favourites.add(newFavouriteEntries); + })); + + // get navigator beforehand because + // local context may be deactivated when action is triggered after navigation + final navigator = Navigator.maybeOf(context); + final showAction = isMainMode && newUris.isNotEmpty + ? SnackBarAction( + label: l10n.showButtonLabel, + onPressed: () { + if (navigator != null) { + navigator.pushAndRemoveUntil( + MaterialPageRoute( + settings: const RouteSettings(name: CollectionPage.routeName), + builder: (context) => CollectionPage( + source: source, + filters: {StoredAlbumFilter(destinationAlbum, source.getStoredAlbumDisplayName(context, destinationAlbum))}, + highlightTest: (entry) => newUris.contains(entry.uri), + ), + ), + (route) => false, + ); + } + }, + ) + : null; + final successCount = successOps.length; + if (successCount < selectionCount) { + final count = selectionCount - successCount; + showFeedback( + context, + FeedbackType.warn, + l10n.collectionExportFailureFeedback(count), + showAction, + ); + } else { + showFeedback( + context, + FeedbackType.info, + l10n.genericSuccessFeedback, + showAction, + ); + } + }, + ); + transientMultiPageInfo.forEach((v) => v.dispose()); + return true; + } + + // returns whether it completed the action (with or without failures) + Future<bool> doQuickMove( + BuildContext context, { + required MoveType moveType, + required Map<String, Set<AvesEntry>> entriesByDestination, + bool hideShowAction = false, + VoidCallback? onSuccess, + }) async { + if (moveType == MoveType.move) { + // skip moving entries to their directory + entriesByDestination.forEach((destinationAlbum, entries) { + entries.removeWhere((entry) => entry.directory == destinationAlbum); + }); + entriesByDestination.removeWhere((_, entries) => entries.isEmpty); + } + + final entries = entriesByDestination.values.expand((v) => v).toSet(); + final todoCount = entries.length; + if (todoCount == 0) return true; + + final toBin = moveType == MoveType.toBin; + final copy = moveType == MoveType.copy; + + // permission for modification at destinations + final destinationAlbums = entriesByDestination.keys.toSet(); + if (!await checkStoragePermissionForAlbums(context, destinationAlbums)) return false; + + // permission for modification at origins + final originAlbums = entries.map((e) => e.directory).nonNulls.toSet(); + if ({MoveType.move, MoveType.toBin}.contains(moveType) && !await checkStoragePermissionForAlbums(context, originAlbums, entries: entries)) return false; + + final hasEnoughSpaceByDestination = await Future.wait(destinationAlbums.map((destinationAlbum) { + return checkFreeSpaceForMove(context, entries, destinationAlbum, moveType); + })); + if (hasEnoughSpaceByDestination.any((v) => !v)) return false; + + final l10n = context.l10n; + var nameConflictStrategy = NameConflictStrategy.rename; + if (!toBin && destinationAlbums.length == 1) { + final destinationDirectory = Directory(destinationAlbums.single); + final names = [ + ...entries.map((v) => '${v.filenameWithoutExtension}${v.extension}'), + // do not guard up front based on directory existence, + // as conflicts could be within moved entries scattered across multiple albums + if (await destinationDirectory.exists()) ...destinationDirectory.listSync().map((v) => pContext.basename(v.path)), + ].map((v) => v.toLowerCase()).toList(); + // case insensitive comparison + final uniqueNames = names.toSet(); + if (uniqueNames.length < names.length) { + final value = await showDialog<NameConflictStrategy>( + context: context, + builder: (context) => AvesSingleSelectionDialog<NameConflictStrategy>( + initialValue: nameConflictStrategy, + options: Map.fromEntries(NameConflictStrategy.values.map((v) => MapEntry(v, v.getName(context)))), + message: originAlbums.length == 1 ? l10n.nameConflictDialogSingleSourceMessage : l10n.nameConflictDialogMultipleSourceMessage, + confirmationButtonLabel: l10n.continueButtonLabel, + ), + routeSettings: const RouteSettings(name: AvesSingleSelectionDialog.routeName), + ); + if (value == null) return false; + nameConflictStrategy = value; + } + } + + if ({MoveType.move, MoveType.copy, MoveType.toBin}.contains(moveType) && !await _checkUndatedItems(context, entries)) return false; + + final source = context.read<CollectionSource>(); + source.pauseMonitoring(); + final opId = mediaEditService.newOpId; + await showOpReport<MoveOpEvent>( + context: context, + opStream: mediaEditService.move( + opId: opId, + entriesByDestination: entriesByDestination, + copy: copy, + nameConflictStrategy: nameConflictStrategy, + ), + itemCount: todoCount, + onCancel: () => mediaEditService.cancelFileOp(opId), + onDone: (processed) async { + final successOps = processed.where((op) => op.success).toSet(); + + // move + final movedOps = successOps.where((op) => !op.skipped && !op.deleted).toSet(); + final movedEntries = movedOps.map((op) => op.uri).map((uri) => entries.firstWhereOrNull((entry) => entry.uri == uri)).nonNulls.toSet(); + await source.updateAfterMove( + todoEntries: entries, + moveType: moveType, + destinationAlbums: destinationAlbums, + movedOps: movedOps, + ); + + // delete (when trying to move to bin obsolete entries) + final deletedOps = successOps.where((op) => op.deleted).toSet(); + final deletedUris = deletedOps.map((op) => op.uri).toSet(); + await source.removeEntries(deletedUris, includeTrash: true); + + source.resumeMonitoring(); + + // cleanup + if ({MoveType.move, MoveType.toBin}.contains(moveType)) { + await storageService.deleteEmptyRegularDirectories(originAlbums); + } + + final successCount = successOps.length; + if (successCount < todoCount) { + final count = todoCount - successCount; + showFeedback( + context, + FeedbackType.warn, + copy ? l10n.collectionCopyFailureFeedback(count) : l10n.collectionMoveFailureFeedback(count), + ); + } else { + final count = movedOps.length; + final appMode = context.read<ValueNotifier<AppMode>?>()?.value; + + SnackBarAction? action; + if (count > 0 && appMode == AppMode.main) { + // get navigator beforehand because + // local context may be deactivated when action is triggered after navigation + final navigator = Navigator.maybeOf(context); + if (toBin) { + if (movedEntries.isNotEmpty) { + action = SnackBarAction( + label: Themes.asButtonLabel(l10n.entryActionRestore), + onPressed: () { + if (navigator != null) { + doMove( + navigator.context, + moveType: MoveType.fromBin, + entries: movedEntries, + hideShowAction: true, + ); + } + }, + ); + } + } else if (!hideShowAction) { + action = SnackBarAction( + label: l10n.showButtonLabel, + onPressed: () { + if (navigator != null) { + _showMovedItems(navigator.context, destinationAlbums, movedOps); + } + }, + ); + } + } + + if (!toBin || (toBin && settings.confirmAfterMoveToBin)) { + showFeedback( + context, + FeedbackType.info, + copy ? l10n.collectionCopySuccessFeedback(count) : l10n.collectionMoveSuccessFeedback(count), + action, + ); + } + + EntryMovedNotification(moveType, movedEntries).dispatch(context); + onSuccess?.call(); + } + }, + ); + return true; + } + + // returns whether it completed the action (with or without failures) + Future<bool> doMove( + BuildContext context, { + required MoveType moveType, + required Set<AvesEntry> entries, + bool hideShowAction = false, + VoidCallback? onSuccess, + }) async { + if (moveType == MoveType.toBin) { + final l10n = context.l10n; + if (!await showSkippableConfirmationDialog( + context: context, + type: ConfirmationDialog.moveToBin, + message: l10n.binEntriesConfirmationDialogMessage(entries.length), + confirmationButtonLabel: l10n.deleteButtonLabel, + )) { + return false; + } + } + + final entriesByDestination = <String, Set<AvesEntry>>{}; + switch (moveType) { + case MoveType.copy: + case MoveType.move: + case MoveType.export: + final destinationAlbumFilter = await pickAlbum( + context: context, + moveType: moveType, + chipTypes: {AlbumChipType.stored}, + initialGroup: null, + ); + if (destinationAlbumFilter == null || destinationAlbumFilter is! StoredAlbumFilter) return false; + + final destinationAlbum = destinationAlbumFilter.album; + settings.recentDestinationAlbums = settings.recentDestinationAlbums + ..remove(destinationAlbum) + ..insert(0, destinationAlbum); + entriesByDestination[destinationAlbum] = entries; + case MoveType.toBin: + entriesByDestination[AndroidFileUtils.trashDirPath] = entries; + case MoveType.fromBin: + groupBy<AvesEntry, String?>(entries, (e) => e.directory).forEach((originAlbum, dirEntries) { + if (originAlbum != null) { + entriesByDestination[originAlbum] = dirEntries.toSet(); + } + }); + } + + return await doQuickMove( + context, + moveType: moveType, + entriesByDestination: entriesByDestination, + onSuccess: onSuccess, + ); + } + + // returns whether it completed the action (with or without failures) + Future<bool> rename( + BuildContext context, { + required Map<AvesEntry, String> entriesToNewName, + required bool persist, + VoidCallback? onSuccess, + }) async { + final entries = entriesToNewName.keys.toSet(); + final todoCount = entries.length; + assert(todoCount > 0); + + if (!await checkStoragePermission(context, entries)) return false; + + if (!await _checkUndatedItems(context, entries)) return false; + + final source = context.read<CollectionSource>(); + source.pauseMonitoring(); + final opId = mediaEditService.newOpId; + await showOpReport<MoveOpEvent>( + context: context, + opStream: mediaEditService.rename( + opId: opId, + entriesToNewName: entriesToNewName, + ), + itemCount: todoCount, + onCancel: () => mediaEditService.cancelFileOp(opId), + onDone: (processed) async { + final successOps = processed.where((op) => op.success).toSet(); + final movedOps = successOps.where((op) => !op.skipped).toSet(); + await source.updateAfterRename( + todoEntries: entries, + movedOps: movedOps, + persist: persist, + ); + source.resumeMonitoring(); + + final l10n = context.l10n; + final successCount = successOps.length; + if (successCount < todoCount) { + final count = todoCount - successCount; + showFeedback(context, FeedbackType.warn, l10n.collectionRenameFailureFeedback(count)); + } else { + final count = movedOps.length; + showFeedback(context, FeedbackType.info, l10n.collectionRenameSuccessFeedback(count)); + onSuccess?.call(); + } + }, + ); + return true; + } + + Future<bool> _checkUndatedItems(BuildContext context, Set<AvesEntry> entries) async { + final undatedItems = entries.where((entry) { + if (!entry.isCatalogued) return false; + final dateMillis = entry.catalogMetadata?.dateMillis; + return dateMillis == null || dateMillis == 0; + }).toSet(); + if (undatedItems.isNotEmpty) { + final confirmationDialogDelegate = MoveUndatedConfirmationDialogDelegate(); + final confirmed = await showSkippableConfirmationDialog( + context: context, + type: ConfirmationDialog.moveUndatedItems, + delegate: confirmationDialogDelegate, + confirmationButtonLabel: context.l10n.continueButtonLabel, + ); + confirmationDialogDelegate.dispose(); + if (!confirmed) return false; + + if (settings.setMetadataDateBeforeFileOp) { + final entriesToDate = undatedItems.where((entry) => entry.canEditDate).toSet(); + if (entriesToDate.isNotEmpty) { + await EntrySetActionDelegate().editDate( + context, + entries: entriesToDate, + modifier: DateModifier.copyField(DateFieldSource.fileModifiedDate), + showResult: false, + ); + } + } + } + return true; + } + + Future<void> _showMovedItems( + BuildContext context, + Set<String> destinationAlbums, + Set<MoveOpEvent> movedOps, + ) async { + final newUris = movedOps.map((op) => op.newFields[EntryFields.uri] as String?).toSet(); + bool highlightTest(AvesEntry entry) => newUris.contains(entry.uri); + + final collection = context.read<CollectionLens?>(); + if (collection == null || collection.filters.any((f) => f is StoredAlbumFilter || f is TrashFilter)) { + final source = context.read<CollectionSource>(); + final targetFilters = collection?.filters.where((f) => f != TrashFilter.instance).toSet() ?? {}; + // we could simply add the filter to the current collection + // but navigating makes the change less jarring + if (destinationAlbums.length == 1) { + final destinationAlbum = destinationAlbums.single; + targetFilters.removeWhere((f) => f is StoredAlbumFilter); + targetFilters.add(StoredAlbumFilter(destinationAlbum, source.getStoredAlbumDisplayName(context, destinationAlbum))); + } + unawaited(Navigator.maybeOf(context)?.pushAndRemoveUntil( + MaterialPageRoute( + settings: const RouteSettings(name: CollectionPage.routeName), + builder: (context) => CollectionPage( + source: source, + filters: targetFilters, + highlightTest: highlightTest, + ), + ), + (route) => false, + )); + } else { + // track in current page, without navigation + await Future.delayed(ADurations.highlightScrollInitDelay); + final targetEntry = collection.sortedEntries.firstWhereOrNull(highlightTest); + if (targetEntry != null) { + context.read<HighlightInfo>().trackItem(targetEntry, highlightItem: targetEntry); + } + } + } +} + +class MoveUndatedConfirmationDialogDelegate extends ConfirmationDialogDelegate { + final ValueNotifier<bool> _setMetadataDate = ValueNotifier(false); + + MoveUndatedConfirmationDialogDelegate() { + _setMetadataDate.value = settings.setMetadataDateBeforeFileOp; + } + + void dispose() { + _setMetadataDate.dispose(); + } + + @override + List<Widget> build(BuildContext context) => [ + Padding( + padding: const EdgeInsets.all(16) + const EdgeInsets.only(top: 8), + child: Text(context.l10n.moveUndatedConfirmationDialogMessage), + ), + ValueListenableBuilder<bool>( + valueListenable: _setMetadataDate, + builder: (context, flag, child) => SwitchListTile( + value: flag, + onChanged: (v) => _setMetadataDate.value = v, + title: Text(context.l10n.moveUndatedConfirmationDialogSetDate), + ), + ), + ]; + + @override + void apply() => settings.setMetadataDateBeforeFileOp = _setMetadataDate.value; +} diff --git a/lib/widgets/common/action_mixins/feedback.dart b/lib/widgets/common/action_mixins/feedback.dart new file mode 100644 index 0000000..6666ed6 --- /dev/null +++ b/lib/widgets/common/action_mixins/feedback.dart @@ -0,0 +1,533 @@ +import 'dart:async'; +import 'dart:math'; + +import 'package:aves/model/settings/enums/accessibility_timeout.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/colors.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/action_mixins/overlay_snack_bar.dart'; +import 'package:aves/widgets/common/basic/circle.dart'; +import 'package:aves/widgets/common/basic/text/change_highlight.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/extensions/media_query.dart'; +import 'package:aves/widgets/common/extensions/theme.dart'; +import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; +import 'package:overlay_support/overlay_support.dart'; +import 'package:percent_indicator/circular_percent_indicator.dart'; +import 'package:provider/provider.dart'; + +enum FeedbackType { info, warn } + +typedef MarginComputer = EdgeInsets Function(BuildContext context); + +mixin FeedbackMixin { + static final ValueNotifier<MarginComputer?> snackBarMarginOverrideNotifier = ValueNotifier(null); + static OverlaySupportEntry? _overlayNotificationEntry; + + static EdgeInsets snackBarMarginDefault(BuildContext context) { + return EdgeInsets.only( + bottom: context.select<MediaQueryData, double>((mq) => max(mq.effectiveBottomPadding, mq.systemGestureInsets.bottom)), + ); + } + + void dismissFeedback(BuildContext context) { + ScaffoldMessenger.of(context).hideCurrentSnackBar(); + _overlayNotificationEntry?.dismiss(); + _overlayNotificationEntry = null; + } + + void showFeedback(BuildContext context, FeedbackType type, String message, [SnackBarAction? action]) { + ScaffoldMessengerState? scaffoldMessenger; + try { + scaffoldMessenger = ScaffoldMessenger.of(context); + } catch (error) { + // minor issue: the page triggering this feedback likely + // allows the user to navigate away and they did so + debugPrint('failed to find ScaffoldMessenger in context'); + } + if (scaffoldMessenger != null) { + showFeedbackWithMessenger(context, scaffoldMessenger, type, message, action); + } + } + + // provide the messenger if feedback happens as the widget is disposed + void showFeedbackWithMessenger(BuildContext context, ScaffoldMessengerState messenger, FeedbackType type, String message, [SnackBarAction? action]) { + settings.timeToTakeAction.getSnackBarDuration(action != null).then((duration) { + final start = DateTime.now(); + final theme = Theme.of(context); + final snackBarTheme = theme.snackBarTheme; + + final snackBarContent = _FeedbackMessage( + type: type, + message: message, + progressColor: theme.colorScheme.primary, + start: start, + stop: action != null ? start.add(duration) : null, + ); + + if (snackBarMarginOverrideNotifier.value != null) { + // as of Flutter v2.10.4, `SnackBar` can only be positioned at the bottom, + // and space under the snack bar `margin` does not receive gestures + // (because it is used by the `Dismissible` wrapping the snack bar) + // so we use `showOverlayNotification` instead + _overlayNotificationEntry = showOverlayNotification( + (context) => SafeArea( + bottom: false, + child: ValueListenableBuilder<MarginComputer?>( + valueListenable: snackBarMarginOverrideNotifier, + builder: (context, marginComputer, child) { + final margin = (marginComputer ?? snackBarMarginDefault).call(context); + return AnimatedPadding( + padding: margin, + duration: ADurations.pageTransitionLoose, + child: child, + ); + }, + child: OverlaySnackBar( + content: snackBarContent, + action: action != null + ? TextButton( + style: ButtonStyle( + foregroundColor: WidgetStateProperty.all(snackBarTheme.actionTextColor), + ), + onPressed: () { + dismissFeedback(context); + action.onPressed(); + }, + child: Text(action.label), + ) + : null, + animation: kAlwaysCompleteAnimation, + dismissDirection: DismissDirection.horizontal, + onDismiss: () => dismissFeedback(context), + ), + ), + ), + duration: duration, + // reuse the same key to dismiss previous snack bar when a new one is shown + key: const Key('snack'), + position: NotificationPosition.bottom, + context: context, + ); + } else { + messenger.showSnackBar(SnackBar( + content: snackBarContent, + padding: action != null ? EdgeInsetsDirectional.only(start: snackBarHorizontalPadding(snackBarTheme)) : null, + action: action, + duration: duration, + dismissDirection: DismissDirection.horizontal, + )); + } + }); + } + + static double snackBarHorizontalPadding(SnackBarThemeData snackBarTheme) { + final isFloatingSnackBar = (snackBarTheme.behavior ?? SnackBarBehavior.fixed) == SnackBarBehavior.floating; + final double horizontalPadding = isFloatingSnackBar ? 16.0 : 24.0; + return horizontalPadding; + } + + // report overlay for multiple operations + + Future<void> showOpReport<T>({ + required BuildContext context, + required Stream<T> opStream, + int? itemCount, + VoidCallback? onCancel, + Future<void> Function(Set<T> processed)? onDone, + }) async { + final opCompleter = Completer(); + await showDialog( + context: context, + barrierDismissible: false, + builder: (context) => ReportOverlay<T>( + opStream: opStream, + itemCount: itemCount, + onCancel: onCancel, + onDone: (processed) async { + Navigator.maybeOf(context)?.pop(); + await onDone?.call(processed); + opCompleter.complete(); + }, + ), + routeSettings: const RouteSettings(name: ReportOverlay.routeName), + ); + return opCompleter.future; + } +} + +class ReportOverlay<T> extends StatefulWidget { + static const routeName = '/dialog/report_overlay'; + + final Stream<T> opStream; + final int? itemCount; + final VoidCallback? onCancel; + final void Function(Set<T> processed) onDone; + + static const double diameter = 160.0; + static const double strokeWidth = 8.0; + + const ReportOverlay({ + super.key, + required this.opStream, + required this.itemCount, + required this.onCancel, + required this.onDone, + }); + + @override + State<ReportOverlay<T>> createState() => _ReportOverlayState<T>(); +} + +class _ReportOverlayState<T> extends State<ReportOverlay<T>> with SingleTickerProviderStateMixin { + final processed = <T>{}; + late AnimationController _animationController; + late CurvedAnimation _animation; + + Stream<T> get opStream => widget.opStream; + + static const double fontSize = 18.0; + + @override + void initState() { + super.initState(); + + _animationController = AnimationController( + duration: ADurations.collectionOpOverlayAnimation, + vsync: this, + ); + _animation = CurvedAnimation( + parent: _animationController, + curve: Curves.easeOutQuad, + ); + _animationController.forward(); + + // do not handle completion inside `StreamBuilder` + // as it could be called multiple times + Future<void> onComplete() => _animationController.reverse().then((_) => widget.onDone(processed)); + opStream.listen( + processed.add, + onError: (error) => debugPrint('_showOpReport error=$error'), + onDone: onComplete, + ); + } + + @override + void dispose() { + _animation.dispose(); + _animationController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + const diameter = ReportOverlay.diameter; + const strokeWidth = ReportOverlay.strokeWidth; + final percentFormatter = NumberFormat.percentPattern(context.locale); + + final theme = Theme.of(context); + final colorScheme = theme.colorScheme; + final progressColor = colorScheme.primary; + final animate = context.select<Settings, bool>((v) => v.animate); + return PopScope( + canPop: false, + child: StreamBuilder<T>( + stream: opStream, + builder: (context, snapshot) { + final processedCount = processed.length.toDouble(); + final total = widget.itemCount; + final percent = total == null || total == 0 ? 0.0 : min(1.0, processedCount / total); + return FadeTransition( + opacity: _animation, + child: Stack( + alignment: Alignment.center, + children: [ + Container( + width: diameter + 2, + height: diameter + 2, + decoration: BoxDecoration( + color: theme.isDark ? const Color(0xBB000000) : const Color(0xEEFFFFFF), + shape: BoxShape.circle, + ), + ), + if (animate) const ReportProgressIndicator(opacity: .1), + CircularPercentIndicator( + percent: percent, + lineWidth: strokeWidth, + radius: diameter / 2, + backgroundColor: colorScheme.onSurface.withValues(alpha: .2), + progressColor: progressColor, + animation: animate, + center: total != null + ? Text( + percentFormatter.format(percent), + style: const TextStyle(fontSize: fontSize), + ) + : null, + animateFromLastPercent: true, + ), + if (widget.onCancel != null) + Material( + color: Colors.transparent, + child: Container( + width: diameter, + height: diameter, + margin: const EdgeInsets.only(top: fontSize), + alignment: const FractionalOffset(0.5, 0.75), + child: Tooltip( + message: context.l10n.cancelTooltip, + preferBelow: false, + child: IconButton( + icon: const Icon(AIcons.cancel), + onPressed: widget.onCancel, + ), + ), + ), + ), + ], + ), + ); + }, + ), + ); + } +} + +class ReportProgressIndicator extends StatelessWidget { + final double opacity; + + const ReportProgressIndicator({ + super.key, + this.opacity = 1, + }); + + @override + Widget build(BuildContext context) { + const diameter = ReportOverlay.diameter; + const strokeWidth = ReportOverlay.strokeWidth; + final progressColor = Theme.of(context).colorScheme.primary; + + return Container( + width: diameter, + height: diameter, + padding: const EdgeInsets.all(strokeWidth / 2), + child: CircularProgressIndicator( + color: progressColor.withValues(alpha: opacity), + strokeWidth: strokeWidth, + ), + ); + } +} + +class _FeedbackMessage extends StatefulWidget { + final FeedbackType type; + final String message; + final DateTime? start, stop; + final Color progressColor; + + const _FeedbackMessage({ + required this.type, + required this.message, + required this.progressColor, + this.start, + this.stop, + }); + + @override + State<_FeedbackMessage> createState() => _FeedbackMessageState(); +} + +class _FeedbackMessageState extends State<_FeedbackMessage> with SingleTickerProviderStateMixin { + AnimationController? _animationController; + CurvedAnimation? _animation; + Animation<int>? _remainingDurationMillis; + int? _totalDurationMillis; + + @override + void initState() { + super.initState(); + final start = widget.start; + final stop = widget.stop; + if (start != null && stop != null) { + _totalDurationMillis = stop.difference(start).inMilliseconds; + final remainingDuration = stop.difference(DateTime.now()); + final effectiveDuration = remainingDuration > Duration.zero ? remainingDuration : const Duration(milliseconds: 1); + _animationController = AnimationController( + duration: effectiveDuration, + vsync: this, + ); + _animation = CurvedAnimation( + parent: _animationController!, + curve: Curves.linear, + ); + _remainingDurationMillis = IntTween( + begin: effectiveDuration.inMilliseconds, + end: 0, + ).animate(_animation!); + _animationController!.forward(); + } + } + + @override + void dispose() { + _animation?.dispose(); + _animationController?.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final durationFormatter = NumberFormat('0', context.locale); + + final textScaler = MediaQuery.textScalerOf(context); + final theme = Theme.of(context); + final colorScheme = theme.colorScheme; + final contentTextStyle = theme.snackBarTheme.contentTextStyle ?? + theme.textTheme.bodyMedium!.copyWith( + color: colorScheme.onInverseSurface, + ); + final contentTextFontSize = contentTextStyle.fontSize ?? theme.textTheme.bodyMedium!.fontSize!; + final timerChangeShadowColor = colorScheme.primary; + + final remainingDurationAnimation = _remainingDurationMillis; + return Row( + children: [ + if (widget.type == FeedbackType.warn) ...[ + CustomPaint( + painter: const _WarnIndicator(AColors.warning), + size: Size(4, textScaler.scale(contentTextFontSize)), + ), + const SizedBox(width: 8), + ], + Expanded(child: Text(widget.message)), + if (remainingDurationAnimation != null) ...[ + const SizedBox(width: 16), + AnimatedBuilder( + animation: remainingDurationAnimation, + builder: (context, child) { + final remainingDurationMillis = remainingDurationAnimation.value; + final totalDurationMillis = _totalDurationMillis; + return CircularIndicator( + radius: 16, + lineWidth: 2, + percent: totalDurationMillis != null && totalDurationMillis > 0 ? remainingDurationMillis / totalDurationMillis : 0, + background: Colors.grey, + // progress color is provided by the caller, + // because we cannot use the app context theme here + foreground: widget.progressColor, + center: ChangeHighlightText( + durationFormatter.format((remainingDurationMillis / 1000).ceil()), + style: contentTextStyle.copyWith( + shadows: [ + Shadow( + color: timerChangeShadowColor.withAlpha(0), + blurRadius: 0, + ) + ], + ), + changedStyle: contentTextStyle.copyWith( + shadows: [ + Shadow( + color: timerChangeShadowColor, + blurRadius: 5, + ) + ], + ), + duration: context.read<DurationsData>().formTextStyleTransition, + ), + ); + }, + ), + ] + ], + ); + } +} + +class _WarnIndicator extends CustomPainter { + final Color color; + + const _WarnIndicator(this.color); + + @override + void paint(Canvas canvas, Size size) { + canvas.drawRRect( + RRect.fromLTRBR(0, 0, size.width, size.height, Radius.circular(size.shortestSide / 2)), + Paint() + ..style = PaintingStyle.fill + ..color = color, + ); + } + + @override + bool shouldRepaint(_WarnIndicator oldDelegate) => false; +} + +class ActionFeedback extends StatefulWidget { + final Widget? child; + + const ActionFeedback({ + super.key, + required this.child, + }); + + @override + State<ActionFeedback> createState() => _ActionFeedbackState(); +} + +class _ActionFeedbackState extends State<ActionFeedback> with SingleTickerProviderStateMixin { + late final AnimationController _animationController; + + @override + void initState() { + super.initState(); + _animationController = AnimationController( + duration: ADurations.viewerActionFeedbackAnimation, + vsync: this, + ); + } + + @override + void didUpdateWidget(covariant ActionFeedback oldWidget) { + super.didUpdateWidget(oldWidget); + + if (oldWidget.child != widget.child) { + _animationController.reset(); + if (widget.child != null) { + _animationController.forward(); + } + } + } + + @override + void dispose() { + _animationController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return IgnorePointer( + child: Center( + child: AnimatedBuilder( + animation: _animationController, + builder: (context, child) { + final t = _animationController.value; + final opacity = Curves.easeOutQuad.transform(t > .5 ? (1 - t) * 2 : t * 2); + final scale = Curves.slowMiddle.transform(t) * 2; + return Opacity( + opacity: opacity, + child: Transform.scale( + scale: scale, + child: child, + ), + ); + }, + child: widget.child, + ), + ), + ); + } +} diff --git a/lib/widgets/common/action_mixins/overlay_snack_bar.dart b/lib/widgets/common/action_mixins/overlay_snack_bar.dart new file mode 100644 index 0000000..a32206a --- /dev/null +++ b/lib/widgets/common/action_mixins/overlay_snack_bar.dart @@ -0,0 +1,431 @@ +import 'package:aves/widgets/common/extensions/theme.dart'; +import 'package:flutter/material.dart'; + +// adapted from Flutter `SnackBar` in `/material/snack_bar.dart` + +// As of Flutter v3.23.0, `SnackBar` is not customizable enough to add margin +// and ignore pointers in that area, so we use an overlay entry instead. +// This overlay entry is not under a `Scaffold` (which is expected by `SnackBar` +// and `SnackBarAction`), and is not dismissed the same way. + +const double _singleLineVerticalPadding = 14.0; +const Duration _snackBarDisplayDuration = Duration(milliseconds: 4000); +const Curve _snackBarHeightCurve = Curves.fastOutSlowIn; +const Curve _snackBarM3HeightCurve = Curves.easeInOutQuart; + +const Curve _snackBarFadeInCurve = Interval(0.4, 1.0); +const Curve _snackBarM3FadeInCurve = Interval(0.4, 0.6, curve: Curves.easeInCirc); +const Curve _snackBarFadeOutCurve = Interval(0.72, 1.0, curve: Curves.fastOutSlowIn); + +class OverlaySnackBar extends StatefulWidget { + final Widget content; + final Color? backgroundColor; + final double? elevation; + final EdgeInsetsGeometry? margin; + final EdgeInsetsGeometry? padding; + final double? width; + final ShapeBorder? shape; + final HitTestBehavior? hitTestBehavior; + final SnackBarBehavior? behavior; + final Widget? action; + final double? actionOverflowThreshold; + final bool? showCloseIcon; + final Color? closeIconColor; + final Duration duration; + final Animation<double>? animation; + final VoidCallback? onVisible; + final DismissDirection dismissDirection; + final Clip clipBehavior; + final VoidCallback onDismiss; + + const OverlaySnackBar({ + super.key, + required this.content, + this.backgroundColor, + this.elevation, + this.margin, + this.padding, + this.width, + this.shape, + this.hitTestBehavior, + this.behavior, + this.action, + this.actionOverflowThreshold, + this.showCloseIcon, + this.closeIconColor, + this.duration = _snackBarDisplayDuration, + this.animation, + this.onVisible, + this.dismissDirection = DismissDirection.down, + this.clipBehavior = Clip.hardEdge, + required this.onDismiss, + }) : assert(elevation == null || elevation >= 0.0), + assert( + width == null || margin == null, + 'Width and margin can not be used together', + ), + assert(actionOverflowThreshold == null || (actionOverflowThreshold >= 0 && actionOverflowThreshold <= 1), 'Action overflow threshold must be between 0 and 1 inclusive'); + + @override + State<OverlaySnackBar> createState() => _OverlaySnackBarState(); +} + +class _OverlaySnackBarState extends State<OverlaySnackBar> { + bool _wasVisible = false; + + CurvedAnimation? _heightAnimation; + CurvedAnimation? _fadeInAnimation; + CurvedAnimation? _fadeInM3Animation; + CurvedAnimation? _fadeOutAnimation; + CurvedAnimation? _heightM3Animation; + + @override + void initState() { + super.initState(); + widget.animation!.addStatusListener(_onAnimationStatusChanged); + _setAnimations(); + } + + @override + void didUpdateWidget(OverlaySnackBar oldWidget) { + super.didUpdateWidget(oldWidget); + if (widget.animation != oldWidget.animation) { + oldWidget.animation!.removeStatusListener(_onAnimationStatusChanged); + widget.animation!.addStatusListener(_onAnimationStatusChanged); + _disposeAnimations(); + _setAnimations(); + } + } + + void _setAnimations() { + assert(widget.animation != null); + _heightAnimation = CurvedAnimation(parent: widget.animation!, curve: _snackBarHeightCurve); + _fadeInAnimation = CurvedAnimation(parent: widget.animation!, curve: _snackBarFadeInCurve); + _fadeInM3Animation = CurvedAnimation(parent: widget.animation!, curve: _snackBarM3FadeInCurve); + _fadeOutAnimation = CurvedAnimation( + parent: widget.animation!, + curve: _snackBarFadeOutCurve, + reverseCurve: const Threshold(0.0), + ); + // Material 3 Animation has a height animation on entry, but a direct fade out on exit. + _heightM3Animation = CurvedAnimation( + parent: widget.animation!, + curve: _snackBarM3HeightCurve, + reverseCurve: const Threshold(0.0), + ); + } + + void _disposeAnimations() { + _heightAnimation?.dispose(); + _fadeInAnimation?.dispose(); + _fadeInM3Animation?.dispose(); + _fadeOutAnimation?.dispose(); + _heightM3Animation?.dispose(); + _heightAnimation = null; + _fadeInAnimation = null; + _fadeInM3Animation = null; + _fadeOutAnimation = null; + _heightM3Animation = null; + } + + @override + void dispose() { + widget.animation!.removeStatusListener(_onAnimationStatusChanged); + _disposeAnimations(); + super.dispose(); + } + + void _onAnimationStatusChanged(AnimationStatus status) { + if (status.isCompleted) { + if (widget.onVisible != null && !_wasVisible) { + widget.onVisible!(); + } + _wasVisible = true; + } + } + + @override + Widget build(BuildContext context) { + assert(debugCheckHasMediaQuery(context)); + final bool accessibleNavigation = MediaQuery.accessibleNavigationOf(context); + assert(widget.animation != null); + final ThemeData theme = Theme.of(context); + final ColorScheme colorScheme = theme.colorScheme; + final SnackBarThemeData snackBarTheme = theme.snackBarTheme; + final bool isThemeDark = theme.isDark; + final Color buttonColor = isThemeDark ? colorScheme.primary : colorScheme.secondary; + final SnackBarThemeData defaults = _SnackbarDefaultsM3(context); + + // SnackBar uses a theme that is the opposite brightness from + // the surrounding theme. + final Brightness brightness = isThemeDark ? Brightness.light : Brightness.dark; + + // Invert the theme values for Material 2. Material 3 values are tokenized to pre-inverted values. + final ThemeData effectiveTheme = theme.useMaterial3 + ? theme + : theme.copyWith( + colorScheme: ColorScheme( + primary: colorScheme.onPrimary, + secondary: buttonColor, + surface: colorScheme.onSurface, + error: colorScheme.onError, + onPrimary: colorScheme.primary, + onSecondary: colorScheme.secondary, + onSurface: colorScheme.surface, + onError: colorScheme.error, + brightness: brightness, + ), + ); + + final TextStyle? contentTextStyle = snackBarTheme.contentTextStyle ?? defaults.contentTextStyle; + final SnackBarBehavior snackBarBehavior = widget.behavior ?? snackBarTheme.behavior ?? defaults.behavior!; + final double? width = widget.width ?? snackBarTheme.width; + assert(() { + // Whether the behavior is set through the constructor or the theme, + // assert that our other properties are configured properly. + if (snackBarBehavior != SnackBarBehavior.floating) { + String message(String parameter) { + final String prefix = '$parameter can only be used with floating behavior.'; + if (widget.behavior != null) { + return '$prefix SnackBarBehavior.fixed was set in the SnackBar constructor.'; + } else if (snackBarTheme.behavior != null) { + return '$prefix SnackBarBehavior.fixed was set by the inherited SnackBarThemeData.'; + } else { + return '$prefix SnackBarBehavior.fixed was set by default.'; + } + } + + assert(widget.margin == null, message('Margin')); + assert(width == null, message('Width')); + } + return true; + }()); + + final bool showCloseIcon = widget.showCloseIcon ?? snackBarTheme.showCloseIcon ?? defaults.showCloseIcon!; + + final bool isFloatingSnackBar = snackBarBehavior == SnackBarBehavior.floating; + final double horizontalPadding = isFloatingSnackBar ? 16.0 : 24.0; + final EdgeInsetsGeometry padding = widget.padding ?? EdgeInsetsDirectional.only(start: horizontalPadding, end: widget.action != null || showCloseIcon ? 0 : horizontalPadding); + + final double iconHorizontalMargin = (widget.padding?.resolve(TextDirection.ltr).right ?? horizontalPadding) / 12.0; + + final IconButton? iconButton = showCloseIcon + ? IconButton( + icon: const Icon(Icons.close), + iconSize: 24, + color: widget.closeIconColor ?? snackBarTheme.closeIconColor ?? defaults.closeIconColor, + onPressed: () => ScaffoldMessenger.of(context).hideCurrentSnackBar(reason: SnackBarClosedReason.dismiss), + tooltip: MaterialLocalizations.of(context).closeButtonTooltip, + ) + : null; + + final EdgeInsets margin = widget.margin?.resolve(TextDirection.ltr) ?? snackBarTheme.insetPadding ?? defaults.insetPadding!; + + Widget snackBar = Padding( + padding: padding, + child: Row( + children: <Widget>[ + Expanded( + child: Container( + padding: widget.action != null ? null : const EdgeInsets.symmetric(vertical: _singleLineVerticalPadding), + child: DefaultTextStyle( + style: contentTextStyle!, + child: widget.content, + ), + ), + ), + if (widget.action != null) + TextButtonTheme( + data: TextButtonThemeData( + style: TextButton.styleFrom( + foregroundColor: buttonColor, + padding: EdgeInsets.symmetric(horizontal: horizontalPadding), + ), + ), + child: widget.action!, + ), + if (showCloseIcon) + Padding( + padding: EdgeInsets.symmetric(horizontal: iconHorizontalMargin), + child: iconButton, + ), + ], + ), + ); + + if (!isFloatingSnackBar) { + snackBar = SafeArea( + top: false, + child: snackBar, + ); + } + + final double elevation = widget.elevation ?? snackBarTheme.elevation ?? defaults.elevation!; + final Color backgroundColor = widget.backgroundColor ?? snackBarTheme.backgroundColor ?? defaults.backgroundColor!; + final ShapeBorder? shape = widget.shape ?? snackBarTheme.shape ?? (isFloatingSnackBar ? defaults.shape : null); + + snackBar = Material( + shape: shape, + elevation: elevation, + color: backgroundColor, + clipBehavior: widget.clipBehavior, + child: Theme( + data: effectiveTheme, + child: accessibleNavigation || theme.useMaterial3 + ? snackBar + : FadeTransition( + opacity: _fadeOutAnimation!, + child: snackBar, + ), + ), + ); + + if (isFloatingSnackBar) { + // If width is provided, do not include horizontal margins. + if (width != null) { + snackBar = Container( + margin: EdgeInsets.only(top: margin.top, bottom: margin.bottom), + width: width, + child: snackBar, + ); + } else { + snackBar = Padding( + padding: margin, + child: snackBar, + ); + } + snackBar = SafeArea( + top: false, + bottom: false, + child: snackBar, + ); + } + + snackBar = Semantics( + container: true, + liveRegion: true, + onDismiss: widget.onDismiss, + child: Dismissible( + key: const Key('dismissible'), + direction: widget.dismissDirection, + resizeDuration: null, + behavior: widget.hitTestBehavior ?? (widget.margin != null || snackBarTheme.insetPadding != null ? HitTestBehavior.deferToChild : HitTestBehavior.opaque), + onDismissed: (direction) => widget.onDismiss(), + child: snackBar, + ), + ); + + final Widget snackBarTransition; + if (accessibleNavigation) { + snackBarTransition = snackBar; + } else if (isFloatingSnackBar && !theme.useMaterial3) { + snackBarTransition = FadeTransition( + opacity: _fadeInAnimation!, + child: snackBar, + ); + // Is Material 3 Floating Snack Bar. + } else if (isFloatingSnackBar && theme.useMaterial3) { + snackBarTransition = FadeTransition( + opacity: _fadeInM3Animation!, + child: ValueListenableBuilder<double>( + valueListenable: _heightM3Animation!, + builder: (context, value, child) { + return Align( + alignment: Alignment.bottomLeft, + heightFactor: value, + child: child, + ); + }, + child: snackBar, + ), + ); + } else { + snackBarTransition = ValueListenableBuilder<double>( + valueListenable: _heightAnimation!, + builder: (context, value, child) { + return Align( + alignment: AlignmentDirectional.topStart, + heightFactor: value, + child: child, + ); + }, + child: snackBar, + ); + } + + return Hero( + tag: '<SnackBar Hero tag - ${widget.content}>', + transitionOnUserGestures: true, + child: ClipRect( + clipBehavior: widget.clipBehavior, + child: snackBarTransition, + ), + ); + } +} + +// BEGIN GENERATED TOKEN PROPERTIES - Snackbar + +// Do not edit by hand. The code between the "BEGIN GENERATED" and +// "END GENERATED" comments are generated from data in the Material +// Design token database by the script: +// dev/tools/gen_defaults/bin/gen_defaults.dart. + +class _SnackbarDefaultsM3 extends SnackBarThemeData { + _SnackbarDefaultsM3(this.context); + + final BuildContext context; + late final ThemeData _theme = Theme.of(context); + late final ColorScheme _colors = _theme.colorScheme; + + @override + Color get backgroundColor => _colors.inverseSurface; + + @override + Color get actionTextColor => WidgetStateColor.resolveWith((states) { + if (states.contains(WidgetState.disabled)) { + return _colors.inversePrimary; + } + if (states.contains(WidgetState.pressed)) { + return _colors.inversePrimary; + } + if (states.contains(WidgetState.hovered)) { + return _colors.inversePrimary; + } + if (states.contains(WidgetState.focused)) { + return _colors.inversePrimary; + } + return _colors.inversePrimary; + }); + + @override + Color get disabledActionTextColor => _colors.inversePrimary; + + @override + TextStyle get contentTextStyle => Theme.of(context).textTheme.bodyMedium!.copyWith( + color: _colors.onInverseSurface, + ); + + @override + double get elevation => 6.0; + + @override + ShapeBorder get shape => const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4.0))); + + @override + SnackBarBehavior get behavior => SnackBarBehavior.fixed; + + @override + EdgeInsets get insetPadding => const EdgeInsets.fromLTRB(15.0, 5.0, 15.0, 10.0); + + @override + bool get showCloseIcon => false; + + @override + Color? get closeIconColor => _colors.onInverseSurface; + + @override + double get actionOverflowThreshold => 0.25; +} + +// END GENERATED TOKEN PROPERTIES - Snackbar diff --git a/lib/widgets/common/action_mixins/permission_aware.dart b/lib/widgets/common/action_mixins/permission_aware.dart new file mode 100644 index 0000000..c553fd9 --- /dev/null +++ b/lib/widgets/common/action_mixins/permission_aware.dart @@ -0,0 +1,119 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/props.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/utils/android_file_utils.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; + +mixin PermissionAwareMixin { + Future<bool> checkStoragePermission(BuildContext context, Set<AvesEntry> entries) { + final storageDirs = entries.map((e) => e.storageDirectory).nonNulls.toSet(); + return checkStoragePermissionForAlbums(context, storageDirs, entries: entries); + } + + Future<bool> checkStoragePermissionForAlbums(BuildContext context, Set<String> storageDirs, {Set<AvesEntry>? entries}) async { + final restrictedDirsLowerCase = await storageService.getRestrictedDirectoriesLowerCase(); + while (true) { + final inaccessibleDirs = await storageService.getInaccessibleDirectories(storageDirs); + + final restrictedInaccessibleDirsLowerCase = inaccessibleDirs + .map((dir) => dir.copyWith( + relativeDir: dir.relativeDir.toLowerCase(), + )) + .where(restrictedDirsLowerCase.contains) + .toSet(); + if (restrictedInaccessibleDirsLowerCase.isNotEmpty) { + if (entries != null && await storageService.canRequestMediaFileBulkAccess()) { + // request media file access for items in restricted directories + final uris = <String>[], mimeTypes = <String>[]; + entries.where((entry) { + final dirPath = entry.directory; + if (dirPath == null) return false; + final dir = androidFileUtils.relativeDirectoryFromPath(dirPath); + return restrictedInaccessibleDirsLowerCase.contains(dir?.copyWith(relativeDir: dir.relativeDir.toLowerCase())); + }).forEach((entry) { + uris.add(entry.uri); + mimeTypes.add(entry.mimeType); + }); + final granted = await storageService.requestMediaFileAccess(uris, mimeTypes); + if (!granted) return false; + } else if (entries == null && await storageService.canInsertMedia(restrictedInaccessibleDirsLowerCase)) { + // insertion in restricted directories + } else { + // cannot proceed further + await showRestrictedDirectoryDialog(context, restrictedInaccessibleDirsLowerCase.first); + return false; + } + // clear restricted directories + inaccessibleDirs.removeWhere((dir) => restrictedInaccessibleDirsLowerCase.contains(dir.copyWith(relativeDir: dir.relativeDir.toLowerCase()))); + } + + if (inaccessibleDirs.isEmpty) return true; + + final dir = inaccessibleDirs.first; + final confirmed = await showDialog<bool>( + context: context, + builder: (context) { + final l10n = context.l10n; + final directory = dir.relativeDir.isEmpty ? l10n.rootDirectoryDescription : l10n.otherDirectoryDescription(dir.relativeDir); + final volume = dir.getVolumeDescription(context); + return AvesDialog( + content: Text(l10n.storageAccessDialogMessage(directory, volume)), + actions: [ + const CancelButton(), + TextButton( + onPressed: () => Navigator.maybeOf(context)?.pop(true), + // MD2 button labels were upper case but they are lower case in MD3 + child: Text(Themes.asButtonLabel(MaterialLocalizations.of(context).okButtonLabel)), + ), + ], + ); + }, + routeSettings: const RouteSettings(name: AvesDialog.warningRouteName), + ); + // abort if the user cancels in Flutter + if (confirmed == null || !confirmed) return false; + + if (!await _checkSystemFilePickerEnabled(context)) return false; + + final granted = await storageService.requestDirectoryAccess(dir.dirPath); + if (!granted) { + // abort if the user denies access from the native dialog + return false; + } + } + } + + Future<bool?> showRestrictedDirectoryDialog(BuildContext context, VolumeRelativeDirectory dir) { + return showDialog<bool>( + context: context, + builder: (context) { + final directory = dir.relativeDir.isEmpty ? context.l10n.rootDirectoryDescription : context.l10n.otherDirectoryDescription(dir.relativeDir); + final volume = dir.getVolumeDescription(context); + return AvesDialog( + content: Text(context.l10n.restrictedAccessDialogMessage(directory, volume)), + actions: const [OkButton()], + ); + }, + routeSettings: const RouteSettings(name: AvesDialog.warningRouteName), + ); + } + + Future<bool> _checkSystemFilePickerEnabled(BuildContext context) async { + if (await deviceService.isSystemFilePickerEnabled()) return true; + + await showDialog( + context: context, + builder: (context) => AvesDialog( + content: Text(context.l10n.missingSystemFilePickerDialogMessage), + actions: const [OkButton()], + ), + routeSettings: const RouteSettings(name: AvesDialog.warningRouteName), + ); + return false; + } +} diff --git a/lib/widgets/common/action_mixins/size_aware.dart b/lib/widgets/common/action_mixins/size_aware.dart new file mode 100644 index 0000000..0510ea0 --- /dev/null +++ b/lib/widgets/common/action_mixins/size_aware.dart @@ -0,0 +1,92 @@ +import 'dart:async'; +import 'dart:math'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/utils/android_file_utils.dart'; +import 'package:aves/utils/collection_utils.dart'; +import 'package:aves/utils/file_utils.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; + +mixin SizeAwareMixin { + Future<bool> checkFreeSpaceForMove( + BuildContext context, + Set<AvesEntry> selection, + String destinationAlbum, + MoveType moveType, + ) async { + if (moveType == MoveType.toBin) return true; + + // assume we have enough space if we cannot find the volume or its remaining free space + final destinationVolume = androidFileUtils.getStorageVolume(destinationAlbum); + if (destinationVolume == null) return true; + + final free = await storageService.getFreeSpace(destinationVolume); + if (free == null) return true; + + late int needed; + int sumSize(int sum, AvesEntry entry) => sum + (entry.sizeBytes ?? 0); + switch (moveType) { + case MoveType.copy: + case MoveType.export: + needed = selection.fold(0, sumSize); + case MoveType.move: + case MoveType.toBin: + case MoveType.fromBin: + // when moving, we only need space for the entries that are not already on the destination volume + final byVolume = groupBy<AvesEntry, StorageVolume?>(selection, (entry) => androidFileUtils.getStorageVolume(entry.path)).whereNotNullKey(); + final otherVolumes = byVolume.keys.where((volume) => volume != destinationVolume); + final fromOtherVolumes = otherVolumes.fold<int>(0, (sum, volume) => sum + byVolume[volume]!.fold(0, sumSize)); + // and we need at least as much space as the largest entry because individual entries are copied then deleted + final largestSingle = selection.fold<int>(0, (largest, entry) => max(largest, entry.sizeBytes ?? 0)); + needed = max(fromOtherVolumes, largestSingle); + } + + final hasEnoughSpace = needed < free; + if (!hasEnoughSpace) { + await _showNotEnoughSpaceDialog(context, needed, free, destinationVolume); + } + return hasEnoughSpace; + } + + Future<bool> checkFreeSpace( + BuildContext context, + int needed, + String destinationAlbum, + ) async { + // assume we have enough space if we cannot find the volume or its remaining free space + final destinationVolume = androidFileUtils.getStorageVolume(destinationAlbum); + if (destinationVolume == null) return true; + + final free = await storageService.getFreeSpace(destinationVolume); + if (free == null) return true; + + final hasEnoughSpace = needed < free; + if (!hasEnoughSpace) { + await _showNotEnoughSpaceDialog(context, needed, free, destinationVolume); + } + return hasEnoughSpace; + } + + Future<void> _showNotEnoughSpaceDialog(BuildContext context, int needed, int free, StorageVolume destinationVolume) async { + await showDialog( + context: context, + builder: (context) { + final locale = context.locale; + final neededSize = formatFileSize(locale, needed); + final freeSize = formatFileSize(locale, free); + final volume = destinationVolume.getDescription(context); + return AvesDialog( + content: Text(context.l10n.notEnoughSpaceDialogMessage(neededSize, freeSize, volume)), + actions: const [OkButton()], + ); + }, + routeSettings: const RouteSettings(name: AvesDialog.warningRouteName), + ); + } +} diff --git a/lib/widgets/common/action_mixins/vault_aware.dart b/lib/widgets/common/action_mixins/vault_aware.dart new file mode 100644 index 0000000..45ece04 --- /dev/null +++ b/lib/widgets/common/action_mixins/vault_aware.dart @@ -0,0 +1,149 @@ +import 'package:aves/model/filters/covered/stored_album.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/vaults/details.dart'; +import 'package:aves/model/vaults/vaults.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/widgets/common/action_mixins/feedback.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:aves/widgets/dialogs/filter_editors/password_dialog.dart'; +import 'package:aves/widgets/dialogs/filter_editors/pattern_dialog.dart'; +import 'package:aves/widgets/dialogs/filter_editors/pin_dialog.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:local_auth/error_codes.dart' as auth_error; +import 'package:local_auth/local_auth.dart'; + +mixin VaultAwareMixin on FeedbackMixin { + Future<bool> _tryUnlock(BuildContext context, String dirPath) async { + if (!vaults.isVault(dirPath) || !vaults.isLocked(dirPath)) return true; + + final details = vaults.detailsForPath(dirPath); + if (details == null) return false; + + bool? confirmed; + switch (details.lockType) { + case VaultLockType.system: + try { + confirmed = await LocalAuthentication().authenticate( + localizedReason: context.l10n.authenticateToUnlockVault, + ); + } on PlatformException catch (e, stack) { + if (!{'auth_in_progress', 'NotAvailable'}.contains(e.code)) { + // `auth_in_progress`: `Authentication in progress` + // `NotAvailable`: `Required security features not enabled` + await reportService.recordError(e, stack); + } + } + case VaultLockType.pattern: + final pattern = await showDialog<String>( + context: context, + builder: (context) => const PatternDialog(needConfirmation: false), + routeSettings: const RouteSettings(name: PatternDialog.routeName), + ); + if (pattern != null) { + confirmed = pattern == await securityService.readValue(details.passKey); + } + case VaultLockType.pin: + final pin = await showDialog<String>( + context: context, + builder: (context) => const PinDialog(needConfirmation: false), + routeSettings: const RouteSettings(name: PinDialog.routeName), + ); + if (pin != null) { + confirmed = pin == await securityService.readValue(details.passKey); + } + case VaultLockType.password: + final password = await showDialog<String>( + context: context, + builder: (context) => const PasswordDialog(needConfirmation: false), + routeSettings: const RouteSettings(name: PasswordDialog.routeName), + ); + if (password != null) { + confirmed = password == await securityService.readValue(details.passKey); + } + } + + if (confirmed == null || !confirmed) return false; + + await vaults.unlock(context, dirPath); + return true; + } + + Future<bool> unlockAlbum(BuildContext context, String dirPath) async { + final success = await _tryUnlock(context, dirPath); + if (!success) { + showFeedback(context, FeedbackType.warn, context.l10n.genericFailureFeedback); + } + return success; + } + + Future<bool> unlockFilter(BuildContext context, CollectionFilter filter) { + return filter is StoredAlbumFilter ? unlockAlbum(context, filter.album) : Future.value(true); + } + + Future<bool> unlockFilters(BuildContext context, Set<CollectionFilter> filters) async { + var unlocked = true; + await Future.forEach(filters, (filter) async { + if (unlocked) { + unlocked = await unlockFilter(context, filter); + } + }); + return unlocked; + } + + void lockFilters(Set<StoredAlbumFilter> filters) => vaults.lock(filters.map((v) => v.album).toSet()); + + Future<bool> setVaultPass(BuildContext context, VaultDetails details) async { + switch (details.lockType) { + case VaultLockType.system: + final l10n = context.l10n; + try { + return await LocalAuthentication().authenticate( + localizedReason: l10n.authenticateToConfigureVault, + ); + } on PlatformException catch (e, stack) { + await showDialog( + context: context, + builder: (context) => AvesDialog( + content: Text(e.message ?? l10n.genericFailureFeedback), + actions: const [OkButton()], + ), + routeSettings: const RouteSettings(name: AvesDialog.warningRouteName), + ); + if (e.code != auth_error.notAvailable) { + await reportService.recordError(e, stack); + } + } + case VaultLockType.pattern: + final pattern = await showDialog<String>( + context: context, + builder: (context) => const PatternDialog(needConfirmation: true), + routeSettings: const RouteSettings(name: PatternDialog.routeName), + ); + if (pattern != null) { + return await securityService.writeValue(details.passKey, pattern); + } + case VaultLockType.pin: + final pin = await showDialog<String>( + context: context, + builder: (context) => const PinDialog(needConfirmation: true), + routeSettings: const RouteSettings(name: PinDialog.routeName), + ); + if (pin != null) { + return await securityService.writeValue(details.passKey, pin); + } + case VaultLockType.password: + final password = await showDialog<String>( + context: context, + builder: (context) => const PasswordDialog(needConfirmation: true), + routeSettings: const RouteSettings(name: PasswordDialog.routeName), + ); + if (password != null) { + return await securityService.writeValue(details.passKey, password); + } + } + return false; + } +} diff --git a/lib/widgets/common/app_bar/app_bar_subtitle.dart b/lib/widgets/common/app_bar/app_bar_subtitle.dart new file mode 100644 index 0000000..4eb44ee --- /dev/null +++ b/lib/widgets/common/app_bar/app_bar_subtitle.dart @@ -0,0 +1,93 @@ +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/model/source/events.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/extensions/theme.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; + +class SourceStateAwareAppBarTitle extends StatelessWidget { + final Widget title; + final CollectionSource source; + + const SourceStateAwareAppBarTitle({ + super.key, + required this.title, + required this.source, + }); + + @override + Widget build(BuildContext context) { + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + title, + ValueListenableBuilder<SourceState>( + valueListenable: source.stateNotifier, + builder: (context, sourceState, child) { + return AnimatedSwitcher( + duration: ADurations.appBarTitleAnimation, + transitionBuilder: (child, animation) => FadeTransition( + opacity: animation, + child: SizeTransition( + sizeFactor: animation, + child: child, + ), + ), + child: sourceState == SourceState.ready + ? const SizedBox() + : SourceStateSubtitle( + source: source, + ), + ); + }, + ), + ], + ); + } +} + +class SourceStateSubtitle extends StatelessWidget { + final CollectionSource source; + + const SourceStateSubtitle({ + super.key, + required this.source, + }); + + @override + Widget build(BuildContext context) { + final sourceState = source.state; + final subtitle = sourceState.getName(context.l10n); + if (subtitle == null) return const SizedBox(); + + final theme = Theme.of(context); + return DefaultTextStyle.merge( + style: theme.textTheme.bodySmall!.copyWith(fontFeatures: const [FontFeature.disable('smcp')]), + child: ValueListenableBuilder<ProgressEvent>( + valueListenable: source.progressNotifier, + builder: (context, progress, snapshot) { + return Text.rich( + TextSpan( + children: [ + TextSpan(text: subtitle), + if (progress.total != 0 && sourceState != SourceState.locatingCountries) ...[ + const WidgetSpan(child: SizedBox(width: 8)), + TextSpan( + text: '${progress.done}/${progress.total}', + style: TextStyle(color: theme.isDark ? Colors.white30 : Colors.black26), + ), + ] + ], + ), + softWrap: false, + overflow: TextOverflow.fade, + maxLines: 1, + ); + }, + ), + ); + } +} diff --git a/lib/widgets/common/app_bar/app_bar_title.dart b/lib/widgets/common/app_bar/app_bar_title.dart new file mode 100644 index 0000000..cd9f0f9 --- /dev/null +++ b/lib/widgets/common/app_bar/app_bar_title.dart @@ -0,0 +1,28 @@ +import 'package:flutter/material.dart'; + +class InteractiveAppBarTitle extends StatelessWidget { + final GestureTapCallback? onTap; + final Widget child; + + const InteractiveAppBarTitle({ + super.key, + this.onTap, + required this.child, + }); + + @override + Widget build(BuildContext context) { + final textScaler = MediaQuery.textScalerOf(context); + return GestureDetector( + onTap: onTap, + // use a `Container` with a dummy color to make it expand + // so that we can also detect taps around the title `Text` + child: Container( + alignment: AlignmentDirectional.centerStart, + color: Colors.transparent, + height: textScaler.scale(kToolbarHeight), + child: child, + ), + ); + } +} diff --git a/lib/widgets/common/app_bar/crumb_line.dart b/lib/widgets/common/app_bar/crumb_line.dart new file mode 100644 index 0000000..580f1ec --- /dev/null +++ b/lib/widgets/common/app_bar/crumb_line.dart @@ -0,0 +1,106 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class CrumbLine<T> extends StatefulWidget { + final List<String> Function(BuildContext context) split; + final T Function(BuildContext context, int index) combine; + final void Function(T combined) onTap; + + static const EdgeInsets padding = EdgeInsets.only(top: 6, bottom: 20); + + const CrumbLine({ + super.key, + required this.split, + required this.combine, + required this.onTap, + }); + + @override + State<CrumbLine<T>> createState() => _CrumbLineState<T>(); + + static double getPreferredHeight(TextScaler textScaler) => textScaler.scale(22) + padding.vertical; +} + +class _CrumbLineState<T> extends State<CrumbLine<T>> { + final ScrollController _scrollController = ScrollController(); + + @override + void dispose() { + _scrollController.dispose(); + super.dispose(); + } + + @override + void didUpdateWidget(covariant CrumbLine<T> oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.split(context).length < widget.split(context).length) { + // scroll to show last crumb + WidgetsBinding.instance.addPostFrameCallback((_) { + final animate = context.read<Settings>().animate; + final extent = _scrollController.position.maxScrollExtent; + if (animate) { + _scrollController.animateTo( + extent, + duration: const Duration(milliseconds: 500), + curve: Curves.easeOutQuad, + ); + } else { + _scrollController.jumpTo(extent); + } + }); + } + } + + @override + Widget build(BuildContext context) { + final parts = widget.split(context); + + final crumbColor = DefaultTextStyle.of(context).style.color; + return ListView.builder( + scrollDirection: Axis.horizontal, + controller: _scrollController, + padding: const EdgeInsets.symmetric(horizontal: 8), + itemBuilder: (context, index) { + Widget _buildText(String text) => Padding( + padding: const EdgeInsets.symmetric(horizontal: 8), + child: Text(text), + ); + + if (index >= parts.length) return const SizedBox(); + final text = parts[index]; + if (index == parts.length - 1) { + return Center( + child: DefaultTextStyle.merge( + style: TextStyle( + color: Theme.of(context).colorScheme.primary, + ), + child: _buildText(text), + ), + ); + } + return GestureDetector( + onTap: parts.isNotEmpty ? () => widget.onTap(widget.combine(context, index)) : null, + child: Container( + // use a `Container` with a dummy color to make it expand + // so that we can also detect taps around the title `Text` + color: Colors.transparent, + child: Row( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + _buildText(text), + Icon( + AIcons.next, + color: crumbColor, + ), + ], + ), + ), + ); + }, + itemCount: parts.length, + ); + } +} diff --git a/lib/widgets/common/app_bar/sliver_app_bar_title.dart b/lib/widgets/common/app_bar/sliver_app_bar_title.dart new file mode 100644 index 0000000..08b15cf --- /dev/null +++ b/lib/widgets/common/app_bar/sliver_app_bar_title.dart @@ -0,0 +1,23 @@ +import 'package:flutter/material.dart'; + +// as of Flutter v2.8.1, fading opacity in `SliverAppBar` +// is not applied to title when `appBarTheme.titleTextStyle` is defined, +// so this wrapper manually applies opacity to the default text style +class SliverAppBarTitleWrapper extends StatelessWidget { + final Widget child; + + const SliverAppBarTitleWrapper({ + super.key, + required this.child, + }); + + @override + Widget build(BuildContext context) { + final toolbarOpacity = context.dependOnInheritedWidgetOfExactType<FlexibleSpaceBarSettings>()!.toolbarOpacity; + final baseColor = (DefaultTextStyle.of(context).style.color ?? Theme.of(context).textTheme.titleLarge!.color!); + return DefaultTextStyle.merge( + style: TextStyle(color: baseColor.withValues(alpha: toolbarOpacity)), + child: child, + ); + } +} diff --git a/lib/widgets/common/aves_highlight.dart b/lib/widgets/common/aves_highlight.dart new file mode 100644 index 0000000..3a2f4f0 --- /dev/null +++ b/lib/widgets/common/aves_highlight.dart @@ -0,0 +1,103 @@ +// ignore_for_file: depend_on_referenced_packages +import 'package:flutter/material.dart'; +import 'package:highlight/highlight.dart' show highlight, Node; + +// adapted from package `flutter_highlight` v0.7.0 `HighlightView` +// TODO TLAD use the TextSpan getter when this is fixed: https://github.com/git-touch/highlight/issues/6 + +/// Highlight Flutter Widget +class AvesHighlightView extends StatelessWidget { + /// The original code to be highlighted + final String source; + + /// Highlight language + /// + /// It is recommended to give it a value for performance + /// + /// [All available languages](https://github.com/pd4d10/highlight/tree/master/highlight/lib/languages) + final String? language; + + /// Highlight theme + /// + /// [All available themes](https://github.com/pd4d10/highlight/blob/master/flutter_highlight/lib/themes) + final Map<String, TextStyle> theme; + + /// Padding + final EdgeInsetsGeometry? padding; + + /// Text styles + /// + /// Specify text styles such as font family and font size + final TextStyle? textStyle; + + AvesHighlightView({ + super.key, + required String input, + this.language, + this.theme = const {}, + this.padding, + this.textStyle, + int tabSize = 8, // TODO: https://github.com/flutter/flutter/issues/50087 + }) : source = input.replaceAll('\t', ' ' * tabSize); + + List<TextSpan> _convert(List<Node> nodes) { + final spans = <TextSpan>[]; + var currentSpans = spans; + final stack = <List<TextSpan>>[]; + + void _traverse(Node node) { + if (node.value != null) { + currentSpans.add(node.className == null ? TextSpan(text: node.value) : TextSpan(text: node.value, style: theme[node.className!])); + } else if (node.children != null) { + final tmp = <TextSpan>[]; + currentSpans.add(TextSpan(children: tmp, style: theme[node.className!])); + stack.add(currentSpans); + currentSpans = tmp; + + node.children!.forEach((n) { + _traverse(n); + if (n == node.children!.last) { + currentSpans = stack.isEmpty ? spans : stack.removeLast(); + } + }); + } + } + + for (var node in nodes) { + _traverse(node); + } + + return spans; + } + + static const _rootKey = 'root'; + static const _defaultFontColor = Color(0xff000000); + static const _defaultBackgroundColor = Color(0xffffffff); + + // TODO: dart:io is not available at web platform currently + // See: https://github.com/flutter/flutter/issues/39998 + // So we just use monospace here for now + static const _defaultFontFamily = 'monospace'; + + @override + Widget build(BuildContext context) { + var _textStyle = TextStyle( + fontFamily: _defaultFontFamily, + color: theme[_rootKey]?.color ?? _defaultFontColor, + ); + if (textStyle != null) { + _textStyle = _textStyle.merge(textStyle); + } + + return Container( + color: theme[_rootKey]?.backgroundColor ?? _defaultBackgroundColor, + padding: padding, + child: SelectableText.rich( + TextSpan( + style: _textStyle, + children: _convert(highlight.parse(source, language: language).nodes!), + ), + ), + ); + } +} diff --git a/lib/widgets/common/basic/circle.dart b/lib/widgets/common/basic/circle.dart new file mode 100644 index 0000000..0b3fdba --- /dev/null +++ b/lib/widgets/common/basic/circle.dart @@ -0,0 +1,108 @@ +import 'dart:math'; + +import 'package:flutter/material.dart'; + +class CircularIndicator extends StatefulWidget { + final double radius, lineWidth, percent; + final Color background, foreground; + final Widget center; + + const CircularIndicator({ + super.key, + required this.radius, + required this.lineWidth, + required this.percent, + required this.background, + required this.foreground, + required this.center, + }); + + @override + State<CircularIndicator> createState() => _CircularIndicatorState(); +} + +class _CircularIndicatorState extends State<CircularIndicator> { + @override + Widget build(BuildContext context) { + return SizedBox.square( + dimension: widget.radius * 2, + child: Stack( + alignment: Alignment.center, + children: [ + _Circle( + radius: widget.radius, + lineWidth: widget.lineWidth, + percent: 1.0, + color: widget.background, + ), + _Circle( + radius: widget.radius, + lineWidth: widget.lineWidth, + percent: widget.percent, + color: widget.foreground, + ), + widget.center, + ], + ), + ); + } +} + +class _Circle extends StatelessWidget { + final double radius, lineWidth, percent; + final Color color; + + const _Circle({ + required this.radius, + required this.lineWidth, + required this.percent, + required this.color, + }); + + @override + Widget build(BuildContext context) { + return CustomPaint( + size: Size.square(radius), + painter: _CirclePainter( + lineWidth: lineWidth, + radius: radius - lineWidth / 2, + color: color, + percent: percent, + ), + ); + } +} + +class _CirclePainter extends CustomPainter { + final double radius, lineWidth, percent; + final Color color; + + const _CirclePainter({ + required this.radius, + required this.lineWidth, + required this.percent, + required this.color, + }); + + @override + void paint(Canvas canvas, Size size) { + final center = Offset(size.width / 2, size.height / 2); + final paint = Paint() + ..style = PaintingStyle.stroke + ..color = color + ..strokeWidth = lineWidth; + + canvas.translate(center.dx, center.dy); + canvas.rotate(-pi / 2); + canvas.drawArc( + Rect.fromCircle(center: Offset.zero, radius: radius), + 0, + 2 * pi * percent, + false, + paint, + ); + } + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => true; +} diff --git a/lib/widgets/common/basic/color_indicator.dart b/lib/widgets/common/basic/color_indicator.dart new file mode 100644 index 0000000..85b5da0 --- /dev/null +++ b/lib/widgets/common/basic/color_indicator.dart @@ -0,0 +1,46 @@ +import 'package:aves/widgets/common/fx/borders.dart'; +import 'package:flutter/widgets.dart'; + +class ColorIndicator extends StatelessWidget { + final Color? value; + final Color? alternate; + final Widget? child; + + static const double radius = 16; + + const ColorIndicator({ + super.key, + required this.value, + this.alternate, + this.child, + }); + + @override + Widget build(BuildContext context) { + const dimension = radius * 2; + + Gradient? gradient; + final _value = value; + final _alternate = alternate; + if (_value != null && _alternate != null && _alternate != _value) { + gradient = LinearGradient( + begin: AlignmentDirectional.topStart, + end: AlignmentDirectional.bottomEnd, + colors: [_value, _value, _alternate, _alternate], + stops: const [0, .5, .5, 1], + ); + } + + return Container( + height: dimension, + width: dimension, + decoration: BoxDecoration( + color: _value, + border: AvesBorder.border(context), + gradient: gradient, + shape: BoxShape.circle, + ), + child: child, + ); + } +} diff --git a/lib/widgets/common/basic/derived_material_localization.dart b/lib/widgets/common/basic/derived_material_localization.dart new file mode 100644 index 0000000..59bdca1 --- /dev/null +++ b/lib/widgets/common/basic/derived_material_localization.dart @@ -0,0 +1,524 @@ +import 'package:aves/services/common/services.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; + +// apply custom regional preferences on context localization +// until this is fixed: https://github.com/flutter/flutter/issues/122274 +class MaterialLocalizationsRegionalizer extends StatefulWidget { + final Widget child; + + const MaterialLocalizationsRegionalizer({ + super.key, + required this.child, + }); + + @override + State<MaterialLocalizationsRegionalizer> createState() => _MaterialLocalizationsRegionalizerState(); +} + +class _MaterialLocalizationsRegionalizerState extends State<MaterialLocalizationsRegionalizer> { + late final Future<int?> _firstDayOfWeekLoader; + + @override + void initState() { + super.initState(); + _firstDayOfWeekLoader = deviceService.getFirstDayOfWeekIndex(); + } + + @override + Widget build(BuildContext context) { + return FutureBuilder<int?>( + future: _firstDayOfWeekLoader, + builder: (context, snapshot) { + final firstDayOfWeekIndex = snapshot.data; + final localizationsDelegate = DerivedMaterialLocalizationsDelegate( + Localizations.localeOf(context), + DerivedMaterialLocalizations( + parent: MaterialLocalizations.of(context), + firstDayOfWeekIndex: firstDayOfWeekIndex, + ), + ); + return Localizations.override( + context: context, + delegates: [localizationsDelegate], + child: widget.child, + ); + }, + ); + } +} + +class DerivedMaterialLocalizationsDelegate extends LocalizationsDelegate<MaterialLocalizations> { + final Locale locale; + final MaterialLocalizations localizations; + + const DerivedMaterialLocalizationsDelegate(this.locale, this.localizations); + + @override + bool isSupported(Locale locale) => locale == this.locale; + + @override + Future<MaterialLocalizations> load(Locale locale) async { + return SynchronousFuture<MaterialLocalizations>(localizations); + } + + @override + bool shouldReload(DerivedMaterialLocalizationsDelegate old) => true; +} + +class DerivedMaterialLocalizations extends MaterialLocalizations { + final MaterialLocalizations parent; + final int? _firstDayOfWeekIndex; + + DerivedMaterialLocalizations({ + required this.parent, + int? firstDayOfWeekIndex, + }) : _firstDayOfWeekIndex = firstDayOfWeekIndex; + + @override + String aboutListTileTitle(String applicationName) => parent.aboutListTileTitle(applicationName); + + @override + String get alertDialogLabel => parent.alertDialogLabel; + + @override + String get anteMeridiemAbbreviation => parent.anteMeridiemAbbreviation; + + @override + String get backButtonTooltip => parent.backButtonTooltip; + + @override + String get bottomSheetLabel => parent.bottomSheetLabel; + + @override + String get calendarModeButtonLabel => parent.calendarModeButtonLabel; + + @override + String get cancelButtonLabel => parent.cancelButtonLabel; + + @override + String get clearButtonTooltip => parent.clearButtonTooltip; + + @override + String get closeButtonLabel => parent.closeButtonLabel; + + @override + String get closeButtonTooltip => parent.closeButtonTooltip; + + @override + String get continueButtonLabel => parent.continueButtonLabel; + + @override + String get copyButtonLabel => parent.copyButtonLabel; + + @override + String get currentDateLabel => parent.currentDateLabel; + + @override + String get cutButtonLabel => parent.cutButtonLabel; + + @override + String get dateHelpText => parent.dateHelpText; + + @override + String get dateInputLabel => parent.dateInputLabel; + + @override + String get dateOutOfRangeLabel => parent.dateOutOfRangeLabel; + + @override + String get datePickerHelpText => parent.datePickerHelpText; + + @override + String dateRangeEndDateSemanticLabel(String formattedDate) => parent.dateRangeEndDateSemanticLabel(formattedDate); + + @override + String get dateRangeEndLabel => parent.dateRangeEndLabel; + + @override + String get dateRangePickerHelpText => parent.dateRangePickerHelpText; + + @override + String dateRangeStartDateSemanticLabel(String formattedDate) => parent.dateRangeStartDateSemanticLabel(formattedDate); + + @override + String get dateRangeStartLabel => parent.dateRangeStartLabel; + + @override + String get dateSeparator => parent.dateSeparator; + + @override + String get deleteButtonTooltip => parent.deleteButtonTooltip; + + @override + String get dialModeButtonLabel => parent.dialModeButtonLabel; + + @override + String get dialogLabel => parent.dialogLabel; + + @override + String get drawerLabel => parent.drawerLabel; + + @override + int get firstDayOfWeekIndex => _firstDayOfWeekIndex ?? parent.firstDayOfWeekIndex; + + @override + String get firstPageTooltip => parent.firstPageTooltip; + + @override + String formatCompactDate(DateTime date) => parent.formatCompactDate(date); + + @override + String formatDecimal(int number) => parent.formatDecimal(number); + + @override + String formatFullDate(DateTime date) => parent.formatFullDate(date); + + @override + String formatHour(TimeOfDay timeOfDay, {bool alwaysUse24HourFormat = false}) => parent.formatHour(timeOfDay, alwaysUse24HourFormat: alwaysUse24HourFormat); + + @override + String formatMediumDate(DateTime date) => parent.formatMediumDate(date); + + @override + String formatMinute(TimeOfDay timeOfDay) => parent.formatMinute(timeOfDay); + + @override + String formatMonthYear(DateTime date) => parent.formatMonthYear(date); + + @override + String formatShortDate(DateTime date) => parent.formatShortDate(date); + + @override + String formatShortMonthDay(DateTime date) => parent.formatShortMonthDay(date); + + @override + String formatTimeOfDay(TimeOfDay timeOfDay, {bool alwaysUse24HourFormat = false}) => parent.formatTimeOfDay(timeOfDay); + + @override + String formatYear(DateTime date) => parent.formatYear(date); + + @override + String get hideAccountsLabel => parent.hideAccountsLabel; + + @override + String get inputDateModeButtonLabel => parent.inputDateModeButtonLabel; + + @override + String get inputTimeModeButtonLabel => parent.inputTimeModeButtonLabel; + + @override + String get invalidDateFormatLabel => parent.invalidDateFormatLabel; + + @override + String get invalidDateRangeLabel => parent.invalidDateRangeLabel; + + @override + String get invalidTimeLabel => parent.invalidTimeLabel; + + @override + String get keyboardKeyAlt => parent.keyboardKeyAlt; + + @override + String get keyboardKeyAltGraph => parent.keyboardKeyAltGraph; + + @override + String get keyboardKeyBackspace => parent.keyboardKeyBackspace; + + @override + String get keyboardKeyCapsLock => parent.keyboardKeyCapsLock; + + @override + String get keyboardKeyChannelDown => parent.keyboardKeyChannelDown; + + @override + String get keyboardKeyChannelUp => parent.keyboardKeyChannelUp; + + @override + String get keyboardKeyControl => parent.keyboardKeyControl; + + @override + String get keyboardKeyDelete => parent.keyboardKeyDelete; + + @override + String get keyboardKeyEject => parent.keyboardKeyEject; + + @override + String get keyboardKeyEnd => parent.keyboardKeyEnd; + + @override + String get keyboardKeyEscape => parent.keyboardKeyEscape; + + @override + String get keyboardKeyFn => parent.keyboardKeyFn; + + @override + String get keyboardKeyHome => parent.keyboardKeyHome; + + @override + String get keyboardKeyInsert => parent.keyboardKeyInsert; + + @override + String get keyboardKeyMeta => parent.keyboardKeyMeta; + + @override + String get keyboardKeyMetaMacOs => parent.keyboardKeyMetaMacOs; + + @override + String get keyboardKeyMetaWindows => parent.keyboardKeyMetaWindows; + + @override + String get keyboardKeyNumLock => parent.keyboardKeyNumLock; + + @override + String get keyboardKeyNumpad0 => parent.keyboardKeyNumpad0; + + @override + String get keyboardKeyNumpad1 => parent.keyboardKeyNumpad1; + + @override + String get keyboardKeyNumpad2 => parent.keyboardKeyNumpad2; + + @override + String get keyboardKeyNumpad3 => parent.keyboardKeyNumpad3; + + @override + String get keyboardKeyNumpad4 => parent.keyboardKeyNumpad4; + + @override + String get keyboardKeyNumpad5 => parent.keyboardKeyNumpad5; + + @override + String get keyboardKeyNumpad6 => parent.keyboardKeyNumpad6; + + @override + String get keyboardKeyNumpad7 => parent.keyboardKeyNumpad7; + + @override + String get keyboardKeyNumpad8 => parent.keyboardKeyNumpad8; + + @override + String get keyboardKeyNumpad9 => parent.keyboardKeyNumpad9; + + @override + String get keyboardKeyNumpadAdd => parent.keyboardKeyNumpadAdd; + + @override + String get keyboardKeyNumpadComma => parent.keyboardKeyNumpadComma; + + @override + String get keyboardKeyNumpadDecimal => parent.keyboardKeyNumpadDecimal; + + @override + String get keyboardKeyNumpadDivide => parent.keyboardKeyNumpadDivide; + + @override + String get keyboardKeyNumpadEnter => parent.keyboardKeyNumpadEnter; + + @override + String get keyboardKeyNumpadEqual => parent.keyboardKeyNumpadEqual; + + @override + String get keyboardKeyNumpadMultiply => parent.keyboardKeyNumpadMultiply; + + @override + String get keyboardKeyNumpadParenLeft => parent.keyboardKeyNumpadParenLeft; + + @override + String get keyboardKeyNumpadParenRight => parent.keyboardKeyNumpadParenRight; + + @override + String get keyboardKeyNumpadSubtract => parent.keyboardKeyNumpadSubtract; + + @override + String get keyboardKeyPageDown => parent.keyboardKeyPageDown; + + @override + String get keyboardKeyPageUp => parent.keyboardKeyPageUp; + + @override + String get keyboardKeyPower => parent.keyboardKeyPower; + + @override + String get keyboardKeyPowerOff => parent.keyboardKeyPowerOff; + + @override + String get keyboardKeyPrintScreen => parent.keyboardKeyPrintScreen; + + @override + String get keyboardKeyScrollLock => parent.keyboardKeyScrollLock; + + @override + String get keyboardKeySelect => parent.keyboardKeySelect; + + @override + String get keyboardKeyShift => parent.keyboardKeyShift; + + @override + String get keyboardKeySpace => parent.keyboardKeySpace; + + @override + String get lastPageTooltip => parent.lastPageTooltip; + + @override + String licensesPackageDetailText(int licenseCount) => parent.licensesPackageDetailText(licenseCount); + + @override + String get licensesPageTitle => parent.licensesPageTitle; + + @override + String get lookUpButtonLabel => parent.lookUpButtonLabel; + + @override + String get menuBarMenuLabel => parent.menuBarMenuLabel; + + @override + String get menuDismissLabel => parent.menuDismissLabel; + + @override + String get modalBarrierDismissLabel => parent.modalBarrierDismissLabel; + + @override + String get moreButtonTooltip => parent.moreButtonTooltip; + + @override + List<String> get narrowWeekdays => parent.narrowWeekdays; + + @override + String get nextMonthTooltip => parent.nextMonthTooltip; + + @override + String get nextPageTooltip => parent.nextPageTooltip; + + @override + String get okButtonLabel => parent.okButtonLabel; + + @override + String get openAppDrawerTooltip => parent.openAppDrawerTooltip; + + @override + String pageRowsInfoTitle(int firstRow, int lastRow, int rowCount, bool rowCountIsApproximate) => parent.pageRowsInfoTitle(firstRow, lastRow, rowCount, rowCountIsApproximate); + + @override + DateTime? parseCompactDate(String? inputString) => parent.parseCompactDate(inputString); + + @override + String get pasteButtonLabel => parent.pasteButtonLabel; + + @override + String get popupMenuLabel => parent.popupMenuLabel; + + @override + String get postMeridiemAbbreviation => parent.postMeridiemAbbreviation; + + @override + String get previousMonthTooltip => parent.previousMonthTooltip; + + @override + String get previousPageTooltip => parent.previousPageTooltip; + + @override + String get refreshIndicatorSemanticLabel => parent.refreshIndicatorSemanticLabel; + + @override + String remainingTextFieldCharacterCount(int remaining) => parent.remainingTextFieldCharacterCount(remaining); + + @override + String get reorderItemDown => throw UnimplementedError(); + + @override + String get reorderItemLeft => throw UnimplementedError(); + + @override + String get reorderItemRight => throw UnimplementedError(); + + @override + String get reorderItemToEnd => throw UnimplementedError(); + + @override + String get reorderItemToStart => throw UnimplementedError(); + + @override + String get reorderItemUp => throw UnimplementedError(); + + @override + String get rowsPerPageTitle => parent.rowsPerPageTitle; + + @override + String get saveButtonLabel => parent.saveButtonLabel; + + @override + String get scanTextButtonLabel => parent.scanTextButtonLabel; + + @override + String get scrimLabel => parent.scrimLabel; + + @override + String scrimOnTapHint(String modalRouteContentName) => parent.scrimOnTapHint(modalRouteContentName); + + @override + ScriptCategory get scriptCategory => parent.scriptCategory; + + @override + String get searchFieldLabel => parent.searchFieldLabel; + + @override + String get searchWebButtonLabel => parent.searchWebButtonLabel; + + @override + String get selectAllButtonLabel => parent.selectAllButtonLabel; + + @override + String get selectYearSemanticsLabel => parent.selectYearSemanticsLabel; + + @override + String get selectedDateLabel => parent.selectedDateLabel; + + @override + String selectedRowCountTitle(int selectedRowCount) => parent.selectedRowCountTitle(selectedRowCount); + + @override + String get shareButtonLabel => parent.shareButtonLabel; + + @override + String get showAccountsLabel => parent.showAccountsLabel; + + @override + String get showMenuTooltip => parent.showMenuTooltip; + + @override + String get signedInLabel => parent.signedInLabel; + + @override + String tabLabel({required int tabIndex, required int tabCount}) => parent.tabLabel(tabIndex: tabIndex, tabCount: tabCount); + + @override + TimeOfDayFormat timeOfDayFormat({bool alwaysUse24HourFormat = false}) => parent.timeOfDayFormat(alwaysUse24HourFormat: alwaysUse24HourFormat); + + @override + String get timePickerDialHelpText => parent.timePickerDialHelpText; + + @override + String get timePickerHourLabel => parent.timePickerHourLabel; + + @override + String get timePickerHourModeAnnouncement => parent.timePickerHourModeAnnouncement; + + @override + String get timePickerInputHelpText => parent.timePickerInputHelpText; + + @override + String get timePickerMinuteLabel => parent.timePickerMinuteLabel; + + @override + String get timePickerMinuteModeAnnouncement => parent.timePickerMinuteModeAnnouncement; + + @override + String get unspecifiedDate => parent.unspecifiedDate; + + @override + String get unspecifiedDateRange => parent.unspecifiedDateRange; + + @override + String get viewLicensesButtonLabel => parent.viewLicensesButtonLabel; +} diff --git a/lib/widgets/common/basic/draggable_scrollbar/arrow_clipper.dart b/lib/widgets/common/basic/draggable_scrollbar/arrow_clipper.dart new file mode 100644 index 0000000..94deba5 --- /dev/null +++ b/lib/widgets/common/basic/draggable_scrollbar/arrow_clipper.dart @@ -0,0 +1,38 @@ +import 'package:flutter/rendering.dart'; + +class ArrowClipper extends CustomClipper<Path> { + @override + Path getClip(Size size) { + final path = Path(); + path.lineTo(0.0, size.height); + path.lineTo(size.width, size.height); + path.lineTo(size.width, 0.0); + path.lineTo(0.0, 0.0); + path.close(); + + const double arrowWidth = 8.0; + final startPointX = (size.width - arrowWidth) / 2; + var startPointY = size.height / 2 - arrowWidth / 2; + path.moveTo(startPointX, startPointY); + path.lineTo(startPointX + arrowWidth / 2, startPointY - arrowWidth / 2); + path.lineTo(startPointX + arrowWidth, startPointY); + path.lineTo(startPointX + arrowWidth, startPointY + 1.0); + path.lineTo(startPointX + arrowWidth / 2, startPointY - arrowWidth / 2 + 1.0); + path.lineTo(startPointX, startPointY + 1.0); + path.close(); + + startPointY = size.height / 2 + arrowWidth / 2; + path.moveTo(startPointX + arrowWidth, startPointY); + path.lineTo(startPointX + arrowWidth / 2, startPointY + arrowWidth / 2); + path.lineTo(startPointX, startPointY); + path.lineTo(startPointX, startPointY - 1.0); + path.lineTo(startPointX + arrowWidth / 2, startPointY + arrowWidth / 2 - 1.0); + path.lineTo(startPointX + arrowWidth, startPointY - 1.0); + path.close(); + + return path; + } + + @override + bool shouldReclip(covariant CustomClipper<Path> oldClipper) => false; +} diff --git a/lib/widgets/common/basic/draggable_scrollbar/notifications.dart b/lib/widgets/common/basic/draggable_scrollbar/notifications.dart new file mode 100644 index 0000000..28ca11d --- /dev/null +++ b/lib/widgets/common/basic/draggable_scrollbar/notifications.dart @@ -0,0 +1,10 @@ +import 'package:flutter/widgets.dart'; + +@immutable +class DraggableScrollbarNotification extends Notification { + final DraggableScrollbarEvent event; + + const DraggableScrollbarNotification(this.event); +} + +enum DraggableScrollbarEvent { dragStart, dragEnd } diff --git a/lib/widgets/common/basic/draggable_scrollbar/scroll_label.dart b/lib/widgets/common/basic/draggable_scrollbar/scroll_label.dart new file mode 100644 index 0000000..e42c171 --- /dev/null +++ b/lib/widgets/common/basic/draggable_scrollbar/scroll_label.dart @@ -0,0 +1,30 @@ +import 'package:flutter/material.dart'; + +class ScrollLabel extends StatelessWidget { + final Animation<double> animation; + final Color backgroundColor; + final Widget child; + + const ScrollLabel({ + super.key, + required this.child, + required this.animation, + required this.backgroundColor, + }); + + @override + Widget build(BuildContext context) { + return FadeTransition( + opacity: animation, + child: Container( + margin: const EdgeInsetsDirectional.only(end: 12.0), + child: Material( + elevation: 4.0, + color: backgroundColor, + borderRadius: const BorderRadius.all(Radius.circular(16)), + child: child, + ), + ), + ); + } +} diff --git a/lib/widgets/common/basic/draggable_scrollbar/scrollbar.dart b/lib/widgets/common/basic/draggable_scrollbar/scrollbar.dart new file mode 100644 index 0000000..245e2a6 --- /dev/null +++ b/lib/widgets/common/basic/draggable_scrollbar/scrollbar.dart @@ -0,0 +1,364 @@ +import 'dart:async'; + +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/widgets/common/basic/draggable_scrollbar/notifications.dart'; +import 'package:aves/widgets/common/basic/draggable_scrollbar/scroll_label.dart'; +import 'package:aves/widgets/common/basic/draggable_scrollbar/transition.dart'; +import 'package:aves/widgets/common/basic/gestures/gesture_detector.dart'; +import 'package:flutter/widgets.dart'; + +/* + adapted from package `draggable_scrollbar` v0.0.4: + - removed default thumb builders + - allow any `ScrollView` as child + - allow any `Widget` as label content + - moved out constraints responsibility + - various extent & thumb positioning fixes + - null safety + - directionality aware + */ + +/// Build the Scroll Thumb and label using the current configuration +typedef ScrollThumbBuilder = Widget Function( + Color backgroundColor, + Animation<double> thumbAnimation, + Animation<double> labelAnimation, + double height, { + Widget? labelText, +}); + +/// Build a Text widget using the current scroll offset +typedef OffsetLabelBuilder = Widget Function(double offsetY); +typedef TextLabelBuilder = Widget Function(String label); + +/// A widget that will display a BoxScrollView with a ScrollThumb that can be dragged +/// for quick navigation of the BoxScrollView. +class DraggableScrollbar extends StatefulWidget { + /// The background color of the label and thumb + final Color backgroundColor; + + final Map<double, String> Function()? crumbsBuilder; + + final Size scrollThumbSize; + + /// A function that builds a thumb using the current configuration + final ScrollThumbBuilder scrollThumbBuilder; + + /// The amount of padding that should surround the thumb + final EdgeInsets padding; + + /// Determines how quickly the scrollbar will animate in and out + final Duration scrollbarAnimationDuration; + + /// How long should the thumb be visible before fading out + final Duration scrollbarTimeToFade; + + /// Build a Text widget from the current offset in the BoxScrollView + final OffsetLabelBuilder labelTextBuilder; + + final TextLabelBuilder crumbTextBuilder; + + /// The ScrollController for the BoxScrollView + final ScrollController controller; + + final double Function(double scrollOffset, double offsetIncrement)? dragOffsetSnapper; + + /// The view that will be scrolled with the scroll thumb + final Widget child; + + const DraggableScrollbar({ + super.key, + required this.backgroundColor, + required this.scrollThumbSize, + required this.scrollThumbBuilder, + required this.controller, + this.dragOffsetSnapper, + this.crumbsBuilder, + this.padding = EdgeInsets.zero, + this.scrollbarAnimationDuration = const Duration(milliseconds: 300), + this.scrollbarTimeToFade = const Duration(milliseconds: 1000), + required this.labelTextBuilder, + required this.crumbTextBuilder, + required this.child, + }); + + @override + State<DraggableScrollbar> createState() => _DraggableScrollbarState(); + + static const double labelThumbPadding = 16; + + static Widget buildScrollThumbAndLabel({ + required Widget scrollThumb, + required Color backgroundColor, + required Animation<double> thumbAnimation, + required Animation<double> labelAnimation, + required Widget? labelText, + }) { + final scrollThumbAndLabel = labelText == null + ? scrollThumb + : Row( + mainAxisSize: MainAxisSize.min, + mainAxisAlignment: MainAxisAlignment.end, + children: [ + ScrollLabel( + animation: labelAnimation, + backgroundColor: backgroundColor, + child: labelText, + ), + const SizedBox(width: labelThumbPadding), + scrollThumb, + ], + ); + return SlideFadeTransition( + animation: thumbAnimation, + child: scrollThumbAndLabel, + ); + } +} + +class _DraggableScrollbarState extends State<DraggableScrollbar> with TickerProviderStateMixin { + final ValueNotifier<double> _thumbOffsetNotifier = ValueNotifier(0), _viewOffsetNotifier = ValueNotifier(0); + bool _isDragInProcess = false; + double _boundlessThumbOffset = 0, _offsetIncrement = 0; + late Offset _longPressLastGlobalPosition; + + late AnimationController _thumbAnimationController; + late CurvedAnimation _thumbAnimation; + late AnimationController _labelAnimationController; + late CurvedAnimation _labelAnimation; + Timer? _fadeoutTimer; + Map<double, String>? _percentCrumbs; + final Map<double, String> _viewportCrumbs = {}; + + static const double crumbPadding = 30; + static const double crumbMinViewportRatio = 4; + + @override + void initState() { + super.initState(); + + _thumbAnimationController = AnimationController( + vsync: this, + duration: widget.scrollbarAnimationDuration, + ); + + _thumbAnimation = CurvedAnimation( + parent: _thumbAnimationController, + curve: Curves.fastOutSlowIn, + ); + + _labelAnimationController = AnimationController( + vsync: this, + duration: widget.scrollbarAnimationDuration, + ); + + _labelAnimation = CurvedAnimation( + parent: _labelAnimationController, + curve: Curves.fastOutSlowIn, + ); + } + + @override + void didUpdateWidget(covariant DraggableScrollbar oldWidget) { + super.didUpdateWidget(oldWidget); + + if (oldWidget.crumbsBuilder != widget.crumbsBuilder) { + _percentCrumbs = null; + } + } + + @override + void dispose() { + _thumbAnimation.dispose(); + _thumbAnimationController.dispose(); + _labelAnimation.dispose(); + _labelAnimationController.dispose(); + _fadeoutTimer?.cancel(); + super.dispose(); + } + + ScrollController get controller => widget.controller; + + double get scrollBarHeight => context.size!.height - widget.padding.vertical; + + double get thumbMaxScrollExtent => scrollBarHeight - widget.scrollThumbSize.height; + + double get thumbMinScrollExtent => 0.0; + + @override + Widget build(BuildContext context) { + return NotificationListener<ScrollNotification>( + onNotification: (notification) { + _onScrollNotification(notification); + return false; + }, + child: Stack( + children: [ + RepaintBoundary( + child: widget.child, + ), + if (_isDragInProcess) + ..._viewportCrumbs.entries.map((kv) { + final offset = kv.key; + final label = kv.value; + return Positioned.directional( + textDirection: Directionality.of(context), + top: offset, + end: DraggableScrollbar.labelThumbPadding + widget.scrollThumbSize.width, + child: Padding( + padding: widget.padding, + child: ConstrainedBox( + constraints: BoxConstraints(minHeight: widget.scrollThumbSize.height), + child: Center( + child: ScrollLabel( + animation: kAlwaysCompleteAnimation, + backgroundColor: widget.backgroundColor, + child: widget.crumbTextBuilder(label), + ), + ), + ), + ), + ); + }), + // exclude semantics, otherwise this layer will block access to content layers below when using TalkBack + ExcludeSemantics( + child: RepaintBoundary( + child: AGestureDetector( + onLongPressStart: (details) { + _longPressLastGlobalPosition = details.globalPosition; + _onVerticalDragStart(); + }, + onLongPressMoveUpdate: (details) { + final dy = (details.globalPosition - _longPressLastGlobalPosition).dy; + _longPressLastGlobalPosition = details.globalPosition; + _onVerticalDragUpdate(dy); + }, + onLongPressEnd: (_) => _onVerticalDragEnd(), + onVerticalDragStart: (_) => _onVerticalDragStart(), + onVerticalDragUpdate: (details) => _onVerticalDragUpdate(details.delta.dy), + onVerticalDragEnd: (_) => _onVerticalDragEnd(), + longPressTimeout: settings.longPressTimeout, + child: ValueListenableBuilder<double>( + valueListenable: _thumbOffsetNotifier, + builder: (context, thumbOffset, child) => Container( + alignment: AlignmentDirectional.topEnd, + padding: EdgeInsets.only(top: thumbOffset) + widget.padding, + child: widget.scrollThumbBuilder( + widget.backgroundColor, + _thumbAnimation, + _labelAnimation, + widget.scrollThumbSize.height, + labelText: _isDragInProcess + ? ValueListenableBuilder<double>( + valueListenable: _viewOffsetNotifier, + builder: (context, viewOffset, child) => widget.labelTextBuilder(viewOffset + thumbOffset), + ) + : null, + ), + ), + ), + ), + ), + ), + ], + ), + ); + } + + void _onScrollNotification(ScrollNotification notification) { + final scrollMetrics = notification.metrics; + + // do not update the thumb if we cannot actually scroll + if (scrollMetrics.minScrollExtent >= scrollMetrics.maxScrollExtent) return; + + _viewOffsetNotifier.value = scrollMetrics.pixels; + + // we update the thumb position from the scrolled offset + // when the user is not dragging the thumb + if (!_isDragInProcess) { + if (notification is ScrollUpdateNotification) { + final scrollExtent = (scrollMetrics.pixels / scrollMetrics.maxScrollExtent * thumbMaxScrollExtent); + _thumbOffsetNotifier.value = thumbMaxScrollExtent > thumbMinScrollExtent ? scrollExtent.clamp(thumbMinScrollExtent, thumbMaxScrollExtent) : thumbMinScrollExtent; + } + + if (notification is ScrollUpdateNotification || notification is OverscrollNotification) { + _showThumb(); + _scheduleFadeout(); + } + } + } + + void _onVerticalDragStart() { + const DraggableScrollbarNotification(DraggableScrollbarEvent.dragStart).dispatch(context); + _boundlessThumbOffset = _thumbOffsetNotifier.value; + _offsetIncrement = 1 / thumbMaxScrollExtent * controller.position.maxScrollExtent; + _labelAnimationController.forward(); + _fadeoutTimer?.cancel(); + _showThumb(); + _updateViewportCrumbs(); + setState(() => _isDragInProcess = true); + } + + void _onVerticalDragUpdate(double deltaY) { + _showThumb(); + if (_isDragInProcess && thumbMinScrollExtent < thumbMaxScrollExtent) { + // thumb offset + _boundlessThumbOffset += deltaY; + _thumbOffsetNotifier.value = _boundlessThumbOffset.clamp(thumbMinScrollExtent, thumbMaxScrollExtent); + + // scroll offset + final min = controller.position.minScrollExtent; + final max = controller.position.maxScrollExtent; + final scrollOffset = _thumbOffsetNotifier.value / thumbMaxScrollExtent * max; + controller.jumpTo((widget.dragOffsetSnapper?.call(scrollOffset, _offsetIncrement) ?? scrollOffset).clamp(min, max)); + } + } + + void _onVerticalDragEnd() { + const DraggableScrollbarNotification(DraggableScrollbarEvent.dragEnd).dispatch(context); + _scheduleFadeout(); + setState(() => _isDragInProcess = false); + } + + void _showThumb() { + if (_thumbAnimationController.status != AnimationStatus.forward) { + _thumbAnimationController.forward(); + } + } + + void _scheduleFadeout() { + _fadeoutTimer?.cancel(); + _fadeoutTimer = Timer(widget.scrollbarTimeToFade, () { + _thumbAnimationController.reverse(); + _labelAnimationController.reverse(); + _fadeoutTimer = null; + }); + } + + void _updateViewportCrumbs() { + _viewportCrumbs.clear(); + final crumbsBuilder = widget.crumbsBuilder; + if (crumbsBuilder != null) { + final maxOffset = thumbMaxScrollExtent; + final position = controller.position; + if (position.maxScrollExtent / position.viewportDimension > crumbMinViewportRatio) { + double lastLabelOffset = -crumbPadding; + _percentCrumbs ??= crumbsBuilder(); + _percentCrumbs!.entries.forEach((kv) { + final percent = kv.key; + final label = kv.value; + final labelOffset = percent * maxOffset; + if (labelOffset >= lastLabelOffset + crumbPadding) { + lastLabelOffset = labelOffset; + _viewportCrumbs[labelOffset] = label; + } + }); + // hide lonesome crumb, whether it is because of a single section, + // or because multiple sections collapsed to a single crumb + if (_viewportCrumbs.length == 1) { + _viewportCrumbs.clear(); + } + } + } + } +} diff --git a/lib/widgets/common/basic/draggable_scrollbar/transition.dart b/lib/widgets/common/basic/draggable_scrollbar/transition.dart new file mode 100644 index 0000000..2eeb3a3 --- /dev/null +++ b/lib/widgets/common/basic/draggable_scrollbar/transition.dart @@ -0,0 +1,31 @@ +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:flutter/widgets.dart'; + +class SlideFadeTransition extends StatelessWidget { + final Animation<double> animation; + final Widget child; + + const SlideFadeTransition({ + super.key, + required this.animation, + required this.child, + }); + + @override + Widget build(BuildContext context) { + return AnimatedBuilder( + animation: animation, + builder: (context, child) => animation.value == 0.0 ? Container() : child!, + child: SlideTransition( + position: Tween( + begin: Offset((context.isRtl ? -1 : 1) * .3, 0), + end: Offset.zero, + ).animate(animation), + child: FadeTransition( + opacity: animation, + child: child, + ), + ), + ); + } +} diff --git a/lib/widgets/common/basic/font_size_icon_theme.dart b/lib/widgets/common/basic/font_size_icon_theme.dart new file mode 100644 index 0000000..0ef46d6 --- /dev/null +++ b/lib/widgets/common/basic/font_size_icon_theme.dart @@ -0,0 +1,23 @@ +import 'package:flutter/widgets.dart'; + +// scale icons according to text scale +class FontSizeIconTheme extends StatelessWidget { + final Widget child; + + const FontSizeIconTheme({ + super.key, + required this.child, + }); + + @override + Widget build(BuildContext context) { + final textScaler = MediaQuery.textScalerOf(context); + final iconTheme = IconTheme.of(context); + return IconTheme( + data: iconTheme.copyWith( + size: textScaler.scale(iconTheme.size!), + ), + child: child, + ); + } +} diff --git a/lib/widgets/common/basic/gestures/gesture_detector.dart b/lib/widgets/common/basic/gestures/gesture_detector.dart new file mode 100644 index 0000000..e7a6d08 --- /dev/null +++ b/lib/widgets/common/basic/gestures/gesture_detector.dart @@ -0,0 +1,992 @@ +import 'package:flutter/gestures.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/widgets.dart'; + +// as of Flutter v3.27.1, `GestureDetector` does not allow setting long press delay +// adapted from Flutter `GestureDetector` in `/widgets/gesture_detector.dart` +class AGestureDetector extends StatelessWidget { + /// Creates a widget that detects gestures. + /// + /// Pan and scale callbacks cannot be used simultaneously because scale is a + /// superset of pan. Use the scale callbacks instead. + /// + /// Horizontal and vertical drag callbacks cannot be used simultaneously + /// because a combination of a horizontal and vertical drag is a pan. + /// Use the pan callbacks instead. + /// + /// {@youtube 560 315 https://www.youtube.com/watch?v=WhVXkCFPmK4} + /// + /// By default, gesture detectors contribute semantic information to the tree + /// that is used by assistive technology. + AGestureDetector({ + super.key, + this.child, + this.onTapDown, + this.onTapUp, + this.onTap, + this.onTapCancel, + this.onSecondaryTap, + this.onSecondaryTapDown, + this.onSecondaryTapUp, + this.onSecondaryTapCancel, + this.onTertiaryTapDown, + this.onTertiaryTapUp, + this.onTertiaryTapCancel, + this.onDoubleTapDown, + this.onDoubleTap, + this.onDoubleTapCancel, + this.onLongPressDown, + this.onLongPressCancel, + this.onLongPress, + this.onLongPressStart, + this.onLongPressMoveUpdate, + this.onLongPressUp, + this.onLongPressEnd, + this.onSecondaryLongPressDown, + this.onSecondaryLongPressCancel, + this.onSecondaryLongPress, + this.onSecondaryLongPressStart, + this.onSecondaryLongPressMoveUpdate, + this.onSecondaryLongPressUp, + this.onSecondaryLongPressEnd, + this.onTertiaryLongPressDown, + this.onTertiaryLongPressCancel, + this.onTertiaryLongPress, + this.onTertiaryLongPressStart, + this.onTertiaryLongPressMoveUpdate, + this.onTertiaryLongPressUp, + this.onTertiaryLongPressEnd, + this.onVerticalDragDown, + this.onVerticalDragStart, + this.onVerticalDragUpdate, + this.onVerticalDragEnd, + this.onVerticalDragCancel, + this.onHorizontalDragDown, + this.onHorizontalDragStart, + this.onHorizontalDragUpdate, + this.onHorizontalDragEnd, + this.onHorizontalDragCancel, + this.onForcePressStart, + this.onForcePressPeak, + this.onForcePressUpdate, + this.onForcePressEnd, + this.onPanDown, + this.onPanStart, + this.onPanUpdate, + this.onPanEnd, + this.onPanCancel, + this.onScaleStart, + this.onScaleUpdate, + this.onScaleEnd, + this.behavior, + this.excludeFromSemantics = false, + this.dragStartBehavior = DragStartBehavior.start, + this.trackpadScrollCausesScale = false, + this.trackpadScrollToScaleFactor = kDefaultTrackpadScrollToScaleFactor, + this.supportedDevices, + this.longPressTimeout = kLongPressTimeout, + }) : assert(() { + final bool haveVerticalDrag = onVerticalDragStart != null || onVerticalDragUpdate != null || onVerticalDragEnd != null; + final bool haveHorizontalDrag = onHorizontalDragStart != null || onHorizontalDragUpdate != null || onHorizontalDragEnd != null; + final bool havePan = onPanStart != null || onPanUpdate != null || onPanEnd != null; + final bool haveScale = onScaleStart != null || onScaleUpdate != null || onScaleEnd != null; + if (havePan || haveScale) { + if (havePan && haveScale) { + throw FlutterError.fromParts(<DiagnosticsNode>[ + ErrorSummary('Incorrect GestureDetector arguments.'), + ErrorDescription( + 'Having both a pan gesture recognizer and a scale gesture recognizer is redundant; scale is a superset of pan.', + ), + ErrorHint('Just use the scale gesture recognizer.'), + ]); + } + final String recognizer = havePan ? 'pan' : 'scale'; + if (haveVerticalDrag && haveHorizontalDrag) { + throw FlutterError( + 'Incorrect GestureDetector arguments.\n' + 'Simultaneously having a vertical drag gesture recognizer, a horizontal drag gesture recognizer, and a $recognizer gesture recognizer ' + 'will result in the $recognizer gesture recognizer being ignored, since the other two will catch all drags.', + ); + } + } + return true; + }()); + + /// The widget below this widget in the tree. + /// + /// {@macro flutter.widgets.ProxyWidget.child} + final Widget? child; + + /// A pointer that might cause a tap with a primary button has contacted the + /// screen at a particular location. + /// + /// This is called after a short timeout, even if the winning gesture has not + /// yet been selected. If the tap gesture wins, [onTapUp] will be called, + /// otherwise [onTapCancel] will be called. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + final GestureTapDownCallback? onTapDown; + + /// A pointer that will trigger a tap with a primary button has stopped + /// contacting the screen at a particular location. + /// + /// This triggers immediately before [onTap] in the case of the tap gesture + /// winning. If the tap gesture did not win, [onTapCancel] is called instead. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + final GestureTapUpCallback? onTapUp; + + /// A tap with a primary button has occurred. + /// + /// This triggers when the tap gesture wins. If the tap gesture did not win, + /// [onTapCancel] is called instead. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + /// * [onTapUp], which is called at the same time but includes details + /// regarding the pointer position. + final GestureTapCallback? onTap; + + /// The pointer that previously triggered [onTapDown] will not end up causing + /// a tap. + /// + /// This is called after [onTapDown], and instead of [onTapUp] and [onTap], if + /// the tap gesture did not win. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + final GestureTapCancelCallback? onTapCancel; + + /// A tap with a secondary button has occurred. + /// + /// This triggers when the tap gesture wins. If the tap gesture did not win, + /// [onSecondaryTapCancel] is called instead. + /// + /// See also: + /// + /// * [kSecondaryButton], the button this callback responds to. + /// * [onSecondaryTapUp], which is called at the same time but includes details + /// regarding the pointer position. + final GestureTapCallback? onSecondaryTap; + + /// A pointer that might cause a tap with a secondary button has contacted the + /// screen at a particular location. + /// + /// This is called after a short timeout, even if the winning gesture has not + /// yet been selected. If the tap gesture wins, [onSecondaryTapUp] will be + /// called, otherwise [onSecondaryTapCancel] will be called. + /// + /// See also: + /// + /// * [kSecondaryButton], the button this callback responds to. + final GestureTapDownCallback? onSecondaryTapDown; + + /// A pointer that will trigger a tap with a secondary button has stopped + /// contacting the screen at a particular location. + /// + /// This triggers in the case of the tap gesture winning. If the tap gesture + /// did not win, [onSecondaryTapCancel] is called instead. + /// + /// See also: + /// + /// * [onSecondaryTap], a handler triggered right after this one that doesn't + /// pass any details about the tap. + /// * [kSecondaryButton], the button this callback responds to. + final GestureTapUpCallback? onSecondaryTapUp; + + /// The pointer that previously triggered [onSecondaryTapDown] will not end up + /// causing a tap. + /// + /// This is called after [onSecondaryTapDown], and instead of + /// [onSecondaryTapUp], if the tap gesture did not win. + /// + /// See also: + /// + /// * [kSecondaryButton], the button this callback responds to. + final GestureTapCancelCallback? onSecondaryTapCancel; + + /// A pointer that might cause a tap with a tertiary button has contacted the + /// screen at a particular location. + /// + /// This is called after a short timeout, even if the winning gesture has not + /// yet been selected. If the tap gesture wins, [onTertiaryTapUp] will be + /// called, otherwise [onTertiaryTapCancel] will be called. + /// + /// See also: + /// + /// * [kTertiaryButton], the button this callback responds to. + final GestureTapDownCallback? onTertiaryTapDown; + + /// A pointer that will trigger a tap with a tertiary button has stopped + /// contacting the screen at a particular location. + /// + /// This triggers in the case of the tap gesture winning. If the tap gesture + /// did not win, [onTertiaryTapCancel] is called instead. + /// + /// See also: + /// + /// * [kTertiaryButton], the button this callback responds to. + final GestureTapUpCallback? onTertiaryTapUp; + + /// The pointer that previously triggered [onTertiaryTapDown] will not end up + /// causing a tap. + /// + /// This is called after [onTertiaryTapDown], and instead of + /// [onTertiaryTapUp], if the tap gesture did not win. + /// + /// See also: + /// + /// * [kTertiaryButton], the button this callback responds to. + final GestureTapCancelCallback? onTertiaryTapCancel; + + /// A pointer that might cause a double tap has contacted the screen at a + /// particular location. + /// + /// Triggered immediately after the down event of the second tap. + /// + /// If the user completes the double tap and the gesture wins, [onDoubleTap] + /// will be called after this callback. Otherwise, [onDoubleTapCancel] will + /// be called after this callback. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + final GestureTapDownCallback? onDoubleTapDown; + + /// The user has tapped the screen with a primary button at the same location + /// twice in quick succession. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + final GestureTapCallback? onDoubleTap; + + /// The pointer that previously triggered [onDoubleTapDown] will not end up + /// causing a double tap. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + final GestureTapCancelCallback? onDoubleTapCancel; + + /// The pointer has contacted the screen with a primary button, which might + /// be the start of a long-press. + /// + /// This triggers after the pointer down event. + /// + /// If the user completes the long-press, and this gesture wins, + /// [onLongPressStart] will be called after this callback. Otherwise, + /// [onLongPressCancel] will be called after this callback. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + /// * [onSecondaryLongPressDown], a similar callback but for a secondary button. + /// * [onTertiaryLongPressDown], a similar callback but for a tertiary button. + /// * [LongPressGestureRecognizer.onLongPressDown], which exposes this + /// callback at the gesture layer. + final GestureLongPressDownCallback? onLongPressDown; + + /// A pointer that previously triggered [onLongPressDown] will not end up + /// causing a long-press. + /// + /// This triggers once the gesture loses if [onLongPressDown] has previously + /// been triggered. + /// + /// If the user completed the long-press, and the gesture won, then + /// [onLongPressStart] and [onLongPress] are called instead. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + /// * [LongPressGestureRecognizer.onLongPressCancel], which exposes this + /// callback at the gesture layer. + final GestureLongPressCancelCallback? onLongPressCancel; + + /// Called when a long press gesture with a primary button has been recognized. + /// + /// Triggered when a pointer has remained in contact with the screen at the + /// same location for a long period of time. + /// + /// This is equivalent to (and is called immediately after) [onLongPressStart]. + /// The only difference between the two is that this callback does not + /// contain details of the position at which the pointer initially contacted + /// the screen. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + /// * [LongPressGestureRecognizer.onLongPress], which exposes this + /// callback at the gesture layer. + final GestureLongPressCallback? onLongPress; + + /// Called when a long press gesture with a primary button has been recognized. + /// + /// Triggered when a pointer has remained in contact with the screen at the + /// same location for a long period of time. + /// + /// This is equivalent to (and is called immediately before) [onLongPress]. + /// The only difference between the two is that this callback contains + /// details of the position at which the pointer initially contacted the + /// screen, whereas [onLongPress] does not. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + /// * [LongPressGestureRecognizer.onLongPressStart], which exposes this + /// callback at the gesture layer. + final GestureLongPressStartCallback? onLongPressStart; + + /// A pointer has been drag-moved after a long-press with a primary button. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + /// * [LongPressGestureRecognizer.onLongPressMoveUpdate], which exposes this + /// callback at the gesture layer. + final GestureLongPressMoveUpdateCallback? onLongPressMoveUpdate; + + /// A pointer that has triggered a long-press with a primary button has + /// stopped contacting the screen. + /// + /// This is equivalent to (and is called immediately after) [onLongPressEnd]. + /// The only difference between the two is that this callback does not + /// contain details of the state of the pointer when it stopped contacting + /// the screen. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + /// * [LongPressGestureRecognizer.onLongPressUp], which exposes this + /// callback at the gesture layer. + final GestureLongPressUpCallback? onLongPressUp; + + /// A pointer that has triggered a long-press with a primary button has + /// stopped contacting the screen. + /// + /// This is equivalent to (and is called immediately before) [onLongPressUp]. + /// The only difference between the two is that this callback contains + /// details of the state of the pointer when it stopped contacting the + /// screen, whereas [onLongPressUp] does not. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + /// * [LongPressGestureRecognizer.onLongPressEnd], which exposes this + /// callback at the gesture layer. + final GestureLongPressEndCallback? onLongPressEnd; + + /// The pointer has contacted the screen with a secondary button, which might + /// be the start of a long-press. + /// + /// This triggers after the pointer down event. + /// + /// If the user completes the long-press, and this gesture wins, + /// [onSecondaryLongPressStart] will be called after this callback. Otherwise, + /// [onSecondaryLongPressCancel] will be called after this callback. + /// + /// See also: + /// + /// * [kSecondaryButton], the button this callback responds to. + /// * [onLongPressDown], a similar callback but for a secondary button. + /// * [onTertiaryLongPressDown], a similar callback but for a tertiary button. + /// * [LongPressGestureRecognizer.onSecondaryLongPressDown], which exposes + /// this callback at the gesture layer. + final GestureLongPressDownCallback? onSecondaryLongPressDown; + + /// A pointer that previously triggered [onSecondaryLongPressDown] will not + /// end up causing a long-press. + /// + /// This triggers once the gesture loses if [onSecondaryLongPressDown] has + /// previously been triggered. + /// + /// If the user completed the long-press, and the gesture won, then + /// [onSecondaryLongPressStart] and [onSecondaryLongPress] are called instead. + /// + /// See also: + /// + /// * [kSecondaryButton], the button this callback responds to. + /// * [LongPressGestureRecognizer.onSecondaryLongPressCancel], which exposes + /// this callback at the gesture layer. + final GestureLongPressCancelCallback? onSecondaryLongPressCancel; + + /// Called when a long press gesture with a secondary button has been + /// recognized. + /// + /// Triggered when a pointer has remained in contact with the screen at the + /// same location for a long period of time. + /// + /// This is equivalent to (and is called immediately after) + /// [onSecondaryLongPressStart]. The only difference between the two is that + /// this callback does not contain details of the position at which the + /// pointer initially contacted the screen. + /// + /// See also: + /// + /// * [kSecondaryButton], the button this callback responds to. + /// * [LongPressGestureRecognizer.onSecondaryLongPress], which exposes + /// this callback at the gesture layer. + final GestureLongPressCallback? onSecondaryLongPress; + + /// Called when a long press gesture with a secondary button has been + /// recognized. + /// + /// Triggered when a pointer has remained in contact with the screen at the + /// same location for a long period of time. + /// + /// This is equivalent to (and is called immediately before) + /// [onSecondaryLongPress]. The only difference between the two is that this + /// callback contains details of the position at which the pointer initially + /// contacted the screen, whereas [onSecondaryLongPress] does not. + /// + /// See also: + /// + /// * [kSecondaryButton], the button this callback responds to. + /// * [LongPressGestureRecognizer.onSecondaryLongPressStart], which exposes + /// this callback at the gesture layer. + final GestureLongPressStartCallback? onSecondaryLongPressStart; + + /// A pointer has been drag-moved after a long press with a secondary button. + /// + /// See also: + /// + /// * [kSecondaryButton], the button this callback responds to. + /// * [LongPressGestureRecognizer.onSecondaryLongPressMoveUpdate], which exposes + /// this callback at the gesture layer. + final GestureLongPressMoveUpdateCallback? onSecondaryLongPressMoveUpdate; + + /// A pointer that has triggered a long-press with a secondary button has + /// stopped contacting the screen. + /// + /// This is equivalent to (and is called immediately after) + /// [onSecondaryLongPressEnd]. The only difference between the two is that + /// this callback does not contain details of the state of the pointer when + /// it stopped contacting the screen. + /// + /// See also: + /// + /// * [kSecondaryButton], the button this callback responds to. + /// * [LongPressGestureRecognizer.onSecondaryLongPressUp], which exposes + /// this callback at the gesture layer. + final GestureLongPressUpCallback? onSecondaryLongPressUp; + + /// A pointer that has triggered a long-press with a secondary button has + /// stopped contacting the screen. + /// + /// This is equivalent to (and is called immediately before) + /// [onSecondaryLongPressUp]. The only difference between the two is that + /// this callback contains details of the state of the pointer when it + /// stopped contacting the screen, whereas [onSecondaryLongPressUp] does not. + /// + /// See also: + /// + /// * [kSecondaryButton], the button this callback responds to. + /// * [LongPressGestureRecognizer.onSecondaryLongPressEnd], which exposes + /// this callback at the gesture layer. + final GestureLongPressEndCallback? onSecondaryLongPressEnd; + + /// The pointer has contacted the screen with a tertiary button, which might + /// be the start of a long-press. + /// + /// This triggers after the pointer down event. + /// + /// If the user completes the long-press, and this gesture wins, + /// [onTertiaryLongPressStart] will be called after this callback. Otherwise, + /// [onTertiaryLongPressCancel] will be called after this callback. + /// + /// See also: + /// + /// * [kTertiaryButton], the button this callback responds to. + /// * [onLongPressDown], a similar callback but for a primary button. + /// * [onSecondaryLongPressDown], a similar callback but for a secondary button. + /// * [LongPressGestureRecognizer.onTertiaryLongPressDown], which exposes + /// this callback at the gesture layer. + final GestureLongPressDownCallback? onTertiaryLongPressDown; + + /// A pointer that previously triggered [onTertiaryLongPressDown] will not + /// end up causing a long-press. + /// + /// This triggers once the gesture loses if [onTertiaryLongPressDown] has + /// previously been triggered. + /// + /// If the user completed the long-press, and the gesture won, then + /// [onTertiaryLongPressStart] and [onTertiaryLongPress] are called instead. + /// + /// See also: + /// + /// * [kTertiaryButton], the button this callback responds to. + /// * [LongPressGestureRecognizer.onTertiaryLongPressCancel], which exposes + /// this callback at the gesture layer. + final GestureLongPressCancelCallback? onTertiaryLongPressCancel; + + /// Called when a long press gesture with a tertiary button has been + /// recognized. + /// + /// Triggered when a pointer has remained in contact with the screen at the + /// same location for a long period of time. + /// + /// This is equivalent to (and is called immediately after) + /// [onTertiaryLongPressStart]. The only difference between the two is that + /// this callback does not contain details of the position at which the + /// pointer initially contacted the screen. + /// + /// See also: + /// + /// * [kTertiaryButton], the button this callback responds to. + /// * [LongPressGestureRecognizer.onTertiaryLongPress], which exposes + /// this callback at the gesture layer. + final GestureLongPressCallback? onTertiaryLongPress; + + /// Called when a long press gesture with a tertiary button has been + /// recognized. + /// + /// Triggered when a pointer has remained in contact with the screen at the + /// same location for a long period of time. + /// + /// This is equivalent to (and is called immediately before) + /// [onTertiaryLongPress]. The only difference between the two is that this + /// callback contains details of the position at which the pointer initially + /// contacted the screen, whereas [onTertiaryLongPress] does not. + /// + /// See also: + /// + /// * [kTertiaryButton], the button this callback responds to. + /// * [LongPressGestureRecognizer.onTertiaryLongPressStart], which exposes + /// this callback at the gesture layer. + final GestureLongPressStartCallback? onTertiaryLongPressStart; + + /// A pointer has been drag-moved after a long press with a tertiary button. + /// + /// See also: + /// + /// * [kTertiaryButton], the button this callback responds to. + /// * [LongPressGestureRecognizer.onTertiaryLongPressMoveUpdate], which exposes + /// this callback at the gesture layer. + final GestureLongPressMoveUpdateCallback? onTertiaryLongPressMoveUpdate; + + /// A pointer that has triggered a long-press with a tertiary button has + /// stopped contacting the screen. + /// + /// This is equivalent to (and is called immediately after) + /// [onTertiaryLongPressEnd]. The only difference between the two is that + /// this callback does not contain details of the state of the pointer when + /// it stopped contacting the screen. + /// + /// See also: + /// + /// * [kTertiaryButton], the button this callback responds to. + /// * [LongPressGestureRecognizer.onTertiaryLongPressUp], which exposes + /// this callback at the gesture layer. + final GestureLongPressUpCallback? onTertiaryLongPressUp; + + /// A pointer that has triggered a long-press with a tertiary button has + /// stopped contacting the screen. + /// + /// This is equivalent to (and is called immediately before) + /// [onTertiaryLongPressUp]. The only difference between the two is that + /// this callback contains details of the state of the pointer when it + /// stopped contacting the screen, whereas [onTertiaryLongPressUp] does not. + /// + /// See also: + /// + /// * [kTertiaryButton], the button this callback responds to. + /// * [LongPressGestureRecognizer.onTertiaryLongPressEnd], which exposes + /// this callback at the gesture layer. + final GestureLongPressEndCallback? onTertiaryLongPressEnd; + + /// A pointer has contacted the screen with a primary button and might begin + /// to move vertically. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + final GestureDragDownCallback? onVerticalDragDown; + + /// A pointer has contacted the screen with a primary button and has begun to + /// move vertically. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + final GestureDragStartCallback? onVerticalDragStart; + + /// A pointer that is in contact with the screen with a primary button and + /// moving vertically has moved in the vertical direction. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + final GestureDragUpdateCallback? onVerticalDragUpdate; + + /// A pointer that was previously in contact with the screen with a primary + /// button and moving vertically is no longer in contact with the screen and + /// was moving at a specific velocity when it stopped contacting the screen. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + final GestureDragEndCallback? onVerticalDragEnd; + + /// The pointer that previously triggered [onVerticalDragDown] did not + /// complete. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + final GestureDragCancelCallback? onVerticalDragCancel; + + /// A pointer has contacted the screen with a primary button and might begin + /// to move horizontally. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + final GestureDragDownCallback? onHorizontalDragDown; + + /// A pointer has contacted the screen with a primary button and has begun to + /// move horizontally. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + final GestureDragStartCallback? onHorizontalDragStart; + + /// A pointer that is in contact with the screen with a primary button and + /// moving horizontally has moved in the horizontal direction. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + final GestureDragUpdateCallback? onHorizontalDragUpdate; + + /// A pointer that was previously in contact with the screen with a primary + /// button and moving horizontally is no longer in contact with the screen and + /// was moving at a specific velocity when it stopped contacting the screen. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + final GestureDragEndCallback? onHorizontalDragEnd; + + /// The pointer that previously triggered [onHorizontalDragDown] did not + /// complete. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + final GestureDragCancelCallback? onHorizontalDragCancel; + + /// A pointer has contacted the screen with a primary button and might begin + /// to move. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + final GestureDragDownCallback? onPanDown; + + /// A pointer has contacted the screen with a primary button and has begun to + /// move. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + final GestureDragStartCallback? onPanStart; + + /// A pointer that is in contact with the screen with a primary button and + /// moving has moved again. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + final GestureDragUpdateCallback? onPanUpdate; + + /// A pointer that was previously in contact with the screen with a primary + /// button and moving is no longer in contact with the screen and was moving + /// at a specific velocity when it stopped contacting the screen. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + final GestureDragEndCallback? onPanEnd; + + /// The pointer that previously triggered [onPanDown] did not complete. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + final GestureDragCancelCallback? onPanCancel; + + /// The pointers in contact with the screen have established a focal point and + /// initial scale of 1.0. + final GestureScaleStartCallback? onScaleStart; + + /// The pointers in contact with the screen have indicated a new focal point + /// and/or scale. + final GestureScaleUpdateCallback? onScaleUpdate; + + /// The pointers are no longer in contact with the screen. + final GestureScaleEndCallback? onScaleEnd; + + /// The pointer is in contact with the screen and has pressed with sufficient + /// force to initiate a force press. The amount of force is at least + /// [ForcePressGestureRecognizer.startPressure]. + /// + /// This callback will only be fired on devices with pressure + /// detecting screens. + final GestureForcePressStartCallback? onForcePressStart; + + /// The pointer is in contact with the screen and has pressed with the maximum + /// force. The amount of force is at least + /// [ForcePressGestureRecognizer.peakPressure]. + /// + /// This callback will only be fired on devices with pressure + /// detecting screens. + final GestureForcePressPeakCallback? onForcePressPeak; + + /// A pointer is in contact with the screen, has previously passed the + /// [ForcePressGestureRecognizer.startPressure] and is either moving on the + /// plane of the screen, pressing the screen with varying forces or both + /// simultaneously. + /// + /// This callback will only be fired on devices with pressure + /// detecting screens. + final GestureForcePressUpdateCallback? onForcePressUpdate; + + /// The pointer tracked by [onForcePressStart] is no longer in contact with the screen. + /// + /// This callback will only be fired on devices with pressure + /// detecting screens. + final GestureForcePressEndCallback? onForcePressEnd; + + /// How this gesture detector should behave during hit testing when deciding + /// how the hit test propagates to children and whether to consider targets + /// behind this one. + /// + /// This defaults to [HitTestBehavior.deferToChild] if [child] is not null and + /// [HitTestBehavior.translucent] if child is null. + /// + /// See [HitTestBehavior] for the allowed values and their meanings. + final HitTestBehavior? behavior; + + /// Whether to exclude these gestures from the semantics tree. For + /// example, the long-press gesture for showing a tooltip is + /// excluded because the tooltip itself is included in the semantics + /// tree directly and so having a gesture to show it would result in + /// duplication of information. + final bool excludeFromSemantics; + + /// Determines the way that drag start behavior is handled. + /// + /// If set to [DragStartBehavior.start], gesture drag behavior will + /// begin at the position where the drag gesture won the arena. If set to + /// [DragStartBehavior.down] it will begin at the position where a down event + /// is first detected. + /// + /// In general, setting this to [DragStartBehavior.start] will make drag + /// animation smoother and setting it to [DragStartBehavior.down] will make + /// drag behavior feel slightly more reactive. + /// + /// By default, the drag start behavior is [DragStartBehavior.start]. + /// + /// Only the [DragGestureRecognizer.onStart] callbacks for the + /// [VerticalDragGestureRecognizer], [HorizontalDragGestureRecognizer] and + /// [PanGestureRecognizer] are affected by this setting. + /// + /// See also: + /// + /// * [DragGestureRecognizer.dragStartBehavior], which gives an example for the different behaviors. + final DragStartBehavior dragStartBehavior; + + /// The kind of devices that are allowed to be recognized. + /// + /// If set to null, events from all device types will be recognized. Defaults to null. + final Set<PointerDeviceKind>? supportedDevices; + + /// {@macro flutter.gestures.scale.trackpadScrollCausesScale} + final bool trackpadScrollCausesScale; + + /// {@macro flutter.gestures.scale.trackpadScrollToScaleFactor} + final Offset trackpadScrollToScaleFactor; + + final Duration longPressTimeout; + + @override + Widget build(BuildContext context) { + final Map<Type, GestureRecognizerFactory> gestures = <Type, GestureRecognizerFactory>{}; + final DeviceGestureSettings? gestureSettings = MediaQuery.maybeGestureSettingsOf(context); + final ScrollBehavior configuration = ScrollConfiguration.of(context); + + if (onTapDown != null || onTapUp != null || onTap != null || onTapCancel != null || onSecondaryTap != null || onSecondaryTapDown != null || onSecondaryTapUp != null || onSecondaryTapCancel != null || onTertiaryTapDown != null || onTertiaryTapUp != null || onTertiaryTapCancel != null) { + gestures[TapGestureRecognizer] = GestureRecognizerFactoryWithHandlers<TapGestureRecognizer>( + () => TapGestureRecognizer(debugOwner: this, supportedDevices: supportedDevices), + (instance) { + instance + ..onTapDown = onTapDown + ..onTapUp = onTapUp + ..onTap = onTap + ..onTapCancel = onTapCancel + ..onSecondaryTap = onSecondaryTap + ..onSecondaryTapDown = onSecondaryTapDown + ..onSecondaryTapUp = onSecondaryTapUp + ..onSecondaryTapCancel = onSecondaryTapCancel + ..onTertiaryTapDown = onTertiaryTapDown + ..onTertiaryTapUp = onTertiaryTapUp + ..onTertiaryTapCancel = onTertiaryTapCancel + ..gestureSettings = gestureSettings + ..supportedDevices = supportedDevices; + }, + ); + } + + if (onDoubleTap != null || onDoubleTapDown != null || onDoubleTapCancel != null) { + gestures[DoubleTapGestureRecognizer] = GestureRecognizerFactoryWithHandlers<DoubleTapGestureRecognizer>( + () => DoubleTapGestureRecognizer(debugOwner: this, supportedDevices: supportedDevices), + (instance) { + instance + ..onDoubleTapDown = onDoubleTapDown + ..onDoubleTap = onDoubleTap + ..onDoubleTapCancel = onDoubleTapCancel + ..gestureSettings = gestureSettings + ..supportedDevices = supportedDevices; + }, + ); + } + + if (onLongPressDown != null || onLongPressCancel != null || onLongPress != null || onLongPressStart != null || onLongPressMoveUpdate != null || onLongPressUp != null || onLongPressEnd != null || onSecondaryLongPressDown != null || onSecondaryLongPressCancel != null || onSecondaryLongPress != null || onSecondaryLongPressStart != null || onSecondaryLongPressMoveUpdate != null || onSecondaryLongPressUp != null || onSecondaryLongPressEnd != null || onTertiaryLongPressDown != null || onTertiaryLongPressCancel != null || onTertiaryLongPress != null || onTertiaryLongPressStart != null || onTertiaryLongPressMoveUpdate != null || onTertiaryLongPressUp != null || onTertiaryLongPressEnd != null) { + gestures[LongPressGestureRecognizer] = GestureRecognizerFactoryWithHandlers<LongPressGestureRecognizer>( + () => LongPressGestureRecognizer(duration: longPressTimeout, debugOwner: this, supportedDevices: supportedDevices), + (instance) { + instance + ..onLongPressDown = onLongPressDown + ..onLongPressCancel = onLongPressCancel + ..onLongPress = onLongPress + ..onLongPressStart = onLongPressStart + ..onLongPressMoveUpdate = onLongPressMoveUpdate + ..onLongPressUp = onLongPressUp + ..onLongPressEnd = onLongPressEnd + ..onSecondaryLongPressDown = onSecondaryLongPressDown + ..onSecondaryLongPressCancel = onSecondaryLongPressCancel + ..onSecondaryLongPress = onSecondaryLongPress + ..onSecondaryLongPressStart = onSecondaryLongPressStart + ..onSecondaryLongPressMoveUpdate = onSecondaryLongPressMoveUpdate + ..onSecondaryLongPressUp = onSecondaryLongPressUp + ..onSecondaryLongPressEnd = onSecondaryLongPressEnd + ..onTertiaryLongPressDown = onTertiaryLongPressDown + ..onTertiaryLongPressCancel = onTertiaryLongPressCancel + ..onTertiaryLongPress = onTertiaryLongPress + ..onTertiaryLongPressStart = onTertiaryLongPressStart + ..onTertiaryLongPressMoveUpdate = onTertiaryLongPressMoveUpdate + ..onTertiaryLongPressUp = onTertiaryLongPressUp + ..onTertiaryLongPressEnd = onTertiaryLongPressEnd + ..gestureSettings = gestureSettings + ..supportedDevices = supportedDevices; + }, + ); + } + + if (onVerticalDragDown != null || onVerticalDragStart != null || onVerticalDragUpdate != null || onVerticalDragEnd != null || onVerticalDragCancel != null) { + gestures[VerticalDragGestureRecognizer] = GestureRecognizerFactoryWithHandlers<VerticalDragGestureRecognizer>( + () => VerticalDragGestureRecognizer(debugOwner: this, supportedDevices: supportedDevices), + (instance) { + instance + ..onDown = onVerticalDragDown + ..onStart = onVerticalDragStart + ..onUpdate = onVerticalDragUpdate + ..onEnd = onVerticalDragEnd + ..onCancel = onVerticalDragCancel + ..dragStartBehavior = dragStartBehavior + ..multitouchDragStrategy = configuration.getMultitouchDragStrategy(context) + ..gestureSettings = gestureSettings + ..supportedDevices = supportedDevices; + }, + ); + } + + if (onHorizontalDragDown != null || onHorizontalDragStart != null || onHorizontalDragUpdate != null || onHorizontalDragEnd != null || onHorizontalDragCancel != null) { + gestures[HorizontalDragGestureRecognizer] = GestureRecognizerFactoryWithHandlers<HorizontalDragGestureRecognizer>( + () => HorizontalDragGestureRecognizer(debugOwner: this, supportedDevices: supportedDevices), + (instance) { + instance + ..onDown = onHorizontalDragDown + ..onStart = onHorizontalDragStart + ..onUpdate = onHorizontalDragUpdate + ..onEnd = onHorizontalDragEnd + ..onCancel = onHorizontalDragCancel + ..dragStartBehavior = dragStartBehavior + ..multitouchDragStrategy = configuration.getMultitouchDragStrategy(context) + ..gestureSettings = gestureSettings + ..supportedDevices = supportedDevices; + }, + ); + } + + if (onPanDown != null || onPanStart != null || onPanUpdate != null || onPanEnd != null || onPanCancel != null) { + gestures[PanGestureRecognizer] = GestureRecognizerFactoryWithHandlers<PanGestureRecognizer>( + () => PanGestureRecognizer(debugOwner: this, supportedDevices: supportedDevices), + (instance) { + instance + ..onDown = onPanDown + ..onStart = onPanStart + ..onUpdate = onPanUpdate + ..onEnd = onPanEnd + ..onCancel = onPanCancel + ..dragStartBehavior = dragStartBehavior + ..multitouchDragStrategy = configuration.getMultitouchDragStrategy(context) + ..gestureSettings = gestureSettings + ..supportedDevices = supportedDevices; + }, + ); + } + + if (onScaleStart != null || onScaleUpdate != null || onScaleEnd != null) { + gestures[ScaleGestureRecognizer] = GestureRecognizerFactoryWithHandlers<ScaleGestureRecognizer>( + () => ScaleGestureRecognizer(debugOwner: this, supportedDevices: supportedDevices), + (instance) { + instance + ..onStart = onScaleStart + ..onUpdate = onScaleUpdate + ..onEnd = onScaleEnd + ..dragStartBehavior = dragStartBehavior + ..gestureSettings = gestureSettings + ..trackpadScrollCausesScale = trackpadScrollCausesScale + ..trackpadScrollToScaleFactor = trackpadScrollToScaleFactor + ..supportedDevices = supportedDevices; + }, + ); + } + + if (onForcePressStart != null || onForcePressPeak != null || onForcePressUpdate != null || onForcePressEnd != null) { + gestures[ForcePressGestureRecognizer] = GestureRecognizerFactoryWithHandlers<ForcePressGestureRecognizer>( + () => ForcePressGestureRecognizer(debugOwner: this, supportedDevices: supportedDevices), + (instance) { + instance + ..onStart = onForcePressStart + ..onPeak = onForcePressPeak + ..onUpdate = onForcePressUpdate + ..onEnd = onForcePressEnd + ..gestureSettings = gestureSettings + ..supportedDevices = supportedDevices; + }, + ); + } + + return RawGestureDetector( + gestures: gestures, + behavior: behavior, + excludeFromSemantics: excludeFromSemantics, + child: child, + ); + } + + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + super.debugFillProperties(properties); + properties.add(EnumProperty<DragStartBehavior>('startBehavior', dragStartBehavior)); + } +} diff --git a/lib/widgets/common/basic/gestures/ink_well.dart b/lib/widgets/common/basic/gestures/ink_well.dart new file mode 100644 index 0000000..1c3c854 --- /dev/null +++ b/lib/widgets/common/basic/gestures/ink_well.dart @@ -0,0 +1,1089 @@ +import 'dart:async'; +import 'dart:collection'; + +import 'package:aves/widgets/common/basic/gestures/gesture_detector.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; + +// as of Flutter v3.27.1, `InkResponse` does not allow setting long press delay +// adapted from Flutter `InkResponse` and related classes in `/material/ink_well.dart` +class AInkResponse extends StatelessWidget { + /// Creates an area of a [Material] that responds to touch. + /// + /// Must have an ancestor [Material] widget in which to cause ink reactions. + const AInkResponse({ + super.key, + this.child, + this.onTap, + this.onTapDown, + this.onTapUp, + this.onTapCancel, + this.onDoubleTap, + this.onLongPress, + this.onSecondaryTap, + this.onSecondaryTapUp, + this.onSecondaryTapDown, + this.onSecondaryTapCancel, + this.onHighlightChanged, + this.onHover, + this.mouseCursor, + this.containedInkWell = false, + this.highlightShape = BoxShape.circle, + this.radius, + this.borderRadius, + this.customBorder, + this.focusColor, + this.hoverColor, + this.highlightColor, + this.overlayColor, + this.splashColor, + this.splashFactory, + this.enableFeedback = true, + this.excludeFromSemantics = false, + this.focusNode, + this.canRequestFocus = true, + this.onFocusChange, + this.autofocus = false, + this.statesController, + this.hoverDuration, + this.longPressTimeout = kLongPressTimeout, + }); + + /// The widget below this widget in the tree. + /// + /// {@macro flutter.widgets.ProxyWidget.child} + final Widget? child; + + /// Called when the user taps this part of the material. + final GestureTapCallback? onTap; + + /// Called when the user taps down this part of the material. + final GestureTapDownCallback? onTapDown; + + /// Called when the user releases a tap that was started on this part of the + /// material. [onTap] is called immediately after. + final GestureTapUpCallback? onTapUp; + + /// Called when the user cancels a tap that was started on this part of the + /// material. + final GestureTapCallback? onTapCancel; + + /// Called when the user double taps this part of the material. + final GestureTapCallback? onDoubleTap; + + /// Called when the user long-presses on this part of the material. + final GestureLongPressCallback? onLongPress; + + /// Called when the user taps this part of the material with a secondary button. + final GestureTapCallback? onSecondaryTap; + + /// Called when the user taps down on this part of the material with a + /// secondary button. + final GestureTapDownCallback? onSecondaryTapDown; + + /// Called when the user releases a secondary button tap that was started on + /// this part of the material. [onSecondaryTap] is called immediately after. + final GestureTapUpCallback? onSecondaryTapUp; + + /// Called when the user cancels a secondary button tap that was started on + /// this part of the material. + final GestureTapCallback? onSecondaryTapCancel; + + /// Called when this part of the material either becomes highlighted or stops + /// being highlighted. + /// + /// The value passed to the callback is true if this part of the material has + /// become highlighted and false if this part of the material has stopped + /// being highlighted. + /// + /// If all of [onTap], [onDoubleTap], and [onLongPress] become null while a + /// gesture is ongoing, then [onTapCancel] will be fired and + /// [onHighlightChanged] will be fired with the value false _during the + /// build_. This means, for instance, that in that scenario [State.setState] + /// cannot be called. + final ValueChanged<bool>? onHighlightChanged; + + /// Called when a pointer enters or exits the ink response area. + /// + /// The value passed to the callback is true if a pointer has entered this + /// part of the material and false if a pointer has exited this part of the + /// material. + final ValueChanged<bool>? onHover; + + /// The cursor for a mouse pointer when it enters or is hovering over the + /// widget. + /// + /// If [mouseCursor] is a [WidgetStateProperty<MouseCursor>], + /// [WidgetStateProperty.resolve] is used for the following [WidgetState]s: + /// + /// * [WidgetState.hovered]. + /// * [WidgetState.focused]. + /// * [WidgetState.disabled]. + /// + /// If this property is null, [WidgetStateMouseCursor.clickable] will be used. + final MouseCursor? mouseCursor; + + /// Whether this ink response should be clipped its bounds. + /// + /// This flag also controls whether the splash migrates to the center of the + /// [InkResponse] or not. If [containedInkWell] is true, the splash remains + /// centered around the tap location. If it is false, the splash migrates to + /// the center of the [InkResponse] as it grows. + /// + /// See also: + /// + /// * [highlightShape], the shape of the focus, hover, and pressed + /// highlights. + /// * [borderRadius], which controls the corners when the box is a rectangle. + /// * [getRectCallback], which controls the size and position of the box when + /// it is a rectangle. + final bool containedInkWell; + + /// The shape (e.g., circle, rectangle) to use for the highlight drawn around + /// this part of the material when pressed, hovered over, or focused. + /// + /// The same shape is used for the pressed highlight (see [highlightColor]), + /// the focus highlight (see [focusColor]), and the hover highlight (see + /// [hoverColor]). + /// + /// If the shape is [BoxShape.circle], then the highlight is centered on the + /// [InkResponse]. If the shape is [BoxShape.rectangle], then the highlight + /// fills the [InkResponse], or the rectangle provided by [getRectCallback] if + /// the callback is specified. + /// + /// See also: + /// + /// * [containedInkWell], which controls clipping behavior. + /// * [borderRadius], which controls the corners when the box is a rectangle. + /// * [highlightColor], the color of the highlight. + /// * [getRectCallback], which controls the size and position of the box when + /// it is a rectangle. + final BoxShape highlightShape; + + /// The radius of the ink splash. + /// + /// Splashes grow up to this size. By default, this size is determined from + /// the size of the rectangle provided by [getRectCallback], or the size of + /// the [InkResponse] itself. + /// + /// See also: + /// + /// * [splashColor], the color of the splash. + /// * [splashFactory], which defines the appearance of the splash. + final double? radius; + + /// The border radius of the containing rectangle. This is effective only if + /// [highlightShape] is [BoxShape.rectangle]. + /// + /// If this is null, it is interpreted as [BorderRadius.zero]. + final BorderRadius? borderRadius; + + /// The custom clip border. + /// + /// If this is null, the ink response will not clip its content. + final ShapeBorder? customBorder; + + /// The color of the ink response when the parent widget is focused. If this + /// property is null then the focus color of the theme, + /// [ThemeData.focusColor], will be used. + /// + /// See also: + /// + /// * [highlightShape], the shape of the focus, hover, and pressed + /// highlights. + /// * [hoverColor], the color of the hover highlight. + /// * [splashColor], the color of the splash. + /// * [splashFactory], which defines the appearance of the splash. + final Color? focusColor; + + /// The color of the ink response when a pointer is hovering over it. If this + /// property is null then the hover color of the theme, + /// [ThemeData.hoverColor], will be used. + /// + /// See also: + /// + /// * [highlightShape], the shape of the focus, hover, and pressed + /// highlights. + /// * [highlightColor], the color of the pressed highlight. + /// * [focusColor], the color of the focus highlight. + /// * [splashColor], the color of the splash. + /// * [splashFactory], which defines the appearance of the splash. + final Color? hoverColor; + + /// The highlight color of the ink response when pressed. If this property is + /// null then the highlight color of the theme, [ThemeData.highlightColor], + /// will be used. + /// + /// See also: + /// + /// * [hoverColor], the color of the hover highlight. + /// * [focusColor], the color of the focus highlight. + /// * [highlightShape], the shape of the focus, hover, and pressed + /// highlights. + /// * [splashColor], the color of the splash. + /// * [splashFactory], which defines the appearance of the splash. + final Color? highlightColor; + + /// Defines the ink response focus, hover, and splash colors. + /// + /// This default null property can be used as an alternative to + /// [focusColor], [hoverColor], [highlightColor], and + /// [splashColor]. If non-null, it is resolved against one of + /// [WidgetState.focused], [WidgetState.hovered], and + /// [WidgetState.pressed]. It's convenient to use when the parent + /// widget can pass along its own WidgetStateProperty value for + /// the overlay color. + /// + /// [WidgetState.pressed] triggers a ripple (an ink splash), per + /// the current Material Design spec. The [overlayColor] doesn't map + /// a state to [highlightColor] because a separate highlight is not + /// used by the current design guidelines. See + /// https://material.io/design/interaction/states.html#pressed + /// + /// If the overlay color is null or resolves to null, then [focusColor], + /// [hoverColor], [splashColor] and their defaults are used instead. + /// + /// See also: + /// + /// * The Material Design specification for overlay colors and how they + /// match a component's state: + /// <https://material.io/design/interaction/states.html#anatomy>. + final WidgetStateProperty<Color?>? overlayColor; + + /// The splash color of the ink response. If this property is null then the + /// splash color of the theme, [ThemeData.splashColor], will be used. + /// + /// See also: + /// + /// * [splashFactory], which defines the appearance of the splash. + /// * [radius], the (maximum) size of the ink splash. + /// * [highlightColor], the color of the highlight. + final Color? splashColor; + + /// Defines the appearance of the splash. + /// + /// Defaults to the value of the theme's splash factory: [ThemeData.splashFactory]. + /// + /// See also: + /// + /// * [radius], the (maximum) size of the ink splash. + /// * [splashColor], the color of the splash. + /// * [highlightColor], the color of the highlight. + /// * [InkSplash.splashFactory], which defines the default splash. + /// * [InkRipple.splashFactory], which defines a splash that spreads out + /// more aggressively than the default. + final InteractiveInkFeatureFactory? splashFactory; + + /// Whether detected gestures should provide acoustic and/or haptic feedback. + /// + /// For example, on Android a tap will produce a clicking sound and a + /// long-press will produce a short vibration, when feedback is enabled. + /// + /// See also: + /// + /// * [Feedback] for providing platform-specific feedback to certain actions. + final bool enableFeedback; + + /// Whether to exclude the gestures introduced by this widget from the + /// semantics tree. + /// + /// For example, a long-press gesture for showing a tooltip is usually + /// excluded because the tooltip itself is included in the semantics + /// tree directly and so having a gesture to show it would result in + /// duplication of information. + final bool excludeFromSemantics; + + /// {@template flutter.material.inkwell.onFocusChange} + /// Handler called when the focus changes. + /// + /// Called with true if this widget's node gains focus, and false if it loses + /// focus. + /// {@endtemplate} + final ValueChanged<bool>? onFocusChange; + + /// {@macro flutter.widgets.Focus.autofocus} + final bool autofocus; + + /// {@macro flutter.widgets.Focus.focusNode} + final FocusNode? focusNode; + + /// {@macro flutter.widgets.Focus.canRequestFocus} + final bool canRequestFocus; + + /// The rectangle to use for the highlight effect and for clipping + /// the splash effects if [containedInkWell] is true. + /// + /// This method is intended to be overridden by descendants that + /// specialize [InkResponse] for unusual cases. For example, + /// [TableRowInkWell] implements this method to return the rectangle + /// corresponding to the row that the widget is in. + /// + /// The default behavior returns null, which is equivalent to + /// returning the referenceBox argument's bounding box (though + /// slightly more efficient). + RectCallback? getRectCallback(RenderBox referenceBox) => null; + + /// {@template flutter.material.inkwell.statesController} + /// Represents the interactive "state" of this widget in terms of + /// a set of [WidgetState]s, like [WidgetState.pressed] and + /// [WidgetState.focused]. + /// + /// Classes based on this one can provide their own + /// [WidgetStatesController] to which they've added listeners. + /// They can also update the controller's [WidgetStatesController.value] + /// however, this may only be done when it's safe to call + /// [State.setState], like in an event handler. + /// {@endtemplate} + final WidgetStatesController? statesController; + + /// The duration of the animation that animates the hover effect. + /// + /// The default is 50ms. + final Duration? hoverDuration; + + final Duration longPressTimeout; + + @override + Widget build(BuildContext context) { + final _ParentInkResponseState? parentState = _ParentInkResponseProvider.maybeOf(context); + return _InkResponseStateWidget( + onTap: onTap, + onTapDown: onTapDown, + onTapUp: onTapUp, + onTapCancel: onTapCancel, + onDoubleTap: onDoubleTap, + onLongPress: onLongPress, + onSecondaryTap: onSecondaryTap, + onSecondaryTapUp: onSecondaryTapUp, + onSecondaryTapDown: onSecondaryTapDown, + onSecondaryTapCancel: onSecondaryTapCancel, + onHighlightChanged: onHighlightChanged, + onHover: onHover, + mouseCursor: mouseCursor, + containedInkWell: containedInkWell, + highlightShape: highlightShape, + radius: radius, + borderRadius: borderRadius, + customBorder: customBorder, + focusColor: focusColor, + hoverColor: hoverColor, + highlightColor: highlightColor, + overlayColor: overlayColor, + splashColor: splashColor, + splashFactory: splashFactory, + enableFeedback: enableFeedback, + excludeFromSemantics: excludeFromSemantics, + focusNode: focusNode, + canRequestFocus: canRequestFocus, + onFocusChange: onFocusChange, + autofocus: autofocus, + parentState: parentState, + getRectCallback: getRectCallback, + debugCheckContext: debugCheckContext, + statesController: statesController, + hoverDuration: hoverDuration, + longPressTimeout: longPressTimeout, + child: child, + ); + } + + /// Asserts that the given context satisfies the prerequisites for + /// this class. + /// + /// This method is intended to be overridden by descendants that + /// specialize [InkResponse] for unusual cases. For example, + /// [TableRowInkWell] implements this method to verify that the widget is + /// in a table. + @mustCallSuper + bool debugCheckContext(BuildContext context) { + assert(debugCheckHasMaterial(context)); + assert(debugCheckHasDirectionality(context)); + return true; + } +} + +abstract class _ParentInkResponseState { + void markChildInkResponsePressed(_ParentInkResponseState childState, bool value); +} + +class _ParentInkResponseProvider extends InheritedWidget { + const _ParentInkResponseProvider({ + required this.state, + required super.child, + }); + + final _ParentInkResponseState state; + + @override + bool updateShouldNotify(_ParentInkResponseProvider oldWidget) => state != oldWidget.state; + + static _ParentInkResponseState? maybeOf(BuildContext context) { + return context.dependOnInheritedWidgetOfExactType<_ParentInkResponseProvider>()?.state; + } +} + +typedef _GetRectCallback = RectCallback? Function(RenderBox referenceBox); +typedef _CheckContext = bool Function(BuildContext context); + +class _InkResponseStateWidget extends StatefulWidget { + const _InkResponseStateWidget({ + this.child, + this.onTap, + this.onTapDown, + this.onTapUp, + this.onTapCancel, + this.onDoubleTap, + this.onLongPress, + this.onSecondaryTap, + this.onSecondaryTapUp, + this.onSecondaryTapDown, + this.onSecondaryTapCancel, + this.onHighlightChanged, + this.onHover, + this.mouseCursor, + this.containedInkWell = false, + this.highlightShape = BoxShape.circle, + this.radius, + this.borderRadius, + this.customBorder, + this.focusColor, + this.hoverColor, + this.highlightColor, + this.overlayColor, + this.splashColor, + this.splashFactory, + this.enableFeedback = true, + this.excludeFromSemantics = false, + this.focusNode, + this.canRequestFocus = true, + this.onFocusChange, + this.autofocus = false, + this.parentState, + this.getRectCallback, + required this.debugCheckContext, + this.statesController, + this.hoverDuration, + required this.longPressTimeout, + }); + + final Widget? child; + final GestureTapCallback? onTap; + final GestureTapDownCallback? onTapDown; + final GestureTapUpCallback? onTapUp; + final GestureTapCallback? onTapCancel; + final GestureTapCallback? onDoubleTap; + final GestureLongPressCallback? onLongPress; + final GestureTapCallback? onSecondaryTap; + final GestureTapUpCallback? onSecondaryTapUp; + final GestureTapDownCallback? onSecondaryTapDown; + final GestureTapCallback? onSecondaryTapCancel; + final ValueChanged<bool>? onHighlightChanged; + final ValueChanged<bool>? onHover; + final MouseCursor? mouseCursor; + final bool containedInkWell; + final BoxShape highlightShape; + final double? radius; + final BorderRadius? borderRadius; + final ShapeBorder? customBorder; + final Color? focusColor; + final Color? hoverColor; + final Color? highlightColor; + final WidgetStateProperty<Color?>? overlayColor; + final Color? splashColor; + final InteractiveInkFeatureFactory? splashFactory; + final bool enableFeedback; + final bool excludeFromSemantics; + final ValueChanged<bool>? onFocusChange; + final bool autofocus; + final FocusNode? focusNode; + final bool canRequestFocus; + final _ParentInkResponseState? parentState; + final _GetRectCallback? getRectCallback; + final _CheckContext debugCheckContext; + final WidgetStatesController? statesController; + final Duration? hoverDuration; + final Duration longPressTimeout; + + @override + _InkResponseState createState() => _InkResponseState(); + + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + super.debugFillProperties(properties); + final List<String> gestures = <String>[ + if (onTap != null) 'tap', + if (onDoubleTap != null) 'double tap', + if (onLongPress != null) 'long press', + if (onTapDown != null) 'tap down', + if (onTapUp != null) 'tap up', + if (onTapCancel != null) 'tap cancel', + if (onSecondaryTap != null) 'secondary tap', + if (onSecondaryTapUp != null) 'secondary tap up', + if (onSecondaryTapDown != null) 'secondary tap down', + if (onSecondaryTapCancel != null) 'secondary tap cancel', + ]; + properties.add(IterableProperty<String>('gestures', gestures, ifEmpty: '<none>')); + properties.add(DiagnosticsProperty<MouseCursor>('mouseCursor', mouseCursor)); + properties.add(DiagnosticsProperty<bool>('containedInkWell', containedInkWell, level: DiagnosticLevel.fine)); + properties.add(DiagnosticsProperty<BoxShape>( + 'highlightShape', + highlightShape, + description: '${containedInkWell ? "clipped to " : ""}$highlightShape', + showName: false, + )); + } +} + +/// Used to index the allocated highlights for the different types of highlights +/// in [_InkResponseState]. +enum _HighlightType { + pressed, + hover, + focus, +} + +class _InkResponseState extends State<_InkResponseStateWidget> with AutomaticKeepAliveClientMixin<_InkResponseStateWidget> implements _ParentInkResponseState { + Set<InteractiveInkFeature>? _splashes; + InteractiveInkFeature? _currentSplash; + bool _hovering = false; + final Map<_HighlightType, InkHighlight?> _highlights = <_HighlightType, InkHighlight?>{}; + late final Map<Type, Action<Intent>> _actionMap = <Type, Action<Intent>>{ + ActivateIntent: CallbackAction<ActivateIntent>(onInvoke: activateOnIntent), + ButtonActivateIntent: CallbackAction<ButtonActivateIntent>(onInvoke: activateOnIntent), + }; + WidgetStatesController? internalStatesController; + + bool get highlightsExist => _highlights.values.where((highlight) => highlight != null).isNotEmpty; + + final ObserverList<_ParentInkResponseState> _activeChildren = ObserverList<_ParentInkResponseState>(); + + static const Duration _activationDuration = Duration(milliseconds: 100); + Timer? _activationTimer; + + @override + void markChildInkResponsePressed(_ParentInkResponseState childState, bool value) { + final bool lastAnyPressed = _anyChildInkResponsePressed; + if (value) { + _activeChildren.add(childState); + } else { + _activeChildren.remove(childState); + } + final bool nowAnyPressed = _anyChildInkResponsePressed; + if (nowAnyPressed != lastAnyPressed) { + widget.parentState?.markChildInkResponsePressed(this, nowAnyPressed); + } + } + + bool get _anyChildInkResponsePressed => _activeChildren.isNotEmpty; + + void activateOnIntent(Intent? intent) { + _activationTimer?.cancel(); + _activationTimer = null; + _startNewSplash(context: context); + _currentSplash?.confirm(); + _currentSplash = null; + if (widget.onTap != null) { + if (widget.enableFeedback) { + Feedback.forTap(context); + } + widget.onTap?.call(); + } + // Delay the call to `updateHighlight` to simulate a pressed delay + // and give MaterialStatesController listeners a chance to react. + _activationTimer = Timer(_activationDuration, () { + updateHighlight(_HighlightType.pressed, value: false); + }); + } + + void simulateTap([Intent? intent]) { + _startNewSplash(context: context); + handleTap(); + } + + void simulateLongPress() { + _startNewSplash(context: context); + handleLongPress(); + } + + void handleStatesControllerChange() { + // Force a rebuild to resolve widget.overlayColor, widget.mouseCursor + setState(() {}); + } + + WidgetStatesController get statesController => widget.statesController ?? internalStatesController!; + + void initStatesController() { + if (widget.statesController == null) { + internalStatesController = WidgetStatesController(); + } + statesController.update(WidgetState.disabled, !enabled); + statesController.addListener(handleStatesControllerChange); + } + + @override + void initState() { + super.initState(); + initStatesController(); + FocusManager.instance.addHighlightModeListener(handleFocusHighlightModeChange); + } + + @override + void didUpdateWidget(_InkResponseStateWidget oldWidget) { + super.didUpdateWidget(oldWidget); + if (widget.statesController != oldWidget.statesController) { + oldWidget.statesController?.removeListener(handleStatesControllerChange); + if (widget.statesController != null) { + internalStatesController?.dispose(); + internalStatesController = null; + } + initStatesController(); + } + if (widget.radius != oldWidget.radius || widget.highlightShape != oldWidget.highlightShape || widget.borderRadius != oldWidget.borderRadius) { + final InkHighlight? hoverHighlight = _highlights[_HighlightType.hover]; + if (hoverHighlight != null) { + hoverHighlight.dispose(); + updateHighlight(_HighlightType.hover, value: _hovering, callOnHover: false); + } + final InkHighlight? focusHighlight = _highlights[_HighlightType.focus]; + if (focusHighlight != null) { + focusHighlight.dispose(); + // Do not call updateFocusHighlights() here because it is called below + } + } + if (widget.customBorder != oldWidget.customBorder) { + _updateHighlightsAndSplashes(); + } + if (enabled != isWidgetEnabled(oldWidget)) { + statesController.update(WidgetState.disabled, !enabled); + if (!enabled) { + statesController.update(WidgetState.pressed, false); + // Remove the existing hover highlight immediately when enabled is false. + // Do not rely on updateHighlight or InkHighlight.deactivate to not break + // the expected lifecycle which is updating _hovering when the mouse exit. + // Manually updating _hovering here or calling InkHighlight.deactivate + // will lead to onHover not being called or call when it is not allowed. + final InkHighlight? hoverHighlight = _highlights[_HighlightType.hover]; + hoverHighlight?.dispose(); + } + // Don't call widget.onHover because many widgets, including the button + // widgets, apply setState to an ancestor context from onHover. + updateHighlight(_HighlightType.hover, value: _hovering, callOnHover: false); + } + updateFocusHighlights(); + } + + @override + void dispose() { + FocusManager.instance.removeHighlightModeListener(handleFocusHighlightModeChange); + statesController.removeListener(handleStatesControllerChange); + internalStatesController?.dispose(); + _activationTimer?.cancel(); + _activationTimer = null; + super.dispose(); + } + + @override + bool get wantKeepAlive => highlightsExist || (_splashes != null && _splashes!.isNotEmpty); + + Duration getFadeDurationForType(_HighlightType type) { + switch (type) { + case _HighlightType.pressed: + return const Duration(milliseconds: 200); + case _HighlightType.hover: + case _HighlightType.focus: + return widget.hoverDuration ?? const Duration(milliseconds: 50); + } + } + + void updateHighlight(_HighlightType type, {required bool value, bool callOnHover = true}) { + final InkHighlight? highlight = _highlights[type]; + void handleInkRemoval() { + assert(_highlights[type] != null); + _highlights[type] = null; + updateKeepAlive(); + } + + switch (type) { + case _HighlightType.pressed: + statesController.update(WidgetState.pressed, value); + case _HighlightType.hover: + if (callOnHover) { + statesController.update(WidgetState.hovered, value); + } + case _HighlightType.focus: + // see handleFocusUpdate() + break; + } + + if (type == _HighlightType.pressed) { + widget.parentState?.markChildInkResponsePressed(this, value); + } + if (value == (highlight != null && highlight.active)) { + return; + } + + if (value) { + if (highlight == null) { + final Color resolvedOverlayColor = widget.overlayColor?.resolve(statesController.value) ?? + switch (type) { + // Use the backwards compatible defaults + _HighlightType.pressed => widget.highlightColor ?? Theme.of(context).highlightColor, + _HighlightType.focus => widget.focusColor ?? Theme.of(context).focusColor, + _HighlightType.hover => widget.hoverColor ?? Theme.of(context).hoverColor, + }; + final RenderBox referenceBox = context.findRenderObject()! as RenderBox; + _highlights[type] = InkHighlight( + controller: Material.of(context), + referenceBox: referenceBox, + color: enabled ? resolvedOverlayColor : resolvedOverlayColor.withAlpha(0), + shape: widget.highlightShape, + radius: widget.radius, + borderRadius: widget.borderRadius, + customBorder: widget.customBorder, + rectCallback: widget.getRectCallback!(referenceBox), + onRemoved: handleInkRemoval, + textDirection: Directionality.of(context), + fadeDuration: getFadeDurationForType(type), + ); + updateKeepAlive(); + } else { + highlight.activate(); + } + } else { + highlight!.deactivate(); + } + assert(value == (_highlights[type] != null && _highlights[type]!.active)); + + switch (type) { + case _HighlightType.pressed: + widget.onHighlightChanged?.call(value); + case _HighlightType.hover: + if (callOnHover) { + widget.onHover?.call(value); + } + case _HighlightType.focus: + break; + } + } + + void _updateHighlightsAndSplashes() { + for (final InkHighlight? highlight in _highlights.values) { + highlight?.customBorder = widget.customBorder; + } + _currentSplash?.customBorder = widget.customBorder; + + if (_splashes != null && _splashes!.isNotEmpty) { + for (final InteractiveInkFeature inkFeature in _splashes!) { + inkFeature.customBorder = widget.customBorder; + } + } + } + + InteractiveInkFeature _createSplash(Offset globalPosition) { + final MaterialInkController inkController = Material.of(context); + final RenderBox referenceBox = context.findRenderObject()! as RenderBox; + final Offset position = referenceBox.globalToLocal(globalPosition); + final Color color = widget.overlayColor?.resolve(statesController.value) ?? widget.splashColor ?? Theme.of(context).splashColor; + final RectCallback? rectCallback = widget.containedInkWell ? widget.getRectCallback!(referenceBox) : null; + final BorderRadius? borderRadius = widget.borderRadius; + final ShapeBorder? customBorder = widget.customBorder; + + InteractiveInkFeature? splash; + void onRemoved() { + if (_splashes != null) { + assert(_splashes!.contains(splash)); + _splashes!.remove(splash); + if (_currentSplash == splash) { + _currentSplash = null; + } + updateKeepAlive(); + } // else we're probably in deactivate() + } + + splash = (widget.splashFactory ?? Theme.of(context).splashFactory).create( + controller: inkController, + referenceBox: referenceBox, + position: position, + color: color, + containedInkWell: widget.containedInkWell, + rectCallback: rectCallback, + radius: widget.radius, + borderRadius: borderRadius, + customBorder: customBorder, + onRemoved: onRemoved, + textDirection: Directionality.of(context), + ); + + return splash; + } + + void handleFocusHighlightModeChange(FocusHighlightMode mode) { + if (!mounted) { + return; + } + setState(updateFocusHighlights); + } + + bool get _shouldShowFocus { + return switch (MediaQuery.maybeNavigationModeOf(context)) { + NavigationMode.traditional || null => enabled && _hasFocus, + NavigationMode.directional => _hasFocus, + }; + } + + void updateFocusHighlights() { + final bool showFocus = switch (FocusManager.instance.highlightMode) { + FocusHighlightMode.touch => false, + FocusHighlightMode.traditional => _shouldShowFocus, + }; + updateHighlight(_HighlightType.focus, value: showFocus); + } + + bool _hasFocus = false; + + void handleFocusUpdate(bool hasFocus) { + _hasFocus = hasFocus; + // Set here rather than updateHighlight because this widget's + // (MaterialState) states include MaterialState.focused if + // the InkWell _has_ the focus, rather than if it's showing + // the focus per FocusManager.instance.highlightMode. + statesController.update(WidgetState.focused, hasFocus); + updateFocusHighlights(); + widget.onFocusChange?.call(hasFocus); + } + + void handleAnyTapDown(TapDownDetails details) { + if (_anyChildInkResponsePressed) { + return; + } + _startNewSplash(details: details); + } + + void handleTapDown(TapDownDetails details) { + handleAnyTapDown(details); + widget.onTapDown?.call(details); + } + + void handleTapUp(TapUpDetails details) { + widget.onTapUp?.call(details); + } + + void handleSecondaryTapDown(TapDownDetails details) { + handleAnyTapDown(details); + widget.onSecondaryTapDown?.call(details); + } + + void handleSecondaryTapUp(TapUpDetails details) { + widget.onSecondaryTapUp?.call(details); + } + + void _startNewSplash({TapDownDetails? details, BuildContext? context}) { + assert(details != null || context != null); + + final Offset globalPosition; + if (context != null) { + final RenderBox referenceBox = context.findRenderObject()! as RenderBox; + assert(referenceBox.hasSize, 'InkResponse must be done with layout before starting a splash.'); + globalPosition = referenceBox.localToGlobal(referenceBox.paintBounds.center); + } else { + globalPosition = details!.globalPosition; + } + statesController.update(WidgetState.pressed, true); // ... before creating the splash + final InteractiveInkFeature splash = _createSplash(globalPosition); + _splashes ??= HashSet<InteractiveInkFeature>(); + _splashes!.add(splash); + _currentSplash?.cancel(); + _currentSplash = splash; + updateKeepAlive(); + updateHighlight(_HighlightType.pressed, value: true); + } + + void handleTap() { + _currentSplash?.confirm(); + _currentSplash = null; + updateHighlight(_HighlightType.pressed, value: false); + if (widget.onTap != null) { + if (widget.enableFeedback) { + Feedback.forTap(context); + } + widget.onTap?.call(); + } + } + + void handleTapCancel() { + _currentSplash?.cancel(); + _currentSplash = null; + widget.onTapCancel?.call(); + updateHighlight(_HighlightType.pressed, value: false); + } + + void handleDoubleTap() { + _currentSplash?.confirm(); + _currentSplash = null; + updateHighlight(_HighlightType.pressed, value: false); + widget.onDoubleTap?.call(); + } + + void handleLongPress() { + _currentSplash?.confirm(); + _currentSplash = null; + if (widget.onLongPress != null) { + if (widget.enableFeedback) { + Feedback.forLongPress(context); + } + widget.onLongPress!(); + } + } + + void handleSecondaryTap() { + _currentSplash?.confirm(); + _currentSplash = null; + updateHighlight(_HighlightType.pressed, value: false); + widget.onSecondaryTap?.call(); + } + + void handleSecondaryTapCancel() { + _currentSplash?.cancel(); + _currentSplash = null; + widget.onSecondaryTapCancel?.call(); + updateHighlight(_HighlightType.pressed, value: false); + } + + @override + void deactivate() { + if (_splashes != null) { + final Set<InteractiveInkFeature> splashes = _splashes!; + _splashes = null; + for (final InteractiveInkFeature splash in splashes) { + splash.dispose(); + } + _currentSplash = null; + } + assert(_currentSplash == null); + for (final _HighlightType highlight in _highlights.keys) { + _highlights[highlight]?.dispose(); + _highlights[highlight] = null; + } + widget.parentState?.markChildInkResponsePressed(this, false); + super.deactivate(); + } + + bool isWidgetEnabled(_InkResponseStateWidget widget) { + return _primaryButtonEnabled(widget) || _secondaryButtonEnabled(widget); + } + + bool _primaryButtonEnabled(_InkResponseStateWidget widget) { + return widget.onTap != null || widget.onDoubleTap != null || widget.onLongPress != null || widget.onTapUp != null || widget.onTapDown != null; + } + + bool _secondaryButtonEnabled(_InkResponseStateWidget widget) { + return widget.onSecondaryTap != null || widget.onSecondaryTapUp != null || widget.onSecondaryTapDown != null; + } + + bool get enabled => isWidgetEnabled(widget); + + bool get _primaryEnabled => _primaryButtonEnabled(widget); + + bool get _secondaryEnabled => _secondaryButtonEnabled(widget); + + void handleMouseEnter(PointerEnterEvent event) { + _hovering = true; + if (enabled) { + handleHoverChange(); + } + } + + void handleMouseExit(PointerExitEvent event) { + _hovering = false; + // If the exit occurs after we've been disabled, we still + // want to take down the highlights and run widget.onHover. + handleHoverChange(); + } + + void handleHoverChange() { + updateHighlight(_HighlightType.hover, value: _hovering); + } + + bool get _canRequestFocus { + return switch (MediaQuery.maybeNavigationModeOf(context)) { + NavigationMode.traditional || null => enabled && widget.canRequestFocus, + NavigationMode.directional => true, + }; + } + + @override + Widget build(BuildContext context) { + assert(widget.debugCheckContext(context)); + super.build(context); // See AutomaticKeepAliveClientMixin. + + Color getHighlightColorForType(_HighlightType type) { + const Set<WidgetState> pressed = <WidgetState>{WidgetState.pressed}; + const Set<WidgetState> focused = <WidgetState>{WidgetState.focused}; + const Set<WidgetState> hovered = <WidgetState>{WidgetState.hovered}; + + final ThemeData theme = Theme.of(context); + return switch (type) { + // The pressed state triggers a ripple (ink splash), per the current + // Material Design spec. A separate highlight is no longer used. + // See https://material.io/design/interaction/states.html#pressed + _HighlightType.pressed => widget.overlayColor?.resolve(pressed) ?? widget.highlightColor ?? theme.highlightColor, + _HighlightType.focus => widget.overlayColor?.resolve(focused) ?? widget.focusColor ?? theme.focusColor, + _HighlightType.hover => widget.overlayColor?.resolve(hovered) ?? widget.hoverColor ?? theme.hoverColor, + }; + } + + for (final _HighlightType type in _highlights.keys) { + _highlights[type]?.color = getHighlightColorForType(type); + } + + _currentSplash?.color = widget.overlayColor?.resolve(statesController.value) ?? widget.splashColor ?? Theme.of(context).splashColor; + + final MouseCursor effectiveMouseCursor = WidgetStateProperty.resolveAs<MouseCursor>( + widget.mouseCursor ?? WidgetStateMouseCursor.clickable, + statesController.value, + ); + + return _ParentInkResponseProvider( + state: this, + child: Actions( + actions: _actionMap, + child: Focus( + focusNode: widget.focusNode, + canRequestFocus: _canRequestFocus, + onFocusChange: handleFocusUpdate, + autofocus: widget.autofocus, + child: MouseRegion( + cursor: effectiveMouseCursor, + onEnter: handleMouseEnter, + onExit: handleMouseExit, + child: DefaultSelectionStyle.merge( + mouseCursor: effectiveMouseCursor, + child: Semantics( + onTap: widget.excludeFromSemantics || widget.onTap == null ? null : simulateTap, + onLongPress: widget.excludeFromSemantics || widget.onLongPress == null ? null : simulateLongPress, + child: AGestureDetector( + onTapDown: _primaryEnabled ? handleTapDown : null, + onTapUp: _primaryEnabled ? handleTapUp : null, + onTap: _primaryEnabled ? handleTap : null, + onTapCancel: _primaryEnabled ? handleTapCancel : null, + onDoubleTap: widget.onDoubleTap != null ? handleDoubleTap : null, + onLongPress: widget.onLongPress != null ? handleLongPress : null, + onSecondaryTapDown: _secondaryEnabled ? handleSecondaryTapDown : null, + onSecondaryTapUp: _secondaryEnabled ? handleSecondaryTapUp : null, + onSecondaryTap: _secondaryEnabled ? handleSecondaryTap : null, + onSecondaryTapCancel: _secondaryEnabled ? handleSecondaryTapCancel : null, + behavior: HitTestBehavior.opaque, + excludeFromSemantics: true, + longPressTimeout: widget.longPressTimeout, + child: widget.child, + ), + ), + ), + ), + ), + ), + ); + } +} diff --git a/lib/widgets/common/basic/insets.dart b/lib/widgets/common/basic/insets.dart new file mode 100644 index 0000000..1e083a3 --- /dev/null +++ b/lib/widgets/common/basic/insets.dart @@ -0,0 +1,225 @@ +import 'dart:math'; + +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/widgets/aves_app.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/extensions/media_query.dart'; +import 'package:aves/widgets/common/providers/media_query_data_provider.dart'; +import 'package:aves/widgets/common/tile_extent_controller.dart'; +import 'package:aves_utils/aves_utils.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +// This widget should be added on top of Scaffolds with: +// - `resizeToAvoidBottomInset` set to false, +// - a vertically scrollable body. +// It will prevent the body from scrolling when a user swipe from bottom to use Android 10 style navigation gestures. +class BottomGestureAreaProtector extends StatelessWidget { + const BottomGestureAreaProtector({super.key}); + + @override + Widget build(BuildContext context) { + return Positioned( + left: 0, + right: 0, + bottom: 0, + height: MediaQuery.systemGestureInsetsOf(context).bottom, + child: GestureDetector( + // absorb vertical gestures only + onVerticalDragDown: (details) {}, + behavior: HitTestBehavior.translucent, + ), + ); + } +} + +// It will prevent the body from scrolling when a user swipe from top to show the status bar when system UI is hidden. +class TopGestureAreaProtector extends StatelessWidget { + const TopGestureAreaProtector({super.key}); + + @override + Widget build(BuildContext context) { + return Positioned( + left: 0, + top: 0, + right: 0, + height: MediaQuery.systemGestureInsetsOf(context).top, + child: GestureDetector( + // absorb vertical gestures only + onVerticalDragDown: (details) {}, + behavior: HitTestBehavior.translucent, + ), + ); + } +} + +// It will prevent the body from scrolling when a user swipe from edges to use Android 10 style navigation gestures. +class SideGestureAreaProtector extends StatelessWidget { + const SideGestureAreaProtector({super.key}); + + @override + Widget build(BuildContext context) { + return Positioned.fill( + child: Row( + // `systemGestureInsets` are not directional + textDirection: TextDirection.ltr, + children: [ + SizedBox( + width: MediaQuery.systemGestureInsetsOf(context).left, + child: GestureDetector( + // absorb horizontal gestures only + onHorizontalDragDown: (details) {}, + behavior: HitTestBehavior.translucent, + ), + ), + const Spacer(), + SizedBox( + width: MediaQuery.systemGestureInsetsOf(context).right, + child: GestureDetector( + // absorb horizontal gestures only + onHorizontalDragDown: (details) {}, + behavior: HitTestBehavior.translucent, + ), + ), + ], + ), + ); + } +} + +class GestureAreaProtectorStack extends StatelessWidget { + final Widget child; + + const GestureAreaProtectorStack({ + super.key, + required this.child, + }); + + @override + Widget build(BuildContext context) { + return Stack( + children: [ + child, + const BottomGestureAreaProtector(), + ], + ); + } +} + +class BottomPaddingSliver extends StatelessWidget { + const BottomPaddingSliver({super.key}); + + @override + Widget build(BuildContext context) { + return SliverToBoxAdapter( + child: Selector<MediaQueryData, double>( + selector: (context, mq) => mq.effectiveBottomPadding, + builder: (context, mqPaddingBottom, child) { + return SizedBox(height: mqPaddingBottom); + }, + ), + ); + } +} + +class TvTileGridBottomPaddingSliver extends StatelessWidget { + const TvTileGridBottomPaddingSliver({super.key}); + + @override + Widget build(BuildContext context) { + return SliverToBoxAdapter( + child: SizedBox( + height: settings.useTvLayout ? context.select<TileExtentController, double>((controller) => controller.spacing) : 0, + ), + ); + } +} + +// `MediaQuery.padding` matches cutout areas but also includes other system UI like the status bar +// so we cannot use `SafeArea` along `MediaQuery.removePadding()` to remove cutout areas +class SafeCutoutArea extends StatelessWidget { + final Animation<double>? animation; + final Widget child; + + const SafeCutoutArea({ + super.key, + this.animation, + required this.child, + }); + + @override + Widget build(BuildContext context) { + return ValueListenableBuilder<EdgeInsets>( + valueListenable: AvesApp.cutoutInsetsNotifier, + builder: (context, cutoutInsets, child) { + return NullableValueListenableBuilder<double>( + valueListenable: animation, + builder: (context, value, child) { + final double factor = value ?? 1.0; + final effectiveInsets = cutoutInsets * factor; + return Padding( + padding: effectiveInsets, + child: MediaQueryDataProvider( + value: MediaQuery.of(context).removeCutoutInsets(effectiveInsets), + child: child!, + ), + ); + }, + child: child, + ); + }, + child: child, + ); + } +} + +extension ExtraMediaQueryData on MediaQueryData { + MediaQueryData removeCutoutInsets(EdgeInsets cutoutInsets) { + return copyWith( + padding: EdgeInsets.only( + left: max(0.0, padding.left - cutoutInsets.left), + top: max(0.0, padding.top - cutoutInsets.top), + right: max(0.0, padding.right - cutoutInsets.right), + bottom: max(0.0, padding.bottom - cutoutInsets.bottom), + ), + viewPadding: EdgeInsets.only( + left: max(0.0, viewPadding.left - cutoutInsets.left), + top: max(0.0, viewPadding.top - cutoutInsets.top), + right: max(0.0, viewPadding.right - cutoutInsets.right), + bottom: max(0.0, viewPadding.bottom - cutoutInsets.bottom), + ), + ); + } +} + +class DirectionalSafeArea extends StatelessWidget { + final bool start, top, end, bottom; + final EdgeInsets minimum; + final bool maintainBottomViewPadding; + final Widget child; + + const DirectionalSafeArea({ + super.key, + this.start = true, + this.top = true, + this.end = true, + this.bottom = true, + this.minimum = EdgeInsets.zero, + this.maintainBottomViewPadding = false, + required this.child, + }); + + @override + Widget build(BuildContext context) { + final isRtl = context.isRtl; + return SafeArea( + left: isRtl ? end : start, + top: top, + right: isRtl ? start : end, + bottom: bottom, + minimum: minimum, + maintainBottomViewPadding: maintainBottomViewPadding, + child: child, + ); + } +} diff --git a/lib/widgets/common/basic/labeled_checkbox.dart b/lib/widgets/common/basic/labeled_checkbox.dart new file mode 100644 index 0000000..c106e07 --- /dev/null +++ b/lib/widgets/common/basic/labeled_checkbox.dart @@ -0,0 +1,55 @@ +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; + +class LabeledCheckbox extends StatefulWidget { + final bool value; + final ValueChanged<bool?> onChanged; + final String text; + + const LabeledCheckbox({ + super.key, + required this.value, + required this.onChanged, + required this.text, + }); + + @override + State<LabeledCheckbox> createState() => _LabeledCheckboxState(); +} + +class _LabeledCheckboxState extends State<LabeledCheckbox> { + late TapGestureRecognizer _tapRecognizer; + + @override + void initState() { + super.initState(); + _tapRecognizer = TapGestureRecognizer()..onTap = () => widget.onChanged(!widget.value); + } + + @override + void dispose() { + _tapRecognizer.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Text.rich( + TextSpan( + children: [ + WidgetSpan( + alignment: PlaceholderAlignment.middle, + child: Checkbox( + value: widget.value, + onChanged: widget.onChanged, + ), + ), + TextSpan( + text: widget.text, + recognizer: _tapRecognizer, + ), + ], + ), + ); + } +} diff --git a/lib/widgets/common/basic/link_chip.dart b/lib/widgets/common/basic/link_chip.dart new file mode 100644 index 0000000..53ddc65 --- /dev/null +++ b/lib/widgets/common/basic/link_chip.dart @@ -0,0 +1,63 @@ +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/aves_app.dart'; +import 'package:flutter/material.dart'; + +class LinkChip extends StatelessWidget { + final Widget? leading; + final String text; + final String? urlString; + final Color? color; + final TextStyle? textStyle; + final VoidCallback? onTap; + + static const borderRadius = BorderRadius.all(Radius.circular(8)); + + const LinkChip({ + super.key, + this.leading, + required this.text, + this.urlString, + this.color, + this.textStyle, + this.onTap, + }); + + @override + Widget build(BuildContext context) { + return DefaultTextStyle.merge( + style: (textStyle ?? const TextStyle()).copyWith(color: color), + child: InkWell( + borderRadius: borderRadius, + onTap: onTap ?? () => AvesApp.launchUrl(urlString), + child: Padding( + padding: const EdgeInsets.all(8), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (leading != null) ...[ + leading!, + const SizedBox(width: 8), + ], + Flexible( + child: Text( + text, + softWrap: false, + overflow: TextOverflow.fade, + maxLines: 1, + ), + ), + const SizedBox(width: 8), + Builder( + builder: (context) => Icon( + AIcons.openOutside, + size: DefaultTextStyle.of(context).style.fontSize, + color: color, + ), + ), + ], + ), + ), + ), + ); + } +} diff --git a/lib/widgets/common/basic/list_tiles/color.dart b/lib/widgets/common/basic/list_tiles/color.dart new file mode 100644 index 0000000..93d2e2a --- /dev/null +++ b/lib/widgets/common/basic/list_tiles/color.dart @@ -0,0 +1,99 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/widgets/common/basic/color_indicator.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:flex_color_picker/flex_color_picker.dart' show ColorPicker, ColorPickerType; +import 'package:flutter/material.dart'; + +class ColorListTile extends StatelessWidget { + final String title; + final Color value; + final ValueSetter<Color> onChanged; + + const ColorListTile({ + super.key, + required this.title, + required this.value, + required this.onChanged, + }); + + @override + Widget build(BuildContext context) { + return ListTile( + title: Text(title), + trailing: ColorIndicator( + value: value, + ), + contentPadding: const EdgeInsetsDirectional.only(start: 16, end: 36 - ColorIndicator.radius), + onTap: () async { + final color = await showDialog<Color>( + context: context, + builder: (context) => ColorPickerDialog( + initialValue: value, + ), + routeSettings: const RouteSettings(name: ColorPickerDialog.routeName), + ); + if (color != null) { + onChanged(color); + } + }, + ); + } +} + +class ColorPickerDialog extends StatefulWidget { + static const routeName = '/dialog/pick_color'; + + final Color initialValue; + + const ColorPickerDialog({ + super.key, + required this.initialValue, + }); + + @override + State<ColorPickerDialog> createState() => _ColorPickerDialogState(); +} + +class _ColorPickerDialogState extends State<ColorPickerDialog> { + late Color color; + + @override + void initState() { + super.initState(); + color = widget.initialValue; + } + + @override + Widget build(BuildContext context) { + final useTvLayout = settings.useTvLayout; + return AvesDialog( + scrollableContent: [ + ColorPicker( + color: color, + onColorChanged: (v) => color = v, + pickersEnabled: useTvLayout + ? const { + ColorPickerType.primary: true, + ColorPickerType.accent: false, + } + : const { + ColorPickerType.primary: false, + ColorPickerType.accent: false, + ColorPickerType.wheel: true, + }, + hasBorder: true, + borderRadius: 20, + subheading: useTvLayout ? const SizedBox(height: 16) : null, + ) + ], + actions: [ + const CancelButton(), + TextButton( + onPressed: () => Navigator.maybeOf(context)?.pop(color), + child: Text(context.l10n.applyButtonLabel), + ), + ], + ); + } +} diff --git a/lib/widgets/common/basic/list_tiles/reselectable_radio.dart b/lib/widgets/common/basic/list_tiles/reselectable_radio.dart new file mode 100644 index 0000000..1f937da --- /dev/null +++ b/lib/widgets/common/basic/list_tiles/reselectable_radio.dart @@ -0,0 +1,89 @@ +import 'package:flutter/material.dart'; + +// `RadioListTile` that can trigger `onChanged` on tap when already selected, if `reselectable` is true +class ReselectableRadioListTile<T> extends StatelessWidget { + final T value; + final T groupValue; + final ValueChanged<T?>? onChanged; + final bool toggleable; + final bool reselectable; + final Color? activeColor; + final Widget? title; + final Widget? subtitle; + final Widget? secondary; + final bool isThreeLine; + final bool? dense; + final bool selected; + final ListTileControlAffinity controlAffinity; + final bool autofocus; + + bool get checked => value == groupValue; + + const ReselectableRadioListTile({ + super.key, + required this.value, + required this.groupValue, + required this.onChanged, + this.toggleable = false, + this.reselectable = false, + this.activeColor, + this.title, + this.subtitle, + this.isThreeLine = false, + this.dense, + this.secondary, + this.selected = false, + this.controlAffinity = ListTileControlAffinity.platform, + this.autofocus = false, + }) : assert(!isThreeLine || subtitle != null); + + @override + Widget build(BuildContext context) { + final Widget control = Radio<T>( + value: value, + groupValue: groupValue, + onChanged: onChanged, + toggleable: toggleable, + activeColor: activeColor, + materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, + autofocus: autofocus, + ); + Widget? leading, trailing; + switch (controlAffinity) { + case ListTileControlAffinity.leading: + case ListTileControlAffinity.platform: + leading = control; + trailing = secondary; + case ListTileControlAffinity.trailing: + leading = secondary; + trailing = control; + } + return MergeSemantics( + child: ListTileTheme.merge( + selectedColor: activeColor ?? Theme.of(context).colorScheme.primary, + child: ListTile( + leading: leading, + title: title, + subtitle: subtitle, + trailing: trailing, + isThreeLine: isThreeLine, + dense: dense, + enabled: onChanged != null, + onTap: onChanged != null + ? () { + if (toggleable && checked) { + onChanged!(null); + return; + } + if (reselectable || !checked) { + onChanged!(value); + } + } + : null, + selected: selected, + autofocus: autofocus, + ), + ), + ); + } +} diff --git a/lib/widgets/common/basic/list_tiles/slider.dart b/lib/widgets/common/basic/list_tiles/slider.dart new file mode 100644 index 0000000..1a95a2e --- /dev/null +++ b/lib/widgets/common/basic/list_tiles/slider.dart @@ -0,0 +1,71 @@ +import 'package:flutter/material.dart'; + +class SliderListTile extends StatelessWidget { + final String title; + final double value; + final ValueChanged<double>? onChanged; + final double min; + final double max; + final int? divisions; + final EdgeInsetsGeometry titlePadding; + final Widget Function(BuildContext context, double value)? titleTrailing; + + const SliderListTile({ + super.key, + required this.title, + required this.value, + required this.onChanged, + this.min = 0.0, + this.max = 1.0, + this.divisions, + this.titlePadding = const EdgeInsetsDirectional.only(start: 16), + this.titleTrailing, + }); + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final listTileTitleTextStyle = ListTileTheme.of(context).titleTextStyle ?? theme.textTheme.bodyLarge!.copyWith(color: theme.colorScheme.onSurface); + return SliderTheme( + data: SliderTheme.of(context).copyWith( + overlayShape: const RoundSliderOverlayShape( + // align `Slider`s on `Switch`es by matching their overlay/reaction radius + // `kRadialReactionRadius` is used when `SwitchThemeData.splashRadius` is undefined + overlayRadius: kRadialReactionRadius, + ), + ), + child: Padding( + padding: const EdgeInsets.only(top: 16, bottom: 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: titlePadding, + child: Row( + children: [ + Text( + title, + style: listTileTitleTextStyle, + ), + const Spacer(), + if (titleTrailing != null) titleTrailing!(context, value), + ], + ), + ), + Padding( + // match `SwitchListTile.contentPadding` + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Slider( + value: value, + onChanged: onChanged, + min: min, + max: max, + divisions: divisions, + ), + ), + ], + ), + ), + ); + } +} diff --git a/lib/widgets/common/basic/markdown_container.dart b/lib/widgets/common/basic/markdown_container.dart new file mode 100644 index 0000000..391b34a --- /dev/null +++ b/lib/widgets/common/basic/markdown_container.dart @@ -0,0 +1,71 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/widgets/aves_app.dart'; +import 'package:aves/widgets/common/fx/borders.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_markdown_plus/flutter_markdown_plus.dart'; + +class MarkdownContainer extends StatelessWidget { + final String data; + final TextDirection? textDirection; + final ScrollController? scrollController; + + const MarkdownContainer({ + super.key, + required this.data, + this.textDirection, + this.scrollController, + }); + + static const double mobileMaxWidth = 460; + + @override + Widget build(BuildContext context) { + final useTvLayout = settings.useTvLayout; + + Widget child = Directionality( + textDirection: textDirection ?? Directionality.of(context), + child: Markdown( + data: data, + selectable: true, + onTapLink: (text, href, title) => AvesApp.launchUrl(href), + controller: scrollController, + shrinkWrap: true, + ), + ); + + if (!useTvLayout) { + child = Theme( + data: Theme.of(context).copyWith( + scrollbarTheme: ScrollbarThemeData( + thumbVisibility: WidgetStateProperty.all(true), + radius: const Radius.circular(16), + crossAxisMargin: 6, + mainAxisMargin: 16, + interactive: true, + ), + ), + child: Scrollbar( + child: child, + ), + ); + } + + return Container( + margin: const EdgeInsets.symmetric(horizontal: 8), + decoration: BoxDecoration( + color: Themes.secondLayerColor(context), + border: Border.all( + color: Theme.of(context).dividerColor, + width: AvesBorder.curvedBorderWidth(context), + ), + borderRadius: const BorderRadius.all(Radius.circular(16)), + ), + constraints: BoxConstraints(maxWidth: useTvLayout ? double.infinity : mobileMaxWidth), + child: ClipRRect( + borderRadius: const BorderRadius.all(Radius.circular(16)), + child: child, + ), + ); + } +} diff --git a/lib/widgets/common/basic/multi_cross_fader.dart b/lib/widgets/common/basic/multi_cross_fader.dart new file mode 100644 index 0000000..df65a57 --- /dev/null +++ b/lib/widgets/common/basic/multi_cross_fader.dart @@ -0,0 +1,62 @@ +import 'package:flutter/material.dart'; + +class MultiCrossFader extends StatefulWidget { + final Duration duration; + final Curve fadeCurve, sizeCurve; + final AlignmentGeometry alignment; + final AnimatedCrossFadeBuilder layoutBuilder; + final Widget child; + + const MultiCrossFader({ + super.key, + required this.duration, + this.fadeCurve = Curves.linear, + this.sizeCurve = Curves.linear, + this.alignment = Alignment.topCenter, + this.layoutBuilder = AnimatedCrossFade.defaultLayoutBuilder, + required this.child, + }); + + @override + State<MultiCrossFader> createState() => _MultiCrossFaderState(); +} + +class _MultiCrossFaderState extends State<MultiCrossFader> { + late Widget _first, _second; + CrossFadeState _fadeState = CrossFadeState.showFirst; + + @override + void initState() { + super.initState(); + _first = widget.child; + _second = const SizedBox(); + } + + @override + void didUpdateWidget(covariant MultiCrossFader oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.child == _first) { + _second = widget.child; + _fadeState = CrossFadeState.showSecond; + } else { + _first = widget.child; + _fadeState = CrossFadeState.showFirst; + } + } + + @override + Widget build(BuildContext context) { + return AnimatedCrossFade( + firstChild: _first, + secondChild: _second, + firstCurve: widget.fadeCurve, + secondCurve: widget.fadeCurve, + sizeCurve: widget.sizeCurve, + alignment: widget.alignment, + crossFadeState: _fadeState, + duration: widget.duration, + reverseDuration: widget.duration, + layoutBuilder: widget.layoutBuilder, + ); + } +} diff --git a/lib/widgets/common/basic/popup/container.dart b/lib/widgets/common/basic/popup/container.dart new file mode 100644 index 0000000..30a0323 --- /dev/null +++ b/lib/widgets/common/basic/popup/container.dart @@ -0,0 +1,35 @@ +import 'package:flutter/material.dart'; + +class PopupMenuItemContainer<T> extends PopupMenuEntry<T> { + final Widget child; + + const PopupMenuItemContainer({ + super.key, + this.height = kMinInteractiveDimension, + required this.child, + }); + + @override + final double height; + + @override + bool represents(void value) => false; + + @override + State<PopupMenuItemContainer> createState() => _PopupMenuItemContainerState(); +} + +class _PopupMenuItemContainerState extends State<PopupMenuItemContainer> { + @override + Widget build(BuildContext context) { + return TooltipTheme( + data: TooltipTheme.of(context).copyWith( + preferBelow: false, + ), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: widget.child, + ), + ); + } +} diff --git a/lib/widgets/common/basic/popup/expansion_panel.dart b/lib/widgets/common/basic/popup/expansion_panel.dart new file mode 100644 index 0000000..63bc94e --- /dev/null +++ b/lib/widgets/common/basic/popup/expansion_panel.dart @@ -0,0 +1,105 @@ +import 'package:aves/theme/durations.dart'; +import 'package:aves/widgets/common/basic/popup/menu_row.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class PopupMenuExpansionPanel<T> extends PopupMenuEntry<T> { + final bool enabled; + final String value; + final ValueNotifier<String?>? expandedNotifier; + final IconData icon; + final String title; + final List<PopupMenuEntry<T>> items; + + const PopupMenuExpansionPanel({ + super.key, + this.enabled = true, + this.height = kMinInteractiveDimension, + required this.value, + this.expandedNotifier, + required this.icon, + required this.title, + required this.items, + }); + + @override + final double height; + + @override + bool represents(void value) => false; + + @override + State<PopupMenuExpansionPanel<T>> createState() => _PopupMenuExpansionPanelState<T>(); +} + +class _PopupMenuExpansionPanelState<T> extends State<PopupMenuExpansionPanel<T>> { + final ValueNotifier<String?> _internalExpandedNotifier = ValueNotifier(null); + + ValueNotifier<String?> get expandedNotifier => widget.expandedNotifier ?? _internalExpandedNotifier; + + @override + void dispose() { + _internalExpandedNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final style = PopupMenuTheme.of(context).labelTextStyle!.resolve( + <WidgetState>{ + if (!widget.enabled) WidgetState.disabled, + }, + )!; + final animationDuration = context.select<DurationsData, Duration>((v) => v.expansionTileAnimation); + + Widget child = ValueListenableBuilder<String?>( + valueListenable: expandedNotifier, + builder: (context, expandedValue, child) { + return ExpansionPanelList( + expansionCallback: (index, isExpanded) { + expandedNotifier.value = isExpanded ? widget.value : null; + }, + animationDuration: animationDuration, + expandedHeaderPadding: EdgeInsets.zero, + elevation: 0, + children: [ + ExpansionPanel( + headerBuilder: (context, isExpanded) { + return DefaultTextStyle( + style: style, + child: IconTheme.merge( + data: IconThemeData( + color: widget.enabled ? null : Theme.of(context).disabledColor, + ), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 12), + child: MenuRow( + text: widget.title, + icon: Icon(widget.icon), + ), + ), + ), + ); + }, + body: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const PopupMenuDivider(height: 0), + ...widget.items, + const PopupMenuDivider(height: 0), + ], + ), + isExpanded: expandedValue == widget.value, + canTapOnHeader: true, + backgroundColor: Colors.transparent, + ), + ], + ); + }, + ); + if (!widget.enabled) { + child = IgnorePointer(child: child); + } + return child; + } +} diff --git a/lib/widgets/common/basic/popup/menu_row.dart b/lib/widgets/common/basic/popup/menu_row.dart new file mode 100644 index 0000000..23f77b4 --- /dev/null +++ b/lib/widgets/common/basic/popup/menu_row.dart @@ -0,0 +1,36 @@ +import 'package:flutter/material.dart'; + +class MenuRow extends StatelessWidget { + final String text; + final Widget? icon; + + const MenuRow({ + super.key, + required this.text, + this.icon, + }); + + static const leadingPadding = EdgeInsetsDirectional.only(end: 12); + + @override + Widget build(BuildContext context) { + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (icon != null) + Padding( + padding: leadingPadding, + child: IconTheme.merge( + data: IconThemeData( + color: ListTileTheme.of(context).iconColor, + ), + child: icon!, + ), + ), + Flexible( + child: Text(text), + ), + ], + ); + } +} diff --git a/lib/widgets/common/basic/query_bar.dart b/lib/widgets/common/basic/query_bar.dart new file mode 100644 index 0000000..e2ddb31 --- /dev/null +++ b/lib/widgets/common/basic/query_bar.dart @@ -0,0 +1,112 @@ +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/utils/debouncer.dart'; +import 'package:aves/widgets/common/basic/font_size_icon_theme.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:flutter/material.dart'; + +class QueryBar extends StatefulWidget { + final ValueNotifier<String> queryNotifier; + final FocusNode? focusNode; + final EdgeInsetsGeometry? leadingPadding; + final IconData? icon; + final String? hintText; + final bool editable; + + const QueryBar({ + super.key, + required this.queryNotifier, + this.focusNode, + this.leadingPadding, + this.icon, + this.hintText, + this.editable = true, + }); + + @override + State<QueryBar> createState() => _QueryBarState(); + + static double getPreferredHeight(TextScaler textScaler) => textScaler.scale(kToolbarHeight); +} + +class _QueryBarState extends State<QueryBar> { + final Debouncer _debouncer = Debouncer(delay: ADurations.searchDebounceDelay); + late TextEditingController _controller; + + ValueNotifier<String> get queryNotifier => widget.queryNotifier; + + @override + void initState() { + super.initState(); + _controller = TextEditingController(text: queryNotifier.value); + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final clearButton = IconButton( + icon: const Icon(AIcons.clear), + onPressed: widget.editable + ? () { + _controller.clear(); + queryNotifier.value = ''; + } + : null, + tooltip: context.l10n.clearTooltip, + ); + + return DefaultTextStyle( + style: Theme.of(context).textTheme.bodyMedium!, + child: FontSizeIconTheme( + child: Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Expanded( + child: TextField( + controller: _controller, + focusNode: widget.focusNode, + decoration: InputDecoration( + icon: Padding( + padding: widget.leadingPadding ?? const EdgeInsetsDirectional.only(start: 16), + // set theme at this level because `InputDecoration` defines its own `IconTheme` with a fixed size + child: FontSizeIconTheme( + child: Icon(widget.icon ?? AIcons.filter), + ), + ), + hintText: widget.hintText ?? MaterialLocalizations.of(context).searchFieldLabel, + hintStyle: Theme.of(context).inputDecorationTheme.hintStyle, + ), + textInputAction: TextInputAction.search, + onChanged: (s) => _debouncer(() => queryNotifier.value = s.trim()), + enabled: widget.editable, + ), + ), + ConstrainedBox( + constraints: const BoxConstraints(minWidth: 16), + child: ValueListenableBuilder<TextEditingValue>( + valueListenable: _controller, + builder: (context, value, child) => AnimatedSwitcher( + duration: ADurations.appBarActionChangeAnimation, + transitionBuilder: (child, animation) => FadeTransition( + opacity: animation, + child: SizeTransition( + axis: Axis.horizontal, + sizeFactor: animation, + child: child, + ), + ), + child: value.text.isNotEmpty ? clearButton : const SizedBox(), + ), + ), + ), + ], + ), + ), + ); + } +} diff --git a/lib/widgets/common/basic/scaffold.dart b/lib/widgets/common/basic/scaffold.dart new file mode 100644 index 0000000..81058a6 --- /dev/null +++ b/lib/widgets/common/basic/scaffold.dart @@ -0,0 +1,42 @@ +import 'package:flutter/material.dart'; + +class AvesScaffold extends StatelessWidget { + final PreferredSizeWidget? appBar; + final Widget? body; + final Widget? floatingActionButton; + final Widget? drawer; + final Widget? bottomNavigationBar; + final Color? backgroundColor; + final bool? resizeToAvoidBottomInset; + final bool extendBody; + + const AvesScaffold({ + super.key, + this.appBar, + this.body, + this.floatingActionButton, + this.drawer, + this.bottomNavigationBar, + this.backgroundColor, + this.resizeToAvoidBottomInset, + this.extendBody = false, + }); + + @override + Widget build(BuildContext context) { + // prevent conflict between drawer drag gesture and Android navigation gestures + final drawerEnableOpenDragGesture = MediaQuery.systemGestureInsetsOf(context).horizontal == 0; + + return Scaffold( + appBar: appBar, + body: body, + floatingActionButton: floatingActionButton, + drawer: drawer, + bottomNavigationBar: bottomNavigationBar, + backgroundColor: backgroundColor, + resizeToAvoidBottomInset: resizeToAvoidBottomInset, + extendBody: extendBody, + drawerEnableOpenDragGesture: drawerEnableOpenDragGesture, + ); + } +} diff --git a/lib/widgets/common/basic/text/animated_diff.dart b/lib/widgets/common/basic/text/animated_diff.dart new file mode 100644 index 0000000..fe37d42 --- /dev/null +++ b/lib/widgets/common/basic/text/animated_diff.dart @@ -0,0 +1,179 @@ +import 'dart:math'; + +import 'package:aves/utils/diff_match.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/widgets.dart'; + +class AnimatedDiffText extends StatefulWidget { + final String text; + final TextStyle? textStyle; + final StrutStyle? strutStyle; + final Curve curve; + final Duration duration; + + const AnimatedDiffText( + this.text, { + super.key, + this.textStyle, + this.strutStyle, + this.curve = Curves.easeInOutCubic, + required this.duration, + }); + + @override + State<AnimatedDiffText> createState() => _AnimatedDiffTextState(); +} + +class _AnimatedDiffTextState extends State<AnimatedDiffText> with SingleTickerProviderStateMixin { + late final AnimationController _controller; + late final CurvedAnimation _animation; + final List<_TextDiff> _diffs = []; + + TextStyle get _textStyle { + final style = widget.textStyle ?? const TextStyle(); + // specify `height` for accurate paragraph height measurement + return style.copyWith(height: style.height ?? DefaultTextStyle.of(context).style.height); + } + + StrutStyle? get _strutStyle => widget.strutStyle; + + @override + void initState() { + super.initState(); + _controller = AnimationController( + duration: widget.duration, + vsync: this, + ); + _animation = CurvedAnimation(parent: _controller, curve: widget.curve); + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + _computeDiff(widget.text, widget.text); + } + + @override + void didUpdateWidget(covariant AnimatedDiffText oldWidget) { + super.didUpdateWidget(oldWidget); + final oldText = oldWidget.text; + final newText = widget.text; + if (oldText != newText) { + _computeDiff(oldText, newText); + _controller.forward(from: 0); + } + } + + @override + void dispose() { + _animation.dispose(); + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return AnimatedBuilder( + animation: _animation, + builder: (context, child) { + return Text.rich( + TextSpan( + children: _diffs.map((diff) { + final (oldText, newText, oldSize, newSize) = diff; + final text = (_animation.value == 0 ? oldText : newText) ?? ''; + return WidgetSpan( + child: AnimatedSize( + key: ValueKey(diff), + curve: widget.curve, + duration: widget.duration, + child: AnimatedSwitcher( + duration: widget.duration, + switchInCurve: widget.curve, + switchOutCurve: widget.curve, + layoutBuilder: (currentChild, previousChildren) { + return Stack( + alignment: Alignment.center, + children: [ + ...previousChildren.map( + (child) => ConstrainedBox( + constraints: BoxConstraints.tight(Size( + min(oldSize.width, newSize.width), + min(oldSize.height, newSize.height), + )), + child: child, + ), + ), + if (currentChild != null) currentChild, + ], + ); + }, + child: Text( + text, + key: Key(text), + style: _textStyle, + ), + ), + ), + ); + }).toList(), + ), + strutStyle: _strutStyle, + ); + }, + ); + } + + Size _textSize(String text) { + final paragraph = RenderParagraph( + TextSpan(text: text, style: _textStyle), + textDirection: Directionality.of(context), + textScaler: MediaQuery.textScalerOf(context), + strutStyle: _strutStyle, + )..layout(const BoxConstraints(), parentUsesSize: true); + final width = paragraph.getMaxIntrinsicWidth(double.infinity); + final height = paragraph.getMaxIntrinsicHeight(double.infinity); + paragraph.dispose(); + return Size(width, height); + } + + // use an adaptation of Google's `Diff Match and Patch` + // as package `diffutil_dart` (as of v3.0.0) is unreliable + void _computeDiff(String oldText, String newText) { + final oldCharacters = oldText.characters.join(); + final newCharacters = newText.characters.join(); + + final dmp = DiffMatchPatch(); + final d = dmp.diff_main(oldCharacters, newCharacters); + dmp.diff_cleanupSemantic(d); + + _diffs + ..clear() + ..addAll(d.map((diff) { + final text = diff.text; + final size = _textSize(text); + return switch (diff.operation) { + Operation.delete => (text, null, size, Size.zero), + Operation.insert => (null, text, Size.zero, size), + Operation.equal || _ => (text, text, size, size), + }; + }).fold<List<_TextDiff>>([], (prev, v) { + if (prev.isNotEmpty) { + final last = prev.last; + final prevNewText = last.$2; + if (prevNewText == null) { + // previous diff is a deletion + final thisOldText = v.$1; + if (thisOldText == null) { + // this diff is an insertion + // merge deletion and insertion as a change operation + final change = (last.$1, v.$2, last.$3, v.$4); + return [...prev.take(prev.length - 1), change]; + } + } + } + return [...prev, v]; + })); + } +} + +typedef _TextDiff = (String?, String?, Size, Size); diff --git a/lib/widgets/common/basic/text/background_painter.dart b/lib/widgets/common/basic/text/background_painter.dart new file mode 100644 index 0000000..e3757c1 --- /dev/null +++ b/lib/widgets/common/basic/text/background_painter.dart @@ -0,0 +1,77 @@ +import 'dart:ui' as ui; + +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; + +// as of Flutter v3.3.7, text style background does not have consistent height +// when rendering multi-script text, so we paint the background behind via a stack instead +class TextBackgroundPainter extends StatelessWidget { + final List<TextSpan> spans; + final TextStyle style; + final TextAlign textAlign; + final Widget child; + + const TextBackgroundPainter({ + super.key, + required this.spans, + required this.style, + required this.textAlign, + required this.child, + }); + + @override + Widget build(BuildContext context) { + final backgroundColor = style.backgroundColor; + if (backgroundColor == null || backgroundColor.a == 0) { + return child; + } + + return LayoutBuilder( + builder: (context, constraints) { + final paragraph = RenderParagraph( + TextSpan( + children: spans, + style: style, + ), + textAlign: textAlign, + textDirection: Directionality.of(context), + textScaler: MediaQuery.textScalerOf(context), + )..layout(constraints, parentUsesSize: true); + + final textLength = spans.map((v) => v.text?.length ?? 0).sum; + final allBoxes = paragraph.getBoxesForSelection( + TextSelection(baseOffset: 0, extentOffset: textLength), + boxHeightStyle: ui.BoxHeightStyle.max, + ); + paragraph.dispose(); + + // merge boxes to avoid artifacts at box edges, from anti-aliasing and rounding hacks + final lineRects = groupBy<TextBox, double>(allBoxes, (v) => v.top).entries.map((kv) { + final top = kv.key; + final lineBoxes = kv.value; + return Rect.fromLTRB( + lineBoxes.map((v) => v.left).min, + top, + lineBoxes.map((v) => v.right).max, + lineBoxes.first.bottom, + ); + }); + + return Stack( + children: [ + ...lineRects.map((rect) { + return Positioned.fromRect( + rect: rect, + child: ColoredBox( + color: backgroundColor, + ), + ); + }), + child, + ], + ); + }, + ); + } +} diff --git a/lib/widgets/common/basic/text/change_highlight.dart b/lib/widgets/common/basic/text/change_highlight.dart new file mode 100644 index 0000000..cea4737 --- /dev/null +++ b/lib/widgets/common/basic/text/change_highlight.dart @@ -0,0 +1,89 @@ +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; + +class ChangeHighlightText extends StatefulWidget { + final String data; + final TextStyle style, changedStyle; + final Curve curve; + final Duration duration; + + const ChangeHighlightText( + this.data, { + super.key, + required this.style, + required this.changedStyle, + this.curve = Curves.linear, + required this.duration, + }); + + @override + State<ChangeHighlightText> createState() => _ChangeHighlightTextState(); +} + +class _ChangeHighlightTextState extends State<ChangeHighlightText> with SingleTickerProviderStateMixin { + late final AnimationController _controller; + late final CurvedAnimation _animation; + late final Animation<TextStyle> _style; + + @override + void initState() { + super.initState(); + _controller = AnimationController( + duration: widget.duration, + vsync: this, + ) + ..value = 1 + ..addListener(() => setState(() {})); + _animation = CurvedAnimation( + parent: _controller, + curve: widget.curve, + ); + _style = ShadowedTextStyleTween(begin: widget.changedStyle, end: widget.style).animate(_animation); + } + + @override + void didUpdateWidget(ChangeHighlightText oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.data != widget.data) { + _controller + ..value = 0 + ..forward(); + } + } + + @override + void dispose() { + _animation.dispose(); + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Text( + widget.data, + style: _style.value, + ); + } +} + +class ShadowedTextStyleTween extends Tween<TextStyle> { + ShadowedTextStyleTween({super.begin, super.end}); + + @override + TextStyle lerp(double t) { + final textStyle = TextStyle.lerp(begin, end, t)!; + final beginShadows = begin!.shadows; + final endShadows = end!.shadows; + if (beginShadows != null && endShadows != null && beginShadows.length == endShadows.length) { + return textStyle.copyWith( + shadows: beginShadows.mapIndexed((i, a) { + final b = endShadows[i]; + return Shadow.lerp(a, b, t)!; + }).toList(), + ); + } else { + return textStyle; + } + } +} diff --git a/lib/widgets/common/basic/text/outlined.dart b/lib/widgets/common/basic/text/outlined.dart new file mode 100644 index 0000000..3ccf145 --- /dev/null +++ b/lib/widgets/common/basic/text/outlined.dart @@ -0,0 +1,102 @@ +import 'dart:ui'; + +import 'package:flutter/material.dart'; + +class OutlinedText extends StatelessWidget { + final List<TextSpan> textSpans; + final double outlineWidth; + final Color outlineColor; + final double outlineBlurSigma; + final TextAlign? textAlign; + final bool? softWrap; + final TextOverflow? overflow; + final int? maxLines; + + static const widgetSpanAlignment = PlaceholderAlignment.middle; + + const OutlinedText({ + super.key, + required this.textSpans, + double? outlineWidth, + Color? outlineColor, + double? outlineBlurSigma, + this.textAlign, + this.softWrap, + this.overflow, + this.maxLines, + }) : outlineWidth = outlineWidth ?? 1, + outlineColor = outlineColor ?? Colors.black, + outlineBlurSigma = outlineBlurSigma ?? 0; + + @override + Widget build(BuildContext context) { + // TODO TLAD [subtitles] fix background area for mixed alphabetic-ideographic text + // as of Flutter v3.10.0, the area computed for `backgroundColor` has inconsistent height + // in case of mixed alphabetic-ideographic text. The painted boxes depend on the script. + // Possible workarounds would be to use metrics from: + // - `TextPainter.getBoxesForSelection` + // - `Paragraph.getBoxesForRange` + // and paint the background at the bottom of the `Stack` + + final hasOutline = outlineWidth > 0; + + Widget? outline; + if (hasOutline) { + outline = Text.rich( + TextSpan( + children: textSpans.map(_toStrokeSpan).toList(), + ), + textAlign: textAlign, + softWrap: softWrap, + overflow: overflow, + maxLines: maxLines, + ); + if (outlineBlurSigma > 0) { + outline = ImageFiltered( + imageFilter: ImageFilter.blur( + sigmaX: outlineBlurSigma, + sigmaY: outlineBlurSigma, + ), + child: outline, + ); + } + } + + final fill = Text.rich( + TextSpan( + children: hasOutline ? textSpans.map(_toFillSpan).toList() : textSpans, + ), + textAlign: textAlign, + softWrap: softWrap, + overflow: overflow, + maxLines: maxLines, + ); + + return Stack( + children: [ + if (outline != null) outline, + fill, + ], + ); + } + + TextSpan _toStrokeSpan(TextSpan span) => TextSpan( + text: span.text, + children: span.children, + style: (span.style ?? const TextStyle()).copyWith( + foreground: Paint() + ..style = PaintingStyle.stroke + ..color = outlineColor + ..strokeWidth = outlineWidth, + ), + ); + + TextSpan _toFillSpan(TextSpan span) => TextSpan( + text: span.text, + children: span.children, + style: (span.style ?? const TextStyle()).copyWith( + backgroundColor: Colors.transparent, + shadows: [], + ), + ); +} diff --git a/lib/widgets/common/basic/text_dropdown_button.dart b/lib/widgets/common/basic/text_dropdown_button.dart new file mode 100644 index 0000000..e282446 --- /dev/null +++ b/lib/widgets/common/basic/text_dropdown_button.dart @@ -0,0 +1,93 @@ +import 'package:flutter/material.dart'; + +class TextDropdownButton<T> extends StatefulWidget { + final List<T> values; + final String Function(T value) valueText; + final IconData Function(T value)? valueIcon; + final T? value; + final Widget? underline; + final bool isExpanded; + final double? itemHeight; + final Color? dropdownColor; + final ValueChanged<T?>? onChanged; + + const TextDropdownButton({ + super.key, + required this.values, + required this.valueText, + this.valueIcon, + this.value, + this.underline, + this.isExpanded = false, + this.itemHeight = kMinInteractiveDimension, + this.dropdownColor, + required this.onChanged, + }); + + @override + State<TextDropdownButton<T>> createState() => _TextDropdownButtonState<T>(); +} + +class _TextDropdownButtonState<T> extends State<TextDropdownButton<T>> { + @override + Widget build(BuildContext context) { + return DropdownButton( + items: widget.values + .map((v) => DropdownMenuItem<T>( + value: v, + child: _buildItem(widget.valueText(v), widget.valueIcon?.call(v), selected: false), + )) + .toList(), + selectedItemBuilder: (context) => widget.values + .map((v) => DropdownMenuItem<T>( + value: v, + child: _buildItem(widget.valueText(v), widget.valueIcon?.call(v), selected: true), + )) + .toList(), + value: widget.value, + style: Theme.of(context).textTheme.titleMedium!.copyWith(fontWeight: FontWeight.normal), + underline: widget.underline, + isExpanded: widget.isExpanded, + itemHeight: widget.itemHeight, + dropdownColor: widget.dropdownColor, + onChanged: widget.onChanged, + ); + } + + static Widget _buildItem<T>(String text, IconData? icon, {required bool selected}) { + final softWrap = selected ? false : null; + final overflow = selected ? TextOverflow.fade : null; + + Widget child = icon != null + ? Text.rich( + TextSpan( + children: [ + WidgetSpan( + alignment: PlaceholderAlignment.middle, + child: Padding( + padding: const EdgeInsetsDirectional.only(end: 8, bottom: 2), + child: Icon(icon), + ), + ), + TextSpan(text: text), + ], + ), + softWrap: softWrap, + overflow: overflow, + ) + : Text( + text, + softWrap: softWrap, + overflow: overflow, + ); + + if (selected) { + child = Align( + alignment: AlignmentDirectional.centerStart, + child: child, + ); + } + + return child; + } +} diff --git a/lib/widgets/common/basic/time_shift_selector.dart b/lib/widgets/common/basic/time_shift_selector.dart new file mode 100644 index 0000000..da0aafc --- /dev/null +++ b/lib/widgets/common/basic/time_shift_selector.dart @@ -0,0 +1,152 @@ +import 'package:aves/ref/locales.dart'; +import 'package:aves/utils/time_utils.dart'; +import 'package:aves/widgets/common/basic/wheel.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; + +class TimeShiftSelector extends StatefulWidget { + final TimeShiftController controller; + + const TimeShiftSelector({ + super.key, + required this.controller, + }); + + @override + State<TimeShiftSelector> createState() => _TimeShiftSelectorState(); +} + +class _TimeShiftSelectorState extends State<TimeShiftSelector> { + late ValueNotifier<int> _shiftHour, _shiftMinute, _shiftSecond; + late ValueNotifier<String> _shiftSign; + + static const _positiveSign = '+'; + static const _negativeSign = '-'; + + @override + void initState() { + super.initState(); + + var initialValue = widget.controller.initialValue; + final sign = initialValue.isNegative ? _negativeSign : _positiveSign; + initialValue = initialValue.abs(); + final hours = initialValue.inHours; + initialValue -= Duration(hours: hours); + final minutes = initialValue.inMinutes; + initialValue -= Duration(minutes: minutes); + final seconds = initialValue.inSeconds; + + _shiftSign = ValueNotifier(sign); + _shiftHour = ValueNotifier(hours); + _shiftMinute = ValueNotifier(minutes); + _shiftSecond = ValueNotifier(seconds); + + _shiftSign.addListener(_updateValue); + _shiftHour.addListener(_updateValue); + _shiftMinute.addListener(_updateValue); + _shiftSecond.addListener(_updateValue); + } + + @override + void dispose() { + _shiftSign.dispose(); + _shiftHour.dispose(); + _shiftMinute.dispose(); + _shiftSecond.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + final timeComponentFormatter = NumberFormat('0', context.locale); + + const textStyle = TextStyle(fontSize: 34); + const digitsAlign = TextAlign.right; + + return Center( + child: Table( + textDirection: timeComponentsDirection, + children: [ + TableRow( + children: [ + const SizedBox(), + Center(child: Text(l10n.durationDialogHours)), + const SizedBox(width: 16), + Center(child: Text(l10n.durationDialogMinutes)), + const SizedBox(width: 16), + Center(child: Text(l10n.durationDialogSeconds)), + ], + ), + TableRow( + children: [ + WheelSelector( + valueNotifier: _shiftSign, + values: const [_positiveSign, _negativeSign], + textStyle: textStyle, + textAlign: TextAlign.center, + format: (v) => v, + ), + Align( + alignment: Alignment.centerRight, + child: WheelSelector( + valueNotifier: _shiftHour, + values: List.generate(hoursInDay, (i) => i), + textStyle: textStyle, + textAlign: digitsAlign, + format: timeComponentFormatter.format, + ), + ), + const Text( + ':', + style: textStyle, + ), + Align( + alignment: Alignment.centerLeft, + child: WheelSelector( + valueNotifier: _shiftMinute, + values: List.generate(minutesInHour, (i) => i), + textStyle: textStyle, + textAlign: digitsAlign, + format: timeComponentFormatter.format, + ), + ), + const Text( + ':', + style: textStyle, + ), + Align( + alignment: Alignment.centerLeft, + child: WheelSelector( + valueNotifier: _shiftSecond, + values: List.generate(secondsInMinute, (i) => i), + textStyle: textStyle, + textAlign: digitsAlign, + format: timeComponentFormatter.format, + ), + ), + ], + ) + ], + defaultColumnWidth: const IntrinsicColumnWidth(), + defaultVerticalAlignment: TableCellVerticalAlignment.middle, + ), + ); + } + + void _updateValue() { + final sign = _shiftSign.value == _positiveSign ? 1 : -1; + final hours = _shiftHour.value; + final minutes = _shiftMinute.value; + final seconds = _shiftSecond.value; + widget.controller.value = Duration(hours: hours, minutes: minutes, seconds: seconds) * sign; + } +} + +class TimeShiftController { + final Duration initialValue; + Duration value; + + TimeShiftController({required this.initialValue}) : value = initialValue; +} diff --git a/lib/widgets/common/basic/tv_edge_focus.dart b/lib/widgets/common/basic/tv_edge_focus.dart new file mode 100644 index 0000000..190d047 --- /dev/null +++ b/lib/widgets/common/basic/tv_edge_focus.dart @@ -0,0 +1,25 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +// to be placed at the edges of lists and grids, +// so that TV can reach them with D-pad +class TvEdgeFocus extends StatelessWidget { + final FocusNode? focusNode; + + const TvEdgeFocus({ + super.key, + this.focusNode, + }); + + @override + Widget build(BuildContext context) { + final useTvLayout = context.select<Settings, bool>((v) => v.useTvLayout); + return useTvLayout + ? Focus( + focusNode: focusNode, + child: const SizedBox(), + ) + : const SizedBox(); + } +} diff --git a/lib/widgets/common/basic/wheel.dart b/lib/widgets/common/basic/wheel.dart new file mode 100644 index 0000000..a5c6dff --- /dev/null +++ b/lib/widgets/common/basic/wheel.dart @@ -0,0 +1,172 @@ +import 'package:aves/theme/durations.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:provider/provider.dart'; + +class WheelSelector<T> extends StatefulWidget { + final ValueNotifier<T> valueNotifier; + final List<T> values; + final TextStyle textStyle; + final TextAlign textAlign; + final String Function(T v) format; + + const WheelSelector({ + super.key, + required this.valueNotifier, + required this.values, + required this.textStyle, + required this.textAlign, + required this.format, + }); + + @override + State<WheelSelector<T>> createState() => _WheelSelectorState<T>(); +} + +class _WheelSelectorState<T> extends State<WheelSelector<T>> { + late final FixedExtentScrollController _controller; + final ValueNotifier<bool> _focusedNotifier = ValueNotifier(false); + + ValueNotifier<T> get valueNotifier => widget.valueNotifier; + + List<T> get values => widget.values; + + @override + void initState() { + super.initState(); + _controller = FixedExtentScrollController( + initialItem: values.indexOf(valueNotifier.value), + ); + } + + @override + void dispose() { + _controller.dispose(); + _focusedNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final textScaler = MediaQuery.textScalerOf(context); + const background = Colors.transparent; + final foreground = DefaultTextStyle.of(context).style.color!; + final transitionDuration = context.select<DurationsData, Duration>((v) => v.formTransition); + final itemSize = Size.square(textScaler.scale(40)); + + return FocusableActionDetector( + shortcuts: const { + SingleActivator(LogicalKeyboardKey.arrowUp): _AdjustValueIntent.up(), + SingleActivator(LogicalKeyboardKey.arrowDown): _AdjustValueIntent.down(), + }, + actions: { + _AdjustValueIntent: CallbackAction<_AdjustValueIntent>(onInvoke: _onAdjustValueIntent), + }, + onShowFocusHighlight: (v) => _focusedNotifier.value = v, + child: NotificationListener<ScrollNotification>( + // cancel notification bubbling so that the dialog scroll bar + // does not misinterpret wheel scrolling for dialog content scrolling + onNotification: (notification) => true, + child: Padding( + padding: const EdgeInsets.all(8), + child: Stack( + children: [ + Positioned.fill( + child: Center( + child: ValueListenableBuilder<bool>( + valueListenable: _focusedNotifier, + builder: (context, focused, child) { + return AnimatedContainer( + width: itemSize.width, + height: itemSize.height, + duration: transitionDuration, + decoration: BoxDecoration( + color: foreground.withValues(alpha: focused ? .2 : 0), + borderRadius: const BorderRadius.all(Radius.circular(8)), + ), + ); + }), + ), + ), + SizedBox( + width: itemSize.width, + height: itemSize.height * 3, + child: ShaderMask( + shaderCallback: LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [ + background, + foreground, + foreground, + background, + ], + ).createShader, + child: Theme( + data: Theme.of(context).copyWith( + scrollbarTheme: ScrollbarThemeData( + thumbVisibility: WidgetStateProperty.all(false), + ), + ), + child: ListWheelScrollView( + controller: _controller, + physics: const FixedExtentScrollPhysics(parent: BouncingScrollPhysics()), + diameterRatio: 1.2, + itemExtent: itemSize.height, + squeeze: 1.3, + onSelectedItemChanged: (i) => valueNotifier.value = values[i], + children: values + .map((i) => SizedBox.fromSize( + size: itemSize, + child: Text( + widget.format(i), + textAlign: widget.textAlign, + style: widget.textStyle, + ), + )) + .toList(), + ), + ), + ), + ), + ], + ), + ), + ), + ); + } + + void _onAdjustValueIntent(_AdjustValueIntent intent) { + late int delta; + switch (intent.type) { + case _ValueAdjustmentType.up: + delta = -1; + case _ValueAdjustmentType.down: + delta = 1; + } + final targetItem = _controller.selectedItem + delta; + final duration = context.read<DurationsData>().formTransition; + if (duration > Duration.zero) { + _controller.animateToItem(targetItem, duration: duration, curve: Curves.easeInOutCubic); + } else { + _controller.jumpToItem(targetItem); + } + } +} + +class _AdjustValueIntent extends Intent { + const _AdjustValueIntent({ + required this.type, + }); + + const _AdjustValueIntent.up() : type = _ValueAdjustmentType.up; + + const _AdjustValueIntent.down() : type = _ValueAdjustmentType.down; + + final _ValueAdjustmentType type; +} + +enum _ValueAdjustmentType { + up, + down, +} diff --git a/lib/widgets/common/behaviour/eager_scale_gesture_recognizer.dart b/lib/widgets/common/behaviour/eager_scale_gesture_recognizer.dart new file mode 100644 index 0000000..aeba82b --- /dev/null +++ b/lib/widgets/common/behaviour/eager_scale_gesture_recognizer.dart @@ -0,0 +1,580 @@ +// ignore_for_file: depend_on_referenced_packages +import 'dart:math' as math; + +import 'package:flutter/gestures.dart'; + +// adapted from Flutter `ScaleGestureRecognizer` in `/gestures/scale.dart` +// ignore_for_file: avoid_types_on_closure_parameters, unnecessary_null_comparison + +/// The possible states of a [ScaleGestureRecognizer]. +enum _ScaleState { + /// The recognizer is ready to start recognizing a gesture. + ready, + + /// The sequence of pointer events seen thus far is consistent with a scale + /// gesture but the gesture has not been accepted definitively. + possible, + + /// The sequence of pointer events seen thus far has been accepted + /// definitively as a scale gesture. + accepted, + + /// The sequence of pointer events seen thus far has been accepted + /// definitively as a scale gesture and the pointers established a focal point + /// and initial scale. + started, +} + +class _PointerPanZoomData { + _PointerPanZoomData.fromStartEvent(this.parent, PointerPanZoomStartEvent event) + : _position = event.position, + _pan = Offset.zero, + _scale = 1, + _rotation = 0; + + _PointerPanZoomData.fromUpdateEvent(this.parent, PointerPanZoomUpdateEvent event) + : _position = event.position, + _pan = event.pan, + _scale = event.scale, + _rotation = event.rotation; + + final EagerScaleGestureRecognizer parent; + final Offset _position; + final Offset _pan; + final double _scale; + final double _rotation; + + Offset get focalPoint { + if (parent.trackpadScrollCausesScale) { + return _position; + } + return _position + _pan; + } + + double get scale { + if (parent.trackpadScrollCausesScale) { + return _scale * math.exp((_pan.dx * parent.trackpadScrollToScaleFactor.dx) + (_pan.dy * parent.trackpadScrollToScaleFactor.dy)); + } + return _scale; + } + + double get rotation => _rotation; + + @override + String toString() => '_PointerPanZoomData(parent: $parent, _position: $_position, _pan: $_pan, _scale: $_scale, _rotation: $_rotation)'; +} + +//////////////////////////////////////////////////////////////////////////////// + +bool _isFlingGesture(Velocity velocity) { + final double speedSquared = velocity.pixelsPerSecond.distanceSquared; + return speedSquared > kMinFlingVelocity * kMinFlingVelocity; +} + +/// Defines a line between two pointers on screen. +/// +/// [_LineBetweenPointers] is an abstraction of a line between two pointers in +/// contact with the screen. Used to track the rotation of a scale gesture. +class _LineBetweenPointers { + /// Creates a [_LineBetweenPointers]. None of the [pointerStartLocation], [pointerStartId] + /// [pointerEndLocation] and [pointerEndId] must be null. [pointerStartId] and [pointerEndId] + /// should be different. + _LineBetweenPointers({ + this.pointerStartLocation = Offset.zero, + this.pointerStartId = 0, + this.pointerEndLocation = Offset.zero, + this.pointerEndId = 1, + }) : assert(pointerStartId != pointerEndId); + + // The location and the id of the pointer that marks the start of the line. + final Offset pointerStartLocation; + final int pointerStartId; + + // The location and the id of the pointer that marks the end of the line. + final Offset pointerEndLocation; + final int pointerEndId; +} + +/// Recognizes a scale gesture. +/// +/// [ScaleGestureRecognizer] tracks the pointers in contact with the screen and +/// calculates their focal point, indicated scale, and rotation. When a focal +/// point is established, the recognizer calls [onStart]. As the focal point, +/// scale, and rotation change, the recognizer calls [onUpdate]. When the +/// pointers are no longer in contact with the screen, the recognizer calls +/// [onEnd]. +class EagerScaleGestureRecognizer extends OneSequenceGestureRecognizer { + /// Create a gesture recognizer for interactions intended for scaling content. + /// + /// {@macro flutter.gestures.GestureRecognizer.supportedDevices} + EagerScaleGestureRecognizer({ + super.debugOwner, + super.supportedDevices, + super.allowedButtonsFilter, + this.dragStartBehavior = DragStartBehavior.down, + this.trackpadScrollCausesScale = false, + this.trackpadScrollToScaleFactor = kDefaultTrackpadScrollToScaleFactor, + }); + + /// Determines what point is used as the starting point in all calculations + /// involving this gesture. + /// + /// When set to [DragStartBehavior.down], the scale is calculated starting + /// from the position where the pointer first contacted the screen. + /// + /// When set to [DragStartBehavior.start], the scale is calculated starting + /// from the position where the scale gesture began. The scale gesture may + /// begin after the time that the pointer first contacted the screen if there + /// are multiple listeners competing for the gesture. In that case, the + /// gesture arena waits to determine whether or not the gesture is a scale + /// gesture before giving the gesture to this GestureRecognizer. This happens + /// in the case of nested GestureDetectors, for example. + /// + /// Defaults to [DragStartBehavior.down]. + /// + /// See also: + /// + /// * https://flutter.dev/docs/development/ui/advanced/gestures#gesture-disambiguation, + /// which provides more information about the gesture arena. + DragStartBehavior dragStartBehavior; + + /// The pointers in contact with the screen have established a focal point and + /// initial scale of 1.0. + /// + /// This won't be called until the gesture arena has determined that this + /// GestureRecognizer has won the gesture. + /// + /// See also: + /// + /// * https://flutter.dev/docs/development/ui/advanced/gestures#gesture-disambiguation, + /// which provides more information about the gesture arena. + GestureScaleStartCallback? onStart; + + /// The pointers in contact with the screen have indicated a new focal point + /// and/or scale. + GestureScaleUpdateCallback? onUpdate; + + /// The pointers are no longer in contact with the screen. + GestureScaleEndCallback? onEnd; + + _ScaleState _state = _ScaleState.ready; + + Matrix4? _lastTransform; + + /// {@template flutter.gestures.scale.trackpadScrollCausesScale} + /// Whether scrolling up/down on a trackpad should cause scaling instead of + /// panning. + /// + /// Defaults to false. + /// {@endtemplate} + bool trackpadScrollCausesScale; + + /// {@template flutter.gestures.scale.trackpadScrollToScaleFactor} + /// A factor to control the direction and magnitude of scale when converting + /// trackpad scrolling. + /// + /// Incoming trackpad pan offsets will be divided by this factor to get scale + /// values. Increasing this offset will reduce the amount of scaling caused by + /// a fixed amount of trackpad scrolling. + /// + /// Defaults to [kDefaultTrackpadScrollToScaleFactor]. + /// {@endtemplate} + Offset trackpadScrollToScaleFactor; + + /// The number of pointers being tracked by the gesture recognizer. + /// + /// Typically this is the number of fingers being used to pan the widget using the gesture + /// recognizer. + int get pointerCount { + return _pointerPanZooms.length + _pointerQueue.length; + } + + late Offset _initialFocalPoint; + Offset? _currentFocalPoint; + late double _initialSpan; + late double _currentSpan; + late double _initialHorizontalSpan; + late double _currentHorizontalSpan; + late double _initialVerticalSpan; + late double _currentVerticalSpan; + late Offset _localFocalPoint; + _LineBetweenPointers? _initialLine; + _LineBetweenPointers? _currentLine; + final Map<int, Offset> _pointerLocations = <int, Offset>{}; + final List<int> _pointerQueue = <int>[]; // A queue to sort pointers in order of entrance + final Map<int, VelocityTracker> _velocityTrackers = <int, VelocityTracker>{}; + VelocityTracker? _scaleVelocityTracker; + late Offset _delta; + final Map<int, _PointerPanZoomData> _pointerPanZooms = <int, _PointerPanZoomData>{}; + double _initialPanZoomScaleFactor = 1; + double _initialPanZoomRotationFactor = 0; + + double get _pointerScaleFactor => _initialSpan > 0.0 ? _currentSpan / _initialSpan : 1.0; + + double get _pointerHorizontalScaleFactor => _initialHorizontalSpan > 0.0 ? _currentHorizontalSpan / _initialHorizontalSpan : 1.0; + + double get _pointerVerticalScaleFactor => _initialVerticalSpan > 0.0 ? _currentVerticalSpan / _initialVerticalSpan : 1.0; + + double get _scaleFactor { + double scale = _pointerScaleFactor; + for (final _PointerPanZoomData p in _pointerPanZooms.values) { + scale *= p.scale / _initialPanZoomScaleFactor; + } + return scale; + } + + double get _horizontalScaleFactor { + double scale = _pointerHorizontalScaleFactor; + for (final _PointerPanZoomData p in _pointerPanZooms.values) { + scale *= p.scale / _initialPanZoomScaleFactor; + } + return scale; + } + + double get _verticalScaleFactor { + double scale = _pointerVerticalScaleFactor; + for (final _PointerPanZoomData p in _pointerPanZooms.values) { + scale *= p.scale / _initialPanZoomScaleFactor; + } + return scale; + } + + double _computeRotationFactor() { + double factor = 0.0; + if (_initialLine != null && _currentLine != null) { + final double fx = _initialLine!.pointerStartLocation.dx; + final double fy = _initialLine!.pointerStartLocation.dy; + final double sx = _initialLine!.pointerEndLocation.dx; + final double sy = _initialLine!.pointerEndLocation.dy; + + final double nfx = _currentLine!.pointerStartLocation.dx; + final double nfy = _currentLine!.pointerStartLocation.dy; + final double nsx = _currentLine!.pointerEndLocation.dx; + final double nsy = _currentLine!.pointerEndLocation.dy; + + final double angle1 = math.atan2(fy - sy, fx - sx); + final double angle2 = math.atan2(nfy - nsy, nfx - nsx); + + factor = angle2 - angle1; + } + for (final _PointerPanZoomData p in _pointerPanZooms.values) { + factor += p.rotation; + } + factor -= _initialPanZoomRotationFactor; + return factor; + } + + @override + void addAllowedPointer(PointerDownEvent event) { + super.addAllowedPointer(event); + _velocityTrackers[event.pointer] = VelocityTracker.withKind(event.kind); + if (_state == _ScaleState.ready) { + _state = _ScaleState.possible; + _initialSpan = 0.0; + _currentSpan = 0.0; + _initialHorizontalSpan = 0.0; + _currentHorizontalSpan = 0.0; + _initialVerticalSpan = 0.0; + _currentVerticalSpan = 0.0; + } + } + + @override + bool isPointerPanZoomAllowed(PointerPanZoomStartEvent event) => true; + + @override + void addAllowedPointerPanZoom(PointerPanZoomStartEvent event) { + super.addAllowedPointerPanZoom(event); + startTrackingPointer(event.pointer, event.transform); + _velocityTrackers[event.pointer] = VelocityTracker.withKind(event.kind); + if (_state == _ScaleState.ready) { + _state = _ScaleState.possible; + _initialPanZoomScaleFactor = 1.0; + _initialPanZoomRotationFactor = 0.0; + } + } + + @override + void handleEvent(PointerEvent event) { + assert(_state != _ScaleState.ready); + bool didChangeConfiguration = false; + bool shouldStartIfAccepted = false; + if (event is PointerMoveEvent) { + final VelocityTracker tracker = _velocityTrackers[event.pointer]!; + if (!event.synthesized) { + tracker.addPosition(event.timeStamp, event.position); + } + _pointerLocations[event.pointer] = event.position; + shouldStartIfAccepted = true; + _lastTransform = event.transform; + } else if (event is PointerDownEvent) { + _pointerLocations[event.pointer] = event.position; + _pointerQueue.add(event.pointer); + didChangeConfiguration = true; + shouldStartIfAccepted = true; + _lastTransform = event.transform; + } else if (event is PointerUpEvent || event is PointerCancelEvent) { + _pointerLocations.remove(event.pointer); + _pointerQueue.remove(event.pointer); + didChangeConfiguration = true; + _lastTransform = event.transform; + } else if (event is PointerPanZoomStartEvent) { + assert(_pointerPanZooms[event.pointer] == null); + _pointerPanZooms[event.pointer] = _PointerPanZoomData.fromStartEvent(this, event); + didChangeConfiguration = true; + shouldStartIfAccepted = true; + _lastTransform = event.transform; + } else if (event is PointerPanZoomUpdateEvent) { + assert(_pointerPanZooms[event.pointer] != null); + if (!event.synthesized && !trackpadScrollCausesScale) { + _velocityTrackers[event.pointer]!.addPosition(event.timeStamp, event.pan); + } + _pointerPanZooms[event.pointer] = _PointerPanZoomData.fromUpdateEvent(this, event); + _lastTransform = event.transform; + shouldStartIfAccepted = true; + } else if (event is PointerPanZoomEndEvent) { + assert(_pointerPanZooms[event.pointer] != null); + _pointerPanZooms.remove(event.pointer); + didChangeConfiguration = true; + } + + _updateLines(); + _update(); + + if (!didChangeConfiguration || _reconfigure(event.pointer)) { + _advanceStateMachine(shouldStartIfAccepted, event); + } + stopTrackingIfPointerNoLongerDown(event); + } + + void _update() { + final Offset? previousFocalPoint = _currentFocalPoint; + + // Compute the focal point + Offset focalPoint = Offset.zero; + for (final int pointer in _pointerLocations.keys) { + focalPoint += _pointerLocations[pointer]!; + } + for (final _PointerPanZoomData p in _pointerPanZooms.values) { + focalPoint += p.focalPoint; + } + _currentFocalPoint = pointerCount > 0 ? focalPoint / pointerCount.toDouble() : Offset.zero; + + if (previousFocalPoint == null) { + _localFocalPoint = PointerEvent.transformPosition( + _lastTransform, + _currentFocalPoint!, + ); + _delta = Offset.zero; + } else { + final Offset localPreviousFocalPoint = _localFocalPoint; + _localFocalPoint = PointerEvent.transformPosition( + _lastTransform, + _currentFocalPoint!, + ); + _delta = _localFocalPoint - localPreviousFocalPoint; + } + + final int count = _pointerLocations.keys.length; + + Offset pointerFocalPoint = Offset.zero; + for (final int pointer in _pointerLocations.keys) { + pointerFocalPoint += _pointerLocations[pointer]!; + } + if (count > 0) { + pointerFocalPoint = pointerFocalPoint / count.toDouble(); + } + + // Span is the average deviation from focal point. Horizontal and vertical + // spans are the average deviations from the focal point's horizontal and + // vertical coordinates, respectively. + double totalDeviation = 0.0; + double totalHorizontalDeviation = 0.0; + double totalVerticalDeviation = 0.0; + for (final int pointer in _pointerLocations.keys) { + totalDeviation += (pointerFocalPoint - _pointerLocations[pointer]!).distance; + totalHorizontalDeviation += (pointerFocalPoint.dx - _pointerLocations[pointer]!.dx).abs(); + totalVerticalDeviation += (pointerFocalPoint.dy - _pointerLocations[pointer]!.dy).abs(); + } + _currentSpan = count > 0 ? totalDeviation / count : 0.0; + _currentHorizontalSpan = count > 0 ? totalHorizontalDeviation / count : 0.0; + _currentVerticalSpan = count > 0 ? totalVerticalDeviation / count : 0.0; + } + + /// Updates [_initialLine] and [_currentLine] accordingly to the situation of + /// the registered pointers. + void _updateLines() { + final int count = _pointerLocations.keys.length; + assert(_pointerQueue.length >= count); + + /// In case of just one pointer registered, reconfigure [_initialLine] + if (count < 2) { + _initialLine = _currentLine; + } else if (_initialLine != null && _initialLine!.pointerStartId == _pointerQueue[0] && _initialLine!.pointerEndId == _pointerQueue[1]) { + /// Rotation updated, set the [_currentLine] + _currentLine = _LineBetweenPointers( + pointerStartId: _pointerQueue[0], + pointerStartLocation: _pointerLocations[_pointerQueue[0]]!, + pointerEndId: _pointerQueue[1], + pointerEndLocation: _pointerLocations[_pointerQueue[1]]!, + ); + } else { + /// A new rotation process is on the way, set the [_initialLine] + _initialLine = _LineBetweenPointers( + pointerStartId: _pointerQueue[0], + pointerStartLocation: _pointerLocations[_pointerQueue[0]]!, + pointerEndId: _pointerQueue[1], + pointerEndLocation: _pointerLocations[_pointerQueue[1]]!, + ); + _currentLine = _initialLine; + } + } + + bool _reconfigure(int pointer) { + _initialFocalPoint = _currentFocalPoint!; + _initialSpan = _currentSpan; + _initialLine = _currentLine; + _initialHorizontalSpan = _currentHorizontalSpan; + _initialVerticalSpan = _currentVerticalSpan; + if (_pointerPanZooms.isEmpty) { + _initialPanZoomScaleFactor = 1.0; + _initialPanZoomRotationFactor = 0.0; + } else { + _initialPanZoomScaleFactor = _scaleFactor / _pointerScaleFactor; + _initialPanZoomRotationFactor = _pointerPanZooms.values.map((_PointerPanZoomData x) => x.rotation).reduce((double a, double b) => a + b); + } + if (_state == _ScaleState.started) { + if (onEnd != null) { + final VelocityTracker tracker = _velocityTrackers[pointer]!; + + Velocity velocity = tracker.getVelocity(); + if (_isFlingGesture(velocity)) { + final Offset pixelsPerSecond = velocity.pixelsPerSecond; + if (pixelsPerSecond.distanceSquared > kMaxFlingVelocity * kMaxFlingVelocity) { + velocity = Velocity(pixelsPerSecond: (pixelsPerSecond / pixelsPerSecond.distance) * kMaxFlingVelocity); + } + invokeCallback<void>('onEnd', () => onEnd!(ScaleEndDetails(velocity: velocity, scaleVelocity: _scaleVelocityTracker?.getVelocity().pixelsPerSecond.dx ?? -1, pointerCount: pointerCount))); + } else { + invokeCallback<void>('onEnd', () => onEnd!(ScaleEndDetails(scaleVelocity: _scaleVelocityTracker?.getVelocity().pixelsPerSecond.dx ?? -1, pointerCount: pointerCount))); + } + } + _state = _ScaleState.accepted; + _scaleVelocityTracker = VelocityTracker.withKind(PointerDeviceKind.touch); // arbitrary PointerDeviceKind + return false; + } + _scaleVelocityTracker = VelocityTracker.withKind(PointerDeviceKind.touch); // arbitrary PointerDeviceKind + return true; + } + + void _advanceStateMachine(bool shouldStartIfAccepted, PointerEvent event) { + if (_state == _ScaleState.ready) { + _state = _ScaleState.possible; + } + + // TLAD insert start + if (_pointerQueue.length == 2) { + resolve(GestureDisposition.accepted); + } + // TLAD insert end + + if (_state == _ScaleState.possible) { + final double spanDelta = (_currentSpan - _initialSpan).abs(); + final double focalPointDelta = (_currentFocalPoint! - _initialFocalPoint).distance; + if (spanDelta > computeScaleSlop(event.kind) || focalPointDelta > computePanSlop(event.kind, gestureSettings) || math.max(_scaleFactor / _pointerScaleFactor, _pointerScaleFactor / _scaleFactor) > 1.05) { + resolve(GestureDisposition.accepted); + } + } else if (_state.index >= _ScaleState.accepted.index) { + resolve(GestureDisposition.accepted); + } + + if (_state == _ScaleState.accepted && shouldStartIfAccepted) { + _state = _ScaleState.started; + _dispatchOnStartCallbackIfNeeded(); + } + + if (_state == _ScaleState.started) { + _scaleVelocityTracker?.addPosition(event.timeStamp, Offset(_scaleFactor, 0)); + if (onUpdate != null) { + invokeCallback<void>('onUpdate', () { + onUpdate!(ScaleUpdateDetails( + scale: _scaleFactor, + horizontalScale: _horizontalScaleFactor, + verticalScale: _verticalScaleFactor, + focalPoint: _currentFocalPoint!, + localFocalPoint: _localFocalPoint, + rotation: _computeRotationFactor(), + pointerCount: pointerCount, + focalPointDelta: _delta, + )); + }); + } + } + } + + void _dispatchOnStartCallbackIfNeeded() { + assert(_state == _ScaleState.started); + if (onStart != null) { + invokeCallback<void>('onStart', () { + onStart!(ScaleStartDetails( + focalPoint: _currentFocalPoint!, + localFocalPoint: _localFocalPoint, + pointerCount: pointerCount, + )); + }); + } + } + + @override + void acceptGesture(int pointer) { + if (_state == _ScaleState.possible) { + _state = _ScaleState.started; + _dispatchOnStartCallbackIfNeeded(); + if (dragStartBehavior == DragStartBehavior.start) { + _initialFocalPoint = _currentFocalPoint!; + _initialSpan = _currentSpan; + _initialLine = _currentLine; + _initialHorizontalSpan = _currentHorizontalSpan; + _initialVerticalSpan = _currentVerticalSpan; + if (_pointerPanZooms.isEmpty) { + _initialPanZoomScaleFactor = 1.0; + _initialPanZoomRotationFactor = 0.0; + } else { + _initialPanZoomScaleFactor = _scaleFactor / _pointerScaleFactor; + _initialPanZoomRotationFactor = _pointerPanZooms.values.map((_PointerPanZoomData x) => x.rotation).reduce((double a, double b) => a + b); + } + } + } + } + + @override + void rejectGesture(int pointer) { + _pointerPanZooms.remove(pointer); + _pointerLocations.remove(pointer); + _pointerQueue.remove(pointer); + stopTrackingPointer(pointer); + } + + @override + void didStopTrackingLastPointer(int pointer) { + switch (_state) { + case _ScaleState.possible: + resolve(GestureDisposition.rejected); + case _ScaleState.ready: + assert(false); // We should have not seen a pointer yet + case _ScaleState.accepted: + break; + case _ScaleState.started: + assert(false); // We should be in the accepted state when user is done + } + _state = _ScaleState.ready; + } + + @override + void dispose() { + _velocityTrackers.clear(); + super.dispose(); + } + + @override + String get debugDescription => 'scale'; +} diff --git a/lib/widgets/common/behaviour/intents.dart b/lib/widgets/common/behaviour/intents.dart new file mode 100644 index 0000000..98dcfd7 --- /dev/null +++ b/lib/widgets/common/behaviour/intents.dart @@ -0,0 +1,27 @@ +import 'package:flutter/widgets.dart'; + +class ScrollControllerAction extends CallbackAction<ScrollIntent> { + ScrollControllerAction({ + required ScrollController scrollController, + }) : super(onInvoke: (intent) => _onScrollIntent(intent, scrollController)); + + static void _onScrollIntent( + ScrollIntent intent, + ScrollController scrollController, + ) { + late int factor; + switch (intent.direction) { + case AxisDirection.up: + case AxisDirection.left: + factor = -1; + case AxisDirection.down: + case AxisDirection.right: + factor = 1; + } + scrollController.animateTo( + scrollController.offset + factor * 150, + duration: const Duration(milliseconds: 500), + curve: Curves.easeOutCubic, + ); + } +} diff --git a/lib/widgets/common/behaviour/known_extent_scroll_physics.dart b/lib/widgets/common/behaviour/known_extent_scroll_physics.dart new file mode 100644 index 0000000..018a049 --- /dev/null +++ b/lib/widgets/common/behaviour/known_extent_scroll_physics.dart @@ -0,0 +1,83 @@ +import 'package:flutter/physics.dart'; +import 'package:flutter/widgets.dart'; + +// adapted from Flutter `FixedExtentScrollPhysics` in `/widgets/list_wheel_scroll_view.dart` +class KnownExtentScrollPhysics extends ScrollPhysics { + final double Function(int index) indexToScrollOffset; + final int Function(double offset) scrollOffsetToIndex; + + const KnownExtentScrollPhysics({ + required this.indexToScrollOffset, + required this.scrollOffsetToIndex, + super.parent, + }); + + @override + KnownExtentScrollPhysics applyTo(ScrollPhysics? ancestor) { + return KnownExtentScrollPhysics( + indexToScrollOffset: indexToScrollOffset, + scrollOffsetToIndex: scrollOffsetToIndex, + parent: buildParent(ancestor), + ); + } + + @override + Simulation? createBallisticSimulation(ScrollMetrics position, double velocity) { + final ScrollMetrics metrics = position; + + // Scenario 1: + // If we're out of range and not headed back in range, defer to the parent + // ballistics, which should put us back in range at the scrollable's boundary. + if ((velocity <= 0.0 && metrics.pixels <= metrics.minScrollExtent) || (velocity >= 0.0 && metrics.pixels >= metrics.maxScrollExtent)) { + return super.createBallisticSimulation(metrics, velocity); + } + + // Create a test simulation to see where it would have ballistically fallen + // naturally without settling onto items. + final Simulation? testFrictionSimulation = super.createBallisticSimulation(metrics, velocity); + + // Scenario 2: + // If it was going to end up past the scroll extent, defer back to the + // parent physics' ballistics again which should put us on the scrollable's + // boundary. + if (testFrictionSimulation != null && (testFrictionSimulation.x(double.infinity) == metrics.minScrollExtent || testFrictionSimulation.x(double.infinity) == metrics.maxScrollExtent)) { + return super.createBallisticSimulation(metrics, velocity); + } + + // From the natural final position, find the nearest item it should have + // settled to. + final offset = (testFrictionSimulation?.x(double.infinity) ?? metrics.pixels).clamp(metrics.minScrollExtent, metrics.maxScrollExtent); + final int settlingItemIndex = scrollOffsetToIndex(offset); + final double settlingPixels = indexToScrollOffset(settlingItemIndex); + + // Scenario 3: + // If there's no velocity and we're already at where we intend to land, + // do nothing. + if (velocity.abs() < toleranceFor(position).velocity && (settlingPixels - metrics.pixels).abs() < toleranceFor(position).distance) { + return null; + } + + // Scenario 4: + // If we're going to end back at the same item because initial velocity + // is too low to break past it, use a spring simulation to get back. + if (settlingItemIndex == scrollOffsetToIndex(metrics.pixels)) { + return SpringSimulation( + spring, + metrics.pixels, + settlingPixels, + velocity, + tolerance: toleranceFor(position), + ); + } + + // Scenario 5: + // Create a new friction simulation except the drag will be tweaked to land + // exactly on the item closest to the natural stopping point. + return FrictionSimulation.through( + metrics.pixels, + settlingPixels, + velocity, + toleranceFor(position).velocity * velocity.sign, + ); + } +} diff --git a/lib/widgets/common/behaviour/pop/double_back.dart b/lib/widgets/common/behaviour/pop/double_back.dart new file mode 100644 index 0000000..d73aa56 --- /dev/null +++ b/lib/widgets/common/behaviour/pop/double_back.dart @@ -0,0 +1,49 @@ +import 'dart:async'; + +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/widgets/common/behaviour/pop/scope.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:overlay_support/overlay_support.dart'; +import 'package:provider/provider.dart'; + +final DoubleBackPopHandler doubleBackPopHandler = DoubleBackPopHandler._private(); + +class DoubleBackPopHandler extends PopHandler { + bool _backOnce = false; + Timer? _backTimer; + + DoubleBackPopHandler._private(); + + @override + bool canPop(BuildContext context) { + if (context.select<Settings, bool>((v) => !v.mustBackTwiceToExit)) return true; + if (Navigator.canPop(context)) return true; + return false; + } + + @override + void onPopBlocked(BuildContext context) { + if (_backOnce) { + if (Navigator.canPop(context)) { + Navigator.maybeOf(context)?.pop(); + } else { + // exit + reportService.log('Exit by pop'); + PopExitNotification().dispatch(context); + SystemNavigator.pop(); + } + } else { + _backOnce = true; + _backTimer?.cancel(); + _backTimer = Timer(ADurations.doubleBackTimerDelay, () => _backOnce = false); + toast( + context.l10n.doubleBackExitMessage, + duration: ADurations.doubleBackTimerDelay, + ); + } + } +} diff --git a/lib/widgets/common/behaviour/pop/scope.dart b/lib/widgets/common/behaviour/pop/scope.dart new file mode 100644 index 0000000..ff750b9 --- /dev/null +++ b/lib/widgets/common/behaviour/pop/scope.dart @@ -0,0 +1,54 @@ +import 'package:collection/collection.dart'; +import 'package:flutter/widgets.dart'; + +// this widget combines multiple pop handlers with a guaranteed order +class AvesPopScope extends StatelessWidget { + final List<PopHandler> handlers; + final Widget child; + + const AvesPopScope({ + super.key, + required this.handlers, + required this.child, + }); + + @override + Widget build(BuildContext context) { + final blocker = handlers.firstWhereOrNull((v) => !v.canPop(context)); + return PopScope( + canPop: blocker == null, + onPopInvokedWithResult: (didPop, result) { + if (!didPop) { + blocker?.onPopBlocked(context); + } + }, + child: child, + ); + } +} + +abstract class PopHandler { + bool canPop(BuildContext context); + + void onPopBlocked(BuildContext context); +} + +class APopHandler implements PopHandler { + final bool Function(BuildContext context) _canPop; + final void Function(BuildContext context) _onPopBlocked; + + APopHandler({ + required bool Function(BuildContext context) canPop, + required void Function(BuildContext context) onPopBlocked, + }) : _canPop = canPop, + _onPopBlocked = onPopBlocked; + + @override + bool canPop(BuildContext context) => _canPop(context); + + @override + void onPopBlocked(BuildContext context) => _onPopBlocked(context); +} + +@immutable +class PopExitNotification extends Notification {} diff --git a/lib/widgets/common/behaviour/pop/tv_navigation.dart b/lib/widgets/common/behaviour/pop/tv_navigation.dart new file mode 100644 index 0000000..4935907 --- /dev/null +++ b/lib/widgets/common/behaviour/pop/tv_navigation.dart @@ -0,0 +1,43 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/widgets/collection/collection_page.dart'; +import 'package:aves/widgets/common/behaviour/pop/scope.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +final TvNavigationPopHandler tvNavigationPopHandler = TvNavigationPopHandler._private(); + +// address `TV-DB` requirement from https://developer.android.com/docs/quality-guidelines/tv-app-quality +class TvNavigationPopHandler implements PopHandler { + TvNavigationPopHandler._private(); + + @override + bool canPop(BuildContext context) { + if (context.select<Settings, bool>((v) => !v.useTvLayout)) return true; + if (_isHome(context)) return true; + return false; + } + + @override + void onPopBlocked(BuildContext context) { + Navigator.maybeOf(context)?.pushAndRemoveUntil( + settings.homeNavItem.routeBuilder(context, topLevel: true), + (route) => false, + ); + } + + static bool _isHome(BuildContext context) { + final home = settings.homeNavItem; + final currentRoute = context.currentRouteName; + + if (currentRoute != home.route) return false; + + switch (home.route) { + case CollectionPage.routeName: + return context.read<CollectionLens>().filters.isEmpty; + default: + return true; + } + } +} diff --git a/lib/widgets/common/behaviour/route_tracker.dart b/lib/widgets/common/behaviour/route_tracker.dart new file mode 100644 index 0000000..274e08a --- /dev/null +++ b/lib/widgets/common/behaviour/route_tracker.dart @@ -0,0 +1,18 @@ +import 'package:aves/services/common/services.dart'; +import 'package:flutter/material.dart'; + +class ReportingRouteTracker extends NavigatorObserver { + @override + void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) => reportService.log('Nav push to ${_name(route)}'); + + @override + void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) => reportService.log('Nav pop to ${_name(previousRoute)}'); + + @override + void didRemove(Route<dynamic> route, Route<dynamic>? previousRoute) => reportService.log('Nav remove to ${_name(previousRoute)}'); + + @override + void didReplace({Route<dynamic>? newRoute, Route<dynamic>? oldRoute}) => reportService.log('Nav replace to ${_name(newRoute)}'); + + String _name(Route<dynamic>? route) => route?.settings.name ?? 'unnamed ${route?.runtimeType}'; +} diff --git a/lib/widgets/common/behaviour/routes.dart b/lib/widgets/common/behaviour/routes.dart new file mode 100644 index 0000000..e9a42d8 --- /dev/null +++ b/lib/widgets/common/behaviour/routes.dart @@ -0,0 +1,46 @@ +import 'package:flutter/material.dart'; + +class DirectPageTransitionsTheme extends PageTransitionsTheme { + const DirectPageTransitionsTheme(); + + @override + Widget buildTransitions<T>( + PageRoute<T> route, + BuildContext context, + Animation<double> animation, + Animation<double> secondaryAnimation, + Widget child, + ) => + child; +} + +class DirectMaterialPageRoute<T> extends PageRouteBuilder<T> { + DirectMaterialPageRoute({ + super.settings, + required WidgetBuilder builder, + }) : super( + transitionDuration: Duration.zero, + pageBuilder: (context, a, sa) => builder(context), + ); + + @override + Widget buildTransitions(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) { + return child; + } +} + +class TransparentMaterialPageRoute<T> extends PageRouteBuilder<T> { + TransparentMaterialPageRoute({ + super.settings, + required super.pageBuilder, + }); + + @override + bool get opaque => false; + + @override + Widget buildTransitions(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) { + final theme = Theme.of(context).pageTransitionsTheme; + return theme.buildTransitions<T>(this, context, animation, secondaryAnimation, child); + } +} diff --git a/lib/widgets/common/behaviour/sloppy_scroll_physics.dart b/lib/widgets/common/behaviour/sloppy_scroll_physics.dart new file mode 100644 index 0000000..f850795 --- /dev/null +++ b/lib/widgets/common/behaviour/sloppy_scroll_physics.dart @@ -0,0 +1,30 @@ +import 'package:flutter/gestures.dart'; +import 'package:flutter/widgets.dart'; + +// TODO TLAD merge with `MagnifierScrollerPhysics` +class SloppyScrollPhysics extends ScrollPhysics { + final DeviceGestureSettings? gestureSettings; + + // in [0, 1] + // 0: most reactive but will not let Magnifier recognizers accept gestures + // 1: less reactive but gives the most leeway to Magnifier recognizers + final double touchSlopFactor; + + const SloppyScrollPhysics({ + required this.gestureSettings, + this.touchSlopFactor = 1, + super.parent, + }); + + @override + SloppyScrollPhysics applyTo(ScrollPhysics? ancestor) { + return SloppyScrollPhysics( + gestureSettings: gestureSettings, + touchSlopFactor: touchSlopFactor, + parent: buildParent(ancestor), + ); + } + + @override + double get dragStartDistanceMotionThreshold => (gestureSettings?.touchSlop ?? kTouchSlop) * touchSlopFactor; +} diff --git a/lib/widgets/common/behaviour/springy_scroll_physics.dart b/lib/widgets/common/behaviour/springy_scroll_physics.dart new file mode 100644 index 0000000..51b887c --- /dev/null +++ b/lib/widgets/common/behaviour/springy_scroll_physics.dart @@ -0,0 +1,19 @@ +import 'package:flutter/widgets.dart'; + +class SpringyScrollPhysics extends ScrollPhysics { + @override + final SpringDescription spring; + + const SpringyScrollPhysics({ + required this.spring, + super.parent, + }); + + @override + SpringyScrollPhysics applyTo(ScrollPhysics? ancestor) { + return SpringyScrollPhysics( + spring: spring, + parent: buildParent(ancestor), + ); + } +} diff --git a/lib/widgets/common/expandable_filter_row.dart b/lib/widgets/common/expandable_filter_row.dart new file mode 100644 index 0000000..a69652c --- /dev/null +++ b/lib/widgets/common/expandable_filter_row.dart @@ -0,0 +1,181 @@ +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/theme/styles.dart'; +import 'package:aves/widgets/common/identity/aves_filter_chip.dart'; +import 'package:flutter/material.dart'; + +class TitledExpandableFilterRow extends StatelessWidget { + final String title; + final List<CollectionFilter> filters; + final ValueNotifier<String?> expandedNotifier; + final bool showGenericIcon; + final HeroType Function(CollectionFilter filter)? heroTypeBuilder; + final AFilterCallback onTap; + final OffsetFilterCallback? onLongPress; + + const TitledExpandableFilterRow({ + super.key, + required this.title, + required this.filters, + required this.expandedNotifier, + this.showGenericIcon = true, + this.heroTypeBuilder, + required this.onTap, + required this.onLongPress, + }); + + @override + Widget build(BuildContext context) { + if (filters.isEmpty) return const SizedBox(); + + final isExpanded = expandedNotifier.value == title; + + Widget header = Text( + title, + style: AStyles.knownTitleText, + ); + void toggle() => expandedNotifier.value = isExpanded ? null : title; + if (settings.useTvLayout) { + header = Padding( + padding: const EdgeInsets.symmetric(vertical: 8), + child: InkWell( + onTap: toggle, + borderRadius: const BorderRadius.all(Radius.circular(123)), + child: Padding( + padding: const EdgeInsets.all(16), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + header, + const SizedBox(width: 16), + Icon(isExpanded ? AIcons.collapse : AIcons.expand), + ], + ), + ), + ), + ); + } else { + header = Padding( + padding: const EdgeInsets.all(16), + child: Row( + children: [ + header, + const Spacer(), + IconButton( + icon: Icon(isExpanded ? AIcons.collapse : AIcons.expand), + onPressed: toggle, + tooltip: isExpanded ? MaterialLocalizations.of(context).expandedIconTapHint : MaterialLocalizations.of(context).collapsedIconTapHint, + ), + ], + ), + ); + } + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + header, + ExpandableFilterRow( + filters: filters, + isExpanded: isExpanded, + showGenericIcon: showGenericIcon, + heroTypeBuilder: heroTypeBuilder, + onTap: onTap, + onLongPress: onLongPress, + ), + ], + ); + } +} + +class ExpandableFilterRow extends StatelessWidget { + final List<CollectionFilter> filters; + final bool isExpanded; + final bool showGenericIcon; + final Widget? Function(CollectionFilter)? leadingBuilder; + final HeroType Function(CollectionFilter filter)? heroTypeBuilder; + final AFilterCallback onTap; + final AFilterCallback? onRemove; + final OffsetFilterCallback? onLongPress; + + static const double horizontalPadding = 8; + static const double verticalPadding = 8; + + const ExpandableFilterRow({ + super.key, + required this.filters, + required this.isExpanded, + this.showGenericIcon = true, + this.leadingBuilder, + this.heroTypeBuilder, + required this.onTap, + this.onRemove, + required this.onLongPress, + }); + + @override + Widget build(BuildContext context) { + if (filters.isEmpty) return const SizedBox(); + return AnimatedSwitcher( + duration: ADurations.filterRowExpandAnimation, + layoutBuilder: (currentChild, previousChildren) => Stack( + children: [ + ...previousChildren, + if (currentChild != null) currentChild, + ], + ), + child: isExpanded ? _buildExpanded() : _buildCollapsed(), + ); + } + + Widget _buildExpanded() { + return Container( + key: const Key('wrap'), + padding: const EdgeInsets.symmetric(horizontal: horizontalPadding), + // specify transparent as a workaround to prevent + // chip border clipping when the floating app bar is fading + color: Colors.transparent, + child: Wrap( + spacing: horizontalPadding, + runSpacing: verticalPadding, + children: filters.map(_buildChip).toList(), + ), + ); + } + + Widget _buildCollapsed() { + final list = Container( + key: const Key('list'), + // specify transparent as a workaround to prevent + // chip border clipping when the floating app bar is fading + color: Colors.transparent, + height: AvesFilterChip.minChipHeight, + child: ListView.separated( + scrollDirection: Axis.horizontal, + padding: const EdgeInsets.symmetric(horizontal: horizontalPadding), + itemBuilder: (context, index) { + return index < filters.length ? _buildChip(filters[index]) : const SizedBox(); + }, + separatorBuilder: (context, index) => const SizedBox(width: 8), + itemCount: filters.length, + ), + ); + return list; + } + + Widget _buildChip(CollectionFilter filter) { + return AvesFilterChip( + // key is expected by test driver + key: Key(filter.key), + filter: filter, + allowGenericIcon: showGenericIcon, + leadingOverride: leadingBuilder?.call(filter), + heroType: heroTypeBuilder?.call(filter) ?? HeroType.onTap, + onTap: onTap, + onRemove: onRemove, + onLongPress: onLongPress, + ); + } +} diff --git a/lib/widgets/common/extensions/build_context.dart b/lib/widgets/common/extensions/build_context.dart new file mode 100644 index 0000000..ba02734 --- /dev/null +++ b/lib/widgets/common/extensions/build_context.dart @@ -0,0 +1,25 @@ +import 'package:aves/l10n/l10n.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; + +extension ExtraContext on BuildContext { + String? get currentRouteName => ModalRoute.of(this)?.settings.name; + + AppLocalizations get l10n => AppLocalizations.of(this)!; + + String get locale => l10n.localeName; + + bool get isArabic => locale.startsWith('ar'); + + bool get isRtl => Directionality.of(this) == TextDirection.rtl; + + String applyDirectionality(String text) => '$_directionalityMark$text'; + + String get _directionalityMark { + if (isRtl) { + return isArabic ? Unicode.ALM : Unicode.RLM; + } else { + return Unicode.LRM; + } + } +} diff --git a/lib/widgets/common/extensions/geometry.dart b/lib/widgets/common/extensions/geometry.dart new file mode 100644 index 0000000..3979c4a --- /dev/null +++ b/lib/widgets/common/extensions/geometry.dart @@ -0,0 +1,7 @@ +import 'dart:ui'; + +extension ExtraRect on Rect { + bool containsIncludingBottomRight(Offset offset, {double tolerance = 0}) { + return offset.dx >= left - tolerance && offset.dx <= right + tolerance && offset.dy >= top - tolerance && offset.dy <= bottom + tolerance; + } +} diff --git a/lib/widgets/common/extensions/media_query.dart b/lib/widgets/common/extensions/media_query.dart new file mode 100644 index 0000000..f3a1cfc --- /dev/null +++ b/lib/widgets/common/extensions/media_query.dart @@ -0,0 +1,65 @@ +import 'dart:math'; + +import 'package:flutter/widgets.dart'; + +extension ExtraMediaQueryData on MediaQueryData { + /* + examples of MediaQuery props in practice + + -- Flutter v1.22.5 + + S20, Android 11, portrait, notch top, button nav bar bottom + padding EdgeInsets(0.0, 26.0, 0.0, 48.0) + viewPadding EdgeInsets(0.0, 26.0, 0.0, 48.0) + viewInsets EdgeInsets.zero + + S20, Android 11, landscape, notch left, button nav bar right + padding EdgeInsets(26.0, 24.0, 0.0, 0.0) + viewPadding EdgeInsets(26.0, 24.0, 0.0, 0.0) + viewInsets EdgeInsets.zero + + S10e, Android 10, portrait, notch top, button nav bar bottom + padding EdgeInsets(0.0, 39.0, 0.0, 0.0) + viewPadding EdgeInsets(0.0, 39.0, 0.0, 0.0) + viewInsets EdgeInsets(0.0, 0.0, 0.0, 48.0) + + S10e, Android 10, portrait, notch top, gesture nav bar bottom + padding EdgeInsets(0.0, 39.0, 0.0, 0.0) + viewPadding EdgeInsets(0.0, 39.0, 0.0, 0.0) + viewInsets EdgeInsets(0.0, 0.0, 0.0, 15.0) + + S10e, Android 10, landscape, notch left, button nav bar right + padding EdgeInsets(38.7, 24.0, 0.0, 0.0) + viewPadding EdgeInsets(38.7, 24.0, 0.0, 0.0) + viewInsets EdgeInsets.zero + + S7, portrait/landscape, no notch, no nav bar + padding EdgeInsets(0.0, 24.0, 0.0, 0.0) + viewPadding EdgeInsets(0.0, 24.0, 0.0, 0.0) + viewInsets EdgeInsets.zero + + -- Flutter v2.2.1 + + S10e, Android 11, portrait, notch top, button nav bar bottom, keyboard off + padding EdgeInsets(0.0, 39.0, 0.0, 48.0) + viewPadding EdgeInsets(0.0, 39.0, 0.0, 48.0) + viewInsets EdgeInsets.zero + + S10e, Android 11, portrait, notch top, button nav bar bottom, keyboard on + padding EdgeInsets(0.0, 39.0, 0.0, 0.0) + viewPadding EdgeInsets(0.0, 39.0, 0.0, 48.0) + viewInsets EdgeInsets(0.0, 0.0, 0.0, 338.0) + + S10e, Android 11, portrait, notch top, gesture nav bar bottom, keyboard off + padding EdgeInsets(0.0, 39.0, 0.0, 15.0) + viewPadding EdgeInsets(0.0, 39.0, 0.0, 15.0) + viewInsets EdgeInsets.zero + + S10e, Android 11, portrait, notch top, gesture nav bar bottom, keyboard on + padding EdgeInsets(0.0, 39.0, 0.0, 0.0) + viewPadding EdgeInsets(0.0, 39.0, 0.0, 15.0) + viewInsets EdgeInsets(0.0, 0.0, 0.0, 338.0) + */ + + double get effectiveBottomPadding => max(viewPadding.bottom, viewInsets.bottom); +} diff --git a/lib/widgets/common/extensions/theme.dart b/lib/widgets/common/extensions/theme.dart new file mode 100644 index 0000000..0ad34a6 --- /dev/null +++ b/lib/widgets/common/extensions/theme.dart @@ -0,0 +1,5 @@ +import 'package:flutter/material.dart'; + +extension ExtraThemeData on ThemeData { + bool get isDark => brightness == Brightness.dark; +} diff --git a/lib/widgets/common/fx/blurred.dart b/lib/widgets/common/fx/blurred.dart new file mode 100644 index 0000000..f1e4139 --- /dev/null +++ b/lib/widgets/common/fx/blurred.dart @@ -0,0 +1,94 @@ +import 'dart:ui'; + +import 'package:flutter/material.dart'; + +final _filter = ImageFilter.blur(sigmaX: 4, sigmaY: 4); +// do not use `ColorFilter.matrix` for identity, +// as it yields performance issues when there are other layers on top +final _identity = ImageFilter.matrix(Matrix4.identity().storage); + +class BlurredRect extends StatelessWidget { + final bool enabled; + final Widget child; + + const BlurredRect({ + super.key, + this.enabled = true, + required this.child, + }); + + @override + Widget build(BuildContext context) { + return ClipRect( + // TODO TLAD [flutter vNext] use `BackdropFilter.grouped` + child: BackdropFilter( + // do not modify tree when disabling filter + filter: enabled ? _filter : _identity, + child: child, + ), + ); + } +} + +class BlurredRRect extends StatelessWidget { + final bool enabled; + final BorderRadius? borderRadius; + final Widget child; + + const BlurredRRect({ + super.key, + this.enabled = true, + required this.borderRadius, + required this.child, + }); + + factory BlurredRRect.all({ + Key? key, + bool enabled = true, + required double borderRadius, + required Widget child, + }) { + return BlurredRRect( + key: key, + enabled: enabled, + borderRadius: BorderRadius.all(Radius.circular(borderRadius)), + child: child, + ); + } + + @override + Widget build(BuildContext context) { + return ClipRRect( + borderRadius: borderRadius ?? BorderRadius.zero, + // TODO TLAD [flutter vNext] use `BackdropFilter.grouped` + child: BackdropFilter( + // do not modify tree when disabling filter + filter: enabled ? _filter : _identity, + child: child, + ), + ); + } +} + +class BlurredOval extends StatelessWidget { + final bool enabled; + final Widget child; + + const BlurredOval({ + super.key, + this.enabled = true, + required this.child, + }); + + @override + Widget build(BuildContext context) { + return ClipOval( + // TODO TLAD [flutter vNext] use `BackdropFilter.grouped` + child: BackdropFilter( + // do not modify tree when disabling filter + filter: enabled ? _filter : _identity, + child: child, + ), + ); + } +} diff --git a/lib/widgets/common/fx/borders.dart b/lib/widgets/common/fx/borders.dart new file mode 100644 index 0000000..ac4cfdc --- /dev/null +++ b/lib/widgets/common/fx/borders.dart @@ -0,0 +1,24 @@ +import 'package:aves/widgets/common/extensions/theme.dart'; +import 'package:flutter/material.dart'; + +class AvesBorder { + static Color _borderColor(BuildContext context) => Theme.of(context).isDark ? Colors.white30 : Colors.black26; + + // 1 device pixel for straight lines is fine + static double straightBorderWidth(BuildContext context) => 1 / MediaQuery.devicePixelRatioOf(context); + + // 1 device pixel for curves is too thin + static double curvedBorderWidth(BuildContext context) => MediaQuery.devicePixelRatioOf(context) > 2 ? 0.5 : 1.0; + + static BorderSide straightSide(BuildContext context, {double? width}) => BorderSide( + color: _borderColor(context), + width: width ?? straightBorderWidth(context), + ); + + static BorderSide curvedSide(BuildContext context, {double? width}) => BorderSide( + color: _borderColor(context), + width: width ?? curvedBorderWidth(context), + ); + + static Border border(BuildContext context, {double? width}) => Border.fromBorderSide(curvedSide(context, width: width)); +} diff --git a/lib/widgets/common/fx/checkered_decoration.dart b/lib/widgets/common/fx/checkered_decoration.dart new file mode 100644 index 0000000..b7fb249 --- /dev/null +++ b/lib/widgets/common/fx/checkered_decoration.dart @@ -0,0 +1,40 @@ +import 'package:flutter/material.dart'; + +class CheckeredPainter extends CustomPainter { + final Paint lightPaint, darkPaint; + final double checkSize; + final Offset offset; + + CheckeredPainter({ + Color light = const Color(0xFF999999), + Color dark = const Color(0xFF666666), + this.checkSize = 20, + this.offset = Offset.zero, + }) : lightPaint = Paint()..color = light, + darkPaint = Paint()..color = dark; + + @override + void paint(Canvas canvas, Size size) { + final background = Offset.zero & size; + canvas.drawRect(background, lightPaint); + + final dx = offset.dx % (checkSize * 2); + final dy = offset.dy % (checkSize * 2); + + final xMax = (size.width / checkSize).ceil(); + final yMax = (size.height / checkSize).ceil(); + for (var x = -2; x < xMax; x++) { + for (var y = -2; y < yMax; y++) { + if ((x + y) % 2 == 0) { + final check = Rect.fromLTWH(dx + x * checkSize, dy + y * checkSize, checkSize, checkSize); + if (check.overlaps(background)) { + canvas.drawRect(check.intersect(background), darkPaint); + } + } + } + } + } + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => false; +} diff --git a/lib/widgets/common/fx/colors.dart b/lib/widgets/common/fx/colors.dart new file mode 100644 index 0000000..0b7646f --- /dev/null +++ b/lib/widgets/common/fx/colors.dart @@ -0,0 +1,26 @@ +import 'package:flutter/painting.dart'; + +class MatrixColorFilters { + static const ColorFilter greyscale = ColorFilter.matrix(<double>[ + 0.2126, + 0.7152, + 0.0722, + 0, + 0, + 0.2126, + 0.7152, + 0.0722, + 0, + 0, + 0.2126, + 0.7152, + 0.0722, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + ]); +} diff --git a/lib/widgets/common/fx/dashed_path_painter.dart b/lib/widgets/common/fx/dashed_path_painter.dart new file mode 100644 index 0000000..847ca42 --- /dev/null +++ b/lib/widgets/common/fx/dashed_path_painter.dart @@ -0,0 +1,142 @@ +import 'dart:math' as math; +import 'dart:ui' as ui; + +import 'package:flutter/material.dart'; + +// from https://stackoverflow.com/a/71099304/786656 +class DashedPathPainter extends CustomPainter { + final Path originalPath; + final Color pathColor; + final double strokeWidth; + final double dashGapLength; + final double dashLength; + late DashedPathProperties _dashedPathProperties; + + DashedPathPainter({ + required this.originalPath, + required this.pathColor, + this.strokeWidth = 3.0, + this.dashGapLength = 5.0, + this.dashLength = 10.0, + }); + + @override + void paint(Canvas canvas, Size size) { + _dashedPathProperties = DashedPathProperties( + path: Path(), + dashLength: dashLength, + dashGapLength: dashGapLength, + ); + final dashedPath = _getDashedPath(originalPath, dashLength, dashGapLength); + canvas.drawPath( + dashedPath, + Paint() + ..style = PaintingStyle.stroke + ..color = pathColor + ..strokeWidth = strokeWidth, + ); + } + + @override + bool shouldRepaint(DashedPathPainter oldDelegate) => oldDelegate.originalPath != originalPath || oldDelegate.pathColor != pathColor || oldDelegate.strokeWidth != strokeWidth || oldDelegate.dashGapLength != dashGapLength || oldDelegate.dashLength != dashLength; + + Path _getDashedPath( + Path originalPath, + double dashLength, + double dashGapLength, + ) { + final metricsIterator = originalPath.computeMetrics().iterator; + while (metricsIterator.moveNext()) { + final metric = metricsIterator.current; + _dashedPathProperties.extractedPathLength = 0.0; + while (_dashedPathProperties.extractedPathLength < metric.length) { + if (_dashedPathProperties.addDashNext) { + _dashedPathProperties.addDash(metric, dashLength); + } else { + _dashedPathProperties.addDashGap(metric, dashGapLength); + } + } + } + return _dashedPathProperties.path; + } +} + +class DashedPathProperties { + double extractedPathLength; + Path path; + + final double _dashLength; + double _remainingDashLength; + double _remainingDashGapLength; + bool _previousWasDash; + + DashedPathProperties({ + required this.path, + required double dashLength, + required double dashGapLength, + }) : assert(dashLength > 0.0, 'dashLength must be > 0.0'), + assert(dashGapLength > 0.0, 'dashGapLength must be > 0.0'), + _dashLength = dashLength, + _remainingDashLength = dashLength, + _remainingDashGapLength = dashGapLength, + _previousWasDash = false, + extractedPathLength = 0.0; + + bool get addDashNext { + if (!_previousWasDash || _remainingDashLength != _dashLength) { + return true; + } + return false; + } + + void addDash(ui.PathMetric metric, double dashLength) { + // Calculate lengths (actual + available) + final end = _calculateLength(metric, _remainingDashLength); + final availableEnd = _calculateLength(metric, dashLength); + // Add path + final pathSegment = metric.extractPath(extractedPathLength, end); + path.addPath(pathSegment, Offset.zero); + // Update + final delta = _remainingDashLength - (end - extractedPathLength); + _remainingDashLength = _updateRemainingLength( + delta: delta, + end: end, + availableEnd: availableEnd, + initialLength: dashLength, + ); + extractedPathLength = end; + _previousWasDash = true; + } + + void addDashGap(ui.PathMetric metric, double dashGapLength) { + // Calculate lengths (actual + available) + final end = _calculateLength(metric, _remainingDashGapLength); + final availableEnd = _calculateLength(metric, dashGapLength); + // Move path's end point + ui.Tangent tangent = metric.getTangentForOffset(end)!; + path.moveTo(tangent.position.dx, tangent.position.dy); + // Update + final delta = end - extractedPathLength; + _remainingDashGapLength = _updateRemainingLength( + delta: delta, + end: end, + availableEnd: availableEnd, + initialLength: dashGapLength, + ); + extractedPathLength = end; + _previousWasDash = false; + } + + double _calculateLength(ui.PathMetric metric, double addedLength) { + return math.min(extractedPathLength + addedLength, metric.length); + } + + double _updateRemainingLength({ + required double delta, + required double end, + required double availableEnd, + required double initialLength, + }) { + return (delta > 0 && availableEnd == end) ? delta : initialLength; + } +} diff --git a/lib/widgets/common/fx/highlight_decoration.dart b/lib/widgets/common/fx/highlight_decoration.dart new file mode 100644 index 0000000..f3a323a --- /dev/null +++ b/lib/widgets/common/fx/highlight_decoration.dart @@ -0,0 +1,31 @@ +import 'package:flutter/material.dart'; + +class HighlightDecoration extends Decoration { + final Color color; + + const HighlightDecoration({required this.color}); + + @override + BoxPainter createBoxPainter([VoidCallback? onChanged]) { + return _HighlightDecorationPainter(this, onChanged); + } +} + +class _HighlightDecorationPainter extends BoxPainter { + final HighlightDecoration decoration; + + const _HighlightDecorationPainter(this.decoration, VoidCallback? onChanged) : super(onChanged); + + @override + void paint(Canvas canvas, Offset offset, ImageConfiguration configuration) { + final size = configuration.size; + if (size == null) return; + + final confHeight = size.height; + final paintHeight = confHeight * .32; + final rect = Rect.fromLTWH(offset.dx, offset.dy + size.height * .58, size.width, paintHeight); + final rrect = RRect.fromRectAndRadius(rect, Radius.circular(paintHeight)); + final paint = Paint()..color = decoration.color; + canvas.drawRRect(rrect, paint); + } +} diff --git a/lib/widgets/common/fx/sweeper.dart b/lib/widgets/common/fx/sweeper.dart new file mode 100644 index 0000000..43e64d2 --- /dev/null +++ b/lib/widgets/common/fx/sweeper.dart @@ -0,0 +1,157 @@ +import 'dart:async'; +import 'dart:math'; + +import 'package:aves/theme/durations.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; + +class Sweeper extends StatefulWidget { + final WidgetBuilder builder; + final double startAngle; + final double sweepAngle; + final Curve curve; + final ValueNotifier<bool> toggledNotifier; + final bool centerSweep; + final VoidCallback? onSweepEnd; + + const Sweeper({ + super.key, + required this.builder, + this.startAngle = -pi / 2, + this.sweepAngle = pi / 4, + this.curve = Curves.easeInOutCubic, + required this.toggledNotifier, + this.centerSweep = true, + this.onSweepEnd, + }); + + @override + State<Sweeper> createState() => _SweeperState(); +} + +class _SweeperState extends State<Sweeper> with SingleTickerProviderStateMixin { + late AnimationController _angleAnimationController; + late CurvedAnimation _angleAnimation; + late Animation<double> _angle; + bool _isAppearing = false; + + bool get isToggled => widget.toggledNotifier.value; + + @override + void initState() { + super.initState(); + _angleAnimationController = AnimationController( + duration: ADurations.sweepingAnimation, + vsync: this, + ); + final startAngle = widget.startAngle; + final sweepAngle = widget.sweepAngle; + final centerSweep = widget.centerSweep; + _angleAnimation = CurvedAnimation( + parent: _angleAnimationController, + curve: widget.curve, + ); + _angle = Tween( + begin: startAngle - sweepAngle * (centerSweep ? .5 : 0), + end: startAngle + pi * 2 - sweepAngle * (centerSweep ? .5 : 1), + ).animate(_angleAnimation); + _angleAnimationController.addStatusListener(_onAnimationStatusChanged); + _registerWidget(widget); + } + + @override + void didUpdateWidget(covariant Sweeper oldWidget) { + super.didUpdateWidget(oldWidget); + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + + @override + void dispose() { + _angleAnimation.dispose(); + _angleAnimationController.dispose(); + _unregisterWidget(widget); + super.dispose(); + } + + void _registerWidget(Sweeper widget) { + widget.toggledNotifier.addListener(_onToggle); + } + + void _unregisterWidget(Sweeper widget) { + widget.toggledNotifier.removeListener(_onToggle); + } + + @override + Widget build(BuildContext context) { + return IgnorePointer( + child: AnimatedOpacity( + opacity: isToggled && (_isAppearing || _angleAnimationController.status == AnimationStatus.forward) ? 1 : 0, + duration: ADurations.sweeperOpacityAnimation, + child: ValueListenableBuilder<double>( + valueListenable: _angleAnimationController, + builder: (context, value, child) { + return ClipPath( + clipper: _SweepClipPath( + startAngle: _angle.value, + sweepAngle: widget.sweepAngle, + ), + child: widget.builder(context), + ); + }), + ), + ); + } + + void _onAnimationStatusChanged(AnimationStatus status) { + setState(() {}); + if (status.isCompleted) { + widget.onSweepEnd?.call(); + } + } + + Future<void> _onToggle() async { + if (isToggled) { + _isAppearing = true; + setState(() {}); + await Future.delayed(ADurations.sweeperOpacityAnimation * timeDilation); + _isAppearing = false; + if (!mounted) return; + _angleAnimationController.reset(); + unawaited(_angleAnimationController.forward()); + } + if (!mounted) return; + setState(() {}); + } +} + +class _SweepClipPath extends CustomClipper<Path> { + final double startAngle; + final double sweepAngle; + + const _SweepClipPath({required this.startAngle, required this.sweepAngle}); + + @override + Path getClip(Size size) { + final width = size.width; + final height = size.height; + final centerX = width / 2; + final centerY = height / 2; + final diagonal = sqrt(width * width + height * height); + return Path() + ..moveTo(centerX, centerY) + ..addArc( + Rect.fromCenter( + center: Offset(centerX, centerY), + width: diagonal, + height: diagonal, + ), + startAngle, + sweepAngle, + ) + ..lineTo(centerX, centerY); + } + + @override + bool shouldReclip(covariant CustomClipper<Path> oldClipper) => true; +} diff --git a/lib/widgets/common/fx/transition_image.dart b/lib/widgets/common/fx/transition_image.dart new file mode 100644 index 0000000..044b708 --- /dev/null +++ b/lib/widgets/common/fx/transition_image.dart @@ -0,0 +1,246 @@ +import 'dart:ui' as ui; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; + +// adapted from Flutter `_ImageState` in `/widgets/image.dart` +// and `DecorationImagePainter` in `/painting/decoration_image.dart` +// to transition between 2 different fits during hero animation: +// - BoxFit.cover at t=0 +// - BoxFit.contain at t=1 + +class TransitionImage extends StatefulWidget { + final ImageProvider image; + final ValueListenable<double> animation; + final BoxFit thumbnailFit, viewerFit; + final Color? background; + + const TransitionImage({ + super.key, + required this.image, + required this.animation, + required this.thumbnailFit, + required this.viewerFit, + this.background, + }); + + @override + State<TransitionImage> createState() => _TransitionImageState(); +} + +class _TransitionImageState extends State<TransitionImage> with WidgetsBindingObserver { + ImageStream? _imageStream; + ImageInfo? _imageInfo; + bool _isListeningToStream = false; + bool _wasSynchronouslyLoaded = false; + late DisposableBuildContext<State<TransitionImage>> _scrollAwareContext; + ImageStreamCompleterHandle? _completerHandle; + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addObserver(this); + _scrollAwareContext = DisposableBuildContext<State<TransitionImage>>(this); + } + + @override + void dispose() { + assert(_imageStream != null); + WidgetsBinding.instance.removeObserver(this); + _stopListeningToStream(); + _completerHandle?.dispose(); + _scrollAwareContext.dispose(); + _replaceImage(info: null); + super.dispose(); + } + + @override + void didChangeDependencies() { + _resolveImage(); + + if (TickerMode.of(context)) { + _listenToStream(); + } else { + _stopListeningToStream(keepStreamAlive: true); + } + + super.didChangeDependencies(); + } + + @override + void didUpdateWidget(TransitionImage oldWidget) { + super.didUpdateWidget(oldWidget); + if (widget.image != oldWidget.image) { + _resolveImage(); + } + } + + @override + void reassemble() { + _resolveImage(); // in case the image cache was flushed + super.reassemble(); + } + + void _resolveImage() { + final ScrollAwareImageProvider provider = ScrollAwareImageProvider<Object>( + context: _scrollAwareContext, + imageProvider: widget.image, + ); + final ImageStream newStream = provider.resolve(createLocalImageConfiguration(context)); + _updateSourceStream(newStream); + } + + ImageStreamListener? _imageStreamListener; + + ImageStreamListener _getListener({bool recreateListener = false}) { + if (_imageStreamListener == null || recreateListener) { + _imageStreamListener = ImageStreamListener(_handleImageFrame); + } + return _imageStreamListener!; + } + + void _handleImageFrame(ImageInfo imageInfo, bool synchronousCall) { + setState(() { + _replaceImage(info: imageInfo); + _wasSynchronouslyLoaded = _wasSynchronouslyLoaded | synchronousCall; + }); + } + + void _replaceImage({required ImageInfo? info}) { + final ImageInfo? oldImageInfo = _imageInfo; + SchedulerBinding.instance.addPostFrameCallback((_) => oldImageInfo?.dispose()); + _imageInfo = info; + } + + // Updates _imageStream to newStream, and moves the stream listener + // registration from the old stream to the new stream (if a listener was + // registered). + void _updateSourceStream(ImageStream newStream) { + if (_imageStream?.key == newStream.key) { + return; + } + + if (_isListeningToStream) { + _imageStream!.removeListener(_getListener()); + } + + setState(() { + _replaceImage(info: null); + _wasSynchronouslyLoaded = false; + }); + + _imageStream = newStream; + if (_isListeningToStream) { + _imageStream!.addListener(_getListener()); + } + } + + void _listenToStream() { + if (_isListeningToStream) { + return; + } + + _imageStream!.addListener(_getListener()); + _completerHandle?.dispose(); + _completerHandle = null; + + _isListeningToStream = true; + } + + /// Stops listening to the image stream, if this state object has attached a + /// listener. + /// + /// If the listener from this state is the last listener on the stream, the + /// stream will be disposed. To keep the stream alive, set `keepStreamAlive` + /// to true, which create [ImageStreamCompleterHandle] to keep the completer + /// alive and is compatible with the [TickerMode] being off. + void _stopListeningToStream({bool keepStreamAlive = false}) { + if (!_isListeningToStream) { + return; + } + + if (keepStreamAlive && _completerHandle == null && _imageStream?.completer != null) { + _completerHandle = _imageStream!.completer!.keepAlive(); + } + + _imageStream!.removeListener(_getListener()); + _isListeningToStream = false; + } + + @override + Widget build(BuildContext context) { + return ValueListenableBuilder<double>( + valueListenable: widget.animation, + builder: (context, t, child) => CustomPaint( + painter: _TransitionImagePainter( + image: _imageInfo?.image, + scale: _imageInfo?.scale ?? 1.0, + t: t, + thumbnailFit: widget.thumbnailFit, + viewerFit: widget.viewerFit, + background: widget.background, + ), + ), + ); + } +} + +class _TransitionImagePainter extends CustomPainter { + final ui.Image? image; + final double scale, t; + final Color? background; + final BoxFit thumbnailFit, viewerFit; + + static final _paint = Paint() + ..isAntiAlias = false + ..filterQuality = FilterQuality.low; + static const _alignment = Alignment.center; + + const _TransitionImagePainter({ + required this.image, + required this.scale, + required this.t, + required this.thumbnailFit, + required this.viewerFit, + required this.background, + }); + + @override + void paint(Canvas canvas, Size size) { + final _image = image; + if (_image == null) return; + + if (size.isEmpty) { + return; + } + + final outputSize = size; + final inputSize = Size(_image.width.toDouble(), _image.height.toDouble()); + + final thumbnailSizes = applyBoxFit(thumbnailFit, inputSize / scale, size); + final viewerSizes = applyBoxFit(viewerFit, inputSize / scale, size); + final sourceSize = Size.lerp(thumbnailSizes.source, viewerSizes.source, t)! * scale; + final destinationSize = Size.lerp(thumbnailSizes.destination, viewerSizes.destination, t)!; + + final halfWidthDelta = (outputSize.width - destinationSize.width) / 2.0; + final halfHeightDelta = (outputSize.height - destinationSize.height) / 2.0; + final dx = halfWidthDelta + _alignment.x * halfWidthDelta; + final dy = halfHeightDelta + _alignment.y * halfHeightDelta; + final destinationPosition = Offset(dx, dy); + + final destinationRect = destinationPosition & destinationSize; + final sourceRect = _alignment.inscribe( + sourceSize, + Offset.zero & inputSize, + ); + if (background != null) { + // deflate to avoid background artifact around opaque image + canvas.drawRect(destinationRect.deflate(1), Paint()..color = background!); + } + canvas.drawImageRect(_image, sourceRect, destinationRect, _paint); + } + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => true; +} diff --git a/lib/widgets/common/fx/transitions.dart b/lib/widgets/common/fx/transitions.dart new file mode 100644 index 0000000..b4b7f16 --- /dev/null +++ b/lib/widgets/common/fx/transitions.dart @@ -0,0 +1,14 @@ +import 'package:flutter/widgets.dart'; + +class AvesTransitions { + static Widget formTransitionBuilder(Widget child, Animation<double> animation) { + return FadeTransition( + opacity: animation, + child: SizeTransition( + sizeFactor: animation, + axisAlignment: -1, + child: child, + ), + ); + } +} diff --git a/lib/widgets/common/grid/draggable_thumb_label.dart b/lib/widgets/common/grid/draggable_thumb_label.dart new file mode 100644 index 0000000..0645597 --- /dev/null +++ b/lib/widgets/common/grid/draggable_thumb_label.dart @@ -0,0 +1,88 @@ +import 'package:aves/theme/format.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/grid/sections/list_layout.dart'; +import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; +import 'package:provider/provider.dart'; + +class DraggableCrumbLabel extends StatelessWidget { + final String label; + + const DraggableCrumbLabel({ + super.key, + required this.label, + }); + + @override + Widget build(BuildContext context) { + return ConstrainedBox( + constraints: const BoxConstraints(maxWidth: _crumbLabelMaxWidth), + child: Padding( + padding: _padding, + child: _buildText(label, isCrumb: true), + ), + ); + } +} + +class DraggableThumbLabel<T> extends StatelessWidget { + final double offsetY; + final List<String> Function(BuildContext context, T item) lineBuilder; + + const DraggableThumbLabel({ + super.key, + required this.offsetY, + required this.lineBuilder, + }); + + @override + Widget build(BuildContext context) { + final sll = context.read<SectionedListLayout<T>>(); + final sectionLayout = sll.getSectionAt(offsetY); + if (sectionLayout == null) return const SizedBox(); + + final item = sll.getItemAt(Offset(0, offsetY)) ?? sll.sections[sectionLayout.sectionKey]!.first; + + final lines = lineBuilder(context, item); + if (lines.isEmpty) return const SizedBox(); + + return ConstrainedBox( + constraints: const BoxConstraints(maxWidth: _thumbLabelMaxWidth), + child: Padding( + padding: _padding, + child: lines.length > 1 + ? Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.end, + children: lines.map((v) => _buildText(v, isCrumb: false)).toList(), + ) + : _buildText(lines.first, isCrumb: false), + ), + ); + } + + static String formatMonthThumbLabel(BuildContext context, DateTime? date) { + if (date == null) return context.l10n.sectionUnknown; + return DateFormat.yMMM(context.locale).format(date); + } + + static String formatDayThumbLabel(BuildContext context, DateTime? date) { + if (date == null) return context.l10n.sectionUnknown; + return formatDay(date, context.locale); + } +} + +const double _crumbLabelMaxWidth = 96; +const double _thumbLabelMaxWidth = 144; +const EdgeInsets _padding = EdgeInsets.symmetric(vertical: 4, horizontal: 8); + +Widget _buildText(String text, {required bool isCrumb}) => Text( + text, + style: TextStyle( + color: Colors.black, + fontSize: isCrumb ? 10 : 14, + ), + softWrap: false, + overflow: TextOverflow.fade, + maxLines: 1, + ); diff --git a/lib/widgets/common/grid/header.dart b/lib/widgets/common/grid/header.dart new file mode 100644 index 0000000..ed70d0e --- /dev/null +++ b/lib/widgets/common/grid/header.dart @@ -0,0 +1,289 @@ +import 'package:aves/model/selection.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/section_keys.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/theme/styles.dart'; +import 'package:aves/widgets/common/basic/gestures/gesture_detector.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/grid/sections/list_layout.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:provider/provider.dart'; + +class SectionHeader<T> extends StatelessWidget { + final SectionKey sectionKey; + final Widget? leading, trailing; + final String title; + final bool selectable; + + const SectionHeader({ + super.key, + required this.sectionKey, + this.leading, + required this.title, + this.trailing, + this.selectable = true, + }); + + static const leadingSize = Size.square(32); + static const widgetSpanAlignmentMargin = EdgeInsetsDirectional.only(bottom: 4); + static final leadingMargin = const EdgeInsetsDirectional.only(end: 8) + widgetSpanAlignmentMargin; + static final trailingMargin = const EdgeInsetsDirectional.only(start: 8) + widgetSpanAlignmentMargin; + static const margin = EdgeInsets.symmetric(vertical: 0, horizontal: 8); + static const padding = EdgeInsets.symmetric(vertical: 16, horizontal: 8); + static const widgetSpanAlignment = PlaceholderAlignment.middle; + + @override + Widget build(BuildContext context) { + final onTap = selectable ? () => _toggleSectionSelection(context) : null; + + final theme = Theme.of(context); + + Widget child = Container( + padding: padding, + constraints: BoxConstraints(minHeight: leadingSize.height), + child: AGestureDetector( + onTap: onTap, + onLongPress: selectable + ? Feedback.wrapForLongPress(() { + final selection = context.read<Selection<T>>(); + if (selection.isSelecting) { + _toggleSectionSelection(context); + } else { + selection.select(); + selection.addToSelection(_getSectionEntries(context)); + } + }, context) + : null, + longPressTimeout: settings.longPressTimeout, + child: Text.rich( + TextSpan( + children: [ + WidgetSpan( + alignment: widgetSpanAlignment, + child: Theme( + data: theme.copyWith( + iconTheme: theme.iconTheme.copyWith( + color: theme.colorScheme.onSurface, + ), + ), + child: _SectionSelectableLeading<T>( + selectable: selectable, + sectionKey: sectionKey, + browsingBuilder: leading != null + ? (context) => Container( + width: leadingSize.width, + height: leadingSize.height, + margin: leadingMargin, + child: leading, + ) + : null, + onPressed: onTap, + ), + ), + ), + TextSpan( + text: title, + style: _headerTextStyle(context), + ), + if (trailing != null) + WidgetSpan( + alignment: widgetSpanAlignment, + child: Container( + margin: trailingMargin, + child: trailing, + ), + ), + ], + ), + ), + ), + ); + if (settings.useTvLayout) { + // prevent ink response when tapping the header does nothing, + // because otherwise Play Store reviewers think it is broken navigation + child = context.select<Selection<T>, bool>((v) => v.isSelecting) + ? InkWell( + onTap: onTap, + borderRadius: const BorderRadius.all(Radius.circular(123)), + child: child, + ) + : Focus(child: child); + } + return Container( + alignment: AlignmentDirectional.centerStart, + margin: margin, + child: child, + ); + } + + List<T> _getSectionEntries(BuildContext context) => context.read<SectionedListLayout<T>>().sections[sectionKey] ?? []; + + void _toggleSectionSelection(BuildContext context) { + final sectionEntries = _getSectionEntries(context); + final selection = context.read<Selection<T>>(); + final isSelected = selection.isSelected(sectionEntries); + if (isSelected) { + selection.removeFromSelection(sectionEntries); + } else { + selection.addToSelection(sectionEntries); + } + } + + // TODO TLAD [perf] cache header extent computation? + static double getPreferredHeight({ + required BuildContext context, + required double maxWidth, + required String title, + bool hasLeading = false, + bool hasTrailing = false, + }) { + final textScaler = MediaQuery.textScalerOf(context); + final leadingFontSize = leadingSize.height; + final textScaleFactor = textScaler.scale(leadingFontSize) / leadingFontSize; + final maxContentWidth = maxWidth - (SectionHeader.padding.horizontal + SectionHeader.margin.horizontal); + final paragraph = RenderParagraph( + TextSpan( + children: [ + // as of Flutter v3.7.7, `RenderParagraph` fails to lay out `WidgetSpan` offscreen + // so we use a hair space times a magic number to match width + TextSpan( + // 23 hair spaces match a width of 40.0 + text: '\u200A' * (hasLeading ? 23 : 1), + // force a higher first line to match leading icon/selector dimension + style: TextStyle(height: 2.3 * textScaleFactor), + ), + if (hasTrailing) TextSpan(text: '\u200A' * 17), + TextSpan( + text: title, + style: _headerTextStyle(context), + ), + ], + ), + textDirection: TextDirection.ltr, + textScaler: textScaler, + )..layout(BoxConstraints(maxWidth: maxContentWidth), parentUsesSize: true); + final height = paragraph.getMaxIntrinsicHeight(maxContentWidth); + paragraph.dispose(); + return height; + } + + static TextStyle _headerTextStyle(BuildContext context) { + // specify `height` for accurate paragraph height measurement + final defaultTextHeight = DefaultTextStyle.of(context).style.height; + return AStyles.unknownTitleText.copyWith(height: defaultTextHeight); + } +} + +class _SectionSelectableLeading<T> extends StatelessWidget { + final bool selectable; + final SectionKey sectionKey; + final WidgetBuilder? browsingBuilder; + final VoidCallback? onPressed; + + const _SectionSelectableLeading({ + super.key, + this.selectable = true, + required this.sectionKey, + required this.browsingBuilder, + required this.onPressed, + }); + + @override + Widget build(BuildContext context) { + if (!selectable) return _buildBrowsing(context); + + final duration = context.select<DurationsData, Duration>((v) => v.formTransition); + final isSelecting = context.select<Selection<T>, bool>((selection) => selection.isSelecting); + final Widget child = isSelecting + ? _SectionSelectingLeading<T>( + sectionKey: sectionKey, + onPressed: onPressed, + ) + : _buildBrowsing(context); + + return FocusTraversalGroup( + descendantsAreFocusable: false, + descendantsAreTraversable: false, + child: AnimatedSwitcher( + duration: duration, + switchInCurve: Curves.easeInOut, + switchOutCurve: Curves.easeInOut, + transitionBuilder: (child, animation) { + Widget transition = ScaleTransition( + scale: animation, + child: child, + ); + if (browsingBuilder == null) { + // when switching with a header that has no icon, + // we also transition the size for a smooth push to the text + transition = SizeTransition( + axis: Axis.horizontal, + sizeFactor: animation, + child: transition, + ); + } + return transition; + }, + child: child, + ), + ); + } + + Widget _buildBrowsing(BuildContext context) => browsingBuilder?.call(context) ?? SizedBox(height: SectionHeader.leadingSize.height + SectionHeader.widgetSpanAlignmentMargin.vertical); +} + +class _SectionSelectingLeading<T> extends StatelessWidget { + final SectionKey sectionKey; + final VoidCallback? onPressed; + + const _SectionSelectingLeading({ + super.key, + required this.sectionKey, + required this.onPressed, + }); + + @override + Widget build(BuildContext context) { + final duration = context.select<DurationsData, Duration>((v) => v.formTransition); + final sectionEntries = context.watch<SectionedListLayout<T>>().sections[sectionKey] ?? []; + final selection = context.watch<Selection<T>>(); + final isSelected = selection.isSelected(sectionEntries); + return AnimatedSwitcher( + duration: duration, + switchInCurve: Curves.easeOutBack, + switchOutCurve: Curves.easeOutBack, + transitionBuilder: (child, animation) => ScaleTransition( + scale: animation, + child: child, + ), + child: TooltipTheme( + key: ValueKey(isSelected), + data: TooltipTheme.of(context).copyWith( + preferBelow: false, + ), + child: Container( + width: SectionHeader.leadingSize.width, + height: SectionHeader.leadingSize.height, + margin: SectionHeader.leadingMargin, + child: Theme( + data: Theme.of(context).copyWith( + materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, + ), + child: IconButton( + iconSize: 26, + onPressed: onPressed, + tooltip: isSelected ? context.l10n.collectionDeselectSectionTooltip : context.l10n.collectionSelectSectionTooltip, + style: ButtonStyle( + padding: WidgetStateProperty.all<EdgeInsetsGeometry>(EdgeInsets.zero), + minimumSize: WidgetStateProperty.all<Size>(SectionHeader.leadingSize), + ), + icon: Icon(isSelected ? AIcons.selected : AIcons.unselected), + ), + ), + ), + ), + ); + } +} diff --git a/lib/widgets/common/grid/item_tracker.dart b/lib/widgets/common/grid/item_tracker.dart new file mode 100644 index 0000000..ea8aadf --- /dev/null +++ b/lib/widgets/common/grid/item_tracker.dart @@ -0,0 +1,170 @@ +import 'dart:async'; +import 'dart:math'; + +import 'package:aves/model/highlight.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/widgets/common/grid/sections/list_layout.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class GridItemTracker<T> extends StatefulWidget { + final GlobalKey scrollableKey; + final ValueNotifier<double> appBarHeightNotifier; + final TileLayout tileLayout; + final ScrollController scrollController; + final Widget child; + + const GridItemTracker({ + super.key, + required this.scrollableKey, + required this.appBarHeightNotifier, + required this.tileLayout, + required this.scrollController, + required this.child, + }); + + @override + State<GridItemTracker<T>> createState() => _GridItemTrackerState<T>(); +} + +class _GridItemTrackerState<T> extends State<GridItemTracker<T>> with WidgetsBindingObserver { + ValueNotifier<double> get appBarHeightNotifier => widget.appBarHeightNotifier; + + ScrollController get scrollController => widget.scrollController; + + @override + Widget build(BuildContext context) { + return widget.child; + } + + Size get scrollableSize { + final scrollableContext = widget.scrollableKey.currentContext!; + return (scrollableContext.findRenderObject() as RenderBox).size; + } + + final Set<StreamSubscription> _subscriptions = {}; + + // grid section metrics before the app is laid out with the new orientation + late SectionedListLayout<T> _lastSectionedListLayout; + late Size _lastScrollableSize; + Orientation _lastOrientation = Orientation.portrait; + + @override + void initState() { + super.initState(); + final highlightInfo = context.read<HighlightInfo>(); + _subscriptions.add(highlightInfo.eventBus.on<TrackEvent<T>>().listen(_trackItem)); + WidgetsBinding.instance.addObserver(this); + _saveLayoutMetrics(); + } + + @override + void didUpdateWidget(covariant GridItemTracker<T> oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.tileLayout != widget.tileLayout) { + _onLayoutChanged(); + } + _saveLayoutMetrics(); + } + + @override + void didChangeMetrics() { + // the order of `WidgetsBindingObserver` metrics change notification is unreliable + // w.r.t. the `View` update, and consequentially to this widget update: + // `WidgetsBindingObserver` is notified mostly before, sometimes after, the widget update + final size = View.of(context).physicalSize; + final orientation = size.width > size.height ? Orientation.landscape : Orientation.portrait; + if (_lastOrientation != orientation) { + _lastOrientation = orientation; + _onLayoutChanged(); + _saveLayoutMetrics(); + } + } + + @override + void dispose() { + WidgetsBinding.instance.removeObserver(this); + _subscriptions + ..forEach((sub) => sub.cancel()) + ..clear(); + super.dispose(); + } + + // about scrolling & offset retrieval: + // `Scrollable.ensureVisible` only works on already rendered objects + // `RenderViewport.showOnScreen` can find any `RenderSliver`, but not always a `RenderMetadata` + // `RenderViewport.scrollOffsetOf` is a good alternative + Future<void> _trackItem(TrackEvent event) async { + final sectionedListLayout = context.read<SectionedListLayout<T>>(); + final tileRect = sectionedListLayout.getTileRect(event.item); + if (tileRect == null) return; + + final viewportRect = Offset(0, scrollController.offset) & scrollableSize; + final itemVisibility = max(0, tileRect.intersect(viewportRect).height) / tileRect.height; + if (!event.predicate(itemVisibility)) return; + + double scrollOffset = tileRect.top + (tileRect.height - scrollableSize.height) * ((event.alignment.y + 1) / 2); + // most of the time the app bar will be scrolled away after scaling, + // so we compensate for it to center the focal point thumbnail + scrollOffset += appBarHeightNotifier.value; + scrollOffset = scrollOffset.clamp(0, scrollController.position.maxScrollExtent); + + if (scrollOffset > 0) { + if (event.animate) { + await scrollController.animateTo( + scrollOffset, + duration: Duration(milliseconds: (scrollOffset / 2).round().clamp(ADurations.highlightScrollAnimationMinMillis, ADurations.highlightScrollAnimationMaxMillis)), + curve: Curves.easeInOutCubic, + ); + } else { + scrollController.jumpTo(scrollOffset); + await Future.delayed(ADurations.highlightJumpDelay); + } + } + + final highlightItem = event.highlightItem; + if (highlightItem != null) { + context.read<HighlightInfo>().set(highlightItem); + } + } + + Future<void> _saveLayoutMetrics() async { + // use a delay to obtain current layout metrics + // so that we can handle window orientation change with the previous metrics, + // regardless of the `View`/`WidgetsBindingObserver` order uncertainty + await Future.delayed(const Duration(milliseconds: 500)); + if (!mounted) return; + _lastSectionedListLayout = context.read<SectionedListLayout<T>>(); + _lastScrollableSize = scrollableSize; + } + + void _onLayoutChanged() { + if (scrollController.positions.length != 1) return; + + // do not track when view shows top edge + if (scrollController.offset == 0) return; + + final layout = _lastSectionedListLayout; + final halfSize = _lastScrollableSize / 2; + final center = Offset( + halfSize.width, + halfSize.height + scrollController.offset - appBarHeightNotifier.value, + ); + var pivotItem = layout.getItemAt(center) ?? layout.getItemAt(Offset(0, center.dy)); + if (pivotItem == null) { + final pivotSectionKey = layout.getSectionAt(center.dy)?.sectionKey; + if (pivotSectionKey != null) { + pivotItem = layout.sections[pivotSectionKey]?.firstOrNull; + } + } + + if (pivotItem != null) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; + context.read<HighlightInfo>().trackItem(pivotItem, animate: false); + }); + } + } +} diff --git a/lib/widgets/common/grid/overlay.dart b/lib/widgets/common/grid/overlay.dart new file mode 100644 index 0000000..8d0149d --- /dev/null +++ b/lib/widgets/common/grid/overlay.dart @@ -0,0 +1,58 @@ +import 'package:aves/model/selection.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/identity/aves_icons.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class GridItemSelectionOverlay<T> extends StatelessWidget { + final T item; + final BorderRadius? borderRadius; + final EdgeInsets? padding; + + const GridItemSelectionOverlay({ + super.key, + required this.item, + this.borderRadius, + this.padding, + }); + + @override + Widget build(BuildContext context) { + final duration = context.select<DurationsData, Duration>((v) => v.formTransition); + final isSelecting = context.select<Selection<T>, bool>((selection) => selection.isSelecting); + return AnimatedSwitcher( + duration: duration, + child: isSelecting + ? Selector<Selection<T>, bool>( + selector: (context, selection) => selection.isSelected({item}), + builder: (context, isSelected, child) { + return AnimatedContainer( + alignment: AlignmentDirectional.topEnd, + padding: padding, + decoration: BoxDecoration( + color: isSelected ? Theme.of(context).colorScheme.primary.withValues(alpha: .6) : Colors.transparent, + borderRadius: borderRadius, + ), + duration: duration, + child: AnimatedSwitcher( + duration: duration, + switchInCurve: Curves.easeOutBack, + switchOutCurve: Curves.easeOutBack, + transitionBuilder: (child, animation) => ScaleTransition( + scale: animation, + child: child, + ), + child: OverlayIcon( + key: ValueKey(isSelected), + icon: isSelected ? AIcons.selected : AIcons.unselected, + margin: EdgeInsets.zero, + ), + ), + ); + }, + ) + : const SizedBox(), + ); + } +} diff --git a/lib/widgets/common/grid/scaling.dart b/lib/widgets/common/grid/scaling.dart new file mode 100644 index 0000000..fe29b4b --- /dev/null +++ b/lib/widgets/common/grid/scaling.dart @@ -0,0 +1,248 @@ +import 'package:aves/model/highlight.dart'; +import 'package:aves/widgets/common/behaviour/eager_scale_gesture_recognizer.dart'; +import 'package:aves/widgets/common/grid/sections/fixed/scale_overlay.dart'; +import 'package:aves/widgets/common/grid/sections/mosaic/scale_overlay.dart'; +import 'package:aves/widgets/common/grid/sections/section_layout_builder.dart'; +import 'package:aves/widgets/common/grid/theme.dart'; +import 'package:aves/widgets/common/providers/tile_extent_controller_provider.dart'; +import 'package:aves/widgets/common/tile_extent_controller.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:provider/provider.dart'; + +// metadata to identify entry from RenderObject hit test during collection scaling +class ScalerMetadata<T> { + final T item; + + const ScalerMetadata(this.item); +} + +class GridScaleGestureDetector<T> extends StatefulWidget { + final GlobalKey scrollableKey; + final TileLayout tileLayout; + final double Function(double width) heightForWidth; + final Widget Function(Offset center, Size tileSize, Widget child) gridBuilder; + final TileBuilder<T> scaledItemBuilder; + final MosaicItemBuilder mosaicItemBuilder; + final Object Function(T item)? highlightItem; + final Widget child; + + const GridScaleGestureDetector({ + super.key, + required this.scrollableKey, + required this.tileLayout, + required this.heightForWidth, + required this.gridBuilder, + required this.scaledItemBuilder, + required this.mosaicItemBuilder, + this.highlightItem, + required this.child, + }); + + @override + State<GridScaleGestureDetector<T>> createState() => _GridScaleGestureDetectorState<T>(); +} + +class _GridScaleGestureDetectorState<T> extends State<GridScaleGestureDetector<T>> { + Size? _startSize; + double? _extentMin, _extentMax; + bool _applyingScale = false; + ValueNotifier<Size>? _scaledSizeNotifier; + OverlayEntry? _overlayEntry; + ScalerMetadata<T>? _metadata; + + TileLayout get tileLayout => widget.tileLayout; + + @override + void dispose() { + _scaledSizeNotifier?.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final gestureSettings = MediaQuery.gestureSettingsOf(context); + + final child = GestureDetector( + // Horizontal/vertical drag gestures are interpreted as scaling + // if they are not handled by `onHorizontalDragStart`/`onVerticalDragStart` + // at the scaling `GestureDetector` level, or handled beforehand down the widget tree. + // Setting `onHorizontalDragStart`, `onVerticalDragStart`, and `onScaleStart` + // all at once is not allowed, so we use another `GestureDetector` for that. + onVerticalDragStart: (details) {}, + onHorizontalDragStart: (details) {}, + child: widget.child, + ); + + // as of Flutter v2.5.3, `ScaleGestureRecognizer` does not work well + // when combined with the `VerticalDragGestureRecognizer` inside a `GridView`, + // so it is modified to eagerly accept the gesture + // when multiple pointers are involved, and take priority over drag gestures. + return RawGestureDetector( + gestures: <Type, GestureRecognizerFactory>{ + EagerScaleGestureRecognizer: GestureRecognizerFactoryWithHandlers<EagerScaleGestureRecognizer>( + () => EagerScaleGestureRecognizer(debugOwner: this), + (instance) { + instance + ..onStart = _onScaleStart + ..onUpdate = _onScaleUpdate + ..onEnd = _onScaleEnd + ..dragStartBehavior = DragStartBehavior.start + ..gestureSettings = gestureSettings; + }, + ), + }, + child: child, + ); + } + + void _onScaleStart(ScaleStartDetails details) { + // the gesture detector wrongly detects a new scaling gesture + // when scaling ends and we apply the new extent, so we prevent this + // until we scaled and scrolled to the tile in the new grid + if (_applyingScale) return; + + final tileExtentController = context.read<TileExtentController>(); + + final scrollableContext = widget.scrollableKey.currentContext!; + final scrollableBox = scrollableContext.findRenderObject() as RenderBox; + final renderMetaData = _getClosestRenderMetadata( + box: scrollableBox, + localFocalPoint: details.localFocalPoint, + spacing: tileExtentController.spacing, + ); + // abort if we cannot find an image to show on overlay + if (renderMetaData == null) return; + final metadata = renderMetaData.metaData; + if (metadata is! ScalerMetadata<T>) return; + _metadata = metadata; + + switch (tileLayout) { + case TileLayout.mosaic: + _startSize = Size.square(tileExtentController.extentNotifier.value); + case TileLayout.grid: + case TileLayout.list: + _startSize = renderMetaData.size; + } + _scaledSizeNotifier = ValueNotifier(_startSize!); + + // not the same as `MediaQuery` metrics, because of screen insets/padding + final scrollViewRect = scrollableBox.localToGlobal(Offset.zero) & scrollableBox.size; + final contentRect = scrollViewRect.deflate(tileExtentController.horizontalPadding); + + _extentMin = tileExtentController.effectiveExtentMin; + _extentMax = tileExtentController.effectiveExtentMax; + + final halfSize = _startSize! / 2; + switch (tileLayout) { + case TileLayout.mosaic: + _overlayEntry = OverlayEntry( + builder: (context) => MosaicScaleOverlay( + contentRect: contentRect, + spacing: tileExtentController.spacing, + extentMax: _extentMax!, + scaledSizeNotifier: _scaledSizeNotifier!, + itemBuilder: widget.mosaicItemBuilder, + ), + ); + case TileLayout.grid: + case TileLayout.list: + final tileCenter = renderMetaData.localToGlobal(Offset(halfSize.width, halfSize.height)); + _overlayEntry = OverlayEntry( + builder: (context) => TileExtentControllerProvider( + controller: tileExtentController, + child: FixedExtentScaleOverlay( + tileLayout: tileLayout, + tileCenter: tileCenter, + contentRect: contentRect, + scaledSizeNotifier: _scaledSizeNotifier!, + gridBuilder: widget.gridBuilder, + builder: (scaledTileSize) => SizedBox.fromSize( + size: scaledTileSize, + child: GridTheme( + extent: tileLayout == TileLayout.grid ? scaledTileSize.width : scaledTileSize.height, + child: widget.scaledItemBuilder(_metadata!.item, scaledTileSize), + ), + ), + ), + ), + ); + } + Overlay.of(scrollableContext).insert(_overlayEntry!); + } + + void _onScaleUpdate(ScaleUpdateDetails details) { + if (_scaledSizeNotifier == null) return; + + final s = details.scale; + switch (tileLayout) { + case TileLayout.mosaic: + case TileLayout.grid: + final scaledWidth = (_startSize!.width * s).clamp(_extentMin!, _extentMax!); + _scaledSizeNotifier!.value = Size(scaledWidth, widget.heightForWidth(scaledWidth)); + case TileLayout.list: + final scaledHeight = (_startSize!.height * s).clamp(_extentMin!, _extentMax!); + _scaledSizeNotifier!.value = Size(_startSize!.width, scaledHeight); + } + } + + void _onScaleEnd(ScaleEndDetails details) { + if (_scaledSizeNotifier == null) return; + + final scaledSize = _scaledSizeNotifier!.value; + _scaledSizeNotifier!.dispose(); + _scaledSizeNotifier = null; + + _overlayEntry + ?..remove() + ..dispose(); + _overlayEntry = null; + + _applyingScale = true; + final tileExtentController = context.read<TileExtentController>(); + final oldExtent = tileExtentController.extentNotifier.value; + // sanitize and update grid layout if necessary + late final double preferredExtent; + switch (tileLayout) { + case TileLayout.mosaic: + case TileLayout.grid: + preferredExtent = scaledSize.width; + case TileLayout.list: + preferredExtent = scaledSize.height; + } + final newExtent = tileExtentController.setUserPreferredExtent(preferredExtent); + if (newExtent == oldExtent) { + _applyingScale = false; + } else { + // scroll to show the focal point thumbnail at its new position + WidgetsBinding.instance.addPostFrameCallback((_) { + final trackItem = _metadata!.item; + final highlightItem = widget.highlightItem?.call(trackItem) ?? trackItem; + context.read<HighlightInfo>().trackItem(trackItem, animate: false, highlightItem: highlightItem); + _applyingScale = false; + }); + } + } + + RenderMetaData? _getClosestRenderMetadata({ + required RenderBox box, + required Offset localFocalPoint, + required double spacing, + }) { + var position = localFocalPoint; + while (position.dx > 0 && position.dy > 0) { + final result = BoxHitTestResult(); + box.hitTest(result, position: position); + + // find `RenderObject`s at the gesture focal point + U? firstOf<U>(BoxHitTestResult result) => result.path.firstWhereOrNull((el) => el.target is U)?.target as U?; + final renderMetaData = firstOf<RenderMetaData>(result); + if (renderMetaData != null) return renderMetaData; + position = position.translate(-spacing, -spacing); + } + return null; + } +} diff --git a/lib/widgets/common/grid/sections/fixed/list_layout.dart b/lib/widgets/common/grid/sections/fixed/list_layout.dart new file mode 100644 index 0000000..162fcc8 --- /dev/null +++ b/lib/widgets/common/grid/sections/fixed/list_layout.dart @@ -0,0 +1,62 @@ +import 'dart:math'; + +import 'package:aves/model/source/section_keys.dart'; +import 'package:aves/widgets/common/grid/sections/list_layout.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; + +class FixedExtentSectionedListLayout<T> extends SectionedListLayout<T> { + final int columnCount; + final double tileWidth, tileHeight; + + const FixedExtentSectionedListLayout({ + required super.sections, + required super.showHeaders, + required this.columnCount, + required this.tileWidth, + required this.tileHeight, + required super.spacing, + required super.horizontalPadding, + required super.sectionLayouts, + }); + + @override + Rect? getTileRect(T item) { + final MapEntry<SectionKey?, List<T>>? section = sections.entries.firstWhereOrNull((kv) => kv.value.contains(item)); + if (section == null) return null; + + final sectionKey = section.key; + final sectionLayout = sectionLayouts.firstWhereOrNull((sl) => sl.sectionKey == sectionKey); + if (sectionLayout == null) return null; + + final sectionItemIndex = section.value.indexOf(item); + final column = sectionItemIndex % columnCount; + final row = (sectionItemIndex / columnCount).floor(); + final listIndex = sectionLayout.firstIndex + 1 + row; + + final left = horizontalPadding + tileWidth * column + spacing * (column - 1); + final top = sectionLayout.indexToLayoutOffset(listIndex); + return Rect.fromLTWH(left, top, tileWidth, tileHeight); + } + + @override + T? getItemAt(Offset position) { + var dy = position.dy; + final sectionLayout = getSectionAt(dy); + if (sectionLayout == null) return null; + + final section = sections[sectionLayout.sectionKey]; + if (section == null) return null; + + dy -= sectionLayout.minOffset + sectionLayout.headerExtent; + if (dy < 0) return null; + + final row = dy ~/ (tileHeight + spacing); + final column = max(0, position.dx - horizontalPadding) ~/ (tileWidth + spacing); + final index = row * columnCount + column; + if (index >= section.length) return null; + + return section[index]; + } +} diff --git a/lib/widgets/common/grid/sections/fixed/row.dart b/lib/widgets/common/grid/sections/fixed/row.dart new file mode 100644 index 0000000..f0f9e1c --- /dev/null +++ b/lib/widgets/common/grid/sections/fixed/row.dart @@ -0,0 +1,162 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; + +class FixedExtentGridRow extends MultiChildRenderObjectWidget { + final double width, height, spacing; + final TextDirection textDirection; + + const FixedExtentGridRow({ + super.key, + required this.width, + required this.height, + required this.spacing, + required this.textDirection, + required super.children, + }); + + @override + RenderObject createRenderObject(BuildContext context) { + return RenderFixedExtentGridRow( + width: width, + height: height, + spacing: spacing, + textDirection: textDirection, + ); + } + + @override + void updateRenderObject(BuildContext context, RenderFixedExtentGridRow renderObject) { + renderObject.width = width; + renderObject.height = height; + renderObject.spacing = spacing; + renderObject.textDirection = textDirection; + } + + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + super.debugFillProperties(properties); + properties.add(DoubleProperty('width', width)); + properties.add(DoubleProperty('height', height)); + properties.add(DoubleProperty('spacing', spacing)); + properties.add(EnumProperty<TextDirection>('textDirection', textDirection)); + } +} + +class _GridRowParentData extends ContainerBoxParentData<RenderBox> {} + +class RenderFixedExtentGridRow extends RenderBox with ContainerRenderObjectMixin<RenderBox, _GridRowParentData>, RenderBoxContainerDefaultsMixin<RenderBox, _GridRowParentData> { + RenderFixedExtentGridRow({ + List<RenderBox>? children, + required double width, + required double height, + required double spacing, + required TextDirection textDirection, + }) : _width = width, + _height = height, + _spacing = spacing, + _textDirection = textDirection { + addAll(children); + } + + double get width => _width; + double _width; + + set width(double value) { + if (_width == value) return; + _width = value; + markNeedsLayout(); + } + + double get height => _height; + double _height; + + set height(double value) { + if (_height == value) return; + _height = value; + markNeedsLayout(); + } + + double get spacing => _spacing; + double _spacing; + + set spacing(double value) { + if (_spacing == value) return; + _spacing = value; + markNeedsLayout(); + } + + TextDirection get textDirection => _textDirection; + TextDirection _textDirection; + + set textDirection(TextDirection value) { + if (_textDirection == value) return; + _textDirection = value; + markNeedsLayout(); + } + + @override + void setupParentData(RenderBox child) { + if (child.parentData is! _GridRowParentData) { + child.parentData = _GridRowParentData(); + } + } + + double get intrinsicWidth => width * childCount + spacing * (childCount - 1); + + @override + double computeMinIntrinsicWidth(double height) => intrinsicWidth; + + @override + double computeMaxIntrinsicWidth(double height) => intrinsicWidth; + + @override + double computeMinIntrinsicHeight(double width) => height; + + @override + double computeMaxIntrinsicHeight(double width) => height; + + @override + void performLayout() { + var child = firstChild; + if (child == null) { + size = constraints.smallest; + return; + } + size = Size(constraints.maxWidth, height); + final childConstraints = BoxConstraints.tight(Size(width, height)); + final flipMainAxis = textDirection == TextDirection.rtl; + var offset = Offset(flipMainAxis ? size.width - width : 0, 0); + final dx = (flipMainAxis ? -1 : 1) * (width + spacing); + while (child != null) { + child.layout(childConstraints, parentUsesSize: false); + final childParentData = child.parentData! as _GridRowParentData; + childParentData.offset = offset; + offset += Offset(dx, 0); + child = childParentData.nextSibling; + } + } + + @override + double? computeDistanceToActualBaseline(TextBaseline baseline) { + return defaultComputeDistanceToHighestActualBaseline(baseline); + } + + @override + bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { + return defaultHitTestChildren(result, position: position); + } + + @override + void paint(PaintingContext context, Offset offset) { + defaultPaint(context, offset); + } + + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + super.debugFillProperties(properties); + properties.add(DoubleProperty('width', width)); + properties.add(DoubleProperty('height', height)); + properties.add(DoubleProperty('spacing', spacing)); + properties.add(EnumProperty<TextDirection>('textDirection', textDirection)); + } +} diff --git a/lib/widgets/common/grid/sections/fixed/scale_grid.dart b/lib/widgets/common/grid/sections/fixed/scale_grid.dart new file mode 100644 index 0000000..c31b6ea --- /dev/null +++ b/lib/widgets/common/grid/sections/fixed/scale_grid.dart @@ -0,0 +1,111 @@ +import 'dart:ui' as ui; + +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; + +class FixedExtentGridPainter extends CustomPainter { + final TileLayout tileLayout; + final Offset tileCenter; + final Size tileSize; + final double spacing, horizontalPadding, borderWidth; + final Radius borderRadius; + final Color color; + final TextDirection textDirection; + + const FixedExtentGridPainter({ + required this.tileLayout, + required this.tileCenter, + required this.tileSize, + required this.spacing, + required this.horizontalPadding, + required this.borderWidth, + required this.borderRadius, + required this.color, + required this.textDirection, + }); + + @override + void paint(Canvas canvas, Size size) { + late final Offset chipCenter; + late final Size chipSize; + late final int deltaColumn; + late final Shader strokeShader; + switch (tileLayout) { + case TileLayout.mosaic: + return; + case TileLayout.grid: + chipCenter = tileCenter; + chipSize = tileSize; + deltaColumn = 2; + strokeShader = ui.Gradient.radial( + tileCenter, + chipSize.shortestSide * 2, + [ + color, + Colors.transparent, + ], + [ + .8, + 1, + ], + ); + case TileLayout.list: + chipSize = Size.square(tileSize.shortestSide); + final chipCenterToEdge = chipSize.width / 2; + chipCenter = Offset(textDirection == TextDirection.rtl ? size.width - (chipCenterToEdge + horizontalPadding) : chipCenterToEdge + horizontalPadding, tileCenter.dy); + deltaColumn = 0; + strokeShader = ui.Gradient.linear( + tileCenter - Offset(0, chipSize.shortestSide * 3), + tileCenter + Offset(0, chipSize.shortestSide * 3), + [ + Colors.transparent, + color, + color, + Colors.transparent, + ], + [ + 0, + .2, + .8, + 1, + ], + ); + } + final strokePaint = Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = borderWidth + ..shader = strokeShader; + final fillPaint = Paint() + ..style = PaintingStyle.fill + ..color = color.withValues(alpha: .25); + + final chipWidth = chipSize.width; + final chipHeight = chipSize.height; + + final deltaX = tileSize.width + spacing; + final deltaY = tileSize.height + spacing; + for (var i = -deltaColumn; i <= deltaColumn; i++) { + final dx = deltaX * i; + for (var j = -2; j <= 2; j++) { + if (i == 0 && j == 0) continue; + final dy = deltaY * j; + final rect = RRect.fromRectAndRadius( + Rect.fromCenter( + center: chipCenter + Offset(dx, dy), + width: chipWidth - borderWidth, + height: chipHeight - borderWidth, + ), + borderRadius, + ); + + if ((i.abs() == 1 && j == 0) || (j.abs() == 1 && i == 0)) { + canvas.drawRRect(rect, fillPaint); + } + canvas.drawRRect(rect, strokePaint); + } + } + } + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => true; +} diff --git a/lib/widgets/common/grid/sections/fixed/scale_overlay.dart b/lib/widgets/common/grid/sections/fixed/scale_overlay.dart new file mode 100644 index 0000000..56be3a9 --- /dev/null +++ b/lib/widgets/common/grid/sections/fixed/scale_overlay.dart @@ -0,0 +1,136 @@ +import 'package:aves/theme/durations.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/extensions/theme.dart'; +import 'package:aves/widgets/common/providers/media_query_data_provider.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:aves_utils/aves_utils.dart'; +import 'package:flutter/material.dart'; + +class FixedExtentScaleOverlay extends StatelessWidget { + final TileLayout tileLayout; + final Offset tileCenter; + final double xMin, xMax; + final ValueNotifier<Size> scaledSizeNotifier; + final Widget Function(Offset center, Size tileSize, Widget child) gridBuilder; + final Widget Function(Size scaledTileSize) builder; + + FixedExtentScaleOverlay({ + super.key, + required this.tileLayout, + required this.tileCenter, + required Rect contentRect, + required this.scaledSizeNotifier, + required this.gridBuilder, + required this.builder, + }) : xMin = contentRect.left, + xMax = contentRect.right; + + @override + Widget build(BuildContext context) { + return MediaQueryDataProvider( + child: IgnorePointer( + child: _OverlayBackground( + gradientCenter: tileLayout == TileLayout.grid ? tileCenter : Offset(context.isRtl ? xMax : xMin, tileCenter.dy), + child: ValueListenableBuilder<Size>( + valueListenable: scaledSizeNotifier, + builder: (context, scaledSize, child) { + final width = scaledSize.width; + final height = scaledSize.height; + // keep scaled thumbnail within the screen + var dx = .0; + if (tileCenter.dx - width / 2 < xMin) { + dx = xMin - (tileCenter.dx - width / 2); + } else if (tileCenter.dx + width / 2 > xMax) { + dx = xMax - (tileCenter.dx + width / 2); + } + final clampedCenter = tileCenter.translate(dx, 0); + + var child = builder(scaledSize); + child = Stack( + children: [ + Positioned( + left: clampedCenter.dx - width / 2, + top: clampedCenter.dy - height / 2, + child: DefaultTextStyle( + style: const TextStyle(), + child: child, + ), + ), + ], + ); + child = gridBuilder(clampedCenter, scaledSize, child); + return child; + }, + ), + ), + ), + ); + } +} + +class _OverlayBackground extends StatefulWidget { + final Offset gradientCenter; + final Widget child; + + const _OverlayBackground({ + required this.gradientCenter, + required this.child, + }); + + @override + State<_OverlayBackground> createState() => _OverlayBackgroundState(); +} + +class _OverlayBackgroundState extends State<_OverlayBackground> { + bool _initialized = false; + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addPostFrameCallback((_) => setState(() => _initialized = true)); + } + + @override + Widget build(BuildContext context) { + return AnimatedContainer( + decoration: _buildBackgroundDecoration(context), + duration: ADurations.scalingGridBackgroundAnimation, + child: widget.child, + ); + } + + BoxDecoration _buildBackgroundDecoration(BuildContext context) { + final isDark = Theme.of(context).isDark; + final gradientCenter = widget.gradientCenter; + return _initialized + ? BoxDecoration( + gradient: RadialGradient( + center: FractionalOffset.fromOffsetAndSize(gradientCenter, MediaQuery.sizeOf(context)), + radius: 1, + colors: isDark + ? const [ + Colors.black, + Colors.black54, + ] + : const [ + Colors.white, + Colors.white38, + ], + ), + ) + : BoxDecoration( + // provide dummy gradient to lerp to the other one during animation + gradient: RadialGradient( + colors: isDark + ? const [ + ColorUtils.transparentBlack, + ColorUtils.transparentBlack, + ] + : const [ + ColorUtils.transparentWhite, + ColorUtils.transparentWhite, + ], + ), + ); + } +} diff --git a/lib/widgets/common/grid/sections/fixed/section_layout.dart b/lib/widgets/common/grid/sections/fixed/section_layout.dart new file mode 100644 index 0000000..7cdfbc9 --- /dev/null +++ b/lib/widgets/common/grid/sections/fixed/section_layout.dart @@ -0,0 +1,41 @@ +import 'package:aves/widgets/common/grid/sections/section_layout.dart'; + +class FixedExtentSectionLayout extends SectionLayout { + final double tileHeight, mainAxisStride; + + @override + List<Object?> get props => [sectionKey, firstIndex, lastIndex, minOffset, maxOffset, headerExtent, tileHeight, spacing]; + + const FixedExtentSectionLayout({ + required super.sectionKey, + required super.firstIndex, + required super.lastIndex, + required super.minOffset, + required super.maxOffset, + required super.headerExtent, + required this.tileHeight, + required super.spacing, + required super.builder, + }) : mainAxisStride = tileHeight + spacing; + + @override + double indexToLayoutOffset(int index) { + index -= bodyFirstIndex; + if (index < 0) return minOffset; + return bodyMinOffset + index * mainAxisStride; + } + + @override + int getMinChildIndexForScrollOffset(double scrollOffset) { + scrollOffset -= bodyMinOffset; + if (mainAxisStride == 0 || !scrollOffset.isFinite || scrollOffset < 0) return firstIndex; + return bodyFirstIndex + scrollOffset ~/ mainAxisStride; + } + + @override + int getMaxChildIndexForScrollOffset(double scrollOffset) { + scrollOffset -= bodyMinOffset; + if (mainAxisStride == 0 || !scrollOffset.isFinite || scrollOffset < 0) return firstIndex; + return bodyFirstIndex + (scrollOffset / mainAxisStride).ceil() - 1; + } +} diff --git a/lib/widgets/common/grid/sections/fixed/section_layout_builder.dart b/lib/widgets/common/grid/sections/fixed/section_layout_builder.dart new file mode 100644 index 0000000..e450f23 --- /dev/null +++ b/lib/widgets/common/grid/sections/fixed/section_layout_builder.dart @@ -0,0 +1,109 @@ +import 'package:aves/model/source/section_keys.dart'; +import 'package:aves/widgets/common/grid/sections/fixed/list_layout.dart'; +import 'package:aves/widgets/common/grid/sections/fixed/row.dart'; +import 'package:aves/widgets/common/grid/sections/fixed/section_layout.dart'; +import 'package:aves/widgets/common/grid/sections/list_layout.dart'; +import 'package:aves/widgets/common/grid/sections/section_layout.dart'; +import 'package:aves/widgets/common/grid/sections/section_layout_builder.dart'; +import 'package:flutter/material.dart'; + +class FixedExtentSectionLayoutBuilder<T> extends SectionLayoutBuilder<T> { + int _currentIndex = 0; + double _currentOffset = 0; + final List<Size> _itemSizes; + + FixedExtentSectionLayoutBuilder({ + required super.sections, + required super.showHeaders, + required super.getHeaderExtent, + required super.buildHeader, + required super.scrollableWidth, + required super.tileLayout, + required super.columnCount, + required super.spacing, + required super.horizontalPadding, + required super.tileWidth, + required super.tileHeight, + required super.tileBuilder, + required super.tileAnimationDelay, + }) : _itemSizes = List.generate(columnCount, (index) => Size(tileWidth, tileHeight)); + + @override + SectionedListLayout<T> updateLayouts(BuildContext context) { + final sectionLayouts = sections.keys + .map((sectionKey) => buildSectionLayout( + headerExtent: showHeaders ? getHeaderExtent(context, sectionKey) : 0.0, + sectionKey: sectionKey, + section: sections[sectionKey]!, + animate: animate, + )) + .toList(); + + return FixedExtentSectionedListLayout<T>( + sections: sections, + showHeaders: showHeaders, + columnCount: columnCount, + tileWidth: tileWidth, + tileHeight: tileHeight, + spacing: spacing, + horizontalPadding: horizontalPadding, + sectionLayouts: sectionLayouts, + ); + } + + @override + SectionLayout buildSectionLayout({ + required double headerExtent, + required SectionKey sectionKey, + required List<T> section, + required bool animate, + }) { + final sectionItemCount = section.length; + final rowCount = (sectionItemCount / columnCount).ceil(); + final sectionChildCount = 1 + rowCount; + + final sectionFirstIndex = _currentIndex; + _currentIndex += sectionChildCount; + final sectionLastIndex = _currentIndex - 1; + + final sectionMinOffset = _currentOffset; + _currentOffset += headerExtent + tileHeight * rowCount + spacing * (rowCount - 1); + final sectionMaxOffset = _currentOffset; + + return FixedExtentSectionLayout( + sectionKey: sectionKey, + firstIndex: sectionFirstIndex, + lastIndex: sectionLastIndex, + minOffset: sectionMinOffset, + maxOffset: sectionMaxOffset, + headerExtent: headerExtent, + tileHeight: tileHeight, + spacing: spacing, + builder: (context, listIndex) { + final textDirection = Directionality.of(context); + final sectionChildIndex = listIndex - sectionFirstIndex; + return buildSectionWidget( + context: context, + section: section, + sectionGridIndex: listIndex * columnCount, + sectionChildIndex: sectionChildIndex, + itemIndexRange: () => ( + (sectionChildIndex - 1) * columnCount, + sectionChildIndex * columnCount, + ), + sectionKey: sectionKey, + headerExtent: headerExtent, + itemSizes: _itemSizes, + animate: animate, + buildGridRow: (children) => FixedExtentGridRow( + width: tileWidth, + height: tileHeight, + spacing: spacing, + textDirection: textDirection, + children: children, + ), + ); + }, + ); + } +} diff --git a/lib/widgets/common/grid/sections/list_layout.dart b/lib/widgets/common/grid/sections/list_layout.dart new file mode 100644 index 0000000..06e9f05 --- /dev/null +++ b/lib/widgets/common/grid/sections/list_layout.dart @@ -0,0 +1,28 @@ +import 'package:aves/model/source/section_keys.dart'; +import 'package:aves/widgets/common/grid/sections/section_layout.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; + +abstract class SectionedListLayout<T> { + final Map<SectionKey, List<T>> sections; + final bool showHeaders; + final double spacing, horizontalPadding; + final List<SectionLayout> sectionLayouts; + + const SectionedListLayout({ + required this.sections, + required this.showHeaders, + required this.spacing, + required this.horizontalPadding, + required this.sectionLayouts, + }); + + // returns tile rectangle in layout space, i.e. x=0 is start + Rect? getTileRect(T item); + + SectionLayout? getSectionAt(double offsetY) => sectionLayouts.firstWhereOrNull((sl) => offsetY < sl.maxOffset); + + // `position` in layout space, i.e. x=0 is start + T? getItemAt(Offset position); +} diff --git a/lib/widgets/common/grid/sections/mosaic/list_layout.dart b/lib/widgets/common/grid/sections/mosaic/list_layout.dart new file mode 100644 index 0000000..4590bf9 --- /dev/null +++ b/lib/widgets/common/grid/sections/mosaic/list_layout.dart @@ -0,0 +1,78 @@ +import 'package:aves/model/source/section_keys.dart'; +import 'package:aves/widgets/common/grid/sections/list_layout.dart'; +import 'package:aves/widgets/common/grid/sections/mosaic/section_layout.dart'; +import 'package:aves/widgets/common/grid/sections/section_layout.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; + +class MosaicSectionedListLayout<T> extends SectionedListLayout<T> { + const MosaicSectionedListLayout({ + required super.sections, + required super.showHeaders, + required super.spacing, + required super.horizontalPadding, + required super.sectionLayouts, + }); + + List<MosaicRowLayout> _rowsFor(SectionLayout sectionLayout) => (sectionLayout as MosaicSectionLayout).rows; + + @override + Rect? getTileRect(T item) { + final MapEntry<SectionKey?, List<T>>? section = sections.entries.firstWhereOrNull((kv) => kv.value.contains(item)); + if (section == null) return null; + + final sectionKey = section.key; + final sectionLayout = sectionLayouts.firstWhereOrNull((sl) => sl.sectionKey == sectionKey); + if (sectionLayout == null) return null; + + final sectionItemIndex = section.value.indexOf(item); + final row = _rowsFor(sectionLayout).firstWhereOrNull((row) => sectionItemIndex <= row.lastIndex); + if (row == null) return null; + + final rowItemIndex = sectionItemIndex - row.firstIndex; + final tileWidth = row.itemWidths[rowItemIndex]; + final tileHeight = row.height - spacing; + + var left = horizontalPadding; + row.itemWidths.forEachIndexedWhile((i, width) { + if (i == rowItemIndex) return true; + + left += width + spacing; + return false; + }); + final listIndex = sectionLayout.firstIndex + 1 + _rowsFor(sectionLayout).indexOf(row); + + final top = sectionLayout.indexToLayoutOffset(listIndex); + return Rect.fromLTWH(left, top, tileWidth, tileHeight); + } + + @override + T? getItemAt(Offset position) { + var dy = position.dy; + final sectionLayout = getSectionAt(dy); + if (sectionLayout == null) return null; + + final section = sections[sectionLayout.sectionKey]; + if (section == null) return null; + + dy -= sectionLayout.minOffset + sectionLayout.headerExtent; + if (dy < 0) return null; + + final row = _rowsFor(sectionLayout).firstWhereOrNull((v) => dy < v.maxOffset); + if (row == null) return null; + + var dx = position.dx - horizontalPadding; + var index = -1; + row.itemWidths.forEachIndexedWhile((i, width) { + dx -= width + spacing; + if (dx > 0) return true; + + index = row.firstIndex + i; + return false; + }); + + if (index < 0 || index >= section.length) return null; + return section[index]; + } +} diff --git a/lib/widgets/common/grid/sections/mosaic/row.dart b/lib/widgets/common/grid/sections/mosaic/row.dart new file mode 100644 index 0000000..1198405 --- /dev/null +++ b/lib/widgets/common/grid/sections/mosaic/row.dart @@ -0,0 +1,159 @@ +import 'package:aves/widgets/common/grid/sections/mosaic/section_layout.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; + +class MosaicGridRow extends MultiChildRenderObjectWidget { + final MosaicRowLayout rowLayout; + final double spacing; + final TextDirection textDirection; + + const MosaicGridRow({ + super.key, + required this.rowLayout, + required this.spacing, + required this.textDirection, + required super.children, + }); + + @override + RenderObject createRenderObject(BuildContext context) { + return RenderMosaicGridRow( + rowLayout: rowLayout, + spacing: spacing, + textDirection: textDirection, + ); + } + + @override + void updateRenderObject(BuildContext context, RenderMosaicGridRow renderObject) { + renderObject.rowLayout = rowLayout; + renderObject.spacing = spacing; + renderObject.textDirection = textDirection; + } + + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + super.debugFillProperties(properties); + properties.add(DiagnosticsProperty<MosaicRowLayout>('rowLayout', rowLayout)); + properties.add(DoubleProperty('spacing', spacing)); + properties.add(EnumProperty<TextDirection>('textDirection', textDirection)); + } +} + +class _GridRowParentData extends ContainerBoxParentData<RenderBox> {} + +class RenderMosaicGridRow extends RenderBox with ContainerRenderObjectMixin<RenderBox, _GridRowParentData>, RenderBoxContainerDefaultsMixin<RenderBox, _GridRowParentData> { + RenderMosaicGridRow({ + List<RenderBox>? children, + required MosaicRowLayout rowLayout, + required double spacing, + required TextDirection textDirection, + }) : _rowLayout = rowLayout, + _spacing = spacing, + _textDirection = textDirection { + addAll(children); + } + + MosaicRowLayout get rowLayout => _rowLayout; + MosaicRowLayout _rowLayout; + + set rowLayout(MosaicRowLayout value) { + if (_rowLayout == value) return; + _rowLayout = value; + markNeedsLayout(); + } + + double get spacing => _spacing; + double _spacing; + + set spacing(double value) { + if (_spacing == value) return; + _spacing = value; + markNeedsLayout(); + } + + TextDirection get textDirection => _textDirection; + TextDirection _textDirection; + + set textDirection(TextDirection value) { + if (_textDirection == value) return; + _textDirection = value; + markNeedsLayout(); + } + + @override + void setupParentData(RenderBox child) { + if (child.parentData is! _GridRowParentData) { + child.parentData = _GridRowParentData(); + } + } + + double get intrinsicWidth => rowLayout.itemWidths.sum + spacing * (childCount - 1); + + @override + double computeMinIntrinsicWidth(double height) => intrinsicWidth; + + @override + double computeMaxIntrinsicWidth(double height) => intrinsicWidth; + + @override + double computeMinIntrinsicHeight(double width) => rowLayout.height; + + @override + double computeMaxIntrinsicHeight(double width) => rowLayout.height; + + @override + void performLayout() { + var child = firstChild; + if (child == null) { + size = constraints.smallest; + return; + } + final thumbnailHeight = rowLayout.height - spacing; + size = Size(constraints.maxWidth, rowLayout.height); + final flipMainAxis = textDirection == TextDirection.rtl; + var i = 0; + double offsetX = flipMainAxis ? size.width : 0; + while (child != null) { + final thumbnailWidth = rowLayout.itemWidths[i]; + final childConstraints = BoxConstraints.tight(Size(thumbnailWidth, thumbnailHeight)); + child.layout(childConstraints, parentUsesSize: false); + final childParentData = child.parentData! as _GridRowParentData; + if (flipMainAxis) { + offsetX -= thumbnailWidth; + } + childParentData.offset = Offset(offsetX, 0); + if (flipMainAxis) { + offsetX -= spacing; + } else { + offsetX += thumbnailWidth + spacing; + } + child = childParentData.nextSibling; + i++; + } + } + + @override + double? computeDistanceToActualBaseline(TextBaseline baseline) { + return defaultComputeDistanceToHighestActualBaseline(baseline); + } + + @override + bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { + return defaultHitTestChildren(result, position: position); + } + + @override + void paint(PaintingContext context, Offset offset) { + defaultPaint(context, offset); + } + + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + super.debugFillProperties(properties); + properties.add(DiagnosticsProperty<MosaicRowLayout>('rowLayout', rowLayout)); + properties.add(DoubleProperty('spacing', spacing)); + properties.add(EnumProperty<TextDirection>('textDirection', textDirection)); + } +} diff --git a/lib/widgets/common/grid/sections/mosaic/scale_grid.dart b/lib/widgets/common/grid/sections/mosaic/scale_grid.dart new file mode 100644 index 0000000..820d5c7 --- /dev/null +++ b/lib/widgets/common/grid/sections/mosaic/scale_grid.dart @@ -0,0 +1,74 @@ +import 'package:aves/theme/durations.dart'; +import 'package:aves/widgets/common/grid/sections/mosaic/scale_overlay.dart'; +import 'package:aves/widgets/common/grid/sections/mosaic/section_layout_builder.dart'; +import 'package:flutter/material.dart'; + +class MosaicGrid extends StatelessWidget { + final Rect contentRect; + final Size tileSize; + final double spacing; + final MosaicItemBuilder builder; + + static const _itemRatios = <double>[ + 3 / 4, + 16 / 9, + 9 / 16, + 3 / 4, + 4 / 3, + 4 / 3, + 3 / 4, + 4 / 3, + 4 / 3, + 4 / 3, + ]; + + const MosaicGrid({ + super.key, + required this.contentRect, + required this.tileSize, + required this.spacing, + required this.builder, + }); + + @override + Widget build(BuildContext context) { + final children = <Widget>[]; + + final targetExtent = tileSize.width; + final rows = MosaicSectionLayoutBuilder.computeMosaicRows( + section: List.generate(5, (i) => _itemRatios).expand((v) => v).toList(), + availableWidthFor: (itemCount) => contentRect.width - (itemCount - 1) * spacing, + heightMax: targetExtent * MosaicSectionLayoutBuilder.heightMaxFactor, + targetExtent: targetExtent, + spacing: spacing, + bottom: tileSize.height - tileSize.width, + coverRatioResolver: (item) => item, + ); + + var i = 0; + var dy = contentRect.top; + rows.forEach((row) { + var dx = contentRect.left; + final itemHeight = row.height - spacing; + row.itemWidths.forEach((itemWidth) { + children.add( + AnimatedPositioned( + left: dx, + top: dy, + width: itemWidth, + height: itemHeight, + duration: ADurations.scalingGridPositionAnimation, + child: builder(i, targetExtent), + ), + ); + dx += itemWidth + spacing; + i++; + }); + dy += row.height; + }); + + return Stack( + children: children, + ); + } +} diff --git a/lib/widgets/common/grid/sections/mosaic/scale_overlay.dart b/lib/widgets/common/grid/sections/mosaic/scale_overlay.dart new file mode 100644 index 0000000..1e44634 --- /dev/null +++ b/lib/widgets/common/grid/sections/mosaic/scale_overlay.dart @@ -0,0 +1,117 @@ +import 'package:aves/theme/durations.dart'; +import 'package:aves/widgets/common/extensions/theme.dart'; +import 'package:aves/widgets/common/grid/sections/mosaic/scale_grid.dart'; +import 'package:aves/widgets/common/providers/media_query_data_provider.dart'; +import 'package:aves_utils/aves_utils.dart'; +import 'package:flutter/material.dart'; + +typedef MosaicItemBuilder = Widget Function(int index, double targetExtent); + +class MosaicScaleOverlay extends StatelessWidget { + final Rect contentRect; + final double spacing, extentMax; + final ValueNotifier<Size> scaledSizeNotifier; + final MosaicItemBuilder itemBuilder; + + const MosaicScaleOverlay({ + super.key, + required this.contentRect, + required this.spacing, + required this.extentMax, + required this.scaledSizeNotifier, + required this.itemBuilder, + }); + + @override + Widget build(BuildContext context) { + return MediaQueryDataProvider( + child: IgnorePointer( + child: _OverlayBackground( + child: ValueListenableBuilder<Size>( + valueListenable: scaledSizeNotifier, + builder: (context, scaledSize, child) { + final theme = Theme.of(context); + final colorScheme = theme.colorScheme; + Widget _buildBar(double width, Color color) => ClipRRect( + borderRadius: const BorderRadius.all(Radius.circular(4)), + child: Container( + color: color, + width: width, + height: 4, + ), + ); + return SafeArea( + left: false, + right: false, + bottom: false, + child: Column( + children: [ + Padding( + padding: const EdgeInsets.symmetric(vertical: 4), + child: Stack( + alignment: Alignment.center, + children: [ + _buildBar(extentMax, colorScheme.onSurface.withValues(alpha: .2)), + _buildBar(scaledSize.width, colorScheme.primary), + ], + ), + ), + Expanded( + child: MosaicGrid( + contentRect: contentRect, + tileSize: scaledSize, + spacing: spacing, + builder: itemBuilder, + ), + ), + ], + ), + ); + }, + ), + ), + ), + ); + } +} + +class _OverlayBackground extends StatefulWidget { + final Widget child; + + const _OverlayBackground({ + required this.child, + }); + + @override + State<_OverlayBackground> createState() => _OverlayBackgroundState(); +} + +class _OverlayBackgroundState extends State<_OverlayBackground> { + bool _initialized = false; + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addPostFrameCallback((_) => setState(() => _initialized = true)); + } + + @override + Widget build(BuildContext context) { + return AnimatedContainer( + decoration: _buildBackgroundDecoration(context), + duration: ADurations.scalingGridBackgroundAnimation, + child: widget.child, + ); + } + + BoxDecoration _buildBackgroundDecoration(BuildContext context) { + final isDark = Theme.of(context).isDark; + return _initialized + ? BoxDecoration( + color: isDark ? Colors.black87 : const Color(0xDDFFFFFF), + ) + : BoxDecoration( + color: isDark ? ColorUtils.transparentBlack : ColorUtils.transparentWhite, + ); + } +} diff --git a/lib/widgets/common/grid/sections/mosaic/section_layout.dart b/lib/widgets/common/grid/sections/mosaic/section_layout.dart new file mode 100644 index 0000000..0cba43a --- /dev/null +++ b/lib/widgets/common/grid/sections/mosaic/section_layout.dart @@ -0,0 +1,61 @@ +import 'package:aves/widgets/common/grid/sections/section_layout.dart'; +import 'package:collection/collection.dart'; +import 'package:equatable/equatable.dart'; + +class MosaicSectionLayout extends SectionLayout { + final List<MosaicRowLayout> rows; + + @override + List<Object?> get props => [sectionKey, firstIndex, lastIndex, minOffset, maxOffset, headerExtent, rows, spacing]; + + const MosaicSectionLayout({ + required super.sectionKey, + required super.firstIndex, + required super.lastIndex, + required super.minOffset, + required super.maxOffset, + required super.headerExtent, + required this.rows, + required super.spacing, + required super.builder, + }); + + @override + double indexToLayoutOffset(int index) { + index -= bodyFirstIndex; + if (index < 0) return minOffset; + return bodyMinOffset + (index < rows.length ? rows[index].minOffset : rows.lastOrNull?.maxOffset ?? 0); + } + + @override + int getMinChildIndexForScrollOffset(double scrollOffset) { + scrollOffset -= bodyMinOffset; + if (scrollOffset < 0) return firstIndex; + return bodyFirstIndex + rows.indexWhere((v) => scrollOffset < v.maxOffset); + } + + @override + int getMaxChildIndexForScrollOffset(double scrollOffset) { + scrollOffset -= bodyMinOffset; + if (scrollOffset < 0) return firstIndex; + final rowIndex = rows.indexWhere((v) => scrollOffset < v.maxOffset); + return bodyFirstIndex + (rowIndex == -1 ? rows.length - 1 : rowIndex); + } +} + +class MosaicRowLayout extends Equatable { + final int firstIndex, lastIndex; + final double minOffset, maxOffset, height; + final List<double> itemWidths; + + @override + List<Object?> get props => [firstIndex, lastIndex, minOffset, maxOffset, height, itemWidths]; + + const MosaicRowLayout({ + required this.firstIndex, + required this.lastIndex, + required this.minOffset, + required this.height, + required this.itemWidths, + }) : maxOffset = minOffset + height; +} diff --git a/lib/widgets/common/grid/sections/mosaic/section_layout_builder.dart b/lib/widgets/common/grid/sections/mosaic/section_layout_builder.dart new file mode 100644 index 0000000..26701c5 --- /dev/null +++ b/lib/widgets/common/grid/sections/mosaic/section_layout_builder.dart @@ -0,0 +1,198 @@ +import 'dart:math'; + +import 'package:aves/model/source/section_keys.dart'; +import 'package:aves/widgets/common/grid/sections/list_layout.dart'; +import 'package:aves/widgets/common/grid/sections/mosaic/list_layout.dart'; +import 'package:aves/widgets/common/grid/sections/mosaic/row.dart'; +import 'package:aves/widgets/common/grid/sections/mosaic/section_layout.dart'; +import 'package:aves/widgets/common/grid/sections/provider.dart'; +import 'package:aves/widgets/common/grid/sections/section_layout.dart'; +import 'package:aves/widgets/common/grid/sections/section_layout_builder.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; + +class MosaicSectionLayoutBuilder<T> extends SectionLayoutBuilder<T> { + int _currentIndex = 0; + double _currentOffset = 0; + late double Function(int itemCount) rowAvailableWidth; + late double rowHeightMax; + final CoverRatioResolver<T> coverRatioResolver; + + static const double heightMaxFactor = 2.4; + static const double minThumbnailAspectRatio = 9 / 32; + static const double maxThumbnailAspectRatio = 32 / 9; + + MosaicSectionLayoutBuilder({ + required super.sections, + required super.showHeaders, + required super.getHeaderExtent, + required super.buildHeader, + required super.scrollableWidth, + required super.tileLayout, + required super.columnCount, + required super.spacing, + required super.horizontalPadding, + required super.tileWidth, + required super.tileHeight, + required super.tileBuilder, + required Duration tileAnimationDelay, + required this.coverRatioResolver, + }) : super(tileAnimationDelay: Duration(milliseconds: (tileAnimationDelay.inMilliseconds / columnCount).ceil())) { + final rowWidth = scrollableWidth - horizontalPadding * 2; + rowAvailableWidth = (itemCount) => rowWidth - (itemCount - 1) * spacing; + rowHeightMax = tileWidth * heightMaxFactor; + } + + @override + SectionedListLayout<T> updateLayouts(BuildContext context) { + final sectionLayouts = sections.keys + .map((sectionKey) => buildSectionLayout( + headerExtent: showHeaders ? getHeaderExtent(context, sectionKey) : 0.0, + sectionKey: sectionKey, + section: sections[sectionKey]!, + animate: animate, + )) + .toList(); + + return MosaicSectionedListLayout<T>( + sections: sections, + showHeaders: showHeaders, + spacing: spacing, + horizontalPadding: horizontalPadding, + sectionLayouts: sectionLayouts, + ); + } + + @override + SectionLayout buildSectionLayout({ + required double headerExtent, + required SectionKey sectionKey, + required List<T> section, + required bool animate, + }) { + final rows = computeMosaicRows( + section: section, + availableWidthFor: rowAvailableWidth, + heightMax: rowHeightMax, + targetExtent: tileWidth, + spacing: spacing, + bottom: bottom, + coverRatioResolver: (item) => coverRatioResolver(item).clamp(minThumbnailAspectRatio, maxThumbnailAspectRatio), + ); + final rowCount = rows.length; + final sectionChildCount = 1 + rowCount; + + final sectionFirstIndex = _currentIndex; + _currentIndex += sectionChildCount; + final sectionLastIndex = _currentIndex - 1; + + final sectionMinOffset = _currentOffset; + _currentOffset += headerExtent + rows.map((v) => v.height).sum - spacing; + final sectionMaxOffset = _currentOffset; + + return MosaicSectionLayout( + sectionKey: sectionKey, + firstIndex: sectionFirstIndex, + lastIndex: sectionLastIndex, + minOffset: sectionMinOffset, + maxOffset: sectionMaxOffset, + headerExtent: headerExtent, + rows: rows, + spacing: spacing, + builder: (context, listIndex) { + final textDirection = Directionality.of(context); + final sectionChildIndex = listIndex - sectionFirstIndex; + final isHeader = sectionChildIndex == 0; + final row = isHeader ? rows.first : rows[sectionChildIndex - 1]; + final sectionGridIndex = isHeader ? sectionFirstIndex * columnCount : (sectionChildIndex + 1) * columnCount + row.firstIndex; + return buildSectionWidget( + context: context, + section: section, + sectionGridIndex: sectionGridIndex, + sectionChildIndex: sectionChildIndex, + itemIndexRange: () => isHeader ? const (0, 0) : (row.firstIndex, row.lastIndex + 1), + sectionKey: sectionKey, + headerExtent: headerExtent, + itemSizes: row.itemWidths.map((v) => Size(v, row.height)).toList(), + animate: animate, + buildGridRow: (children) { + return isHeader + ? const SizedBox() + : MosaicGridRow( + rowLayout: row, + spacing: spacing, + textDirection: textDirection, + children: children, + ); + }, + ); + }, + ); + } + + static List<MosaicRowLayout> computeMosaicRows<T>({ + required List<T> section, + required double Function(int itemCount) availableWidthFor, + required double heightMax, + required double targetExtent, + required double spacing, + required double bottom, + required CoverRatioResolver<T> coverRatioResolver, + }) { + final rows = <MosaicRowLayout>[]; + final items = <T>[]; + double ratioSum = 0, ratioMin = double.infinity; + int firstIndex = 0; + double minOffset = 0; + + void addRow(int i, {required bool complete}) { + if (items.isEmpty) return; + + final availableWidth = availableWidthFor(items.length); + var height = availableWidth / ratioSum + spacing; + if (height > heightMax + precisionErrorTolerance) { + if (!complete) { + ratioSum = availableWidth / (heightMax - spacing); + addRow(i, complete: complete); + } + return; + } + + height += bottom; + rows.add(MosaicRowLayout( + firstIndex: firstIndex, + lastIndex: i - 1, + minOffset: minOffset, + height: height, + itemWidths: items.map((item) => availableWidth * coverRatioResolver(item) / ratioSum).toList(), + )); + firstIndex = i; + minOffset += height; + ratioMin = double.infinity; + ratioSum = 0; + items.clear(); + } + + section.forEachIndexed((i, item) { + final ratio = coverRatioResolver(item); + final nextAvailableWidth = availableWidthFor(items.length + 1); + final nextRatioSum = ratio + ratioSum; + final nextItemMinWidth = nextAvailableWidth * min(ratio, ratioMin) / nextRatioSum; + final nextHeight = nextAvailableWidth / nextRatioSum + spacing; + if (nextItemMinWidth < targetExtent || nextHeight < targetExtent) { + // add row when appending the next item would make other items too small + addRow(i, complete: true); + } + items.add(item); + ratioMin = min(ratio, ratioMin); + ratioSum += ratio; + }); + if (items.isNotEmpty) { + // add last row, possibly incomplete + addRow(section.length, complete: false); + } + + return rows; + } +} diff --git a/lib/widgets/common/grid/sections/provider.dart b/lib/widgets/common/grid/sections/provider.dart new file mode 100644 index 0000000..d8b2eb9 --- /dev/null +++ b/lib/widgets/common/grid/sections/provider.dart @@ -0,0 +1,105 @@ +import 'package:aves/model/source/section_keys.dart'; +import 'package:aves/widgets/common/grid/sections/fixed/section_layout_builder.dart'; +import 'package:aves/widgets/common/grid/sections/list_layout.dart'; +import 'package:aves/widgets/common/grid/sections/mosaic/section_layout_builder.dart'; +import 'package:aves/widgets/common/grid/sections/section_layout_builder.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:provider/provider.dart'; + +typedef CoverRatioResolver<T> = double Function(T item); + +abstract class SectionedListLayoutProvider<T> extends StatelessWidget { + final double scrollableWidth; + final TileLayout tileLayout; + final int columnCount; + final double spacing, horizontalPadding, tileWidth, tileHeight; + final TileBuilder<T> tileBuilder; + final Duration tileAnimationDelay; + final CoverRatioResolver<T> coverRatioResolver; + final Widget child; + + const SectionedListLayoutProvider({ + super.key, + required this.scrollableWidth, + required this.tileLayout, + required int columnCount, + required this.spacing, + required this.horizontalPadding, + required double tileWidth, + required this.tileHeight, + required this.tileBuilder, + required this.tileAnimationDelay, + required this.coverRatioResolver, + required this.child, + }) : assert(scrollableWidth != 0), + columnCount = tileLayout == TileLayout.list ? 1 : columnCount, + tileWidth = tileLayout == TileLayout.list ? scrollableWidth - (horizontalPadding * 2) : tileWidth; + + @override + Widget build(BuildContext context) { + return ProxyProvider0<SectionedListLayout<T>>( + update: (context, _) { + switch (tileLayout) { + case TileLayout.mosaic: + return MosaicSectionLayoutBuilder<T>( + sections: sections, + showHeaders: showHeaders, + getHeaderExtent: getHeaderExtent, + buildHeader: buildHeader, + scrollableWidth: scrollableWidth, + tileLayout: tileLayout, + columnCount: columnCount, + spacing: spacing, + horizontalPadding: horizontalPadding, + tileWidth: tileWidth, + tileHeight: tileHeight, + tileBuilder: tileBuilder, + tileAnimationDelay: tileAnimationDelay, + coverRatioResolver: coverRatioResolver, + ).updateLayouts(context); + case TileLayout.grid: + case TileLayout.list: + return FixedExtentSectionLayoutBuilder<T>( + sections: sections, + showHeaders: showHeaders, + buildHeader: buildHeader, + getHeaderExtent: getHeaderExtent, + scrollableWidth: scrollableWidth, + tileLayout: tileLayout, + columnCount: columnCount, + spacing: spacing, + horizontalPadding: horizontalPadding, + tileWidth: tileWidth, + tileHeight: tileHeight, + tileBuilder: tileBuilder, + tileAnimationDelay: tileAnimationDelay, + ).updateLayouts(context); + } + }, + child: child, + ); + } + + bool get showHeaders; + + Map<SectionKey, List<T>> get sections; + + double getHeaderExtent(BuildContext context, SectionKey sectionKey); + + Widget buildHeader(BuildContext context, SectionKey sectionKey, double headerExtent); + + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + super.debugFillProperties(properties); + properties.add(DoubleProperty('scrollableWidth', scrollableWidth)); + properties.add(EnumProperty<TileLayout>('tileLayout', tileLayout)); + properties.add(IntProperty('columnCount', columnCount)); + properties.add(DoubleProperty('spacing', spacing)); + properties.add(DoubleProperty('horizontalPadding', horizontalPadding)); + properties.add(DoubleProperty('tileWidth', tileWidth)); + properties.add(DoubleProperty('tileHeight', tileHeight)); + properties.add(DiagnosticsProperty<bool>('showHeaders', showHeaders)); + } +} diff --git a/lib/widgets/common/grid/sections/section_layout.dart b/lib/widgets/common/grid/sections/section_layout.dart new file mode 100644 index 0000000..ccc7b99 --- /dev/null +++ b/lib/widgets/common/grid/sections/section_layout.dart @@ -0,0 +1,37 @@ +import 'package:aves/model/source/section_keys.dart'; +import 'package:equatable/equatable.dart'; +import 'package:flutter/material.dart'; + +@immutable +abstract class SectionLayout extends Equatable { + final SectionKey sectionKey; + final int firstIndex, lastIndex, bodyFirstIndex; + final double minOffset, maxOffset, bodyMinOffset; + final double headerExtent, spacing; + final IndexedWidgetBuilder builder; + + @override + List<Object?> get props => [sectionKey, firstIndex, lastIndex, minOffset, maxOffset, headerExtent, spacing]; + + const SectionLayout({ + required this.sectionKey, + required this.firstIndex, + required this.lastIndex, + required this.minOffset, + required this.maxOffset, + required this.headerExtent, + required this.spacing, + required this.builder, + }) : bodyFirstIndex = firstIndex + 1, + bodyMinOffset = minOffset + headerExtent; + + bool hasChild(int index) => firstIndex <= index && index <= lastIndex; + + bool hasChildAtOffset(double scrollOffset) => minOffset <= scrollOffset && scrollOffset <= maxOffset; + + double indexToLayoutOffset(int index); + + int getMinChildIndexForScrollOffset(double scrollOffset); + + int getMaxChildIndexForScrollOffset(double scrollOffset); +} diff --git a/lib/widgets/common/grid/sections/section_layout_builder.dart b/lib/widgets/common/grid/sections/section_layout_builder.dart new file mode 100644 index 0000000..2be7e97 --- /dev/null +++ b/lib/widgets/common/grid/sections/section_layout_builder.dart @@ -0,0 +1,105 @@ +import 'package:aves/model/source/section_keys.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/widgets/common/grid/sections/list_layout.dart'; +import 'package:aves/widgets/common/grid/sections/section_layout.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_staggered_animations/flutter_staggered_animations.dart'; +import 'package:provider/provider.dart'; + +typedef TileBuilder<T> = Widget Function(T item, Size tileSize); + +abstract class SectionLayoutBuilder<T> { + final Map<SectionKey, List<T>> sections; + final bool showHeaders; + final double Function(BuildContext context, SectionKey sectionKey) getHeaderExtent; + final Widget Function(BuildContext context, SectionKey sectionKey, double headerExtent) buildHeader; + final double scrollableWidth; + final TileLayout tileLayout; + final int columnCount; + final double spacing, horizontalPadding, tileWidth, tileHeight, bottom; + final TileBuilder<T> tileBuilder; + final Duration tileAnimationDelay; + final bool animate; + + const SectionLayoutBuilder({ + required this.sections, + required this.showHeaders, + required this.getHeaderExtent, + required this.buildHeader, + required this.scrollableWidth, + required this.tileLayout, + required this.columnCount, + required this.spacing, + required this.horizontalPadding, + required this.tileWidth, + required this.tileHeight, + required this.tileBuilder, + required this.tileAnimationDelay, + }) : animate = tileAnimationDelay > Duration.zero, + bottom = tileHeight - tileWidth; + + SectionedListLayout<T> updateLayouts(BuildContext context); + + SectionLayout buildSectionLayout({ + required double headerExtent, + required SectionKey sectionKey, + required List<T> section, + required bool animate, + }); + + Widget buildSectionWidget({ + required BuildContext context, + required List<T> section, + required int sectionGridIndex, + required int sectionChildIndex, + required (int, int) Function() itemIndexRange, + required SectionKey sectionKey, + required double headerExtent, + required List<Size> itemSizes, + required bool animate, + required Widget Function(List<Widget> children) buildGridRow, + }) { + if (sectionChildIndex == 0) { + final header = headerExtent > 0 ? buildHeader(context, sectionKey, headerExtent) : const SizedBox(); + return animate ? _buildAnimation(context, sectionGridIndex, header) : header; + } + + final sectionItemCount = section.length; + final itemMinMax = itemIndexRange(); + final minItemIndex = itemMinMax.$1.clamp(0, sectionItemCount); + final maxItemIndex = itemMinMax.$2.clamp(0, sectionItemCount); + final childrenCount = maxItemIndex - minItemIndex; + final children = <Widget>[]; + for (var i = 0; i < childrenCount; i++) { + final item = RepaintBoundary( + child: tileBuilder(section[minItemIndex + i], itemSizes[i]), + ); + if (animate) { + children.add(_buildAnimation(context, sectionGridIndex + i, item)); + } else { + children.add(item); + } + } + return Padding( + padding: EdgeInsets.symmetric(horizontal: horizontalPadding), + child: buildGridRow(children), + ); + } + + Widget _buildAnimation(BuildContext context, int index, Widget child) { + final durations = context.watch<DurationsData>(); + return AnimationConfiguration.staggeredGrid( + position: index, + columnCount: tileLayout == TileLayout.mosaic ? 1 : columnCount, + duration: durations.staggeredAnimation, + delay: tileAnimationDelay, + child: SlideAnimation( + verticalOffset: 50.0, + child: FadeInAnimation( + child: child, + ), + ), + ); + } +} diff --git a/lib/widgets/common/grid/selector.dart b/lib/widgets/common/grid/selector.dart new file mode 100644 index 0000000..8f92217 --- /dev/null +++ b/lib/widgets/common/grid/selector.dart @@ -0,0 +1,244 @@ +import 'dart:async'; +import 'dart:math'; + +import 'package:aves/model/selection.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/utils/math_utils.dart'; +import 'package:aves/widgets/common/basic/gestures/gesture_detector.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/extensions/media_query.dart'; +import 'package:aves/widgets/common/grid/sections/list_layout.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class GridSelectionGestureDetector<T> extends StatefulWidget { + final GlobalKey scrollableKey; + final bool selectable; + final List<T> items; + final ScrollController scrollController; + final ValueNotifier<double> appBarHeightNotifier; + final Widget child; + + const GridSelectionGestureDetector({ + super.key, + required this.scrollableKey, + this.selectable = true, + required this.items, + required this.scrollController, + required this.appBarHeightNotifier, + required this.child, + }); + + @override + State<GridSelectionGestureDetector<T>> createState() => _GridSelectionGestureDetectorState<T>(); +} + +class _GridSelectionGestureDetectorState<T> extends State<GridSelectionGestureDetector<T>> { + bool _pressing = false, _selecting = false; + late int _fromIndex, _lastToIndex; + late Offset _localPosition; + late EdgeInsets _scrollableInsets; + late double _scrollSpeedFactor; + Timer? _selectionUpdateTimer; + Timer? _scrollMonitoringTimer; + var _isScrolling = false; + + List<T> get items => widget.items; + + ScrollController get scrollController => widget.scrollController; + + double get appBarHeight => widget.appBarHeightNotifier.value; + + double get scrollableWidth { + final scrollableContext = widget.scrollableKey.currentContext!; + final scrollableBox = scrollableContext.findRenderObject() as RenderBox; + // not the same as `MediaQuery.size.width`, because of screen insets/padding + return scrollableBox.size.width; + } + + static const double _scrollEdgeRatio = .15; + static const double _scrollMaxPixelPerSecond = 600.0; + static const Duration _scrollUpdateInterval = Duration(milliseconds: 100); + + @override + void initState() { + super.initState(); + _registerWidget(widget); + } + + @override + void didUpdateWidget(covariant GridSelectionGestureDetector<T> oldWidget) { + super.didUpdateWidget(oldWidget); + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + + @override + void dispose() { + _unregisterWidget(widget); + _stopScrollMonitoringTimer(); + super.dispose(); + } + + void _registerWidget(GridSelectionGestureDetector<T> widget) { + widget.scrollController.addListener(_onScrollChanged); + } + + void _unregisterWidget(GridSelectionGestureDetector<T> widget) { + widget.scrollController.removeListener(_onScrollChanged); + } + + @override + Widget build(BuildContext context) { + final selectable = widget.selectable; + return AGestureDetector( + onLongPressStart: selectable + ? (details) { + if (_isScrolling) return; + + final fromItem = _getItemAt(details.localPosition); + if (fromItem == null) return; + + Feedback.forLongPress(context); + final selection = context.read<Selection<T>>(); + selection.toggleSelection(fromItem); + _selecting = selection.isSelected([fromItem]); + _fromIndex = items.indexOf(fromItem); + _lastToIndex = _fromIndex; + _scrollableInsets = EdgeInsets.only( + top: appBarHeight, + bottom: context.read<MediaQueryData>().effectiveBottomPadding, + ); + _scrollSpeedFactor = 0; + _pressing = true; + } + : null, + onLongPressMoveUpdate: selectable + ? (details) { + if (!_pressing) return; + _localPosition = details.localPosition; + _onLongPressUpdate(); + } + : null, + onLongPressEnd: selectable + ? (details) { + if (!_pressing) return; + _setScrollSpeed(0); + _pressing = false; + } + : null, + onTapUp: selectable && context.select<Selection<T>, bool>((selection) => selection.isSelecting) + ? (details) { + if (_isScrolling) return; + + final item = _getItemAt(details.localPosition); + if (item == null) return; + + final selection = context.read<Selection<T>>(); + selection.toggleSelection(item); + } + : null, + longPressTimeout: settings.longPressTimeout, + child: widget.child, + ); + } + + void _onScrollChanged() { + _isScrolling = true; + _stopScrollMonitoringTimer(); + _scrollMonitoringTimer = Timer(settings.longPressTimeout + const Duration(milliseconds: 150), () { + _isScrolling = false; + }); + } + + void _stopScrollMonitoringTimer() => _scrollMonitoringTimer?.cancel(); + + void _onLongPressUpdate() { + final dy = _localPosition.dy; + + final height = scrollController.position.viewportDimension; + final top = dy < height / 2; + + final distanceToEdge = max(0, top ? dy - _scrollableInsets.top : height - dy - _scrollableInsets.bottom); + final threshold = height * _scrollEdgeRatio; + if (distanceToEdge < threshold) { + _setScrollSpeed((top ? -1 : 1) * roundToPrecision((threshold - distanceToEdge) / threshold, decimals: 1)); + } else { + _setScrollSpeed(0); + } + + final toItem = _getItemAt(_localPosition); + if (toItem != null) { + _toggleSelectionToIndex(items.indexOf(toItem)); + } + } + + void _setScrollSpeed(double speedFactor) { + if (speedFactor == _scrollSpeedFactor) return; + _scrollSpeedFactor = speedFactor; + _selectionUpdateTimer?.cancel(); + + final current = scrollController.offset; + if (speedFactor == 0) { + scrollController.jumpTo(current); + return; + } + + final target = speedFactor > 0 ? scrollController.position.maxScrollExtent : .0; + if (target != current) { + final distance = target - current; + final millis = distance * 1000 / _scrollMaxPixelPerSecond / speedFactor; + scrollController.animateTo( + target, + duration: Duration(milliseconds: millis.round()), + curve: Curves.linear, + ); + // use a timer to update the selection, because `onLongPressMoveUpdate` + // is not called when the pointer stays still while the view is scrolling + _selectionUpdateTimer = Timer.periodic(_scrollUpdateInterval, (_) => _onLongPressUpdate()); + } + } + + T? _getItemAt(Offset localPosition) { + // as of Flutter v1.22.5, `hitTest` on the `ScrollView` render object works fine when it is static, + // but when it is scrolling (through controller animation), result is incomplete and children are missing, + // so we use custom layout computation instead to find the item. + final offset = Offset(0, scrollController.offset - appBarHeight) + localPosition; + final sectionedListLayout = context.read<SectionedListLayout<T>>(); + return sectionedListLayout.getItemAt(context.isRtl ? Offset(scrollableWidth - offset.dx, offset.dy) : offset); + } + + void _toggleSelectionToIndex(int toIndex) { + if (toIndex == -1) return; + + Iterable<T> getRange(int start, int end) => start < end && 0 <= start && end <= items.length ? items.getRange(start, end) : {}; + final selection = context.read<Selection<T>>(); + void addRange(int start, int end) => selection.addToSelection(getRange(start, end)); + void removeRange(int start, int end) => selection.removeFromSelection(getRange(start, end)); + + if (_selecting) { + if (toIndex <= _fromIndex) { + if (toIndex < _lastToIndex) { + addRange(toIndex, min(_fromIndex, _lastToIndex)); + if (_fromIndex < _lastToIndex) { + removeRange(_fromIndex + 1, _lastToIndex + 1); + } + } else if (_lastToIndex < toIndex) { + removeRange(_lastToIndex, toIndex); + } + } else if (_fromIndex < toIndex) { + if (_lastToIndex < toIndex) { + addRange(max(_fromIndex, _lastToIndex), toIndex + 1); + if (_lastToIndex < _fromIndex) { + removeRange(_lastToIndex, _fromIndex); + } + } else if (toIndex < _lastToIndex) { + removeRange(toIndex + 1, _lastToIndex + 1); + } + } + _lastToIndex = toIndex; + } else { + removeRange(min(_fromIndex, toIndex), max(_fromIndex, toIndex) + 1); + } + } +} diff --git a/lib/widgets/common/grid/sliver.dart b/lib/widgets/common/grid/sliver.dart new file mode 100644 index 0000000..3d7ed75 --- /dev/null +++ b/lib/widgets/common/grid/sliver.dart @@ -0,0 +1,264 @@ +import 'dart:math' as math; + +import 'package:aves/widgets/common/grid/sections/list_layout.dart'; +import 'package:aves/widgets/common/grid/sections/section_layout.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/widgets.dart'; +import 'package:provider/provider.dart'; + +// Use a `SliverList` instead of multiple `SliverGrid` because having one `SliverGrid` per section does not scale up. +// With the multiple `SliverGrid` solution, thumbnails at the beginning of each sections are built even though they are offscreen +// because of `RenderSliverMultiBoxAdaptor.addInitialChild` called by `RenderSliverGrid.performLayout` (line 591), as of Flutter v3.3.3. +// cf https://github.com/flutter/flutter/issues/49027 +// adapted from Flutter `RenderSliverFixedExtentBoxAdaptor` in `/rendering/sliver_fixed_extent_list.dart` +class SectionedListSliver<T> extends StatelessWidget { + const SectionedListSliver({super.key}); + + @override + Widget build(BuildContext context) { + final sectionLayouts = context.watch<SectionedListLayout<T>>().sectionLayouts; + final childCount = sectionLayouts.isEmpty ? 0 : sectionLayouts.last.lastIndex + 1; + return _SliverKnownExtentList( + sectionLayouts: sectionLayouts, + delegate: SliverChildBuilderDelegate( + (context, index) { + if (index >= childCount) return null; + final sectionLayout = sectionLayouts.firstWhereOrNull((section) => section.hasChild(index)); + return sectionLayout?.builder(context, index) ?? const SizedBox(); + }, + childCount: childCount, + addAutomaticKeepAlives: false, + addRepaintBoundaries: false, + ), + ); + } +} + +class _SliverKnownExtentList extends SliverMultiBoxAdaptorWidget { + final List<SectionLayout> sectionLayouts; + + const _SliverKnownExtentList({ + required super.delegate, + required this.sectionLayouts, + }); + + @override + _RenderSliverKnownExtentBoxAdaptor createRenderObject(BuildContext context) { + final element = context as SliverMultiBoxAdaptorElement; + return _RenderSliverKnownExtentBoxAdaptor(childManager: element, sectionLayouts: sectionLayouts); + } + + @override + void updateRenderObject(BuildContext context, _RenderSliverKnownExtentBoxAdaptor renderObject) { + renderObject.sectionLayouts = sectionLayouts; + } +} + +class _RenderSliverKnownExtentBoxAdaptor extends RenderSliverMultiBoxAdaptor { + List<SectionLayout> _sectionLayouts; + + List<SectionLayout> get sectionLayouts => _sectionLayouts; + + set sectionLayouts(List<SectionLayout> value) { + if (_sectionLayouts == value) return; + _sectionLayouts = value; + markNeedsLayout(); + } + + _RenderSliverKnownExtentBoxAdaptor({ + required super.childManager, + required List<SectionLayout> sectionLayouts, + }) : _sectionLayouts = sectionLayouts; + + SectionLayout? sectionAtIndex(int index) => sectionLayouts.firstWhereOrNull((section) => section.hasChild(index)); + + SectionLayout? sectionAtOffset(double scrollOffset) => sectionLayouts.firstWhereOrNull((section) => section.hasChildAtOffset(scrollOffset)) ?? sectionLayouts.lastOrNull; + + double indexToLayoutOffset(int index) { + return (sectionAtIndex(index) ?? sectionLayouts.lastOrNull)?.indexToLayoutOffset(index) ?? 0; + } + + int getMinChildIndexForScrollOffset(double scrollOffset) { + return sectionAtOffset(scrollOffset)?.getMinChildIndexForScrollOffset(scrollOffset) ?? 0; + } + + int getMaxChildIndexForScrollOffset(double scrollOffset) { + return sectionAtOffset(scrollOffset)?.getMaxChildIndexForScrollOffset(scrollOffset) ?? 0; + } + + double estimateMaxScrollOffset( + SliverConstraints constraints, { + int? firstIndex, + int? lastIndex, + double? leadingScrollOffset, + double? trailingScrollOffset, + }) { + // default implementation is an estimation via `childManager.estimateMaxScrollOffset()` + // but we have the accurate offset via pre-computed section layouts + return _sectionLayouts.last.maxOffset; + } + + double computeMaxScrollOffset(SliverConstraints constraints) { + return sectionLayouts.last.maxOffset; + } + + int _calculateLeadingGarbage(int firstIndex) { + var walker = firstChild; + var leadingGarbage = 0; + while (walker != null && indexOf(walker) < firstIndex) { + leadingGarbage += 1; + walker = childAfter(walker); + } + return leadingGarbage; + } + + int _calculateTrailingGarbage(int targetLastIndex) { + var walker = lastChild; + var trailingGarbage = 0; + while (walker != null && indexOf(walker) > targetLastIndex) { + trailingGarbage += 1; + walker = childBefore(walker); + } + return trailingGarbage; + } + + @override + void performLayout() { + final constraints = this.constraints; + childManager.didStartLayout(); + childManager.setDidUnderflow(false); + + final scrollOffset = constraints.scrollOffset + constraints.cacheOrigin; + assert(scrollOffset >= 0.0); + final remainingExtent = constraints.remainingCacheExtent; + assert(remainingExtent >= 0.0); + final targetEndScrollOffset = scrollOffset + remainingExtent; + + final childConstraints = constraints.asBoxConstraints(); + + final firstIndex = getMinChildIndexForScrollOffset(scrollOffset); + final targetLastIndex = targetEndScrollOffset.isFinite ? getMaxChildIndexForScrollOffset(targetEndScrollOffset) : null; + + if (firstChild != null) { + final leadingGarbage = _calculateLeadingGarbage(firstIndex); + final trailingGarbage = targetLastIndex != null ? _calculateTrailingGarbage(targetLastIndex) : 0; + collectGarbage(leadingGarbage, trailingGarbage); + } else { + collectGarbage(0, 0); + } + + if (firstChild == null) { + if (!addInitialChild(index: firstIndex, layoutOffset: indexToLayoutOffset(firstIndex))) { + // There are either no children, or we are past the end of all our children. + double max; + if (firstIndex <= 0) { + max = 0.0; + } else { + max = computeMaxScrollOffset(constraints); + } + geometry = SliverGeometry( + scrollExtent: max, + maxPaintExtent: max, + ); + childManager.didFinishLayout(); + return; + } + } + + RenderBox? trailingChildWithLayout; + + for (var index = indexOf(firstChild!) - 1; index >= firstIndex; --index) { + final child = insertAndLayoutLeadingChild(childConstraints); + if (child == null) { + // Items before the previously first child are no longer present. + // Reset the scroll offset to offset all items prior and up to the + // missing item. Let parent re-layout everything. + final layout = sectionAtIndex(index) ?? sectionLayouts.first; + geometry = SliverGeometry(scrollOffsetCorrection: layout.indexToLayoutOffset(index)); + return; + } + final childParentData = child.parentData as SliverMultiBoxAdaptorParentData; + childParentData.layoutOffset = indexToLayoutOffset(index); + assert(childParentData.index == index); + trailingChildWithLayout ??= child; + } + + if (trailingChildWithLayout == null) { + firstChild!.layout(childConstraints); + final childParentData = firstChild!.parentData as SliverMultiBoxAdaptorParentData; + childParentData.layoutOffset = indexToLayoutOffset(firstIndex); + trailingChildWithLayout = firstChild; + } + + var estimatedMaxScrollOffset = double.infinity; + for (var index = indexOf(trailingChildWithLayout!) + 1; targetLastIndex == null || index <= targetLastIndex; ++index) { + var child = childAfter(trailingChildWithLayout!); + if (child == null || indexOf(child) != index) { + child = insertAndLayoutChild(childConstraints, after: trailingChildWithLayout); + if (child == null) { + // We have run out of children. + final layout = sectionAtIndex(index) ?? sectionLayouts.last; + estimatedMaxScrollOffset = layout.maxOffset; + break; + } + } else { + child.layout(childConstraints); + } + trailingChildWithLayout = child; + final childParentData = child.parentData as SliverMultiBoxAdaptorParentData; + assert(childParentData.index == index); + childParentData.layoutOffset = indexToLayoutOffset(childParentData.index!); + } + + final lastIndex = indexOf(lastChild!); + final leadingScrollOffset = indexToLayoutOffset(firstIndex); + final trailingScrollOffset = indexToLayoutOffset(lastIndex + 1); + + assert(firstIndex == 0 || childScrollOffset(firstChild!)! - scrollOffset <= precisionErrorTolerance); + assert(debugAssertChildListIsNonEmptyAndContiguous()); + assert(indexOf(firstChild!) == firstIndex); + assert(targetLastIndex == null || lastIndex <= targetLastIndex); + + estimatedMaxScrollOffset = math.min( + estimatedMaxScrollOffset, + estimateMaxScrollOffset( + constraints, + firstIndex: firstIndex, + lastIndex: lastIndex, + leadingScrollOffset: leadingScrollOffset, + trailingScrollOffset: trailingScrollOffset, + ), + ); + + final paintExtent = calculatePaintOffset( + constraints, + from: math.min(constraints.scrollOffset, leadingScrollOffset), + to: trailingScrollOffset, + ); + + final cacheExtent = calculateCacheOffset( + constraints, + from: leadingScrollOffset, + to: trailingScrollOffset, + ); + + final targetEndScrollOffsetForPaint = constraints.scrollOffset + constraints.remainingPaintExtent; + final targetLastIndexForPaint = targetEndScrollOffsetForPaint.isFinite ? getMaxChildIndexForScrollOffset(targetEndScrollOffsetForPaint) : null; + geometry = SliverGeometry( + scrollExtent: estimatedMaxScrollOffset, + paintExtent: math.min(paintExtent, estimatedMaxScrollOffset), + cacheExtent: cacheExtent, + maxPaintExtent: estimatedMaxScrollOffset, + // Conservative to avoid flickering away the clip during scroll. + hasVisualOverflow: (targetLastIndexForPaint != null && lastIndex >= targetLastIndexForPaint) || constraints.scrollOffset > 0.0, + ); + + // We may have started the layout while scrolled to the end, which would not + // expose a new child. + if (estimatedMaxScrollOffset == trailingScrollOffset) childManager.setDidUnderflow(true); + childManager.didFinishLayout(); + } +} diff --git a/lib/widgets/common/grid/theme.dart b/lib/widgets/common/grid/theme.dart new file mode 100644 index 0000000..55ca836 --- /dev/null +++ b/lib/widgets/common/grid/theme.dart @@ -0,0 +1,111 @@ +import 'dart:math'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/favourites.dart'; +import 'package:aves/model/entry/extensions/multipage.dart'; +import 'package:aves/model/entry/extensions/props.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/widgets/common/identity/aves_icons.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class GridTheme extends StatelessWidget { + final double extent; + final bool showLocation; + final bool? showTrash; + final Widget child; + + const GridTheme({ + super.key, + required this.extent, + this.showLocation = true, + this.showTrash, + required this.child, + }); + + @override + Widget build(BuildContext context) { + return ProxyProvider2<Settings, MediaQueryData, GridThemeData>( + update: (context, settings, mq, previous) { + final margin = OverlayIcon.defaultMargin.vertical; + var iconSize = min<double>(24.0, ((extent - margin) / 5).floorToDouble() - margin); + final fontSize = (iconSize * .7).floorToDouble(); + iconSize = mq.textScaler.scale(iconSize); + final highlightBorderWidth = extent * .1; + final interactiveDimension = min(iconSize * 2, kMinInteractiveDimension); + return GridThemeData( + iconSize: iconSize, + fontSize: fontSize, + highlightBorderWidth: highlightBorderWidth, + interactiveDimension: interactiveDimension, + showFavourite: settings.showThumbnailFavourite, + showHdr: settings.showThumbnailHdr, + locationIcon: showLocation ? settings.thumbnailLocationIcon : ThumbnailOverlayLocationIcon.none, + tagIcon: settings.thumbnailTagIcon, + showMotionPhoto: settings.showThumbnailMotionPhoto, + showRating: settings.showThumbnailRating, + showRaw: settings.showThumbnailRaw, + showTrash: showTrash ?? true, + showVideoDuration: settings.showThumbnailVideoDuration, + ); + }, + child: child, + ); + } +} + +typedef GridThemeIconBuilder = List<Widget> Function(BuildContext context, AvesEntry entry); + +class GridThemeData { + final double iconSize, fontSize, highlightBorderWidth, interactiveDimension; + final bool showFavourite, showHdr, showMotionPhoto, showRating, showRaw, showTrash, showVideoDuration; + final bool showLocated, showUnlocated, showTagged, showUntagged; + late final GridThemeIconBuilder iconBuilder; + + GridThemeData({ + required this.iconSize, + required this.fontSize, + required this.highlightBorderWidth, + required this.interactiveDimension, + required this.showFavourite, + required this.showHdr, + required ThumbnailOverlayLocationIcon locationIcon, + required ThumbnailOverlayTagIcon tagIcon, + required this.showMotionPhoto, + required this.showRating, + required this.showRaw, + required this.showTrash, + required this.showVideoDuration, + }) : showLocated = locationIcon == ThumbnailOverlayLocationIcon.located, + showUnlocated = locationIcon == ThumbnailOverlayLocationIcon.unlocated, + showTagged = tagIcon == ThumbnailOverlayTagIcon.tagged, + showUntagged = tagIcon == ThumbnailOverlayTagIcon.untagged { + iconBuilder = (context, entry) { + final located = entry.hasGps; + final tagged = entry.tags.isNotEmpty; + final isMultiPage = entry.isMultiPage; + return [ + if (entry.isFavourite && showFavourite) const FavouriteIcon(), + if (tagged && showTagged) TagIcon.tagged(), + if (!tagged && showUntagged) TagIcon.untagged(), + if (located && showLocated) LocationIcon.located(), + if (!located && showUnlocated) LocationIcon.unlocated(), + if (entry.rating != 0 && showRating) RatingIcon(entry: entry), + if (entry.isHdr && showHdr) const HdrIcon(), + if (entry.isPureVideo) + VideoIcon(entry: entry) + else if (entry.isAnimated) + const AnimatedImageIcon() + else ...[ + if ((entry.isRaw || (isMultiPage && entry.stackedEntries?.any((v) => v.isRaw) == true)) && showRaw) const RawIcon(), + if (entry.is360) const PanoramaIcon(), + ], + if (entry.isMotionPhoto && showMotionPhoto) const MotionPhotoIcon(), + if (isMultiPage && !entry.isMotionPhoto) MultiPageIcon(entry: entry), + if (entry.isGeotiff) const GeoTiffIcon(), + if (entry.trashed && showTrash) TrashIcon(trashDaysLeft: entry.trashDaysLeft), + ]; + }; + } +} diff --git a/lib/widgets/common/identity/aves_app_bar.dart b/lib/widgets/common/identity/aves_app_bar.dart new file mode 100644 index 0000000..fc388b9 --- /dev/null +++ b/lib/widgets/common/identity/aves_app_bar.dart @@ -0,0 +1,293 @@ +import 'dart:async'; +import 'dart:math'; + +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/widgets/aves_app.dart'; +import 'package:aves/widgets/common/basic/font_size_icon_theme.dart'; +import 'package:aves/widgets/common/basic/gestures/ink_well.dart'; +import 'package:aves/widgets/common/basic/insets.dart'; +import 'package:aves/widgets/common/fx/blurred.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class AvesAppBar extends StatelessWidget { + final double contentHeight; + final bool pinned; + final Widget? leading; + final Widget title; + final List<Widget> Function(BuildContext context, double maxWidth) actions; + final Widget? bottom; + final Object? transitionKey; + + static const leadingHeroTag = 'appbar-leading'; + static const titleHeroTag = 'appbar-title'; + static const double _titleMinWidth = 96; + + const AvesAppBar({ + super.key, + required this.contentHeight, + required this.pinned, + required this.leading, + required this.title, + required this.actions, + this.bottom, + this.transitionKey, + }); + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final colorScheme = theme.colorScheme; + final textScaler = MediaQuery.textScalerOf(context); + final useTvLayout = settings.useTvLayout; + + Widget? _leading = leading; + if (_leading != null) { + _leading = FontSizeIconTheme( + child: _leading, + ); + } + + Widget _title = FontSizeIconTheme( + child: LayoutBuilder( + builder: (context, constraints) { + return Row( + key: ValueKey(transitionKey), + children: [ + Expanded(child: title), + ...(actions(context, max(0, constraints.maxWidth - _titleMinWidth))), + ], + ); + }, + ), + ); + + final animate = context.select<Settings, bool>((v) => v.animate); + if (animate) { + _title = Hero( + tag: titleHeroTag, + flightShuttleBuilder: _flightShuttleBuilder, + transitionOnUserGestures: true, + child: AnimatedSwitcher( + duration: context.read<DurationsData>().iconAnimation, + child: _title, + ), + ); + + if (_leading != null) { + _leading = Hero( + tag: leadingHeroTag, + flightShuttleBuilder: _flightShuttleBuilder, + transitionOnUserGestures: true, + child: _leading, + ); + } + } + + return SliverPersistentHeader( + floating: !useTvLayout, + pinned: pinned, + delegate: _SliverAppBarDelegate( + height: MediaQuery.paddingOf(context).top + appBarHeightForContentHeight(contentHeight), + child: DirectionalSafeArea( + start: !useTvLayout, + bottom: false, + child: AvesFloatingBar( + builder: (context, backgroundColor, child) => Material( + color: backgroundColor, + child: AInkResponse( + // absorb taps while providing visual feedback + onTap: () {}, + onLongPress: () {}, + containedInkWell: true, + highlightShape: BoxShape.rectangle, + longPressTimeout: settings.longPressTimeout, + child: child, + ), + ), + child: Theme( + data: theme.copyWith( + colorScheme: colorScheme.copyWith( + onSurfaceVariant: colorScheme.onSurface, + ), + ), + child: Column( + children: [ + SizedBox( + height: textScaler.scale(kToolbarHeight), + child: Row( + children: [ + _leading != null + ? Padding( + padding: const EdgeInsets.symmetric(horizontal: 4), + child: _leading, + ) + : const SizedBox(width: 16), + Expanded( + child: DefaultTextStyle( + style: theme.appBarTheme.titleTextStyle!, + child: _title, + ), + ), + ], + ), + ), + if (bottom != null) bottom!, + ], + ), + ), + ), + ), + ), + ); + } + + static Widget _flightShuttleBuilder( + BuildContext flightContext, + Animation<double> animation, + HeroFlightDirection flightDirection, + BuildContext fromHeroContext, + BuildContext toHeroContext, + ) { + final pushing = flightDirection == HeroFlightDirection.push; + Widget popBuilder(context, child) => Opacity(opacity: 1 - animation.value, child: child); + Widget pushBuilder(context, child) => Opacity(opacity: animation.value, child: child); + return Material( + type: MaterialType.transparency, + child: DefaultTextStyle( + style: DefaultTextStyle.of(toHeroContext).style, + child: Stack( + children: [ + AnimatedBuilder( + animation: animation, + builder: pushing ? popBuilder : pushBuilder, + child: fromHeroContext.widget, + ), + AnimatedBuilder( + animation: animation, + builder: pushing ? pushBuilder : popBuilder, + child: toHeroContext.widget, + ), + ], + ), + ), + ); + } + + static double appBarHeightForContentHeight(double contentHeight) => AvesFloatingBar.margin.vertical + contentHeight; +} + +class _SliverAppBarDelegate extends SliverPersistentHeaderDelegate { + final double height; + final Widget child; + + const _SliverAppBarDelegate({ + required this.height, + required this.child, + }); + + @override + double get minExtent => height; + + @override + double get maxExtent => height; + + @override + Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) => child; + + @override + bool shouldRebuild(covariant _SliverAppBarDelegate oldDelegate) => true; +} + +class AvesFloatingBar extends StatefulWidget { + final Widget Function(BuildContext context, Color backgroundColor, Widget? child) builder; + final Widget? child; + + static const margin = EdgeInsets.all(8); + static const borderRadius = BorderRadius.all(Radius.circular(8)); + + const AvesFloatingBar({ + super.key, + required this.builder, + this.child, + }); + + @override + State<AvesFloatingBar> createState() => _AvesFloatingBarState(); +} + +class _AvesFloatingBarState extends State<AvesFloatingBar> with RouteAware { + // prevent expensive blurring when the current page is hidden + final ValueNotifier<bool> _isBlurAllowedNotifier = ValueNotifier(true); + Timer? _blurBlockTimer; + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + final route = ModalRoute.of(context); + if (route is PageRoute) { + AvesApp.pageRouteObserver.subscribe(this, route); + } + } + + @override + void dispose() { + AvesApp.pageRouteObserver.unsubscribe(this); + _isBlurAllowedNotifier.dispose(); + super.dispose(); + } + + @override + void didPopNext() { + // post to prevent single frame flash during hero + _blurBlockTimer?.cancel(); + _blurBlockTimer = null; + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; + _isBlurAllowedNotifier.value = true; + }); + } + + @override + void didPushNext() { + // delay blur disabling, otherwise visual artifacts appear during page transition with Impeller + _blurBlockTimer?.cancel(); + _blurBlockTimer = Timer(ADurations.pageTransitionLoose, () { + if (mounted) { + _isBlurAllowedNotifier.value = false; + } + }); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final backgroundColor = theme.appBarTheme.backgroundColor ?? Themes.firstLayerColor(context); + return ValueListenableBuilder<bool>( + valueListenable: _isBlurAllowedNotifier, + builder: (context, isBlurAllowed, child) { + final blurred = isBlurAllowed && context.select<Settings, bool>((v) => v.enableBlurEffect); + return Container( + foregroundDecoration: BoxDecoration( + border: Border.all( + color: theme.dividerColor, + ), + borderRadius: AvesFloatingBar.borderRadius, + ), + margin: AvesFloatingBar.margin, + child: BlurredRRect( + enabled: blurred, + borderRadius: AvesFloatingBar.borderRadius, + child: widget.builder( + context, + blurred ? backgroundColor.withValues(alpha: .85) : backgroundColor, + widget.child, + ), + ), + ); + }, + ); + } +} diff --git a/lib/widgets/common/identity/aves_caption.dart b/lib/widgets/common/identity/aves_caption.dart new file mode 100644 index 0000000..a47c1ae --- /dev/null +++ b/lib/widgets/common/identity/aves_caption.dart @@ -0,0 +1,42 @@ +import 'package:aves/theme/durations.dart'; +import 'package:aves/widgets/common/basic/text/change_highlight.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class AvesCaption extends StatelessWidget { + final String data; + + const AvesCaption( + this.data, { + super.key, + }); + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final subtitleStyle = theme.textTheme.bodySmall!; + final subtitleChangeShadowColor = theme.colorScheme.onSurface; + return ChangeHighlightText( + // provide key to refresh on theme brightness change + key: ValueKey(subtitleChangeShadowColor), + data, + style: subtitleStyle.copyWith( + shadows: [ + Shadow( + color: subtitleChangeShadowColor.withAlpha(0), + blurRadius: 0, + ) + ], + ), + changedStyle: subtitleStyle.copyWith( + shadows: [ + Shadow( + color: subtitleChangeShadowColor, + blurRadius: 3, + ) + ], + ), + duration: context.read<DurationsData>().formTextStyleTransition, + ); + } +} diff --git a/lib/widgets/common/identity/aves_donut.dart b/lib/widgets/common/identity/aves_donut.dart new file mode 100644 index 0000000..3ad6bc7 --- /dev/null +++ b/lib/widgets/common/identity/aves_donut.dart @@ -0,0 +1,201 @@ +import 'dart:math'; + +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/colors.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:charts_flutter/flutter.dart' as charts; +import 'package:collection/collection.dart'; +import 'package:equatable/equatable.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +typedef DatumKeyFormatter = String Function(AvesDonutDatum d); +typedef DatumValueFormatter = String Function(int d); +typedef DatumColorizer = Color Function(BuildContext context, AvesDonutDatum d); +typedef DatumCallback = void Function(AvesDonutDatum d); + +class AvesDonut extends StatefulWidget { + final Widget title; + final Map<String, int> byTypes; + final Duration animationDuration; + final DatumKeyFormatter formatKey; + final DatumValueFormatter formatValue; + final DatumColorizer colorize; + final DatumCallback? onTap; + + const AvesDonut({ + super.key, + required this.title, + required this.byTypes, + required this.animationDuration, + required this.formatKey, + required this.formatValue, + required this.colorize, + this.onTap, + }); + + @override + State<AvesDonut> createState() => _AvesDonutState(); +} + +class _AvesDonutState extends State<AvesDonut> with AutomaticKeepAliveClientMixin { + Map<String, int> get byTypes => widget.byTypes; + + DatumKeyFormatter get formatKey => widget.formatKey; + + DatumValueFormatter get formatValue => widget.formatValue; + + DatumColorizer get colorize => widget.colorize; + + static const avesDonutMinWidth = 124.0; + + @override + Widget build(BuildContext context) { + super.build(context); + + if (byTypes.isEmpty) return const SizedBox(); + + final sum = byTypes.values.sum; + + final seriesData = byTypes.entries.map((kv) { + final type = kv.key; + return AvesDonutDatum( + key: type, + value: kv.value, + ); + }).toList(); + seriesData.sort((d1, d2) { + final c = d2.value.compareTo(d1.value); + return c != 0 ? c : compareAsciiUpperCase(formatKey(d1), formatKey(d2)); + }); + + return AvesColorsProvider( + allowMonochrome: false, + child: LayoutBuilder( + builder: (context, constraints) { + final series = [ + charts.Series<AvesDonutDatum, String>( + id: 'type', + colorFn: (d, i) => charts.ColorUtil.fromDartColor(colorize(context, d)), + domainFn: (d, i) => formatKey(d), + measureFn: (d, i) => d.value, + data: seriesData, + labelAccessorFn: (d, _) => '${formatKey(d)}: ${d.value}', + ), + ]; + + final textScaler = MediaQuery.textScalerOf(context); + final minWidth = textScaler.scale(avesDonutMinWidth); + final availableWidth = constraints.maxWidth; + final dim = max(minWidth, availableWidth / (availableWidth > 4 * minWidth ? 4 : (availableWidth > 2 * minWidth ? 2 : 1))); + + final donut = SizedBox( + width: dim, + height: dim, + child: Stack( + alignment: Alignment.center, + children: [ + ClipRRect( + borderRadius: BorderRadius.all(Radius.circular(dim)), + child: Container( + width: dim * .7, + height: dim * .7, + color: Themes.secondLayerColor(context), + ), + ), + charts.PieChart( + series, + animate: context.select<Settings, bool>((v) => v.animate), + animationDuration: widget.animationDuration, + defaultRenderer: charts.ArcRendererConfig<String>( + arcWidth: 16, + ), + ), + Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + widget.title, + Text( + formatValue(sum), + textAlign: TextAlign.center, + ), + ], + ), + ), + ], + ), + ); + final onTap = widget.onTap; + final legend = SizedBox( + width: dim, + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.start, + children: seriesData + .map((d) => InkWell( + onTap: onTap != null ? () => onTap(d) : null, + borderRadius: const BorderRadius.all(Radius.circular(123)), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(AIcons.circle, fill: 1, color: colorize(context, d)), + const SizedBox(width: 8), + Flexible( + child: Text( + formatKey(d), + overflow: TextOverflow.fade, + softWrap: false, + maxLines: 1, + ), + ), + const SizedBox(width: 8), + Text( + formatValue(d.value), + style: TextStyle( + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + const SizedBox(width: 4), + ], + ), + )) + .toList(), + ), + ); + final children = [ + donut, + legend, + ]; + return availableWidth > minWidth * 2 + ? Row( + mainAxisSize: MainAxisSize.min, + children: children, + ) + : Column( + mainAxisSize: MainAxisSize.min, + children: children, + ); + }, + ), + ); + } + + @override + bool get wantKeepAlive => true; +} + +@immutable +class AvesDonutDatum extends Equatable { + final String key; + final int value; + + @override + List<Object?> get props => [key, value]; + + const AvesDonutDatum({ + required this.key, + required this.value, + }); +} diff --git a/lib/widgets/common/identity/aves_expansion_tile.dart b/lib/widgets/common/identity/aves_expansion_tile.dart new file mode 100644 index 0000000..ad856f6 --- /dev/null +++ b/lib/widgets/common/identity/aves_expansion_tile.dart @@ -0,0 +1,74 @@ +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/widgets/common/identity/highlight_title.dart'; +import 'package:expansion_tile_card/expansion_tile_card.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class AvesExpansionTile extends StatelessWidget { + final String value; + final Widget? leading; + final String title; + final Color? highlightColor; + final ValueNotifier<String?>? expandedNotifier; + final bool initiallyExpanded, showHighlight; + final List<Widget> children; + + const AvesExpansionTile({ + super.key, + String? value, + this.leading, + required this.title, + this.highlightColor, + this.expandedNotifier, + this.initiallyExpanded = false, + this.showHighlight = true, + required this.children, + }) : value = value ?? title; + + @override + Widget build(BuildContext context) { + final enabled = children.isNotEmpty == true; + Widget titleChild = HighlightTitle( + title: title, + color: highlightColor, + enabled: enabled, + showHighlight: showHighlight, + ); + if (leading != null) { + titleChild = Row( + children: [ + leading!, + const SizedBox(width: 8), + Expanded(child: titleChild), + ], + ); + } + + final animationDuration = context.select<DurationsData, Duration>((v) => v.expansionTileAnimation); + final theme = Theme.of(context); + final colorScheme = theme.colorScheme; + return ExpansionTileCard( + // key is expected by test driver + key: Key('tilecard-$value'), + value: value, + expandedNotifier: expandedNotifier, + title: titleChild, + expandable: enabled, + initiallyExpanded: initiallyExpanded, + finalPadding: const EdgeInsets.symmetric(vertical: 6.0), + baseColor: Themes.firstLayerColor(context), + expandedTextColor: colorScheme.onSurface, + duration: animationDuration, + shadowColor: theme.shadowColor, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Divider(thickness: 1, height: 1), + const SizedBox(height: 4), + if (enabled) ...children, + ], + ), + ); + } +} diff --git a/lib/widgets/common/identity/aves_fab.dart b/lib/widgets/common/identity/aves_fab.dart new file mode 100644 index 0000000..2c943ca --- /dev/null +++ b/lib/widgets/common/identity/aves_fab.dart @@ -0,0 +1,27 @@ +import 'package:aves/theme/icons.dart'; +import 'package:flutter/material.dart'; + +class AvesFab extends StatelessWidget { + final String tooltip; + final VoidCallback onPressed; + + const AvesFab({ + super.key, + required this.tooltip, + required this.onPressed, + }); + + @override + Widget build(BuildContext context) { + return TooltipTheme( + data: TooltipTheme.of(context).copyWith( + preferBelow: false, + ), + child: FloatingActionButton( + tooltip: tooltip, + onPressed: onPressed, + child: const Icon(AIcons.apply), + ), + ); + } +} diff --git a/lib/widgets/common/identity/aves_filter_chip.dart b/lib/widgets/common/identity/aves_filter_chip.dart new file mode 100644 index 0000000..1bbe9f2 --- /dev/null +++ b/lib/widgets/common/identity/aves_filter_chip.dart @@ -0,0 +1,426 @@ +import 'dart:async'; +import 'dart:math'; + +import 'package:aves/app_mode.dart'; +import 'package:aves/model/covers.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/filters/rating.dart'; +import 'package:aves/model/settings/enums/accessibility_animations.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/colors.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/collection/filter_bar.dart'; +import 'package:aves/widgets/common/basic/font_size_icon_theme.dart'; +import 'package:aves/widgets/common/basic/gestures/ink_well.dart'; +import 'package:aves/widgets/common/basic/popup/menu_row.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/providers/media_query_data_provider.dart'; +import 'package:aves/widgets/filter_grids/common/action_delegates/chip.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:provider/provider.dart'; + +typedef AFilterCallback<T extends CollectionFilter> = void Function(T filter); +typedef OffsetFilterCallback<T extends CollectionFilter> = void Function(BuildContext context, T filter, Offset tapPosition); + +enum HeroType { always, onTap, never } + +@immutable +class AvesFilterDecoration { + final Radius radius; + final Widget widget; + + const AvesFilterDecoration({ + required this.radius, + required this.widget, + }); + + BorderRadius get textBorderRadius => BorderRadius.vertical(bottom: radius); + + BorderRadius get chipBorderRadius => BorderRadius.all(radius); +} + +class AvesFilterChip extends StatefulWidget { + final CollectionFilter filter; + final bool showLeading, showText, allowGenericIcon, useFilterColor; + final AvesFilterDecoration? decoration; + final Color? background; + final String? banner; + final Widget? leadingOverride, details; + final double padding; + final double? maxWidth; + final HeroType heroType; + final AFilterCallback? onTap, onRemove; + final OffsetFilterCallback? onLongPress; + + static const double defaultPadding = 6.0; + static const double defaultRadius = 32; + static const double outlineWidth = 2; + static const double minChipHeight = kMinInteractiveDimension; + static const double minChipWidth = kMinInteractiveDimension; + static const double iconSize = 18; + static const double fontSize = 14; + static const double decoratedContentVerticalPadding = 5; + + const AvesFilterChip({ + super.key, + required this.filter, + this.showLeading = true, + this.showText = true, + this.allowGenericIcon = true, + this.useFilterColor = true, + this.decoration, + this.background, + this.banner, + this.leadingOverride, + this.details, + this.padding = defaultPadding, + this.maxWidth, + this.heroType = HeroType.onTap, + this.onTap, + this.onRemove, + this.onLongPress = showDefaultLongPressMenu, + }); + + static double computeMaxWidthForRow( + BuildContext context, { + required int minChipPerRow, + required double chipPadding, + required double rowPadding, + }) { + final mqWidth = MediaQuery.sizeOf(context).width; + final mqHorizontalPadding = MediaQuery.paddingOf(context).horizontal; + return (mqWidth - mqHorizontalPadding - chipPadding * minChipPerRow - rowPadding) / minChipPerRow; + } + + static Future<void> showDefaultLongPressMenu(BuildContext context, CollectionFilter filter, Offset tapPosition) async { + if (context.read<ValueNotifier<AppMode>>().value.canNavigate) { + // remove focus, if any, to prevent the keyboard from showing up + // after the user is done with the popup menu + FocusManager.instance.primaryFocus?.unfocus(); + + final overlay = Overlay.of(context).context.findRenderObject() as RenderBox; + const touchArea = Size(kMinInteractiveDimension, kMinInteractiveDimension); + final actionDelegate = ChipActionDelegate(); + final animations = context.read<Settings>().accessibilityAnimations; + + final selectedAction = await showMenu<ChipAction>( + context: context, + position: RelativeRect.fromRect(tapPosition & touchArea, Offset.zero & overlay.size), + items: [ + PopupMenuItem( + child: Text(filter.getTooltip(context)), + ), + const PopupMenuDivider(), + ...ChipAction.values.where((action) => actionDelegate.isVisible(action, filter: filter)).map((action) { + late String text; + switch (action) { + case ChipAction.reverse: + text = filter.reversed ? context.l10n.chipActionFilterIn : context.l10n.chipActionFilterOut; + case ChipAction.ratingOrGreater: + text = RatingFilter.formatRatingRange(context, (filter as RatingFilter).rating, RatingFilter.opOrGreater); + case ChipAction.ratingOrLower: + text = RatingFilter.formatRatingRange(context, (filter as RatingFilter).rating, RatingFilter.opOrLower); + default: + text = action.getText(context); + } + return PopupMenuItem( + value: action, + child: FontSizeIconTheme( + child: MenuRow(text: text, icon: action.getIcon()), + ), + ); + }), + ], + popUpAnimationStyle: animations.popUpAnimationStyle, + ); + if (selectedAction != null) { + // wait for the popup menu to hide before proceeding with the action + await Future.delayed(animations.popUpAnimationDelay * timeDilation); + actionDelegate.onActionSelected(context, filter, selectedAction); + } + } + } + + @override + State<AvesFilterChip> createState() => _AvesFilterChipState(); +} + +class _AvesFilterChipState extends State<AvesFilterChip> { + final Set<StreamSubscription> _subscriptions = {}; + late Future<Color> _colorFuture; + late Color _outlineColor; + late bool _tapped; + Offset? _tapPosition; + + CollectionFilter get filter => widget.filter; + + double get padding => widget.padding; + + @override + void initState() { + super.initState(); + _tapped = false; + _subscriptions.add(covers.packageChangeStream.listen(_onCoverColorChanged)); + _subscriptions.add(covers.colorChangeStream.listen(_onCoverColorChanged)); + _subscriptions.add(settings.updateStream.where((event) => event.key == SettingKeys.themeColorModeKey).listen((_) { + // delay so that contextual colors reflect the new settings + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; + _onCoverColorChanged(null); + }); + })); + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + _initColorLoader(); + } + + @override + void didUpdateWidget(covariant AvesFilterChip oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.filter != filter) { + _initColorLoader(); + _tapped = false; + } + } + + @override + void dispose() { + _subscriptions + ..forEach((sub) => sub.cancel()) + ..clear(); + super.dispose(); + } + + void _initColorLoader() { + // For app albums, `filter.color` yields a regular async `Future` the first time + // but it yields a `SynchronousFuture` when called again on a known album. + // This works fine to avoid a frame with no Future data, for new widgets. + // However, when the user moves away and back to a page with a chip using the async future, + // the existing widget FutureBuilder cycles again from the start, with a frame in `waiting` state and no data. + // So we save the result of the Future to a local variable because of this specific case. + _colorFuture = filter.color(context); + _outlineColor = context.read<AvesColorsData>().neutral; + } + + void _onCoverColorChanged(Set<CollectionFilter>? event) { + if (event == null || event.contains(filter)) { + _initColorLoader(); + setState(() {}); + } + } + + @override + Widget build(BuildContext context) { + final decoration = widget.decoration; + final chipBackground = widget.background ?? Themes.firstLayerColor(context); + + final onTap = widget.onTap != null + ? () { + WidgetsBinding.instance.addPostFrameCallback((_) => widget.onTap?.call(filter)); + setState(() => _tapped = true); + } + : null; + final onRemove = widget.onRemove != null + ? () { + WidgetsBinding.instance.addPostFrameCallback((_) => widget.onRemove?.call(filter)); + setState(() => _tapped = true); + } + : null; + final onLongPress = widget.onLongPress != null + ? Feedback.wrapForLongPress(() { + if (_tapPosition != null) { + widget.onLongPress?.call(context, filter, _tapPosition!); + } + }, context) + : null; + + Widget? content; + final showLeading = widget.showLeading; + final showText = widget.showText; + if (showLeading || showText) { + final textScaler = MediaQuery.textScalerOf(context); + final iconSize = textScaler.scale(AvesFilterChip.iconSize); + final leading = showLeading ? widget.leadingOverride ?? filter.iconBuilder(context, iconSize, allowGenericIcon: widget.allowGenericIcon) : null; + final trailing = onRemove != null + ? Theme( + data: Theme.of(context).copyWith( + materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, + ), + child: IconButton( + icon: Icon(AIcons.clear, size: iconSize), + padding: EdgeInsets.zero, + splashRadius: IconTheme.of(context).size, + constraints: const BoxConstraints(), + onPressed: onRemove, + ), + ) + : null; + + content = Row( + mainAxisSize: decoration != null ? MainAxisSize.max : MainAxisSize.min, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + if (leading != null) leading, + if (leading != null && showText) SizedBox(width: padding), + if (showText) + Flexible( + child: Text( + filter.getLabel(context), + style: TextStyle( + fontSize: AvesFilterChip.fontSize, + decoration: filter.reversed ? TextDecoration.lineThrough : null, + decorationThickness: 2, + ), + softWrap: false, + overflow: TextOverflow.fade, + ), + ), + if (trailing != null) ...[ + SizedBox(width: padding), + trailing, + ], + ], + ); + + final details = widget.details; + if (details != null) { + content = Column( + mainAxisSize: MainAxisSize.min, + children: [ + content, + Flexible(child: details), + ], + ); + } + + if (decoration != null) { + content = Align( + alignment: Alignment.bottomCenter, + child: ClipRRect( + borderRadius: decoration.textBorderRadius, + child: Container( + padding: EdgeInsets.symmetric(horizontal: padding * 2, vertical: AvesFilterChip.decoratedContentVerticalPadding), + color: chipBackground, + child: content, + ), + ), + ); + } else { + content = Padding( + padding: EdgeInsets.symmetric(horizontal: padding * 2), + child: content, + ); + } + } + + final borderRadius = decoration?.chipBorderRadius ?? const BorderRadius.all(Radius.circular(AvesFilterChip.defaultRadius)); + final banner = widget.banner; + Widget chip = Container( + constraints: BoxConstraints( + minWidth: AvesFilterChip.minChipWidth, + maxWidth: max( + AvesFilterChip.minChipWidth, + widget.maxWidth ?? + AvesFilterChip.computeMaxWidthForRow( + context, + minChipPerRow: 2, + chipPadding: FilterBar.chipPadding.horizontal, + rowPadding: FilterBar.rowPadding.horizontal, + )), + minHeight: AvesFilterChip.minChipHeight, + ), + child: Stack( + fit: StackFit.passthrough, + children: [ + if (decoration != null) + ClipRRect( + borderRadius: decoration.chipBorderRadius, + child: decoration.widget, + ), + Material( + color: decoration != null ? Colors.transparent : chipBackground, + shape: RoundedRectangleBorder( + borderRadius: borderRadius, + ), + child: AInkResponse( + // as of Flutter v2.8.0, `InkWell` does not have `onLongPressStart` like `GestureDetector`, + // so we get the long press details from the tap instead + onTapDown: onLongPress != null ? (details) => _tapPosition = details.globalPosition : null, + onTap: onTap, + onLongPress: onLongPress, + containedInkWell: true, + highlightShape: BoxShape.rectangle, + borderRadius: borderRadius, + longPressTimeout: settings.longPressTimeout, + child: FutureBuilder<Color>( + future: _colorFuture, + builder: (context, snapshot) { + if (snapshot.hasData) { + _outlineColor = snapshot.data!; + } + return DecoratedBox( + decoration: BoxDecoration( + border: Border.fromBorderSide(BorderSide( + color: widget.useFilterColor ? _outlineColor : context.select<AvesColorsData, Color>((v) => v.neutral), + width: AvesFilterChip.outlineWidth, + )), + borderRadius: borderRadius, + ), + position: DecorationPosition.foreground, + child: content, + ); + }, + ), + ), + ), + if (banner != null) + LayoutBuilder( + builder: (context, constraints) { + return ClipRRect( + borderRadius: borderRadius, + child: Align( + // align to corner the scaled down banner in RTL + alignment: AlignmentDirectional.topStart, + child: Transform( + transform: Matrix4.identity().scaled((constraints.maxHeight / 90 - .4).clamp(.45, 1.0)), + child: Banner( + message: banner.toUpperCase(), + location: BannerLocation.topStart, + color: Theme.of(context).colorScheme.primary, + child: const SizedBox(), + ), + ), + ), + ); + }, + ), + ], + ), + ); + + final animate = context.select<Settings, bool>((v) => v.animate); + if (animate) { + final heroType = widget.heroType; + if (heroType == HeroType.always || (heroType == HeroType.onTap && _tapped)) { + chip = Hero( + tag: filter, + transitionOnUserGestures: true, + child: MediaQueryDataProvider( + child: DefaultTextStyle( + style: const TextStyle(), + child: chip, + ), + ), + ); + } + } + return chip; + } +} diff --git a/lib/widgets/common/identity/aves_icons.dart b/lib/widgets/common/identity/aves_icons.dart new file mode 100644 index 0000000..3f67d63 --- /dev/null +++ b/lib/widgets/common/identity/aves_icons.dart @@ -0,0 +1,363 @@ +import 'package:aves/image_providers/app_icon_image_provider.dart'; +import 'package:aves/model/covers.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/multipage.dart'; +import 'package:aves/model/entry/extensions/props.dart'; +import 'package:aves/model/vaults/vaults.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/extensions/theme.dart'; +import 'package:aves/widgets/common/grid/theme.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class VideoIcon extends StatelessWidget { + final AvesEntry entry; + + const VideoIcon({ + super.key, + required this.entry, + }); + + @override + Widget build(BuildContext context) { + final gridTheme = context.watch<GridThemeData>(); + final showDuration = gridTheme.showVideoDuration; + Widget child = OverlayIcon( + icon: entry.is360 ? AIcons.sphericalVideo : AIcons.videoPlay, + text: showDuration ? entry.durationText : null, + iconScale: entry.is360 && showDuration ? .9 : 1, + ); + if (showDuration) { + child = DefaultTextStyle( + style: TextStyle( + fontSize: gridTheme.fontSize, + ), + child: child, + ); + } + return child; + } +} + +class AnimatedImageIcon extends StatelessWidget { + const AnimatedImageIcon({super.key}); + + static const scale = .8; + + @override + Widget build(BuildContext context) { + return const OverlayIcon( + icon: AIcons.animated, + iconScale: scale, + ); + } +} + +class GeoTiffIcon extends StatelessWidget { + const GeoTiffIcon({super.key}); + + @override + Widget build(BuildContext context) { + return const OverlayIcon( + icon: AIcons.geo, + ); + } +} + +class HdrIcon extends StatelessWidget { + const HdrIcon({super.key}); + + @override + Widget build(BuildContext context) { + return const OverlayIcon( + icon: AIcons.hdr, + ); + } +} + +class PanoramaIcon extends StatelessWidget { + const PanoramaIcon({super.key}); + + static const scale = .85; + + @override + Widget build(BuildContext context) { + return const OverlayIcon( + icon: AIcons.panorama, + iconScale: scale, + ); + } +} + +class FavouriteIcon extends StatelessWidget { + const FavouriteIcon({super.key}); + + static const scale = .9; + + @override + Widget build(BuildContext context) { + return const OverlayIcon( + icon: AIcons.favourite, + iconScale: scale, + ); + } +} + +class TagIcon extends StatelessWidget { + final IconData icon; + + const TagIcon._private({required this.icon}); + + factory TagIcon.tagged() => const TagIcon._private(icon: AIcons.tag); + + factory TagIcon.untagged() => TagIcon._private(icon: AIcons.tagUntagged); + + static const scale = .9; + + @override + Widget build(BuildContext context) { + return OverlayIcon( + icon: icon, + iconScale: scale, + relativeOffset: const Offset(.05, .05), + ); + } +} + +class LocationIcon extends StatelessWidget { + final IconData icon; + + const LocationIcon._private({required this.icon}); + + factory LocationIcon.located() => const LocationIcon._private(icon: AIcons.location); + + factory LocationIcon.unlocated() => const LocationIcon._private(icon: AIcons.locationUnlocated); + + @override + Widget build(BuildContext context) { + return OverlayIcon( + icon: icon, + ); + } +} + +class RawIcon extends StatelessWidget { + const RawIcon({super.key}); + + @override + Widget build(BuildContext context) { + return const OverlayIcon( + icon: AIcons.raw, + ); + } +} + +class MotionPhotoIcon extends StatelessWidget { + const MotionPhotoIcon({super.key}); + + static const scale = .8; + + @override + Widget build(BuildContext context) { + return const OverlayIcon( + icon: AIcons.motionPhoto, + iconScale: scale, + ); + } +} + +class MultiPageIcon extends StatelessWidget { + final AvesEntry entry; + + static const scale = .8; + + const MultiPageIcon({ + super.key, + required this.entry, + }); + + @override + Widget build(BuildContext context) { + String? text; + if (entry.isStack) { + text = '${entry.stackedEntries?.length}'; + } + final child = OverlayIcon( + icon: AIcons.multiPage, + iconScale: scale, + text: text, + ); + return DefaultTextStyle( + style: TextStyle( + fontSize: context.select<GridThemeData, double>((t) => t.fontSize), + ), + child: child, + ); + } +} + +class RatingIcon extends StatelessWidget { + final AvesEntry entry; + + const RatingIcon({ + super.key, + required this.entry, + }); + + @override + Widget build(BuildContext context) { + return DefaultTextStyle( + style: TextStyle( + fontSize: context.select<GridThemeData, double>((t) => t.fontSize), + ), + child: OverlayIcon( + icon: AIcons.rating, + text: '${entry.rating}', + ), + ); + } +} + +class TrashIcon extends StatelessWidget { + final int? trashDaysLeft; + + const TrashIcon({ + super.key, + required this.trashDaysLeft, + }); + + @override + Widget build(BuildContext context) { + final child = OverlayIcon( + icon: AIcons.bin, + text: trashDaysLeft != null ? context.l10n.timeDays(trashDaysLeft!) : null, + ); + + return DefaultTextStyle( + style: TextStyle( + fontSize: context.select<GridThemeData, double>((t) => t.fontSize), + ), + child: child, + ); + } +} + +class OverlayIcon extends StatelessWidget { + final IconData icon; + final String? text; + final double iconScale; + final EdgeInsetsGeometry margin; + final Offset? relativeOffset; + + static const defaultMargin = EdgeInsets.only(left: 1, right: 1, bottom: 1); + + const OverlayIcon({ + super.key, + required this.icon, + this.iconScale = 1, + this.text, + // default margin for multiple icons in a `Column` + this.margin = defaultMargin, + this.relativeOffset, + }); + + @override + Widget build(BuildContext context) { + final size = context.select<GridThemeData, double>((t) => t.iconSize); + Widget iconChild = Icon( + icon, + size: size, + ); + + if (relativeOffset != null) { + iconChild = FractionalTranslation( + translation: relativeOffset!, + child: iconChild, + ); + } + + if (iconScale != 1) { + // using a transform is better than modifying the icon size to properly center the scaled icon + iconChild = Transform.scale( + scale: iconScale, + child: iconChild, + ); + } + + iconChild = SizedBox( + width: size, + height: size, + child: iconChild, + ); + + return Container( + margin: margin, + padding: text != null ? EdgeInsetsDirectional.only(end: size / 4) : null, + decoration: BoxDecoration( + color: Theme.of(context).isDark ? const Color(0xAA000000) : const Color(0xCCFFFFFF), + borderRadius: BorderRadius.all(Radius.circular(size)), + ), + child: text == null + ? iconChild + : Row( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + iconChild, + const SizedBox(width: 2), + Flexible( + child: Text( + text!, + // consistent with the color used for the icon next to it + style: TextStyle(color: IconTheme.of(context).color), + softWrap: false, + overflow: TextOverflow.fade, + maxLines: 1, + ), + ), + ], + ), + ); + } +} + +class IconUtils { + static Widget? getAlbumIcon({ + required BuildContext context, + required String albumPath, + double? size, + }) { + size ??= IconTheme.of(context).size; + Widget buildIcon(IconData icon) => Icon(icon, size: size); + + switch (covers.effectiveAlbumType(albumPath)) { + case AlbumType.camera: + return buildIcon(AIcons.cameraAlbum); + case AlbumType.screenshots: + case AlbumType.videoCaptures: + return buildIcon(AIcons.screenshotAlbum); + case AlbumType.screenRecordings: + return buildIcon(AIcons.recordingAlbum); + case AlbumType.download: + return buildIcon(AIcons.downloadAlbum); + case AlbumType.app: + final package = covers.effectiveAlbumPackage(albumPath); + return package != null + ? Image( + image: AppIconImage( + packageName: package, + size: size!, + ), + width: size, + height: size, + ) + : null; + case AlbumType.vault: + return buildIcon(vaults.isLocked(albumPath) ? AIcons.locked : AIcons.unlocked); + case AlbumType.regular: + return null; + } + } +} diff --git a/lib/widgets/common/identity/aves_logo.dart b/lib/widgets/common/identity/aves_logo.dart new file mode 100644 index 0000000..2c35137 --- /dev/null +++ b/lib/widgets/common/identity/aves_logo.dart @@ -0,0 +1,148 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/widgets/common/fx/borders.dart'; +import 'package:aves/widgets/common/fx/colors.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class AvesLogo extends StatelessWidget { + final double size; + + const AvesLogo({ + super.key, + required this.size, + }); + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + + Widget child = CustomPaint( + size: Size(size / 1.4, size / 1.4), + painter: AvesLogoPainter(), + ); + if (context.select<Settings, bool>((v) => v.themeColorMode == AvesThemeColorMode.monochrome)) { + final tint = Color.lerp(theme.colorScheme.primary, Colors.white, .5)!; + child = ColorFiltered( + colorFilter: ColorFilter.mode(tint, BlendMode.modulate), + child: ColorFiltered( + colorFilter: MatrixColorFilters.greyscale, + child: child, + ), + ); + } + + return CircleAvatar( + backgroundColor: theme.dividerColor, + radius: size / 2, + child: CircleAvatar( + backgroundColor: Colors.white, + radius: size / 2 - AvesBorder.curvedBorderWidth(context), + child: child, + ), + ); + } +} + +class AvesLogoPainter extends CustomPainter { + @override + void paint(Canvas canvas, Size size) { + final dim = size.width / 100; + final strokePaint = Paint() + ..style = PaintingStyle.stroke + ..color = Colors.black + ..strokeWidth = dim * 3.050970 + ..strokeCap = StrokeCap.round + ..strokeJoin = StrokeJoin.round; + + final path0 = Path(); + path0.moveTo(31.784 * dim, 63.612 * dim); + path0.lineTo(48.252 * dim, 80.08 * dim); + final radius = Radius.elliptical(2.911 * dim, 2.911 * dim); + path0.arcToPoint(Offset(48.252 * dim, 84.196 * dim), radius: radius, rotation: 0, largeArc: false, clockwise: true); + path0.lineTo(40.379000000000005 * dim, 92.069 * dim); + path0.arcToPoint(Offset(19.072000000000006 * dim, 92.069 * dim), radius: Radius.elliptical(15.067 * dim, 15.067 * dim), rotation: 0, largeArc: false, clockwise: true); + path0.lineTo(11.2 * dim, 84.197 * dim); + path0.arcToPoint(Offset(11.2 * dim, 80.08 * dim), radius: radius, rotation: 0, largeArc: false, clockwise: true); + path0.lineTo(27.668 * dim, 63.611999999999995 * dim); + path0.arcToPoint(Offset(31.785 * dim, 63.611999999999995 * dim), radius: radius, rotation: 0, largeArc: false, clockwise: true); + path0.close(); + + final path1 = Path(); + path1.moveTo(56.368 * dim, 39.026 * dim); + path1.lineTo(72.837 * dim, 55.494 * dim); + final radius2 = Radius.elliptical(2.904 * dim, 2.904 * dim); + path1.arcToPoint(Offset(72.837 * dim, 59.611 * dim), radius: radius2, rotation: 0, largeArc: false, clockwise: true); + path1.lineTo(56.367000000000004 * dim, 76.079 * dim); + path1.arcToPoint(Offset(52.252 * dim, 76.079 * dim), radius: radius2, rotation: 0, largeArc: false, clockwise: true); + path1.lineTo(35.784 * dim, 59.611 * dim); + path1.arcToPoint(Offset(35.784 * dim, 55.495 * dim), radius: radius2, rotation: 0, largeArc: false, clockwise: true); + path1.lineTo(52.251999999999995 * dim, 39.027 * dim); + path1.arcToPoint(Offset(56.367999999999995 * dim, 39.027 * dim), radius: radius2, rotation: 0, largeArc: false, clockwise: true); + path1.close(); + + final path2 = Path(); + path2.moveTo(60.37 * dim, 30.908 * dim); + final radius4 = Radius.elliptical(2.91 * dim, 2.91 * dim); + path2.arcToPoint(Offset(60.37 * dim, 35.025 * dim), radius: radius4, rotation: 0, largeArc: false, clockwise: false); + path2.lineTo(76.838 * dim, 51.492 * dim); + path2.arcToPoint(Offset(80.954 * dim, 51.492 * dim), radius: radius4, rotation: 0, largeArc: false, clockwise: false); + path2.lineTo(97.422 * dim, 35.025 * dim); + path2.arcToPoint(Offset(97.422 * dim, 30.907999999999998 * dim), radius: radius4, rotation: 0, largeArc: false, clockwise: false); + path2.lineTo(89.24799999999999 * dim, 22.733999999999998 * dim); + path2.arcToPoint(Offset(68.54399999999998 * dim, 22.733999999999998 * dim), radius: Radius.elliptical(14.64 * dim, 14.64 * dim), rotation: 0, largeArc: false, clockwise: false); + path2.close(); + path2.moveTo(76.624 * dim, 30.695 * dim); + final radius5 = Radius.elliptical(3.213 * dim, 3.213 * dim); + path2.arcToPoint(Offset(81.167 * dim, 30.695 * dim), radius: radius5, rotation: 0, largeArc: false, clockwise: true); + path2.arcToPoint(Offset(81.167 * dim, 35.237 * dim), radius: radius5, rotation: 0, largeArc: false, clockwise: true); + path2.arcToPoint(Offset(76.624 * dim, 35.237 * dim), radius: radius5, rotation: 0, largeArc: false, clockwise: true); + path2.arcToPoint(Offset(76.624 * dim, 30.694000000000003 * dim), radius: radius5, rotation: 0, largeArc: false, clockwise: true); + path2.close(); + + final path3 = Path(); + path3.moveTo(24.305 * dim, 6.96 * dim); + path3.lineTo(48.35 * dim, 31.004 * dim); + path3.arcToPoint(Offset(48.35 * dim, 35.121 * dim), radius: radius, rotation: 0, largeArc: false, clockwise: true); + path3.lineTo(31.882 * dim, 51.588 * dim); + path3.arcToPoint(Offset(27.765 * dim, 51.588 * dim), radius: radius, rotation: 0, largeArc: false, clockwise: true); + path3.lineTo(17.084 * dim, 40.907 * dim); + path3.arcToPoint(Offset(17.084 * dim, 8.75 * dim), radius: Radius.elliptical(22.738 * dim, 22.738 * dim), rotation: 0, largeArc: false, clockwise: true); + path3.lineTo(18.874 * dim, 6.96 * dim); + path3.arcToPoint(Offset(24.305 * dim, 6.96 * dim), radius: Radius.elliptical(3.84 * dim, 3.84 * dim), rotation: 0, largeArc: false, clockwise: true); + path3.close(); + + canvas.drawPath( + path0, + Paint() + ..style = PaintingStyle.fill + ..color = const Color(0xffef435a)); + + canvas.drawPath( + path1, + Paint() + ..style = PaintingStyle.fill + ..color = const Color(0xffe0e0e0)); + + canvas.drawPath( + path2, + Paint() + ..style = PaintingStyle.fill + ..color = const Color(0xffffc11f)); + + canvas.drawPath( + path3, + Paint() + ..style = PaintingStyle.fill + ..color = const Color(0xff1cc8eb)); + + // stroke should be painted over fill + canvas.drawPath(path0, strokePaint); + canvas.drawPath(path1, strokePaint); + canvas.drawPath(path2, strokePaint); + canvas.drawPath(path3, strokePaint); + } + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => true; +} diff --git a/lib/widgets/common/identity/buttons/captioned_button.dart b/lib/widgets/common/identity/buttons/captioned_button.dart new file mode 100644 index 0000000..4d6df92 --- /dev/null +++ b/lib/widgets/common/identity/buttons/captioned_button.dart @@ -0,0 +1,184 @@ +import 'package:aves/widgets/common/identity/buttons/overlay_button.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; + +typedef CaptionedIconButtonBuilder = Widget Function(BuildContext context, FocusNode focusNode); + +class CaptionedButton extends StatefulWidget { + final Animation<double> scale; + final Widget captionText; + final CaptionedIconButtonBuilder iconButtonBuilder; + final bool autofocus, showCaption; + final VoidCallback? onPressed; + + static const EdgeInsets padding = EdgeInsets.symmetric(horizontal: 8); + static const double iconTextPadding = 8; + + CaptionedButton({ + super.key, + this.scale = kAlwaysCompleteAnimation, + Widget? icon, + CaptionedIconButtonBuilder? iconButtonBuilder, + String? caption, + Widget? captionText, + this.autofocus = false, + this.showCaption = true, + required this.onPressed, + }) : assert(icon != null || iconButtonBuilder != null), + assert(caption != null || captionText != null), + iconButtonBuilder = iconButtonBuilder ?? ((_, focusNode) => IconButton(icon: icon!, onPressed: onPressed, focusNode: focusNode)), + captionText = captionText ?? CaptionedButtonText(text: caption!, enabled: onPressed != null); + + @override + State<CaptionedButton> createState() => _CaptionedButtonState(); + + static double getWidth(BuildContext context) => OverlayButton.getSize(context) + padding.horizontal; + + static Size getSize(BuildContext context, String text, {required bool showCaption}) { + final width = getWidth(context); + var height = width; + if (showCaption) { + final paragraph = RenderParagraph( + TextSpan(text: text, style: CaptionedButtonText._textStyle(context)), + textDirection: TextDirection.ltr, + textScaler: MediaQuery.textScalerOf(context), + maxLines: CaptionedButtonText.maxLines, + )..layout(const BoxConstraints(), parentUsesSize: true); + height += paragraph.getMaxIntrinsicHeight(width) + padding.vertical; + paragraph.dispose(); + } + return Size(width, height); + } + + static double getTelevisionButtonHeight(BuildContext context) { + final text = 'whatever' * 42; + return CaptionedButton.getSize(context, text, showCaption: true).height; + } +} + +class _CaptionedButtonState extends State<CaptionedButton> { + final FocusNode _focusNode = FocusNode(); + final ValueNotifier<bool> _focusedNotifier = ValueNotifier(false); + bool _didAutofocus = false; + + @override + void initState() { + super.initState(); + _updateTraversal(); + _focusNode.addListener(_onFocusChanged); + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + _handleAutofocus(); + } + + @override + void didUpdateWidget(covariant CaptionedButton oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.onPressed != widget.onPressed) { + _updateTraversal(); + } + if (oldWidget.autofocus != widget.autofocus) { + _handleAutofocus(); + } + } + + @override + void dispose() { + _focusNode.dispose(); + _focusedNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return SizedBox( + width: CaptionedButton.getWidth(context), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + SizedBox(height: CaptionedButton.padding.top), + OverlayButton( + scale: widget.scale, + focusNode: _focusNode, + child: widget.iconButtonBuilder(context, _focusNode), + ), + if (widget.showCaption) ...[ + const SizedBox(height: CaptionedButton.iconTextPadding), + ScaleTransition( + scale: widget.scale, + child: ValueListenableBuilder<bool>( + valueListenable: _focusedNotifier, + builder: (context, focused, child) { + final style = CaptionedButtonText._textStyle(context); + return AnimatedDefaultTextStyle( + style: focused + ? style.copyWith( + color: Theme.of(context).colorScheme.primary, + ) + : style, + duration: const Duration(milliseconds: 200), + child: widget.captionText, + ); + }, + ), + ), + ], + SizedBox(height: CaptionedButton.padding.bottom), + ], + ), + ); + } + + void _handleAutofocus() { + if (!_didAutofocus && widget.autofocus) { + FocusScope.of(context).autofocus(_focusNode); + _didAutofocus = true; + } + } + + void _onFocusChanged() => _focusedNotifier.value = _focusNode.hasFocus; + + void _updateTraversal() { + final enabled = widget.onPressed != null; + _focusNode.skipTraversal = !enabled; + _focusNode.canRequestFocus = enabled; + } +} + +class CaptionedButtonText extends StatelessWidget { + final String text; + final bool enabled; + + static const int maxLines = 2; + + const CaptionedButtonText({ + super.key, + required this.text, + required this.enabled, + }); + + @override + Widget build(BuildContext context) { + var style = DefaultTextStyle.of(context).style; + if (!enabled) { + style = style.copyWith(color: style.color!.withValues(alpha: .2)); + } + + return Text( + text, + style: style, + textAlign: TextAlign.center, + overflow: TextOverflow.ellipsis, + maxLines: maxLines, + ); + } + + static TextStyle _textStyle(BuildContext context) { + // specify `height` for accurate paragraph height measurement + final defaultTextHeight = DefaultTextStyle.of(context).style.height; + return Theme.of(context).textTheme.bodySmall!.copyWith(height: defaultTextHeight); + } +} diff --git a/lib/widgets/common/identity/buttons/outlined_button.dart b/lib/widgets/common/identity/buttons/outlined_button.dart new file mode 100644 index 0000000..851ef93 --- /dev/null +++ b/lib/widgets/common/identity/buttons/outlined_button.dart @@ -0,0 +1,43 @@ +import 'package:flutter/material.dart'; + +class AvesOutlinedButton extends StatelessWidget { + final Widget? icon; + final String label; + final VoidCallback? onPressed; + + const AvesOutlinedButton({ + super.key, + this.icon, + required this.label, + required this.onPressed, + }); + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final foreground = WidgetStateProperty.resolveWith<Color>((states) { + return states.contains(WidgetState.disabled) ? theme.disabledColor : theme.colorScheme.onSurface; + }); + final style = ButtonStyle( + foregroundColor: foreground, + iconColor: foreground, + side: WidgetStateProperty.resolveWith<BorderSide>((states) { + return BorderSide( + color: states.contains(WidgetState.disabled) ? theme.disabledColor : theme.colorScheme.primary, + ); + }), + ); + return icon != null + ? OutlinedButton.icon( + onPressed: onPressed, + style: style, + icon: icon!, + label: Text(label), + ) + : OutlinedButton( + onPressed: onPressed, + style: style, + child: Text(label), + ); + } +} diff --git a/lib/widgets/common/identity/buttons/overlay_button.dart b/lib/widgets/common/identity/buttons/overlay_button.dart new file mode 100644 index 0000000..17fdc16 --- /dev/null +++ b/lib/widgets/common/identity/buttons/overlay_button.dart @@ -0,0 +1,191 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/widgets/common/extensions/theme.dart'; +import 'package:aves/widgets/common/fx/blurred.dart'; +import 'package:aves/widgets/common/fx/borders.dart'; +import 'package:flutter/material.dart'; + +class OverlayButton extends StatefulWidget { + final Animation<double> scale; + final BorderRadius? borderRadius; + final FocusNode? focusNode; + final Widget child; + + const OverlayButton({ + super.key, + this.scale = kAlwaysCompleteAnimation, + this.borderRadius, + this.focusNode, + required this.child, + }); + + @override + State<OverlayButton> createState() => _OverlayButtonState(); + + // icon (24) + icon padding (8) + button padding (16) + static double getSize(BuildContext context) => 48; +} + +class _OverlayButtonState extends State<OverlayButton> { + final ValueNotifier<bool> _focusedNotifier = ValueNotifier(false); + + @override + void initState() { + super.initState(); + _registerWidget(widget); + } + + @override + void didUpdateWidget(covariant OverlayButton oldWidget) { + super.didUpdateWidget(oldWidget); + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + + @override + void dispose() { + _unregisterWidget(widget); + _focusedNotifier.dispose(); + super.dispose(); + } + + void _registerWidget(OverlayButton widget) { + widget.focusNode?.addListener(_onFocusChanged); + } + + void _unregisterWidget(OverlayButton widget) { + widget.focusNode?.removeListener(_onFocusChanged); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final colorScheme = theme.colorScheme; + final borderRadius = widget.borderRadius; + + final blurred = settings.enableBlurEffect; + final overlayBackground = Themes.overlayBackgroundColor( + brightness: colorScheme.brightness, + blurred: blurred, + ); + + return Theme( + data: theme.copyWith( + colorScheme: colorScheme.copyWith( + onSurfaceVariant: colorScheme.onSurface, + ), + ), + child: ScaleTransition( + scale: widget.scale, + child: ValueListenableBuilder<bool>( + valueListenable: _focusedNotifier, + builder: (context, focused, child) { + final border = AvesBorder.border( + context, + width: AvesBorder.curvedBorderWidth(context) * (focused ? 3 : 1), + ); + return borderRadius != null + ? BlurredRRect( + enabled: blurred, + borderRadius: borderRadius, + child: Material( + type: MaterialType.button, + borderRadius: borderRadius, + color: overlayBackground, + child: AnimatedContainer( + foregroundDecoration: BoxDecoration( + border: border, + borderRadius: borderRadius, + ), + duration: const Duration(milliseconds: 200), + child: widget.child, + ), + ), + ) + : BlurredOval( + enabled: blurred, + child: Material( + type: MaterialType.circle, + color: overlayBackground, + child: AnimatedContainer( + foregroundDecoration: BoxDecoration( + border: border, + shape: BoxShape.circle, + ), + duration: const Duration(milliseconds: 200), + child: widget.child, + ), + ), + ); + }, + ), + ), + ); + } + + void _onFocusChanged() => _focusedNotifier.value = widget.focusNode?.hasFocus ?? false; +} + +class ScalingOverlayTextButton extends StatelessWidget { + final Animation<double> scale; + final VoidCallback? onPressed; + final Widget child; + + const ScalingOverlayTextButton({ + super.key, + required this.scale, + this.onPressed, + required this.child, + }); + + @override + Widget build(BuildContext context) { + return SizeTransition( + sizeFactor: scale, + child: OverlayTextButton( + onPressed: onPressed, + child: child, + ), + ); + } +} + +class OverlayTextButton extends StatelessWidget { + final VoidCallback? onPressed; + final Widget child; + + const OverlayTextButton({ + super.key, + this.onPressed, + required this.child, + }); + + static const _borderRadius = 123.0; + static final _minSize = WidgetStateProperty.all<Size>(const Size(kMinInteractiveDimension, kMinInteractiveDimension)); + + @override + Widget build(BuildContext context) { + final blurred = settings.enableBlurEffect; + final theme = Theme.of(context); + final foreground = theme.colorScheme.onSurface; + return BlurredRRect.all( + enabled: blurred, + borderRadius: _borderRadius, + child: OutlinedButton( + onPressed: onPressed, + style: ButtonStyle( + backgroundColor: WidgetStateProperty.all<Color>(Themes.overlayBackgroundColor(brightness: theme.brightness, blurred: blurred)), + foregroundColor: WidgetStateProperty.all<Color>(foreground), + overlayColor: theme.isDark ? WidgetStateProperty.all<Color>(Colors.white.withValues(alpha: .12)) : null, + minimumSize: _minSize, + iconColor: WidgetStateProperty.all<Color>(foreground), + side: WidgetStateProperty.all<BorderSide>(AvesBorder.curvedSide(context)), + shape: WidgetStateProperty.all<OutlinedBorder>(const RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(_borderRadius)), + )), + ), + child: child, + ), + ); + } +} diff --git a/lib/widgets/common/identity/empty.dart b/lib/widgets/common/identity/empty.dart new file mode 100644 index 0000000..458d7a8 --- /dev/null +++ b/lib/widgets/common/identity/empty.dart @@ -0,0 +1,74 @@ +import 'package:aves/theme/durations.dart'; +import 'package:aves/widgets/common/extensions/media_query.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:flutter_staggered_animations/flutter_staggered_animations.dart'; +import 'package:provider/provider.dart'; + +class EmptyContent extends StatelessWidget { + final IconData? icon; + final String text; + final Widget? bottom; + final AlignmentGeometry alignment; + final double fontSize; + final bool safeBottom; + + const EmptyContent({ + super.key, + this.icon, + required this.text, + this.bottom, + this.alignment = const FractionalOffset(.5, .35), + this.fontSize = 22, + this.safeBottom = true, + }); + + @override + Widget build(BuildContext context) { + final color = Theme.of(context).colorScheme.primary.withValues(alpha: .5); + final durations = context.watch<DurationsData>(); + return Padding( + padding: safeBottom + ? EdgeInsets.only( + bottom: context.select<MediaQueryData, double>((mq) => mq.effectiveBottomPadding), + ) + : EdgeInsets.zero, + child: Align( + alignment: alignment, + child: Column( + mainAxisSize: MainAxisSize.min, + children: AnimationConfiguration.toStaggeredList( + duration: durations.staggeredAnimation, + delay: durations.staggeredAnimationDelay * timeDilation, + childAnimationBuilder: (child) => SlideAnimation( + verticalOffset: 50.0, + child: FadeInAnimation( + child: child, + ), + ), + children: [ + if (icon != null) ...[ + Icon( + icon, + size: 64, + color: color, + ), + const SizedBox(height: 16) + ], + if (text.isNotEmpty) + Text( + text, + style: TextStyle( + color: color, + fontSize: fontSize, + ), + textAlign: TextAlign.center, + ), + if (bottom != null) bottom!, + ], + ), + ), + ), + ); + } +} diff --git a/lib/widgets/common/identity/highlight_title.dart b/lib/widgets/common/identity/highlight_title.dart new file mode 100644 index 0000000..76647e1 --- /dev/null +++ b/lib/widgets/common/identity/highlight_title.dart @@ -0,0 +1,74 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/ref/locales.dart'; +import 'package:aves/theme/colors.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/widgets/common/basic/text/outlined.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/extensions/theme.dart'; +import 'package:aves/widgets/common/fx/highlight_decoration.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class HighlightTitle extends StatelessWidget { + final String title; + final Color? color; + final double fontSize; + final bool enabled; + final bool showHighlight; + + const HighlightTitle({ + super.key, + required this.title, + this.color, + this.fontSize = 18, + this.enabled = true, + this.showHighlight = true, + }); + + static const disabledColor = Colors.grey; + + static List<Shadow> shadows(BuildContext context) => [ + Shadow( + color: Theme.of(context).isDark ? Colors.black : Colors.white, + offset: const Offset(0, 1), + blurRadius: 2, + ) + ]; + + @override + Widget build(BuildContext context) { + final style = TextStyle( + shadows: shadows(context), + fontSize: fontSize, + letterSpacing: canHaveLetterSpacing(context.locale) ? 1 : 0, + fontFeatures: const [FontFeature.enable('smcp')], + ); + + final colors = context.watch<AvesColorsData>(); + return Align( + alignment: AlignmentDirectional.centerStart, + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 2), + decoration: showHighlight && context.select<Settings, bool>((v) => v.themeColorMode == AvesThemeColorMode.polychrome) + ? HighlightDecoration( + color: enabled ? color ?? colors.fromString(title) : disabledColor, + ) + : null, + margin: const EdgeInsets.symmetric(vertical: 4.0), + child: OutlinedText( + textSpans: [ + TextSpan( + text: title, + style: style, + ), + ], + outlineColor: Themes.firstLayerColor(context), + softWrap: false, + overflow: TextOverflow.fade, + maxLines: 1, + ), + ), + ); + } +} diff --git a/lib/widgets/common/identity/scroll_thumb.dart b/lib/widgets/common/identity/scroll_thumb.dart new file mode 100644 index 0000000..718abf2 --- /dev/null +++ b/lib/widgets/common/identity/scroll_thumb.dart @@ -0,0 +1,47 @@ +import 'package:aves/widgets/common/basic/draggable_scrollbar/arrow_clipper.dart'; +import 'package:aves/widgets/common/basic/draggable_scrollbar/scrollbar.dart'; +import 'package:flutter/material.dart'; + +const double avesScrollThumbHeight = 48; + +// height and background color do not change +// so we do not rely on the builder props +ScrollThumbBuilder avesScrollThumbBuilder({ + required double height, + required Color backgroundColor, +}) { + final scrollThumb = Container( + decoration: const BoxDecoration( + color: Colors.black26, + borderRadius: BorderRadius.all(Radius.circular(12)), + ), + height: height, + margin: _margin, + padding: _padding, + child: ClipPath( + clipper: ArrowClipper(), + child: Container( + width: _width, + decoration: BoxDecoration( + color: backgroundColor, + borderRadius: const BorderRadius.all(Radius.circular(12)), + ), + ), + ), + ); + return (backgroundColor, thumbAnimation, labelAnimation, height, {labelText}) { + return DraggableScrollbar.buildScrollThumbAndLabel( + scrollThumb: scrollThumb, + backgroundColor: backgroundColor, + thumbAnimation: thumbAnimation, + labelAnimation: labelAnimation, + labelText: labelText, + ); + }; +} + +const _margin = EdgeInsetsDirectional.only(end: 1); +const _padding = EdgeInsets.all(2); +const _width = 20.0; + +double get avesScrollThumbWidth => _width + _padding.horizontal + _margin.horizontal; diff --git a/lib/widgets/common/map/attribution.dart b/lib/widgets/common/map/attribution.dart new file mode 100644 index 0000000..1031779 --- /dev/null +++ b/lib/widgets/common/map/attribution.dart @@ -0,0 +1,67 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/text.dart'; +import 'package:aves/widgets/aves_app.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/viewer/info/common.dart'; +import 'package:aves_map/aves_map.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_markdown_plus/flutter_markdown_plus.dart'; +import 'package:provider/provider.dart'; + +class Attribution extends StatelessWidget { + final EntryMapStyle? style; + + const Attribution({ + super.key, + required this.style, + }); + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + if (style == EntryMapStyles.osmLiberty) return _buildOsmAttributionMarkdown(context, l10n.mapAttributionOsmLiberty); + if (style == EntryMapStyles.openTopoMap) return _buildOsmAttributionMarkdown(context, l10n.mapAttributionOpenTopoMap); + if (style == EntryMapStyles.osmHot) return _buildOsmAttributionMarkdown(context, l10n.mapAttributionOsmHot); + if (style == EntryMapStyles.stamenWatercolor) return _buildOsmAttributionMarkdown(context, l10n.mapAttributionStamen); + return const SizedBox(); + } + + Widget _buildOsmAttributionMarkdown(BuildContext context, String data) { + final theme = Theme.of(context); + Widget child = MarkdownBody( + data: '${context.l10n.mapAttributionOsmData}${AText.separator}$data', + selectable: true, + styleSheet: MarkdownStyleSheet( + a: TextStyle(color: theme.colorScheme.primary), + p: theme.textTheme.bodySmall!.merge(const TextStyle(fontSize: InfoRowGroup.fontSize)), + ), + onTapLink: (text, href, title) => AvesApp.launchUrl(href), + ); + + final animate = context.select<Settings, bool>((v) => v.animate); + if (animate) { + child = Hero( + tag: 'map-attribution', + flightShuttleBuilder: (flightContext, animation, flightDirection, fromHeroContext, toHeroContext) { + return DefaultTextStyle( + style: DefaultTextStyle.of(toHeroContext).style, + child: MediaQuery.removeViewPadding( + context: context, + removeLeft: true, + removeTop: true, + removeRight: true, + removeBottom: true, + child: toHeroContext.widget, + ), + ); + }, + child: child, + ); + } + + return Padding( + padding: const EdgeInsets.only(top: 4), + child: child, + ); + } +} diff --git a/lib/widgets/common/map/buttons/button.dart b/lib/widgets/common/map/buttons/button.dart new file mode 100644 index 0000000..0d3f6da --- /dev/null +++ b/lib/widgets/common/map/buttons/button.dart @@ -0,0 +1,48 @@ +import 'package:aves/widgets/common/identity/buttons/overlay_button.dart'; +import 'package:aves_map/aves_map.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class MapOverlayButton extends StatelessWidget { + final ValueWidgetBuilder<VisualDensity> builder; + + const MapOverlayButton({ + super.key, + required this.builder, + }); + + factory MapOverlayButton.icon({ + Key? buttonKey, + required Widget icon, + required String tooltip, + VoidCallback? onPressed, + }) { + return MapOverlayButton( + builder: (context, visualDensity, child) => IconButton( + key: buttonKey, + iconSize: iconSize(visualDensity), + visualDensity: visualDensity, + icon: icon, + onPressed: onPressed, + tooltip: tooltip, + ), + ); + } + + @override + Widget build(BuildContext context) { + return Selector<MapThemeData, Animation<double>>( + selector: (context, v) => v.scale, + builder: (context, scale, child) => OverlayButton( + scale: scale, + child: child!, + ), + child: Selector<MapThemeData, VisualDensity>( + selector: (context, v) => v.visualDensity, + builder: builder, + ), + ); + } + + static double iconSize(VisualDensity visualDensity) => 20 + 1.5 * visualDensity.horizontal; +} diff --git a/lib/widgets/common/map/buttons/coordinate_filter.dart b/lib/widgets/common/map/buttons/coordinate_filter.dart new file mode 100644 index 0000000..80405f3 --- /dev/null +++ b/lib/widgets/common/map/buttons/coordinate_filter.dart @@ -0,0 +1,108 @@ +import 'package:aves/model/filters/coordinate.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/utils/debouncer.dart'; +import 'package:aves/widgets/common/fx/blurred.dart'; +import 'package:aves/widgets/common/identity/aves_filter_chip.dart'; +import 'package:aves/widgets/viewer/controls/notifications.dart'; +import 'package:aves_map/aves_map.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class OverlayCoordinateFilterChip extends StatefulWidget { + final ValueNotifier<ZoomedBounds> boundsNotifier; + final double padding; + + const OverlayCoordinateFilterChip({ + super.key, + required this.boundsNotifier, + required this.padding, + }); + + @override + State<OverlayCoordinateFilterChip> createState() => _OverlayCoordinateFilterChipState(); +} + +class _OverlayCoordinateFilterChipState extends State<OverlayCoordinateFilterChip> { + final Debouncer _debouncer = Debouncer(delay: ADurations.mapInfoDebounceDelay); + final ValueNotifier<ZoomedBounds?> _idleBoundsNotifier = ValueNotifier(null); + + @override + void initState() { + super.initState(); + _registerWidget(widget); + } + + @override + void didUpdateWidget(covariant OverlayCoordinateFilterChip oldWidget) { + super.didUpdateWidget(oldWidget); + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + + @override + void dispose() { + _unregisterWidget(widget); + _idleBoundsNotifier.dispose(); + super.dispose(); + } + + void _registerWidget(OverlayCoordinateFilterChip widget) { + widget.boundsNotifier.addListener(_onBoundsChanged); + } + + void _unregisterWidget(OverlayCoordinateFilterChip widget) { + widget.boundsNotifier.removeListener(_onBoundsChanged); + } + + @override + Widget build(BuildContext context) { + final blurred = settings.enableBlurEffect; + final theme = Theme.of(context); + return Align( + alignment: Alignment.topLeft, + child: Selector<MapThemeData, Animation<double>>( + selector: (context, v) => v.scale, + builder: (context, scale, child) => SizeTransition( + sizeFactor: scale, + axisAlignment: 1, + child: FadeTransition( + opacity: scale, + child: child, + ), + ), + child: ValueListenableBuilder<ZoomedBounds?>( + valueListenable: _idleBoundsNotifier, + builder: (context, bounds, child) { + if (bounds == null) return const SizedBox(); + final filter = CoordinateFilter( + bounds.sw, + bounds.ne, + // more stable format when bounds change + minuteSecondPadding: true, + ); + return Padding( + padding: EdgeInsets.all(widget.padding), + child: BlurredRRect.all( + enabled: blurred, + borderRadius: AvesFilterChip.defaultRadius, + child: AvesFilterChip( + filter: filter, + useFilterColor: false, + background: Themes.overlayBackgroundColor(brightness: theme.brightness, blurred: blurred), + maxWidth: double.infinity, + onTap: (filter) => SelectFilterNotification(CoordinateFilter(bounds.sw, bounds.ne)).dispatch(context), + ), + ), + ); + }, + ), + ), + ); + } + + void _onBoundsChanged() { + _debouncer(() => _idleBoundsNotifier.value = widget.boundsNotifier.value); + } +} diff --git a/lib/widgets/common/map/buttons/panel.dart b/lib/widgets/common/map/buttons/panel.dart new file mode 100644 index 0000000..c054194 --- /dev/null +++ b/lib/widgets/common/map/buttons/panel.dart @@ -0,0 +1,264 @@ +import 'package:aves/model/settings/enums/accessibility_animations.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/basic/popup/menu_row.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/map/buttons/button.dart'; +import 'package:aves/widgets/common/map/buttons/coordinate_filter.dart'; +import 'package:aves/widgets/common/map/compass.dart'; +import 'package:aves/widgets/common/map/map_action_delegate.dart'; +import 'package:aves/widgets/common/providers/map_theme_provider.dart'; +import 'package:aves_map/aves_map.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:flutter/services.dart'; +import 'package:latlong2/latlong.dart'; +import 'package:provider/provider.dart'; + +class MapButtonPanel extends StatefulWidget { + final AvesMapController controller; + final ValueNotifier<ZoomedBounds> boundsNotifier; + final void Function(BuildContext context)? openMapPage; + + const MapButtonPanel({ + super.key, + required this.controller, + required this.boundsNotifier, + this.openMapPage, + }); + + @override + State<MapButtonPanel> createState() => _MapButtonPanelState(); +} + +class _MapButtonPanelState extends State<MapButtonPanel> { + late MapActionDelegate _actionDelegate; + + @override + void initState() { + super.initState(); + _updateDelegate(); + } + + @override + void didUpdateWidget(covariant MapButtonPanel oldWidget) { + super.didUpdateWidget(oldWidget); + _updateDelegate(); + } + + void _updateDelegate() => _actionDelegate = MapActionDelegate(widget.controller); + + @override + Widget build(BuildContext context) { + final showCoordinateFilter = context.select<MapThemeData, bool>((v) => v.showCoordinateFilter); + final visualDensity = context.select<MapThemeData, VisualDensity>((v) => v.visualDensity); + final double padding = 8 + visualDensity.horizontal * 2; + + Widget? topLeftButton = _buildNavigationButton(context); + Widget? topRightButton = _buildTopRightButton(context); + + return Positioned.fill( + child: TooltipTheme( + data: TooltipTheme.of(context).copyWith( + preferBelow: false, + ), + child: SafeArea( + bottom: false, + child: Stack( + children: [ + Positioned( + left: padding, + right: padding, + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: EdgeInsets.only(top: padding), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + if (topLeftButton != null) ...[ + topLeftButton, + SizedBox(height: padding), + ], + _buildCompass(context), + ], + ), + ), + showCoordinateFilter + ? Expanded( + child: OverlayCoordinateFilterChip( + boundsNotifier: widget.boundsNotifier, + padding: padding, + ), + ) + : const Spacer(), + Padding( + padding: EdgeInsets.only(top: padding), + // key is expected by test driver + child: Column( + children: [ + if (topRightButton != null) ...[ + topRightButton, + SizedBox(height: padding), + ], + // key is expected by test driver + _buildActionButton(context, MapAction.selectStyle, buttonKey: const Key('map-menu-layers')), + ], + ), + ), + ], + ), + ), + Positioned( + right: padding, + bottom: padding, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + _buildActionButton(context, MapAction.zoomIn), + SizedBox(height: padding), + _buildActionButton(context, MapAction.zoomOut), + ], + ), + ), + ], + ), + ), + ), + ); + } + + Widget? _buildNavigationButton(BuildContext context) { + Widget? child; + switch (context.select<MapThemeData, MapNavigationButton>((v) => v.navigationButton)) { + case MapNavigationButton.back: + if (!settings.useTvLayout) { + child = MapOverlayButton.icon( + icon: const BackButtonIcon(), + onPressed: () => Navigator.maybeOf(context)?.pop(), + tooltip: MaterialLocalizations.of(context).backButtonTooltip, + ); + } + case MapNavigationButton.close: + child = MapOverlayButton.icon( + icon: const CloseButtonIcon(), + onPressed: SystemNavigator.pop, + tooltip: MaterialLocalizations.of(context).closeButtonTooltip, + ); + case MapNavigationButton.map: + final _openMapPage = widget.openMapPage; + if (_openMapPage != null) { + child = MapOverlayButton.icon( + icon: const Icon(AIcons.showFullscreenCorners), + onPressed: () => _openMapPage.call(context), + tooltip: context.l10n.openMapPageTooltip, + ); + } + case MapNavigationButton.none: + break; + } + if (child != null) { + child = _heroify(context, 'top-left', child); + } + return child; + } + + Widget? _buildTopRightButton(BuildContext context) { + const heroTag = 'top-right'; + + final actions = [ + MapAction.openMapApp, + MapAction.addShortcut, + ].where((action) => _actionDelegate.isVisible(context, action)).toList(); + + Widget? child; + if (actions.length == 1) { + child = _buildActionButton(context, actions.first, heroTag: heroTag); + } else if (actions.length > 1) { + child = MapOverlayButton(builder: (context, visualDensity, child) { + final animations = context.read<Settings>().accessibilityAnimations; + return PopupMenuButton<MapAction>( + itemBuilder: (context) => actions + .map((action) => PopupMenuItem( + value: action, + child: MenuRow( + text: action.getText(context), + icon: action.getIcon(), + ), + )) + .toList(), + onSelected: (action) async { + // wait for the popup menu to hide before proceeding with the action + await Future.delayed(animations.popUpAnimationDelay * timeDilation); + _actionDelegate.onActionSelected(context, action); + }, + iconSize: MapOverlayButton.iconSize(visualDensity), + popUpAnimationStyle: animations.popUpAnimationStyle, + ); + }); + child = _heroify(context, heroTag, child); + } + return child; + } + + Widget _buildCompass(BuildContext context) { + final iconTheme = IconTheme.of(context); + final iconSize = Size.square(iconTheme.size!); + return ValueListenableBuilder<ZoomedBounds>( + valueListenable: widget.boundsNotifier, + builder: (context, bounds, child) { + final degrees = bounds.rotation; + final opacity = degrees == 0 ? .0 : 1.0; + return IgnorePointer( + ignoring: opacity == 0, + child: AnimatedOpacity( + opacity: opacity, + duration: context.select<DurationsData, Duration>((v) => v.viewerOverlayAnimation), + child: MapOverlayButton.icon( + icon: Transform( + origin: iconSize.center(Offset.zero), + transform: Matrix4.rotationZ(degToRadian(degrees)), + child: CustomPaint( + painter: CompassPainter( + color: iconTheme.color!, + ), + size: iconSize, + ), + ), + onPressed: widget.controller.resetRotation, + tooltip: context.l10n.mapPointNorthUpTooltip, + ), + ), + ); + }, + ); + } + + Widget _buildActionButton(BuildContext context, MapAction action, {Key? buttonKey, String? heroTag}) { + final child = MapOverlayButton.icon( + buttonKey: buttonKey, + icon: action.getIcon(), + onPressed: () => _actionDelegate.onActionSelected(context, action), + tooltip: action.getText(context), + ); + return _heroify(context, heroTag ?? action.name, child); + } + + Widget _heroify(BuildContext context, String? tag, Widget child) { + if (tag != null) { + final animate = context.select<Settings, bool>((v) => v.animate); + if (animate) { + return Hero( + tag: 'map-button-$tag', + flightShuttleBuilder: MapTheme.heroFlightShuttleBuilder, + child: child, + ); + } + } + return child; + } +} diff --git a/lib/widgets/common/map/compass.dart b/lib/widgets/common/map/compass.dart new file mode 100644 index 0000000..2563ecf --- /dev/null +++ b/lib/widgets/common/map/compass.dart @@ -0,0 +1,43 @@ +import 'package:flutter/material.dart'; + +class CompassPainter extends CustomPainter { + final Color color; + + const CompassPainter({ + required this.color, + }); + + @override + void paint(Canvas canvas, Size size) { + final center = Offset(size.width / 2, size.height / 2); + final base = size.width * .3; + final height = size.height * .4; + + final northTriangle = Path() + ..moveTo(center.dx - base / 2, center.dy) + ..lineTo(center.dx, center.dy - height) + ..lineTo(center.dx + base / 2, center.dy) + ..close(); + final southTriangle = Path() + ..moveTo(center.dx - base / 2, center.dy) + ..lineTo(center.dx + base / 2, center.dy) + ..lineTo(center.dx, center.dy + height) + ..close(); + + final fillPaint = Paint() + ..style = PaintingStyle.fill + ..color = color.withValues(alpha: .6); + final strokePaint = Paint() + ..style = PaintingStyle.stroke + ..color = color + ..strokeWidth = 1.7 + ..strokeJoin = StrokeJoin.round; + + canvas.drawPath(northTriangle, fillPaint); + canvas.drawPath(northTriangle, strokePaint); + canvas.drawPath(southTriangle, strokePaint); + } + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => true; +} diff --git a/lib/widgets/common/map/decorator.dart b/lib/widgets/common/map/decorator.dart new file mode 100644 index 0000000..3de7a72 --- /dev/null +++ b/lib/widgets/common/map/decorator.dart @@ -0,0 +1,67 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/widgets/common/fx/borders.dart'; +import 'package:aves/widgets/common/providers/map_theme_provider.dart'; +import 'package:aves_map/aves_map.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class MapDecorator extends StatelessWidget { + final Widget child; + + static const mapBorderRadius = BorderRadius.all(Radius.circular(24)); // to match button circles + static const mapBackground = Color(0xFFDBD5D3); + static const mapLoadingGrid = Color(0xFFC4BEBB); + + const MapDecorator({ + super.key, + required this.child, + }); + + @override + Widget build(BuildContext context) { + Widget _child = ClipRRect( + borderRadius: mapBorderRadius, + child: Container( + color: mapBackground, + foregroundDecoration: BoxDecoration( + border: AvesBorder.border(context), + borderRadius: mapBorderRadius, + ), + child: Stack( + children: [ + const GridPaper( + color: mapLoadingGrid, + interval: 10, + divisions: 1, + subdivisions: 1, + child: CustomPaint( + size: Size.infinite, + ), + ), + child, + ], + ), + ), + ); + + final animate = context.select<Settings, bool>((v) => v.animate); + if (animate) { + _child = Hero( + tag: 'map-canvas', + flightShuttleBuilder: MapTheme.heroFlightShuttleBuilder, + child: _child, + ); + } + + final interactive = context.select<MapThemeData, bool>((v) => v.interactive); + return GestureDetector( + onScaleStart: interactive + ? null + : (details) { + // absorb scale gesture here to prevent scrolling + // and triggering by mistake a move to the image page above + }, + child: _child, + ); + } +} diff --git a/lib/widgets/common/map/geo_map.dart b/lib/widgets/common/map/geo_map.dart new file mode 100644 index 0000000..a794c66 --- /dev/null +++ b/lib/widgets/common/map/geo_map.dart @@ -0,0 +1,508 @@ +import 'dart:async'; +import 'dart:math'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/images.dart'; +import 'package:aves/model/entry/extensions/location.dart'; +import 'package:aves/model/entry/sort.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/ref/poi.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/utils/math_utils.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/buttons/overlay_button.dart'; +import 'package:aves/widgets/common/map/attribution.dart'; +import 'package:aves/widgets/common/map/buttons/panel.dart'; +import 'package:aves/widgets/common/map/decorator.dart'; +import 'package:aves/widgets/common/map/leaflet/map.dart'; +import 'package:aves/widgets/common/map/map_action_delegate.dart'; +import 'package:aves/widgets/common/thumbnail/image.dart'; +import 'package:aves_map/aves_map.dart'; +import 'package:aves_utils/aves_utils.dart'; +import 'package:collection/collection.dart'; +import 'package:fluster/fluster.dart'; +import 'package:flutter/material.dart'; +import 'package:latlong2/latlong.dart'; +import 'package:provider/provider.dart'; + +class GeoMap extends StatefulWidget { + final AvesMapController controller; + final CollectionLens? collection; + final List<AvesEntry>? entries; + final Size availableSize; + final LatLng? initialCenter; + final double? initialZoom; + final ValueNotifier<bool> isAnimatingNotifier; + final ValueNotifier<LatLng?>? dotLocationNotifier; + final ValueNotifier<double>? overlayOpacityNotifier; + final MapOverlay? overlayEntry; + final Set<List<LatLng>>? tracks; + final UserZoomChangeCallback? onUserZoomChange; + final MapTapCallback? onMapTap; + final void Function( + LatLng markerLocation, + AvesEntry markerEntry, + )? onMarkerTap; + final void Function( + LatLng markerLocation, + AvesEntry markerEntry, + Set<AvesEntry> clusterEntries, + Offset tapLocalPosition, + WidgetBuilder markerBuilder, + )? onMarkerLongPress; + final void Function(BuildContext context)? openMapPage; + + const GeoMap({ + super.key, + required this.controller, + this.collection, + this.entries, + required this.availableSize, + this.initialCenter, + this.initialZoom, + required this.isAnimatingNotifier, + this.dotLocationNotifier, + this.overlayOpacityNotifier, + this.overlayEntry, + this.tracks, + this.onUserZoomChange, + this.onMapTap, + this.onMarkerTap, + this.onMarkerLongPress, + this.openMapPage, + }) : assert(collection != null || entries != null); + + @override + State<GeoMap> createState() => _GeoMapState(); +} + +class _GeoMapState extends State<GeoMap> { + final Set<StreamSubscription> _subscriptions = {}; + + // as of google_maps_flutter v2.0.6, Google map initialization is blocking + // cf https://github.com/flutter/flutter/issues/28493 + // it is especially severe the first time, but still significant afterwards + // so we prevent loading it while scrolling or animating + bool _heavyMapLoaded = false; + late final ValueNotifier<ZoomedBounds> _boundsNotifier; + Fluster<GeoEntry<AvesEntry>>? _defaultMarkerCluster; + Fluster<GeoEntry<AvesEntry>>? _slowMarkerCluster; + final AChangeNotifier _clusterChangeNotifier = AChangeNotifier(); + + List<AvesEntry> get entries => widget.collection?.sortedEntries ?? widget.entries ?? []; + + // cap initial zoom to avoid a zoom change + // when toggling overlay on Google map initial state + static const double minInitialZoom = 3; + + @override + void initState() { + super.initState(); + _boundsNotifier = ValueNotifier(_initBounds()); + _registerWidget(widget); + _onCollectionChanged(); + } + + @override + void didUpdateWidget(covariant GeoMap oldWidget) { + super.didUpdateWidget(oldWidget); + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + + @override + void dispose() { + _clusterChangeNotifier.dispose(); + _unregisterWidget(widget); + super.dispose(); + } + + void _registerWidget(GeoMap widget) { + widget.collection?.addListener(_onCollectionChanged); + _subscriptions.add(widget.controller.markerLocationChanges.listen((event) => _onCollectionChanged())); + } + + void _unregisterWidget(GeoMap widget) { + widget.collection?.removeListener(_onCollectionChanged); + _subscriptions + ..forEach((sub) => sub.cancel()) + ..clear(); + } + + @override + Widget build(BuildContext context) { + final devicePixelRatio = MediaQuery.devicePixelRatioOf(context); + void onMarkerLongPress(GeoEntry<AvesEntry> geoEntry, LatLng tapLocation) => _onMarkerLongPress( + geoEntry: geoEntry, + tapLocation: tapLocation, + devicePixelRatio: devicePixelRatio, + ); + + return Selector<Settings, EntryMapStyle?>( + selector: (context, s) => s.mapStyle, + builder: (context, mapStyle, child) { + final isHeavy = mapStyle?.isHeavy ?? false; + final locale = context.locale; + Widget _buildMarkerWidget(MarkerKey<AvesEntry> key) => ImageMarker( + key: key, + count: key.count, + locale: locale, + buildThumbnailImage: (extent) => ThumbnailImage( + entry: key.entry, + extent: extent, + devicePixelRatio: devicePixelRatio, + progressive: !isHeavy, + ), + ); + bool _isMarkerImageReady(MarkerKey<AvesEntry> key) => key.entry.isThumbnailReady(extent: MapThemeData.markerImageExtent); + + Widget child = const SizedBox(); + if (mapStyle != null) { + if (mapStyle.needMobileService) { + child = mobileServices.buildMap<AvesEntry>( + controller: widget.controller, + clusterListenable: _clusterChangeNotifier, + boundsNotifier: _boundsNotifier, + style: mapStyle, + decoratorBuilder: _decorateMap, + buttonPanelBuilder: _buildButtonPanel, + markerClusterBuilder: _buildMarkerClusters, + markerWidgetBuilder: _buildMarkerWidget, + markerImageReadyChecker: _isMarkerImageReady, + dotLocationNotifier: widget.dotLocationNotifier, + overlayOpacityNotifier: widget.overlayOpacityNotifier, + overlayEntry: widget.overlayEntry, + tracks: widget.tracks, + onUserZoomChange: widget.onUserZoomChange, + onMapTap: widget.onMapTap, + onMarkerTap: _onMarkerTap, + onMarkerLongPress: onMarkerLongPress, + ); + } else { + child = EntryLeafletMap<AvesEntry>( + controller: widget.controller, + clusterListenable: _clusterChangeNotifier, + boundsNotifier: _boundsNotifier, + minZoom: 2, + maxZoom: 16, + style: mapStyle, + decoratorBuilder: _decorateMap, + buttonPanelBuilder: _buildButtonPanel, + markerClusterBuilder: _buildMarkerClusters, + markerWidgetBuilder: _buildMarkerWidget, + dotLocationNotifier: widget.dotLocationNotifier, + markerSize: Size( + MapThemeData.markerImageExtent + MapThemeData.markerOuterBorderWidth * 2, + MapThemeData.markerImageExtent + MapThemeData.markerOuterBorderWidth * 2 + MapThemeData.markerArrowSize.height, + ), + dotMarkerSize: const Size( + MapThemeData.markerDotDiameter + MapThemeData.markerOuterBorderWidth * 2, + MapThemeData.markerDotDiameter + MapThemeData.markerOuterBorderWidth * 2, + ), + overlayOpacityNotifier: widget.overlayOpacityNotifier, + overlayEntry: widget.overlayEntry, + tracks: widget.tracks, + onUserZoomChange: widget.onUserZoomChange, + onMapTap: widget.onMapTap, + onMarkerTap: _onMarkerTap, + onMarkerLongPress: onMarkerLongPress, + ); + } + } else { + final overlay = Center( + child: OverlayTextButton( + onPressed: () => MapActionDelegate.selectStyle(context), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + const Icon(AIcons.layers), + const SizedBox(width: 8), + Text(context.l10n.mapStyleTooltip), + ], + ), + ), + ); + child = _decorateMap(context, overlay); + } + + final mapHeight = context.select<MapThemeData, double?>((v) => v.mapHeight); + child = Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // TODO TLAD [flutter vNext] wrap into `BackdropGroup` + mapHeight != null + ? SizedBox( + height: mapHeight, + child: child, + ) + : Expanded(child: child), + SafeArea( + top: false, + bottom: false, + child: Padding( + padding: context.select<MapThemeData, EdgeInsets>((v) => v.attributionPadding), + child: Attribution(style: mapStyle), + ), + ), + ], + ); + + return AnimatedSize( + alignment: Alignment.topCenter, + curve: Curves.easeInOutCubic, + duration: ADurations.mapStyleSwitchAnimation, + child: ValueListenableBuilder<bool>( + valueListenable: widget.isAnimatingNotifier, + builder: (context, animating, child) { + if (!animating && isHeavy) { + _heavyMapLoaded = true; + } + Widget replacement = Stack( + children: [ + const MapDecorator( + child: SizedBox(), + ), + _buildButtonPanel(context), + ], + ); + if (mapHeight != null) { + replacement = SizedBox( + height: mapHeight, + child: replacement, + ); + } + return Visibility( + visible: !isHeavy || _heavyMapLoaded, + replacement: replacement, + child: child!, + ); + }, + child: child, + ), + ); + }, + ); + } + + ZoomedBounds _initBounds() { + ZoomedBounds? bounds; + + final overlayEntry = widget.overlayEntry; + if (overlayEntry != null) { + // fit map to overlaid item + final corner1 = overlayEntry.topLeft; + final corner2 = overlayEntry.bottomRight; + if (corner1 != null && corner2 != null) { + bounds = ZoomedBounds.fromPoints( + points: {corner1, corner2}, + ); + } + } + + final initialZoom = widget.initialZoom ?? settings.infoMapZoom; + if (bounds == null) { + LatLng? centerToSave; + final initialCenter = widget.initialCenter; + if (initialCenter != null) { + // fit map for specified center and user zoom + bounds = ZoomedBounds.fromPoints( + points: {initialCenter}, + collocationZoom: initialZoom, + ); + centerToSave = initialCenter; + } else { + // fit map for all located items if possible, falling back to most recent items + bounds = _initBoundsForEntries(entries: entries); + centerToSave = bounds?.projectedCenter; + } + + if (centerToSave != null) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; + settings.mapDefaultCenter = centerToSave; + }); + } + } + if (bounds == null) { + // fallback to default center + var center = settings.mapDefaultCenter; + if (center == null) { + center = PointsOfInterest.wonders[Random().nextInt(PointsOfInterest.wonders.length)]; + WidgetsBinding.instance.addPostFrameCallback((_) => settings.mapDefaultCenter = center); + } + bounds = ZoomedBounds.fromPoints( + points: {center}, + collocationZoom: initialZoom, + ); + } + + return bounds.copyWith( + zoom: max(bounds.zoom, minInitialZoom), + ); + } + + ZoomedBounds? _initBoundsForEntries({required List<AvesEntry> entries, int? recentCount}) { + if (recentCount != null) { + entries = List.of(entries)..sort(AvesEntrySort.compareByDate); + entries = entries.take(recentCount).toList(); + } + + if (entries.isEmpty) return null; + + final points = entries.map((v) => v.latLng!).toSet(); + var bounds = ZoomedBounds.fromPoints( + points: points, + collocationZoom: settings.infoMapZoom, + ); + bounds = bounds.copyWith(zoom: max(minInitialZoom, bounds.zoom.floorToDouble())); + + final neededSize = bounds.toDisplaySize(); + final availableSize = widget.availableSize; + if (neededSize.width > availableSize.width || neededSize.height > availableSize.height) { + return _initBoundsForEntries(entries: entries, recentCount: (recentCount ?? 10000) ~/ 10); + } + return bounds; + } + + void _onCollectionChanged() { + _defaultMarkerCluster = _buildFluster(); + _slowMarkerCluster = null; + _clusterChangeNotifier.notify(); + } + + Fluster<GeoEntry<AvesEntry>> _buildFluster({int nodeSize = 64}) { + final markers = entries + .map((entry) { + final latLng = entry.latLng; + return latLng != null + ? GeoEntry<AvesEntry>( + entry: entry, + latitude: latLng.latitude, + longitude: latLng.longitude, + markerId: entry.uri, + ) + : null; + }) + .nonNulls + .toList(); + + return Fluster<GeoEntry<AvesEntry>>( + // we keep clustering on the whole range of zooms (including the maximum) + // to avoid collocated entries overlapping + minZoom: 0, + maxZoom: 22, + // TODO TLAD [map] derive `radius` / `extent`, from device pixel ratio and marker extent? + // (radius=120, extent=2 << 8) is equivalent to (radius=240, extent=2 << 9) + radius: 240, + extent: 2 << 9, + // node size: 64 by default, higher means faster indexing but slower search + nodeSize: nodeSize, + points: markers, + // use lambda instead of tear-off because of runtime exception when using + // `T Function(BaseCluster, double, double)` for `T Function(BaseCluster?, double?, double?)` + // ignore: unnecessary_lambdas + createCluster: (base, lng, lat) => GeoEntry<AvesEntry>.createCluster(base, lng, lat), + ); + } + + Map<MarkerKey<AvesEntry>, GeoEntry<AvesEntry>> _buildMarkerClusters() { + final bounds = _boundsNotifier.value; + final geoEntries = _defaultMarkerCluster?.clusters(bounds.boundingBox, bounds.zoom.round()) ?? []; + return Map.fromEntries(geoEntries.map((v) { + if (v.isCluster!) { + final uri = v.childMarkerId; + final entry = entries.firstWhere((v) => v.uri == uri); + return MapEntry(MarkerKey(entry, v.pointsSize), v); + } + return MapEntry(MarkerKey(v.entry!, null), v); + })); + } + + Set<AvesEntry> _getClusterEntries(GeoEntry<AvesEntry> geoEntry) { + final clusterId = geoEntry.clusterId; + if (clusterId == null) { + return {geoEntry.entry!}; + } + + var points = _defaultMarkerCluster?.points(clusterId) ?? []; + if (points.length != geoEntry.pointsSize) { + // `Fluster.points()` method does not always return all the points contained in a cluster + // the higher `nodeSize` is, the higher the chance to get all the points (i.e. as many as the cluster `pointsSize`) + _slowMarkerCluster ??= _buildFluster(nodeSize: smallestPowerOf2(entries.length).toInt()); + points = _slowMarkerCluster!.points(clusterId); + assert(points.length == geoEntry.pointsSize, 'got ${points.length}/${geoEntry.pointsSize} for geoEntry=$geoEntry'); + } + return points.map((geoEntry) => geoEntry.entry!).toSet(); + } + + void _onMarkerTap(GeoEntry<AvesEntry> geoEntry) { + final onTap = widget.onMarkerTap; + if (onTap == null) return; + + final clusterId = geoEntry.clusterId; + AvesEntry? markerEntry; + if (clusterId != null) { + final uri = geoEntry.childMarkerId; + markerEntry = entries.firstWhereOrNull((v) => v.uri == uri); + } else { + markerEntry = geoEntry.entry; + } + if (markerEntry == null) return; + + final markerLocation = LatLng(geoEntry.latitude!, geoEntry.longitude!); + onTap(markerLocation, markerEntry); + } + + Future<void> _onMarkerLongPress({ + required GeoEntry<AvesEntry> geoEntry, + required LatLng tapLocation, + required double devicePixelRatio, + }) async { + final onMarkerLongPress = widget.onMarkerLongPress; + if (onMarkerLongPress == null) return; + + final clusterEntries = _getClusterEntries(geoEntry); + final tapLocalPosition = _boundsNotifier.value.offset(tapLocation); + + AvesEntry markerEntry; + if (geoEntry.isCluster!) { + final uri = geoEntry.childMarkerId; + markerEntry = entries.firstWhere((v) => v.uri == uri); + } else { + markerEntry = geoEntry.entry!; + } + final locale = context.locale; + final markerLocation = LatLng(geoEntry.latitude!, geoEntry.longitude!); + Widget markerBuilder(BuildContext context) => ImageMarker( + count: geoEntry.pointsSize, + locale: locale, + drawArrow: false, + buildThumbnailImage: (extent) => ThumbnailImage( + entry: markerEntry, + extent: extent, + devicePixelRatio: devicePixelRatio, + ), + ); + onMarkerLongPress( + markerLocation, + markerEntry, + clusterEntries, + tapLocalPosition, + markerBuilder, + ); + } + + Widget _decorateMap(BuildContext context, Widget? child) => MapDecorator(child: child!); + + Widget _buildButtonPanel(BuildContext context) { + if (settings.useTvLayout) return const SizedBox(); + return MapButtonPanel( + controller: widget.controller, + boundsNotifier: _boundsNotifier, + openMapPage: widget.openMapPage, + ); + } +} diff --git a/lib/widgets/common/map/leaflet/latlng_tween.dart b/lib/widgets/common/map/leaflet/latlng_tween.dart new file mode 100644 index 0000000..1593c9c --- /dev/null +++ b/lib/widgets/common/map/leaflet/latlng_tween.dart @@ -0,0 +1,13 @@ +import 'package:aves/widgets/common/map/leaflet/latlng_utils.dart'; +import 'package:flutter/widgets.dart'; +import 'package:latlong2/latlong.dart'; + +class LatLngTween extends Tween<LatLng?> { + LatLngTween({ + required super.begin, + required super.end, + }); + + @override + LatLng? lerp(double t) => LatLngUtils.lerp(begin, end, t); +} diff --git a/lib/widgets/common/map/leaflet/latlng_utils.dart b/lib/widgets/common/map/leaflet/latlng_utils.dart new file mode 100644 index 0000000..adec5d1 --- /dev/null +++ b/lib/widgets/common/map/leaflet/latlng_utils.dart @@ -0,0 +1,14 @@ +import 'package:latlong2/latlong.dart'; + +class LatLngUtils { + static LatLng? lerp(LatLng? a, LatLng? b, double t) { + if (a == null && b == null) return null; + + final _a = a ?? const LatLng(0, 0); + final _b = b ?? const LatLng(0, 0); + return LatLng( + _a.latitude + (_b.latitude - _a.latitude) * t, + _a.longitude + (_b.longitude - _a.longitude) * t, + ); + } +} diff --git a/lib/widgets/common/map/leaflet/map.dart b/lib/widgets/common/map/leaflet/map.dart new file mode 100644 index 0000000..9e645dc --- /dev/null +++ b/lib/widgets/common/map/leaflet/map.dart @@ -0,0 +1,337 @@ +import 'dart:async'; +import 'dart:math'; + +import 'package:aves/model/device.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/utils/debouncer.dart'; +import 'package:aves/widgets/common/basic/gestures/gesture_detector.dart'; +import 'package:aves/widgets/common/map/leaflet/latlng_tween.dart' as llt; +import 'package:aves/widgets/common/map/leaflet/scale_layer.dart'; +import 'package:aves/widgets/common/map/leaflet/tile_layers.dart'; +import 'package:aves_map/aves_map.dart'; +import 'package:aves_utils/aves_utils.dart'; +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_map/flutter_map.dart'; +import 'package:latlong2/latlong.dart'; +import 'package:provider/provider.dart'; + +class EntryLeafletMap<T> extends StatefulWidget { + final AvesMapController controller; + final Listenable clusterListenable; + final ValueNotifier<ZoomedBounds> boundsNotifier; + final double minZoom, maxZoom; + final EntryMapStyle style; + final TransitionBuilder decoratorBuilder; + final WidgetBuilder buttonPanelBuilder; + final MarkerClusterBuilder<T> markerClusterBuilder; + final MarkerWidgetBuilder<T> markerWidgetBuilder; + final ValueNotifier<LatLng?>? dotLocationNotifier; + final Size markerSize, dotMarkerSize; + final ValueNotifier<double>? overlayOpacityNotifier; + final MapOverlay? overlayEntry; + final Set<List<LatLng>>? tracks; + final UserZoomChangeCallback? onUserZoomChange; + final MapTapCallback? onMapTap; + final MarkerTapCallback<T>? onMarkerTap; + final MarkerLongPressCallback<T>? onMarkerLongPress; + + const EntryLeafletMap({ + super.key, + required this.controller, + required this.clusterListenable, + required this.boundsNotifier, + this.minZoom = 0, + this.maxZoom = 22, + required this.style, + required this.decoratorBuilder, + required this.buttonPanelBuilder, + required this.markerClusterBuilder, + required this.markerWidgetBuilder, + required this.dotLocationNotifier, + required this.markerSize, + required this.dotMarkerSize, + this.overlayOpacityNotifier, + this.overlayEntry, + this.tracks, + this.onUserZoomChange, + this.onMapTap, + this.onMarkerTap, + this.onMarkerLongPress, + }); + + @override + State<EntryLeafletMap<T>> createState() => _EntryLeafletMapState<T>(); +} + +class _EntryLeafletMapState<T> extends State<EntryLeafletMap<T>> with TickerProviderStateMixin { + final MapController _leafletMapController = MapController(); + final Set<StreamSubscription> _subscriptions = {}; + Map<MarkerKey<T>, GeoEntry<T>> _geoEntryByMarkerKey = {}; + final Debouncer _debouncer = Debouncer(delay: ADurations.mapIdleDebounceDelay); + + ValueNotifier<ZoomedBounds> get boundsNotifier => widget.boundsNotifier; + + ZoomedBounds get bounds => boundsNotifier.value; + + // duration should match the uncustomizable Google map duration + static const _cameraAnimationDuration = Duration(milliseconds: 600); + + @override + void initState() { + super.initState(); + _registerWidget(widget); + WidgetsBinding.instance.addPostFrameCallback((_) => _updateVisibleRegion()); + } + + @override + void didUpdateWidget(covariant EntryLeafletMap<T> oldWidget) { + super.didUpdateWidget(oldWidget); + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + + @override + void dispose() { + _unregisterWidget(widget); + super.dispose(); + } + + void _registerWidget(EntryLeafletMap<T> widget) { + final avesMapController = widget.controller; + _subscriptions.add(avesMapController.moveCommands.listen((event) => _moveTo(event.latLng))); + _subscriptions.add(avesMapController.zoomCommands.listen((event) => _zoomBy(event.delta))); + _subscriptions.add(avesMapController.rotationResetCommands.listen((_) => _resetRotation())); + _subscriptions.add(_leafletMapController.mapEventStream.listen((_) => _updateVisibleRegion())); + widget.clusterListenable.addListener(_updateMarkers); + widget.boundsNotifier.addListener(_onBoundsChanged); + } + + void _unregisterWidget(EntryLeafletMap<T> widget) { + widget.clusterListenable.removeListener(_updateMarkers); + widget.boundsNotifier.removeListener(_onBoundsChanged); + _subscriptions + ..forEach((sub) => sub.cancel()) + ..clear(); + } + + @override + Widget build(BuildContext context) { + return Stack( + children: [ + widget.decoratorBuilder(context, _buildMap()), + widget.buttonPanelBuilder(context), + ], + ); + } + + Widget _buildMap() { + final markerSize = widget.markerSize; + final dotMarkerSize = widget.dotMarkerSize; + + final interactive = context.select<MapThemeData, bool>((v) => v.interactive); + + final markers = _geoEntryByMarkerKey.entries.map((kv) { + final markerKey = kv.key; + final geoEntry = kv.value; + final latLng = LatLng(geoEntry.latitude!, geoEntry.longitude!); + final onMarkerLongPress = widget.onMarkerLongPress; + final onLongPress = onMarkerLongPress != null ? Feedback.wrapForLongPress(() => onMarkerLongPress.call(geoEntry, LatLng(geoEntry.latitude!, geoEntry.longitude!)), context) : null; + return Marker( + point: latLng, + child: AGestureDetector( + onTap: () => widget.onMarkerTap?.call(geoEntry), + // marker tap handling prevents the default handling of focal zoom on double tap, + // so we reimplement the double tap gesture here + onDoubleTap: interactive ? () => _zoomBy(1, focalPoint: latLng) : null, + onLongPress: onLongPress, + // `MapInteractiveViewer` already declares a `LongPressGestureRecognizer` with the default delay (`kLongPressTimeout`), + // so this one should have a shorter delay to win in the gesture arena + longPressTimeout: Duration(milliseconds: min(settings.longPressTimeout.inMilliseconds, kLongPressTimeout.inMilliseconds)), + child: widget.markerWidgetBuilder(markerKey), + ), + width: markerSize.width, + height: markerSize.height, + alignment: Alignment.topCenter, + ); + }).toList(); + + return FlutterMap( + options: MapOptions( + initialCenter: bounds.projectedCenter, + initialZoom: bounds.zoom, + initialRotation: bounds.rotation, + minZoom: widget.minZoom, + maxZoom: widget.maxZoom, + backgroundColor: Colors.transparent, + interactionOptions: InteractionOptions( + // TODO TLAD [map] as of flutter_map v0.14.0, `doubleTapZoom` does not move when zoom is already maximal + // this could be worked around with https://github.com/fleaflet/flutter_map/pull/960 + flags: interactive ? InteractiveFlag.all : InteractiveFlag.none, + // prevent triggering multiple gestures at once (e.g. rotating a bit when mostly zooming) + enableMultiFingerGestureRace: true, + ), + onTap: (tapPosition, point) => widget.onMapTap?.call(point), + ), + mapController: _leafletMapController, + children: [ + _buildMapLayer(), + if (widget.overlayEntry != null) _buildOverlayImageLayer(), + if (widget.tracks != null) _buildTracksLayer(), + MarkerLayer( + markers: markers, + rotate: true, + alignment: Alignment.bottomCenter, + ), + NullableValueListenableBuilder<LatLng?>( + valueListenable: widget.dotLocationNotifier, + builder: (context, dotLocation, child) => MarkerLayer( + markers: [ + if (dotLocation != null) + Marker( + point: dotLocation, + child: const DotMarker(), + width: dotMarkerSize.width, + height: dotMarkerSize.height, + ) + ], + ), + ), + ScaleLayerWidget( + options: ScaleLayerOptions( + unitSystem: settings.unitSystem, + ), + ), + ], + ); + } + + Widget _buildMapLayer() { + final style = widget.style; + if (style == EntryMapStyles.osmLiberty) { + return const OsmLibertyLayer(); + } + + final urlTemplate = style.url; + if (urlTemplate != null) { + final userAgent = style.userAgent; + return TileLayer( + urlTemplate: urlTemplate, + subdomains: style.subdomains, + tileProvider: NetworkTileProvider( + headers: { + if (userAgent != null) 'User-Agent': userAgent, + }, + ), + // similar to `RetinaMode.isHighDensity` from `flutter_map`, but only rebuild for target aspect + retinaMode: MediaQuery.devicePixelRatioOf(context) > 1, + userAgentPackageName: device.userAgent, + ); + } + return const SizedBox(); + } + + Widget _buildOverlayImageLayer() { + final overlayEntry = widget.overlayEntry; + if (overlayEntry == null) return const SizedBox(); + + final corner1 = overlayEntry.topLeft; + final corner2 = overlayEntry.bottomRight; + if (corner1 == null || corner2 == null) return const SizedBox(); + + return NullableValueListenableBuilder<double>( + valueListenable: widget.overlayOpacityNotifier, + builder: (context, value, child) { + final double overlayOpacity = value ?? 1.0; + return OverlayImageLayer( + overlayImages: [ + OverlayImage( + bounds: LatLngBounds(corner1, corner2), + imageProvider: overlayEntry.imageProvider, + opacity: overlayOpacity, + ), + ], + ); + }, + ); + } + + Widget _buildTracksLayer() { + final tracks = widget.tracks; + if (tracks == null) return const SizedBox(); + + final trackColor = Theme.of(context).colorScheme.primary; + return PolylineLayer( + polylines: tracks + .map((v) => Polyline( + points: v, + strokeWidth: MapThemeData.trackWidth.toDouble(), + color: trackColor, + )) + .toList(), + ); + } + + void _onBoundsChanged() => _debouncer(_onIdle); + + void _onIdle() { + if (!mounted) return; + widget.controller.notifyIdle(bounds); + _updateMarkers(); + } + + void _updateMarkers() { + setState(() => _geoEntryByMarkerKey = widget.markerClusterBuilder()); + } + + void _updateVisibleRegion() { + final camera = _leafletMapController.camera; + final bounds = camera.visibleBounds; + boundsNotifier.value = ZoomedBounds( + sw: bounds.southWest, + ne: bounds.northEast, + zoom: camera.zoom, + rotation: camera.rotation, + ); + } + + Future<void> _resetRotation() async { + final rotation = _leafletMapController.camera.rotation; + // prevent multiple turns + final begin = (rotation.abs() % 360) * rotation.sign; + final rotationTween = Tween<double>(begin: begin, end: 0); + await _animateCamera((animation) => _leafletMapController.rotate(rotationTween.evaluate(animation))); + } + + Future<void> _zoomBy(double amount, {LatLng? focalPoint}) async { + final camera = _leafletMapController.camera; + final endZoom = (camera.zoom + amount).clamp(widget.minZoom, widget.maxZoom); + widget.onUserZoomChange?.call(endZoom); + + final center = camera.center; + final centerTween = llt.LatLngTween(begin: center, end: focalPoint ?? center); + + final zoomTween = Tween<double>(begin: camera.zoom, end: endZoom); + await _animateCamera((animation) => _leafletMapController.move(centerTween.evaluate(animation)!, zoomTween.evaluate(animation))); + } + + Future<void> _moveTo(LatLng point) async { + final camera = _leafletMapController.camera; + final centerTween = llt.LatLngTween(begin: camera.center, end: point); + await _animateCamera((animation) => _leafletMapController.move(centerTween.evaluate(animation)!, camera.zoom)); + } + + Future<void> _animateCamera(void Function(Animation<double> animation) animate) async { + final controller = AnimationController(duration: _cameraAnimationDuration, vsync: this); + final animation = CurvedAnimation(parent: controller, curve: Curves.fastOutSlowIn); + controller.addListener(() => animate(animation)); + animation.addStatusListener((status) { + if (!status.isAnimating) { + animation.dispose(); + controller.dispose(); + } + }); + await controller.forward(); + } +} diff --git a/lib/widgets/common/map/leaflet/scale_layer.dart b/lib/widgets/common/map/leaflet/scale_layer.dart new file mode 100644 index 0000000..03454b9 --- /dev/null +++ b/lib/widgets/common/map/leaflet/scale_layer.dart @@ -0,0 +1,163 @@ +import 'dart:math'; + +import 'package:aves/widgets/common/basic/text/outlined.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_map/flutter_map.dart'; +import 'package:latlong2/latlong.dart'; + +class ScaleLayerOptions { + final UnitSystem unitSystem; + final Widget Function(double width, String distance) builder; + + ScaleLayerOptions({ + this.unitSystem = UnitSystem.metric, + this.builder = defaultBuilder, + }); + + static Widget defaultBuilder(double width, String distance) { + return ScaleBar( + distance: distance, + width: width, + ); + } +} + +class ScaleLayerWidget extends StatelessWidget { + final ScaleLayerOptions options; + + final Distance _distanceCalculator = const Distance(); + + const ScaleLayerWidget({ + super.key, + required this.options, + }); + + static const List<double> scaleMeters = [ + 25000000, + 15000000, + 8000000, + 4000000, + 2000000, + 1000000, + 500000, + 250000, + 100000, + 50000, + 25000, + 15000, + 8000, + 4000, + 2000, + 1000, + 500, + 250, + 100, + 50, + 25, + 10, + 5, + ]; + + static const double metersInAKilometer = 1000; + static const double metersInAMile = 1609.344; + static const double metersInAFoot = 0.3048; + + @override + Widget build(BuildContext context) { + final map = MapCamera.of(context); + final center = map.center; + final latitude = center.latitude.abs(); + final level = map.zoom.round() + + (latitude > 80 + ? 4 + : latitude > 60 + ? 3 + : 2); + final scaleLevel = level.clamp(0, 20); + late final double distanceMeters; + late final String displayDistance; + switch (options.unitSystem) { + case UnitSystem.metric: + // meters + distanceMeters = scaleMeters[scaleLevel]; + displayDistance = distanceMeters >= metersInAKilometer ? '${(distanceMeters / metersInAKilometer).toStringAsFixed(0)} km' : '${distanceMeters.toStringAsFixed(0)} m'; + case UnitSystem.imperial: + if (scaleLevel < 15) { + // miles + final distanceMiles = scaleMeters[scaleLevel + 1] / 1000; + distanceMeters = distanceMiles * metersInAMile; + displayDistance = '${distanceMiles.toStringAsFixed(0)} mi'; + } else { + // feet + final distanceFeet = scaleMeters[scaleLevel - 1]; + distanceMeters = distanceFeet * metersInAFoot; + displayDistance = '${distanceFeet.toStringAsFixed(0)} ft'; + } + } + + final start = map.projectAtZoom(center); + final targetPoint = _distanceCalculator.offset(center, distanceMeters, 90); + final end = map.projectAtZoom(targetPoint); + final width = max(0, end.dx - start.dx).toDouble(); + + return options.builder(width, displayDistance); + } +} + +class ScaleBar extends StatelessWidget { + final String distance; + final double width; + + static const Color fillColor = Colors.black; + static const Color outlineColor = Colors.white; + static const double outlineWidth = .5; + static const double barThickness = 1; + + const ScaleBar({ + super.key, + required this.distance, + required this.width, + }); + + @override + Widget build(BuildContext context) { + return Container( + // keep `left` (and not `start`) because zoom buttons are kept right + // because `Google` logo on Google layers are always in the bottom left + alignment: Alignment.bottomLeft, + padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + OutlinedText( + textSpans: [ + TextSpan( + text: distance, + style: const TextStyle( + color: fillColor, + fontSize: 11, + ), + ) + ], + outlineWidth: outlineWidth * 2, + outlineColor: outlineColor, + ), + Container( + height: barThickness + outlineWidth * 2, + width: width, + decoration: const BoxDecoration( + color: fillColor, + border: Border.fromBorderSide(BorderSide( + color: outlineColor, + width: outlineWidth, + )), + borderRadius: BorderRadius.all(Radius.circular(8)), + ), + ), + ], + ), + ); + } +} diff --git a/lib/widgets/common/map/leaflet/tile_layers.dart b/lib/widgets/common/map/leaflet/tile_layers.dart new file mode 100644 index 0000000..916b781 --- /dev/null +++ b/lib/widgets/common/map/leaflet/tile_layers.dart @@ -0,0 +1,98 @@ +import 'dart:io' as io; + +import 'package:aves/services/common/services.dart'; +import 'package:aves/widgets/common/map/leaflet/vector_style_reader_extra.dart'; +import 'package:flutter/material.dart'; +import 'package:vector_map_tiles/src/io/io.dart' as vmtio show Directory; // ignore: implementation_imports +import 'package:vector_map_tiles/vector_map_tiles.dart'; +import 'package:vector_tile_renderer/vector_tile_renderer.dart' as vtr; + +class OsmLibertyLayer extends StatefulWidget { + const OsmLibertyLayer({super.key}); + + @override + State<OsmLibertyLayer> createState() => _OsmLibertyLayerState(); +} + +class _OsmLibertyLayerState extends State<OsmLibertyLayer> { + late final Future<TileProviders> _tileProviderFuture; + late final Future<Style> _styleFuture; + + static const _openMapTileProviderSource = 'openmaptiles'; + + // `Americana` provides tiles, but it uses layer syntax that is not supported by the vector tile renderer. + // Full style is at 'https://americanamap.org/style.json' but it is heavy (1.0 MB, mostly for the layers). + static const _americanaTileProviderUri = 'https://tile.ourmap.us/data/v3.json'; + + // `OSM Liberty` is well supported by the vector tile renderer, but it requires an API key for the tiles. + static const _osmLibertyStyleUri = 'https://maputnik.github.io/osm-liberty/style.json'; + + // as of 2024/09/25, + // Americana provider JSON: 39.4 kB + // OSM Liberty style JSON: 48.3 kB + // OSM Liberty sprites JSON 1x: 16.6 kB + // OSM Liberty sprites PNG 1x: 30.4 kB + // OSM Liberty sprites JSON 2x: 16.6 kB + // OSM Liberty sprites PNG 2x: 82.5 kB + // -> total overhead: 233.8 kB + + @override + void initState() { + super.initState(); + + _tileProviderFuture = ExtraStyleReader.readProviderByName( + { + _openMapTileProviderSource: { + 'url': _americanaTileProviderUri, + 'type': 'vector', + } + }, + ).then(TileProviders.new); + + _styleFuture = StyleReader( + uri: _osmLibertyStyleUri, + logger: const vtr.Logger.console(), + ).readExtra(skipSources: true); + } + + @override + Widget build(BuildContext context) { + return FutureBuilder<TileProviders>( + future: _tileProviderFuture, + builder: (context, tileProviderSnapshot) { + return FutureBuilder<Style>( + future: _styleFuture, + builder: (context, styleSnapshot) { + if (tileProviderSnapshot.hasError) return Text(tileProviderSnapshot.error.toString()); + if (styleSnapshot.hasError) return Text(styleSnapshot.error.toString()); + + final tileProviders = tileProviderSnapshot.data; + final style = styleSnapshot.data; + if (tileProviders == null || style == null) return const SizedBox(); + + return VectorTileLayer( + tileProviders: tileProviders, + theme: style.theme, + sprites: style.sprites, + // `vector` is higher quality and follows map orientation, but it is slower + layerMode: VectorTileLayerMode.raster, + cacheFolder: () async { + final cacheRoot = await storageService.getExternalCacheDirectory(); + final path = pContext.join(cacheRoot, 'map_vector_tiles'); + dynamic result; + if (vmtio.Directory == String) { + result = path; + } else if (vmtio.Directory == io.Directory) { + result = io.Directory(path); + } else { + throw Exception('vmtio.Directory type is not supported'); + } + return result; + }, + ); + }, + ); + }, + ); + } +} diff --git a/lib/widgets/common/map/leaflet/vector_style_reader_extra.dart b/lib/widgets/common/map/leaflet/vector_style_reader_extra.dart new file mode 100644 index 0000000..fa9b162 --- /dev/null +++ b/lib/widgets/common/map/leaflet/vector_style_reader_extra.dart @@ -0,0 +1,113 @@ +import 'dart:convert'; + +import 'package:flutter/foundation.dart'; +import 'package:http/http.dart'; +import 'package:latlong2/latlong.dart'; +import 'package:vector_map_tiles/vector_map_tiles.dart'; +import 'package:vector_tile_renderer/vector_tile_renderer.dart'; + +extension ExtraStyleReader on StyleReader { + Future<Style> readExtra({required bool skipSources}) async { + final styleText = await _httpGet(uri); + final style = await compute(jsonDecode, styleText); + if (style is! Map<String, dynamic>) { + throw _invalidStyle(uri); + } + final sources = style['sources'] as Map<String, dynamic>; + final Map<String, VectorTileProvider> providerByName = skipSources ? {} : await readProviderByName(sources); + final name = style['name'] as String?; + + final center = style['center']; + LatLng? centerPoint; + if (center is List && center.length == 2) { + centerPoint = LatLng((center[1] as num).toDouble(), (center[0] as num).toDouble()); + } + + double? zoom = (style['zoom'] as num?)?.toDouble(); + if (zoom != null && zoom < 2) { + zoom = null; + centerPoint = null; + } + + final spriteUri = style['sprite']; + SpriteStyle? sprites; + if (spriteUri is String && spriteUri.trim().isNotEmpty) { + final spriteUris = [ + _SpriteUri(json: '$spriteUri@2x.json?secure', image: '$spriteUri@2x.png?secure'), + _SpriteUri(json: '$spriteUri.json?secure', image: '$spriteUri.png?secure'), + ]; + for (final spriteUri in spriteUris) { + dynamic spritesJson; + try { + final spritesJsonText = await _httpGet(spriteUri.json); + spritesJson = await compute(jsonDecode, spritesJsonText); + } catch (e) { + logger.log(() => 'error reading sprite uri: ${spriteUri.json}'); + continue; + } + sprites = SpriteStyle(atlasProvider: () => _loadBinary(spriteUri.image), index: SpriteIndexReader(logger: logger).read(spritesJson)); + break; + } + } + return Style(theme: ThemeReader(logger: logger).read(style), providers: TileProviders(providerByName), sprites: sprites, name: name, center: centerPoint, zoom: zoom); + } + + static Future<Map<String, VectorTileProvider>> readProviderByName(Map<String, dynamic> sources) async { + final providers = <String, VectorTileProvider>{}; + final sourceEntries = sources.entries.toList(); + for (final entry in sourceEntries) { + final type = TileProviderType.values.where((e) => e.name == entry.value['type']).firstOrNull; + if (type == null) continue; + dynamic source; + var entryUrl = entry.value['url'] as String?; + if (entryUrl != null) { + final sourceUrl = entryUrl; + source = await compute(jsonDecode, await _httpGet(sourceUrl)); + if (source is! Map) { + throw _invalidStyle(sourceUrl); + } + } else { + source = entry.value; + } + final entryTiles = source['tiles']; + final maxzoom = source['maxzoom'] as int? ?? 14; + final minzoom = source['minzoom'] as int? ?? 1; + if (entryTiles is List && entryTiles.isNotEmpty) { + final tileUri = entryTiles[0] as String; + final tileUrl = tileUri; + providers[entry.key] = NetworkVectorTileProvider(type: type, urlTemplate: tileUrl, maximumZoom: maxzoom, minimumZoom: minzoom); + } + } + if (providers.isEmpty) { + throw 'Unexpected response'; + } + return providers; + } + + static String _invalidStyle(String url) => 'Uri does not appear to be a valid style: $url'; + + static Future<String> _httpGet(String url) async { + final response = await get(Uri.parse(url)); + if (response.statusCode == 200) { + return response.body; + } else { + throw 'HTTP ${response.statusCode}: ${response.body}'; + } + } + + static Future<Uint8List> _loadBinary(String url) async { + final response = await get(Uri.parse(url)); + if (response.statusCode == 200) { + return response.bodyBytes; + } else { + throw 'HTTP ${response.statusCode}: ${response.body}'; + } + } +} + +class _SpriteUri { + final String json; + final String image; + + const _SpriteUri({required this.json, required this.image}); +} diff --git a/lib/widgets/common/map/map_action_delegate.dart b/lib/widgets/common/map/map_action_delegate.dart new file mode 100644 index 0000000..d9183d7 --- /dev/null +++ b/lib/widgets/common/map/map_action_delegate.dart @@ -0,0 +1,92 @@ +import 'package:aves/geo/uri.dart'; +import 'package:aves/model/device.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/widgets/common/action_mixins/feedback.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/dialogs/add_shortcut_dialog.dart'; +import 'package:aves/widgets/dialogs/map/style_selection_dialog.dart'; +import 'package:aves/widgets/map/map_page.dart'; +import 'package:aves_map/aves_map.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class MapActionDelegate with FeedbackMixin { + final AvesMapController controller; + + const MapActionDelegate(this.controller); + + bool isVisible(BuildContext context, MapAction action) { + switch (action) { + case MapAction.selectStyle: + case MapAction.openMapApp: + case MapAction.zoomIn: + case MapAction.zoomOut: + return true; + case MapAction.addShortcut: + return device.canPinShortcut && context.currentRouteName == MapPage.routeName; + } + } + + void onActionSelected(BuildContext context, MapAction action) { + switch (action) { + case MapAction.selectStyle: + selectStyle(context); + case MapAction.openMapApp: + OpenMapAppNotification().dispatch(context); + case MapAction.zoomIn: + controller.zoomBy(1); + case MapAction.zoomOut: + controller.zoomBy(-1); + case MapAction.addShortcut: + _addShortcut(context); + } + } + + static void selectStyle(BuildContext context) { + Navigator.maybeOf(context)?.push<EntryMapStyle>( + MaterialPageRoute( + settings: const RouteSettings(name: MapStyleSelectionDialog.routeName), + builder: (context) => const MapStyleSelectionDialog(), + ), + ); + } + + Future<void> _addShortcut(BuildContext context) async { + final idleBounds = controller.idleBounds; + if (idleBounds == null) { + showFeedback(context, FeedbackType.warn, context.l10n.genericFailureFeedback); + return; + } + + final collection = context.read<CollectionLens>(); + final result = await showDialog<(AvesEntry?, String)>( + context: context, + builder: (context) => AddShortcutDialog( + defaultName: '', + collection: collection, + ), + routeSettings: const RouteSettings(name: AddShortcutDialog.routeName), + ); + if (result == null) return; + + final (coverEntry, name) = result; + if (name.isEmpty) return; + + final geoUri = toGeoUri(idleBounds.projectedCenter, zoom: idleBounds.zoom); + await appService.pinToHomeScreen( + name, + coverEntry, + route: MapPage.routeName, + filters: collection.filters, + geoUri: geoUri, + ); + if (!device.showPinShortcutFeedback) { + showFeedback(context, FeedbackType.info, context.l10n.genericSuccessFeedback); + } + } +} + +class OpenMapAppNotification extends Notification {} diff --git a/lib/widgets/common/providers/durations_provider.dart b/lib/widgets/common/providers/durations_provider.dart new file mode 100644 index 0000000..230af4e --- /dev/null +++ b/lib/widgets/common/providers/durations_provider.dart @@ -0,0 +1,14 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:provider/provider.dart'; + +class DurationsProvider extends ProxyProvider<Settings, DurationsData> { + DurationsProvider({ + super.key, + super.child, + }) : super( + update: (context, settings, __) { + return settings.animate ? DurationsData() : DurationsData.noAnimation(); + }, + ); +} diff --git a/lib/widgets/common/providers/filter_group_provider.dart b/lib/widgets/common/providers/filter_group_provider.dart new file mode 100644 index 0000000..884eae5 --- /dev/null +++ b/lib/widgets/common/providers/filter_group_provider.dart @@ -0,0 +1,17 @@ +import 'package:flutter/widgets.dart'; +import 'package:provider/provider.dart'; + +class FilterGroupProvider extends ListenableProvider<FilterGroupNotifier> { + FilterGroupProvider({ + super.key, + Uri? initialValue, + super.child, + }) : super( + create: (context) => FilterGroupNotifier(initialValue), + dispose: (context, value) => value.dispose(), + ); +} + +class FilterGroupNotifier extends ValueNotifier<Uri?> { + FilterGroupNotifier(super.value); +} diff --git a/lib/widgets/common/providers/highlight_info_provider.dart b/lib/widgets/common/providers/highlight_info_provider.dart new file mode 100644 index 0000000..9deccf7 --- /dev/null +++ b/lib/widgets/common/providers/highlight_info_provider.dart @@ -0,0 +1,11 @@ +import 'package:aves/model/highlight.dart'; +import 'package:provider/provider.dart'; + +class HighlightInfoProvider extends ChangeNotifierProvider<HighlightInfo> { + HighlightInfoProvider({ + super.key, + super.child, + }) : super( + create: (context) => HighlightInfo(), + ); +} diff --git a/lib/widgets/common/providers/map_theme_provider.dart b/lib/widgets/common/providers/map_theme_provider.dart new file mode 100644 index 0000000..919837d --- /dev/null +++ b/lib/widgets/common/providers/map_theme_provider.dart @@ -0,0 +1,90 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves_map/aves_map.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class MapTheme extends StatelessWidget { + final bool interactive, showCoordinateFilter; + final MapNavigationButton navigationButton; + final Animation<double> scale; + final VisualDensity visualDensity; + final double? mapHeight; + final EdgeInsets attributionPadding; + final Widget child; + + const MapTheme({ + super.key, + required this.interactive, + required this.showCoordinateFilter, + required this.navigationButton, + this.scale = kAlwaysCompleteAnimation, + this.visualDensity = VisualDensity.standard, + this.mapHeight, + this.attributionPadding = EdgeInsets.zero, + required this.child, + }); + + @override + Widget build(BuildContext context) { + return ProxyProvider<Settings, MapThemeData>( + update: (context, settings, __) { + return MapThemeData( + interactive: interactive, + showCoordinateFilter: showCoordinateFilter, + navigationButton: navigationButton, + scale: scale, + visualDensity: visualDensity, + mapHeight: mapHeight, + attributionPadding: attributionPadding, + ); + }, + child: child, + ); + } + + static Widget heroFlightShuttleBuilder( + BuildContext flightContext, + Animation<double> animation, + HeroFlightDirection flightDirection, + BuildContext fromHeroContext, + BuildContext toHeroContext, + ) { + final pushing = flightDirection == HeroFlightDirection.push; + final fromMediaQuery = MediaQuery.of(fromHeroContext); + final toMediaQuery = MediaQuery.of(toHeroContext); + final fromRenderBox = fromHeroContext.findRenderObject()! as RenderBox; + final toRenderBox = toHeroContext.findRenderObject()! as RenderBox; + final fromTheme = fromHeroContext.read<MapThemeData>(); + final toTheme = toHeroContext.read<MapThemeData>(); + + return DefaultTextStyle( + style: DefaultTextStyle.of(toHeroContext).style, + child: AnimatedBuilder( + animation: animation, + builder: (context, child) { + final t = pushing ? animation.value : 1 - animation.value; + return MapTheme( + interactive: false, + showCoordinateFilter: false, + navigationButton: toTheme.navigationButton, + visualDensity: VisualDensity.lerp(fromTheme.visualDensity, toTheme.visualDensity, t), + child: MediaQuery( + data: toMediaQuery.copyWith( + padding: EdgeInsets.lerp(fromMediaQuery.padding, toMediaQuery.padding, t), + viewPadding: EdgeInsets.lerp(fromMediaQuery.viewPadding, toMediaQuery.viewPadding, t), + ), + child: Align( + alignment: Alignment.topCenter, + child: SizedBox.fromSize( + size: Size.lerp(fromRenderBox.size, toRenderBox.size, t), + child: child, + ), + ), + ), + ); + }, + child: toHeroContext.widget, + ), + ); + } +} diff --git a/lib/widgets/common/providers/media_query_data_provider.dart b/lib/widgets/common/providers/media_query_data_provider.dart new file mode 100644 index 0000000..742c775 --- /dev/null +++ b/lib/widgets/common/providers/media_query_data_provider.dart @@ -0,0 +1,21 @@ +import 'package:flutter/widgets.dart'; +import 'package:provider/provider.dart'; + +class MediaQueryDataProvider extends StatelessWidget { + final MediaQueryData? value; + final Widget child; + + const MediaQueryDataProvider({ + super.key, + this.value, + required this.child, + }); + + @override + Widget build(BuildContext context) { + return Provider<MediaQueryData>.value( + value: value ?? MediaQuery.of(context), + child: child, + ); + } +} diff --git a/lib/widgets/common/providers/query_provider.dart b/lib/widgets/common/providers/query_provider.dart new file mode 100644 index 0000000..8c05061 --- /dev/null +++ b/lib/widgets/common/providers/query_provider.dart @@ -0,0 +1,27 @@ +import 'package:aves/model/query.dart'; +import 'package:flutter/widgets.dart'; +import 'package:provider/provider.dart'; + +class QueryProvider extends StatelessWidget { + final bool startEnabled; + final String? initialQuery; + final Widget child; + + const QueryProvider({ + super.key, + this.startEnabled = false, + this.initialQuery, + required this.child, + }); + + @override + Widget build(BuildContext context) { + return ChangeNotifierProvider<Query>( + create: (context) => Query( + enabled: startEnabled, + initialValue: initialQuery, + ), + child: child, + ); + } +} diff --git a/lib/widgets/common/providers/selection_provider.dart b/lib/widgets/common/providers/selection_provider.dart new file mode 100644 index 0000000..b1bd9b6 --- /dev/null +++ b/lib/widgets/common/providers/selection_provider.dart @@ -0,0 +1,20 @@ +import 'package:aves/model/selection.dart'; +import 'package:flutter/widgets.dart'; +import 'package:provider/provider.dart'; + +class SelectionProvider<T> extends StatelessWidget { + final Widget child; + + const SelectionProvider({ + super.key, + required this.child, + }); + + @override + Widget build(BuildContext context) { + return ChangeNotifierProvider<Selection<T>>( + create: (context) => Selection<T>(), + child: child, + ); + } +} diff --git a/lib/widgets/common/providers/tile_extent_controller_provider.dart b/lib/widgets/common/providers/tile_extent_controller_provider.dart new file mode 100644 index 0000000..0a5d45b --- /dev/null +++ b/lib/widgets/common/providers/tile_extent_controller_provider.dart @@ -0,0 +1,24 @@ +import 'package:aves/widgets/common/tile_extent_controller.dart'; +import 'package:flutter/widgets.dart'; +import 'package:provider/provider.dart'; + +class TileExtentControllerProvider extends StatelessWidget { + final TileExtentController controller; + final Widget child; + + const TileExtentControllerProvider({ + super.key, + required this.controller, + required this.child, + }); + + @override + Widget build(BuildContext context) { + return LayoutBuilder( + builder: (context, constraints) => ProxyProvider0<TileExtentController>( + update: (context, __) => controller..setViewportSize(constraints.biggest), + child: child, + ), + ); + } +} diff --git a/lib/widgets/common/providers/viewer_entry_provider.dart b/lib/widgets/common/providers/viewer_entry_provider.dart new file mode 100644 index 0000000..ca3ee34 --- /dev/null +++ b/lib/widgets/common/providers/viewer_entry_provider.dart @@ -0,0 +1,17 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:flutter/widgets.dart'; +import 'package:provider/provider.dart'; + +class ViewerEntryProvider extends ListenableProvider<ViewerEntryNotifier> { + ViewerEntryProvider({ + super.key, + super.child, + }) : super( + create: (context) => ViewerEntryNotifier(null), + dispose: (context, value) => value.dispose(), + ); +} + +class ViewerEntryNotifier extends ValueNotifier<AvesEntry?> { + ViewerEntryNotifier(super.value); +} diff --git a/lib/widgets/common/search/delegate.dart b/lib/widgets/common/search/delegate.dart new file mode 100644 index 0000000..e48a21f --- /dev/null +++ b/lib/widgets/common/search/delegate.dart @@ -0,0 +1,150 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/search/route.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:leak_tracker/leak_tracker.dart'; +import 'package:provider/provider.dart'; + +abstract class AvesSearchDelegate extends SearchDelegate { + final String routeName; + final bool canPop; + final TextEditingController queryTextController = TextEditingController(); + final ValueNotifier<SearchBody?> currentBodyNotifier = ValueNotifier(null); + + AvesSearchDelegate({ + required this.routeName, + this.canPop = true, + String? initialQuery, + required super.searchFieldLabel, + required super.searchFieldStyle, + }) { + if (kFlutterMemoryAllocationsEnabled) { + LeakTracking.dispatchObjectCreated( + library: 'aves', + className: '$AvesSearchDelegate', + object: this, + ); + } + query = initialQuery ?? ''; + } + + @override + Widget? buildLeading(BuildContext context) { + if (settings.useTvLayout) { + return const Icon(AIcons.search); + } + + // use a property instead of checking `Navigator.canPop(context)` + // because the navigator state changes as soon as we press back + // so the leading may mistakenly switch to the close button + final animate = context.read<Settings>().animate; + return canPop + ? IconButton( + icon: animate + ? AnimatedIcon( + icon: AnimatedIcons.menu_arrow, + progress: transitionAnimation, + ) + : const Icon(Icons.arrow_back), + onPressed: () => goBack(context), + tooltip: MaterialLocalizations.of(context).backButtonTooltip, + ) + : const CloseButton( + onPressed: SystemNavigator.pop, + ); + } + + @override + List<Widget>? buildActions(BuildContext context) { + return [ + if (!settings.useTvLayout && query.isNotEmpty) + IconButton( + icon: const Icon(AIcons.clear), + onPressed: () { + query = ''; + showSuggestions(context); + }, + tooltip: context.l10n.clearTooltip, + ), + ]; + } + + void goBack(BuildContext context) { + clean(); + Navigator.maybeOf(context)?.pop(); + } + + void clean() { + currentBody = null; + searchFieldFocusNode?.unfocus(); + } + + // adapted from Flutter `SearchDelegate` in `/material/search.dart` + + @override + void showResults(BuildContext context) { + if (settings.useTvLayout) { + suggestionsScrollController?.jumpTo(0); + WidgetsBinding.instance.addPostFrameCallback((_) { + suggestionsFocusNode?.requestFocus(); + FocusScope.of(context).nextFocus(); + }); + } else { + searchFieldFocusNode?.unfocus(); + currentBody = SearchBody.results; + } + } + + @override + void showSuggestions(BuildContext context) { + assert(searchFieldFocusNode != null, '_focusNode must be set by route before showSuggestions is called.'); + searchFieldFocusNode!.requestFocus(); + currentBody = SearchBody.suggestions; + } + + @override + Animation<double> get transitionAnimation => proxyAnimation; + + FocusNode? searchFieldFocusNode; + + FocusNode? get suggestionsFocusNode => null; + + ScrollController? get suggestionsScrollController => null; + + final ProxyAnimation proxyAnimation = ProxyAnimation(kAlwaysDismissedAnimation); + + @override + String get query => queryTextController.text; + + @override + set query(String value) { + queryTextController.text = value; + if (queryTextController.text.isNotEmpty) { + queryTextController.selection = TextSelection.fromPosition(TextPosition(offset: queryTextController.text.length)); + } + } + + SearchBody? get currentBody => currentBodyNotifier.value; + + set currentBody(SearchBody? value) { + currentBodyNotifier.value = value; + } + + SearchPageRoute? route; + + /// Releases the resources. + @override + @mustCallSuper + void dispose() { + if (kFlutterMemoryAllocationsEnabled) { + LeakTracking.dispatchObjectDisposed(object: this); + } + currentBodyNotifier.dispose(); + queryTextController.dispose(); + proxyAnimation.parent = null; + super.dispose(); + } +} diff --git a/lib/widgets/common/search/page.dart b/lib/widgets/common/search/page.dart new file mode 100644 index 0000000..7f218e6 --- /dev/null +++ b/lib/widgets/common/search/page.dart @@ -0,0 +1,173 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/utils/debouncer.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/behaviour/pop/double_back.dart'; +import 'package:aves/widgets/common/behaviour/pop/scope.dart'; +import 'package:aves/widgets/common/behaviour/pop/tv_navigation.dart'; +import 'package:aves/widgets/common/identity/aves_app_bar.dart'; +import 'package:aves/widgets/common/search/delegate.dart'; +import 'package:aves/widgets/common/search/route.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:provider/provider.dart'; + +class SearchPage extends StatefulWidget { + static const routeName = '/search'; + + final AvesSearchDelegate delegate; + final Animation<double> animation; + + const SearchPage({ + super.key, + required this.delegate, + required this.animation, + }); + + @override + State<SearchPage> createState() => _SearchPageState(); +} + +class _SearchPageState extends State<SearchPage> { + final Debouncer _debouncer = Debouncer(delay: ADurations.searchDebounceDelay); + final FocusNode _searchFieldFocusNode = FocusNode(); + + @override + void initState() { + super.initState(); + _registerWidget(widget); + widget.animation.addStatusListener(_onAnimationStatusChanged); + _searchFieldFocusNode.addListener(_onFocusChanged); + } + + @override + void didUpdateWidget(covariant SearchPage oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.delegate != widget.delegate) { + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + } + + @override + void dispose() { + _unregisterWidget(widget); + widget.animation.removeStatusListener(_onAnimationStatusChanged); + _searchFieldFocusNode.dispose(); + super.dispose(); + } + + void _registerWidget(SearchPage widget) { + widget.delegate.queryTextController.addListener(_onQueryChanged); + widget.delegate.currentBodyNotifier.addListener(_onSearchBodyChanged); + widget.delegate.searchFieldFocusNode = _searchFieldFocusNode; + } + + void _unregisterWidget(SearchPage widget) { + widget.delegate.queryTextController.removeListener(_onQueryChanged); + widget.delegate.currentBodyNotifier.removeListener(_onSearchBodyChanged); + widget.delegate.searchFieldFocusNode = null; + } + + void _onAnimationStatusChanged(AnimationStatus status) { + if (!status.isCompleted) { + return; + } + widget.animation.removeStatusListener(_onAnimationStatusChanged); + Future.delayed(ADurations.pageTransitionLoose * timeDilation).then((_) { + if (!mounted) return; + _searchFieldFocusNode.requestFocus(); + }); + } + + void _onFocusChanged() { + if (_searchFieldFocusNode.hasFocus && widget.delegate.currentBody != SearchBody.suggestions) { + widget.delegate.showSuggestions(context); + } + } + + void _onQueryChanged() { + _debouncer(() { + if (!mounted) return; + // rebuild ourselves because query changed. + setState(() {}); + }); + } + + void _onSearchBodyChanged() { + setState(() { + // rebuild ourselves because search body changed. + }); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + + Widget leading = Center(child: widget.delegate.buildLeading(context)); + Widget title = DefaultTextStyle.merge( + style: const TextStyle(fontFeatures: [FontFeature.disable('smcp')]), + child: TextField( + controller: widget.delegate.queryTextController, + focusNode: _searchFieldFocusNode, + decoration: InputDecoration( + border: InputBorder.none, + hintText: widget.delegate.searchFieldLabel, + hintStyle: theme.inputDecorationTheme.hintStyle, + ), + textInputAction: TextInputAction.search, + style: Themes.searchFieldStyle(context), + onSubmitted: (_) => widget.delegate.showResults(context), + ), + ); + Widget body; + switch (widget.delegate.currentBody) { + case SearchBody.suggestions: + body = KeyedSubtree( + key: const ValueKey<SearchBody>(SearchBody.suggestions), + child: widget.delegate.buildSuggestions(context), + ); + case SearchBody.results: + body = KeyedSubtree( + key: const ValueKey<SearchBody>(SearchBody.results), + child: widget.delegate.buildResults(context), + ); + case null: + body = const SizedBox(); + } + + final animate = context.select<Settings, bool>((v) => v.animate); + if (animate) { + leading = Hero( + tag: AvesAppBar.leadingHeroTag, + transitionOnUserGestures: true, + child: leading, + ); + title = Hero( + tag: AvesAppBar.titleHeroTag, + transitionOnUserGestures: true, + child: title, + ); + body = AnimatedSwitcher( + duration: ADurations.searchBodyTransition, + child: body, + ); + } + + return AvesScaffold( + appBar: AppBar( + leading: leading, + title: title, + actions: widget.delegate.buildActions(context), + ), + body: AvesPopScope( + handlers: [ + tvNavigationPopHandler, + doubleBackPopHandler, + ], + child: body, + ), + ); + } +} diff --git a/lib/widgets/common/search/route.dart b/lib/widgets/common/search/route.dart new file mode 100644 index 0000000..e69a1b8 --- /dev/null +++ b/lib/widgets/common/search/route.dart @@ -0,0 +1,90 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/widgets/common/search/delegate.dart'; +import 'package:aves/widgets/common/search/page.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +// adapted from Flutter `_SearchBody` in `/material/search.dart` +enum SearchBody { suggestions, results } + +// adapted from Flutter `_SearchPageRoute` in `/material/search.dart` +class SearchPageRoute<T> extends PageRoute<T> { + SearchPageRoute({ + required this.delegate, + }) : super(settings: RouteSettings(name: delegate.routeName)) { + assert( + delegate.route == null, + 'The ${delegate.runtimeType} instance is currently used by another active ' + 'search. Please close that search by calling close() on the SearchDelegate ' + 'before opening another search with the same delegate instance.', + ); + delegate.route = this; + } + + @override + void dispose() { + // `delegate` is always created by the caller at route creation time, + // so it should always be disposed when the route is disposed + delegate.dispose(); + super.dispose(); + } + + final AvesSearchDelegate delegate; + + @override + Color? get barrierColor => null; + + @override + String? get barrierLabel => null; + + @override + Duration get transitionDuration => const Duration(milliseconds: 300); + + @override + bool get maintainState => false; + + @override + Widget buildTransitions( + BuildContext context, + Animation<double> animation, + Animation<double> secondaryAnimation, + Widget child, + ) { + // a simple fade is usually more fitting for a search page, + // instead of the `pageTransitionsTheme` used by the rest of the app + final animate = context.read<Settings>().animate; + return animate + ? FadeTransition( + opacity: animation, + child: child, + ) + : child; + } + + @override + Animation<double> createAnimation() { + final Animation<double> animation = super.createAnimation(); + delegate.proxyAnimation.parent = animation; + return animation; + } + + @override + Widget buildPage( + BuildContext context, + Animation<double> animation, + Animation<double> secondaryAnimation, + ) { + return SearchPage( + delegate: delegate, + animation: animation, + ); + } + + @override + void didComplete(T? result) { + super.didComplete(result); + assert(delegate.route == this); + delegate.route = null; + delegate.currentBody = null; + } +} diff --git a/lib/widgets/common/thumbnail/decorated.dart b/lib/widgets/common/thumbnail/decorated.dart new file mode 100644 index 0000000..f4b4190 --- /dev/null +++ b/lib/widgets/common/thumbnail/decorated.dart @@ -0,0 +1,92 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/widgets/common/fx/borders.dart'; +import 'package:aves/widgets/common/grid/overlay.dart'; +import 'package:aves/widgets/common/grid/sections/mosaic/section_layout_builder.dart'; +import 'package:aves/widgets/common/thumbnail/image.dart'; +import 'package:aves/widgets/common/thumbnail/notifications.dart'; +import 'package:aves/widgets/common/thumbnail/overlay.dart'; +import 'package:flutter/material.dart'; + +class DecoratedThumbnail extends StatelessWidget { + final AvesEntry entry; + final double tileExtent; + final ValueNotifier<bool>? cancellableNotifier; + final bool isMosaic, selectable, highlightable; + final Object? Function()? heroTagger; + final HeroPlaceholderBuilder? heroPlaceholderBuilder; + final TransitionBuilder? imageDecorator; + + static Color borderColor(BuildContext context) => Theme.of(context).dividerColor; + + static double borderWidth(BuildContext context) => AvesBorder.straightBorderWidth(context); + + const DecoratedThumbnail({ + super.key, + required this.entry, + required this.tileExtent, + this.cancellableNotifier, + this.isMosaic = false, + this.selectable = true, + this.highlightable = true, + this.heroTagger, + this.heroPlaceholderBuilder, + this.imageDecorator, + }); + + @override + Widget build(BuildContext context) { + final double thumbnailHeight = tileExtent; + final double thumbnailWidth; + if (isMosaic) { + thumbnailWidth = thumbnailHeight * + entry.displayAspectRatio.clamp( + MosaicSectionLayoutBuilder.minThumbnailAspectRatio, + MosaicSectionLayoutBuilder.maxThumbnailAspectRatio, + ); + } else { + thumbnailWidth = tileExtent; + } + + Widget child = ThumbnailImage( + entry: entry, + extent: tileExtent, + devicePixelRatio: MediaQuery.devicePixelRatioOf(context), + isMosaic: isMosaic, + cancellableNotifier: cancellableNotifier, + heroTag: heroTagger?.call(), + heroPlaceholderBuilder: heroPlaceholderBuilder, + ); + + child = Stack( + fit: StackFit.passthrough, + children: [ + imageDecorator?.call(context, child) ?? child, + ThumbnailEntryOverlay(entry: entry), + if (selectable) ...[ + GridItemSelectionOverlay<AvesEntry>( + item: entry, + padding: const EdgeInsets.all(2), + ), + ThumbnailZoomOverlay( + onZoom: () => OpenViewerNotification(entry).dispatch(context), + ), + ], + if (highlightable) ThumbnailHighlightOverlay(entry: entry), + ], + ); + + return Container( + // `decoration` with sub logical pixel width yields scintillating borders + // so we use `foregroundDecoration` instead + foregroundDecoration: BoxDecoration( + border: Border.fromBorderSide(BorderSide( + color: borderColor(context), + width: borderWidth(context), + )), + ), + width: thumbnailWidth, + height: thumbnailHeight, + child: child, + ); + } +} diff --git a/lib/widgets/common/thumbnail/error.dart b/lib/widgets/common/thumbnail/error.dart new file mode 100644 index 0000000..9acc11b --- /dev/null +++ b/lib/widgets/common/thumbnail/error.dart @@ -0,0 +1,77 @@ +import 'dart:io'; +import 'dart:math'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/utils/mime_utils.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; + +class ErrorThumbnail extends StatefulWidget { + final AvesEntry entry; + final double extent; + + const ErrorThumbnail({ + super.key, + required this.entry, + required this.extent, + }); + + @override + State<ErrorThumbnail> createState() => _ErrorThumbnailState(); +} + +class _ErrorThumbnailState extends State<ErrorThumbnail> { + late Future<bool> _exists; + + AvesEntry get entry => widget.entry; + + double get extent => widget.extent; + + @override + void initState() { + super.initState(); + final path = entry.trashDetails?.path ?? entry.path; + _exists = path != null ? File(path).exists() : SynchronousFuture(true); + } + + @override + Widget build(BuildContext context) { + final color = Themes.backgroundTextColor(context); + return FutureBuilder<bool>( + future: _exists, + builder: (context, snapshot) { + Widget child; + if (snapshot.connectionState != ConnectionState.done) { + child = const SizedBox(); + } else { + final exists = snapshot.data!; + child = exists + ? LayoutBuilder(builder: (context, constraints) { + final fontSize = min(extent, constraints.biggest.width) / 5; + return Text( + MimeUtils.displayType(entry.mimeType), + style: TextStyle( + color: color, + fontSize: fontSize, + ), + textAlign: TextAlign.center, + ); + }) + : Icon( + AIcons.broken, + size: extent / 2, + color: color, + ); + } + return Container( + alignment: Alignment.center, + color: Themes.firstLayerColor(context), + width: extent, + height: extent, + child: child, + ); + }); + } +} diff --git a/lib/widgets/common/thumbnail/image.dart b/lib/widgets/common/thumbnail/image.dart new file mode 100644 index 0000000..db1a8a2 --- /dev/null +++ b/lib/widgets/common/thumbnail/image.dart @@ -0,0 +1,352 @@ +import 'dart:math'; + +import 'package:aves/image_providers/thumbnail_provider.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/images.dart'; +import 'package:aves/model/entry/extensions/props.dart'; +import 'package:aves/model/settings/enums/entry_background.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/widgets/common/basic/insets.dart'; +import 'package:aves/widgets/common/fx/checkered_decoration.dart'; +import 'package:aves/widgets/common/fx/transition_image.dart'; +import 'package:aves/widgets/common/grid/sections/mosaic/section_layout_builder.dart'; +import 'package:aves/widgets/common/providers/media_query_data_provider.dart'; +import 'package:aves/widgets/common/thumbnail/error.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class ThumbnailImage extends StatefulWidget { + final AvesEntry entry; + final double extent, devicePixelRatio; + final bool isMosaic, progressive; + final BoxFit? fit; + final bool showLoadingBackground; + final ValueNotifier<bool>? cancellableNotifier; + final Object? heroTag; + final HeroPlaceholderBuilder? heroPlaceholderBuilder; + + const ThumbnailImage({ + super.key, + required this.entry, + required this.extent, + required this.devicePixelRatio, + this.progressive = true, + this.isMosaic = false, + this.fit, + this.showLoadingBackground = true, + this.cancellableNotifier, + this.heroTag, + this.heroPlaceholderBuilder, + }); + + @override + State<ThumbnailImage> createState() => _ThumbnailImageState(); + + static Color computeLoadingBackgroundColor(int hashCode, Brightness brightness) { + var rgb = 0x30 + hashCode % 0x20; + if (brightness == Brightness.light) { + rgb = 0xFF - rgb; + } + return Color.fromARGB(0xFF, rgb, rgb, rgb); + } +} + +class _ThumbnailImageState extends State<ThumbnailImage> { + final _providers = <_ConditionalImageProvider>[]; + _ProviderStream? _currentProviderStream; + ImageInfo? _lastImageInfo; + Object? _lastException; + late final ImageStreamListener _streamListener; + + AvesEntry get entry => widget.entry; + + double get extent => widget.extent; + + bool get isMosaic => widget.isMosaic; + + @override + void initState() { + super.initState(); + _streamListener = ImageStreamListener(_onImageLoad, onError: _onError); + _registerWidget(widget); + } + + @override + void didUpdateWidget(covariant ThumbnailImage oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.entry != entry) { + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + } + + @override + void dispose() { + _unregisterWidget(widget); + super.dispose(); + } + + void _registerWidget(ThumbnailImage widget) { + // TODO TLAD [leak] `widget.entry.visualChangeNotifier` + widget.entry.visualChangeNotifier.addListener(_onVisualChanged); + _initProvider(); + } + + void _unregisterWidget(ThumbnailImage widget) { + widget.entry.visualChangeNotifier.removeListener(_onVisualChanged); + _pauseProvider(); + _currentProviderStream?.stopListening(); + _currentProviderStream = null; + _replaceImage(null); + } + + void _initProvider() { + if (!entry.isDecodingSupported) return; + + _lastException = null; + _providers.clear(); + + final highQuality = entry.getThumbnail(extent: extent); + ThumbnailProvider? lowQuality; + if (widget.progressive && !entry.isSvg) { + if (entry.isVideo) { + // previously fetched thumbnail + final cached = entry.bestCachedThumbnail; + final lowQualityExtent = cached.key.extent; + if (lowQualityExtent > 0 && lowQualityExtent != extent) { + lowQuality = cached; + } + } else { + // default platform thumbnail + lowQuality = entry.getThumbnail(); + } + } + _providers.addAll([ + if (lowQuality != null) + _ConditionalImageProvider( + lowQuality, + ), + _ConditionalImageProvider( + highQuality, + _needSizedProvider, + ), + ]); + _loadNextProvider(); + } + + void _loadNextProvider([ImageInfo? imageInfo]) { + final nextIndex = _currentProviderStream == null ? 0 : (_providers.indexOf(_currentProviderStream!.provider) + 1); + if (nextIndex < _providers.length) { + final provider = _providers[nextIndex]; + if (provider.predicate?.call(imageInfo) ?? true) { + _currentProviderStream?.stopListening(); + _currentProviderStream = _ProviderStream(provider, _streamListener); + _currentProviderStream!.startListening(); + } + } + } + + void _onImageLoad(ImageInfo imageInfo, bool synchronousCall) { + _replaceImage(imageInfo); + _loadNextProvider(imageInfo); + } + + void _replaceImage(ImageInfo? imageInfo) { + _lastImageInfo?.dispose(); + _lastImageInfo = imageInfo; + if (imageInfo != null) { + setState(() {}); + } + } + + void _onError(Object exception, StackTrace? stackTrace) { + if (!mounted) return; + setState(() => _lastException = exception); + } + + bool _needSizedProvider(ImageInfo? currentImageInfo) { + if (currentImageInfo == null) return true; + final currentImage = currentImageInfo.image; + final sizedThreshold = extent * widget.devicePixelRatio; + return sizedThreshold > min(currentImage.width, currentImage.height); + } + + void _pauseProvider() async { + if (widget.cancellableNotifier?.value ?? false) { + final key = await _currentProviderStream?.provider.provider.obtainKey(ImageConfiguration.empty); + if (key is ThumbnailProviderKey) { + mediaFetchService.cancelThumbnail(key); + } + } + } + + Color? _loadingBackgroundColor; + + Color loadingBackgroundColor(BuildContext context) { + _loadingBackgroundColor ??= ThumbnailImage.computeLoadingBackgroundColor(entry.uri.hashCode, Theme.of(context).brightness); + return _loadingBackgroundColor!; + } + + @override + Widget build(BuildContext context) { + final animate = context.select<Settings, bool>((v) => v.animate); + if (!entry.isDecodingSupported || _lastException != null) { + return _buildError(context, animate); + } + + // use `RawImage` instead of `Image`, using `ImageInfo` to check dimensions + // and have more control when chaining image providers + + final thumbnailHeight = extent; + final double thumbnailWidth; + if (isMosaic) { + thumbnailWidth = thumbnailHeight * + entry.displayAspectRatio.clamp( + MosaicSectionLayoutBuilder.minThumbnailAspectRatio, + MosaicSectionLayoutBuilder.maxThumbnailAspectRatio, + ); + } else { + thumbnailWidth = extent; + } + final canHaveAlpha = entry.canHaveAlpha; + + final fit = widget.fit ?? (entry.isSvg ? BoxFit.contain : BoxFit.cover); + final imageInfo = _lastImageInfo; + Widget image = imageInfo == null + ? Container( + color: widget.showLoadingBackground ? loadingBackgroundColor(context) : Colors.transparent, + width: thumbnailWidth, + height: thumbnailHeight, + ) + : Selector<Settings, EntryBackground>( + selector: (context, s) => s.imageBackground, + builder: (context, background, child) { + // avoid background color filter or layer when the entry cannot be transparent + final backgroundColor = canHaveAlpha && background.isColor ? background.color : null; + + if (canHaveAlpha && background == EntryBackground.checkered) { + return LayoutBuilder( + builder: (context, constraints) { + final availableSize = constraints.biggest; + final fitSize = applyBoxFit(fit, entry.displaySize, availableSize).destination; + final offset = (fitSize / 2 - availableSize / 2) as Offset; + final child = CustomPaint( + painter: CheckeredPainter(checkSize: extent / 8, offset: offset), + child: RawImage( + image: imageInfo.image, + debugImageLabel: imageInfo.debugLabel, + width: fitSize.width, + height: fitSize.height, + scale: imageInfo.scale, + fit: BoxFit.cover, + ), + ); + // the thumbnail is centered for correct decoration sizing + // when constraints are tight during hero animation + return constraints.isTight ? Center(child: child) : child; + }, + ); + } + + return RawImage( + image: imageInfo.image, + debugImageLabel: imageInfo.debugLabel, + width: thumbnailWidth, + height: thumbnailHeight, + scale: imageInfo.scale, + color: backgroundColor, + colorBlendMode: BlendMode.dstOver, + fit: fit, + ); + }, + ); + + final heroTag = widget.heroTag; + if (animate && heroTag != null) { + final background = settings.imageBackground; + final backgroundColor = background.isColor ? background.color : null; + image = Hero( + tag: heroTag, + flightShuttleBuilder: (flightContext, animation, flightDirection, fromHeroContext, toHeroContext) { + // as of Flutter v3.27.0-0.1.pre, the flight `animation` is incorrect when diverting a pop: + // - diverting a push (t = 0 -> 1) with a pop (t = 1 -> 0) works as expected (t = 0 -> [0,1] -> 0) + // - diverting a pop (t = 1 -> 0) with a push (t = 0 -> 1) finishes the pop (t = 1 -> [0,1] -> 0) instead of diverting (t = 1 -> [0,1] -> 1) + Widget child = TransitionImage( + image: entry.bestCachedThumbnail, + animation: animation, + thumbnailFit: BoxFit.cover, + viewerFit: BoxFit.contain, + background: backgroundColor, + ); + if (!settings.viewerUseCutout) { + child = SafeCutoutArea( + animation: animation, + child: child, + ); + } + return child; + }, + placeholderBuilder: widget.heroPlaceholderBuilder, + transitionOnUserGestures: true, + child: image, + ); + } + + return image; + } + + Widget _buildError(BuildContext context, bool animate) { + Widget child = ErrorThumbnail( + entry: entry, + extent: extent, + ); + + final heroTag = widget.heroTag; + if (animate && heroTag != null) { + child = Hero( + tag: heroTag, + flightShuttleBuilder: (flightContext, animation, flightDirection, fromHeroContext, toHeroContext) { + return MediaQueryDataProvider( + child: DefaultTextStyle( + style: DefaultTextStyle.of(toHeroContext).style, + child: toHeroContext.widget, + ), + ); + }, + transitionOnUserGestures: true, + child: child, + ); + } + + return child; + } + + // when the entry image itself changed (e.g. after rotation) + void _onVisualChanged() async { + // rebuild to refresh the thumbnails + _pauseProvider(); + _initProvider(); + setState(() {}); + } +} + +class _ConditionalImageProvider { + final ImageProvider provider; + final bool Function(ImageInfo?)? predicate; + + const _ConditionalImageProvider(this.provider, [this.predicate]); +} + +class _ProviderStream { + final _ConditionalImageProvider provider; + final ImageStream _stream; + final ImageStreamListener listener; + + _ProviderStream(this.provider, this.listener) : _stream = provider.provider.resolve(ImageConfiguration.empty); + + void startListening() => _stream.addListener(listener); + + void stopListening() => _stream.removeListener(listener); +} diff --git a/lib/widgets/common/thumbnail/notifications.dart b/lib/widgets/common/thumbnail/notifications.dart new file mode 100644 index 0000000..d5edca4 --- /dev/null +++ b/lib/widgets/common/thumbnail/notifications.dart @@ -0,0 +1,9 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:flutter/widgets.dart'; + +@immutable +class OpenViewerNotification extends Notification { + final AvesEntry entry; + + const OpenViewerNotification(this.entry); +} diff --git a/lib/widgets/common/thumbnail/overlay.dart b/lib/widgets/common/thumbnail/overlay.dart new file mode 100644 index 0000000..44ffe84 --- /dev/null +++ b/lib/widgets/common/thumbnail/overlay.dart @@ -0,0 +1,121 @@ +import 'dart:math'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/highlight.dart'; +import 'package:aves/model/selection.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/fx/sweeper.dart'; +import 'package:aves/widgets/common/grid/theme.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class ThumbnailEntryOverlay extends StatelessWidget { + final AvesEntry entry; + + const ThumbnailEntryOverlay({ + super.key, + required this.entry, + }); + + @override + Widget build(BuildContext context) { + final iconBuilder = context.select<GridThemeData, GridThemeIconBuilder>((t) => t.iconBuilder); + final children = iconBuilder(context, entry); + if (children.isEmpty) return const SizedBox(); + return Align( + alignment: AlignmentDirectional.bottomStart, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: children, + ), + ); + } +} + +class ThumbnailHighlightOverlay extends StatefulWidget { + final AvesEntry entry; + + const ThumbnailHighlightOverlay({ + super.key, + required this.entry, + }); + + @override + State<ThumbnailHighlightOverlay> createState() => _ThumbnailHighlightOverlayState(); +} + +class _ThumbnailHighlightOverlayState extends State<ThumbnailHighlightOverlay> { + final ValueNotifier<bool> _highlightedNotifier = ValueNotifier(false); + + AvesEntry get entry => widget.entry; + + static const startAngle = pi * -3 / 4; + + @override + void dispose() { + _highlightedNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final highlightInfo = context.watch<HighlightInfo>(); + _highlightedNotifier.value = highlightInfo.contains(entry); + return Sweeper( + builder: (context) => Container( + decoration: BoxDecoration( + border: Border.fromBorderSide(BorderSide( + color: Theme.of(context).colorScheme.primary, + width: context.select<GridThemeData, double>((t) => t.highlightBorderWidth), + )), + ), + ), + toggledNotifier: _highlightedNotifier, + startAngle: startAngle, + centerSweep: false, + onSweepEnd: highlightInfo.clear, + ); + } +} + +class ThumbnailZoomOverlay extends StatelessWidget { + final VoidCallback? onZoom; + + const ThumbnailZoomOverlay({ + super.key, + this.onZoom, + }); + + static const alignment = AlignmentDirectional.bottomEnd; + + @override + Widget build(BuildContext context) { + final duration = context.select<DurationsData, Duration>((v) => v.formTransition); + final isSelecting = context.select<Selection<AvesEntry>, bool>((selection) => selection.isSelecting); + final interactiveDimension = context.select<GridThemeData, double>((t) => t.interactiveDimension); + return AnimatedSwitcher( + duration: duration, + child: isSelecting + ? Align( + alignment: alignment, + child: GestureDetector( + onTap: onZoom, + child: Container( + alignment: alignment, + padding: const EdgeInsets.symmetric(vertical: 1, horizontal: 2), + width: interactiveDimension, + height: interactiveDimension, + child: Icon( + AIcons.showFullscreenArrows, + size: context.select<GridThemeData, double>((t) => t.iconSize), + color: Colors.white70, + ), + ), + ), + ) + : const SizedBox(), + ); + } +} diff --git a/lib/widgets/common/thumbnail/scroller.dart b/lib/widgets/common/thumbnail/scroller.dart new file mode 100644 index 0000000..c0adf63 --- /dev/null +++ b/lib/widgets/common/thumbnail/scroller.dart @@ -0,0 +1,206 @@ +import 'dart:math'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/widgets/common/behaviour/known_extent_scroll_physics.dart'; +import 'package:aves/widgets/common/grid/theme.dart'; +import 'package:aves/widgets/common/thumbnail/decorated.dart'; +import 'package:flutter/material.dart'; + +class ThumbnailScroller extends StatefulWidget { + final double availableWidth; + final int entryCount; + final AvesEntry? Function(int index) entryBuilder; + final ValueNotifier<int?> indexNotifier; + final void Function(int index)? onTap; + final Object? Function(AvesEntry entry)? heroTagger; + final bool scrollable, highlightable, showLocation; + + const ThumbnailScroller({ + super.key, + required this.availableWidth, + required this.entryCount, + required this.entryBuilder, + required this.indexNotifier, + this.onTap, + this.heroTagger, + this.highlightable = false, + this.showLocation = true, + this.scrollable = true, + }); + + @override + State<ThumbnailScroller> createState() => _ThumbnailScrollerState(); + + static double get preferredHeight => _ThumbnailScrollerState.thumbnailExtent; +} + +class _ThumbnailScrollerState extends State<ThumbnailScroller> { + final ValueNotifier<bool> _cancellableNotifier = ValueNotifier(true); + late ScrollController _scrollController; + bool _isAnimating = false, _isScrolling = false; + + static const double thumbnailExtent = 48; + static const double separatorWidth = 2; + static const double itemExtent = thumbnailExtent + separatorWidth; + + int get entryCount => widget.entryCount; + + ValueNotifier<int?> get indexNotifier => widget.indexNotifier; + + bool get scrollable => widget.scrollable; + + static double widthFor(int pageCount) => pageCount == 0 ? 0 : pageCount * thumbnailExtent + (pageCount - 1) * separatorWidth; + + @override + void initState() { + super.initState(); + _registerWidget(widget); + } + + @override + void didUpdateWidget(covariant ThumbnailScroller oldWidget) { + super.didUpdateWidget(oldWidget); + + if (oldWidget.indexNotifier != widget.indexNotifier) { + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + } + + @override + void dispose() { + _unregisterWidget(widget); + _cancellableNotifier.dispose(); + super.dispose(); + } + + void _registerWidget(ThumbnailScroller widget) { + final scrollOffset = indexToScrollOffset(indexNotifier.value ?? 0); + _scrollController = ScrollController(initialScrollOffset: scrollOffset); + _scrollController.addListener(_onScrollChanged); + widget.indexNotifier.addListener(_onIndexChanged); + } + + void _unregisterWidget(ThumbnailScroller widget) { + _scrollController.removeListener(_onScrollChanged); + _scrollController.dispose(); + widget.indexNotifier.removeListener(_onIndexChanged); + } + + @override + Widget build(BuildContext context) { + final marginWidth = max(0.0, (widget.availableWidth - thumbnailExtent) / 2 - separatorWidth); + final padding = scrollable ? EdgeInsets.only(left: marginWidth + separatorWidth, right: marginWidth) : EdgeInsets.zero; + + return GridTheme( + extent: thumbnailExtent, + showLocation: widget.showLocation, + showTrash: false, + child: SizedBox( + width: scrollable ? null : widthFor(entryCount), + height: thumbnailExtent, + child: ListView.builder( + scrollDirection: Axis.horizontal, + controller: _scrollController, + // as of Flutter v2.10.2, `FixedExtentScrollController` can only be used with `ListWheelScrollView` + // and `FixedExtentScrollPhysics` can only be used with Scrollables that uses the `FixedExtentScrollController` + // so we use `KnownExtentScrollPhysics`, adapted from `FixedExtentScrollPhysics` without the constraints + physics: scrollable + ? KnownExtentScrollPhysics( + indexToScrollOffset: indexToScrollOffset, + scrollOffsetToIndex: scrollOffsetToIndex, + ) + : const NeverScrollableScrollPhysics(), + padding: padding, + itemExtent: itemExtent, + itemBuilder: (context, index) => _buildThumbnail(index), + itemCount: entryCount, + ), + ), + ); + } + + Widget _buildThumbnail(int index) { + final pageEntry = widget.entryBuilder(index); + if (pageEntry == null) return const SizedBox(); + + return Stack( + children: [ + GestureDetector( + onTap: () { + indexNotifier.value = index; + widget.onTap?.call(index); + }, + child: DecoratedThumbnail( + entry: pageEntry, + tileExtent: thumbnailExtent, + // the retrieval task queue can pile up for thumbnails of heavy pages + // (e.g. thumbnails of 15MP HEIF images inside 100MB+ HEIC containers) + // so we cancel these requests when possible + cancellableNotifier: _cancellableNotifier, + selectable: false, + highlightable: widget.highlightable, + heroTagger: () => widget.heroTagger?.call(pageEntry), + ), + ), + IgnorePointer( + child: ValueListenableBuilder<int?>( + valueListenable: indexNotifier, + builder: (context, currentIndex, child) { + return AnimatedContainer( + color: currentIndex == index ? Colors.transparent : Colors.black45, + width: thumbnailExtent, + height: thumbnailExtent, + duration: ADurations.thumbnailScrollerShadeAnimation, + ); + }, + ), + ), + ], + ); + } + + Future<void> _goTo(int index) async { + if (!scrollable) return; + + final targetOffset = indexToScrollOffset(index); + final offsetDelta = (targetOffset - _scrollController.offset).abs(); + + if (offsetDelta > widget.availableWidth * 2) { + _scrollController.jumpTo(targetOffset); + } else { + _isAnimating = true; + await _scrollController.animateTo( + targetOffset, + duration: ADurations.thumbnailScrollerScrollAnimation, + curve: Curves.easeOutCubic, + ); + _isAnimating = false; + } + } + + void _onScrollChanged() { + if (!_isAnimating) { + final index = scrollOffsetToIndex(_scrollController.offset); + if (indexNotifier.value != index) { + _isScrolling = true; + indexNotifier.value = index; + } + } + } + + void _onIndexChanged() { + if (!_isScrolling && !_isAnimating) { + final index = indexNotifier.value; + if (index != null) { + _goTo(index); + } + } + _isScrolling = false; + } + + double indexToScrollOffset(int index) => index * itemExtent; + + int scrollOffsetToIndex(double offset) => (offset / itemExtent).round(); +} diff --git a/lib/widgets/common/tile_extent_controller.dart b/lib/widgets/common/tile_extent_controller.dart new file mode 100644 index 0000000..bf4567d --- /dev/null +++ b/lib/widgets/common/tile_extent_controller.dart @@ -0,0 +1,126 @@ +import 'dart:async'; +import 'dart:math'; + +import 'package:aves/model/settings/settings.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:flutter/widgets.dart'; +import 'package:leak_tracker/leak_tracker.dart'; + +class TileExtentController { + final String settingsRouteKey; + final int columnCountMin, columnCountDefault; + final double extentMin, extentMax, spacing, horizontalPadding; + late final ValueNotifier<double> extentNotifier; + + late double userPreferredExtent; + Size _viewportSize = Size.zero; + final Set<StreamSubscription> _subscriptions = {}; + + Size get viewportSize => _viewportSize; + + TileExtentController({ + required this.settingsRouteKey, + this.columnCountMin = 2, + required this.columnCountDefault, + required this.extentMin, + required this.extentMax, + required this.spacing, + required this.horizontalPadding, + }) { + if (kFlutterMemoryAllocationsEnabled) { + LeakTracking.dispatchObjectCreated( + library: 'aves', + className: '$TileExtentController', + object: this, + ); + } + // initialize extent to 0, so that it will be dynamically sized on first launch + extentNotifier = ValueNotifier(0); + userPreferredExtent = settings.getTileExtent(settingsRouteKey); + _subscriptions.add(settings.updateTileExtentStream.listen((_) => _onSettingsChanged())); + } + + void dispose() { + if (kFlutterMemoryAllocationsEnabled) { + LeakTracking.dispatchObjectDisposed(object: this); + } + _subscriptions + ..forEach((sub) => sub.cancel()) + ..clear(); + } + + void _onSettingsChanged() { + if (userPreferredExtent != settings.getTileExtent(settingsRouteKey)) { + _update(); + } + } + + void setViewportSize(Size viewportSize) { + // sanitize screen size (useful when reloading while screen is off, reporting a 0,0 size) + final viewportSizeMin = Size.square(extentMin * columnCountMin); + // dimensions are rounded to prevent updates on minor changes + // e.g. available space on S10e is `Size(360.0, 721.0)` when status bar is visible, `Size(360.0, 721.3)` when it is not + final newViewportSize = Size(max(viewportSize.width, viewportSizeMin.width).roundToDouble(), max(viewportSize.height, viewportSizeMin.height).roundToDouble()); + if (_viewportSize != newViewportSize) { + _viewportSize = newViewportSize; + _update(); + } + } + + double setUserPreferredColumnCount(int columnCount) => _update(userPreferredExtent: _extentForColumnCount(columnCount)); + + double setUserPreferredExtent(double extent) => _update(userPreferredExtent: extent.roundToDouble()); + + double _update({double? userPreferredExtent}) { + final preferredExtent = userPreferredExtent ?? settings.getTileExtent(settingsRouteKey); + final targetExtent = preferredExtent > 0 ? preferredExtent : extentNotifier.value; + + final columnCount = _effectiveColumnCountForExtent(targetExtent); + final newExtent = _extentForColumnCount(columnCount).clamp(effectiveExtentMin, effectiveExtentMax); + + if (this.userPreferredExtent != preferredExtent) { + this.userPreferredExtent = preferredExtent; + settings.setTileExtent(settingsRouteKey, preferredExtent); + } + if (extentNotifier.value != newExtent) { + extentNotifier.value = newExtent; + } + return newExtent; + } + + double _extentMax() => min(extentMax, (viewportSize.shortestSide - (horizontalPadding * 2) - spacing * (columnCountMin - 1)) / columnCountMin); + + double _columnCountForExtent(double extent) => (viewportSize.width - (horizontalPadding * 2) + spacing) / (extent + spacing); + + double _extentForColumnCount(int columnCount) => (viewportSize.width - (horizontalPadding * 2) - spacing * (columnCount - 1)) / columnCount; + + int _effectiveColumnCountMin() => max(columnCountMin, _columnCountForExtent(_extentMax()).ceil()); + + int _effectiveColumnCountMax() => max(columnCountMin, _columnCountForExtent(extentMin).floor()); + + int _effectiveColumnCountForExtent(double extent) { + if (extent > 0) { + final columnCount = _columnCountForExtent(extent); + final countMax = _effectiveColumnCountMax(); + final countMin = min(_effectiveColumnCountMin(), countMax); + return columnCount.round().clamp(countMin, countMax); + } + return columnCountDefault; + } + + double get effectiveExtentMin => min(_extentForColumnCount(_effectiveColumnCountMax()), effectiveExtentMax); + + double get effectiveExtentMax => _extentForColumnCount(_effectiveColumnCountMin()); + + (int min, int max) get effectiveColumnRange => (_effectiveColumnCountMin(), _effectiveColumnCountMax()); + + int get columnCount => _effectiveColumnCountForExtent(extentNotifier.value); + + Duration getTileAnimationDelay(Duration pageTarget) { + final extent = extentNotifier.value; + final columnCount = ((viewportSize.width - (horizontalPadding * 2) + spacing) / (extent + spacing)).round(); + final rowCount = (viewportSize.height + spacing) ~/ (extent + spacing); + return pageTarget ~/ (columnCount + rowCount) * timeDilation; + } +} diff --git a/lib/widgets/debug/app_debug_action.dart b/lib/widgets/debug/app_debug_action.dart new file mode 100644 index 0000000..d126cce --- /dev/null +++ b/lib/widgets/debug/app_debug_action.dart @@ -0,0 +1,7 @@ +enum AppDebugAction { + prepScreenshotThumbnails, + prepScreenshotStats, + prepScreenshotCountries, + mediaStoreScanDir, + greenScreen, +} diff --git a/lib/widgets/debug/app_debug_page.dart b/lib/widgets/debug/app_debug_page.dart new file mode 100644 index 0000000..3678b6b --- /dev/null +++ b/lib/widgets/debug/app_debug_page.dart @@ -0,0 +1,136 @@ +import 'dart:async'; + +import 'package:aves/model/favourites.dart'; +import 'package:aves/model/filters/covered/location.dart'; +import 'package:aves/model/filters/covered/tag.dart'; +import 'package:aves/model/filters/path.dart'; +import 'package:aves/model/settings/enums/accessibility_animations.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/widgets/common/basic/font_size_icon_theme.dart'; +import 'package:aves/widgets/common/basic/popup/menu_row.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/behaviour/pop/scope.dart'; +import 'package:aves/widgets/common/behaviour/pop/tv_navigation.dart'; +import 'package:aves/widgets/debug/app_debug_action.dart'; +import 'package:aves/widgets/debug/cache.dart'; +import 'package:aves/widgets/debug/capabilities.dart'; +import 'package:aves/widgets/debug/colors.dart'; +import 'package:aves/widgets/debug/database.dart'; +import 'package:aves/widgets/debug/general.dart'; +import 'package:aves/widgets/debug/leaking.dart'; +import 'package:aves/widgets/debug/media_store_scan_dialog.dart'; +import 'package:aves/widgets/debug/os_apps.dart'; +import 'package:aves/widgets/debug/os_codecs.dart'; +import 'package:aves/widgets/debug/os_paths.dart'; +import 'package:aves/widgets/debug/os_storage.dart'; +import 'package:aves/widgets/debug/report.dart'; +import 'package:aves/widgets/debug/settings.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:provider/provider.dart'; + +class AppDebugPage extends StatelessWidget { + static const routeName = '/debug'; + + const AppDebugPage({super.key}); + + @override + Widget build(BuildContext context) { + final animations = context.select<Settings, AccessibilityAnimations>((v) => v.accessibilityAnimations); + return Directionality( + textDirection: TextDirection.ltr, + child: AvesScaffold( + appBar: AppBar( + title: const Text('Debug'), + actions: [ + FontSizeIconTheme( + child: PopupMenuButton<AppDebugAction>( + // key is expected by test driver + key: const Key('appbar-menu-button'), + itemBuilder: (context) => AppDebugAction.values + .map((v) => PopupMenuItem( + // key is expected by test driver + key: Key('menu-${v.name}'), + value: v, + child: MenuRow(text: v.name), + )) + .toList(), + onSelected: (action) async { + // wait for the popup menu to hide before proceeding with the action + await Future.delayed(animations.popUpAnimationDelay * timeDilation); + unawaited(_onActionSelected(context, action)); + }, + popUpAnimationStyle: animations.popUpAnimationStyle, + ), + ), + ], + ), + body: AvesPopScope( + handlers: [tvNavigationPopHandler], + child: SafeArea( + child: ListView( + padding: const EdgeInsets.all(8), + children: const [ + DebugGeneralSection(), + DebugLeakingSection(), + DebugCacheSection(), + DebugCapabilitiesSection(), + DebugColorSection(), + DebugAppDatabaseSection(), + DebugErrorReportingSection(), + DebugSettingsSection(), + DebugOSAppSection(), + DebugOSCodecSection(), + DebugOSPathSection(), + DebugOSStorageSection(), + ], + ), + ), + ), + ), + ); + } + + Future<void> _onActionSelected(BuildContext context, AppDebugAction action) async { + switch (action) { + case AppDebugAction.prepScreenshotThumbnails: + // get source beforehand, as widget may be unmounted during action handling + final source = context.read<CollectionSource>(); + settings.changeFilterVisibility(settings.hiddenFilters, true); + settings.changeFilterVisibility({ + TagFilter('aves-thumbnail', reversed: true), + }, false); + await favourites.clear(); + await favourites.add(source.visibleEntries); + case AppDebugAction.prepScreenshotStats: + settings.changeFilterVisibility(settings.hiddenFilters, true); + settings.changeFilterVisibility({ + PathFilter('/storage/emulated/0/Pictures/Dev'), + }, false); + case AppDebugAction.prepScreenshotCountries: + settings.changeFilterVisibility({ + LocationFilter(LocationLevel.country, 'Belgium;BE'), + LocationFilter(LocationLevel.country, 'Croatia;HR'), + }, false); + case AppDebugAction.mediaStoreScanDir: + // scan files copied from test assets + // we do it via the app instead of broadcasting via ADB + // because `MEDIA_SCANNER_SCAN_FILE` intent got deprecated in API 29 + await showDialog<String>( + context: context, + builder: (context) => const MediaStoreScanDirDialog(), + ); + case AppDebugAction.greenScreen: + await Navigator.maybeOf(context)?.push( + MaterialPageRoute( + builder: (context) => const Scaffold( + backgroundColor: Colors.green, + body: SizedBox(), + ), + ), + ); + } + } +} diff --git a/lib/widgets/debug/cache.dart b/lib/widgets/debug/cache.dart new file mode 100644 index 0000000..419e3c0 --- /dev/null +++ b/lib/widgets/debug/cache.dart @@ -0,0 +1,116 @@ +import 'package:aves/ref/locales.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/utils/file_utils.dart'; +import 'package:aves/widgets/common/identity/aves_expansion_tile.dart'; +import 'package:flutter/material.dart'; + +class DebugCacheSection extends StatefulWidget { + const DebugCacheSection({super.key}); + + @override + State<DebugCacheSection> createState() => _DebugCacheSectionState(); +} + +class _DebugCacheSectionState extends State<DebugCacheSection> with AutomaticKeepAliveClientMixin { + final TextEditingController _imageCacheSizeTextController = TextEditingController(); + + @override + void initState() { + super.initState(); + _imageCacheSizeTextController.text = '${imageCache.maximumSizeBytes}'; + } + + @override + void dispose() { + _imageCacheSizeTextController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + super.build(context); + + final currentSizeBytes = formatFileSize(asciiLocale, imageCache.currentSizeBytes); + final maxSizeBytes = formatFileSize(asciiLocale, imageCache.maximumSizeBytes); + return AvesExpansionTile( + title: 'Cache', + children: [ + Padding( + padding: const EdgeInsets.symmetric(horizontal: 8), + child: Column( + children: [ + Row( + children: [ + Expanded( + child: Text('Image cache:\n\t${imageCache.currentSize}/${imageCache.maximumSize} items\n\t$currentSizeBytes/$maxSizeBytes'), + ), + const SizedBox(width: 8), + ElevatedButton( + onPressed: () { + imageCache.clear(); + + setState(() {}); + }, + child: const Text('Clear'), + ), + ], + ), + Row( + children: [ + Expanded( + child: TextField( + controller: _imageCacheSizeTextController, + decoration: const InputDecoration(labelText: 'imageCache size bytes'), + keyboardType: TextInputType.number, + ), + ), + const SizedBox(width: 8), + ElevatedButton( + onPressed: () { + final size = int.tryParse(_imageCacheSizeTextController.text); + if (size != null) { + imageCache.maximumSizeBytes = size; + } else { + _imageCacheSizeTextController.text = '${imageCache.maximumSizeBytes}'; + } + setState(() {}); + }, + child: const Text('Apply'), + ), + ], + ), + const Divider(), + Row( + children: [ + const Expanded( + child: Text('Glide disk cache: ?'), + ), + const SizedBox(width: 8), + ElevatedButton( + onPressed: mediaFetchService.clearImageDiskCache, + child: const Text('Clear'), + ), + ], + ), + Row( + children: [ + const Expanded( + child: Text('Glide memory cache: ?'), + ), + const SizedBox(width: 8), + ElevatedButton( + onPressed: mediaFetchService.clearImageMemoryCache, + child: const Text('Clear'), + ), + ], + ), + ], + ), + ), + ], + ); + } + + @override + bool get wantKeepAlive => true; +} diff --git a/lib/widgets/debug/capabilities.dart b/lib/widgets/debug/capabilities.dart new file mode 100644 index 0000000..449d8f2 --- /dev/null +++ b/lib/widgets/debug/capabilities.dart @@ -0,0 +1,136 @@ +import 'package:aves/model/device.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/widgets/common/identity/aves_expansion_tile.dart'; +import 'package:aves/widgets/common/identity/highlight_title.dart'; +import 'package:aves/widgets/viewer/info/common.dart'; +import 'package:flutter/material.dart'; + +class DebugCapabilitiesSection extends StatefulWidget { + const DebugCapabilitiesSection({super.key}); + + @override + State<DebugCapabilitiesSection> createState() => _DebugCapabilitiesSectionState(); +} + +class _DebugCapabilitiesSectionState extends State<DebugCapabilitiesSection> with AutomaticKeepAliveClientMixin { + late final Future<List<dynamic>> _appFuture, _windowFuture; + + @override + void initState() { + super.initState(); + _appFuture = Future.wait([ + appProfileService.canInteractAcrossProfiles(), + appProfileService.canRequestInteractAcrossProfiles(), + appProfileService.getTargetUserProfiles(), + ]); + _windowFuture = Future.wait([ + windowService.isCutoutAware(), + windowService.isRotationLocked(), + windowService.supportsHdr(), + windowService.supportsWideGamut(), + ]); + } + + @override + Widget build(BuildContext context) { + super.build(context); + return AvesExpansionTile( + title: 'Capabilities', + children: [ + Padding( + padding: const EdgeInsets.symmetric(horizontal: 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const HighlightTitle(title: 'Device'), + InfoRowGroup( + info: { + 'canAuthenticateUser': '${device.canAuthenticateUser}', + 'canPinShortcut': '${device.canPinShortcut}', + 'canRenderFlagEmojis': '${device.canRenderFlagEmojis}', + 'canRenderSubdivisionFlagEmojis': '${device.canRenderSubdivisionFlagEmojis}', + 'canRequestManageMedia': '${device.canRequestManageMedia}', + 'canSetLockScreenWallpaper': '${device.canSetLockScreenWallpaper}', + 'hasGeocoder': '${device.hasGeocoder}', + 'isDynamicColorAvailable': '${device.isDynamicColorAvailable}', + 'isTelevision': '${device.isTelevision}', + 'showPinShortcutFeedback': '${device.showPinShortcutFeedback}', + 'supportEdgeToEdgeUIMode': '${device.supportEdgeToEdgeUIMode}', + 'supportPictureInPicture': '${device.supportPictureInPicture}', + }, + ), + ], + ), + ), + FutureBuilder<List<dynamic>>( + future: _windowFuture, + builder: (context, snapshot) { + final data = snapshot.data; + if (data == null) { + return const SizedBox(); + } + final [ + bool isCutoutAware, + bool isRotationLocked, + bool supportsHdr, + bool supportsWideGamut, + ] = data; + + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const HighlightTitle(title: 'Window'), + InfoRowGroup( + info: { + 'isCutoutAware': '$isCutoutAware', + 'isRotationLocked': '$isRotationLocked', + 'supportsHdr': '$supportsHdr', + 'supportsWideGamut': '$supportsWideGamut', + }, + ), + ], + ), + ); + }, + ), + FutureBuilder<List<dynamic>>( + future: _appFuture, + builder: (context, snapshot) { + final data = snapshot.data; + if (data == null) { + return const SizedBox(); + } + final [ + bool canInteractAcrossProfiles, + bool canRequestInteractAcrossProfiles, + List<String> targetUserProfiles, + ] = data; + + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const HighlightTitle(title: 'App'), + InfoRowGroup( + info: { + 'userAgent': device.userAgent, + 'canInteractAcrossProfiles': '$canInteractAcrossProfiles', + 'canRequestInteractAcrossProfiles': '$canRequestInteractAcrossProfiles', + 'targetUserProfiles': '$targetUserProfiles', + }, + ), + ], + ), + ); + }, + ), + ], + ); + } + + @override + bool get wantKeepAlive => true; +} diff --git a/lib/widgets/debug/colors.dart b/lib/widgets/debug/colors.dart new file mode 100644 index 0000000..52bebdc --- /dev/null +++ b/lib/widgets/debug/colors.dart @@ -0,0 +1,99 @@ +import 'package:aves/widgets/common/identity/aves_expansion_tile.dart'; +import 'package:flex_color_picker/flex_color_picker.dart'; +import 'package:flutter/material.dart'; + +class DebugColorSection extends StatefulWidget { + const DebugColorSection({super.key}); + + @override + State<DebugColorSection> createState() => _DebugColorSectionState(); +} + +class _DebugColorSectionState extends State<DebugColorSection> with AutomaticKeepAliveClientMixin { + @override + Widget build(BuildContext context) { + super.build(context); + + final scheme = Theme.of(context).colorScheme; + final List<(String, Color)> colors = [ + ('primary', scheme.primary), + ('onPrimary', scheme.onPrimary), + ('primaryContainer', scheme.primaryContainer), + ('onPrimaryContainer', scheme.onPrimaryContainer), + ('primaryFixed', scheme.primaryFixed), + ('primaryFixedDim', scheme.primaryFixedDim), + ('onPrimaryFixed', scheme.onPrimaryFixed), + ('onPrimaryFixedVariant', scheme.onPrimaryFixedVariant), + ('secondary', scheme.secondary), + ('onSecondary', scheme.onSecondary), + ('secondaryContainer', scheme.secondaryContainer), + ('onSecondaryContainer', scheme.onSecondaryContainer), + ('secondaryFixed', scheme.secondaryFixed), + ('secondaryFixedDim', scheme.secondaryFixedDim), + ('onSecondaryFixed', scheme.onSecondaryFixed), + ('onSecondaryFixedVariant', scheme.onSecondaryFixedVariant), + ('tertiary', scheme.tertiary), + ('onTertiary', scheme.onTertiary), + ('tertiaryContainer', scheme.tertiaryContainer), + ('onTertiaryContainer', scheme.onTertiaryContainer), + ('tertiaryFixed', scheme.tertiaryFixed), + ('tertiaryFixedDim', scheme.tertiaryFixedDim), + ('onTertiaryFixed', scheme.onTertiaryFixed), + ('onTertiaryFixedVariant', scheme.onTertiaryFixedVariant), + ('error', scheme.error), + ('onError', scheme.onError), + ('errorContainer', scheme.errorContainer), + ('onErrorContainer', scheme.onErrorContainer), + ('surface', scheme.surface), + ('onSurface', scheme.onSurface), + ('surfaceDim', scheme.surfaceDim), + ('surfaceBright', scheme.surfaceBright), + ('surfaceContainerLowest', scheme.surfaceContainerLowest), + ('surfaceContainerLow', scheme.surfaceContainerLow), + ('surfaceContainer', scheme.surfaceContainer), + ('surfaceContainerHigh', scheme.surfaceContainerHigh), + ('surfaceContainerHighest', scheme.surfaceContainerHighest), + ('onSurfaceVariant', scheme.onSurfaceVariant), + ('outline', scheme.outline), + ('outlineVariant', scheme.outlineVariant), + ('shadow', scheme.shadow), + ('scrim', scheme.scrim), + ('inverseSurface', scheme.inverseSurface), + ('onInverseSurface', scheme.onInverseSurface), + ('inversePrimary', scheme.inversePrimary), + ('surfaceTint', scheme.surfaceTint), + ]; + return AvesExpansionTile( + title: 'Colors', + children: [ + Padding( + padding: const EdgeInsets.symmetric(horizontal: 8), + child: Column( + children: colors.map((kv) { + final (text, color) = kv; + return Row( + children: [ + Text(text), + const Spacer(), + Text( + color.hex, + style: const TextStyle(fontFamily: 'monospace'), + ), + const SizedBox(width: 4), + Container( + width: 20, + height: 20, + color: color, + ), + ], + ); + }).toList(), + ), + ), + ], + ); + } + + @override + bool get wantKeepAlive => true; +} diff --git a/lib/widgets/debug/database.dart b/lib/widgets/debug/database.dart new file mode 100644 index 0000000..42bdb60 --- /dev/null +++ b/lib/widgets/debug/database.dart @@ -0,0 +1,343 @@ +import 'package:aves/model/covers.dart'; +import 'package:aves/model/dynamic_albums.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/favourites.dart'; +import 'package:aves/model/metadata/address.dart'; +import 'package:aves/model/metadata/catalog.dart'; +import 'package:aves/model/metadata/trash.dart'; +import 'package:aves/model/vaults/details.dart'; +import 'package:aves/model/vaults/vaults.dart'; +import 'package:aves/model/viewer/video_playback.dart'; +import 'package:aves/ref/locales.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/utils/file_utils.dart'; +import 'package:aves/widgets/common/identity/aves_expansion_tile.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; + +class DebugAppDatabaseSection extends StatefulWidget { + const DebugAppDatabaseSection({super.key}); + + @override + State<DebugAppDatabaseSection> createState() => _DebugAppDatabaseSectionState(); +} + +class _DebugAppDatabaseSectionState extends State<DebugAppDatabaseSection> with AutomaticKeepAliveClientMixin { + late Future<int> _dbFileSizeLoader; + late Future<Set<AvesEntry>> _dbEntryLoader; + late Future<Map<int?, int?>> _dbDateLoader; + late Future<Set<CatalogMetadata>> _dbMetadataLoader; + late Future<Set<AddressDetails>> _dbAddressLoader; + late Future<Set<TrashDetails>> _dbTrashLoader; + late Future<Set<VaultDetails>> _dbVaultsLoader; + late Future<Set<FavouriteRow>> _dbFavouritesLoader; + late Future<Set<CoverRow>> _dbCoversLoader; + late Future<Set<DynamicAlbumRow>> _dbDynamicAlbumsLoader; + late Future<Set<VideoPlaybackRow>> _dbVideoPlaybackLoader; + + @override + void initState() { + super.initState(); + _startDbReport(); + } + + @override + void dispose() { + _disposeLoadedContent(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + super.build(context); + + return AvesExpansionTile( + title: 'Database', + children: [ + Padding( + padding: const EdgeInsets.symmetric(horizontal: 8), + child: Column( + children: [ + FutureBuilder<int>( + future: _dbFileSizeLoader, + builder: (context, snapshot) { + if (snapshot.hasError) return Text(snapshot.error.toString()); + + if (snapshot.connectionState != ConnectionState.done) return const SizedBox(); + + return Row( + children: [ + Expanded( + child: Text('DB file size: ${formatFileSize(asciiLocale, snapshot.data!)}'), + ), + const SizedBox(width: 8), + ElevatedButton( + onPressed: () => localMediaDb.reset().then((_) => _reload()), + child: const Text('Reset'), + ), + ], + ); + }, + ), + FutureBuilder<Set<AvesEntry>>( + future: _dbEntryLoader, + builder: (context, snapshot) { + if (snapshot.hasError) return Text(snapshot.error.toString()); + + if (snapshot.connectionState != ConnectionState.done) return const SizedBox(); + + final entries = snapshot.data!; + final byOrigin = groupBy<AvesEntry, int>(entries, (entry) => entry.origin); + return Row( + children: [ + Expanded( + child: Text('entry rows: ${entries.length} (${byOrigin.entries.map((kv) => '${kv.key}: ${kv.value.length}').join(', ')})'), + ), + const SizedBox(width: 8), + ElevatedButton( + onPressed: () => localMediaDb.clearEntries().then((_) => _reload()), + child: const Text('Clear'), + ), + ], + ); + }, + ), + FutureBuilder<Map<int?, int?>>( + future: _dbDateLoader, + builder: (context, snapshot) { + if (snapshot.hasError) return Text(snapshot.error.toString()); + + if (snapshot.connectionState != ConnectionState.done) return const SizedBox(); + + return Row( + children: [ + Expanded( + child: Text('date rows: ${snapshot.data!.length}'), + ), + const SizedBox(width: 8), + ElevatedButton( + onPressed: () => localMediaDb.clearDates().then((_) => _reload()), + child: const Text('Clear'), + ), + ], + ); + }, + ), + FutureBuilder<Set>( + future: _dbMetadataLoader, + builder: (context, snapshot) { + if (snapshot.hasError) return Text(snapshot.error.toString()); + + if (snapshot.connectionState != ConnectionState.done) return const SizedBox(); + + return Row( + children: [ + Expanded( + child: Text('metadata rows: ${snapshot.data!.length}'), + ), + const SizedBox(width: 8), + ElevatedButton( + onPressed: () => localMediaDb.clearCatalogMetadata().then((_) => _reload()), + child: const Text('Clear'), + ), + ], + ); + }, + ), + FutureBuilder<Set>( + future: _dbAddressLoader, + builder: (context, snapshot) { + if (snapshot.hasError) return Text(snapshot.error.toString()); + + if (snapshot.connectionState != ConnectionState.done) return const SizedBox(); + + return Row( + children: [ + Expanded( + child: Text('address rows: ${snapshot.data!.length}'), + ), + const SizedBox(width: 8), + ElevatedButton( + onPressed: () => localMediaDb.clearAddresses().then((_) => _reload()), + child: const Text('Clear'), + ), + ], + ); + }, + ), + FutureBuilder<Set>( + future: _dbTrashLoader, + builder: (context, snapshot) { + if (snapshot.hasError) return Text(snapshot.error.toString()); + + if (snapshot.connectionState != ConnectionState.done) return const SizedBox(); + + return Row( + children: [ + Expanded( + child: Text('trash rows: ${snapshot.data!.length}'), + ), + const SizedBox(width: 8), + ElevatedButton( + onPressed: () => localMediaDb.clearTrashDetails().then((_) => _reload()), + child: const Text('Clear'), + ), + ], + ); + }, + ), + FutureBuilder<Set>( + future: _dbVaultsLoader, + builder: (context, snapshot) { + if (snapshot.hasError) return Text(snapshot.error.toString()); + + if (snapshot.connectionState != ConnectionState.done) return const SizedBox(); + + return Row( + children: [ + Expanded( + child: Text('vault rows: ${snapshot.data!.length} (${vaults.all.length} in memory)'), + ), + const SizedBox(width: 8), + ElevatedButton( + onPressed: () => vaults.clear().then((_) => _reload()), + child: const Text('Clear'), + ), + ], + ); + }, + ), + FutureBuilder<Set>( + future: _dbFavouritesLoader, + builder: (context, snapshot) { + if (snapshot.hasError) return Text(snapshot.error.toString()); + + if (snapshot.connectionState != ConnectionState.done) return const SizedBox(); + + return Row( + children: [ + Expanded( + child: Text('favourite rows: ${snapshot.data!.length} (${favourites.count} in memory)'), + ), + const SizedBox(width: 8), + ElevatedButton( + onPressed: () => favourites.clear().then((_) => _reload()), + child: const Text('Clear'), + ), + ], + ); + }, + ), + FutureBuilder<Set>( + future: _dbCoversLoader, + builder: (context, snapshot) { + if (snapshot.hasError) return Text(snapshot.error.toString()); + + if (snapshot.connectionState != ConnectionState.done) return const SizedBox(); + + return Row( + children: [ + Expanded( + child: Text('covers: ${snapshot.data!.length} rows\n(${covers.count} in memory)'), + ), + const SizedBox(width: 8), + ElevatedButton( + onPressed: () => localMediaDb.loadAllCovers().then((list) { + debugPrint('covers dump start'); + list.forEach((v) => debugPrint(' $v')); + debugPrint('covers albums dump end'); + }), + child: const Text('Dump'), + ), + ElevatedButton( + onPressed: () => covers.clear().then((_) => _reload()), + child: const Text('Clear'), + ), + ], + ); + }, + ), + FutureBuilder<Set>( + future: _dbDynamicAlbumsLoader, + builder: (context, snapshot) { + if (snapshot.hasError) return Text(snapshot.error.toString()); + + if (snapshot.connectionState != ConnectionState.done) return const SizedBox(); + + return Row( + children: [ + Expanded( + child: Text('dynamic albums: ${snapshot.data!.length} rows\n(${dynamicAlbums.count} in memory)'), + ), + const SizedBox(width: 8), + ElevatedButton( + onPressed: () => localMediaDb.loadAllDynamicAlbums().then((list) { + debugPrint('dynamic albums dump start'); + list.forEach((v) => debugPrint(' $v')); + debugPrint('dynamic albums dump end'); + }), + child: const Text('Dump'), + ), + ElevatedButton( + onPressed: () => dynamicAlbums.clear().then((_) => _reload()), + child: const Text('Clear'), + ), + ], + ); + }, + ), + FutureBuilder<Set>( + future: _dbVideoPlaybackLoader, + builder: (context, snapshot) { + if (snapshot.hasError) return Text(snapshot.error.toString()); + + if (snapshot.connectionState != ConnectionState.done) return const SizedBox(); + + return Row( + children: [ + Expanded( + child: Text('video playback rows: ${snapshot.data!.length}'), + ), + const SizedBox(width: 8), + ElevatedButton( + onPressed: () => localMediaDb.clearVideoPlayback().then((_) => _reload()), + child: const Text('Clear'), + ), + ], + ); + }, + ), + ], + ), + ), + ], + ); + } + + Future<void> _reload() async { + await _disposeLoadedContent(); + _startDbReport(); + } + + void _startDbReport() { + _dbFileSizeLoader = localMediaDb.dbFileSize(); + _dbEntryLoader = localMediaDb.loadEntries(); + _dbDateLoader = localMediaDb.loadDates(); + _dbMetadataLoader = localMediaDb.loadCatalogMetadata(); + _dbAddressLoader = localMediaDb.loadAddresses(); + _dbTrashLoader = localMediaDb.loadAllTrashDetails(); + _dbVaultsLoader = localMediaDb.loadAllVaults(); + _dbFavouritesLoader = localMediaDb.loadAllFavourites(); + _dbCoversLoader = localMediaDb.loadAllCovers(); + _dbDynamicAlbumsLoader = localMediaDb.loadAllDynamicAlbums(); + _dbVideoPlaybackLoader = localMediaDb.loadAllVideoPlayback(); + setState(() {}); + } + + Future<void> _disposeLoadedContent() async { + (await _dbEntryLoader).forEach((v) => v.dispose()); + } + + @override + bool get wantKeepAlive => true; +} diff --git a/lib/widgets/debug/general.dart b/lib/widgets/debug/general.dart new file mode 100644 index 0000000..458c9fc --- /dev/null +++ b/lib/widgets/debug/general.dart @@ -0,0 +1,136 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/services/analysis_service.dart'; +import 'package:aves/services/common/service_policy.dart'; +import 'package:aves/widgets/common/identity/aves_expansion_tile.dart'; +import 'package:aves/widgets/settings/common/tiles.dart'; +import 'package:aves/widgets/viewer/info/common.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:provider/provider.dart'; + +class DebugGeneralSection extends StatefulWidget { + const DebugGeneralSection({super.key}); + + @override + State<DebugGeneralSection> createState() => _DebugGeneralSectionState(); +} + +class _DebugGeneralSectionState extends State<DebugGeneralSection> with AutomaticKeepAliveClientMixin { + static OverlayEntry? _taskQueueOverlayEntry; + + @override + Widget build(BuildContext context) { + super.build(context); + + final source = context.read<CollectionSource>(); + final visibleEntries = source.visibleEntries; + final catalogued = visibleEntries.where((entry) => entry.isCatalogued); + final withGps = catalogued.where((entry) => entry.hasGps); + final withAddress = withGps.where((entry) => entry.hasAddress); + final withFineAddress = withGps.where((entry) => entry.hasFineAddress); + + return AvesExpansionTile( + title: 'General', + children: [ + const Padding( + padding: EdgeInsets.all(8), + child: Text('Time dilation'), + ), + Slider( + value: timeDilation, + onChanged: (v) => setState(() => timeDilation = v), + min: 1.0, + max: 10.0, + divisions: 9, + label: '$timeDilation', + ), + SwitchListTile( + value: _taskQueueOverlayEntry != null, + onChanged: (v) { + _taskQueueOverlayEntry + ?..remove() + ..dispose(); + _taskQueueOverlayEntry = null; + if (v) { + _taskQueueOverlayEntry = OverlayEntry( + builder: (context) => const _TaskQueueOverlay(), + ); + Overlay.of(context).insert(_taskQueueOverlayEntry!); + } + setState(() {}); + }, + title: const Text('Show tasks overlay'), + ), + SettingsSwitchListTile( + selector: (context, s) => s.debugShowViewerTiles, + onChanged: (v) => settings.debugShowViewerTiles = v, + title: 'Show viewer tiles', + ), + ElevatedButton( + onPressed: () => AnalysisService.startService(force: false), + child: const Text('Start analysis service'), + ), + const Divider(), + Padding( + padding: const EdgeInsets.only(left: 8, right: 8, bottom: 8), + child: InfoRowGroup( + info: { + 'All entries': '${source.allEntries.length}', + 'Visible entries': '${visibleEntries.length}', + 'Catalogued': '${catalogued.length}', + 'With GPS': '${withGps.length}', + 'With address': '${withAddress.length}', + 'With fine address': '${withFineAddress.length}', + }, + ), + ), + ], + ); + } + + @override + bool get wantKeepAlive => true; +} + +class _TaskQueueOverlay extends StatelessWidget { + const _TaskQueueOverlay(); + + @override + Widget build(BuildContext context) { + return IgnorePointer( + child: DefaultTextStyle( + style: const TextStyle(), + child: Align( + alignment: AlignmentDirectional.bottomStart, + child: SafeArea( + child: Container( + color: Colors.indigo.shade900.withAlpha(0xCC), + padding: const EdgeInsets.all(8), + child: StreamBuilder<QueueState>( + stream: servicePolicy.queueStream, + builder: (context, snapshot) { + if (snapshot.hasError) return const SizedBox(); + final queuedEntries = <MapEntry<dynamic, int>>[]; + if (snapshot.hasData) { + final state = snapshot.data!; + queuedEntries.add(MapEntry('run', state.runningCount)); + queuedEntries.add(MapEntry('paused', state.pausedCount)); + queuedEntries.addAll(state.queueByPriority.entries.map((kv) => MapEntry(kv.key.toString(), kv.value))); + } + queuedEntries.sort((a, b) => a.key.compareTo(b.key)); + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text(queuedEntries.map((kv) => '${kv.key}: ${kv.value}').join(', ')), + ], + ); + }), + ), + ), + ), + ), + ); + } +} diff --git a/lib/widgets/debug/leaking.dart b/lib/widgets/debug/leaking.dart new file mode 100644 index 0000000..7a97808 --- /dev/null +++ b/lib/widgets/debug/leaking.dart @@ -0,0 +1,180 @@ +import 'dart:io'; + +import 'package:aves/ref/locales.dart'; +import 'package:aves/utils/file_utils.dart'; +import 'package:aves/widgets/common/identity/aves_expansion_tile.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:leak_tracker/leak_tracker.dart'; + +class DebugLeakingSection extends StatefulWidget { + const DebugLeakingSection({super.key}); + + @override + State<DebugLeakingSection> createState() => _DebugLeakingSectionState(); +} + +class _DebugLeakingSectionState extends State<DebugLeakingSection> with AutomaticKeepAliveClientMixin { + static OverlayEntry? _collectorOverlayEntry; + + static const _leakIgnoreConfig = IgnoredLeaks( + experimentalNotGCed: IgnoredLeaksSet(), + notDisposed: IgnoredLeaksSet(), + ); + + @override + Widget build(BuildContext context) { + super.build(context); + + return AvesExpansionTile( + title: 'Leaking', + children: [ + SwitchListTile( + value: _collectorOverlayEntry != null, + onChanged: (v) { + _collectorOverlayEntry + ?..remove() + ..dispose(); + _collectorOverlayEntry = null; + if (v) { + _collectorOverlayEntry = OverlayEntry( + builder: (context) => const _CollectorOverlay(), + ); + Overlay.of(context).insert(_collectorOverlayEntry!); + } + setState(() {}); + }, + title: const Text('Show leak report overlay'), + ), + ElevatedButton( + onPressed: () => LeakTracking.collectLeaks().then((leaks) { + LeakTracking.phase = const PhaseSettings( + ignoredLeaks: _leakIgnoreConfig, + leakDiagnosticConfig: LeakDiagnosticConfig( + collectRetainingPathForNotGCed: true, + collectStackTraceOnStart: true, + collectStackTraceOnDisposal: true, + ), + ); + }), + child: const Text('Track leaks with stacks'), + ), + ElevatedButton( + onPressed: () => LeakTracking.collectLeaks().then((leaks) { + LeakTracking.phase = const PhaseSettings( + ignoredLeaks: _leakIgnoreConfig, + leakDiagnosticConfig: LeakDiagnosticConfig( + collectRetainingPathForNotGCed: true, + collectStackTraceOnStart: false, + collectStackTraceOnDisposal: false, + ), + ); + }), + child: const Text('Track leaks without stacks'), + ), + ], + ); + } + + @override + bool get wantKeepAlive => true; +} + +class _CollectorOverlay extends StatefulWidget { + const _CollectorOverlay(); + + @override + State<_CollectorOverlay> createState() => _CollectorOverlayState(); +} + +class _CollectorOverlayState extends State<_CollectorOverlay> { + AlignmentGeometry _alignment = AlignmentDirectional.bottomStart; + + @override + Widget build(BuildContext context) { + return DefaultTextStyle( + style: const TextStyle(), + child: Align( + alignment: _alignment, + child: SafeArea( + child: Container( + color: Colors.indigo.shade900.withAlpha(0xCC), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Wrap( + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + IconButton( + onPressed: () => setState(() => _alignment = _alignment == AlignmentDirectional.bottomStart ? AlignmentDirectional.topStart : AlignmentDirectional.bottomStart), + icon: Icon(_alignment == AlignmentDirectional.bottomStart ? Icons.vertical_align_top_outlined : Icons.vertical_align_bottom_outlined), + ), + ...LeakType.values.map((type) { + return OutlinedButton( + style: ButtonStyle( + padding: WidgetStateProperty.all(const EdgeInsets.all(6)), + minimumSize: WidgetStateProperty.all(Size.zero), + ), + onPressed: () => LeakTracking.collectLeaks().then((leaks) { + final reports = leaks.byType[type] ?? []; + _printLeaks(type, reports); + }), + child: Text(type.name), + ); + }), + ], + ), + Wrap( + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + StreamBuilder( + stream: Stream.periodic(const Duration(seconds: 1)), + builder: (context, snapshot) { + final currentRss = formatFileSize(asciiLocale, ProcessInfo.currentRss); + final maxRss = formatFileSize(asciiLocale, ProcessInfo.maxRss); + return Text('RSS: $currentRss / $maxRss'); + }, + ), + ], + ), + Wrap( + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + StreamBuilder( + stream: Stream.periodic(const Duration(seconds: 1)), + builder: (context, snapshot) { + final currentImageCache = formatFileSize(asciiLocale, imageCache.currentSizeBytes); + final maxImageCache = formatFileSize(asciiLocale, imageCache.maximumSizeBytes); + return Text('imageCache: $currentImageCache / $maxImageCache'); + }, + ), + ], + ), + ], + ), + ), + ), + ), + ); + } + + void _printLeaks(LeakType type, List<LeakReport> reports) { + debugPrint('* leak type=$type, ${reports.length} reports'); + groupBy(reports, (report) => report.type).forEach((reportType, typedReports) { + debugPrint(' * report type=$reportType'); + groupBy(typedReports, (report) => report.trackedClass).forEach((trackedClass, classedReports) { + debugPrint(' trackedClass=$trackedClass reports=${classedReports.length}'); + classedReports.forEach((report) { + final phase = report.phase; + final retainingPath = report.retainingPath; + final detailedPath = report.detailedPath; + final context = report.context; + if (phase != null || retainingPath != null || detailedPath != null || context != null) { + debugPrint(' phase=$phase retainingPath=$retainingPath detailedPath=$detailedPath context=$context'); + } + }); + }); + }); + } +} diff --git a/lib/widgets/debug/media_store_scan_dialog.dart b/lib/widgets/debug/media_store_scan_dialog.dart new file mode 100644 index 0000000..e759c29 --- /dev/null +++ b/lib/widgets/debug/media_store_scan_dialog.dart @@ -0,0 +1,51 @@ +import 'dart:io'; + +import 'package:aves/ref/mime_types.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:flutter/material.dart'; + +class MediaStoreScanDirDialog extends StatefulWidget { + const MediaStoreScanDirDialog({super.key}); + + @override + State<MediaStoreScanDirDialog> createState() => _MediaStoreScanDirDialogState(); +} + +class _MediaStoreScanDirDialogState extends State<MediaStoreScanDirDialog> { + final TextEditingController _pathController = TextEditingController(); + bool _processing = false; + + @override + void dispose() { + _pathController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return AvesDialog( + content: _processing ? const CircularProgressIndicator() : TextField(controller: _pathController), + actions: [ + TextButton( + onPressed: _processing + ? null + : () async { + final dir = _pathController.text; + if (dir.isNotEmpty) { + setState(() => _processing = true); + await Future.forEach<FileSystemEntity>(Directory(dir).listSync(recursive: true), (file) async { + if (file is File) { + final mimeType = MimeTypes.forExtension(pContext.extension(file.path)); + await mediaStoreService.scanFile(file.path, mimeType!); + } + }); + } + Navigator.maybeOf(context)?.pop(); + }, + child: const Text('Scan'), + ) + ], + ); + } +} diff --git a/lib/widgets/debug/os_apps.dart b/lib/widgets/debug/os_apps.dart new file mode 100644 index 0000000..d8250a4 --- /dev/null +++ b/lib/widgets/debug/os_apps.dart @@ -0,0 +1,122 @@ +import 'package:aves/image_providers/app_icon_image_provider.dart'; +import 'package:aves/model/app_inventory.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/widgets/common/basic/query_bar.dart'; +import 'package:aves/widgets/common/identity/aves_expansion_tile.dart'; +import 'package:aves/widgets/viewer/info/common.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; + +class DebugOSAppSection extends StatefulWidget { + const DebugOSAppSection({super.key}); + + @override + State<DebugOSAppSection> createState() => _DebugOSAppSectionState(); +} + +class _DebugOSAppSectionState extends State<DebugOSAppSection> with AutomaticKeepAliveClientMixin { + late Future<Set<Package>> _loader; + final ValueNotifier<String> _queryNotifier = ValueNotifier(''); + + static const iconSize = 20.0; + + @override + void initState() { + super.initState(); + _loader = appService.getPackages(); + } + + @override + void dispose() { + _queryNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + super.build(context); + + return AvesExpansionTile( + title: 'OS Apps', + children: [ + Padding( + padding: const EdgeInsets.only(left: 8, right: 8, bottom: 8), + child: FutureBuilder<Set<Package>>( + future: _loader, + builder: (context, snapshot) { + if (snapshot.hasError) return Text(snapshot.error.toString()); + if (snapshot.connectionState != ConnectionState.done) return const SizedBox(); + final packages = snapshot.data!.toList()..sort((a, b) => compareAsciiUpperCase(a.packageName, b.packageName)); + final enabledTheme = IconTheme.of(context); + final disabledTheme = enabledTheme.merge(const IconThemeData(opacity: .2)); + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + QueryBar(queryNotifier: _queryNotifier), + ...packages.map((package) { + return ValueListenableBuilder<String>( + valueListenable: _queryNotifier, + builder: (context, query, child) { + if ({package.packageName, ...package.potentialDirs}.none((v) => v.toLowerCase().contains(query.toLowerCase()))) { + return const SizedBox(); + } + return Text.rich( + TextSpan( + children: [ + WidgetSpan( + alignment: PlaceholderAlignment.middle, + child: Image( + image: AppIconImage( + packageName: package.packageName, + size: iconSize, + ), + width: iconSize, + height: iconSize, + ), + ), + TextSpan( + text: ' ${package.packageName}\n', + style: InfoRowGroup.keyStyle(context), + ), + WidgetSpan( + alignment: PlaceholderAlignment.middle, + child: IconTheme( + data: package.categoryLauncher ? enabledTheme : disabledTheme, + child: const Icon( + Icons.launch_outlined, + size: iconSize, + ), + ), + ), + WidgetSpan( + alignment: PlaceholderAlignment.middle, + child: IconTheme( + data: package.isSystem ? enabledTheme : disabledTheme, + child: const Icon( + Icons.android, + size: iconSize, + ), + ), + ), + TextSpan( + text: ' ${package.potentialDirs.join(', ')}\n', + style: InfoRowGroup.valueStyle, + ), + ], + ), + ); + }, + ); + }) + ], + ); + }, + ), + ), + ], + ); + } + + @override + bool get wantKeepAlive => true; +} diff --git a/lib/widgets/debug/os_codecs.dart b/lib/widgets/debug/os_codecs.dart new file mode 100644 index 0000000..e1a4cf9 --- /dev/null +++ b/lib/widgets/debug/os_codecs.dart @@ -0,0 +1,87 @@ +import 'package:aves/services/android_debug_service.dart'; +import 'package:aves/widgets/common/basic/query_bar.dart'; +import 'package:aves/widgets/common/identity/aves_expansion_tile.dart'; +import 'package:aves/widgets/common/identity/highlight_title.dart'; +import 'package:aves/widgets/viewer/info/common.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; + +class DebugOSCodecSection extends StatefulWidget { + const DebugOSCodecSection({super.key}); + + @override + State<DebugOSCodecSection> createState() => _DebugOSCodecSectionState(); +} + +class _DebugOSCodecSectionState extends State<DebugOSCodecSection> with AutomaticKeepAliveClientMixin { + late Future<List<Map>> _loader; + final ValueNotifier<String> _queryNotifier = ValueNotifier(''); + + @override + void initState() { + super.initState(); + _loader = AndroidDebugService.getCodecs(); + } + + @override + void dispose() { + _queryNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + super.build(context); + + return AvesExpansionTile( + title: 'OS Codecs', + children: [ + Padding( + padding: const EdgeInsets.only(left: 8, right: 8, bottom: 8), + child: FutureBuilder<List<Map>>( + future: _loader, + builder: (context, snapshot) { + if (snapshot.hasError) return Text(snapshot.error.toString()); + if (snapshot.connectionState != ConnectionState.done) return const SizedBox(); + final codecs = snapshot.data!.map((codec) { + return codec.map((k, v) => MapEntry(k.toString(), v.toString())); + }).toList() + ..sort((a, b) => compareAsciiUpperCase(a['supportedTypes'] ?? '', b['supportedTypes'] ?? '')); + final byEncoder = groupBy<Map<String, String>, bool>(codecs, (v) => v['isEncoder'] == 'true'); + final decoders = byEncoder[false] ?? []; + final encoders = byEncoder[true] ?? []; + Widget _toCodecColumn(List<Map<String, String>> codecs) => ValueListenableBuilder<String>( + valueListenable: _queryNotifier, + builder: (context, query, child) => Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: codecs.expand((v) { + final types = v['supportedTypes']; + return (query.isEmpty || types == null || types.contains(query)) + ? [ + InfoRowGroup(info: Map.fromEntries(v.entries.where((kv) => kv.key != 'isEncoder'))), + const Divider(), + ] + : <Widget>[]; + }).toList(), + ), + ); + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + QueryBar(queryNotifier: _queryNotifier), + const HighlightTitle(title: 'Decoders'), + _toCodecColumn(decoders), + const HighlightTitle(title: 'Encoders'), + _toCodecColumn(encoders), + ], + ); + }, + ), + ), + ], + ); + } + + @override + bool get wantKeepAlive => true; +} diff --git a/lib/widgets/debug/os_paths.dart b/lib/widgets/debug/os_paths.dart new file mode 100644 index 0000000..1b1734a --- /dev/null +++ b/lib/widgets/debug/os_paths.dart @@ -0,0 +1,49 @@ +import 'dart:collection'; + +import 'package:aves/services/android_debug_service.dart'; +import 'package:aves/widgets/common/identity/aves_expansion_tile.dart'; +import 'package:aves/widgets/viewer/info/common.dart'; +import 'package:flutter/material.dart'; + +class DebugOSPathSection extends StatefulWidget { + const DebugOSPathSection({super.key}); + + @override + State<DebugOSPathSection> createState() => _DebugOSPathSectionState(); +} + +class _DebugOSPathSectionState extends State<DebugOSPathSection> with AutomaticKeepAliveClientMixin { + late Future<Map> _loader; + + @override + void initState() { + super.initState(); + _loader = AndroidDebugService.getContextDirs(); + } + + @override + Widget build(BuildContext context) { + super.build(context); + + return AvesExpansionTile( + title: 'OS Paths', + children: [ + Padding( + padding: const EdgeInsets.only(left: 8, right: 8, bottom: 8), + child: FutureBuilder<Map>( + future: _loader, + builder: (context, snapshot) { + if (snapshot.hasError) return Text(snapshot.error.toString()); + if (snapshot.connectionState != ConnectionState.done) return const SizedBox(); + final data = SplayTreeMap.of(snapshot.data!.map((k, v) => MapEntry(k.toString(), v?.toString() ?? 'null'))); + return InfoRowGroup(info: data); + }, + ), + ), + ], + ); + } + + @override + bool get wantKeepAlive => true; +} diff --git a/lib/widgets/debug/os_storage.dart b/lib/widgets/debug/os_storage.dart new file mode 100644 index 0000000..5765e51 --- /dev/null +++ b/lib/widgets/debug/os_storage.dart @@ -0,0 +1,64 @@ +import 'package:aves/ref/locales.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/utils/android_file_utils.dart'; +import 'package:aves/utils/file_utils.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/identity/aves_expansion_tile.dart'; +import 'package:aves/widgets/viewer/info/common.dart'; +import 'package:flutter/material.dart'; + +class DebugOSStorageSection extends StatefulWidget { + const DebugOSStorageSection({super.key}); + + @override + State<DebugOSStorageSection> createState() => _DebugOSStorageSectionState(); +} + +class _DebugOSStorageSectionState extends State<DebugOSStorageSection> with AutomaticKeepAliveClientMixin { + final Map<String, int?> _freeSpaceByVolume = {}; + + @override + void initState() { + super.initState(); + androidFileUtils.storageVolumes.forEach((volume) async { + final byteCount = await storageService.getFreeSpace(volume); + setState(() => _freeSpaceByVolume[volume.path] = byteCount); + }); + } + + @override + Widget build(BuildContext context) { + super.build(context); + + return AvesExpansionTile( + title: 'OS Storage', + children: [ + ...androidFileUtils.storageVolumes.expand((v) { + final freeSpace = _freeSpaceByVolume[v.path]; + return [ + Padding( + padding: const EdgeInsets.all(8), + child: Text(v.path), + ), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 8), + child: InfoRowGroup( + info: { + 'description': v.getDescription(context), + 'isPrimary': '${v.isPrimary}', + 'isRemovable': '${v.isRemovable}', + 'state': v.state, + if (freeSpace != null) 'freeSpace': formatFileSize(asciiLocale, freeSpace), + }, + ), + ), + const Divider(), + ]; + }) + ], + ); + } + + @override + bool get wantKeepAlive => true; +} diff --git a/lib/widgets/debug/report.dart b/lib/widgets/debug/report.dart new file mode 100644 index 0000000..4a7e72d --- /dev/null +++ b/lib/widgets/debug/report.dart @@ -0,0 +1,69 @@ +import 'package:aves/services/android_debug_service.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/widgets/common/identity/aves_expansion_tile.dart'; +import 'package:aves/widgets/viewer/info/common.dart'; +import 'package:flutter/material.dart'; + +class DebugErrorReportingSection extends StatefulWidget { + const DebugErrorReportingSection({super.key}); + + @override + State<DebugErrorReportingSection> createState() => _DebugErrorReportingSectionState(); +} + +class _DebugErrorReportingSectionState extends State<DebugErrorReportingSection> with AutomaticKeepAliveClientMixin { + @override + Widget build(BuildContext context) { + super.build(context); + + return AvesExpansionTile( + title: 'Reporting', + children: [ + const Padding( + padding: EdgeInsets.symmetric(horizontal: 8), + child: ElevatedButton( + onPressed: AndroidDebugService.crash, + child: Text('Crash'), + ), + ), + const Padding( + padding: EdgeInsets.symmetric(horizontal: 8), + child: ElevatedButton( + onPressed: AndroidDebugService.exception, + child: Text('Throw exception'), + ), + ), + const Padding( + padding: EdgeInsets.symmetric(horizontal: 8), + child: ElevatedButton( + onPressed: AndroidDebugService.safeException, + child: Text('Throw exception (safe)'), + ), + ), + const Padding( + padding: EdgeInsets.symmetric(horizontal: 8), + child: ElevatedButton( + onPressed: AndroidDebugService.exceptionInCoroutine, + child: Text('Throw exception in coroutine'), + ), + ), + const Padding( + padding: EdgeInsets.symmetric(horizontal: 8), + child: ElevatedButton( + onPressed: AndroidDebugService.safeExceptionInCoroutine, + child: Text('Throw exception in coroutine (safe)'), + ), + ), + Padding( + padding: const EdgeInsets.only(left: 8, right: 8, bottom: 8), + child: InfoRowGroup( + info: reportService.state, + ), + ) + ], + ); + } + + @override + bool get wantKeepAlive => true; +} diff --git a/lib/widgets/debug/settings.dart b/lib/widgets/debug/settings.dart new file mode 100644 index 0000000..beb0177 --- /dev/null +++ b/lib/widgets/debug/settings.dart @@ -0,0 +1,95 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/widgets/collection/collection_page.dart'; +import 'package:aves/widgets/common/identity/aves_expansion_tile.dart'; +import 'package:aves/widgets/filter_grids/albums_page.dart'; +import 'package:aves/widgets/filter_grids/countries_page.dart'; +import 'package:aves/widgets/filter_grids/places_page.dart'; +import 'package:aves/widgets/filter_grids/tags_page.dart'; +import 'package:aves/widgets/viewer/info/common.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class DebugSettingsSection extends StatefulWidget { + const DebugSettingsSection({super.key}); + + @override + State<DebugSettingsSection> createState() => _DebugSettingsSectionState(); +} + +class _DebugSettingsSectionState extends State<DebugSettingsSection> with AutomaticKeepAliveClientMixin { + @override + Widget build(BuildContext context) { + super.build(context); + + return Consumer<Settings>( + builder: (context, settings, child) { + String toMultiline(Iterable? l) => l != null && l.isNotEmpty ? '\n${l.join('\n')}' : '$l'; + return AvesExpansionTile( + title: 'Settings', + children: [ + Padding( + padding: const EdgeInsets.symmetric(horizontal: 8), + child: ElevatedButton( + onPressed: () => settings.reset(includeInternalKeys: true), + child: const Text('Reset (all store)'), + ), + ), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 8), + child: ElevatedButton( + onPressed: () => settings.reset(includeInternalKeys: false), + child: const Text('Reset (user preferences)'), + ), + ), + SwitchListTile( + value: settings.hasAcceptedTerms, + onChanged: (v) => settings.hasAcceptedTerms = v, + title: const Text('hasAcceptedTerms'), + ), + SwitchListTile( + value: settings.canUseAnalysisService, + onChanged: (v) => settings.canUseAnalysisService = v, + title: const Text('canUseAnalysisService'), + ), + Padding( + padding: const EdgeInsets.only(left: 8, right: 8, bottom: 8), + child: InfoRowGroup( + info: { + 'catalogTimeZoneRawOffsetMillis': '${settings.catalogTimeZoneOffsetMillis}', + 'tileExtent - Collection': '${settings.getTileExtent(CollectionPage.routeName)}', + 'tileExtent - Albums': '${settings.getTileExtent(AlbumListPage.routeName)}', + 'tileExtent - Countries': '${settings.getTileExtent(CountryListPage.routeName)}', + 'tileExtent - Places': '${settings.getTileExtent(PlaceListPage.routeName)}', + 'tileExtent - Tags': '${settings.getTileExtent(TagListPage.routeName)}', + 'mapStyle': '${settings.mapStyle}', + 'infoMapZoom': '${settings.infoMapZoom}', + 'customMapStyles': toMultiline(settings.customMapStyles), + 'collectionSelectionQuickActions': '${settings.collectionSelectionQuickActions}', + 'viewerQuickActions': '${settings.viewerQuickActions}', + 'drawerTypeBookmarks': toMultiline(settings.drawerTypeBookmarks), + 'drawerAlbumBookmarks': toMultiline(settings.drawerAlbumBookmarks), + 'drawerPageBookmarks': toMultiline(settings.drawerPageBookmarks), + 'pinnedFilters': toMultiline(settings.pinnedFilters), + 'hiddenFilters': toMultiline(settings.hiddenFilters), + 'deactivatedHiddenFilters': toMultiline(settings.deactivatedHiddenFilters), + 'searchHistory': toMultiline(settings.searchHistory), + 'recentDestinationAlbums': toMultiline(settings.recentDestinationAlbums), + 'recentTags': toMultiline(settings.recentTags), + 'locale': '${settings.locale}', + 'systemLocales': '${WidgetsBinding.instance.platformDispatcher.locales}', + 'topEntryIds': '${settings.topEntryIds}', + 'longPressTimeout': '${settings.longPressTimeout}', + 'albumGroups': toMultiline(settings.albumGroups.entries), + 'tagGroups': toMultiline(settings.tagGroups.entries), + }, + ), + ), + ], + ); + }, + ); + } + + @override + bool get wantKeepAlive => true; +} diff --git a/lib/widgets/dialogs/add_shortcut_dialog.dart b/lib/widgets/dialogs/add_shortcut_dialog.dart new file mode 100644 index 0000000..0154b44 --- /dev/null +++ b/lib/widgets/dialogs/add_shortcut_dialog.dart @@ -0,0 +1,149 @@ +import 'package:aves/model/covers.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/filters/query.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/providers/media_query_data_provider.dart'; +import 'package:aves/widgets/dialogs/item_picker.dart'; +import 'package:aves/widgets/dialogs/pick_dialogs/item_pick_page.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; + +import 'aves_dialog.dart'; + +class AddShortcutDialog extends StatefulWidget { + static const routeName = '/dialog/add_shortcut'; + + final CollectionLens? collection; + final String defaultName; + + const AddShortcutDialog({ + super.key, + required this.defaultName, + this.collection, + }); + + @override + State<AddShortcutDialog> createState() => _AddShortcutDialogState(); +} + +class _AddShortcutDialogState extends State<AddShortcutDialog> { + final TextEditingController _nameController = TextEditingController(); + final ValueNotifier<bool> _isValidNotifier = ValueNotifier(false); + AvesEntry? _coverEntry; + + @override + void initState() { + super.initState(); + final _collection = widget.collection; + if (_collection != null) { + final entries = _collection.sortedEntries; + if (entries.isNotEmpty) { + final coverEntries = _collection.filters.map((filter) => covers.of(filter)?.$1).nonNulls.map((id) => entries.firstWhereOrNull((entry) => entry.id == id)).nonNulls; + _coverEntry = coverEntries.firstOrNull ?? entries.first; + } + } + _nameController.text = widget.defaultName; + _validate(); + } + + @override + void dispose() { + _nameController.dispose(); + _isValidNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return MediaQueryDataProvider( + child: Builder( + builder: (context) { + final shortestSide = MediaQuery.sizeOf(context).shortestSide; + final extent = (shortestSide / 3.0).clamp(60.0, 160.0); + return AvesDialog( + scrollableContent: [ + if (_coverEntry != null) + Container( + alignment: Alignment.center, + padding: const EdgeInsets.only(top: 16), + child: ItemPicker( + extent: extent, + entry: _coverEntry!, + onTap: _pickEntry, + ), + ), + Padding( + padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 24), + child: TextField( + controller: _nameController, + decoration: InputDecoration( + labelText: context.l10n.addShortcutDialogLabel, + ), + autofocus: true, + maxLength: 25, + onChanged: (_) => _validate(), + onSubmitted: (_) => _submit(context), + ), + ), + ], + actions: [ + const CancelButton(), + ValueListenableBuilder<bool>( + valueListenable: _isValidNotifier, + builder: (context, isValid, child) { + return TextButton( + onPressed: isValid ? () => _submit(context) : null, + child: Text(context.l10n.addShortcutButtonLabel), + ); + }, + ) + ], + ); + }, + ), + ); + } + + Future<void> _pickEntry() async { + final _collection = widget.collection; + if (_collection == null) return; + + final entry = await Navigator.maybeOf(context)?.push<AvesEntry>( + MaterialPageRoute( + settings: const RouteSettings(name: ItemPickPage.routeName), + builder: (context) { + final pickFilters = _collection.filters.toSet(); + final liveFilters = pickFilters.whereType<QueryFilter>().where((v) => v.live).toSet(); + liveFilters.forEach((filter) { + pickFilters.remove(filter); + pickFilters.add(QueryFilter(filter.query)); + }); + return ItemPickPage( + collection: CollectionLens( + source: _collection.source, + filters: pickFilters, + ), + canRemoveFilters: false, + ); + }, + fullscreenDialog: true, + ), + ); + if (entry != null) { + _coverEntry = entry; + setState(() {}); + } + } + + Future<void> _validate() async { + final name = _nameController.text; + _isValidNotifier.value = name.isNotEmpty; + } + + void _submit(BuildContext context) { + if (_isValidNotifier.value) { + Navigator.maybeOf(context)?.pop<(AvesEntry?, String)>((_coverEntry, _nameController.text)); + } + } +} diff --git a/lib/widgets/dialogs/aves_confirmation_dialog.dart b/lib/widgets/dialogs/aves_confirmation_dialog.dart new file mode 100644 index 0000000..6e1a61a --- /dev/null +++ b/lib/widgets/dialogs/aves_confirmation_dialog.dart @@ -0,0 +1,158 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; + +import 'aves_dialog.dart'; + +Future<bool> showConfirmationDialog({ + required BuildContext context, + required String message, + required String confirmationButtonLabel, +}) async { + final confirmed = await showDialog<bool>( + context: context, + builder: (context) => AvesDialog( + content: Text(message), + actions: [ + const CancelButton(), + TextButton( + onPressed: () => Navigator.maybeOf(context)?.pop(true), + child: Text(confirmationButtonLabel), + ), + ], + ), + routeSettings: const RouteSettings(name: AvesDialog.confirmationRouteName), + ); + return confirmed ?? false; +} + +Future<bool> showSkippableConfirmationDialog({ + required BuildContext context, + required ConfirmationDialog type, + String? message, + ConfirmationDialogDelegate? delegate, + required String confirmationButtonLabel, +}) async { + if (!_shouldConfirm(type)) return true; + + assert((message != null) ^ (delegate != null)); + final effectiveDelegate = delegate ?? MessageConfirmationDialogDelegate(message!); + final confirmed = await showDialog<bool>( + context: context, + builder: (context) => _SkippableConfirmationDialog( + type: type, + delegate: effectiveDelegate, + confirmationButtonLabel: confirmationButtonLabel, + ), + routeSettings: const RouteSettings(name: _SkippableConfirmationDialog.routeName), + ); + if (confirmed == null) return false; + + if (confirmed) { + effectiveDelegate.apply(); + } + return confirmed; +} + +bool _shouldConfirm(ConfirmationDialog type) { + switch (type) { + case ConfirmationDialog.createVault: + return settings.confirmCreateVault; + case ConfirmationDialog.deleteForever: + return settings.confirmDeleteForever; + case ConfirmationDialog.moveToBin: + return settings.confirmMoveToBin; + case ConfirmationDialog.moveUndatedItems: + return settings.confirmMoveUndatedItems; + } +} + +void _skipConfirmation(ConfirmationDialog type) { + switch (type) { + case ConfirmationDialog.createVault: + settings.confirmCreateVault = false; + case ConfirmationDialog.deleteForever: + settings.confirmDeleteForever = false; + case ConfirmationDialog.moveToBin: + settings.confirmMoveToBin = false; + case ConfirmationDialog.moveUndatedItems: + settings.confirmMoveUndatedItems = false; + } +} + +abstract class ConfirmationDialogDelegate { + List<Widget> build(BuildContext context); + + void apply() {} +} + +class MessageConfirmationDialogDelegate extends ConfirmationDialogDelegate { + final String message; + + MessageConfirmationDialogDelegate(this.message); + + @override + List<Widget> build(BuildContext context) => [ + Padding( + padding: const EdgeInsets.all(16) + const EdgeInsets.only(top: 8), + child: Text(message), + ), + ]; +} + +class _SkippableConfirmationDialog extends StatefulWidget { + static const routeName = '/dialog/skippable_confirmation'; + + final ConfirmationDialog type; + final ConfirmationDialogDelegate delegate; + final String confirmationButtonLabel; + + const _SkippableConfirmationDialog({ + required this.type, + required this.delegate, + required this.confirmationButtonLabel, + }); + + @override + State<_SkippableConfirmationDialog> createState() => _SkippableConfirmationDialogState(); +} + +class _SkippableConfirmationDialogState extends State<_SkippableConfirmationDialog> { + final ValueNotifier<bool> _skipNotifier = ValueNotifier(false); + + @override + void dispose() { + _skipNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return AvesDialog( + scrollableContent: [ + ...widget.delegate.build(context), + ValueListenableBuilder<bool>( + valueListenable: _skipNotifier, + builder: (context, flag, child) => SwitchListTile( + value: flag, + onChanged: (v) => _skipNotifier.value = v, + title: Text(context.l10n.doNotAskAgain), + ), + ), + ], + actions: [ + const CancelButton(), + TextButton( + onPressed: () { + if (_skipNotifier.value) { + _skipConfirmation(widget.type); + } + Navigator.maybeOf(context)?.pop(true); + }, + child: Text(widget.confirmationButtonLabel), + ), + ], + ); + } +} diff --git a/lib/widgets/dialogs/aves_dialog.dart b/lib/widgets/dialogs/aves_dialog.dart new file mode 100644 index 0000000..924f961 --- /dev/null +++ b/lib/widgets/dialogs/aves_dialog.dart @@ -0,0 +1,185 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:flutter/material.dart'; + +class AvesDialog extends StatelessWidget { + static const confirmationRouteName = '/dialog/confirmation'; + static const warningRouteName = '/dialog/warning'; + + final String? title; + final ScrollController scrollController; + final List<Widget>? scrollableContent; + final double horizontalContentPadding; + final Widget? content; + final List<Widget> actions; + + static const Radius cornerRadius = Radius.circular(24); + static const double defaultHorizontalContentPadding = 24; + static const double controlCaptionPadding = 16; + static const double borderWidth = 1.0; + static const EdgeInsets actionsPadding = EdgeInsets.symmetric(vertical: 4, horizontal: 16); + static const EdgeInsets buttonPadding = EdgeInsets.symmetric(horizontal: 8); + + AvesDialog({ + super.key, + this.title, + ScrollController? scrollController, + this.scrollableContent, + this.horizontalContentPadding = defaultHorizontalContentPadding, + this.content, + this.actions = const [], + }) : assert((scrollableContent != null) ^ (content != null)), + scrollController = scrollController ?? ScrollController(); + + @override + Widget build(BuildContext context) { + return AlertDialog( + title: title != null + ? Padding( + // padding to avoid transparent border overlapping + padding: const EdgeInsets.symmetric(horizontal: borderWidth), + child: DialogTitle(title: title!), + ) + : null, + titlePadding: EdgeInsets.zero, + // the `scrollable` flag of `AlertDialog` makes it + // scroll both the title and the content together, + // and overflow feedback ignores the dialog shape, + // so we restrict scrolling to the content instead + content: _buildContent(context), + contentPadding: scrollableContent != null ? EdgeInsets.zero : EdgeInsets.only(left: horizontalContentPadding, top: 20, right: horizontalContentPadding), + actions: actions, + actionsPadding: actionsPadding, + buttonPadding: buttonPadding, + // clipping to prevent highlighted material to bleed through rounded corners + clipBehavior: Clip.antiAlias, + shape: shape(context), + ); + } + + Widget _buildContent(BuildContext context) { + if (content != null) { + return content!; + } + + if (scrollableContent != null) { + Widget child = ListView( + controller: scrollController, + shrinkWrap: true, + children: scrollableContent!, + ); + + if (!settings.useTvLayout) { + child = Theme( + data: Theme.of(context).copyWith( + scrollbarTheme: ScrollbarThemeData( + thumbVisibility: WidgetStateProperty.all(true), + radius: const Radius.circular(16), + crossAxisMargin: 4, + // adapt margin when corner is around content itself, not outside for the title + mainAxisMargin: 4 + (title != null ? 0 : cornerRadius.y / 2), + interactive: true, + ), + ), + child: Scrollbar( + controller: scrollController, + notificationPredicate: (notification) { + // as of Flutter v3.0.1, the `Scrollbar` does not only respond to the nearest `ScrollView` + // despite the `defaultScrollNotificationPredicate` checking notification depth, + // as the notifications coming from the controller in `ListWheelScrollView` in `WheelSelector` still have a depth of 0. + // Cancelling notification bubbling seems ineffective, so we check the metrics type as a workaround. + return defaultScrollNotificationPredicate(notification) && notification.metrics is! FixedExtentMetrics; + }, + child: child, + ), + ); + } + + return Container( + // padding to avoid transparent border overlapping + padding: const EdgeInsets.symmetric(horizontal: borderWidth), + // workaround because the dialog tries + // to size itself to the content intrinsic size, + // but the `ListView` viewport does not have one + width: MediaQuery.sizeOf(context).width / 2, + child: DecoratedBox( + decoration: contentDecoration(context), + child: child, + ), + ); + } + + return const SizedBox(); + } + + static Decoration contentDecoration(BuildContext context) => BoxDecoration( + border: Border( + bottom: Divider.createBorderSide(context, width: borderWidth), + ), + ); + + static ShapeBorder shape(BuildContext context) { + return RoundedRectangleBorder( + side: Divider.createBorderSide(context, width: borderWidth), + borderRadius: const BorderRadius.all(cornerRadius), + ); + } +} + +class DialogTitle extends StatelessWidget { + final String title; + + const DialogTitle({ + super.key, + required this.title, + }); + + @override + Widget build(BuildContext context) { + return Container( + alignment: Alignment.center, + padding: const EdgeInsets.symmetric(vertical: 18, horizontal: 16), + decoration: AvesDialog.contentDecoration(context), + child: Text( + title, + textAlign: TextAlign.center, + ), + ); + } +} + +Future<void> showNoMatchingAppDialog(BuildContext context) => showDialog( + context: context, + builder: (context) => AvesDialog( + content: Text(context.l10n.noMatchingAppDialogMessage), + actions: const [OkButton()], + ), + routeSettings: const RouteSettings(name: AvesDialog.warningRouteName), + ); + +class CancelButton extends StatelessWidget { + const CancelButton({super.key}); + + @override + Widget build(BuildContext context) { + return TextButton( + onPressed: () => Navigator.maybeOf(context)?.pop(), + // MD2 button labels were upper case but they are lower case in MD3 + child: Text(Themes.asButtonLabel(context.l10n.cancelTooltip)), + ); + } +} + +class OkButton extends StatelessWidget { + const OkButton({super.key}); + + @override + Widget build(BuildContext context) { + return TextButton( + onPressed: () => Navigator.maybeOf(context)?.pop(), + // MD2 button labels were upper case but they are lower case in MD3 + child: Text(Themes.asButtonLabel(MaterialLocalizations.of(context).okButtonLabel)), + ); + } +} diff --git a/lib/widgets/dialogs/cast_dialog.dart b/lib/widgets/dialogs/cast_dialog.dart new file mode 100644 index 0000000..3b7ba60 --- /dev/null +++ b/lib/widgets/dialogs/cast_dialog.dart @@ -0,0 +1,63 @@ +import 'package:aves/ref/upnp.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:dlna_dart/dlna.dart'; +import 'package:flutter/material.dart'; + +class CastDialog extends StatefulWidget { + static const routeName = '/dialog/cast'; + + const CastDialog({super.key}); + + @override + State<CastDialog> createState() => _CastDialogState(); +} + +class _CastDialogState extends State<CastDialog> { + final DLNAManager _dlnaManager = DLNAManager(); + final Map<String, DLNADevice> _seenRenderers = {}; + + @override + void initState() { + super.initState(); + + _dlnaManager.start().then((deviceManager) { + deviceManager.devices.stream.listen((devices) { + _seenRenderers.addAll(Map.fromEntries(devices.entries.where((kv) => kv.value.info.deviceType == Upnp.upnpDeviceTypeMediaRenderer).map((kv) { + final device = kv.value; + return MapEntry(device.info.friendlyName, device); + }))); + setState(() {}); + }); + }); + } + + @override + void dispose() { + _dlnaManager.stop(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return AvesDialog( + title: context.l10n.castDialogTitle, + scrollableContent: [ + if (_seenRenderers.isEmpty) + const Padding( + padding: EdgeInsets.all(16), + child: Center( + child: CircularProgressIndicator(), + ), + ), + ..._seenRenderers.values.map((dev) => ListTile( + title: Text(dev.info.friendlyName), + onTap: () => Navigator.maybeOf(context)?.pop<DLNADevice>(dev), + )), + ], + actions: const [ + CancelButton(), + ], + ); + } +} diff --git a/lib/widgets/dialogs/convert_entry_dialog.dart b/lib/widgets/dialogs/convert_entry_dialog.dart new file mode 100644 index 0000000..cc1974c --- /dev/null +++ b/lib/widgets/dialogs/convert_entry_dialog.dart @@ -0,0 +1,374 @@ +import 'package:aves/model/app/support.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/multipage.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/ref/mime_types.dart'; +import 'package:aves/services/media/media_edit_service.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/text.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/utils/mime_utils.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/basic/list_tiles/slider.dart'; +import 'package:aves/widgets/common/basic/text/change_highlight.dart'; +import 'package:aves/widgets/common/basic/text_dropdown_button.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/fx/transitions.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +import 'aves_dialog.dart'; + +class ConvertEntryDialog extends StatefulWidget { + static const routeName = '/dialog/convert_entry'; + + final Set<AvesEntry> entries; + + const ConvertEntryDialog({ + super.key, + required this.entries, + }); + + @override + State<ConvertEntryDialog> createState() => _ConvertEntryDialogState(); +} + +class _ConvertEntryDialogState extends State<ConvertEntryDialog> { + late List<EntryConvertAction> _actionOptions; + EntryConvertAction _action = EntryConvertAction.convert; + final TextEditingController _widthController = TextEditingController(), _heightController = TextEditingController(); + final ValueNotifier<bool> _isValidNotifier = ValueNotifier(false); + late ValueNotifier<String> _mimeTypeNotifier; + late int _quality; + late bool _writeMetadata, _sameSized; + late List<LengthUnit> _lengthUnitOptions; + late LengthUnit _lengthUnit; + + Set<AvesEntry> get entries => widget.entries; + + EdgeInsets get contentHorizontalPadding => const EdgeInsets.symmetric(horizontal: AvesDialog.defaultHorizontalContentPadding); + + static const _imageExportFormats = [ + MimeTypes.bmp, + MimeTypes.jpeg, + MimeTypes.png, + MimeTypes.webp, + ]; + + static const _qualityFormats = [ + MimeTypes.jpeg, + MimeTypes.webp, + ]; + + @override + void initState() { + super.initState(); + _actionOptions = [ + EntryConvertAction.convert, + if (entries.any((entry) => entry.isMotionPhoto)) EntryConvertAction.convertMotionPhotoToStillImage, + ]; + _mimeTypeNotifier = ValueNotifier(settings.convertMimeType); + _quality = settings.convertQuality; + _writeMetadata = settings.convertWriteMetadata; + _sameSized = entries.map((entry) => entry.displaySize).toSet().length == 1; + _lengthUnitOptions = [ + if (_sameSized) LengthUnit.px, + LengthUnit.percent, + ]; + _lengthUnit = _lengthUnitOptions.first; + _initDimensions(); + _validate(); + } + + void _initDimensions() { + switch (_lengthUnit) { + case LengthUnit.px: + final displaySize = entries.first.displaySize; + _widthController.text = '${displaySize.width.round()}'; + _heightController.text = '${displaySize.height.round()}'; + case LengthUnit.percent: + _widthController.text = '100'; + _heightController.text = '100'; + } + } + + @override + void dispose() { + _widthController.dispose(); + _heightController.dispose(); + _isValidNotifier.dispose(); + _mimeTypeNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return AvesDialog( + scrollableContent: [ + const SizedBox(height: 16), + if (_actionOptions.length > 1) + Padding( + padding: contentHorizontalPadding, + child: TextDropdownButton<EntryConvertAction>( + values: _actionOptions, + valueText: (v) => v.getText(context), + valueIcon: (v) => v.getIconData(), + value: _action, + onChanged: (v) { + _action = v!; + _validate(); + setState(() {}); + }, + isExpanded: true, + dropdownColor: Themes.thirdLayerColor(context), + ), + ), + AnimatedSwitcher( + duration: context.read<DurationsData>().formTransition, + switchInCurve: Curves.easeInOutCubic, + switchOutCurve: Curves.easeInOutCubic, + transitionBuilder: AvesTransitions.formTransitionBuilder, + child: Column( + key: ValueKey(_action), + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (_action == EntryConvertAction.convert) ..._buildConvertContent(context), + if (_action == EntryConvertAction.convertMotionPhotoToStillImage) const SizedBox(height: 16), + ], + ), + ), + ], + actions: [ + const CancelButton(), + ValueListenableBuilder<bool>( + valueListenable: _isValidNotifier, + builder: (context, isValid, child) { + return TextButton( + onPressed: isValid + ? () { + final width = int.tryParse(_widthController.text); + final height = int.tryParse(_heightController.text); + final options = (width != null && height != null) + ? EntryConvertOptions( + action: _action, + mimeType: _mimeTypeNotifier.value, + writeMetadata: _writeMetadata, + lengthUnit: _lengthUnit, + width: width, + height: height, + quality: _quality, + ) + : null; + + if (options != null) { + settings.convertMimeType = options.mimeType; + settings.convertQuality = options.quality; + settings.convertWriteMetadata = options.writeMetadata; + } + + Navigator.maybeOf(context)?.pop(options); + } + : null, + child: Text(context.l10n.applyButtonLabel), + ); + }, + ), + ], + ); + } + + List<Widget> _buildConvertContent(BuildContext context) { + final l10n = context.l10n; + final colorScheme = Theme.of(context).colorScheme; + final trailingStyle = TextStyle(color: colorScheme.onSurfaceVariant); + final trailingChangeShadowColor = colorScheme.onSurface; + + // used by the drop down to match input decoration + final textFieldDecorationBorder = Border( + bottom: BorderSide( + color: colorScheme.onSurface.withValues(alpha: .38), + width: 1.0, + ), + ); + + return [ + Padding( + padding: contentHorizontalPadding, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text(l10n.exportEntryDialogFormat), + const SizedBox(width: AvesDialog.controlCaptionPadding), + TextDropdownButton<String>( + values: _imageExportFormats, + valueText: MimeUtils.displayType, + value: _mimeTypeNotifier.value, + onChanged: (selected) { + if (selected != null) { + setState(() => _mimeTypeNotifier.value = selected); + } + }, + ), + ], + ), + ), + Padding( + padding: contentHorizontalPadding, + child: Row( + crossAxisAlignment: CrossAxisAlignment.baseline, + textBaseline: TextBaseline.alphabetic, + children: [ + Expanded( + child: TextField( + controller: _widthController, + decoration: InputDecoration(labelText: l10n.exportEntryDialogWidth), + keyboardType: TextInputType.number, + onChanged: (value) { + final width = int.tryParse(value); + if (width != null) { + switch (_lengthUnit) { + case LengthUnit.px: + _heightController.text = '${(width / entries.first.displayAspectRatio).round()}'; + case LengthUnit.percent: + _heightController.text = '$width'; + } + } else { + _heightController.text = ''; + } + _validate(); + }, + ), + ), + const SizedBox(width: 8), + const Text(AText.resolutionSeparator), + const SizedBox(width: 8), + Expanded( + child: TextField( + controller: _heightController, + decoration: InputDecoration(labelText: l10n.exportEntryDialogHeight), + keyboardType: TextInputType.number, + onChanged: (value) { + final height = int.tryParse(value); + if (height != null) { + switch (_lengthUnit) { + case LengthUnit.px: + _widthController.text = '${(height * entries.first.displayAspectRatio).round()}'; + case LengthUnit.percent: + _widthController.text = '$height'; + } + } else { + _widthController.text = ''; + } + _validate(); + }, + ), + ), + const SizedBox(width: 16), + TextDropdownButton<LengthUnit>( + values: _lengthUnitOptions, + valueText: (v) => v.getText(context), + value: _lengthUnit, + onChanged: _lengthUnitOptions.length > 1 + ? (v) { + if (v != null && _lengthUnit != v) { + _lengthUnit = v; + _initDimensions(); + _validate(); + setState(() {}); + } + } + : null, + underline: Container( + height: 1.0, + decoration: BoxDecoration( + border: textFieldDecorationBorder, + ), + ), + itemHeight: 60, + dropdownColor: Themes.thirdLayerColor(context), + ), + ], + ), + ), + ValueListenableBuilder<String>( + valueListenable: _mimeTypeNotifier, + builder: (context, mimeType, child) { + Widget child; + if (_qualityFormats.contains(mimeType)) { + child = SliderListTile( + value: _quality.toDouble(), + onChanged: (v) => setState(() => _quality = v.round()), + min: 0, + max: 100, + title: context.l10n.exportEntryDialogQuality, + titlePadding: contentHorizontalPadding, + titleTrailing: (context, value) => ChangeHighlightText( + '${value.round()}', + style: trailingStyle.copyWith( + shadows: [ + Shadow( + color: trailingChangeShadowColor.withAlpha(0), + blurRadius: 0, + ) + ], + ), + changedStyle: trailingStyle.copyWith( + shadows: [ + Shadow( + color: trailingChangeShadowColor, + blurRadius: 3, + ) + ], + ), + duration: context.read<DurationsData>().formTextStyleTransition, + ), + ); + } else { + child = const SizedBox(); + } + return AnimatedSwitcher( + duration: context.read<DurationsData>().formTransition, + switchInCurve: Curves.easeInOutCubic, + switchOutCurve: Curves.easeInOutCubic, + transitionBuilder: AvesTransitions.formTransitionBuilder, + child: child, + ); + }, + ), + ValueListenableBuilder<String>( + valueListenable: _mimeTypeNotifier, + builder: (context, mimeType, child) { + Widget child; + if (AppSupport.canEditExif(mimeType) || AppSupport.canEditIptc(mimeType) || AppSupport.canEditXmp(mimeType)) { + child = SwitchListTile( + value: _writeMetadata, + onChanged: (v) => setState(() => _writeMetadata = v), + title: Text(context.l10n.exportEntryDialogWriteMetadata), + contentPadding: const EdgeInsetsDirectional.only( + start: AvesDialog.defaultHorizontalContentPadding, + end: AvesDialog.defaultHorizontalContentPadding - 8, + ), + ); + } else { + child = const SizedBox(height: 16); + } + return AnimatedSwitcher( + duration: context.read<DurationsData>().formTransition, + switchInCurve: Curves.easeInOutCubic, + switchOutCurve: Curves.easeInOutCubic, + transitionBuilder: AvesTransitions.formTransitionBuilder, + child: child, + ); + }, + ), + ]; + } + + Future<void> _validate() async { + final width = int.tryParse(_widthController.text); + final height = int.tryParse(_heightController.text); + _isValidNotifier.value = (width ?? 0) > 0 && (height ?? 0) > 0; + } +} diff --git a/lib/widgets/dialogs/duration_dialog.dart b/lib/widgets/dialogs/duration_dialog.dart new file mode 100644 index 0000000..ad742c4 --- /dev/null +++ b/lib/widgets/dialogs/duration_dialog.dart @@ -0,0 +1,123 @@ +import 'package:aves/ref/locales.dart'; +import 'package:aves/utils/time_utils.dart'; +import 'package:aves/widgets/common/basic/wheel.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/providers/media_query_data_provider.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; + +class DurationDialog extends StatefulWidget { + final int initialSeconds; + + const DurationDialog({ + super.key, + required this.initialSeconds, + }); + + @override + State<DurationDialog> createState() => _DurationDialogState(); +} + +class _DurationDialogState extends State<DurationDialog> { + late ValueNotifier<int> _minutes, _seconds; + + @override + void initState() { + super.initState(); + final seconds = widget.initialSeconds; + _minutes = ValueNotifier(seconds ~/ secondsInMinute); + _seconds = ValueNotifier(seconds % secondsInMinute); + } + + @override + void dispose() { + _minutes.dispose(); + _seconds.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return MediaQueryDataProvider( + child: Builder(builder: (context) { + final l10n = context.l10n; + final timeComponentFormatter = NumberFormat('0', context.locale); + + const textStyle = TextStyle(fontSize: 34); + const digitsAlign = TextAlign.right; + + return AvesDialog( + scrollableContent: [ + Padding( + padding: const EdgeInsets.only(top: 16), + child: Center( + child: Table( + textDirection: timeComponentsDirection, + children: [ + TableRow( + children: [ + Center(child: Text(l10n.durationDialogMinutes)), + const SizedBox(width: 16), + Center(child: Text(l10n.durationDialogSeconds)), + ], + ), + TableRow( + children: [ + Align( + alignment: Alignment.centerRight, + child: WheelSelector( + valueNotifier: _minutes, + values: List.generate(minutesInHour, (i) => i), + textStyle: textStyle, + textAlign: digitsAlign, + format: timeComponentFormatter.format, + ), + ), + const Padding( + padding: EdgeInsets.only(bottom: 2), + child: Text( + ':', + style: textStyle, + ), + ), + Align( + alignment: Alignment.centerLeft, + child: WheelSelector( + valueNotifier: _seconds, + values: List.generate(secondsInMinute, (i) => i), + textStyle: textStyle, + textAlign: digitsAlign, + format: timeComponentFormatter.format, + ), + ), + ], + ) + ], + defaultColumnWidth: const IntrinsicColumnWidth(), + defaultVerticalAlignment: TableCellVerticalAlignment.middle, + ), + ), + ), + ], + actions: [ + const CancelButton(), + AnimatedBuilder( + animation: Listenable.merge([_minutes, _seconds]), + builder: (context, child) { + final isValid = _minutes.value > 0 || _seconds.value > 0; + return TextButton( + onPressed: isValid ? () => _submit(context) : null, + child: child!, + ); + }, + child: Text(l10n.applyButtonLabel), + ), + ], + ); + }), + ); + } + + void _submit(BuildContext context) => Navigator.maybeOf(context)?.pop(_minutes.value * secondsInMinute + _seconds.value); +} diff --git a/lib/widgets/dialogs/entry_editors/edit_date_dialog.dart b/lib/widgets/dialogs/entry_editors/edit_date_dialog.dart new file mode 100644 index 0000000..0d027d5 --- /dev/null +++ b/lib/widgets/dialogs/entry_editors/edit_date_dialog.dart @@ -0,0 +1,332 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/metadata/date_modifier.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/format.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/basic/text_dropdown_button.dart'; +import 'package:aves/widgets/common/basic/time_shift_selector.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/fx/transitions.dart'; +import 'package:aves/widgets/common/providers/media_query_data_provider.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:aves/widgets/dialogs/item_picker.dart'; +import 'package:aves/widgets/dialogs/pick_dialogs/item_pick_page.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class EditEntryDateDialog extends StatefulWidget { + static const routeName = '/dialog/edit_entry_date'; + + final AvesEntry entry; + final CollectionLens? collection; + + const EditEntryDateDialog({ + super.key, + required this.entry, + this.collection, + }); + + @override + State<EditEntryDateDialog> createState() => _EditEntryDateDialogState(); +} + +class _EditEntryDateDialogState extends State<EditEntryDateDialog> { + DateEditAction _action = DateEditAction.setCustom; + DateFieldSource _copyFieldSource = DateFieldSource.fileModifiedDate; + late AvesEntry _copyItemSource; + late DateTime _customDateTime; + late TimeShiftController _timeShiftController; + bool _showOptions = false; + final Set<MetadataField> _fields = {...DateModifier.writableFields}; + final ValueNotifier<bool> _isValidNotifier = ValueNotifier(false); + + DateTime get copyItemDate => _copyItemSource.bestDate ?? DateTime.now(); + + @override + void initState() { + super.initState(); + _initCustom(); + _initCopyItem(); + _initShift(); + _validate(); + } + + @override + void dispose() { + _isValidNotifier.dispose(); + super.dispose(); + } + + void _initCustom() { + _customDateTime = widget.entry.bestDate ?? DateTime.now(); + } + + void _initCopyItem() { + _copyItemSource = widget.entry; + } + + void _initShift() { + _timeShiftController = TimeShiftController( + initialValue: const Duration(hours: 1), + ); + } + + @override + Widget build(BuildContext context) { + return MediaQueryDataProvider( + child: TooltipTheme( + data: TooltipTheme.of(context).copyWith( + preferBelow: false, + ), + child: Builder(builder: (context) { + final l10n = context.l10n; + + return AvesDialog( + title: l10n.editEntryDateDialogTitle, + scrollableContent: [ + Padding( + padding: const EdgeInsets.only(left: 16, top: 8, right: 16), + child: TextDropdownButton<DateEditAction>( + values: DateEditAction.values, + valueText: (v) => v.getText(context), + value: _action, + onChanged: (v) { + _action = v!; + _validate(); + setState(() {}); + }, + isExpanded: true, + dropdownColor: Themes.thirdLayerColor(context), + ), + ), + AnimatedSwitcher( + duration: context.read<DurationsData>().formTransition, + switchInCurve: Curves.easeInOutCubic, + switchOutCurve: Curves.easeInOutCubic, + transitionBuilder: AvesTransitions.formTransitionBuilder, + child: Column( + key: ValueKey(_action), + mainAxisSize: MainAxisSize.min, + children: [ + if (_action == DateEditAction.setCustom) _buildSetCustomContent(context), + if (_action == DateEditAction.copyField) _buildCopyFieldContent(context), + if (_action == DateEditAction.copyItem) _buildCopyItemContent(context), + if (_action == DateEditAction.shift) _buildShiftContent(context), + (_action == DateEditAction.shift || _action == DateEditAction.remove) ? _buildDestinationFields(context) : const SizedBox(height: 8), + ], + ), + ), + ], + actions: [ + const CancelButton(), + ValueListenableBuilder<bool>( + valueListenable: _isValidNotifier, + builder: (context, isValid, child) { + return TextButton( + onPressed: isValid ? () => _submit(context) : null, + child: Text(l10n.applyButtonLabel), + ); + }, + ), + ], + ); + }), + ), + ); + } + + Widget _buildSetCustomContent(BuildContext context) { + final use24hour = MediaQuery.alwaysUse24HourFormatOf(context); + + return Padding( + padding: const EdgeInsetsDirectional.only(start: 16, end: 8), + child: Row( + children: [ + Expanded(child: Text(formatDateTime(_customDateTime, context.locale, use24hour))), + IconButton( + icon: const Icon(AIcons.edit), + onPressed: _editDate, + tooltip: context.l10n.changeTooltip, + ), + ], + ), + ); + } + + Widget _buildCopyFieldContent(BuildContext context) { + return Padding( + padding: const EdgeInsets.only(left: 16, top: 0, right: 16), + child: TextDropdownButton<DateFieldSource>( + values: DateFieldSource.values, + valueText: (v) => v.getText(context), + value: _copyFieldSource, + onChanged: (v) => setState(() => _copyFieldSource = v!), + isExpanded: true, + dropdownColor: Themes.thirdLayerColor(context), + ), + ); + } + + Widget _buildCopyItemContent(BuildContext context) { + final use24hour = MediaQuery.alwaysUse24HourFormatOf(context); + + return Padding( + padding: const EdgeInsetsDirectional.only(start: 16, end: 8), + child: Row( + children: [ + Expanded(child: Text(formatDateTime(copyItemDate, context.locale, use24hour))), + const SizedBox(width: 8), + ItemPicker( + extent: 48, + entry: _copyItemSource, + onTap: _pickCopyItemSource, + ), + ], + ), + ); + } + + Widget _buildShiftContent(BuildContext context) { + return TimeShiftSelector(controller: _timeShiftController); + } + + Widget _buildDestinationFields(BuildContext context) { + return Padding( + // small padding as a workaround to show dialog action divider + padding: const EdgeInsets.only(bottom: 1), + child: ExpansionPanelList( + expansionCallback: (index, isExpanded) { + setState(() => _showOptions = isExpanded); + }, + animationDuration: context.read<DurationsData>().expansionTileAnimation, + expandedHeaderPadding: EdgeInsets.zero, + elevation: 0, + children: [ + ExpansionPanel( + headerBuilder: (context, isExpanded) => ListTile( + title: Text(context.l10n.editEntryDialogTargetFieldsHeader), + ), + body: Column( + children: DateModifier.writableFields + .map((field) => SwitchListTile( + value: _fields.contains(field), + onChanged: (selected) { + selected ? _fields.add(field) : _fields.remove(field); + _validate(); + setState(() {}); + }, + title: Text(field.title), + )) + .toList(), + ), + isExpanded: _showOptions, + canTapOnHeader: true, + backgroundColor: Colors.transparent, + ), + ], + ), + ); + } + + Future<void> _editDate() async { + final l10n = context.l10n; + final cancelText = Themes.asButtonLabel(l10n.cancelTooltip); + + final _date = await showDatePicker( + context: context, + initialDate: _customDateTime, + firstDate: DateTime(0), + lastDate: DateTime(2100), + cancelText: cancelText, + confirmText: l10n.nextButtonLabel, + ); + if (_date == null) return; + + final _time = await showTimePicker( + context: context, + initialTime: TimeOfDay.fromDateTime(_customDateTime), + cancelText: cancelText, + ); + if (_time == null) return; + + setState(() => _customDateTime = DateTime( + _date.year, + _date.month, + _date.day, + _time.hour, + _time.minute, + )); + } + + CollectionLens? _createPickCollection() { + final baseCollection = widget.collection; + return baseCollection != null + ? CollectionLens( + source: baseCollection.source, + filters: baseCollection.filters, + ) + : null; + } + + Future<void> _pickCopyItemSource() async { + final pickCollection = _createPickCollection(); + if (pickCollection == null) return; + + final entry = await Navigator.maybeOf(context)?.push<AvesEntry>( + MaterialPageRoute( + settings: const RouteSettings(name: ItemPickPage.routeName), + builder: (context) => ItemPickPage( + collection: pickCollection, + canRemoveFilters: true, + ), + fullscreenDialog: true, + ), + ); + if (entry != null) { + setState(() => _copyItemSource = entry); + } + } + + DateModifier _getModifier() { + // fields to modify are only set for the `shift` and `remove` actions, + // as the effective fields for the other actions will depend on + // whether each item supports Exif edition + switch (_action) { + case DateEditAction.setCustom: + return DateModifier.setCustom(const {}, _customDateTime); + case DateEditAction.copyField: + return DateModifier.copyField(_copyFieldSource); + case DateEditAction.copyItem: + return DateModifier.setCustom(const {}, copyItemDate); + case DateEditAction.extractFromTitle: + return DateModifier.extractFromTitle(); + case DateEditAction.shift: + return DateModifier.shift(_fields, _timeShiftController.value.inSeconds); + case DateEditAction.remove: + return DateModifier.remove(_fields); + } + } + + void _validate() { + switch (_action) { + case DateEditAction.setCustom: + case DateEditAction.copyField: + case DateEditAction.copyItem: + case DateEditAction.extractFromTitle: + _isValidNotifier.value = true; + case DateEditAction.shift: + case DateEditAction.remove: + _isValidNotifier.value = _fields.isNotEmpty; + } + } + + void _submit(BuildContext context) { + if (_isValidNotifier.value) { + Navigator.maybeOf(context)?.pop(_getModifier()); + } + } +} diff --git a/lib/widgets/dialogs/entry_editors/edit_description_dialog.dart b/lib/widgets/dialogs/entry_editors/edit_description_dialog.dart new file mode 100644 index 0000000..60c77b9 --- /dev/null +++ b/lib/widgets/dialogs/entry_editors/edit_description_dialog.dart @@ -0,0 +1,116 @@ +import 'package:aves/model/entry/extensions/metadata_edition.dart'; +import 'package:aves/widgets/common/basic/labeled_checkbox.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/providers/media_query_data_provider.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:flutter/material.dart'; + +class EditEntryTitleDescriptionDialog extends StatefulWidget { + static const routeName = '/dialog/edit_entry_title_description'; + + final String initialTitle, initialDescription; + + const EditEntryTitleDescriptionDialog({ + super.key, + required this.initialTitle, + required this.initialDescription, + }); + + @override + State<EditEntryTitleDescriptionDialog> createState() => _EditEntryTitleDescriptionDialogState(); +} + +class _EditEntryTitleDescriptionDialogState extends State<EditEntryTitleDescriptionDialog> { + final Set<DescriptionField> fields = { + DescriptionField.title, + DescriptionField.description, + }; + late final TextEditingController _titleTextController, _descriptionTextController; + + @override + void initState() { + super.initState(); + _titleTextController = TextEditingController(text: widget.initialTitle); + _descriptionTextController = TextEditingController(text: widget.initialDescription); + } + + @override + void dispose() { + _titleTextController.dispose(); + _descriptionTextController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return MediaQueryDataProvider( + child: Builder(builder: (context) { + return AvesDialog( + scrollableContent: [ + const SizedBox(height: 8), + ..._buildFieldEditor(DescriptionField.title), + ..._buildFieldEditor(DescriptionField.description), + const SizedBox(height: 8), + ], + actions: [ + const CancelButton(), + TextButton( + onPressed: fields.isEmpty ? null : () => _submit(context), + child: Text(context.l10n.applyButtonLabel), + ), + ], + ); + }), + ); + } + + List<Widget> _buildFieldEditor(DescriptionField field) { + final editing = fields.contains(field); + return [ + Padding( + padding: const EdgeInsets.symmetric(horizontal: 4), + child: LabeledCheckbox( + value: editing, + onChanged: (v) => setState(() => editing ? fields.remove(field) : fields.add(field)), + text: _fieldName(field), + ), + ), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 8), + child: TextField( + controller: _fieldController(field), + decoration: const InputDecoration( + border: OutlineInputBorder(), + ), + maxLines: null, + enabled: editing, + ), + ), + ]; + } + + TextEditingController _fieldController(DescriptionField field) { + switch (field) { + case DescriptionField.title: + return _titleTextController; + case DescriptionField.description: + return _descriptionTextController; + } + } + + String _fieldName(DescriptionField field) { + final l10n = context.l10n; + return switch (field) { + DescriptionField.title => l10n.viewerInfoLabelTitle, + DescriptionField.description => l10n.viewerInfoLabelDescription, + }; + } + + void _submit(BuildContext context) { + final modifier = Map.fromEntries(fields.map((field) { + final text = _fieldController(field).text; + return MapEntry(field, text.isEmpty ? null : text); + })); + return Navigator.maybeOf(context)?.pop<Map<DescriptionField, String?>>(modifier); + } +} diff --git a/lib/widgets/dialogs/entry_editors/edit_location_dialog.dart b/lib/widgets/dialogs/entry_editors/edit_location_dialog.dart new file mode 100644 index 0000000..6c51a13 --- /dev/null +++ b/lib/widgets/dialogs/entry_editors/edit_location_dialog.dart @@ -0,0 +1,629 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:ui'; + +import 'package:aves/app_mode.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/location.dart'; +import 'package:aves/model/entry/extensions/metadata_edition.dart'; +import 'package:aves/model/entry/sort.dart'; +import 'package:aves/model/filters/covered/location.dart'; +import 'package:aves/model/metadata/catalog.dart'; +import 'package:aves/model/settings/enums/coordinate_format.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/ref/poi.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/format.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/aves_app.dart'; +import 'package:aves/widgets/common/action_mixins/feedback.dart'; +import 'package:aves/widgets/common/basic/text_dropdown_button.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/fx/transitions.dart'; +import 'package:aves/widgets/common/identity/aves_caption.dart'; +import 'package:aves/widgets/common/providers/media_query_data_provider.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:aves/widgets/dialogs/item_picker.dart'; +import 'package:aves/widgets/dialogs/pick_dialogs/item_pick_page.dart'; +import 'package:aves/widgets/dialogs/pick_dialogs/location_pick_page.dart'; +import 'package:aves/widgets/dialogs/time_shift_dialog.dart'; +import 'package:aves/widgets/map/map_page.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_map/flutter_map.dart'; +import 'package:gpx/gpx.dart'; +import 'package:intl/intl.dart'; +import 'package:latlong2/latlong.dart'; +import 'package:provider/provider.dart'; + +class EditEntryLocationDialog extends StatefulWidget { + static const routeName = '/dialog/edit_entry_location'; + + final Set<AvesEntry> entries; + final CollectionLens? collection; + + const EditEntryLocationDialog({ + super.key, + required this.entries, + this.collection, + }); + + @override + State<EditEntryLocationDialog> createState() => _EditEntryLocationDialogState(); +} + +class _EditEntryLocationDialogState extends State<EditEntryLocationDialog> with FeedbackMixin { + final Set<StreamSubscription> _subscriptions = {}; + LocationEditAction _action = LocationEditAction.chooseOnMap; + LatLng? _mapCoordinates; + late final AvesEntry mainEntry; + late AvesEntry _copyItemSource; + Gpx? _gpx; + Duration _gpxShift = Duration.zero; + final Map<AvesEntry, LatLng> _gpxMap = {}; + final TextEditingController _latitudeController = TextEditingController(), _longitudeController = TextEditingController(); + final ValueNotifier<bool> _isValidNotifier = ValueNotifier(false); + + late NumberFormat coordinateFormatter; + static const _gpxProjection = SphericalMercator(); + static const _minDurationToGpxPoint = Duration(hours: 1); + + @override + void initState() { + super.initState(); + final entries = widget.entries; + mainEntry = entries.firstWhereOrNull((entry) => entry.hasGps) ?? entries.first; + _mapCoordinates = mainEntry.latLng; + _copyItemSource = mainEntry; + WidgetsBinding.instance.addPostFrameCallback((_) { + coordinateFormatter = NumberFormat('0.000000', context.locale); + final latLng = mainEntry.latLng; + if (latLng != null) { + _latitudeController.text = coordinateFormatter.format(latLng.latitude); + _longitudeController.text = coordinateFormatter.format(latLng.longitude); + } else { + _latitudeController.text = ''; + _longitudeController.text = ''; + } + setState(_validate); + }); + _subscriptions.add(AvesApp.intentEventBus.on<LocationReceivedEvent>().listen((event) => _setCustomLocation(event.location))); + } + + @override + void dispose() { + _subscriptions + ..forEach((sub) => sub.cancel()) + ..clear(); + _latitudeController.dispose(); + _longitudeController.dispose(); + _isValidNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return MediaQueryDataProvider( + child: TooltipTheme( + data: TooltipTheme.of(context).copyWith( + preferBelow: false, + ), + child: Builder(builder: (context) { + final l10n = context.l10n; + + return AvesDialog( + title: l10n.editEntryLocationDialogTitle, + scrollableContent: [ + Padding( + padding: const EdgeInsets.only(left: 16, top: 8, right: 16), + child: TextDropdownButton<LocationEditAction>( + values: LocationEditAction.values, + valueText: (v) => v.getText(context), + value: _action, + onChanged: (v) => setState(() { + _action = v!; + _validate(); + }), + isExpanded: true, + dropdownColor: Themes.thirdLayerColor(context), + ), + ), + AnimatedSwitcher( + duration: context.read<DurationsData>().formTransition, + switchInCurve: Curves.easeInOutCubic, + switchOutCurve: Curves.easeInOutCubic, + transitionBuilder: AvesTransitions.formTransitionBuilder, + child: KeyedSubtree( + key: ValueKey(_action), + child: _buildContent(), + ), + ), + const SizedBox(height: 8), + ], + actions: [ + const CancelButton(), + ValueListenableBuilder<bool>( + valueListenable: _isValidNotifier, + builder: (context, isValid, child) { + return TextButton( + onPressed: isValid ? () => _submit(context) : null, + child: Text(l10n.applyButtonLabel), + ); + }, + ), + ], + ); + }), + ), + ); + } + + Widget _buildContent() { + switch (_action) { + case LocationEditAction.chooseOnMap: + return _buildChooseOnMapContent(context); + case LocationEditAction.copyItem: + return _buildCopyItemContent(context); + case LocationEditAction.setCustom: + return _buildSetCustomContent(context); + case LocationEditAction.importGpx: + return _buildImportGpxContent(context); + case LocationEditAction.remove: + return const SizedBox(); + } + } + + Widget _buildChooseOnMapContent(BuildContext context) { + return Padding( + padding: const EdgeInsetsDirectional.only(start: 16, end: 8), + child: Row( + children: [ + Expanded(child: _coordinatesText(context, _mapCoordinates)), + const SizedBox(width: 8), + IconButton( + icon: const Icon(AIcons.map), + onPressed: _pickLocation, + tooltip: context.l10n.editEntryLocationDialogChooseOnMap, + ), + ], + ), + ); + } + + void _setCustomLocation(LatLng latLng) { + _latitudeController.text = coordinateFormatter.format(latLng.latitude); + _longitudeController.text = coordinateFormatter.format(latLng.longitude); + _action = LocationEditAction.setCustom; + setState(_validate); + } + + CollectionLens? _createPickCollection() { + final baseCollection = widget.collection; + return baseCollection != null + ? CollectionLens( + source: baseCollection.source, + filters: { + ...baseCollection.filters.whereNot((filter) => filter == LocationFilter.unlocated), + LocationFilter.located, + }, + ) + : null; + } + + Future<void> _pickLocation() async { + final pickCollection = _createPickCollection(); + final latLng = await Navigator.maybeOf(context)?.push( + MaterialPageRoute( + settings: const RouteSettings(name: LocationPickPage.routeName), + builder: (context) => LocationPickPage( + collection: pickCollection, + initialLocation: _mapCoordinates, + ), + fullscreenDialog: true, + ), + ); + if (latLng != null) { + settings.mapDefaultCenter = latLng; + setState(() { + _mapCoordinates = latLng; + _validate(); + }); + } + } + + Widget _buildCopyItemContent(BuildContext context) { + return Padding( + padding: const EdgeInsetsDirectional.only(start: 16, end: 8), + child: Row( + children: [ + Expanded(child: _coordinatesText(context, _copyItemSource.latLng)), + const SizedBox(width: 8), + ItemPicker( + extent: 48, + entry: _copyItemSource, + onTap: _pickCopyItemSource, + ), + ], + ), + ); + } + + Future<void> _pickCopyItemSource() async { + final pickCollection = _createPickCollection(); + if (pickCollection == null) return; + + final entry = await Navigator.maybeOf(context)?.push<AvesEntry>( + MaterialPageRoute( + settings: const RouteSettings(name: ItemPickPage.routeName), + builder: (context) => ItemPickPage( + collection: pickCollection, + canRemoveFilters: true, + ), + fullscreenDialog: true, + ), + ); + if (entry != null) { + setState(() { + _copyItemSource = entry; + _validate(); + }); + } + } + + Widget _buildSetCustomContent(BuildContext context) { + final l10n = context.l10n; + + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: Column( + children: [ + TextField( + controller: _latitudeController, + decoration: InputDecoration( + labelText: l10n.editEntryLocationDialogLatitude, + hintText: coordinateFormatter.format(PointsOfInterest.pointNemo.latitude), + ), + onChanged: (_) => _validate(), + ), + TextField( + controller: _longitudeController, + decoration: InputDecoration( + labelText: l10n.editEntryLocationDialogLongitude, + hintText: coordinateFormatter.format(PointsOfInterest.pointNemo.longitude), + ), + onChanged: (_) => _validate(), + ), + ], + ), + ), + ], + ), + ); + } + + Widget _buildImportGpxContent(BuildContext context) { + final l10n = context.l10n; + return Padding( + padding: const EdgeInsetsDirectional.only(start: 16, end: 8), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Row( + children: [ + Expanded(child: _gpxDateRangeText(context, _gpx)), + const SizedBox(width: 8), + IconButton( + icon: Icon(AIcons.fileImport), + onPressed: _pickGpx, + tooltip: l10n.pickTooltip, + ), + ], + ), + if (_gpx != null) ...[ + Row( + children: [ + Expanded( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(l10n.editEntryLocationDialogTimeShift), + AvesCaption(_formatShiftDuration(_gpxShift)), + ], + ), + ), + const SizedBox(width: 8), + IconButton( + icon: const Icon(AIcons.edit), + onPressed: _pickGpxShift, + tooltip: l10n.changeTooltip, + ), + ], + ), + Row( + children: [ + Expanded(child: Text(l10n.statsWithGps(_gpxMap.length))), + const SizedBox(width: 8), + IconButton( + icon: const Icon(AIcons.map), + onPressed: _previewGpx, + tooltip: l10n.openMapPageTooltip, + ), + ], + ), + ], + ], + ), + ); + } + + Future<void> _pickGpx() async { + final bytes = await storageService.openFile(); + if (bytes.isNotEmpty) { + try { + final allXmlString = utf8.decode(bytes); + final gpx = GpxReader().fromString(allXmlString); + + _gpx = gpx; + _gpxShift = Duration.zero; + _updateGpxMapping(); + + showFeedback(context, FeedbackType.info, context.l10n.genericSuccessFeedback); + } catch (error, stack) { + debugPrint('failed to import GPX, error=$error\n$stack'); + showFeedback(context, FeedbackType.warn, context.l10n.genericFailureFeedback); + } + } + } + + Future<void> _pickGpxShift() async { + final newShift = await showDialog<Duration>( + context: context, + builder: (context) => TimeShiftDialog( + initialValue: _gpxShift, + ), + routeSettings: const RouteSettings(name: TimeShiftDialog.routeName), + ); + if (newShift == null) return; + + _gpxShift = newShift; + _updateGpxMapping(); + } + + String _formatShiftDuration(Duration duration) { + final sign = duration.isNegative ? '-' : '+'; + duration = duration.abs(); + final hours = duration.inHours; + duration -= Duration(hours: hours); + final minutes = duration.inMinutes; + duration -= Duration(minutes: minutes); + final seconds = duration.inSeconds; + return '$sign$hours:${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}'; + } + + void _updateGpxMapping() { + _gpxMap.clear(); + + final gpx = _gpx; + if (gpx == null) return; + + // dated items and points, oldest first + final sortedEntries = widget.entries.where((v) => v.bestDate != null).sorted(AvesEntrySort.compareByDate).reversed.toList(); + final sortedPoints = gpx.trks.expand((trk) => trk.trksegs).expand((trkSeg) => trkSeg.trkpts).where((v) => v.time != null && v.lat != null && v.lon != null).sortedBy((v) => v.time!); + if (sortedEntries.isNotEmpty && sortedPoints.isNotEmpty) { + int entryIndex = 0; + int pointIndex = 0; + + DateTime getEntryDate(AvesEntry entry) => entry.bestDate!; + DateTime getCorrectedPointDate(Wpt wpt) => wpt.time!.add(_gpxShift); + Duration getDurationToPoint(AvesEntry entry, Wpt wpt) => getEntryDate(entry).difference(getCorrectedPointDate(wpt)).abs(); + + while (entryIndex < sortedEntries.length && pointIndex < sortedPoints.length) { + final entry = sortedEntries[entryIndex]; + final wpt = sortedPoints[pointIndex]; + + final entryDate = getEntryDate(entry); + final wptDate = getCorrectedPointDate(wpt); + final durationToPoint = getDurationToPoint(entry, wpt); + + if (entryDate.isAfter(wptDate)) { + if (wpt == sortedPoints.last) { + if (durationToPoint < _minDurationToGpxPoint) { + // assign late entry to last point + _gpxMap[entry] = LatLng(wpt.lat!, wpt.lon!); + } + entryIndex++; + } else { + pointIndex++; + } + } else if (entryDate.isAtSameMomentAs(wptDate)) { + // assign entry to current point + _gpxMap[entry] = LatLng(wpt.lat!, wpt.lon!); + entryIndex++; + } else { + if (wpt == sortedPoints.first) { + if (durationToPoint < _minDurationToGpxPoint) { + // assign early entry to first point + _gpxMap[entry] = LatLng(wpt.lat!, wpt.lon!); + } + } else { + // interpolate entry between previous and current point + final from = sortedPoints[pointIndex - 1]; + final to = wpt; + + final secondsFromStart = getDurationToPoint(entry, from).inSeconds; + final secondsToEnd = getDurationToPoint(entry, to).inSeconds; + final t = (secondsFromStart.toDouble()) / (secondsFromStart + secondsToEnd); + + final fromXY = _gpxProjection.projectXY(LatLng(from.lat!, from.lon!)); + final toXY = _gpxProjection.projectXY(LatLng(to.lat!, to.lon!)); + final entryXY = ( + lerpDouble(fromXY.$1, toXY.$1, t)!, + lerpDouble(fromXY.$2, toXY.$2, t)!, + ); + _gpxMap[entry] = _gpxProjection.unprojectXY(entryXY.$1, entryXY.$2); + } + entryIndex++; + } + } + } + + setState(_validate); + } + + Future<void> _previewGpx() async { + final source = widget.collection?.source; + if (source == null) return; + + final previewEntries = _gpxMap.entries.map((kv) { + final entry = kv.key.copyWith(); + final latLng = kv.value; + final catalogMetadata = entry.catalogMetadata?.copyWith() ?? CatalogMetadata(id: entry.id); + catalogMetadata.latitude = latLng.latitude; + catalogMetadata.longitude = latLng.longitude; + entry.catalogMetadata = catalogMetadata; + return entry; + }).toList(); + + final mapCollection = CollectionLens( + source: source, + listenToSource: false, + fixedSelection: previewEntries, + ); + + final tracks = _gpx?.trks + .expand((trk) => trk.trksegs) + .map((trkSeg) => trkSeg.trkpts + .map((wpt) { + final lat = wpt.lat; + final lon = wpt.lon; + return (lat != null && lon != null) ? LatLng(lat, lon) : null; + }) + .nonNulls + .toList()) + .toSet(); + + await Navigator.maybeOf(context)?.push( + MaterialPageRoute( + settings: const RouteSettings(name: LocationPickPage.routeName), + builder: (context) { + return ListenableProvider<ValueNotifier<AppMode>>.value( + value: ValueNotifier(AppMode.previewMap), + child: MapPage( + collection: mapCollection, + tracks: tracks, + ), + ); + }, + fullscreenDialog: true, + ), + ); + } + + Text _unknownText(BuildContext context) { + final l10n = context.l10n; + return Text( + l10n.viewerInfoUnknown, + style: TextStyle( + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ); + } + + (DateTime, DateTime)? _gpxDateRange(Gpx? gpx) { + final firstDate = gpx?.trks.firstOrNull?.trksegs.firstOrNull?.trkpts.firstOrNull?.time; + final lastDate = gpx?.trks.lastOrNull?.trksegs.lastOrNull?.trkpts.lastOrNull?.time; + return firstDate != null && lastDate != null ? (firstDate, lastDate) : null; + } + + Text _gpxDateRangeText(BuildContext context, Gpx? gpx) { + final dateRange = _gpxDateRange(gpx); + if (dateRange != null) { + final (firstDate, lastDate) = dateRange; + final locale = context.locale; + final use24hour = MediaQuery.alwaysUse24HourFormatOf(context); + return Text( + [ + formatDateTime(firstDate.toLocal(), locale, use24hour), + formatDateTime(lastDate.toLocal(), locale, use24hour), + ].join('\n'), + ); + } else { + return _unknownText(context); + } + } + + Text _coordinatesText(BuildContext context, LatLng? latLng) { + final l10n = context.l10n; + if (latLng != null) { + return Text( + ExtraCoordinateFormat.toDMS(l10n, latLng).join('\n'), + ); + } else { + return _unknownText(context); + } + } + + LatLng? _parseLatLng() { + double? tryParse(String text) { + try { + return double.tryParse(text) ?? (coordinateFormatter.parse(text).toDouble()); + } catch (error) { + // ignore + return null; + } + } + + final lat = tryParse(_latitudeController.text); + final lng = tryParse(_longitudeController.text); + if (lat == null || lng == null) return null; + if (lat < -90 || lat > 90 || lng < -180 || lng > 180) return null; + return LatLng(lat, lng); + } + + void _validate() { + switch (_action) { + case LocationEditAction.chooseOnMap: + _isValidNotifier.value = _mapCoordinates != null; + case LocationEditAction.copyItem: + _isValidNotifier.value = _copyItemSource.hasGps; + case LocationEditAction.setCustom: + _isValidNotifier.value = _parseLatLng() != null; + case LocationEditAction.importGpx: + _isValidNotifier.value = _gpxMap.isNotEmpty; + case LocationEditAction.remove: + _isValidNotifier.value = true; + } + } + + void _submit(BuildContext context) { + final navigator = Navigator.maybeOf(context); + final entries = widget.entries; + final LocationEditActionResult result = {}; + void addLocationForAllEntries(LatLng? latLng) => result.addEntries(entries.map((v) => MapEntry(v, latLng))); + switch (_action) { + case LocationEditAction.chooseOnMap: + addLocationForAllEntries(_mapCoordinates); + case LocationEditAction.copyItem: + addLocationForAllEntries(_copyItemSource.latLng); + case LocationEditAction.setCustom: + addLocationForAllEntries(_parseLatLng()); + case LocationEditAction.importGpx: + result.addAll(_gpxMap); + case LocationEditAction.remove: + addLocationForAllEntries(ExtraAvesEntryMetadataEdition.removalLocation); + } + navigator?.pop(result); + } +} + +typedef LocationEditActionResult = Map<AvesEntry, LatLng?>; diff --git a/lib/widgets/dialogs/entry_editors/edit_rating_dialog.dart b/lib/widgets/dialogs/entry_editors/edit_rating_dialog.dart new file mode 100644 index 0000000..771ab6f --- /dev/null +++ b/lib/widgets/dialogs/entry_editors/edit_rating_dialog.dart @@ -0,0 +1,133 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/theme/colors.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/providers/media_query_data_provider.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:flutter/material.dart'; + +class EditEntryRatingDialog extends StatefulWidget { + static const routeName = '/dialog/edit_entry_rating'; + + final AvesEntry entry; + + const EditEntryRatingDialog({ + super.key, + required this.entry, + }); + + @override + State<EditEntryRatingDialog> createState() => _EditEntryRatingDialogState(); +} + +class _EditEntryRatingDialogState extends State<EditEntryRatingDialog> { + late _RatingAction _action; + late int _rating; + + @override + void initState() { + super.initState(); + final entryRating = widget.entry.rating; + switch (entryRating) { + case -1: + _action = _RatingAction.rejected; + _rating = 0; + case 0: + _action = _RatingAction.unrated; + _rating = 0; + default: + _action = _RatingAction.set; + _rating = entryRating; + } + } + + @override + Widget build(BuildContext context) { + return MediaQueryDataProvider( + child: TooltipTheme( + data: TooltipTheme.of(context).copyWith( + preferBelow: false, + ), + child: Builder(builder: (context) { + final l10n = context.l10n; + + return AvesDialog( + title: l10n.editEntryRatingDialogTitle, + scrollableContent: [ + RadioListTile<_RatingAction>( + value: _RatingAction.set, + groupValue: _action, + onChanged: (v) => setState(() => _action = v!), + title: Wrap( + children: [ + ...List.generate(5, (i) { + final thisRating = i + 1; + final disabled = _rating < thisRating; + return GestureDetector( + onTap: () => setState(() { + _action = _RatingAction.set; + _rating = thisRating; + }), + behavior: HitTestBehavior.opaque, + child: Padding( + padding: const EdgeInsets.all(4), + child: Icon( + AIcons.rating, + fill: disabled ? 0 : 1, + color: disabled ? AColors.starDisabled : AColors.starEnabled, + ), + ), + ); + }) + ], + ), + ), + RadioListTile<_RatingAction>( + value: _RatingAction.rejected, + groupValue: _action, + onChanged: (v) => setState(() { + _action = v!; + _rating = 0; + }), + title: Text(l10n.filterRatingRejectedLabel), + ), + RadioListTile<_RatingAction>( + value: _RatingAction.unrated, + groupValue: _action, + onChanged: (v) => setState(() { + _action = v!; + _rating = 0; + }), + title: Text(l10n.filterNoRatingLabel), + ), + ], + actions: [ + const CancelButton(), + TextButton( + onPressed: isValid ? () => _submit(context) : null, + child: Text(l10n.applyButtonLabel), + ), + ], + ); + }), + ), + ); + } + + bool get isValid => !(_action == _RatingAction.set && _rating <= 0); + + void _submit(BuildContext context) { + late int entryRating; + switch (_action) { + case _RatingAction.set: + entryRating = _rating; + case _RatingAction.rejected: + entryRating = -1; + case _RatingAction.unrated: + entryRating = 0; + } + Navigator.maybeOf(context)?.pop(entryRating); + } +} + +enum _RatingAction { set, rejected, unrated } diff --git a/lib/widgets/dialogs/entry_editors/remove_metadata_dialog.dart b/lib/widgets/dialogs/entry_editors/remove_metadata_dialog.dart new file mode 100644 index 0000000..adebe66 --- /dev/null +++ b/lib/widgets/dialogs/entry_editors/remove_metadata_dialog.dart @@ -0,0 +1,158 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/ref/brand_colors.dart'; +import 'package:aves/theme/colors.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/basic/text/outlined.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/fx/highlight_decoration.dart'; +import 'package:aves/widgets/common/identity/highlight_title.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class RemoveEntryMetadataDialog extends StatefulWidget { + static const routeName = '/dialog/remove_entry_metadata'; + + final bool showJpegTypes; + + const RemoveEntryMetadataDialog({ + super.key, + required this.showJpegTypes, + }); + + @override + State<RemoveEntryMetadataDialog> createState() => _RemoveEntryMetadataDialogState(); +} + +class _RemoveEntryMetadataDialogState extends State<RemoveEntryMetadataDialog> { + late final List<MetadataType> _allOptions, _mainOptions, _moreOptions; + final Set<MetadataType> _types = {}; + bool _showMore = false; + final ValueNotifier<bool> _isValidNotifier = ValueNotifier(false); + + @override + void initState() { + super.initState(); + _allOptions = [ + ...MetadataTypes.common, + if (widget.showJpegTypes) ...MetadataTypes.jpeg, + ]; + final byMain = groupBy(_allOptions, MetadataTypes.main.contains); + _mainOptions = (byMain[true] ?? [])..sort(_compareTypeText); + _moreOptions = (byMain[false] ?? [])..sort(_compareTypeText); + _validate(); + } + + @override + void dispose() { + _isValidNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + final animationDuration = context.select<DurationsData, Duration>((v) => v.expansionTileAnimation); + return AvesDialog( + title: l10n.removeEntryMetadataDialogTitle, + scrollableContent: [ + SwitchListTile( + value: _types.length == _allOptions.length, + onChanged: (selected) { + selected ? _types.addAll(_allOptions) : _types.clear(); + setState(_validate); + }, + title: Align( + alignment: Alignment.centerLeft, + child: Text(l10n.removeEntryMetadataDialogAll), + ), + ), + ..._mainOptions.map(_toTile), + if (_moreOptions.isNotEmpty) + Padding( + padding: const EdgeInsets.only(bottom: 1), + child: ExpansionPanelList( + expansionCallback: (index, isExpanded) { + setState(() => _showMore = isExpanded); + }, + animationDuration: animationDuration, + expandedHeaderPadding: EdgeInsets.zero, + elevation: 0, + children: [ + ExpansionPanel( + headerBuilder: (context, isExpanded) => ListTile( + title: Text(l10n.removeEntryMetadataDialogMore), + ), + body: Column( + children: _moreOptions.map(_toTile).toList(), + ), + isExpanded: _showMore, + canTapOnHeader: true, + backgroundColor: Colors.transparent, + ), + ], + ), + ), + ], + actions: [ + const CancelButton(), + ValueListenableBuilder<bool>( + valueListenable: _isValidNotifier, + builder: (context, isValid, child) { + return TextButton( + onPressed: isValid ? () => _submit(context) : null, + child: Text(context.l10n.applyButtonLabel), + ); + }, + ), + ], + ); + } + + int _compareTypeText(MetadataType a, MetadataType b) => a.getText().compareTo(b.getText()); + + Widget _toTile(MetadataType type) { + final text = type.getText(); + Widget child = OutlinedText( + textSpans: [ + TextSpan( + text: text, + style: TextStyle( + shadows: HighlightTitle.shadows(context), + ), + ), + ], + outlineColor: Themes.firstLayerColor(context), + ); + if (context.select<Settings, bool>((v) => v.themeColorMode == AvesThemeColorMode.polychrome)) { + final colors = context.watch<AvesColorsData>(); + child = Container( + padding: const EdgeInsets.symmetric(horizontal: 2), + decoration: HighlightDecoration( + color: colors.fromBrandColor(BrandColors.get(text)) ?? colors.fromString(text), + ), + child: child, + ); + } + + return SwitchListTile( + value: _types.contains(type), + onChanged: (selected) { + selected ? _types.add(type) : _types.remove(type); + setState(_validate); + }, + title: Align( + alignment: Alignment.centerLeft, + child: child, + ), + ); + } + + void _validate() => _isValidNotifier.value = _types.isNotEmpty; + + void _submit(BuildContext context) => Navigator.maybeOf(context)?.pop(_types); +} diff --git a/lib/widgets/dialogs/entry_editors/rename_entry_dialog.dart b/lib/widgets/dialogs/entry_editors/rename_entry_dialog.dart new file mode 100644 index 0000000..05d4f89 --- /dev/null +++ b/lib/widgets/dialogs/entry_editors/rename_entry_dialog.dart @@ -0,0 +1,105 @@ +import 'dart:io'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; + +class RenameEntryDialog extends StatefulWidget { + static const routeName = '/dialog/rename_entry'; + + final AvesEntry entry; + + const RenameEntryDialog({ + super.key, + required this.entry, + }); + + @override + State<RenameEntryDialog> createState() => _RenameEntryDialogState(); +} + +class _RenameEntryDialogState extends State<RenameEntryDialog> { + final TextEditingController _nameController = TextEditingController(); + final ValueNotifier<bool> _isValidNotifier = ValueNotifier(false); + + AvesEntry get entry => widget.entry; + + @override + void initState() { + super.initState(); + _nameController.text = entry.filenameWithoutExtension ?? entry.sourceTitle ?? ''; + _validate(); + } + + @override + void dispose() { + _nameController.dispose(); + _isValidNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return AvesDialog( + content: Row( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Expanded( + child: TextField( + controller: _nameController, + decoration: InputDecoration( + labelText: context.l10n.renameEntryDialogLabel, + ), + autofocus: true, + maxLines: null, + onChanged: (_) => _validate(), + onSubmitted: (_) => _submit(context), + ), + ), + Padding( + padding: const EdgeInsetsDirectional.only(start: 4, bottom: 12), + child: Text( + '${Unicode.FSI}${entry.extension}${Unicode.PDI}', + style: TextStyle(color: Theme.of(context).hintColor), + ), + ), + ], + ), + actions: [ + const CancelButton(), + ValueListenableBuilder<bool>( + valueListenable: _isValidNotifier, + builder: (context, isValid, child) { + return TextButton( + onPressed: isValid ? () => _submit(context) : null, + child: Text(context.l10n.applyButtonLabel), + ); + }, + ), + ], + ); + } + + String _buildEntryPath(String name) { + if (name.isEmpty) return ''; + return pContext.join(entry.directory!, '$name${entry.extension}'); + } + + String get newName => _nameController.text.trimLeft().replaceAll('\n', ''); + + Future<void> _validate() async { + final _newName = newName; + final path = _buildEntryPath(_newName); + final exists = _newName.isNotEmpty && await FileSystemEntity.type(path) != FileSystemEntityType.notFound; + _isValidNotifier.value = _newName.isNotEmpty && !exists; + } + + void _submit(BuildContext context) { + if (_isValidNotifier.value) { + Navigator.maybeOf(context)?.pop(newName); + } + } +} diff --git a/lib/widgets/dialogs/entry_editors/rename_entry_set_page.dart b/lib/widgets/dialogs/entry_editors/rename_entry_set_page.dart new file mode 100644 index 0000000..85f1d81 --- /dev/null +++ b/lib/widgets/dialogs/entry_editors/rename_entry_set_page.dart @@ -0,0 +1,256 @@ +import 'dart:math'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/naming_pattern.dart'; +import 'package:aves/model/settings/enums/accessibility_animations.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/theme/styles.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/collection/collection_grid.dart'; +import 'package:aves/widgets/common/basic/font_size_icon_theme.dart'; +import 'package:aves/widgets/common/basic/popup/expansion_panel.dart'; +import 'package:aves/widgets/common/basic/popup/menu_row.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/grid/theme.dart'; +import 'package:aves/widgets/common/identity/buttons/outlined_button.dart'; +import 'package:aves/widgets/common/thumbnail/decorated.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:provider/provider.dart'; + +class RenameEntrySetPage extends StatefulWidget { + static const routeName = '/rename_entry_set'; + + final List<AvesEntry> entries; + + const RenameEntrySetPage({ + super.key, + required this.entries, + }); + + @override + State<RenameEntrySetPage> createState() => _RenameEntrySetPageState(); +} + +class _RenameEntrySetPageState extends State<RenameEntrySetPage> { + final TextEditingController _patternTextController = TextEditingController(); + final ValueNotifier<NamingPattern> _namingPatternNotifier = ValueNotifier<NamingPattern>(const NamingPattern([])); + late final String locale; + + static const int previewMax = 10; + static const double thumbnailExtent = 48; + + List<AvesEntry> get entries => widget.entries; + + int get entryCount => entries.length; + + @override + void initState() { + super.initState(); + _patternTextController.text = settings.entryRenamingPattern; + _patternTextController.addListener(_onUserPatternChanged); + + WidgetsBinding.instance.addPostFrameCallback((_) { + locale = context.locale; + _onUserPatternChanged(); + }); + } + + @override + void dispose() { + _patternTextController.dispose(); + _namingPatternNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + final textScaler = MediaQuery.textScalerOf(context); + final effectiveThumbnailExtent = max(thumbnailExtent, textScaler.scale(thumbnailExtent)); + final animations = context.select<Settings, AccessibilityAnimations>((v) => v.accessibilityAnimations); + return AvesScaffold( + appBar: AppBar( + title: Text(l10n.renameEntrySetPageTitle), + ), + body: SafeArea( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.all(8), + child: Row( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Expanded( + child: TextField( + controller: _patternTextController, + decoration: InputDecoration( + labelText: l10n.renameEntrySetPagePatternFieldLabel, + ), + autofocus: true, + ), + ), + FontSizeIconTheme( + child: PopupMenuButton<String>( + itemBuilder: (context) { + return [ + PopupMenuItem( + value: NameNamingProcessor.key, + child: MenuRow(text: l10n.renameProcessorName, icon: const Icon(AIcons.name)), + ), + PopupMenuItem( + value: CounterNamingProcessor.key, + child: MenuRow(text: l10n.renameProcessorCounter, icon: const Icon(AIcons.counter)), + ), + PopupMenuItem( + value: DateNamingProcessor.key, + child: MenuRow(text: l10n.viewerInfoLabelDate, icon: const Icon(AIcons.date)), + ), + PopupMenuItem( + value: TagsNamingProcessor.key, + child: MenuRow(text: l10n.tagPageTitle, icon: const Icon(AIcons.tag)), + ), + PopupMenuExpansionPanel<String>( + value: MetadataFieldNamingProcessor.key, + icon: AIcons.more, + title: MaterialLocalizations.of(context).moreButtonTooltip, + items: [ + ...[ + MetadataField.exifMake, + MetadataField.exifModel, + ].map((field) => PopupMenuItem( + value: MetadataFieldNamingProcessor.keyWithField(field), + child: MenuRow(text: field.title), + )), + PopupMenuItem( + value: HashNamingProcessor.key, + child: MenuRow(text: l10n.renameProcessorHash), + ) + ], + ), + ]; + }, + onSelected: (key) async { + // wait for the popup menu to hide before proceeding with the action + await Future.delayed(animations.popUpAnimationDelay * timeDilation); + _insertProcessor(key); + }, + tooltip: l10n.renameEntrySetPageInsertTooltip, + icon: const Icon(AIcons.add), + popUpAnimationStyle: animations.popUpAnimationStyle, + ), + ), + ], + ), + ), + const Divider(), + Padding( + padding: const EdgeInsets.all(16), + child: Text( + l10n.renameEntrySetPagePreviewSectionTitle, + style: AStyles.knownTitleText, + ), + ), + Expanded( + child: GridTheme( + extent: effectiveThumbnailExtent, + child: ListView.separated( + physics: const NeverScrollableScrollPhysics(), + padding: const EdgeInsets.symmetric(vertical: 12), + itemBuilder: (context, index) { + final entry = entries[index]; + final sourceName = entry.filenameWithoutExtension ?? ''; + return Row( + children: [ + DecoratedThumbnail( + entry: entry, + tileExtent: effectiveThumbnailExtent, + selectable: false, + highlightable: false, + ), + const SizedBox(width: 8), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + sourceName, + style: TextStyle(color: Theme.of(context).colorScheme.onSurfaceVariant), + softWrap: false, + overflow: TextOverflow.fade, + maxLines: 1, + ), + const SizedBox(height: 4), + ValueListenableBuilder<NamingPattern>( + valueListenable: _namingPatternNotifier, + builder: (context, pattern, child) { + return FutureBuilder<String>( + future: pattern.apply(entry, index), + builder: (context, snapshot) { + final info = snapshot.data; + return Text( + info ?? '…', + softWrap: false, + overflow: TextOverflow.fade, + maxLines: 1, + ); + }, + ); + }, + ), + ], + ), + ), + ], + ); + }, + separatorBuilder: (context, index) => const SizedBox( + height: CollectionGrid.fixedExtentLayoutSpacing, + ), + itemCount: min(entryCount, previewMax), + ), + ), + ), + const Divider(height: 0), + Center( + child: Padding( + padding: const EdgeInsets.all(8), + child: AvesOutlinedButton( + label: l10n.entryActionRename, + onPressed: () { + settings.entryRenamingPattern = _patternTextController.text; + Navigator.maybeOf(context)?.pop<NamingPattern>(_namingPatternNotifier.value); + }, + ), + ), + ), + ], + ), + ), + ); + } + + void _onUserPatternChanged() { + _namingPatternNotifier.value = NamingPattern.from( + userPattern: _patternTextController.text, + entryCount: entryCount, + locale: locale, + ); + } + + void _insertProcessor(String key) { + final userPattern = _patternTextController.text; + final selection = _patternTextController.selection; + _patternTextController.value = _patternTextController.value.replaced( + TextRange( + start: NamingPattern.getInsertionOffset(userPattern, selection.start), + end: NamingPattern.getInsertionOffset(userPattern, selection.end), + ), + NamingPattern.defaultPatternFor(key), + ); + } +} diff --git a/lib/widgets/dialogs/entry_editors/tag_editor_page.dart b/lib/widgets/dialogs/entry_editors/tag_editor_page.dart new file mode 100644 index 0000000..97efae4 --- /dev/null +++ b/lib/widgets/dialogs/entry_editors/tag_editor_page.dart @@ -0,0 +1,379 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/filters/covered/tag.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/filters/placeholder.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/expandable_filter_row.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/aves_filter_chip.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class TagEditorPage extends StatefulWidget { + static const routeName = '/info/tag_editor'; + + final Map<AvesEntry, Set<TagFilter>> tagsByEntry; + + const TagEditorPage({ + super.key, + required this.tagsByEntry, + }); + + @override + State<TagEditorPage> createState() => _TagEditorPageState(); +} + +class _TagEditorPageState extends State<TagEditorPage> { + final TextEditingController _newTagTextController = TextEditingController(); + final FocusNode _newTagTextFocusNode = FocusNode(); + final ValueNotifier<String?> _expandedSectionNotifier = ValueNotifier(null); + late final Map<AvesEntry, Set<CollectionFilter>> filtersByEntry; + late final List<CollectionFilter> _topTags; + final List<CollectionFilter> _userAddedFilters = []; + + static final List<PlaceholderFilter> _placeholders = [ + PlaceholderFilter.country, + PlaceholderFilter.state, + PlaceholderFilter.place, + ]; + + @override + void initState() { + super.initState(); + filtersByEntry = widget.tagsByEntry.map((key, value) => MapEntry(key, value.cast<CollectionFilter>().toSet())); + _expandedSectionNotifier.value = settings.tagEditorExpandedSection; + _expandedSectionNotifier.addListener(() => settings.tagEditorExpandedSection = _expandedSectionNotifier.value); + _initTopTags(); + WidgetsBinding.instance.addPostFrameCallback((_) { + final source = context.read<CollectionSource?>(); + settings.removeObsoleteRecentTags(source); + }); + } + + @override + void dispose() { + _newTagTextController.dispose(); + _newTagTextFocusNode.dispose(); + _expandedSectionNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + final showCount = filtersByEntry.length > 1; + final Map<CollectionFilter, int> entryCountByTag = {}; + filtersByEntry.entries.forEach((kv) { + kv.value.forEach((tag) => entryCountByTag[tag] = (entryCountByTag[tag] ?? 0) + 1); + }); + List<MapEntry<CollectionFilter, int>> sortedTags = _sortCurrentTags(entryCountByTag); + + final untaggedColor = Themes.backgroundTextColor(context); + + return PopScope( + canPop: !_isModified, + onPopInvokedWithResult: (didPop, result) async { + if (didPop) return; + + final NavigatorState navigator = Navigator.of(context); + final confirmed = await showDialog<bool>( + context: context, + builder: (context) => AvesDialog( + content: Text(context.l10n.tagEditorDiscardDialogMessage), + actions: [ + const CancelButton(), + TextButton( + onPressed: () => Navigator.maybeOf(context)?.pop(true), + child: Text(Themes.asButtonLabel(MaterialLocalizations.of(context).okButtonLabel)), + ), + ], + ), + routeSettings: const RouteSettings(name: AvesDialog.warningRouteName), + ) ?? + false; + if (confirmed) { + navigator.pop(); + } + }, + child: AvesScaffold( + appBar: AppBar( + title: Text(l10n.tagEditorPageTitle), + actions: [ + IconButton( + icon: const Icon(AIcons.reset), + onPressed: _reset, + tooltip: l10n.resetTooltip, + ), + IconButton( + icon: const Icon(AIcons.apply), + onPressed: () => Navigator.maybeOf(context)?.pop(filtersByEntry), + tooltip: l10n.saveTooltip, + ), + const SizedBox(width: 16), + ], + ), + body: SafeArea( + child: ValueListenableBuilder<String?>( + valueListenable: _expandedSectionNotifier, + builder: (context, expandedSection, child) { + return ValueListenableBuilder<TextEditingValue>( + valueListenable: _newTagTextController, + builder: (context, value, child) { + final upQuery = value.text.trim().toUpperCase(); + bool containQuery(CollectionFilter v) => v.getLabel(context).toUpperCase().contains(upQuery); + final recentFilters = settings.recentTags.where(containQuery).toList(); + final topTagFilters = _topTags.where(containQuery).toList(); + final placeholderFilters = _placeholders.where(containQuery).toList(); + return ListView( + children: [ + Padding( + padding: const EdgeInsetsDirectional.only(start: 8, end: 16), + child: Row( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Expanded( + child: TextField( + controller: _newTagTextController, + focusNode: _newTagTextFocusNode, + decoration: InputDecoration( + labelText: l10n.tagEditorPageNewTagFieldLabel, + ), + autofocus: true, + onSubmitted: (newTag) { + _addCustomTag(newTag); + _newTagTextFocusNode.requestFocus(); + }, + ), + ), + ValueListenableBuilder<TextEditingValue>( + valueListenable: _newTagTextController, + builder: (context, value, child) { + return IconButton( + icon: const Icon(AIcons.add), + onPressed: value.text.trim().isEmpty ? null : () => _addCustomTag(_newTagTextController.text), + tooltip: l10n.tagEditorPageAddTagTooltip, + ); + }, + ), + Selector<Settings, bool>( + selector: (context, s) => s.tagEditorCurrentFilterSectionExpanded, + builder: (context, isExpanded, child) { + return IconButton( + icon: Icon(isExpanded ? AIcons.collapse : AIcons.expand), + onPressed: sortedTags.isEmpty ? null : () => settings.tagEditorCurrentFilterSectionExpanded = !isExpanded, + tooltip: isExpanded ? MaterialLocalizations.of(context).expandedIconTapHint : MaterialLocalizations.of(context).collapsedIconTapHint, + ); + }, + ), + ], + ), + ), + Padding( + padding: const EdgeInsets.symmetric(vertical: 16), + child: AnimatedCrossFade( + firstChild: ConstrainedBox( + constraints: const BoxConstraints(minHeight: AvesFilterChip.minChipHeight), + child: Center( + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(AIcons.tagUntagged, color: untaggedColor), + const SizedBox(width: 8), + Text( + l10n.filterNoTagLabel, + style: TextStyle(color: untaggedColor), + ), + ], + ), + ), + ), + secondChild: ExpandableFilterRow( + filters: sortedTags.map((kv) => kv.key).toList(), + isExpanded: context.select<Settings, bool>((v) => v.tagEditorCurrentFilterSectionExpanded), + showGenericIcon: false, + leadingBuilder: showCount + ? (filter) => _TagCount( + count: sortedTags.firstWhere((kv) => kv.key == filter).value, + ) + : null, + onTap: (filter) { + if (filtersByEntry.keys.length > 1) { + // for multiple entries, set tag for all of them + filtersByEntry.forEach((entry, filters) => filters.add(filter)); + setState(() {}); + } else { + // for single entry, remove tag (like pressing on the remove icon) + _removeTag(filter); + } + }, + onRemove: _removeTag, + onLongPress: null, + ), + crossFadeState: sortedTags.isEmpty ? CrossFadeState.showFirst : CrossFadeState.showSecond, + duration: ADurations.tagEditorTransition, + ), + ), + const Divider(height: 0), + _FilterRow( + title: l10n.statsTopTagsSectionTitle, + filters: topTagFilters, + expandedNotifier: _expandedSectionNotifier, + onTap: _addTag, + ), + _FilterRow( + title: l10n.tagEditorSectionRecent, + filters: recentFilters, + expandedNotifier: _expandedSectionNotifier, + onTap: _addTag, + ), + _FilterRow( + title: l10n.tagEditorSectionPlaceholders, + filters: placeholderFilters, + expandedNotifier: _expandedSectionNotifier, + onTap: _addTag, + ), + ], + ); + }, + ); + }, + ), + ), + ), + ); + } + + void _initTopTags() { + final Map<String, int> entryCountByTag = {}; + final visibleEntries = context.read<CollectionSource?>()?.visibleEntries; + visibleEntries?.forEach((entry) { + entry.tags.forEach((tag) => entryCountByTag[tag] = (entryCountByTag[tag] ?? 0) + 1); + }); + List<MapEntry<CollectionFilter, int>> sortedTopTags = _sortCurrentTags(entryCountByTag.map((key, value) => MapEntry(TagFilter(key), value))); + _topTags = sortedTopTags.map((kv) => kv.key).toList(); + } + + List<MapEntry<CollectionFilter, int>> _sortCurrentTags(Map<CollectionFilter, int> entryCountByTag) { + return entryCountByTag.entries.toList() + ..sort((kv1, kv2) { + final filter1 = kv1.key; + final filter2 = kv2.key; + + final recent1 = _userAddedFilters.indexOf(filter1); + final recent2 = _userAddedFilters.indexOf(filter2); + var c = recent2.compareTo(recent1); + if (c != 0) return c; + + final count1 = kv1.value; + final count2 = kv2.value; + c = count2.compareTo(count1); + if (c != 0) return c; + + return filter1.compareTo(filter2); + }); + } + + bool get _isModified { + for (final kv in filtersByEntry.entries) { + final oldFilters = kv.key.tags.map(TagFilter.new).toSet(); + final newFilters = kv.value; + if (newFilters.length != oldFilters.length || !newFilters.containsAll(oldFilters)) return true; + } + return false; + } + + void _reset() { + _userAddedFilters.clear(); + filtersByEntry.forEach((entry, tags) { + final originalFilters = entry.tags.map(TagFilter.new).toSet(); + tags + ..clear() + ..addAll(originalFilters); + }); + setState(() {}); + } + + void _addCustomTag(String newTag) { + newTag = newTag.trim(); + if (newTag.isNotEmpty) { + _addTag(TagFilter(newTag)); + } + } + + void _addTag(CollectionFilter filter) { + settings.recentTags = settings.recentTags + ..remove(filter) + ..insert(0, filter); + _userAddedFilters + ..remove(filter) + ..add(filter); + filtersByEntry.forEach((entry, tags) => tags.add(filter)); + _newTagTextController.clear(); + setState(() {}); + } + + void _removeTag(CollectionFilter filter) { + _userAddedFilters.remove(filter); + filtersByEntry.forEach((entry, filters) => filters.remove(filter)); + setState(() {}); + } +} + +class _FilterRow extends StatelessWidget { + final String title; + final List<CollectionFilter> filters; + final ValueNotifier<String?> expandedNotifier; + final void Function(CollectionFilter filter) onTap; + + const _FilterRow({ + required this.title, + required this.filters, + required this.expandedNotifier, + required this.onTap, + }); + + @override + Widget build(BuildContext context) { + return filters.isEmpty + ? const SizedBox() + : TitledExpandableFilterRow( + title: title, + filters: filters, + expandedNotifier: expandedNotifier, + showGenericIcon: false, + onTap: onTap, + onLongPress: null, + ); + } +} + +class _TagCount extends StatelessWidget { + final int count; + + const _TagCount({ + required this.count, + }); + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.symmetric(vertical: 2, horizontal: 6), + decoration: BoxDecoration( + border: Border.fromBorderSide(BorderSide( + color: DefaultTextStyle.of(context).style.color!, + )), + borderRadius: const BorderRadius.all(Radius.circular(123)), + ), + child: Text( + '$count', + style: const TextStyle(fontSize: AvesFilterChip.fontSize), + ), + ); + } +} diff --git a/lib/widgets/dialogs/filter_editors/cover_selection_dialog.dart b/lib/widgets/dialogs/filter_editors/cover_selection_dialog.dart new file mode 100644 index 0000000..11ffb00 --- /dev/null +++ b/lib/widgets/dialogs/filter_editors/cover_selection_dialog.dart @@ -0,0 +1,458 @@ +import 'dart:math'; + +import 'package:aves/image_providers/app_icon_image_provider.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/filters/covered/stored_album.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/basic/color_indicator.dart'; +import 'package:aves/widgets/common/basic/list_tiles/color.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/fx/borders.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:aves/widgets/dialogs/item_picker.dart'; +import 'package:aves/widgets/dialogs/pick_dialogs/app_pick_page.dart'; +import 'package:aves/widgets/dialogs/pick_dialogs/item_pick_page.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:provider/provider.dart'; + +class CoverSelectionDialog extends StatefulWidget { + static const routeName = '/dialog/select_cover'; + + final CollectionFilter filter; + final AvesEntry? customEntry; + final String? customPackage; + final Color? customColor; + + const CoverSelectionDialog({ + super.key, + required this.filter, + required this.customEntry, + required this.customPackage, + required this.customColor, + }); + + @override + State<CoverSelectionDialog> createState() => _CoverSelectionDialogState(); +} + +class _CoverSelectionDialogState extends State<CoverSelectionDialog> { + late bool _isCustomEntry, _isCustomPackage, _isCustomColor; + AvesEntry? _customEntry; + String? _customPackage; + Color? _customColor; + + CollectionFilter get filter => widget.filter; + + bool get showAppTab => filter is StoredAlbumFilter && settings.isInstalledAppAccessAllowed; + + bool get showColorTab => settings.themeColorMode == AvesThemeColorMode.polychrome; + + static const double itemPickerExtent = 46; + static const double appPickerExtent = 32; + + double tabBarHeight(BuildContext context) { + return MediaQuery.textScalerOf(context).clamp(minScaleFactor: 1).scale(64); + } + + static const double tabIndicatorWeight = 2; + + @override + void initState() { + super.initState(); + + _customEntry = widget.customEntry; + _isCustomEntry = _customEntry != null; + + _customPackage = widget.customPackage; + _isCustomPackage = _customPackage != null; + + _customColor = widget.customColor; + _isCustomColor = _customColor != null; + } + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + final tabs = <(Tab, Widget)>[ + ( + _buildTab( + context, + const Key('tab-entry'), + AIcons.image, + l10n.coverDialogTabCover, + ), + Column(children: _buildEntryOptions()), + ), + if (showAppTab) + ( + _buildTab( + context, + const Key('tab-package'), + AIcons.app, + l10n.coverDialogTabApp, + ), + Column(children: _buildAppOptions()), + ), + if (showColorTab) + ( + _buildTab( + context, + const Key('tab-color'), + AIcons.palette, + l10n.coverDialogTabColor, + ), + Column(children: _buildColorOptions()), + ), + ]; + + final contentWidget = DecoratedBox( + decoration: AvesDialog.contentDecoration(context), + child: LayoutBuilder( + builder: (context, constraints) { + final availableBodyHeight = constraints.maxHeight - tabBarHeight(context) - tabIndicatorWeight; + final maxHeight = min(availableBodyHeight, tabBodyMaxHeight(context)); + return DefaultTabController( + length: 1 + (showAppTab ? 1 : 0) + (showColorTab ? 1 : 0), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Material( + borderRadius: const BorderRadius.vertical( + top: AvesDialog.cornerRadius, + ), + clipBehavior: Clip.antiAlias, + child: TabBar( + indicatorWeight: tabIndicatorWeight, + tabs: tabs.map((t) => t.$1).toList(), + ), + ), + ConstrainedBox( + constraints: BoxConstraints(maxHeight: maxHeight), + child: TabBarView( + physics: const NeverScrollableScrollPhysics(), + children: tabs + .map((t) => SingleChildScrollView( + child: t.$2, + )) + .toList(), + ), + ), + ], + ), + ); + }, + ), + ); + + final actionsWidget = Padding( + padding: AvesDialog.actionsPadding, + child: OverflowBar( + alignment: MainAxisAlignment.end, + spacing: AvesDialog.buttonPadding.horizontal / 2, + overflowAlignment: OverflowBarAlignment.end, + children: [ + const CancelButton(), + TextButton( + onPressed: () { + final entry = _isCustomEntry ? _customEntry : null; + final package = _isCustomPackage ? _customPackage : null; + final color = _isCustomColor ? _customColor : null; + return Navigator.maybeOf(context)?.pop<(AvesEntry?, String?, Color?)>((entry, package, color)); + }, + child: Text(l10n.applyButtonLabel), + ) + ], + ), + ); + + Widget dialogChild = LayoutBuilder( + builder: (context, constraints) { + final availableBodyWidth = constraints.maxWidth; + final maxWidth = min(availableBodyWidth, tabBodyMaxWidth(context)); + return ConstrainedBox( + constraints: BoxConstraints(maxWidth: maxWidth), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Flexible(child: contentWidget), + actionsWidget, + ], + ), + ); + }, + ); + + return Dialog( + shape: AvesDialog.shape(context), + child: dialogChild, + ); + } + + List<Widget> _buildEntryOptions() { + final l10n = context.l10n; + return [false, true].map( + (isCustom) { + final title = Text( + isCustom ? l10n.setCoverDialogCustom : l10n.setCoverDialogLatest, + softWrap: false, + overflow: TextOverflow.fade, + maxLines: 1, + ); + return ListTileTheme.merge( + minVerticalPadding: isCustom && _customEntry != null ? 0 : null, + child: RadioListTile<bool>( + value: isCustom, + groupValue: _isCustomEntry, + onChanged: (v) { + if (v == null) return; + if (v && _customEntry == null) { + _pickEntry(); + return; + } + _isCustomEntry = v; + setState(() {}); + }, + title: isCustom + ? Row( + children: [ + title, + const Spacer(), + if (_customEntry != null) + ItemPicker( + extent: itemPickerExtent, + entry: _customEntry!, + onTap: _pickEntry, + ), + ], + ) + : title, + ), + ); + }, + ).toList(); + } + + List<Widget> _buildAppOptions() { + final l10n = context.l10n; + return [false, true].map( + (isCustom) { + final title = Text( + isCustom ? l10n.setCoverDialogCustom : l10n.setCoverDialogAuto, + softWrap: false, + overflow: TextOverflow.fade, + maxLines: 1, + ); + return RadioListTile<bool>( + value: isCustom, + groupValue: _isCustomPackage, + onChanged: (v) { + if (v == null) return; + if (v && _customPackage == null) { + _pickPackage(); + return; + } + _isCustomPackage = v; + setState(() {}); + }, + title: isCustom + ? Row( + children: [ + title, + const Spacer(), + if (_customPackage != null) + GestureDetector( + onTap: _pickPackage, + child: _customPackage!.isNotEmpty + ? Image( + image: AppIconImage( + packageName: _customPackage!, + size: appPickerExtent, + ), + width: appPickerExtent, + height: appPickerExtent, + ) + : Container( + height: appPickerExtent, + width: appPickerExtent, + decoration: BoxDecoration( + border: AvesBorder.border(context), + shape: BoxShape.circle, + ), + child: const Icon(AIcons.clear), + ), + ), + ], + ) + : title, + ); + }, + ).toList(); + } + + List<Widget> _buildColorOptions() { + final l10n = context.l10n; + return [false, true].map( + (isCustom) { + final title = Text( + isCustom ? l10n.setCoverDialogCustom : l10n.setCoverDialogAuto, + softWrap: false, + overflow: TextOverflow.fade, + maxLines: 1, + ); + return RadioListTile<bool>( + value: isCustom, + groupValue: _isCustomColor, + onChanged: (v) { + if (v == null) return; + if (v && _customColor == null) { + _pickColor(); + return; + } + _isCustomColor = v; + setState(() {}); + }, + title: isCustom + ? Row( + children: [ + title, + const Spacer(), + if (_customColor != null) + GestureDetector( + onTap: _pickColor, + child: ColorIndicator( + value: _customColor, + ), + ), + ], + ) + : title, + ); + }, + ).toList(); + } + + Future<void> _pickEntry() async { + final entry = await Navigator.maybeOf(context)?.push<AvesEntry>( + MaterialPageRoute( + settings: const RouteSettings(name: ItemPickPage.routeName), + builder: (context) => ItemPickPage( + collection: CollectionLens( + source: context.read<CollectionSource>(), + filters: {filter}, + ), + canRemoveFilters: false, + ), + fullscreenDialog: true, + ), + ); + if (entry != null) { + _customEntry = entry; + _isCustomEntry = true; + setState(() {}); + } + } + + Future<void> _pickPackage() async { + final package = await Navigator.maybeOf(context)?.push<String>( + MaterialPageRoute( + settings: const RouteSettings(name: AppPickPage.routeName), + builder: (context) => AppPickPage( + initialValue: _customPackage, + ), + fullscreenDialog: true, + ), + ); + if (package != null) { + _customPackage = package; + _isCustomPackage = true; + setState(() {}); + } + } + + Future<void> _pickColor() async { + final color = await showDialog<Color>( + context: context, + builder: (context) => ColorPickerDialog( + // avoid a pure material color as the default, so that + // picker controls are not on edge and palette panel is more stable + initialValue: _customColor ?? const Color(0xff3f51b5), + ), + routeSettings: const RouteSettings(name: ColorPickerDialog.routeName), + ); + if (color != null) { + _customColor = color; + _isCustomColor = true; + setState(() {}); + } + } + + // tabs + + Tab _buildTab( + BuildContext context, + Key key, + IconData icon, + String text, { + Color? color, + }) { + // cannot use `IconTheme` over `TabBar` to change size, + // because `TabBar` does so internally + final textScaler = MediaQuery.textScalerOf(context); + final iconSize = textScaler.scale(IconTheme.of(context).size!); + return Tab( + key: key, + height: tabBarHeight(context), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + icon, + size: iconSize, + color: color, + ), + const SizedBox(height: 4), + Text( + text, + style: TextStyle(color: color), + softWrap: false, + overflow: TextOverflow.fade, + ), + ], + ), + ); + } + + // based on `ListTile` height computation (one line, no subtitle, not dense) + double singleOptionTileHeight(BuildContext context) => 56.0 + Theme.of(context).visualDensity.baseSizeAdjustment.dy; + + double tabBodyMaxWidth(BuildContext context) { + final l10n = context.l10n; + final _optionLines = { + l10n.setCoverDialogLatest, + l10n.setCoverDialogAuto, + l10n.setCoverDialogCustom, + }.fold('', (previousValue, element) => '$previousValue\n$element'); + + final paragraph = RenderParagraph( + TextSpan(text: _optionLines, style: Theme.of(context).textTheme.titleMedium!), + textDirection: TextDirection.ltr, + textScaler: MediaQuery.textScalerOf(context), + )..layout(const BoxConstraints(), parentUsesSize: true); + final textWidth = paragraph.getMaxIntrinsicWidth(double.infinity); + paragraph.dispose(); + + // from `RadioListTile` layout + const contentPadding = 32; + const leadingWidth = kMinInteractiveDimension + 8; + return contentPadding + leadingWidth + textWidth + itemPickerExtent; + } + + double tabBodyMaxHeight(BuildContext context) => 2 * singleOptionTileHeight(context); +} diff --git a/lib/widgets/dialogs/filter_editors/create_dynamic_album_dialog.dart b/lib/widgets/dialogs/filter_editors/create_dynamic_album_dialog.dart new file mode 100644 index 0000000..6dc3e68 --- /dev/null +++ b/lib/widgets/dialogs/filter_editors/create_dynamic_album_dialog.dart @@ -0,0 +1,92 @@ +import 'package:aves/model/dynamic_albums.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:flutter/material.dart'; + +class CreateDynamicAlbumDialog extends StatefulWidget { + static const routeName = '/dialog/create_dynamic_album'; + + const CreateDynamicAlbumDialog({super.key}); + + @override + State<CreateDynamicAlbumDialog> createState() => _CreateDynamicAlbumDialogState(); +} + +class _CreateDynamicAlbumDialogState extends State<CreateDynamicAlbumDialog> { + final TextEditingController _nameController = TextEditingController(); + final ValueNotifier<bool> _existsNotifier = ValueNotifier(false); + final ValueNotifier<bool> _isValidNotifier = ValueNotifier(false); + + @override + void initState() { + super.initState(); + _validate(); + } + + @override + void dispose() { + _nameController.dispose(); + _existsNotifier.dispose(); + _isValidNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + + return AvesDialog( + title: l10n.newDynamicAlbumDialogTitle, + content: ValueListenableBuilder<bool>( + valueListenable: _existsNotifier, + builder: (context, exists, child) { + return TextField( + controller: _nameController, + decoration: InputDecoration( + labelText: l10n.newAlbumDialogNameLabel, + helperText: exists ? l10n.dynamicAlbumAlreadyExists : '', + ), + autofocus: true, + onChanged: (_) => _validate(), + onSubmitted: (_) => _submit(context), + ); + }), + actions: [ + const CancelButton(), + ValueListenableBuilder<bool>( + valueListenable: _existsNotifier, + builder: (context, exists, child) { + return ValueListenableBuilder<bool>( + valueListenable: _isValidNotifier, + builder: (context, isValid, child) { + return TextButton( + onPressed: isValid ? () => _submit(context) : null, + child: Text(exists ? l10n.showButtonLabel : l10n.createAlbumButtonLabel), + ); + }, + ); + }, + ), + ], + ); + } + + String? _formatAlbumName() { + final name = _nameController.text.trim(); + if (name.isEmpty) return null; + + return name; + } + + void _validate() { + final name = _formatAlbumName(); + _isValidNotifier.value = name != null; + _existsNotifier.value = dynamicAlbums.contains(name); + } + + void _submit(BuildContext context) { + if (_isValidNotifier.value) { + Navigator.maybeOf(context)?.pop(_formatAlbumName()); + } + } +} diff --git a/lib/widgets/dialogs/filter_editors/create_group_dialog.dart b/lib/widgets/dialogs/filter_editors/create_group_dialog.dart new file mode 100644 index 0000000..055c5fb --- /dev/null +++ b/lib/widgets/dialogs/filter_editors/create_group_dialog.dart @@ -0,0 +1,99 @@ +import 'package:aves/model/grouping/common.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:flutter/material.dart'; + +class CreateGroupDialog extends StatefulWidget { + static const routeName = '/dialog/create_group'; + + final FilterGrouping grouping; + final Uri? parentGroupUri; + + const CreateGroupDialog({ + super.key, + required this.grouping, + required this.parentGroupUri, + }); + + @override + State<CreateGroupDialog> createState() => _CreateGroupDialogState(); +} + +class _CreateGroupDialogState extends State<CreateGroupDialog> { + final TextEditingController _nameController = TextEditingController(); + final ValueNotifier<bool> _existsNotifier = ValueNotifier(false); + final ValueNotifier<bool> _isValidNotifier = ValueNotifier(false); + + FilterGrouping get grouping => widget.grouping; + + Uri? get parentGroupUri => widget.parentGroupUri; + + @override + void initState() { + super.initState(); + _validate(); + } + + @override + void dispose() { + _nameController.dispose(); + _existsNotifier.dispose(); + _isValidNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + + return AvesDialog( + title: l10n.newGroupDialogTitle, + content: ValueListenableBuilder<bool>( + valueListenable: _existsNotifier, + builder: (context, exists, child) { + return TextField( + controller: _nameController, + decoration: InputDecoration( + labelText: l10n.newGroupDialogNameLabel, + helperText: exists ? l10n.groupAlreadyExists : '', + ), + autofocus: true, + onChanged: (_) => _validate(), + onSubmitted: (_) => _submit(context), + ); + }, + ), + actions: [ + const CancelButton(), + ValueListenableBuilder<bool>( + valueListenable: _isValidNotifier, + builder: (context, isValid, child) { + return TextButton( + onPressed: isValid ? () => _submit(context) : null, + child: Text(l10n.createButtonLabel), + ); + }, + ), + ], + ); + } + + Uri? _getNewGroupUri() { + final name = _nameController.text.trim(); + if (name.isEmpty) return null; + return grouping.buildGroupUri(parentGroupUri, name); + } + + void _validate() { + final newGroupUri = _getNewGroupUri(); + final exists = grouping.exists(newGroupUri); + _isValidNotifier.value = newGroupUri != null && !exists; + _existsNotifier.value = exists; + } + + void _submit(BuildContext context) { + if (_isValidNotifier.value) { + Navigator.maybeOf(context)?.pop(_getNewGroupUri()); + } + } +} diff --git a/lib/widgets/dialogs/filter_editors/create_stored_album_dialog.dart b/lib/widgets/dialogs/filter_editors/create_stored_album_dialog.dart new file mode 100644 index 0000000..cd07ca0 --- /dev/null +++ b/lib/widgets/dialogs/filter_editors/create_stored_album_dialog.dart @@ -0,0 +1,204 @@ +import 'dart:io'; + +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/utils/android_file_utils.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class CreateStoredAlbumDialog extends StatefulWidget { + static const routeName = '/dialog/create_stored_album'; + + const CreateStoredAlbumDialog({super.key}); + + @override + State<CreateStoredAlbumDialog> createState() => _CreateStoredAlbumDialogState(); +} + +class _CreateStoredAlbumDialogState extends State<CreateStoredAlbumDialog> { + final ScrollController _scrollController = ScrollController(); + final TextEditingController _nameController = TextEditingController(); + final FocusNode _nameFieldFocusNode = FocusNode(); + final ValueNotifier<bool> _directoryExistsNotifier = ValueNotifier(false); + final ValueNotifier<bool> _albumExistsNotifier = ValueNotifier(false); + final ValueNotifier<bool> _isValidNotifier = ValueNotifier(false); + late Set<StorageVolume> _allVolumes; + late StorageVolume? _primaryVolume, _selectedVolume; + + @override + void initState() { + super.initState(); + _allVolumes = androidFileUtils.storageVolumes; + _primaryVolume = _allVolumes.firstWhereOrNull((volume) => volume.isPrimary) ?? _allVolumes.firstOrNull; + _selectedVolume = _primaryVolume; + _nameFieldFocusNode.addListener(_onFocus); + } + + @override + void dispose() { + _scrollController.dispose(); + _nameController.dispose(); + _nameFieldFocusNode.removeListener(_onFocus); + _nameFieldFocusNode.dispose(); + _directoryExistsNotifier.dispose(); + _isValidNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + const contentHorizontalPadding = EdgeInsets.symmetric(horizontal: AvesDialog.defaultHorizontalContentPadding); + + final volumeTiles = <Widget>[]; + if (_allVolumes.length > 1) { + final byPrimary = groupBy<StorageVolume, bool>(_allVolumes, (volume) => volume.isPrimary); + int compare(StorageVolume a, StorageVolume b) => compareAsciiUpperCaseNatural(a.path, b.path); + final primaryVolumes = (byPrimary[true] ?? [])..sort(compare); + final otherVolumes = (byPrimary[false] ?? [])..sort(compare); + volumeTiles.addAll([ + Padding( + padding: contentHorizontalPadding + const EdgeInsets.only(top: 20), + child: Text(l10n.newAlbumDialogStorageLabel), + ), + ...primaryVolumes.map((volume) => _buildVolumeTile(context, volume)), + ...otherVolumes.map((volume) => _buildVolumeTile(context, volume)), + const SizedBox(height: 8), + ]); + } + + return AvesDialog( + title: l10n.newAlbumDialogTitle, + scrollController: _scrollController, + scrollableContent: [ + ...volumeTiles, + Padding( + padding: contentHorizontalPadding + const EdgeInsets.only(bottom: 8), + child: AnimatedBuilder( + animation: Listenable.merge([_albumExistsNotifier, _directoryExistsNotifier]), + builder: (context, child) { + var helperText = ''; + if (_albumExistsNotifier.value) { + helperText = l10n.newAlbumDialogAlbumAlreadyExistsHelper; + } else if (_directoryExistsNotifier.value) { + helperText = l10n.newAlbumDialogNameLabelAlreadyExistsHelper; + } + return TextField( + controller: _nameController, + focusNode: _nameFieldFocusNode, + decoration: InputDecoration( + labelText: l10n.newAlbumDialogNameLabel, + helperText: helperText, + ), + autofocus: _allVolumes.length == 1, + onChanged: (_) => _validate(), + onSubmitted: (_) => _submit(context), + ); + }), + ), + ], + actions: [ + const CancelButton(), + ValueListenableBuilder<bool>( + valueListenable: _albumExistsNotifier, + builder: (context, albumExists, child) { + return ValueListenableBuilder<bool>( + valueListenable: _isValidNotifier, + builder: (context, isValid, child) { + return TextButton( + onPressed: isValid ? () => _submit(context) : null, + child: Text(albumExists ? l10n.showButtonLabel : l10n.createAlbumButtonLabel), + ); + }, + ); + }, + ), + ], + ); + } + + Widget _buildVolumeTile(BuildContext context, StorageVolume volume) => RadioListTile<StorageVolume>( + value: volume, + groupValue: _selectedVolume, + onChanged: (volume) { + _selectedVolume = volume!; + _validate(); + setState(() {}); + }, + title: Text( + volume.getDescription(context), + softWrap: false, + overflow: TextOverflow.fade, + maxLines: 1, + ), + subtitle: Text( + volume.path, + softWrap: false, + overflow: TextOverflow.fade, + maxLines: 1, + ), + ); + + void _onFocus() async { + // when the field gets focus, we wait for the soft keyboard to appear + // then scroll to the bottom to make sure the field is in view + if (_nameFieldFocusNode.hasFocus) { + await Future.delayed(ADurations.softKeyboardDisplayDelay + const Duration(milliseconds: 500)); + _scrollToBottom(); + } + } + + void _scrollToBottom() { + _scrollController.animateTo( + _scrollController.position.maxScrollExtent, + duration: ADurations.dialogFieldReachAnimation, + curve: Curves.easeInOut, + ); + } + + Future<String?> _buildAlbumPath() async { + final name = _nameController.text.trim(); + if (name.isEmpty) return null; + + final volumePath = _selectedVolume?.path; + if (volumePath == null) return null; + + final candidatePath = pContext.join(volumePath, AndroidFileUtils.standardDirPictures, name); + + // uses resolved directory name case if it exists + var resolvedPath = volumePath; + final relativePathSegments = pContext.split(pContext.relative(candidatePath, from: volumePath)); + for (final targetSegment in relativePathSegments) { + String? resolvedSegment; + final directory = Directory(resolvedPath); + if (await directory.exists()) { + final lowerTargetSegment = targetSegment.toLowerCase(); + resolvedSegment = directory.listSync().map((v) => pContext.basename(v.path)).firstWhereOrNull((v) => v.toLowerCase() == lowerTargetSegment); + } + resolvedPath = pContext.join(resolvedPath, resolvedSegment ?? targetSegment); + } + + return resolvedPath; + } + + Future<void> _validate() async { + final path = await _buildAlbumPath(); + final isValid = path != null; + _isValidNotifier.value = isValid; + _directoryExistsNotifier.value = isValid && await Directory(path).exists(); + _albumExistsNotifier.value = isValid && context.read<CollectionSource>().rawAlbums.contains(path); + } + + Future<void> _submit(BuildContext context) async { + final path = await _buildAlbumPath(); + if (path == null) return; + + Navigator.maybeOf(context)?.pop(path); + } +} diff --git a/lib/widgets/dialogs/filter_editors/edit_vault_dialog.dart b/lib/widgets/dialogs/filter_editors/edit_vault_dialog.dart new file mode 100644 index 0000000..2017d21 --- /dev/null +++ b/lib/widgets/dialogs/filter_editors/edit_vault_dialog.dart @@ -0,0 +1,189 @@ +import 'package:aves/model/device.dart'; +import 'package:aves/model/filters/covered/stored_album.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/model/vaults/details.dart'; +import 'package:aves/model/vaults/vaults.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/action_mixins/feedback.dart'; +import 'package:aves/widgets/common/action_mixins/vault_aware.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/aves_caption.dart'; +import 'package:aves/widgets/dialogs/aves_confirmation_dialog.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:aves/widgets/dialogs/selection_dialogs/common.dart'; +import 'package:aves/widgets/dialogs/selection_dialogs/single_selection.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class EditVaultDialog extends StatefulWidget { + static const routeName = '/dialog/edit_vault'; + + final VaultDetails? initialDetails; + + const EditVaultDialog({ + super.key, + this.initialDetails, + }); + + @override + State<EditVaultDialog> createState() => _EditVaultDialogState(); +} + +class _EditVaultDialogState extends State<EditVaultDialog> with FeedbackMixin, VaultAwareMixin { + final TextEditingController _nameController = TextEditingController(); + late bool _useBin; + late bool _autoLockScreenOff; + late VaultLockType _lockType; + + final ValueNotifier<bool> _existsNotifier = ValueNotifier(false); + final ValueNotifier<bool> _isValidNotifier = ValueNotifier(false); + + final List<VaultLockType> _lockTypeOptions = [ + if (device.canAuthenticateUser) VaultLockType.system, + VaultLockType.pattern, + VaultLockType.pin, + VaultLockType.password, + ]; + + VaultDetails? get initialDetails => widget.initialDetails; + + String get newName => _nameController.text; + + @override + void initState() { + super.initState(); + final details = initialDetails ?? + VaultDetails( + name: '', + autoLockScreenOff: true, + useBin: settings.enableBin, + lockType: _lockTypeOptions.first, + ); + _nameController.text = details.name; + _useBin = details.useBin; + _autoLockScreenOff = details.autoLockScreenOff; + _lockType = details.lockType; + _validate(); + } + + @override + void dispose() { + _nameController.dispose(); + _existsNotifier.dispose(); + _isValidNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + final isNew = initialDetails == null; + return AvesDialog( + title: isNew ? l10n.newVaultDialogTitle : l10n.configureVaultDialogTitle, + scrollableContent: [ + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: ValueListenableBuilder<bool>( + valueListenable: _existsNotifier, + builder: (context, exists, child) { + return TextField( + controller: _nameController, + decoration: InputDecoration( + labelText: l10n.newAlbumDialogNameLabel, + helperText: exists ? l10n.newAlbumDialogNameLabelAlreadyExistsHelper : '', + ), + onChanged: (_) => _validate(), + onSubmitted: (_) => _submit(context), + ); + }), + ), + if (_lockTypeOptions.length > 1) + ListTile( + title: Text(l10n.vaultDialogLockTypeLabel), + subtitle: AvesCaption(_lockType.getText(context)), + onTap: () { + _unfocus(); + showSelectionDialog<VaultLockType>( + context: context, + builder: (context) => AvesSingleSelectionDialog<VaultLockType>( + initialValue: _lockType, + options: Map.fromEntries(_lockTypeOptions.map((v) => MapEntry(v, v.getText(context)))), + ), + onSelection: (v) => setState(() => _lockType = v), + ); + }, + ), + SwitchListTile( + value: _autoLockScreenOff, + onChanged: (v) => setState(() => _autoLockScreenOff = v), + title: Text(l10n.vaultDialogLockModeWhenScreenOff), + ), + if (settings.enableBin) + SwitchListTile( + value: _useBin, + onChanged: (v) async { + if (!v) { + final album = initialDetails?.path; + if (album != null) { + final filter = StoredAlbumFilter(album, null); + final source = context.read<CollectionSource>(); + if (source.trashedEntries.any(filter.test)) { + if (!await showConfirmationDialog( + context: context, + message: l10n.settingsDisablingBinWarningDialogMessage, + confirmationButtonLabel: l10n.applyButtonLabel, + )) { + return; + } + } + } + } + setState(() => _useBin = v); + }, + title: Text(l10n.settingsEnableBin), + ), + ], + actions: [ + const CancelButton(), + ValueListenableBuilder<bool>( + valueListenable: _isValidNotifier, + builder: (context, isValid, child) { + return TextButton( + onPressed: isValid ? () => _submit(context) : null, + child: Text(isNew ? l10n.createAlbumButtonLabel : l10n.applyButtonLabel), + ); + }, + ), + ], + ); + } + + // remove focus, if any, to prevent the keyboard from showing up + // after the user is done with the dialog + void _unfocus() => FocusManager.instance.primaryFocus?.unfocus(); + + Future<void> _validate() async { + final notEmpty = newName.isNotEmpty; + final exists = notEmpty && vaults.all.map((v) => v.name).contains(newName) && newName != initialDetails?.name; + _existsNotifier.value = exists; + _isValidNotifier.value = notEmpty && !exists; + } + + Future<void> _submit(BuildContext context) async { + if (!_isValidNotifier.value) return; + + _unfocus(); + + final details = VaultDetails( + name: newName, + autoLockScreenOff: _autoLockScreenOff, + useBin: _useBin, + lockType: _lockType, + ); + if (!await setVaultPass(context, details)) return; + + Navigator.maybeOf(context)?.pop(details); + } +} diff --git a/lib/widgets/dialogs/filter_editors/password_dialog.dart b/lib/widgets/dialogs/filter_editors/password_dialog.dart new file mode 100644 index 0000000..72f6331 --- /dev/null +++ b/lib/widgets/dialogs/filter_editors/password_dialog.dart @@ -0,0 +1,85 @@ +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:flutter/material.dart'; + +class PasswordDialog extends StatefulWidget { + static const routeName = '/dialog/password'; + + final bool needConfirmation; + + const PasswordDialog({ + super.key, + required this.needConfirmation, + }); + + @override + State<PasswordDialog> createState() => _PasswordDialogState(); +} + +class _PasswordDialogState extends State<PasswordDialog> { + final _controller = TextEditingController(); + final _focusNode = FocusNode(); + bool _confirming = false; + String? _firstPassword; + + @override + void initState() { + super.initState(); + _focusNode.requestFocus(); + } + + @override + void dispose() { + _controller.dispose(); + _focusNode.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return AvesDialog( + content: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text(_confirming ? context.l10n.passwordDialogConfirm : context.l10n.passwordDialogEnter), + Padding( + padding: const EdgeInsets.symmetric(vertical: 16), + child: TextField( + controller: _controller, + focusNode: _focusNode, + obscureText: true, + onSubmitted: _submit, + autofillHints: const [AutofillHints.password], + ), + ), + ], + ), + ); + } + + void _submit(String password) { + if (widget.needConfirmation) { + if (_confirming) { + final match = _firstPassword == password; + Navigator.maybeOf(context)?.pop<String>(match ? password : null); + if (!match) { + showDialog( + context: context, + builder: (context) => AvesDialog( + content: Text(context.l10n.genericFailureFeedback), + actions: const [OkButton()], + ), + routeSettings: const RouteSettings(name: AvesDialog.warningRouteName), + ); + } + } else { + _firstPassword = password; + _controller.clear(); + setState(() => _confirming = true); + WidgetsBinding.instance.addPostFrameCallback((_) => _focusNode.requestFocus()); + } + } else { + Navigator.maybeOf(context)?.pop<String>(password); + } + } +} diff --git a/lib/widgets/dialogs/filter_editors/pattern_dialog.dart b/lib/widgets/dialogs/filter_editors/pattern_dialog.dart new file mode 100644 index 0000000..7bfd49a --- /dev/null +++ b/lib/widgets/dialogs/filter_editors/pattern_dialog.dart @@ -0,0 +1,74 @@ +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:flutter/material.dart'; +import 'package:pattern_lock/pattern_lock.dart'; + +class PatternDialog extends StatefulWidget { + static const routeName = '/dialog/pattern'; + + final bool needConfirmation; + + const PatternDialog({ + super.key, + required this.needConfirmation, + }); + + @override + State<PatternDialog> createState() => _PatternDialogState(); +} + +class _PatternDialogState extends State<PatternDialog> { + bool _confirming = false; + String? _firstPattern; + + @override + Widget build(BuildContext context) { + final colorScheme = Theme.of(context).colorScheme; + return AvesDialog( + content: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text(_confirming ? context.l10n.patternDialogConfirm : context.l10n.patternDialogEnter), + Padding( + padding: const EdgeInsets.symmetric(vertical: 16), + child: SizedBox.square( + dimension: MediaQuery.sizeOf(context).shortestSide / 2, + child: PatternLock( + relativePadding: .4, + selectedColor: colorScheme.primary, + notSelectedColor: colorScheme.onSurface, + pointRadius: 8, + fillPoints: true, + onInputComplete: (input) => _submit(input.join()), + ), + ), + ), + ], + ), + ); + } + + void _submit(String pattern) { + if (widget.needConfirmation) { + if (_confirming) { + final match = _firstPattern == pattern; + Navigator.maybeOf(context)?.pop<String>(match ? pattern : null); + if (!match) { + showDialog( + context: context, + builder: (context) => AvesDialog( + content: Text(context.l10n.genericFailureFeedback), + actions: const [OkButton()], + ), + routeSettings: const RouteSettings(name: AvesDialog.warningRouteName), + ); + } + } else { + _firstPattern = pattern; + setState(() => _confirming = true); + } + } else { + Navigator.maybeOf(context)?.pop<String>(pattern); + } + } +} diff --git a/lib/widgets/dialogs/filter_editors/pin_dialog.dart b/lib/widgets/dialogs/filter_editors/pin_dialog.dart new file mode 100644 index 0000000..00b8bc2 --- /dev/null +++ b/lib/widgets/dialogs/filter_editors/pin_dialog.dart @@ -0,0 +1,91 @@ +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:flutter/material.dart'; +import 'package:pin_code_fields/pin_code_fields.dart'; + +class PinDialog extends StatefulWidget { + static const routeName = '/dialog/pin'; + + final bool needConfirmation; + + const PinDialog({ + super.key, + required this.needConfirmation, + }); + + @override + State<PinDialog> createState() => _PinDialogState(); +} + +class _PinDialogState extends State<PinDialog> { + final _controller = TextEditingController(); + bool _confirming = false; + String? _firstPin; + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final colorScheme = Theme.of(context).colorScheme; + return AvesDialog( + content: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text(_confirming ? context.l10n.pinDialogConfirm : context.l10n.pinDialogEnter), + Padding( + padding: const EdgeInsets.symmetric(vertical: 16), + child: PinCodeTextField( + appContext: context, + length: 4, + controller: _controller, + obscureText: true, + onChanged: (v) {}, + onCompleted: _submit, + animationType: AnimationType.scale, + keyboardType: TextInputType.number, + autoFocus: true, + autoDismissKeyboard: !widget.needConfirmation || _confirming, + pinTheme: PinTheme( + activeColor: colorScheme.onSurface, + inactiveColor: colorScheme.onSurface, + selectedColor: colorScheme.primary, + selectedFillColor: colorScheme.primary, + borderRadius: BorderRadius.circular(8), + shape: PinCodeFieldShape.box, + ), + ), + ), + ], + ), + ); + } + + void _submit(String pin) { + if (widget.needConfirmation) { + if (_confirming) { + final match = _firstPin == pin; + Navigator.maybeOf(context)?.pop<String>(match ? pin : null); + if (!match) { + showDialog( + context: context, + builder: (context) => AvesDialog( + content: Text(context.l10n.genericFailureFeedback), + actions: const [OkButton()], + ), + routeSettings: const RouteSettings(name: AvesDialog.warningRouteName), + ); + } + } else { + _firstPin = pin; + _controller.clear(); + setState(() => _confirming = true); + } + } else { + Navigator.maybeOf(context)?.pop<String>(pin); + } + } +} diff --git a/lib/widgets/dialogs/filter_editors/rename_dynamic_album_dialog.dart b/lib/widgets/dialogs/filter_editors/rename_dynamic_album_dialog.dart new file mode 100644 index 0000000..7af1bc6 --- /dev/null +++ b/lib/widgets/dialogs/filter_editors/rename_dynamic_album_dialog.dart @@ -0,0 +1,93 @@ +import 'package:aves/model/dynamic_albums.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:flutter/material.dart'; + +class RenameDynamicAlbumDialog extends StatefulWidget { + static const routeName = '/dialog/rename_dynamic_album'; + + final String name; + + const RenameDynamicAlbumDialog({ + super.key, + required this.name, + }); + + @override + State<RenameDynamicAlbumDialog> createState() => _RenameDynamicAlbumDialogState(); +} + +class _RenameDynamicAlbumDialogState extends State<RenameDynamicAlbumDialog> { + final TextEditingController _nameController = TextEditingController(); + final ValueNotifier<bool> _existsNotifier = ValueNotifier(false); + final ValueNotifier<bool> _isValidNotifier = ValueNotifier(false); + + String get initialValue => widget.name; + + @override + void initState() { + super.initState(); + _nameController.text = initialValue; + _validate(); + } + + @override + void dispose() { + _nameController.dispose(); + _existsNotifier.dispose(); + _isValidNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return AvesDialog( + content: ValueListenableBuilder<bool>( + valueListenable: _existsNotifier, + builder: (context, exists, child) { + return TextField( + controller: _nameController, + decoration: InputDecoration( + labelText: context.l10n.renameAlbumDialogLabel, + helperText: exists ? context.l10n.dynamicAlbumAlreadyExists : '', + ), + autofocus: true, + onChanged: (_) => _validate(), + onSubmitted: (_) => _submit(context), + ); + }), + actions: [ + const CancelButton(), + ValueListenableBuilder<bool>( + valueListenable: _isValidNotifier, + builder: (context, isValid, child) { + return TextButton( + onPressed: isValid ? () => _submit(context) : null, + child: Text(context.l10n.applyButtonLabel), + ); + }, + ), + ], + ); + } + + String? _formatAlbumName() { + final name = _nameController.text.trim(); + if (name.isEmpty) return null; + + return name; + } + + Future<void> _validate() async { + final newName = _formatAlbumName(); + final exists = dynamicAlbums.contains(newName); + _isValidNotifier.value = newName != null && !exists; + _existsNotifier.value = exists && newName != initialValue; + } + + void _submit(BuildContext context) { + if (_isValidNotifier.value) { + Navigator.maybeOf(context)?.pop(_formatAlbumName()); + } + } +} diff --git a/lib/widgets/dialogs/filter_editors/rename_group_dialog.dart b/lib/widgets/dialogs/filter_editors/rename_group_dialog.dart new file mode 100644 index 0000000..7cf9d4c --- /dev/null +++ b/lib/widgets/dialogs/filter_editors/rename_group_dialog.dart @@ -0,0 +1,101 @@ +import 'package:aves/model/grouping/common.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:flutter/material.dart'; + +class RenameGroupDialog extends StatefulWidget { + static const routeName = '/dialog/rename_group'; + + final FilterGrouping grouping; + final Uri groupUri; + + const RenameGroupDialog({ + super.key, + required this.grouping, + required this.groupUri, + }); + + @override + State<RenameGroupDialog> createState() => _RenameGroupDialogState(); +} + +class _RenameGroupDialogState extends State<RenameGroupDialog> { + final TextEditingController _nameController = TextEditingController(); + final ValueNotifier<bool> _existsNotifier = ValueNotifier(false); + final ValueNotifier<bool> _isValidNotifier = ValueNotifier(false); + + FilterGrouping get grouping => widget.grouping; + + Uri get initialGroupUri => widget.groupUri; + + Uri? get parentGroupUri => FilterGrouping.getParentGroup(initialGroupUri); + + @override + void initState() { + super.initState(); + _nameController.text = FilterGrouping.getGroupName(initialGroupUri) ?? ''; + _validate(); + } + + @override + void dispose() { + _nameController.dispose(); + _existsNotifier.dispose(); + _isValidNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + + return AvesDialog( + content: ValueListenableBuilder<bool>( + valueListenable: _existsNotifier, + builder: (context, exists, child) { + return TextField( + controller: _nameController, + decoration: InputDecoration( + labelText: l10n.renameAlbumDialogLabel, + helperText: exists ? l10n.groupAlreadyExists : '', + ), + autofocus: true, + onChanged: (_) => _validate(), + onSubmitted: (_) => _submit(context), + ); + }, + ), + actions: [ + const CancelButton(), + ValueListenableBuilder<bool>( + valueListenable: _isValidNotifier, + builder: (context, isValid, child) { + return TextButton( + onPressed: isValid ? () => _submit(context) : null, + child: Text(l10n.applyButtonLabel), + ); + }, + ), + ], + ); + } + + Uri? _getNewGroupUri() { + final name = _nameController.text.trim(); + if (name.isEmpty) return null; + return grouping.buildGroupUri(parentGroupUri, name); + } + + void _validate() { + final newGroupUri = _getNewGroupUri(); + final exists = grouping.exists(newGroupUri); + _isValidNotifier.value = newGroupUri != null && !exists; + _existsNotifier.value = exists && newGroupUri != initialGroupUri; + } + + void _submit(BuildContext context) { + if (_isValidNotifier.value) { + Navigator.maybeOf(context)?.pop(_getNewGroupUri()); + } + } +} diff --git a/lib/widgets/dialogs/filter_editors/rename_stored_album_dialog.dart b/lib/widgets/dialogs/filter_editors/rename_stored_album_dialog.dart new file mode 100644 index 0000000..cee4f75 --- /dev/null +++ b/lib/widgets/dialogs/filter_editors/rename_stored_album_dialog.dart @@ -0,0 +1,96 @@ +import 'dart:io'; + +import 'package:aves/services/common/services.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:flutter/material.dart'; + +class RenameStoredAlbumDialog extends StatefulWidget { + static const routeName = '/dialog/rename_stored_album'; + + final String album; + + const RenameStoredAlbumDialog({ + super.key, + required this.album, + }); + + @override + State<RenameStoredAlbumDialog> createState() => _RenameStoredAlbumDialogState(); +} + +class _RenameStoredAlbumDialogState extends State<RenameStoredAlbumDialog> { + final TextEditingController _nameController = TextEditingController(); + final ValueNotifier<bool> _existsNotifier = ValueNotifier(false); + final ValueNotifier<bool> _isValidNotifier = ValueNotifier(false); + + String get album => widget.album; + + String get initialValue => pContext.basename(album); + + @override + void initState() { + super.initState(); + _nameController.text = initialValue; + _validate(); + } + + @override + void dispose() { + _nameController.dispose(); + _existsNotifier.dispose(); + _isValidNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return AvesDialog( + content: ValueListenableBuilder<bool>( + valueListenable: _existsNotifier, + builder: (context, exists, child) { + return TextField( + controller: _nameController, + decoration: InputDecoration( + labelText: context.l10n.renameAlbumDialogLabel, + helperText: exists ? context.l10n.renameAlbumDialogLabelAlreadyExistsHelper : '', + ), + autofocus: true, + onChanged: (_) => _validate(), + onSubmitted: (_) => _submit(context), + ); + }), + actions: [ + const CancelButton(), + ValueListenableBuilder<bool>( + valueListenable: _isValidNotifier, + builder: (context, isValid, child) { + return TextButton( + onPressed: isValid ? () => _submit(context) : null, + child: Text(context.l10n.applyButtonLabel), + ); + }, + ), + ], + ); + } + + String _buildAlbumPath(String name) { + if (name.isEmpty) return ''; + return pContext.join(pContext.dirname(album), name); + } + + Future<void> _validate() async { + final newName = _nameController.text; + final path = _buildAlbumPath(newName); + final exists = newName.isNotEmpty && await FileSystemEntity.type(path) != FileSystemEntityType.notFound; + _existsNotifier.value = exists && newName != initialValue; + _isValidNotifier.value = newName.isNotEmpty; + } + + void _submit(BuildContext context) { + if (_isValidNotifier.value) { + Navigator.maybeOf(context)?.pop(_nameController.text); + } + } +} diff --git a/lib/widgets/dialogs/item_picker.dart b/lib/widgets/dialogs/item_picker.dart new file mode 100644 index 0000000..91fff90 --- /dev/null +++ b/lib/widgets/dialogs/item_picker.dart @@ -0,0 +1,74 @@ +import 'dart:math'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/extensions/theme.dart'; +import 'package:aves/widgets/common/fx/borders.dart'; +import 'package:aves/widgets/common/thumbnail/image.dart'; +import 'package:flutter/material.dart'; + +class ItemPicker extends StatelessWidget { + final double extent; + final AvesEntry entry; + final GestureTapCallback? onTap; + + const ItemPicker({ + super.key, + required this.extent, + required this.entry, + this.onTap, + }); + + @override + Widget build(BuildContext context) { + final imageBorderRadius = BorderRadius.all(Radius.circular(extent * .25)); + final actionBoxDimension = min(40.0, extent * .4); + final actionBoxBorderRadius = BorderRadiusDirectional.only(topStart: Radius.circular(actionBoxDimension * .6)); + return Tooltip( + message: context.l10n.changeTooltip, + child: GestureDetector( + onTap: onTap, + child: Container( + decoration: BoxDecoration( + border: AvesBorder.border(context), + borderRadius: imageBorderRadius, + ), + child: ClipRRect( + borderRadius: imageBorderRadius, + child: SizedBox( + width: extent, + height: extent, + child: Stack( + children: [ + ThumbnailImage( + entry: entry, + extent: extent, + devicePixelRatio: MediaQuery.devicePixelRatioOf(context), + ), + PositionedDirectional( + end: -1, + bottom: -1, + child: Container( + decoration: BoxDecoration( + color: Theme.of(context).isDark ? const Color(0xAA000000) : const Color(0xCCFFFFFF), + border: AvesBorder.border(context), + borderRadius: actionBoxBorderRadius, + ), + width: actionBoxDimension, + height: actionBoxDimension, + child: Icon( + AIcons.edit, + size: actionBoxDimension * .6, + ), + ), + ), + ], + ), + ), + ), + ), + ), + ); + } +} diff --git a/lib/widgets/dialogs/map/style_editor_dialog.dart b/lib/widgets/dialogs/map/style_editor_dialog.dart new file mode 100644 index 0000000..620994b --- /dev/null +++ b/lib/widgets/dialogs/map/style_editor_dialog.dart @@ -0,0 +1,146 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:aves_map/aves_map.dart'; +import 'package:flutter/material.dart'; + +class MapStyleEditorDialog extends StatefulWidget { + static const routeName = '/dialog/map_style_editor'; + + final EntryMapStyle? initialValue; + + const MapStyleEditorDialog({ + super.key, + this.initialValue, + }); + + @override + State<MapStyleEditorDialog> createState() => _MapStyleEditorDialogState(); +} + +class _MapStyleEditorDialogState extends State<MapStyleEditorDialog> { + late final Set<EntryMapStyle> _otherCustomStyles; + final TextEditingController _nameController = TextEditingController(); + final TextEditingController _urlController = TextEditingController(); + final TextEditingController _subdomainsController = TextEditingController(); + final TextEditingController _userAgentController = TextEditingController(); + final ValueNotifier<bool> _isValidNotifier = ValueNotifier(false); + + @override + void initState() { + super.initState(); + final initialValue = widget.initialValue; + _otherCustomStyles = settings.customMapStyles.where((v) => v != initialValue).toSet(); + _nameController.text = initialValue?.name ?? ''; + _urlController.text = initialValue?.url ?? ''; + _subdomainsController.text = initialValue?.subdomains.join(',') ?? ''; + _userAgentController.text = initialValue?.userAgent ?? ''; + _validate(); + } + + @override + void dispose() { + _nameController.dispose(); + _urlController.dispose(); + _subdomainsController.dispose(); + _userAgentController.dispose(); + _isValidNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + return AvesDialog( + scrollableContent: [ + Padding( + padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16), + child: TextField( + controller: _nameController, + decoration: InputDecoration( + labelText: l10n.mapStyleEditorDialogName, + ), + autofocus: true, + onChanged: (_) => _validate(), + ), + ), + Padding( + padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16), + child: TextField( + controller: _urlController, + decoration: InputDecoration( + labelText: l10n.mapStyleEditorDialogUrl, + ), + keyboardType: TextInputType.url, + onChanged: (_) => _validate(), + ), + ), + Padding( + padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16), + child: TextField( + controller: _subdomainsController, + decoration: InputDecoration( + labelText: l10n.mapStyleEditorDialogSubdomains, + ), + ), + ), + Padding( + padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16), + child: TextField( + controller: _userAgentController, + decoration: InputDecoration( + labelText: l10n.mapStyleEditorDialogUserAgent, + ), + ), + ), + ], + actions: [ + const CancelButton(), + ValueListenableBuilder<bool>( + valueListenable: _isValidNotifier, + builder: (context, isValid, child) { + return TextButton( + onPressed: isValid ? () => _submit(context) : null, + child: Text(widget.initialValue != null ? l10n.applyButtonLabel : l10n.createButtonLabel), + ); + }, + ) + ], + ); + } + + EntryMapStyle _buildStyle() { + final name = _nameController.text.trim(); + final url = _urlController.text.trim(); + final subdomains = _subdomainsController.text.split(',').map((v) => v.trim()).toList(); + final userAgent = _userAgentController.text.trim(); + return EntryMapStyle( + key: 'custom_$name', + name: name, + url: url, + subdomains: subdomains, + userAgent: userAgent.isNotEmpty ? userAgent : null, + ); + } + + Future<void> _validate() async { + final style = _buildStyle(); + + final name = style.name ?? ''; + final url = style.url ?? ''; + if (name.isEmpty || url.isEmpty) { + _isValidNotifier.value = false; + return; + } + + final key = style.key; + final duplicate = _otherCustomStyles.any((v) => v.key == key || v.url == url); + _isValidNotifier.value = !duplicate; + } + + void _submit(BuildContext context) { + if (_isValidNotifier.value) { + Navigator.maybeOf(context)?.pop<EntryMapStyle>(_buildStyle()); + } + } +} diff --git a/lib/widgets/dialogs/map/style_selection_dialog.dart b/lib/widgets/dialogs/map/style_selection_dialog.dart new file mode 100644 index 0000000..ea78ce4 --- /dev/null +++ b/lib/widgets/dialogs/map/style_selection_dialog.dart @@ -0,0 +1,185 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/utils/collection_utils.dart'; +import 'package:aves/view/src/settings/enums.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/buttons/outlined_button.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:aves/widgets/dialogs/map/style_editor_dialog.dart'; +import 'package:aves/widgets/dialogs/selection_dialogs/radio_list_tile.dart'; +import 'package:aves_map/aves_map.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class MapStyleSelectionDialog extends StatefulWidget { + static const routeName = '/dialog/map_style_selection'; + + const MapStyleSelectionDialog({super.key}); + + @override + State<MapStyleSelectionDialog> createState() => _MapStyleSelectionDialogState(); +} + +class _MapStyleSelectionDialogState extends State<MapStyleSelectionDialog> { + late EntryMapStyle? _selectedValue; + + @override + void initState() { + super.initState(); + _selectedValue = settings.mapStyle; + } + + @override + Widget build(BuildContext context) { + final useTvLayout = settings.useTvLayout; + final l10n = context.l10n; + final defaultStyles = availability.mapStyles; + final customStyles = context.select<Settings, Set<EntryMapStyle>>((v) => v.customMapStyles).sortedBy((v) => v.getName(context)); + + return PopScope( + onPopInvokedWithResult: (didPop, result) => settings.mapStyle = _selectedValue, + child: AvesScaffold( + appBar: AppBar( + automaticallyImplyLeading: !useTvLayout, + title: Text(context.l10n.mapStyleDialogTitle), + ), + body: SafeArea( + bottom: false, + child: ListView( + children: [ + ...defaultStyles.map((v) { + return SelectionRadioListTile( + // key is expected by test driver + key: Key(v.key), + value: v, + title: v.getName(context), + needConfirmation: false, + secondary: _getDefaultStylePreview(v), + getGroupValue: () => _selectedValue, + setGroupValue: _setGroupValue, + ); + }), + ...customStyles.map((v) { + return SelectionRadioListTile( + // key is expected by test driver + key: Key(v.key), + value: v, + title: v.getName(context), + needConfirmation: false, + secondary: _buildCustomStyleButtons(v), + getGroupValue: () => _selectedValue, + setGroupValue: _setGroupValue, + ); + }), + if (!settings.useTvLayout) + Container( + alignment: Alignment.center, + padding: const EdgeInsets.only(top: 4, bottom: 8), + child: AvesOutlinedButton( + icon: const Icon(AIcons.add), + label: l10n.mapStyleDialogAddStyle, + onPressed: _add, + ), + ), + ], + ), + ), + ), + ); + } + + void _setGroupValue(EntryMapStyle? style) => setState(() => _selectedValue = style); + + Widget? _getDefaultStylePreview(EntryMapStyle style) { + final assetName = _getImageAssetName(style); + if (assetName == null) return null; + + return ImageMarker( + count: null, + locale: null, + drawArrow: false, + buildThumbnailImage: (_) => Image.asset('assets/$assetName'), + ); + } + + String? _getImageAssetName(EntryMapStyle style) { + if (style == EntryMapStyles.googleNormal) return 'map_tile_128_google_normal.png'; + if (style == EntryMapStyles.googleHybrid) return 'map_tile_128_google_hybrid.png'; + if (style == EntryMapStyles.googleTerrain) return 'map_tile_128_google_terrain.png'; + if (style == EntryMapStyles.osmLiberty) return 'map_tile_128_osm_liberty.png'; + if (style == EntryMapStyles.openTopoMap) return 'map_tile_128_opentopomap.png'; + if (style == EntryMapStyles.osmHot) return 'map_tile_128_osm_hot.png'; + if (style == EntryMapStyles.stamenWatercolor) return 'map_tile_128_stamen_watercolor.png'; + return null; + } + + Widget _buildCustomStyleButtons(EntryMapStyle style) { + final l10n = context.l10n; + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + IconButton( + icon: const Icon(AIcons.edit), + onPressed: () => _edit(style), + tooltip: l10n.changeTooltip, + ), + IconButton( + icon: const Icon(AIcons.clear), + onPressed: () => _remove(style), + tooltip: l10n.actionRemove, + ), + ], + ); + } + + Future<void> _add() async { + final newStyle = await showDialog<EntryMapStyle>( + context: context, + builder: (context) => const MapStyleEditorDialog(), + routeSettings: const RouteSettings(name: MapStyleEditorDialog.routeName), + ); + if (newStyle == null) return; + + settings.customMapStyles = settings.customMapStyles..add(newStyle); + _setGroupValue(newStyle); + } + + Future<void> _edit(EntryMapStyle style) async { + final newStyle = await showDialog<EntryMapStyle>( + context: context, + builder: (context) => MapStyleEditorDialog(initialValue: style), + routeSettings: const RouteSettings(name: MapStyleEditorDialog.routeName), + ); + if (newStyle == null) return; + + settings.customMapStyles = settings.customMapStyles..replace(style, newStyle); + _setGroupValue(newStyle); + } + + Future<void> _remove(EntryMapStyle style) async { + final l10n = context.l10n; + final confirmed = await showDialog<bool>( + context: context, + builder: (context) => AvesDialog( + content: Text(l10n.genericDangerWarningDialogMessage), + actions: [ + const CancelButton(), + TextButton( + onPressed: () => Navigator.maybeOf(context)?.pop(true), + child: Text(l10n.applyButtonLabel), + ), + ], + ), + routeSettings: const RouteSettings(name: AvesDialog.warningRouteName), + ); + if (confirmed == null || !confirmed) return; + + settings.customMapStyles = settings.customMapStyles..remove(style); + if (_selectedValue == style) { + _setGroupValue(null); + } + } +} diff --git a/lib/widgets/dialogs/pick_dialogs/album_pick_page.dart b/lib/widgets/dialogs/pick_dialogs/album_pick_page.dart new file mode 100644 index 0000000..5ef1fd3 --- /dev/null +++ b/lib/widgets/dialogs/pick_dialogs/album_pick_page.dart @@ -0,0 +1,387 @@ +import 'package:aves/app_mode.dart'; +import 'package:aves/model/filters/container/album_group.dart'; +import 'package:aves/model/filters/container/dynamic_album.dart'; +import 'package:aves/model/filters/covered/stored_album.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/grouping/common.dart'; +import 'package:aves/model/selection.dart'; +import 'package:aves/model/settings/enums/accessibility_animations.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/album.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/model/vaults/details.dart'; +import 'package:aves/model/vaults/vaults.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/action_mixins/feedback.dart'; +import 'package:aves/widgets/common/action_mixins/vault_aware.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/aves_filter_chip.dart'; +import 'package:aves/widgets/common/identity/buttons/captioned_button.dart'; +import 'package:aves/widgets/common/identity/empty.dart'; +import 'package:aves/widgets/common/providers/filter_group_provider.dart'; +import 'package:aves/widgets/common/providers/query_provider.dart'; +import 'package:aves/widgets/common/providers/selection_provider.dart'; +import 'package:aves/widgets/dialogs/aves_confirmation_dialog.dart'; +import 'package:aves/widgets/dialogs/filter_editors/create_group_dialog.dart'; +import 'package:aves/widgets/dialogs/filter_editors/create_stored_album_dialog.dart'; +import 'package:aves/widgets/dialogs/filter_editors/edit_vault_dialog.dart'; +import 'package:aves/widgets/filter_grids/albums_page.dart'; +import 'package:aves/widgets/filter_grids/common/action_delegates/album_set.dart'; +import 'package:aves/widgets/filter_grids/common/app_bar.dart'; +import 'package:aves/widgets/filter_grids/common/enums.dart'; +import 'package:aves/widgets/filter_grids/common/filter_grid_page.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:provider/provider.dart'; + +Future<AlbumBaseFilter?> pickAlbum({ + required BuildContext context, + required MoveType? moveType, + required Iterable<AlbumChipType> chipTypes, + required Uri? initialGroup, +}) async { + final source = context.read<CollectionSource>(); + if (source.targetScope != CollectionSource.fullScope) { + await reportService.log('Complete source initialization to pick album'); + // source may not be fully initialized in view mode + source.canAnalyze = true; + await source.init(scope: CollectionSource.fullScope); + } + return await Navigator.maybeOf(context)?.push( + MaterialPageRoute<AlbumBaseFilter>( + settings: const RouteSettings(name: _AlbumPickPage.routeName), + builder: (context) => _AlbumPickPage( + source: source, + moveType: moveType, + chipTypes: chipTypes, + initialGroup: initialGroup, + ), + ), + ); +} + +class _AlbumPickPage extends StatefulWidget { + static const routeName = '/album_pick'; + + final CollectionSource source; + final MoveType? moveType; + final Iterable<AlbumChipType> chipTypes; + final Uri? initialGroup; + + const _AlbumPickPage({ + required this.source, + required this.moveType, + required this.chipTypes, + required this.initialGroup, + }); + + @override + State<_AlbumPickPage> createState() => _AlbumPickPageState(); +} + +class _AlbumPickPageState extends State<_AlbumPickPage> with FeedbackMixin, VaultAwareMixin { + final ValueNotifier<double> _appBarHeightNotifier = ValueNotifier(0); + final ValueNotifier<AppMode> _appModeNotifier = ValueNotifier(AppMode.pickFilterInternal); + + CollectionSource get source => widget.source; + + Iterable<AlbumChipType> get albumChipTypes => widget.chipTypes; + + bool get isPickingGroup => albumChipTypes.length == 1 && albumChipTypes.contains(AlbumChipType.group); + + String get title { + final l10n = context.l10n; + if (isPickingGroup) { + return l10n.groupPickerTitle; + } else { + return switch (widget.moveType) { + MoveType.copy => l10n.albumPickPageTitleCopy, + MoveType.move => l10n.albumPickPageTitleMove, + MoveType.export => l10n.albumPickPageTitleExport, + MoveType.toBin || MoveType.fromBin || null => l10n.albumPickPageTitlePick, + }; + } + } + + @override + void dispose() { + _appBarHeightNotifier.dispose(); + _appModeNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return ListenableProvider<ValueNotifier<AppMode>>.value( + value: _appModeNotifier, + child: MultiProvider( + providers: [ + ChangeNotifierProvider<FilterGrouping>.value(value: albumGrouping), + FilterGroupProvider(initialValue: widget.initialGroup), + ], + child: Builder( + // to access filter group provider from subtree context + builder: (context) { + return Selector<Settings, (AlbumChipSectionFactor, ChipSortFactor)>( + selector: (context, s) => (s.albumSectionFactor, s.albumSortFactor), + builder: (context, s, child) { + return StreamBuilder( + stream: source.eventBus.on<AlbumsChangedEvent>(), + builder: (context, snapshot) { + final groupUri = context.watch<FilterGroupNotifier>().value; + final gridItems = AlbumListPage.getGridItems(context, source, albumChipTypes, groupUri); + final scrollController = PrimaryScrollController.of(context); + return SelectionProvider<FilterGridItem<AlbumBaseFilter>>( + child: QueryProvider( + startEnabled: settings.getShowTitleQuery(context.currentRouteName!), + child: FilterGridPage<AlbumBaseFilter>( + settingsRouteKey: AlbumListPage.routeName, + appBar: FilterGridAppBar( + source: source, + title: title, + actionDelegate: AlbumChipSetActionDelegate(gridItems), + actionsBuilder: _buildActions, + isEmpty: false, + appBarHeightNotifier: _appBarHeightNotifier, + scrollController: scrollController, + ), + appBarHeightNotifier: _appBarHeightNotifier, + scrollController: scrollController, + sections: AlbumListPage.groupToSections(context, source, gridItems), + newFilters: source.getNewAlbumFilters(context), + sortFactor: settings.albumSortFactor, + showHeaders: settings.albumSectionFactor != AlbumChipSectionFactor.none, + selectable: false, + emptyBuilder: () => isPickingGroup + ? EmptyContent( + icon: AIcons.group, + text: context.l10n.groupEmpty, + ) + : EmptyContent( + icon: AIcons.album, + text: context.l10n.albumEmpty, + ), + heroType: HeroType.never, + floatingActionButton: _buildFab(context), + onTileTap: (gridItem, _) async { + final filter = gridItem.filter; + if (!await unlockFilter(context, filter)) return; + switch (filter) { + case AlbumGroupFilter _: + context.read<FilterGroupNotifier>().value = filter.uri; + case StoredAlbumFilter _: + case DynamicAlbumFilter _: + _pickFilter(context, filter); + } + }, + ), + ), + ); + }, + ); + }, + ); + }, + ), + ), + ); + } + + Widget? _buildFab(BuildContext context) { + return isPickingGroup + ? FloatingActionButton.extended( + onPressed: () { + final groupUri = context.read<FilterGroupNotifier>().value; + final filter = groupUri != null ? albumGrouping.uriToFilter(groupUri) : AlbumGroupFilter.root; + if (filter is AlbumBaseFilter) { + _pickFilter(context, filter); + } + }, + icon: const Icon(AIcons.apply), + label: Text(context.l10n.groupPickerUseThisGroupButton), + ) + : null; + } + + List<Widget> _buildActions( + BuildContext context, + AppMode appMode, + Selection<FilterGridItem<AlbumBaseFilter>> selection, + AlbumChipSetActionDelegate actionDelegate, + ) { + final itemCount = actionDelegate.allItems.length; + final isSelecting = selection.isSelecting; + final selectedItems = selection.selectedItems; + final selectedFilters = selectedItems.map((v) => v.filter).toSet(); + + bool isVisible(ChipSetAction action) => actionDelegate.isVisible( + action, + appMode: appMode, + isSelecting: isSelecting, + itemCount: itemCount, + selectedFilters: selectedFilters, + ); + + void onActionSelected(ChipSetAction action) { + switch (action) { + case ChipSetAction.createGroup: + final parentGroupUri = context.read<FilterGroupNotifier>().value; + _createGroup(parentGroupUri); + case ChipSetAction.createAlbum: + _createAlbum(); + case ChipSetAction.createVault: + _createVault(); + default: + actionDelegate.onActionSelected(context, action); + } + } + + return settings.useTvLayout + ? _buildTelevisionActions( + context: context, + isVisible: isVisible, + onActionSelected: onActionSelected, + ) + : _buildMobileActions( + context: context, + isVisible: isVisible, + onActionSelected: onActionSelected, + ); + } + + List<Widget> _buildTelevisionActions({ + required BuildContext context, + required bool Function(ChipSetAction action) isVisible, + required void Function(ChipSetAction action) onActionSelected, + }) { + return [ + ...ChipSetActions.general, + ].where(isVisible).map((action) { + return CaptionedButton( + icon: action.getIcon(), + caption: action.getText(context), + onPressed: () => onActionSelected(action), + ); + }).toList(); + } + + List<Widget> _buildMobileActions({ + required BuildContext context, + required bool Function(ChipSetAction action) isVisible, + required void Function(ChipSetAction action) onActionSelected, + }) { + final animations = context.select<Settings, AccessibilityAnimations>((v) => v.accessibilityAnimations); + + final canCreateStoredAlbums = widget.moveType != null; + final quickActions = [ + if (isPickingGroup) ChipSetAction.createGroup, + if (canCreateStoredAlbums) ChipSetAction.createAlbum, + ]; + + // `null` items are converted to dividers + final menuActions = [ + ...ChipSetActions.general, + null, + ChipSetAction.toggleTitleSearch, + if (canCreateStoredAlbums) ...[ + null, + ChipSetAction.createVault, + ] + ]; + + return [ + ...quickActions.where(isVisible).map( + (action) => IconButton( + icon: action.getIcon(), + onPressed: () => onActionSelected(action), + tooltip: action.getText(context), + ), + ), + PopupMenuButton<ChipSetAction>( + itemBuilder: (context) { + return menuActions.where((v) => v == null || isVisible(v)).map((action) { + if (action == null) return const PopupMenuDivider(); + return FilterGridAppBar.toMenuItem(context, action, enabled: true); + }).toList(); + }, + onSelected: (action) async { + // remove focus, if any, to prevent the keyboard from showing up + // after the user is done with the popup menu + FocusManager.instance.primaryFocus?.unfocus(); + + // wait for the popup menu to hide before proceeding with the action + await Future.delayed(animations.popUpAnimationDelay * timeDilation); + onActionSelected(action); + }, + popUpAnimationStyle: animations.popUpAnimationStyle, + ), + ]; + } + + Future<void> _createGroup(Uri? parentGroupUri) async { + final uri = await showDialog<Uri>( + context: context, + builder: (context) => CreateGroupDialog(grouping: albumGrouping, parentGroupUri: parentGroupUri), + routeSettings: const RouteSettings(name: CreateGroupDialog.routeName), + ); + if (uri == null) return; + + // wait for the dialog to hide + await Future.delayed(ADurations.dialogTransitionLoose * timeDilation); + + _pickFilter(context, AlbumGroupFilter.empty(uri)); + } + + Future<void> _createAlbum() async { + final directory = await showDialog<String>( + context: context, + builder: (context) => const CreateStoredAlbumDialog(), + routeSettings: const RouteSettings(name: CreateStoredAlbumDialog.routeName), + ); + if (directory == null) return; + + // wait for the dialog to hide + await Future.delayed(ADurations.dialogTransitionLoose * timeDilation); + + _pickStoredAlbum(context, directory); + } + + Future<void> _createVault() async { + final l10n = context.l10n; + if (!await showSkippableConfirmationDialog( + context: context, + type: ConfirmationDialog.createVault, + message: l10n.newVaultWarningDialogMessage, + confirmationButtonLabel: l10n.continueButtonLabel, + )) { + return; + } + + final details = await showDialog<VaultDetails>( + context: context, + builder: (context) => const EditVaultDialog(), + routeSettings: const RouteSettings(name: EditVaultDialog.routeName), + ); + if (details == null) return; + + // wait for the dialog to hide + await Future.delayed(ADurations.dialogTransitionLoose * timeDilation); + + await vaults.create(details); + _pickStoredAlbum(context, details.path); + } + + void _pickStoredAlbum(BuildContext context, String directory) { + source.createStoredAlbum(directory); + final displayName = source.getStoredAlbumDisplayName(context, directory); + _pickFilter(context, StoredAlbumFilter(directory, displayName)); + } + + void _pickFilter(BuildContext context, AlbumBaseFilter filter) async { + Navigator.maybeOf(context)?.pop<AlbumBaseFilter>(filter); + } +} diff --git a/lib/widgets/dialogs/pick_dialogs/app_pick_page.dart b/lib/widgets/dialogs/pick_dialogs/app_pick_page.dart new file mode 100644 index 0000000..54bd575 --- /dev/null +++ b/lib/widgets/dialogs/pick_dialogs/app_pick_page.dart @@ -0,0 +1,155 @@ +import 'package:aves/image_providers/app_icon_image_provider.dart'; +import 'package:aves/model/app_inventory.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/widgets/common/basic/list_tiles/reselectable_radio.dart'; +import 'package:aves/widgets/common/basic/query_bar.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; + +class AppPickPage extends StatefulWidget { + static const routeName = '/app_pick'; + + final String? initialValue; + + const AppPickPage({ + super.key, + required this.initialValue, + }); + + @override + State<AppPickPage> createState() => _AppPickPageState(); +} + +class _AppPickPageState extends State<AppPickPage> { + late String? _selectedValue; + late Future<Set<Package>> _loader; + final ValueNotifier<String> _queryNotifier = ValueNotifier(''); + + static const double iconSize = 32; + + @override + void initState() { + super.initState(); + _selectedValue = widget.initialValue; + _loader = appService.getPackages(); + } + + @override + void dispose() { + _queryNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final useTvLayout = settings.useTvLayout; + return AvesScaffold( + appBar: AppBar( + automaticallyImplyLeading: !useTvLayout, + title: Text(context.l10n.appPickDialogTitle), + ), + body: SafeArea( + bottom: false, + child: FutureBuilder<Set<Package>>( + future: _loader, + builder: (context, snapshot) { + if (snapshot.hasError) return Text(snapshot.error.toString()); + if (snapshot.connectionState != ConnectionState.done) { + return const Center( + child: CircularProgressIndicator(), + ); + } + + final allPackages = snapshot.data; + if (allPackages == null) return const SizedBox(); + final packages = allPackages.where((package) => package.categoryLauncher).toList()..sort((a, b) => compareAsciiUpperCase(_displayName(a), _displayName(b))); + return Column( + children: [ + if (!useTvLayout) QueryBar(queryNotifier: _queryNotifier), + ValueListenableBuilder<String>( + valueListenable: _queryNotifier, + builder: (context, query, child) { + final upQuery = query.toUpperCase().trim(); + final visiblePackages = packages.where((package) { + return { + package.packageName, + package.currentLabel, + package.englishLabel, + ...package.potentialDirs, + }.any((v) => v != null && v.toUpperCase().contains(upQuery)); + }).toList(); + final showNoneOption = upQuery.isEmpty; + final itemCount = visiblePackages.length + (showNoneOption ? 1 : 0); + return Expanded( + child: ListView.builder( + itemBuilder: (context, index) { + if (showNoneOption) { + if (index == 0) { + return ReselectableRadioListTile<String?>( + value: '', + groupValue: _selectedValue, + onChanged: (v) => Navigator.maybeOf(context)?.pop(v), + reselectable: true, + title: Text( + context.l10n.appPickDialogNone, + softWrap: false, + overflow: TextOverflow.fade, + maxLines: 1, + ), + ); + } + index--; + } + + final package = visiblePackages[index]; + return ReselectableRadioListTile<String?>( + value: package.packageName, + groupValue: _selectedValue, + onChanged: (v) => Navigator.maybeOf(context)?.pop(v), + reselectable: true, + title: Text.rich( + TextSpan( + children: [ + WidgetSpan( + alignment: PlaceholderAlignment.middle, + child: Padding( + padding: const EdgeInsetsDirectional.only(end: 16), + child: Image( + image: AppIconImage( + packageName: package.packageName, + size: iconSize, + ), + width: iconSize, + height: iconSize, + ), + ), + ), + TextSpan( + text: _displayName(package), + ), + ], + ), + softWrap: false, + overflow: TextOverflow.fade, + maxLines: 1, + ), + ); + }, + itemCount: itemCount, + ), + ); + }, + ), + ], + ); + }, + ), + ), + ); + } + + String _displayName(Package package) => package.currentLabel ?? package.packageName; +} diff --git a/lib/widgets/dialogs/pick_dialogs/item_pick_page.dart b/lib/widgets/dialogs/pick_dialogs/item_pick_page.dart new file mode 100644 index 0000000..25d3607 --- /dev/null +++ b/lib/widgets/dialogs/pick_dialogs/item_pick_page.dart @@ -0,0 +1,74 @@ +import 'package:aves/app_mode.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/filters/query.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/widgets/collection/collection_grid.dart'; +import 'package:aves/widgets/collection/collection_page.dart'; +import 'package:aves/widgets/common/basic/insets.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/providers/query_provider.dart'; +import 'package:aves/widgets/common/providers/selection_provider.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class ItemPickPage extends StatefulWidget { + static const routeName = '/item_pick'; + + final CollectionLens collection; + final bool canRemoveFilters; + + const ItemPickPage({ + super.key, + required this.collection, + required this.canRemoveFilters, + }); + + @override + State<ItemPickPage> createState() => _ItemPickPageState(); +} + +class _ItemPickPageState extends State<ItemPickPage> { + final ValueNotifier<AppMode> _appModeNotifier = ValueNotifier(AppMode.initialization); + + @override + void dispose() { + _appModeNotifier.dispose(); + // provided collection should be a new instance specifically created + // for the `ItemPickPage` widget, so it can be safely disposed here + widget.collection.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final collection = widget.collection; + final liveFilter = collection.filters.firstWhereOrNull((v) => v is QueryFilter && v.live) as QueryFilter?; + _appModeNotifier.value = widget.canRemoveFilters ? AppMode.pickUnfilteredMediaInternal : AppMode.pickFilteredMediaInternal; + return ListenableProvider<ValueNotifier<AppMode>>.value( + value: _appModeNotifier, + child: AvesScaffold( + body: SelectionProvider<AvesEntry>( + child: QueryProvider( + startEnabled: settings.getShowTitleQuery(context.currentRouteName!), + initialQuery: liveFilter?.query, + child: GestureAreaProtectorStack( + child: SafeArea( + top: false, + bottom: false, + child: ChangeNotifierProvider<CollectionLens>.value( + value: collection, + child: const CollectionGrid( + settingsRouteKey: CollectionPage.routeName, + ), + ), + ), + ), + ), + ), + ), + ); + } +} diff --git a/lib/widgets/dialogs/pick_dialogs/location_pick_page.dart b/lib/widgets/dialogs/pick_dialogs/location_pick_page.dart new file mode 100644 index 0000000..2182888 --- /dev/null +++ b/lib/widgets/dialogs/pick_dialogs/location_pick_page.dart @@ -0,0 +1,342 @@ +import 'dart:async'; + +import 'package:aves/model/settings/enums/coordinate_format.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/services/geocoding_service.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/theme/text.dart'; +import 'package:aves/utils/debouncer.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/buttons/outlined_button.dart'; +import 'package:aves/widgets/common/map/geo_map.dart'; +import 'package:aves/widgets/common/providers/map_theme_provider.dart'; +import 'package:aves_map/aves_map.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:latlong2/latlong.dart'; + +class LocationPickPage extends StatelessWidget { + static const routeName = '/location_pick'; + + final CollectionLens? collection; + final LatLng? initialLocation; + + const LocationPickPage({ + super.key, + required this.collection, + required this.initialLocation, + }); + + @override + Widget build(BuildContext context) { + return AvesScaffold( + body: SafeArea( + left: false, + top: false, + right: false, + bottom: true, + child: _Content( + collection: collection, + initialLocation: initialLocation, + ), + ), + ); + } +} + +class _Content extends StatefulWidget { + final CollectionLens? collection; + final LatLng? initialLocation; + + const _Content({ + required this.collection, + required this.initialLocation, + }); + + @override + State<_Content> createState() => _ContentState(); +} + +class _ContentState extends State<_Content> with SingleTickerProviderStateMixin { + final Set<StreamSubscription> _subscriptions = {}; + final AvesMapController _mapController = AvesMapController(); + late final ValueNotifier<bool> _isPageAnimatingNotifier; + final ValueNotifier<LatLng?> _dotLocationNotifier = ValueNotifier(null), _infoLocationNotifier = ValueNotifier(null); + final Debouncer _infoDebouncer = Debouncer(delay: ADurations.mapInfoDebounceDelay); + + CollectionLens? get openingCollection => widget.collection; + + @override + void initState() { + super.initState(); + + if (settings.mapStyle?.isHeavy ?? false) { + _isPageAnimatingNotifier = ValueNotifier(true); + Future.delayed(ADurations.pageTransitionLoose * timeDilation).then((_) { + if (!mounted) return; + _isPageAnimatingNotifier.value = false; + }); + } else { + _isPageAnimatingNotifier = ValueNotifier(false); + } + + _dotLocationNotifier.addListener(_updateLocationInfo); + + _subscriptions.add(_mapController.idleUpdates.listen((event) => _onIdle(event.bounds))); + } + + @override + void dispose() { + _subscriptions + ..forEach((sub) => sub.cancel()) + ..clear(); + _mapController.dispose(); + _isPageAnimatingNotifier.dispose(); + _dotLocationNotifier.dispose(); + _infoLocationNotifier.dispose(); + // provided collection should be a new instance specifically created + // for the `LocationPickPage` widget, so it can be safely disposed here + widget.collection?.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Column( + children: [ + Expanded(child: _buildMap()), + Column( + mainAxisSize: MainAxisSize.min, + children: [ + const SizedBox(height: 8), + const Divider(height: 0), + SafeArea( + top: false, + bottom: false, + child: _LocationInfo(locationNotifier: _infoLocationNotifier), + ), + const SizedBox(height: 8), + AvesOutlinedButton( + label: context.l10n.locationPickerUseThisLocationButton, + onPressed: () => Navigator.maybeOf(context)?.pop(_dotLocationNotifier.value), + ), + ], + ), + ], + ); + } + + Widget _buildMap() { + return MapTheme( + interactive: true, + showCoordinateFilter: false, + navigationButton: MapNavigationButton.back, + attributionPadding: const EdgeInsets.symmetric(horizontal: 8), + child: GeoMap( + controller: _mapController, + collection: openingCollection, + availableSize: MediaQuery.sizeOf(context), + initialCenter: widget.initialLocation, + isAnimatingNotifier: _isPageAnimatingNotifier, + dotLocationNotifier: _dotLocationNotifier, + onMapTap: _setLocation, + onMarkerTap: (location, entry) => _setLocation(location), + ), + ); + } + + void _setLocation(LatLng location) { + _dotLocationNotifier.value = location; + _mapController.moveTo(location); + } + + void _onIdle(ZoomedBounds bounds) { + _dotLocationNotifier.value = bounds.projectedCenter; + } + + void _updateLocationInfo() { + final selectedLocation = _dotLocationNotifier.value; + if (_infoLocationNotifier.value == null || selectedLocation == null) { + _infoLocationNotifier.value = selectedLocation; + } else { + _infoDebouncer(() => _infoLocationNotifier.value = selectedLocation); + } + } +} + +class _LocationInfo extends StatelessWidget { + final ValueNotifier<LatLng?> locationNotifier; + + static const double iconPadding = 8.0; + static const double _interRowPadding = 2.0; + + const _LocationInfo({ + required this.locationNotifier, + }); + + @override + Widget build(BuildContext context) { + return ValueListenableBuilder<LatLng?>( + valueListenable: locationNotifier, + builder: (context, location, child) { + final isPortrait = MediaQuery.orientationOf(context) == Orientation.portrait; + final content = isPortrait + ? [ + Expanded( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _AddressRow(location: location), + const SizedBox(height: _interRowPadding), + _CoordinateRow(location: location), + ], + ), + ), + ] + : [ + _CoordinateRow(location: location), + Expanded( + child: _AddressRow(location: location), + ), + ]; + + return Opacity( + opacity: location != null ? 1 : 0, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + const SizedBox(width: iconPadding), + const DotMarker(), + ...content, + ], + ), + ); + }, + ); + } + + static double getIconSize(BuildContext context) { + final textScaler = MediaQuery.textScalerOf(context); + return textScaler.scale(16); + } +} + +class _AddressRow extends StatefulWidget { + final LatLng? location; + + const _AddressRow({ + required this.location, + }); + + @override + State<_AddressRow> createState() => _AddressRowState(); +} + +class _AddressRowState extends State<_AddressRow> { + final ValueNotifier<String?> _addressLineNotifier = ValueNotifier(null); + + @override + void initState() { + super.initState(); + _updateAddress(); + } + + @override + void didUpdateWidget(covariant _AddressRow oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.location != widget.location) { + _updateAddress(); + } + } + + @override + void dispose() { + _addressLineNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final textScaler = MediaQuery.textScalerOf(context); + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + const SizedBox(width: _LocationInfo.iconPadding), + Icon(AIcons.location, size: _LocationInfo.getIconSize(context)), + const SizedBox(width: _LocationInfo.iconPadding), + Expanded( + child: Container( + alignment: AlignmentDirectional.centerStart, + // addresses can include non-latin scripts with inconsistent line height, + // which is especially an issue for relayout/painting of heavy Google map, + // so we give extra height to give breathing room to the text and stabilize layout + height: textScaler.scale(Theme.of(context).textTheme.bodyMedium!.fontSize!) * 2, + child: ValueListenableBuilder<String?>( + valueListenable: _addressLineNotifier, + builder: (context, addressLine, child) { + return Text( + addressLine ?? AText.valueNotAvailable, + softWrap: false, + overflow: TextOverflow.fade, + maxLines: 1, + ); + }, + ), + ), + ), + ], + ); + } + + Future<void> _updateAddress() async { + final location = widget.location; + final addressLine = await _getAddressLine(location); + if (!mounted) return; + if (location == widget.location) { + _addressLineNotifier.value = addressLine; + } + } + + Future<String?> _getAddressLine(LatLng? location) async { + if (location != null && await availability.canLocatePlaces) { + final addresses = await GeocodingService.getAddress(location, settings.appliedLocale); + if (addresses.isNotEmpty) { + final address = addresses.first; + return address.addressLine; + } + } + return null; + } +} + +class _CoordinateRow extends StatelessWidget { + final LatLng? location; + + const _CoordinateRow({ + required this.location, + }); + + @override + Widget build(BuildContext context) { + return Row( + children: [ + const SizedBox(width: _LocationInfo.iconPadding), + Icon(AIcons.geoBounds, size: _LocationInfo.getIconSize(context)), + const SizedBox(width: _LocationInfo.iconPadding), + Expanded( + child: Text( + location != null ? settings.coordinateFormat.format(context, location!) : AText.valueNotAvailable, + softWrap: false, + overflow: TextOverflow.fade, + maxLines: 1, + ), + ), + ], + ); + } +} diff --git a/lib/widgets/dialogs/pick_dialogs/tag_pick_page.dart b/lib/widgets/dialogs/pick_dialogs/tag_pick_page.dart new file mode 100644 index 0000000..f54018e --- /dev/null +++ b/lib/widgets/dialogs/pick_dialogs/tag_pick_page.dart @@ -0,0 +1,314 @@ +import 'package:aves/app_mode.dart'; +import 'package:aves/model/filters/container/tag_group.dart'; +import 'package:aves/model/filters/covered/tag.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/grouping/common.dart'; +import 'package:aves/model/selection.dart'; +import 'package:aves/model/settings/enums/accessibility_animations.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/model/source/tag.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/action_mixins/feedback.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/aves_filter_chip.dart'; +import 'package:aves/widgets/common/identity/buttons/captioned_button.dart'; +import 'package:aves/widgets/common/identity/empty.dart'; +import 'package:aves/widgets/common/providers/filter_group_provider.dart'; +import 'package:aves/widgets/common/providers/query_provider.dart'; +import 'package:aves/widgets/common/providers/selection_provider.dart'; +import 'package:aves/widgets/dialogs/filter_editors/create_group_dialog.dart'; +import 'package:aves/widgets/filter_grids/common/action_delegates/tag_set.dart'; +import 'package:aves/widgets/filter_grids/common/app_bar.dart'; +import 'package:aves/widgets/filter_grids/common/enums.dart'; +import 'package:aves/widgets/filter_grids/common/filter_grid_page.dart'; +import 'package:aves/widgets/filter_grids/tags_page.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:provider/provider.dart'; + +Future<TagBaseFilter?> pickTag({ + required BuildContext context, + required Iterable<ChipType> chipTypes, + required Uri? initialGroup, +}) async { + final source = context.read<CollectionSource>(); + if (source.targetScope != CollectionSource.fullScope) { + await reportService.log('Complete source initialization to pick tag'); + // source may not be fully initialized in view mode + source.canAnalyze = true; + await source.init(scope: CollectionSource.fullScope); + } + return await Navigator.maybeOf(context)?.push( + MaterialPageRoute<TagBaseFilter>( + settings: const RouteSettings(name: _TagPickPage.routeName), + builder: (context) => _TagPickPage( + source: source, + chipTypes: chipTypes, + initialGroup: initialGroup, + ), + ), + ); +} + +class _TagPickPage extends StatefulWidget { + static const routeName = '/tag_pick'; + + final CollectionSource source; + final Iterable<ChipType> chipTypes; + final Uri? initialGroup; + + const _TagPickPage({ + required this.source, + required this.chipTypes, + required this.initialGroup, + }); + + @override + State<_TagPickPage> createState() => _TagPickPageState(); +} + +class _TagPickPageState extends State<_TagPickPage> with FeedbackMixin { + final ValueNotifier<double> _appBarHeightNotifier = ValueNotifier(0); + final ValueNotifier<AppMode> _appModeNotifier = ValueNotifier(AppMode.pickFilterInternal); + + CollectionSource get source => widget.source; + + Iterable<ChipType> get chipTypes => widget.chipTypes; + + bool get isPickingGroup => chipTypes.length == 1 && chipTypes.contains(ChipType.group); + + String get title { + final l10n = context.l10n; + if (isPickingGroup) { + return l10n.groupPickerTitle; + } else { + return l10n.tagPickPageTitle; + } + } + + @override + void dispose() { + _appBarHeightNotifier.dispose(); + _appModeNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return ListenableProvider<ValueNotifier<AppMode>>.value( + value: _appModeNotifier, + child: MultiProvider( + providers: [ + ChangeNotifierProvider<FilterGrouping>.value(value: tagGrouping), + FilterGroupProvider(initialValue: widget.initialGroup), + ], + child: Builder( + // to access filter group provider from subtree context + builder: (context) { + return Selector<Settings, ChipSortFactor>( + selector: (context, s) => s.tagSortFactor, + builder: (context, s, child) { + return StreamBuilder( + stream: source.eventBus.on<TagsChangedEvent>(), + builder: (context, snapshot) { + final groupUri = context.watch<FilterGroupNotifier>().value; + final gridItems = TagListPage.getGridItems(source, chipTypes, groupUri); + final scrollController = PrimaryScrollController.of(context); + return SelectionProvider<FilterGridItem<TagBaseFilter>>( + child: QueryProvider( + startEnabled: settings.getShowTitleQuery(context.currentRouteName!), + child: FilterGridPage<TagBaseFilter>( + settingsRouteKey: TagListPage.routeName, + appBar: FilterGridAppBar( + source: source, + title: title, + actionDelegate: TagChipSetActionDelegate(gridItems), + actionsBuilder: _buildActions, + isEmpty: false, + appBarHeightNotifier: _appBarHeightNotifier, + scrollController: scrollController, + ), + appBarHeightNotifier: _appBarHeightNotifier, + scrollController: scrollController, + sections: TagListPage.groupToSections(gridItems), + newFilters: const {}, + sortFactor: settings.tagSortFactor, + showHeaders: false, + selectable: false, + emptyBuilder: () => isPickingGroup + ? EmptyContent( + icon: AIcons.group, + text: context.l10n.groupEmpty, + ) + : EmptyContent( + icon: AIcons.tag, + text: context.l10n.tagEmpty, + ), + heroType: HeroType.never, + floatingActionButton: _buildFab(context), + onTileTap: (gridItem, _) async { + final filter = gridItem.filter; + switch (filter) { + case TagGroupFilter _: + context.read<FilterGroupNotifier>().value = filter.uri; + case TagFilter _: + _pickFilter(context, filter); + } + }, + ), + ), + ); + }, + ); + }, + ); + }, + ), + ), + ); + } + + Widget? _buildFab(BuildContext context) { + return isPickingGroup + ? FloatingActionButton.extended( + onPressed: () { + final groupUri = context.read<FilterGroupNotifier>().value; + final filter = groupUri != null ? tagGrouping.uriToFilter(groupUri) : TagGroupFilter.root; + if (filter is TagBaseFilter) { + _pickFilter(context, filter); + } + }, + icon: const Icon(AIcons.apply), + label: Text(context.l10n.groupPickerUseThisGroupButton), + ) + : null; + } + + List<Widget> _buildActions( + BuildContext context, + AppMode appMode, + Selection<FilterGridItem<TagBaseFilter>> selection, + TagChipSetActionDelegate actionDelegate, + ) { + final itemCount = actionDelegate.allItems.length; + final isSelecting = selection.isSelecting; + final selectedItems = selection.selectedItems; + final selectedFilters = selectedItems.map((v) => v.filter).toSet(); + + bool isVisible(ChipSetAction action) => actionDelegate.isVisible( + action, + appMode: appMode, + isSelecting: isSelecting, + itemCount: itemCount, + selectedFilters: selectedFilters, + ); + + void onActionSelected(ChipSetAction action) { + switch (action) { + case ChipSetAction.createGroup: + final parentGroupUri = context.read<FilterGroupNotifier>().value; + _createGroup(parentGroupUri); + default: + actionDelegate.onActionSelected(context, action); + } + } + + return settings.useTvLayout + ? _buildTelevisionActions( + context: context, + isVisible: isVisible, + onActionSelected: onActionSelected, + ) + : _buildMobileActions( + context: context, + isVisible: isVisible, + onActionSelected: onActionSelected, + ); + } + + List<Widget> _buildTelevisionActions({ + required BuildContext context, + required bool Function(ChipSetAction action) isVisible, + required void Function(ChipSetAction action) onActionSelected, + }) { + return [ + ...ChipSetActions.general, + ].where(isVisible).map((action) { + return CaptionedButton( + icon: action.getIcon(), + caption: action.getText(context), + onPressed: () => onActionSelected(action), + ); + }).toList(); + } + + List<Widget> _buildMobileActions({ + required BuildContext context, + required bool Function(ChipSetAction action) isVisible, + required void Function(ChipSetAction action) onActionSelected, + }) { + final animations = context.select<Settings, AccessibilityAnimations>((v) => v.accessibilityAnimations); + + final quickActions = [ + if (isPickingGroup) ChipSetAction.createGroup, + ]; + + // `null` items are converted to dividers + final menuActions = [ + ...ChipSetActions.general, + null, + ChipSetAction.toggleTitleSearch, + ]; + + return [ + ...quickActions.where(isVisible).map( + (action) => IconButton( + icon: action.getIcon(), + onPressed: () => onActionSelected(action), + tooltip: action.getText(context), + ), + ), + PopupMenuButton<ChipSetAction>( + itemBuilder: (context) { + return menuActions.where((v) => v == null || isVisible(v)).map((action) { + if (action == null) return const PopupMenuDivider(); + return FilterGridAppBar.toMenuItem(context, action, enabled: true); + }).toList(); + }, + onSelected: (action) async { + // remove focus, if any, to prevent the keyboard from showing up + // after the user is done with the popup menu + FocusManager.instance.primaryFocus?.unfocus(); + + // wait for the popup menu to hide before proceeding with the action + await Future.delayed(animations.popUpAnimationDelay * timeDilation); + onActionSelected(action); + }, + popUpAnimationStyle: animations.popUpAnimationStyle, + ), + ]; + } + + Future<void> _createGroup(Uri? parentGroupUri) async { + final uri = await showDialog<Uri>( + context: context, + builder: (context) => CreateGroupDialog(grouping: tagGrouping, parentGroupUri: parentGroupUri), + routeSettings: const RouteSettings(name: CreateGroupDialog.routeName), + ); + if (uri == null) return; + + // wait for the dialog to hide + await Future.delayed(ADurations.dialogTransitionLoose * timeDilation); + + _pickFilter(context, TagGroupFilter.empty(uri)); + } + + void _pickFilter(BuildContext context, TagBaseFilter filter) async { + Navigator.maybeOf(context)?.pop<TagBaseFilter>(filter); + } +} diff --git a/lib/widgets/dialogs/select_storage_dialog.dart b/lib/widgets/dialogs/select_storage_dialog.dart new file mode 100644 index 0000000..fa667c1 --- /dev/null +++ b/lib/widgets/dialogs/select_storage_dialog.dart @@ -0,0 +1,75 @@ +import 'package:aves/utils/android_file_utils.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; + +class SelectStorageDialog extends StatefulWidget { + static const routeName = '/dialog/select_storage'; + + final StorageVolume? initialVolume; + + const SelectStorageDialog({super.key, this.initialVolume}); + + @override + State<SelectStorageDialog> createState() => _SelectStorageDialogState(); +} + +class _SelectStorageDialogState extends State<SelectStorageDialog> { + late Set<StorageVolume> _allVolumes; + late StorageVolume? _primaryVolume, _selectedVolume; + + @override + void initState() { + super.initState(); + _allVolumes = androidFileUtils.storageVolumes; + _primaryVolume = _allVolumes.firstWhereOrNull((volume) => volume.isPrimary) ?? _allVolumes.firstOrNull; + _selectedVolume = widget.initialVolume ?? _primaryVolume; + } + + @override + Widget build(BuildContext context) { + final byPrimary = groupBy<StorageVolume, bool>(_allVolumes, (volume) => volume.isPrimary); + int compare(StorageVolume a, StorageVolume b) => compareAsciiUpperCaseNatural(a.path, b.path); + final primaryVolumes = (byPrimary[true] ?? [])..sort(compare); + final otherVolumes = (byPrimary[false] ?? [])..sort(compare); + + return AvesDialog( + title: context.l10n.selectStorageVolumeDialogTitle, + scrollableContent: [ + ...primaryVolumes.map((volume) => _buildVolumeTile(context, volume)), + ...otherVolumes.map((volume) => _buildVolumeTile(context, volume)), + ], + actions: [ + const CancelButton(), + TextButton( + onPressed: () => Navigator.maybeOf(context)?.pop(_selectedVolume), + child: Text(context.l10n.applyButtonLabel), + ), + ], + ); + } + + Widget _buildVolumeTile(BuildContext context, StorageVolume volume) => RadioListTile<StorageVolume>( + value: volume, + groupValue: _selectedVolume, + onChanged: (volume) { + _selectedVolume = volume!; + setState(() {}); + }, + title: Text( + volume.getDescription(context), + softWrap: false, + overflow: TextOverflow.fade, + maxLines: 1, + ), + subtitle: Text( + volume.path, + softWrap: false, + overflow: TextOverflow.fade, + maxLines: 1, + ), + ); +} diff --git a/lib/widgets/dialogs/selection_dialogs/common.dart b/lib/widgets/dialogs/selection_dialogs/common.dart new file mode 100644 index 0000000..fe34e4f --- /dev/null +++ b/lib/widgets/dialogs/selection_dialogs/common.dart @@ -0,0 +1,23 @@ +import 'package:aves/theme/durations.dart'; +import 'package:aves/widgets/dialogs/selection_dialogs/single_selection.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; + +Future<void> showSelectionDialog<T>({ + required BuildContext context, + required WidgetBuilder builder, + required void Function(T value) onSelection, +}) async { + final value = await showDialog<T>( + context: context, + builder: builder, + routeSettings: const RouteSettings(name: AvesSingleSelectionDialog.routeName), + ); + // wait for the dialog to hide + await Future.delayed(ADurations.dialogTransitionLoose * timeDilation); + if (value != null) { + onSelection(value); + } +} + +typedef TextBuilder<T> = String? Function(T value); diff --git a/lib/widgets/dialogs/selection_dialogs/multi_selection.dart b/lib/widgets/dialogs/selection_dialogs/multi_selection.dart new file mode 100644 index 0000000..a9079b3 --- /dev/null +++ b/lib/widgets/dialogs/selection_dialogs/multi_selection.dart @@ -0,0 +1,91 @@ +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:aves/widgets/dialogs/selection_dialogs/common.dart'; +import 'package:flutter/material.dart'; + +class AvesMultiSelectionDialog<T> extends StatefulWidget { + static const routeName = '/dialog/multi_selection'; + + final Set<T> initialValue; + final Map<T, String> options; + final TextBuilder<T>? optionSubtitleBuilder; + final String? title, message; + final bool? dense; + + const AvesMultiSelectionDialog({ + super.key, + required this.initialValue, + required this.options, + this.optionSubtitleBuilder, + this.title, + this.message, + this.dense, + }); + + @override + State<AvesMultiSelectionDialog<T>> createState() => _AvesMultiSelectionDialogState<T>(); +} + +class _AvesMultiSelectionDialogState<T> extends State<AvesMultiSelectionDialog<T>> { + late Set<T> _selectedValues; + + @override + void initState() { + super.initState(); + _selectedValues = widget.initialValue; + } + + @override + Widget build(BuildContext context) { + final title = widget.title; + final message = widget.message; + final verticalPadding = (title == null && message == null) ? AvesDialog.cornerRadius.y / 2 : .0; + return AvesDialog( + title: title, + scrollableContent: [ + if (verticalPadding != 0) SizedBox(height: verticalPadding), + if (message != null) + Padding( + padding: const EdgeInsets.all(16), + child: Text(message), + ), + ...widget.options.entries.map((kv) { + final value = kv.key; + final title = kv.value; + final subtitle = widget.optionSubtitleBuilder?.call(value); + return SwitchListTile( + value: _selectedValues.contains(value), + onChanged: (v) { + if (v) { + _selectedValues.add(value); + } else { + _selectedValues.remove(value); + } + setState(() {}); + }, + title: Align( + alignment: AlignmentDirectional.centerStart, + child: Text(title), + ), + subtitle: subtitle != null + ? Text( + subtitle, + softWrap: false, + overflow: TextOverflow.fade, + ) + : null, + dense: widget.dense, + ); + }), + if (verticalPadding != 0) SizedBox(height: verticalPadding), + ], + actions: [ + const CancelButton(), + TextButton( + onPressed: () => Navigator.maybeOf(context)?.pop(widget.options.keys.where(_selectedValues.contains).toList()), + child: Text(context.l10n.applyButtonLabel), + ), + ], + ); + } +} diff --git a/lib/widgets/dialogs/selection_dialogs/radio_list_tile.dart b/lib/widgets/dialogs/selection_dialogs/radio_list_tile.dart new file mode 100644 index 0000000..9307ff9 --- /dev/null +++ b/lib/widgets/dialogs/selection_dialogs/radio_list_tile.dart @@ -0,0 +1,61 @@ +import 'package:aves/widgets/common/basic/list_tiles/reselectable_radio.dart'; +import 'package:aves/widgets/dialogs/selection_dialogs/common.dart'; +import 'package:flutter/material.dart'; + +class SelectionRadioListTile<T> extends StatelessWidget { + final T value; + final String title; + final TextBuilder<T>? optionSubtitleBuilder; + final bool needConfirmation; + final bool? dense; + final Widget? secondary; + final T Function() getGroupValue; + final void Function(T value) setGroupValue; + + const SelectionRadioListTile({ + super.key, + required this.value, + required this.title, + this.optionSubtitleBuilder, + required this.needConfirmation, + this.dense, + this.secondary, + required this.getGroupValue, + required this.setGroupValue, + }); + + @override + Widget build(BuildContext context) { + final subtitle = optionSubtitleBuilder?.call(value); + return ReselectableRadioListTile<T>( + // key is expected by test driver + key: Key('$value'), + value: value, + groupValue: getGroupValue(), + onChanged: (v) { + // always update the group value even when popping afterwards, + // so that the group value can be used in pop handlers + // as well as the regular return value from navigation + setGroupValue(v as T); + if (!needConfirmation) { + Navigator.maybeOf(context)?.pop(v); + } + }, + reselectable: true, + title: Text( + title, + overflow: TextOverflow.ellipsis, + maxLines: 2, + ), + subtitle: subtitle != null + ? Text( + subtitle, + softWrap: false, + overflow: TextOverflow.fade, + ) + : null, + dense: dense, + secondary: secondary, + ); + } +} diff --git a/lib/widgets/dialogs/selection_dialogs/single_selection.dart b/lib/widgets/dialogs/selection_dialogs/single_selection.dart new file mode 100644 index 0000000..a39b030 --- /dev/null +++ b/lib/widgets/dialogs/selection_dialogs/single_selection.dart @@ -0,0 +1,82 @@ +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:aves/widgets/dialogs/selection_dialogs/common.dart'; +import 'package:aves/widgets/dialogs/selection_dialogs/radio_list_tile.dart'; +import 'package:flutter/material.dart'; + +// do not use as `T` a record containing a collection +// because radio value comparison will fail without deep equality +class AvesSingleSelectionDialog<T> extends StatefulWidget { + static const routeName = '/dialog/selection'; + + final T initialValue; + final Map<T, String> options; + final TextBuilder<T>? optionSubtitleBuilder; + final String? title, message, confirmationButtonLabel; + final bool? dense; + + const AvesSingleSelectionDialog({ + super.key, + required this.initialValue, + required this.options, + this.optionSubtitleBuilder, + this.title, + this.message, + this.confirmationButtonLabel, + this.dense, + }); + + @override + State<AvesSingleSelectionDialog<T>> createState() => _AvesSingleSelectionDialogState<T>(); +} + +class _AvesSingleSelectionDialogState<T> extends State<AvesSingleSelectionDialog<T>> { + late T _selectedValue; + + @override + void initState() { + super.initState(); + _selectedValue = widget.initialValue; + } + + @override + Widget build(BuildContext context) { + final title = widget.title; + final message = widget.message; + final verticalPadding = (title == null && message == null) ? AvesDialog.cornerRadius.y / 2 : .0; + final confirmationButtonLabel = widget.confirmationButtonLabel; + final needConfirmation = confirmationButtonLabel != null; + return AvesDialog( + title: title, + scrollableContent: [ + if (verticalPadding != 0) SizedBox(height: verticalPadding), + if (message != null) + Padding( + padding: const EdgeInsets.all(16), + child: Text(message), + ), + ...widget.options.entries.map((kv) { + final radioValue = kv.key; + final radioTitle = kv.value; + return SelectionRadioListTile( + value: radioValue, + title: radioTitle, + optionSubtitleBuilder: widget.optionSubtitleBuilder, + needConfirmation: needConfirmation, + dense: widget.dense, + getGroupValue: () => _selectedValue, + setGroupValue: (v) => setState(() => _selectedValue = v), + ); + }), + if (verticalPadding != 0) SizedBox(height: verticalPadding), + ], + actions: [ + const CancelButton(), + if (needConfirmation) + TextButton( + onPressed: () => Navigator.maybeOf(context)?.pop(_selectedValue), + child: Text(confirmationButtonLabel), + ), + ], + ); + } +} diff --git a/lib/widgets/dialogs/tile_view_dialog.dart b/lib/widgets/dialogs/tile_view_dialog.dart new file mode 100644 index 0000000..1e1b514 --- /dev/null +++ b/lib/widgets/dialogs/tile_view_dialog.dart @@ -0,0 +1,264 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/widgets/common/basic/font_size_icon_theme.dart'; +import 'package:aves/widgets/common/basic/text_dropdown_button.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/fx/transitions.dart'; +import 'package:aves/widgets/common/identity/aves_caption.dart'; +import 'package:aves/widgets/common/identity/highlight_title.dart'; +import 'package:aves/widgets/common/tile_extent_controller.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +import 'aves_dialog.dart'; + +class TileViewDialog<S, G, L> extends StatefulWidget { + static const routeName = '/dialog/tile_view'; + + final (S? sort, G? section, L? layout, bool reverse) initialValue; + final List<TileViewDialogOption<S>> sortOptions; + final List<TileViewDialogOption<G>> sectionOptions; + final List<TileViewDialogOption<L>> layoutOptions; + final String Function(S sort, bool reverse) sortOrder; + final TileExtentController tileExtentController; + final bool Function(S? sort, G? section, L? layout)? canSection; + + const TileViewDialog({ + super.key, + required this.initialValue, + this.sortOptions = const [], + this.sectionOptions = const [], + this.layoutOptions = const [], + required this.sortOrder, + this.canSection, + required this.tileExtentController, + }); + + @override + State<TileViewDialog> createState() => _TileViewDialogState<S, G, L>(); +} + +class _TileViewDialogState<S, G, L> extends State<TileViewDialog<S, G, L>> with SingleTickerProviderStateMixin { + late S? _selectedSort; + late G? _selectedSection; + late L? _selectedLayout; + late bool _reverseSort; + late int _columnMin, _columnMax; + late final ValueNotifier<int> _columnCountNotifier = ValueNotifier(tileExtentController.columnCount); + + List<TileViewDialogOption<S>> get sortOptions => widget.sortOptions; + + List<TileViewDialogOption<G>> get sectionOptions => widget.sectionOptions; + + List<TileViewDialogOption<L>> get layoutOptions => widget.layoutOptions; + + TileExtentController get tileExtentController => widget.tileExtentController; + + bool get canSection => (widget.canSection ?? (s, g, l) => true).call(_selectedSort, _selectedSection, _selectedLayout); + + @override + void initState() { + super.initState(); + final initialValue = widget.initialValue; + _selectedSort = initialValue.$1; + _selectedSection = initialValue.$2; + _selectedLayout = initialValue.$3; + _reverseSort = initialValue.$4; + + final extentController = tileExtentController; + final columnRange = extentController.effectiveColumnRange; + _columnMin = columnRange.$1; + _columnMax = columnRange.$2; + } + + @override + void dispose() { + _columnCountNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + + return AvesDialog( + scrollableContent: [ + _buildSection( + icon: AIcons.sort, + title: l10n.viewDialogSortSectionTitle, + trailing: IconButton( + icon: const Icon(AIcons.sortOrder), + onPressed: () => setState(() => _reverseSort = !_reverseSort), + tooltip: l10n.viewDialogReverseSortOrder, + ), + options: sortOptions, + value: _selectedSort, + onChanged: (v) { + _selectedSort = v; + _reverseSort = false; + }, + bottom: _selectedSort != null ? AvesCaption(widget.sortOrder(_selectedSort as S, _reverseSort)) : null, + ), + AnimatedSwitcher( + duration: context.read<DurationsData>().formTransition, + switchInCurve: Curves.easeInOutCubic, + switchOutCurve: Curves.easeInOutCubic, + transitionBuilder: AvesTransitions.formTransitionBuilder, + child: _buildSection( + show: canSection, + icon: AIcons.section, + title: l10n.viewDialogGroupSectionTitle, + options: sectionOptions, + value: _selectedSection, + onChanged: (v) => _selectedSection = v, + ), + ), + _buildSection( + icon: AIcons.layout, + title: l10n.viewDialogLayoutSectionTitle, + options: layoutOptions, + value: _selectedLayout, + onChanged: (v) => _selectedLayout = v, + ), + if (settings.showPinchGestureAlternatives) + Padding( + padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16), + child: Row( + children: [ + const Icon(AIcons.thumbnailLarge), + Expanded( + child: ValueListenableBuilder<int>( + valueListenable: _columnCountNotifier, + builder: (context, columnCount, child) => Slider( + label: context.l10n.columnCount(columnCount), + value: columnCount.toDouble(), + onChanged: (v) => _columnCountNotifier.value = v.round(), + min: _columnMin.toDouble(), + max: _columnMax.toDouble(), + divisions: (_columnMax - _columnMin), + ), + ), + ), + const Icon(AIcons.thumbnailSmall), + ], + ), + ), + ], + actions: [ + const CancelButton(), + TextButton( + key: const Key('button-apply'), + onPressed: () { + tileExtentController.setUserPreferredColumnCount(_columnCountNotifier.value); + Navigator.maybeOf(context)?.pop<(S?, G?, L?, bool)>((_selectedSort, _selectedSection, _selectedLayout, _reverseSort)); + }, + child: Text(l10n.applyButtonLabel), + ) + ], + ); + } + + Widget _buildSection<T>({ + bool show = true, + required IconData icon, + required String title, + Widget? trailing, + required List<TileViewDialogOption<T>> options, + required T value, + required ValueChanged<T?> onChanged, + Widget? bottom, + }) { + if (options.isEmpty || !show) return const SizedBox(); + + final label = ConstrainedBox( + constraints: const BoxConstraints(minHeight: kMinInteractiveDimension), + child: FontSizeIconTheme( + child: Row( + children: [ + Icon(icon), + const SizedBox(width: 16), + Expanded( + child: HighlightTitle( + title: title, + showHighlight: false, + ), + ), + if (trailing != null) trailing, + ], + ), + ), + ); + final selector = TextDropdownButton<T>( + values: options.map((v) => v.value).toList(), + valueText: (v) => options.firstWhere((option) => option.value == v).title, + valueIcon: (v) => options.firstWhere((option) => option.value == v).icon, + value: value, + onChanged: (v) => setState(() => onChanged(v)), + isExpanded: true, + dropdownColor: Themes.thirdLayerColor(context), + ); + + final textScaler = MediaQuery.textScalerOf(context); + final iconSize = textScaler.scale(IconTheme.of(context).size!); + final isPortrait = MediaQuery.orientationOf(context) == Orientation.portrait; + final child = isPortrait + ? Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + label, + Padding( + padding: EdgeInsetsDirectional.only(start: iconSize + 16, end: 12), + child: selector, + ), + if (bottom != null) + Padding( + padding: EdgeInsetsDirectional.only(start: iconSize + 16), + child: bottom, + ), + ], + ) + : Row( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded(child: label), + const SizedBox(width: 8), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + selector, + if (bottom != null) bottom, + ], + ), + ), + ], + ); + + return TooltipTheme( + data: TooltipTheme.of(context).copyWith( + preferBelow: false, + ), + child: Padding( + padding: const EdgeInsets.only(left: 16, top: 8, right: 16), + child: child, + ), + ); + } +} + +@immutable +class TileViewDialogOption<T> { + final T value; + final String title; + final IconData icon; + + const TileViewDialogOption({ + required this.value, + required this.title, + required this.icon, + }); +} diff --git a/lib/widgets/dialogs/time_shift_dialog.dart b/lib/widgets/dialogs/time_shift_dialog.dart new file mode 100644 index 0000000..92f3a74 --- /dev/null +++ b/lib/widgets/dialogs/time_shift_dialog.dart @@ -0,0 +1,52 @@ +import 'package:aves/widgets/common/basic/time_shift_selector.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:flutter/material.dart'; + +import 'aves_dialog.dart'; + +class TimeShiftDialog extends StatefulWidget { + static const routeName = '/dialog/time_shift'; + + final Duration initialValue; + + const TimeShiftDialog({ + super.key, + required this.initialValue, + }); + + @override + State<TimeShiftDialog> createState() => _TimeShiftDialogState(); +} + +class _TimeShiftDialogState extends State<TimeShiftDialog> { + late TimeShiftController _timeShiftController; + + @override + void initState() { + super.initState(); + _timeShiftController = TimeShiftController( + initialValue: widget.initialValue, + ); + } + + @override + Widget build(BuildContext context) { + return AvesDialog( + scrollableContent: [ + Padding( + padding: const EdgeInsets.symmetric(vertical: 16), + child: TimeShiftSelector(controller: _timeShiftController), + ), + ], + actions: [ + const CancelButton(), + TextButton( + onPressed: () => _submit(context), + child: Text(context.l10n.applyButtonLabel), + ), + ], + ); + } + + void _submit(BuildContext context) => Navigator.maybeOf(context)?.pop(_timeShiftController.value); +} diff --git a/lib/widgets/dialogs/video_speed_dialog.dart b/lib/widgets/dialogs/video_speed_dialog.dart new file mode 100644 index 0000000..eb1f671 --- /dev/null +++ b/lib/widgets/dialogs/video_speed_dialog.dart @@ -0,0 +1,76 @@ +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:flutter/material.dart'; + +import 'aves_dialog.dart'; + +class VideoSpeedDialog extends StatefulWidget { + static const routeName = '/dialog/select_video_speed'; + + final double current, min, max; + + const VideoSpeedDialog({ + super.key, + required this.current, + required this.min, + required this.max, + }); + + @override + State<VideoSpeedDialog> createState() => _VideoSpeedDialogState(); +} + +class _VideoSpeedDialogState extends State<VideoSpeedDialog> { + late double _speed; + + static const interval = .25; + + @override + void initState() { + super.initState(); + _speed = widget.current; + } + + @override + Widget build(BuildContext context) { + return AvesDialog( + horizontalContentPadding: 4, + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.symmetric(horizontal: 24), + child: Wrap( + children: [ + Text(context.l10n.videoSpeedDialogLabel), + const SizedBox(width: 16), + Text('x$_speed'), + ], + ), + ), + const SizedBox(height: 16), + Slider( + value: _speed, + onChanged: (v) => setState(() { + // provided value may be imprecise on some platforms + // e.g. 1.7499999999999998 instead of 1.75 + _speed = (v / interval).round() * interval; + }), + min: widget.min, + max: widget.max, + divisions: ((widget.max - widget.min) / interval).round(), + ), + ], + ), + actions: [ + const CancelButton(), + TextButton( + onPressed: () => _submit(context), + child: Text(context.l10n.applyButtonLabel), + ), + ], + ); + } + + void _submit(BuildContext context) => Navigator.maybeOf(context)?.pop(_speed); +} diff --git a/lib/widgets/dialogs/video_stream_selection_dialog.dart b/lib/widgets/dialogs/video_stream_selection_dialog.dart new file mode 100644 index 0000000..668ac50 --- /dev/null +++ b/lib/widgets/dialogs/video_stream_selection_dialog.dart @@ -0,0 +1,164 @@ +import 'package:aves/ref/languages.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/theme/text.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/widgets/common/basic/text_dropdown_button.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves_video/aves_video.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; + +import 'aves_dialog.dart'; + +class VideoStreamSelectionDialog extends StatefulWidget { + static const routeName = '/dialog/select_video_stream'; + + final Map<MediaStreamSummary, bool> streams; + + const VideoStreamSelectionDialog({ + super.key, + required this.streams, + }); + + @override + State<VideoStreamSelectionDialog> createState() => _VideoStreamSelectionDialogState(); +} + +class _VideoStreamSelectionDialogState extends State<VideoStreamSelectionDialog> { + late List<MediaStreamSummary?> _videoStreams, _audioStreams, _textStreams; + MediaStreamSummary? _currentVideo, _currentAudio, _currentText; + + @override + void initState() { + super.initState(); + + final byType = groupBy<MediaStreamSummary, MediaStreamType>(widget.streams.keys, (v) => v.type); + // check width/height to exclude image streams (that are included among video streams) + _videoStreams = (byType[MediaStreamType.video] ?? []).where((v) => v.width != null && v.height != null).toList(); + _audioStreams = (byType[MediaStreamType.audio] ?? []); + _textStreams = [null, ...byType[MediaStreamType.text] ?? []]; + + final streamEntries = widget.streams.entries; + _currentVideo = streamEntries.firstWhereOrNull((kv) => kv.key.type == MediaStreamType.video && kv.value)?.key; + _currentAudio = streamEntries.firstWhereOrNull((kv) => kv.key.type == MediaStreamType.audio && kv.value)?.key; + _currentText = streamEntries.firstWhereOrNull((kv) => kv.key.type == MediaStreamType.text && kv.value)?.key; + } + + @override + Widget build(BuildContext context) { + final canSelectVideo = _videoStreams.length > 1; + final canSelectAudio = _audioStreams.length > 1; + final canSelectText = _textStreams.length > 1; + final canSelect = canSelectVideo || canSelectAudio || canSelectText; + return AvesDialog( + content: canSelect ? null : Text(context.l10n.videoStreamSelectionDialogNoSelection), + scrollableContent: canSelect + ? [ + if (canSelectVideo) + ..._buildSection( + icon: AIcons.streamVideo, + title: context.l10n.videoStreamSelectionDialogVideo, + streams: _videoStreams, + current: _currentVideo, + setter: (v) => _currentVideo = v, + ), + if (canSelectAudio) + ..._buildSection( + icon: AIcons.streamAudio, + title: context.l10n.videoStreamSelectionDialogAudio, + streams: _audioStreams, + current: _currentAudio, + setter: (v) => _currentAudio = v, + ), + if (canSelectText) + ..._buildSection( + icon: AIcons.streamText, + title: context.l10n.videoStreamSelectionDialogText, + streams: _textStreams, + current: _currentText, + setter: (v) => _currentText = v, + ), + const SizedBox(height: 8), + ] + : null, + actions: [ + const CancelButton(), + if (canSelect) + TextButton( + onPressed: () => _submit(context), + child: Text(context.l10n.applyButtonLabel), + ), + ], + ); + } + + static String _formatLanguage(String value) { + final language = Language.living639_2.firstWhereOrNull((language) => language.iso639_2 == value); + return language?.native ?? value; + } + + String _commonStreamName(MediaStreamSummary? stream) { + if (stream == null) return context.l10n.videoStreamSelectionDialogOff; + final title = stream.title; + final language = stream.language; + if (language != null && language != 'und') { + final formattedLanguage = _formatLanguage(language); + return '$formattedLanguage${title != null && title != formattedLanguage ? ' • $title' : ''}'; + } else if (title != null) { + return title; + } else { + return '${context.l10n.videoStreamSelectionDialogTrack} ${stream.index} (${stream.codecName})'; + } + } + + String _streamName(MediaStreamSummary? stream) { + final common = _commonStreamName(stream); + if (stream != null && stream.type == MediaStreamType.video) { + final w = stream.width; + final h = stream.height; + if (w != null && h != null) { + return '$common • $w${AText.resolutionSeparator}$h'; + } + } + return common; + } + + List<Widget> _buildSection({ + required IconData icon, + required String title, + required List<MediaStreamSummary?> streams, + required MediaStreamSummary? current, + required ValueSetter<MediaStreamSummary?> setter, + }) { + return [ + Padding( + padding: const EdgeInsets.only(left: 16, top: 16, right: 16), + child: Row( + children: [ + Icon(icon), + const SizedBox(width: 16), + Text(title), + ], + ), + ), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + // allow `null` subtitle stream to disable subtitles + child: TextDropdownButton<MediaStreamSummary?>( + values: streams, + valueText: _streamName, + value: current, + onChanged: streams.length > 1 ? (newValue) => setState(() => setter(newValue)) : null, + isExpanded: true, + dropdownColor: Themes.thirdLayerColor(context), + ), + ), + ]; + } + + void _submit(BuildContext context) => Navigator.maybeOf(context)?.pop({ + MediaStreamType.video: _currentVideo, + MediaStreamType.audio: _currentAudio, + MediaStreamType.text: _currentText, + }); +} diff --git a/lib/widgets/dialogs/wallpaper_settings_dialog.dart b/lib/widgets/dialogs/wallpaper_settings_dialog.dart new file mode 100644 index 0000000..20cddd7 --- /dev/null +++ b/lib/widgets/dialogs/wallpaper_settings_dialog.dart @@ -0,0 +1,51 @@ +import 'package:aves/model/device.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:aves/widgets/dialogs/selection_dialogs/radio_list_tile.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; + +class WallpaperSettingsDialog extends StatefulWidget { + static const routeName = '/dialog/wallpaper_settings'; + + const WallpaperSettingsDialog({super.key}); + + @override + State<WallpaperSettingsDialog> createState() => _WallpaperSettingsDialogState(); +} + +class _WallpaperSettingsDialogState extends State<WallpaperSettingsDialog> { + WallpaperTarget _selectedTarget = WallpaperTarget.home; + bool _useScrollEffect = true; + + @override + Widget build(BuildContext context) { + return AvesDialog( + scrollableContent: [ + if (device.canSetLockScreenWallpaper) + ...WallpaperTarget.values.map((value) { + return SelectionRadioListTile( + value: value, + title: value.getName(context), + needConfirmation: true, + getGroupValue: () => _selectedTarget, + setGroupValue: (v) => setState(() => _selectedTarget = v), + ); + }), + SwitchListTile( + value: _useScrollEffect, + onChanged: (v) => setState(() => _useScrollEffect = v), + title: Text(context.l10n.wallpaperUseScrollEffect), + ) + ], + actions: [ + const CancelButton(), + TextButton( + onPressed: () => Navigator.maybeOf(context)?.pop<(WallpaperTarget, bool)>((_selectedTarget, _useScrollEffect)), + child: Text(context.l10n.applyButtonLabel), + ), + ], + ); + } +} diff --git a/lib/widgets/editor/control_panel.dart b/lib/widgets/editor/control_panel.dart new file mode 100644 index 0000000..e938b88 --- /dev/null +++ b/lib/widgets/editor/control_panel.dart @@ -0,0 +1,137 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/basic/multi_cross_fader.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/buttons/overlay_button.dart'; +import 'package:aves/widgets/editor/transform/control_panel.dart'; +import 'package:aves/widgets/editor/transform/controller.dart'; +import 'package:aves/widgets/viewer/overlay/viewer_buttons.dart'; +import 'package:aves_magnifier/aves_magnifier.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class EditorControlPanel extends StatelessWidget { + final AvesEntry entry; + final ValueNotifier<EditorAction?> actionNotifier; + + static const padding = ViewerButtonRowContent.padding; + static const actions = [ + EditorAction.transform, + ]; + + const EditorControlPanel({ + super.key, + required this.entry, + required this.actionNotifier, + }); + + @override + Widget build(BuildContext context) { + return PopScope( + canPop: actionNotifier.value == null, + onPopInvokedWithResult: (didPop, result) { + if (didPop) return; + + _cancelAction(context); + }, + child: Padding( + padding: const EdgeInsets.all(padding), + child: TooltipTheme( + data: TooltipTheme.of(context).copyWith( + preferBelow: false, + ), + child: ValueListenableBuilder<EditorAction?>( + valueListenable: actionNotifier, + builder: (context, action, child) { + return MultiCrossFader( + duration: context.select<DurationsData, Duration>((v) => v.formTransition), + alignment: Alignment.bottomCenter, + layoutBuilder: (topChild, topChildKey, bottomChild, bottomChildKey) { + return Stack( + clipBehavior: Clip.none, + children: <Widget>[ + Positioned( + key: bottomChildKey, + left: 0.0, + bottom: 0.0, + right: 0.0, + child: bottomChild, + ), + Positioned( + key: topChildKey, + child: topChild, + ), + ], + ); + }, + child: action == null ? _buildTopLevelPanel(context) : _buildActionPanel(context, action), + ); + }, + ), + ), + ), + ); + } + + Widget _buildTopLevelPanel(BuildContext context) { + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + Row( + mainAxisSize: MainAxisSize.min, + children: [ + ...actions.map( + (action) => Padding( + padding: const EdgeInsetsDirectional.symmetric(horizontal: padding / 2), + child: OverlayButton( + child: IconButton( + icon: action.getIcon(), + onPressed: () => actionNotifier.value = action, + tooltip: action.getText(context), + ), + ), + ), + ), + ], + ), + const SizedBox(height: padding), + Row( + children: [ + const OverlayButton( + child: CloseButton(), + ), + const Spacer(), + OverlayTextButton( + onPressed: () {}, + child: Text(context.l10n.saveCopyButtonLabel), + ), + ], + ), + ], + ); + } + + Widget _buildActionPanel(BuildContext context, EditorAction action) { + switch (action) { + case EditorAction.transform: + return TransformControlPanel( + entry: entry, + onCancel: () => _cancelAction(context), + onApply: (transformation) => _applyAction(context), + ); + } + } + + void _cancelAction(BuildContext context) { + actionNotifier.value = null; + context.read<AvesMagnifierController>().reset(); + context.read<TransformController>().reset(); + } + + void _applyAction(BuildContext context) { + actionNotifier.value = null; + context.read<TransformController>().reset(); + } +} diff --git a/lib/widgets/editor/entry_editor_page.dart b/lib/widgets/editor/entry_editor_page.dart new file mode 100644 index 0000000..87eca78 --- /dev/null +++ b/lib/widgets/editor/entry_editor_page.dart @@ -0,0 +1,140 @@ +import 'dart:async'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/viewer/view_state.dart'; +import 'package:aves/widgets/editor/control_panel.dart'; +import 'package:aves/widgets/editor/image.dart'; +import 'package:aves/widgets/editor/transform/controller.dart'; +import 'package:aves/widgets/editor/transform/cropper.dart'; +import 'package:aves/widgets/viewer/overlay/minimap.dart'; +import 'package:aves_magnifier/aves_magnifier.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class ImageEditorPage extends StatefulWidget { + static const routeName = '/image_editor'; + + final AvesEntry entry; + + const ImageEditorPage({ + super.key, + required this.entry, + }); + + @override + State<ImageEditorPage> createState() => _ImageEditorPageState(); +} + +class _ImageEditorPageState extends State<ImageEditorPage> { + final Set<StreamSubscription> _subscriptions = {}; + final ValueNotifier<EditorAction?> _actionNotifier = ValueNotifier(null); + final ValueNotifier<EdgeInsets> _marginNotifier = ValueNotifier(EdgeInsets.zero); + final ValueNotifier<ViewState> _viewStateNotifier = ValueNotifier<ViewState>(ViewState.zero); + final AvesMagnifierController _magnifierController = AvesMagnifierController(); + late final TransformController _transformController; + + @override + void initState() { + super.initState(); + _transformController = TransformController(widget.entry.displaySize); + _actionNotifier.addListener(_onActionChanged); + _subscriptions.add(_transformController.transformationStream.map((v) => v.matrix).distinct().listen(_onTransformationMatrixChanged)); + } + + @override + void dispose() { + _subscriptions + ..forEach((sub) => sub.cancel()) + ..clear(); + _actionNotifier.dispose(); + _marginNotifier.dispose(); + _viewStateNotifier.dispose(); + _magnifierController.dispose(); + _transformController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + body: MultiProvider( + providers: [ + Provider<AvesMagnifierController>.value(value: _magnifierController), + Provider<TransformController>.value(value: _transformController), + ], + child: SafeArea( + child: Column( + children: [ + Expanded( + child: Stack( + children: [ + ClipRect( + child: EditorImage( + magnifierController: _magnifierController, + transformController: _transformController, + actionNotifier: _actionNotifier, + marginNotifier: _marginNotifier, + viewStateNotifier: _viewStateNotifier, + entry: widget.entry, + ), + ), + if (settings.showOverlayMinimap) + PositionedDirectional( + start: 8, + bottom: 8, + child: Minimap(viewStateNotifier: _viewStateNotifier), + ), + ValueListenableBuilder<EditorAction?>( + valueListenable: _actionNotifier, + builder: (context, action, child) { + switch (action) { + case EditorAction.transform: + return Cropper( + magnifierController: _magnifierController, + transformController: _transformController, + marginNotifier: _marginNotifier, + ); + case null: + return const SizedBox(); + } + }, + ), + ], + ), + ), + const Divider(height: 0), + EditorControlPanel( + entry: widget.entry, + actionNotifier: _actionNotifier, + ), + ], + ), + ), + ), + resizeToAvoidBottomInset: false, + ); + } + + void _onActionChanged() { + switch (_actionNotifier.value) { + case EditorAction.transform: + _transformController.reset(); + _marginNotifier.value = Cropper.imageMargin; + default: + _marginNotifier.value = EdgeInsets.zero; + } + } + + void _onTransformationMatrixChanged(Matrix4 transformationMatrix) { + final boundaries = _magnifierController.scaleBoundaries; + if (boundaries != null) { + _magnifierController.setScaleBoundaries( + boundaries.copyWith( + externalTransform: transformationMatrix, + ), + ); + } + } +} diff --git a/lib/widgets/editor/image.dart b/lib/widgets/editor/image.dart new file mode 100644 index 0000000..df62135 --- /dev/null +++ b/lib/widgets/editor/image.dart @@ -0,0 +1,224 @@ +import 'dart:async'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/viewer/view_state.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/widgets/editor/transform/controller.dart'; +import 'package:aves/widgets/editor/transform/painter.dart'; +import 'package:aves/widgets/editor/transform/transformation.dart'; +import 'package:aves/widgets/viewer/visual/error.dart'; +import 'package:aves/widgets/viewer/visual/raster.dart'; +import 'package:aves_magnifier/aves_magnifier.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class EditorImage extends StatefulWidget { + final AvesMagnifierController magnifierController; + final TransformController transformController; + final ValueNotifier<EditorAction?> actionNotifier; + final ValueNotifier<EdgeInsets> marginNotifier; + final ValueNotifier<ViewState> viewStateNotifier; + final AvesEntry entry; + + const EditorImage({ + super.key, + required this.magnifierController, + required this.transformController, + required this.actionNotifier, + required this.marginNotifier, + required this.viewStateNotifier, + required this.entry, + }); + + @override + State<EditorImage> createState() => _EditorImageState(); +} + +class _EditorImageState extends State<EditorImage> { + final Set<StreamSubscription> _subscriptions = {}; + final ValueNotifier<double> _scrimOpacityNotifier = ValueNotifier(0); + + AvesEntry get entry => widget.entry; + + TransformController get transformController => widget.transformController; + + ValueNotifier<ViewState> get viewStateNotifier => widget.viewStateNotifier; + + @override + void initState() { + super.initState(); + _registerWidget(widget); + } + + @override + void didUpdateWidget(covariant EditorImage oldWidget) { + super.didUpdateWidget(oldWidget); + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + + @override + void dispose() { + _subscriptions + ..forEach((sub) => sub.cancel()) + ..clear(); + _unregisterWidget(widget); + super.dispose(); + } + + void _registerWidget(EditorImage widget) { + widget.actionNotifier.addListener(_onActionChanged); + _subscriptions.add(widget.magnifierController.stateStream.listen(_onViewStateChanged)); + _subscriptions.add(widget.magnifierController.scaleBoundariesStream.listen(_onViewScaleBoundariesChanged)); + _subscriptions.add(widget.transformController.activityStream.listen(_onTransformActivity)); + } + + void _unregisterWidget(EditorImage widget) { + widget.actionNotifier.removeListener(_onActionChanged); + _subscriptions + ..forEach((sub) => sub.cancel()) + ..clear(); + } + + @override + Widget build(BuildContext context) { + return MagnifierGestureDetectorScope( + axis: const [Axis.horizontal, Axis.vertical], + child: StreamBuilder<Transformation>( + stream: transformController.transformationStream, + builder: (context, snapshot) { + final transformation = (snapshot.data ?? Transformation.zero); + final highlightRegionCorners = transformation.region.corners; + final imageToUserMatrix = transformation.matrix; + + final mediaSize = entry.displaySize; + final canvasSize = MatrixUtils.transformRect(imageToUserMatrix, Offset.zero & mediaSize).size; + + return ValueListenableBuilder<EdgeInsets>( + valueListenable: widget.marginNotifier, + builder: (context, margin, child) { + return Transform( + alignment: Alignment.center, + transform: imageToUserMatrix, + child: ValueListenableBuilder<EditorAction?>( + valueListenable: widget.actionNotifier, + builder: (context, action, child) { + return LayoutBuilder( + builder: (context, constraints) { + final viewportSize = margin.deflateSize(constraints.biggest); + final minScale = ScaleLevel(factor: ScaleLevel.scaleForContained(viewportSize, canvasSize)); + return AvesMagnifier( + key: Key('${entry.uri}_${entry.pageId}_${entry.dateModifiedMillis}'), + controller: widget.magnifierController, + viewportPadding: margin, + contentSize: mediaSize, + allowOriginalScaleBeyondRange: false, + allowGestureScaleBeyondRange: false, + panInertia: _getActionPanInertia(action), + minScale: minScale, + maxScale: const ScaleLevel(factor: 1), + initialScale: minScale, + scaleStateCycle: defaultScaleStateCycle, + applyScale: false, + onScaleStart: (details, doubleTap, boundaries) { + transformController.activity = TransformActivity.pan; + }, + onScaleEnd: (details) { + transformController.activity = TransformActivity.none; + }, + child: child!, + ); + }, + ); + }, + child: Stack( + children: [ + RasterImageView( + entry: entry, + viewStateNotifier: viewStateNotifier, + errorBuilder: (context, error, stackTrace) => ErrorView( + entry: entry, + onTap: () {}, + ), + ), + Positioned.fill( + child: ValueListenableBuilder<ViewState>( + valueListenable: viewStateNotifier, + builder: (context, viewState, child) { + final scale = viewState.scale ?? 1; + final highlightRegionPath = Path()..addPolygon(highlightRegionCorners.map((v) => v * scale).toList(), true); + return ValueListenableBuilder<double>( + valueListenable: _scrimOpacityNotifier, + builder: (context, opacity, child) { + return AnimatedOpacity( + opacity: opacity, + duration: context.read<DurationsData>().viewerOverlayAnimation, + child: CustomPaint( + painter: ScrimPainter( + excludePath: highlightRegionPath, + opacity: opacity, + ), + ), + ); + }, + ); + }, + ), + ), + ], + ), + ), + ); + }, + ); + }, + ), + ); + } + + void _onViewStateChanged(MagnifierState v) { + viewStateNotifier.value = viewStateNotifier.value.copyWith( + position: v.position, + scale: v.scale, + ); + } + + void _onViewScaleBoundariesChanged(ScaleBoundaries v) { + viewStateNotifier.value = viewStateNotifier.value.copyWith( + viewportSize: v.viewportSize, + contentSize: v.contentSize, + ); + } + + void _onActionChanged() => _updateScrim(); + + void _onTransformActivity(TransformActivity activity) => _updateScrim(); + + void _updateScrim() => _scrimOpacityNotifier.value = _getActionScrimOpacity(widget.actionNotifier.value, transformController.activity); + + static double _getActionPanInertia(EditorAction? action) { + switch (action) { + case EditorAction.transform: + return 0; + case null: + return AvesMagnifier.defaultPanInertia; + } + } + + static double _getActionScrimOpacity(EditorAction? action, TransformActivity activity) { + switch (action) { + case EditorAction.transform: + switch (activity) { + case TransformActivity.none: + return .9; + case TransformActivity.pan: + case TransformActivity.resize: + case TransformActivity.straighten: + return .6; + } + case null: + return 0; + } + } +} diff --git a/lib/widgets/editor/transform/control_panel.dart b/lib/widgets/editor/transform/control_panel.dart new file mode 100644 index 0000000..f025b7f --- /dev/null +++ b/lib/widgets/editor/transform/control_panel.dart @@ -0,0 +1,202 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/buttons/captioned_button.dart'; +import 'package:aves/widgets/common/identity/buttons/overlay_button.dart'; +import 'package:aves/widgets/editor/control_panel.dart'; +import 'package:aves/widgets/editor/transform/controller.dart'; +import 'package:aves/widgets/editor/transform/transformation.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; +import 'package:provider/provider.dart'; + +class TransformControlPanel extends StatefulWidget { + final AvesEntry entry; + final VoidCallback onCancel; + final void Function(Transformation transformation) onApply; + + const TransformControlPanel({ + super.key, + required this.entry, + required this.onCancel, + required this.onApply, + }); + + @override + State<TransformControlPanel> createState() => _TransformControlPanelState(); +} + +class _TransformControlPanelState extends State<TransformControlPanel> with TickerProviderStateMixin { + late final List<(WidgetBuilder, WidgetBuilder)> _tabs; + late final TabController _tabController; + + static const padding = EditorControlPanel.padding; + + @override + void initState() { + super.initState(); + _tabs = [ + ( + (context) => Tab(text: context.l10n.editorTransformCrop), + (context) => const CropControlPanel(), + ), + ( + (context) => Tab(text: context.l10n.editorTransformRotate), + (context) => const RotationControlPanel(), + ), + ]; + _tabController = TabController( + length: _tabs.length, + vsync: this, + ); + } + + @override + void dispose() { + _tabController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final transformController = context.watch<TransformController>(); + return Column( + children: [ + SizedBox( + height: CropControlPanel.preferredHeight(context), + child: AnimatedBuilder( + animation: _tabController, + builder: (context, child) { + return AnimatedSwitcher( + duration: context.select<DurationsData, Duration>((v) => v.formTransition), + child: _tabs[_tabController.index].$2(context), + ); + }, + ), + ), + const SizedBox(height: padding), + Row( + children: [ + OverlayButton( + child: BackButton( + onPressed: widget.onCancel, + ), + ), + Expanded( + child: TabBar( + tabs: _tabs.map((v) => v.$1(context)).toList(), + controller: _tabController, + padding: const EdgeInsets.symmetric(horizontal: padding), + indicatorSize: TabBarIndicatorSize.label, + ), + ), + OverlayButton( + child: StreamBuilder<Transformation>( + stream: transformController.transformationStream, + builder: (context, _) { + return IconButton( + icon: const Icon(AIcons.apply), + onPressed: transformController.modified ? () => widget.onApply(transformController.transformation) : null, + tooltip: context.l10n.applyTooltip, + ); + }, + ), + ), + ], + ), + ], + ); + } +} + +class CropControlPanel extends StatelessWidget { + const CropControlPanel({super.key}); + + static double preferredHeight(BuildContext context) => CropAspectRatio.values.map((v) { + return CaptionedButton.getSize(context, v.getText(context), showCaption: true).height; + }).max; + + @override + Widget build(BuildContext context) { + final controller = context.watch<TransformController>(); + return ListView.builder( + scrollDirection: Axis.horizontal, + shrinkWrap: true, + itemBuilder: (context, index) { + final ratio = CropAspectRatio.values[index]; + void setAspectRatio() => controller.setAspectRatio(ratio); + return CaptionedButton( + iconButtonBuilder: (context, focusNode) { + return ValueListenableBuilder<CropAspectRatio>( + valueListenable: controller.aspectRatioNotifier, + builder: (context, selectedRatio, child) { + return IconButton( + color: ratio == selectedRatio ? Theme.of(context).colorScheme.primary : null, + onPressed: setAspectRatio, + focusNode: focusNode, + icon: ratio.getIcon(), + ); + }, + ); + }, + caption: ratio.getText(context), + onPressed: setAspectRatio, + ); + }, + itemCount: CropAspectRatio.values.length, + ); + } +} + +class RotationControlPanel extends StatelessWidget { + const RotationControlPanel({super.key}); + + @override + Widget build(BuildContext context) { + final controller = context.watch<TransformController>(); + final angleFormatter = NumberFormat('0.0°', context.locale); + + return Row( + children: [ + _buildButton(context, EntryAction.flip, controller.flipHorizontally), + Expanded( + child: StreamBuilder<Transformation>( + stream: controller.transformationStream, + builder: (context, _) { + final degrees = controller.transformation.straightenDegrees; + return SliderTheme( + data: SliderTheme.of(context).copyWith( + showValueIndicator: ShowValueIndicator.always, + ), + child: Slider( + value: degrees, + min: TransformController.straightenDegreesMin, + max: TransformController.straightenDegreesMax, + onChangeStart: (v) => controller.activity = TransformActivity.straighten, + onChangeEnd: (v) => controller.activity = TransformActivity.none, + label: angleFormatter.format(degrees), + onChanged: (v) => controller.straightenDegrees = v, + ), + ); + }, + ), + ), + _buildButton(context, EntryAction.rotateCW, controller.rotateClockwise), + ], + ); + } + + Widget _buildButton(BuildContext context, EntryAction action, VoidCallback onPressed) { + return OverlayButton( + child: IconButton( + icon: action.getIcon(), + onPressed: onPressed, + tooltip: action.getText(context), + ), + ); + } +} diff --git a/lib/widgets/editor/transform/controller.dart b/lib/widgets/editor/transform/controller.dart new file mode 100644 index 0000000..57328ca --- /dev/null +++ b/lib/widgets/editor/transform/controller.dart @@ -0,0 +1,102 @@ +import 'dart:async'; +import 'dart:ui'; + +import 'package:aves/widgets/editor/transform/crop_region.dart'; +import 'package:aves/widgets/editor/transform/transformation.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/foundation.dart'; +import 'package:leak_tracker/leak_tracker.dart'; + +class TransformController { + ValueNotifier<CropAspectRatio> aspectRatioNotifier = ValueNotifier(CropAspectRatio.free); + + TransformActivity _activity = TransformActivity.none; + + TransformActivity get activity => _activity; + + Transformation _transformation = Transformation.zero; + + Transformation get transformation => _transformation; + + bool get modified => _transformation != Transformation.zero; + + final StreamController<Transformation> _transformationStreamController = StreamController.broadcast(); + + Stream<Transformation> get transformationStream => _transformationStreamController.stream; + + final StreamController<TransformActivity> _activityStreamController = StreamController.broadcast(); + + Stream<TransformActivity> get activityStream => _activityStreamController.stream; + + static const double straightenDegreesMin = -45; + static const double straightenDegreesMax = 45; + + final Size displaySize; + + TransformController(this.displaySize) { + if (kFlutterMemoryAllocationsEnabled) { + LeakTracking.dispatchObjectCreated( + library: 'aves', + className: '$TransformController', + object: this, + ); + } + reset(); + aspectRatioNotifier.addListener(_onAspectRatioChanged); + } + + void dispose() { + if (kFlutterMemoryAllocationsEnabled) { + LeakTracking.dispatchObjectDisposed(object: this); + } + aspectRatioNotifier.dispose(); + } + + void reset() { + _transformation = Transformation.zero.copyWith( + region: CropRegion.fromRect(Offset.zero & displaySize), + ); + _transformationStreamController.add(_transformation); + setAspectRatio(CropAspectRatio.free); + } + + void flipHorizontally() { + _transformation = _transformation.copyWith( + orientation: _transformation.orientation.flipHorizontally(), + straightenDegrees: -transformation.straightenDegrees, + ); + _transformationStreamController.add(_transformation); + } + + void rotateClockwise() { + _transformation = _transformation.copyWith( + orientation: _transformation.orientation.rotateClockwise(), + ); + _transformationStreamController.add(_transformation); + } + + set straightenDegrees(double straightenDegrees) { + _transformation = _transformation.copyWith( + straightenDegrees: straightenDegrees.clamp(straightenDegreesMin, straightenDegreesMax), + ); + _transformationStreamController.add(_transformation); + } + + set cropRegion(CropRegion region) { + _transformation = _transformation.copyWith( + region: region, + ); + _transformationStreamController.add(_transformation); + } + + set activity(TransformActivity activity) { + _activity = activity; + _activityStreamController.add(_activity); + } + + void setAspectRatio(CropAspectRatio ratio) => aspectRatioNotifier.value = ratio; + + void _onAspectRatioChanged() { + // TODO TLAD [crop] apply + } +} diff --git a/lib/widgets/editor/transform/crop_region.dart b/lib/widgets/editor/transform/crop_region.dart new file mode 100644 index 0000000..5a4e921 --- /dev/null +++ b/lib/widgets/editor/transform/crop_region.dart @@ -0,0 +1,40 @@ +import 'dart:ui'; + +import 'package:equatable/equatable.dart'; +import 'package:flutter/foundation.dart'; + +@immutable +class CropRegion extends Equatable { + // region corners in image pixel coordinates + final Offset topLeft, topRight, bottomRight, bottomLeft; + + List<Offset> get corners => [topLeft, topRight, bottomRight, bottomLeft]; + + Offset get center => (topLeft + bottomRight) / 2; + + @override + List<Object?> get props => [topLeft, topRight, bottomRight, bottomLeft]; + + const CropRegion({ + required this.topLeft, + required this.topRight, + required this.bottomRight, + required this.bottomLeft, + }); + + static const zero = CropRegion( + topLeft: Offset.zero, + topRight: Offset.zero, + bottomRight: Offset.zero, + bottomLeft: Offset.zero, + ); + + factory CropRegion.fromRect(Rect rect) { + return CropRegion( + topLeft: rect.topLeft, + topRight: rect.topRight, + bottomRight: rect.bottomRight, + bottomLeft: rect.bottomLeft, + ); + } +} diff --git a/lib/widgets/editor/transform/cropper.dart b/lib/widgets/editor/transform/cropper.dart new file mode 100644 index 0000000..1c37f85 --- /dev/null +++ b/lib/widgets/editor/transform/cropper.dart @@ -0,0 +1,769 @@ +import 'dart:async'; +import 'dart:math'; + +import 'package:aves/model/viewer/view_state.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/widgets/common/extensions/geometry.dart'; +import 'package:aves/widgets/common/fx/dashed_path_painter.dart'; +import 'package:aves/widgets/editor/transform/controller.dart'; +import 'package:aves/widgets/editor/transform/crop_region.dart'; +import 'package:aves/widgets/editor/transform/handles.dart'; +import 'package:aves/widgets/editor/transform/painter.dart'; +import 'package:aves/widgets/editor/transform/transformation.dart'; +import 'package:aves_magnifier/aves_magnifier.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:aves_utils/aves_utils.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class Cropper extends StatefulWidget { + final AvesMagnifierController magnifierController; + final TransformController transformController; + final ValueNotifier<EdgeInsets> marginNotifier; + + static const double handleDimension = kMinInteractiveDimension; + static const EdgeInsets imageMargin = EdgeInsets.all(kMinInteractiveDimension); + + const Cropper({ + super.key, + required this.magnifierController, + required this.transformController, + required this.marginNotifier, + }); + + @override + State<Cropper> createState() => _CropperState(); +} + +class _CropperState extends State<Cropper> with SingleTickerProviderStateMixin { + final Set<StreamSubscription> _subscriptions = {}; + final ValueNotifier<Rect> _outlineNotifier = ValueNotifier(Rect.zero); + final ValueNotifier<int> _gridDivisionNotifier = ValueNotifier(0); + late AnimationController _gridAnimationController; + late CurvedAnimation _gridOpacity; + + static const double minDimension = Cropper.handleDimension; + static const int panResizeGridDivision = 3; + static const int straightenGridDivision = 9; + static const double overOutlineFactor = .25; + + AvesMagnifierController get magnifierController => widget.magnifierController; + + TransformController get transformController => widget.transformController; + + Transformation get transformation => transformController.transformation; + + CropAspectRatio get cropAspectRatio => transformController.aspectRatioNotifier.value; + + @override + void initState() { + super.initState(); + _gridAnimationController = AnimationController( + duration: context.read<DurationsData>().viewerOverlayAnimation, + vsync: this, + ); + _gridOpacity = CurvedAnimation( + parent: _gridAnimationController, + curve: Curves.easeOutQuad, + ); + _registerWidget(widget); + } + + @override + void didUpdateWidget(covariant Cropper oldWidget) { + super.didUpdateWidget(oldWidget); + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + + @override + void dispose() { + _outlineNotifier.dispose(); + _gridDivisionNotifier.dispose(); + _gridOpacity.dispose(); + _gridAnimationController.dispose(); + _unregisterWidget(widget); + super.dispose(); + } + + void _registerWidget(Cropper widget) { + _subscriptions.add(widget.magnifierController.stateStream.listen(_onViewStateChanged)); + _subscriptions.add(widget.magnifierController.scaleBoundariesStream.map((v) => v.viewportSize).distinct().listen(_onViewportSizeChanged)); + _subscriptions.add(widget.transformController.activityStream.listen(_onTransformActivity)); + _subscriptions.add(widget.transformController.transformationStream.map((v) => v.orientation).distinct().listen(_onOrientationChanged)); + _subscriptions.add(widget.transformController.transformationStream.map((v) => v.straightenDegrees).distinct().listen(_onStraightenDegreesChanged)); + widget.transformController.aspectRatioNotifier.addListener(_onCropAspectRatioChanged); + } + + void _unregisterWidget(Cropper widget) { + _subscriptions + ..forEach((sub) => sub.cancel()) + ..clear(); + widget.transformController.aspectRatioNotifier.removeListener(_onCropAspectRatioChanged); + } + + @override + Widget build(BuildContext context) { + return Positioned.fill( + child: ValueListenableBuilder<EdgeInsets>( + valueListenable: widget.marginNotifier, + builder: (context, margin, child) { + return ValueListenableBuilder<Rect>( + valueListenable: _outlineNotifier, + builder: (context, outline, child) { + if (outline.isEmpty) return const SizedBox(); + + final outlineVisualRect = outline.translate(margin.left, margin.top); + return Stack( + children: [ + Positioned.fill( + child: IgnorePointer( + child: Stack( + children: [ + _buildDashLine([outlineVisualRect.topLeft, outlineVisualRect.topRight]), + _buildDashLine([outlineVisualRect.bottomLeft, outlineVisualRect.bottomRight]), + _buildDashLine([outlineVisualRect.topLeft, outlineVisualRect.bottomLeft]), + _buildDashLine([outlineVisualRect.topRight, outlineVisualRect.bottomRight]), + Positioned.fill( + child: ValueListenableBuilder<int>( + valueListenable: _gridDivisionNotifier, + builder: (context, gridDivision, child) { + return ValueListenableBuilder<double>( + valueListenable: _gridOpacity, + builder: (context, gridOpacity, child) { + return CustomPaint( + painter: CropperPainter( + rect: outlineVisualRect, + gridOpacity: gridOpacity, + gridDivision: gridDivision, + ), + ); + }, + ); + }, + ), + ), + ], + ), + ), + ), + _buildVertexHandle( + margin: margin, + getPosition: () => outline.topLeft, + setPosition: (v) => _handleOutline( + left: min(outline.right - minDimension, v.dx), + top: min(outline.bottom - minDimension, v.dy), + ), + ), + _buildVertexHandle( + margin: margin, + getPosition: () => outline.topRight, + setPosition: (v) => _handleOutline( + right: max(outline.left + minDimension, v.dx), + top: min(outline.bottom - minDimension, v.dy), + ), + ), + _buildVertexHandle( + margin: margin, + getPosition: () => outline.bottomRight, + setPosition: (v) => _handleOutline( + right: max(outline.left + minDimension, v.dx), + bottom: max(outline.top + minDimension, v.dy), + ), + ), + _buildVertexHandle( + margin: margin, + getPosition: () => outline.bottomLeft, + setPosition: (v) => _handleOutline( + left: min(outline.right - minDimension, v.dx), + bottom: max(outline.top + minDimension, v.dy), + ), + ), + _buildEdgeHandle( + margin: margin, + getEdge: () => Rect.fromPoints(outline.bottomLeft, outline.topLeft), + setEdge: (v) => _handleOutline( + left: min(outline.right - minDimension, v.left), + ), + ), + _buildEdgeHandle( + margin: margin, + getEdge: () => Rect.fromPoints(outline.topLeft, outline.topRight), + setEdge: (v) => _handleOutline( + top: min(outline.bottom - minDimension, v.top), + ), + ), + _buildEdgeHandle( + margin: margin, + getEdge: () => Rect.fromPoints(outline.bottomRight, outline.topRight), + setEdge: (v) => _handleOutline( + right: max(outline.left + minDimension, v.right), + ), + ), + _buildEdgeHandle( + margin: margin, + getEdge: () => Rect.fromPoints(outline.bottomLeft, outline.bottomRight), + setEdge: (v) => _handleOutline( + bottom: max(outline.top + minDimension, v.bottom), + ), + ), + ], + ); + }, + ); + }, + ), + ); + } + + // use 1 painter per line so that the dashes of one line + // do not get offset depending on the previous line length + Widget _buildDashLine(List<Offset> points) => CustomPaint( + painter: DashedPathPainter( + originalPath: Path()..addPolygon(points, false), + pathColor: CropperPainter.borderColor, + strokeWidth: CropperPainter.borderWidth, + ), + ); + + void _handleOutline({ + double? left, + double? top, + double? right, + double? bottom, + }) { + final currentOutline = _outlineNotifier.value; + var targetOutline = Rect.fromLTRB( + left ?? currentOutline.left, + top ?? currentOutline.top, + right ?? currentOutline.right, + bottom ?? currentOutline.bottom, + ); + + _RatioStrategy? ratioStrategy; + if (left != null && top != null && right != null) { + ratioStrategy = _RatioStrategy.pinBottom; + } else if (top != null && right != null && bottom != null) { + ratioStrategy = _RatioStrategy.pinLeft; + } else if (left != null && right != null && bottom != null) { + ratioStrategy = _RatioStrategy.pinTop; + } else if (left != null && top != null && bottom != null) { + ratioStrategy = _RatioStrategy.pinRight; + } else if (left != null && top != null) { + ratioStrategy = _RatioStrategy.pinBottomRight; + } else if (left != null) { + ratioStrategy = _RatioStrategy.pinTopRight; + } else if (top != null) { + ratioStrategy = _RatioStrategy.pinBottomLeft; + } else if (right != null) { + ratioStrategy = _RatioStrategy.pinTopLeft; + } else if (bottom != null) { + ratioStrategy = _RatioStrategy.pinTopLeft; + } + if (ratioStrategy != null) { + targetOutline = _applyCropRatioToOutline(targetOutline, ratioStrategy); + } + + // do not try to coerce outline handled outside tilted image + if (transformation.straightenDegrees != 0 && !_isOutlineContained(targetOutline)) return; + + // dismiss if we could not honour aspect ratio + if (cropAspectRatio != CropAspectRatio.free && !_isOutlineContained(targetOutline)) return; + + final currentState = _getViewState(); + final boundaries = magnifierController.scaleBoundaries; + if (currentState == null || boundaries == null) return; + + final gestureRegion = _regionFromOutline(currentState, targetOutline); + final viewportSize = boundaries.viewportSize; + + final gestureOutline = _containedOutlineFromRegion(currentState, gestureRegion); + final clampedOutline = Rect.fromLTRB( + max(gestureOutline.left, 0), + max(gestureOutline.top, 0), + min(gestureOutline.right, viewportSize.width), + min(gestureOutline.bottom, viewportSize.height), + ); + var nextOutline = clampedOutline; + + if (max(gestureOutline.width - clampedOutline.width, gestureOutline.height - clampedOutline.height) > precisionErrorTolerance) { + // zoom out when user gesture reaches outer edges + final targetOutline = Rect.lerp(clampedOutline, gestureOutline, overOutlineFactor)!; + final targetRegion = _regionFromOutline(currentState, targetOutline); + + final nextState = _viewStateForContainedRegion(boundaries, targetRegion); + if (nextState != currentState) { + magnifierController.update( + position: nextState.position, + scale: nextState.scale, + source: ChangeSource.animation, + ); + nextOutline = _containedOutlineFromRegion(nextState, targetRegion); + } + } + + _setOutline(nextOutline); + } + + bool _isOutlineContained(Rect outline) { + final currentState = _getViewState(); + final boundaries = magnifierController.scaleBoundaries; + if (currentState == null || boundaries == null) return false; + + final regionToOutlineMatrix = _getRegionToOutlineMatrix(currentState); + final outlineToRegionMatrix = Matrix4.inverted(regionToOutlineMatrix); + final regionCorners = { + outline.topLeft, + outline.topRight, + outline.bottomRight, + outline.bottomLeft, + }.map(outlineToRegionMatrix.transformOffset).toSet(); + + final contentRect = Offset.zero & boundaries.contentSize; + return regionCorners.every((v) => contentRect.containsIncludingBottomRight(v, tolerance: precisionErrorTolerance)); + } + + VertexHandle _buildVertexHandle({ + required EdgeInsets margin, + required ValueGetter<Offset> getPosition, + required ValueSetter<Offset> setPosition, + }) { + return VertexHandle( + margin: margin, + getPosition: getPosition, + setPosition: setPosition, + onDragStart: _onResizeStart, + onDragEnd: _onResizeEnd, + ); + } + + EdgeHandle _buildEdgeHandle({ + required EdgeInsets margin, + required ValueGetter<Rect> getEdge, + required ValueSetter<Rect> setEdge, + }) { + return EdgeHandle( + margin: margin, + getEdge: getEdge, + setEdge: setEdge, + onDragStart: _onResizeStart, + onDragEnd: _onResizeEnd, + ); + } + + void _onResizeStart() { + transformController.activity = TransformActivity.resize; + } + + void _onResizeEnd() { + transformController.activity = TransformActivity.none; + _showRegion(); + } + + void _showRegion() { + final boundaries = magnifierController.scaleBoundaries; + if (boundaries == null) return; + + final region = transformation.region; + final nextState = _viewStateForContainedRegion(boundaries, region); + + magnifierController.update( + position: nextState.position, + scale: nextState.scale, + source: ChangeSource.animation, + ); + _setOutline(_containedOutlineFromRegion(nextState, region)); + } + + ViewState _viewStateForContainedRegion(ScaleBoundaries boundaries, CropRegion imageRegion) { + final matrix = transformation.matrix; + final displayRegion = imageRegion.corners.map(matrix.transformOffset).toSet(); + final xMin = displayRegion.map((v) => v.dx).min; + final xMax = displayRegion.map((v) => v.dx).max; + final yMin = displayRegion.map((v) => v.dy).min; + final yMax = displayRegion.map((v) => v.dy).max; + final displayRegionSize = Size(xMax - xMin, yMax - yMin); + + final nextScale = boundaries.clampScale(ScaleLevel.scaleForContained(boundaries.viewportSize, displayRegionSize)); + final nextPosition = boundaries.clampPosition( + position: boundaries.contentToStatePosition(nextScale, imageRegion.center), + scale: nextScale, + ); + return ViewState( + position: nextPosition, + scale: nextScale, + viewportSize: boundaries.viewportSize, + contentSize: boundaries.contentSize, + ); + } + + void _onTransformActivity(TransformActivity activity) { + switch (activity) { + case TransformActivity.none: + _showRegion(); + case TransformActivity.pan: + case TransformActivity.resize: + _gridDivisionNotifier.value = panResizeGridDivision; + case TransformActivity.straighten: + _gridDivisionNotifier.value = straightenGridDivision; + } + if (activity == TransformActivity.none) { + _gridAnimationController.reverse(); + } else { + _gridAnimationController.forward(); + } + } + + void _onOrientationChanged(TransformOrientation orientation) { + _showRegion(); + } + + void _onStraightenDegreesChanged(double degrees) { + _updateCropRegion(); + } + + void _onCropAspectRatioChanged() { + final viewState = _getViewState(); + if (viewState == null) return; + + var targetOutline = _applyCropRatioToOutline(_outlineNotifier.value, _RatioStrategy.keepArea); + if (!_isOutlineContained(targetOutline)) { + targetOutline = _applyCropRatioToOutline(_outlineNotifier.value, _RatioStrategy.contain); + } + transformController.cropRegion = _regionFromOutline(viewState, targetOutline); + _showRegion(); + } + + void _onViewStateChanged(MagnifierState state) { + switch (transformController.activity) { + case TransformActivity.none: + break; + case TransformActivity.straighten: + case TransformActivity.pan: + final currentOutline = _outlineNotifier.value; + _setOutline(_applyCropRatioToOutline(currentOutline, _RatioStrategy.contain)); + case TransformActivity.resize: + break; + } + } + + void _onViewportSizeChanged(Size viewportSize) { + final boundaries = magnifierController.scaleBoundaries; + if (boundaries != null) { + magnifierController.setScaleBoundaries( + boundaries.copyWith( + padding: _getBoundariesPadding, + ), + ); + } + _showRegion(); + } + + EdgeInsets _getBoundariesPadding(double scale) { + // TODO TLAD handle orientation + if (transformation.orientation != TransformOrientation.normal) { + return const EdgeInsets.all(double.infinity); + } + // TODO TLAD handle straightening + if (transformation.straightenDegrees != 0) { + return const EdgeInsets.all(double.infinity); + } + + final viewState = _getViewState(); + if (viewState != null) { + final viewportSize = viewState.viewportSize; + final contentSize = viewState.contentSize; + if (viewportSize != null && contentSize != null) { + final fullRegion = CropRegion.fromRect(Offset.zero & contentSize); + final fullOutline = _containingOutlineFromRegion(viewState, fullRegion); + final cropOutline = _outlineNotifier.value; + + final paddingWidth = max(0.0, (min(fullOutline.width, viewportSize.width) - cropOutline.width) / 2); + final paddingHeight = max(0.0, (min(fullOutline.height, viewportSize.height) - cropOutline.height) / 2); + return EdgeInsets.symmetric(vertical: paddingHeight, horizontal: paddingWidth); + } + } + + return EdgeInsets.zero; + } + + ViewState? _getViewState() { + final scaleBoundaries = magnifierController.scaleBoundaries; + if (scaleBoundaries == null) return null; + + final state = magnifierController.currentState; + return ViewState( + position: state.position, + scale: state.scale, + viewportSize: scaleBoundaries.viewportSize, + contentSize: scaleBoundaries.contentSize, + ); + } + + void _setOutline(Rect targetOutline) { + final viewState = _getViewState(); + final viewportSize = viewState?.viewportSize; + if (targetOutline.isEmpty || viewState == null || viewportSize == null) return; + + // ensure outline is within content + var targetRegion = _regionFromOutline(viewState, targetOutline); + var newOutline = _containedOutlineFromRegion(viewState, targetRegion); + final outlineWidthDelta = targetOutline.width - newOutline.width; + final outlineHeightDelta = targetOutline.height - newOutline.height; + if (outlineWidthDelta > precisionErrorTolerance || outlineHeightDelta > precisionErrorTolerance) { + // keep outline area if possible, otherwise trim + final regionToOutlineMatrix = _getRegionToOutlineMatrix(viewState); + final rect = Offset.zero & viewState.contentSize!; + final edgeRegionCorners = targetRegion.corners.where((v) => v.dx == rect.left || v.dx == rect.right || v.dy == rect.top || v.dy == rect.bottom).toSet(); + final edgeOutlineCorners = edgeRegionCorners.map(regionToOutlineMatrix.transformOffset).toSet(); + if (edgeOutlineCorners.isNotEmpty) { + final direction = edgeOutlineCorners.map((v) => newOutline.center - v).reduce((prev, v) => prev + v); + final movedOutline = targetOutline.shift(Offset( + outlineWidthDelta * direction.dx.sign, + outlineHeightDelta * direction.dy.sign, + )); + targetRegion = _regionFromOutline(viewState, movedOutline); + newOutline = _containedOutlineFromRegion(viewState, targetRegion); + } + } + + // ensure outline is large enough to be handled + newOutline = Rect.fromLTWH( + newOutline.left, + newOutline.top, + max(newOutline.width, minDimension), + max(newOutline.height, minDimension), + ); + + _outlineNotifier.value = newOutline; + switch (transformController.activity) { + case TransformActivity.pan: + case TransformActivity.resize: + _updateCropRegion(); + break; + case TransformActivity.none: + case TransformActivity.straighten: + break; + } + } + + void _updateCropRegion() { + final viewState = _getViewState(); + final outline = _outlineNotifier.value; + if (viewState != null && !outline.isEmpty) { + transformController.cropRegion = _regionFromOutline(viewState, outline); + } + } + + Matrix4 _getRegionToOutlineMatrix(ViewState viewState) { + final magnifierMatrix = viewState.matrix; + + final viewportCenter = viewState.viewportSize!.center(Offset.zero); + final transformOrigin = Matrix4.inverted(magnifierMatrix).transformOffset(viewportCenter); + final transformMatrix = Matrix4.identity() + ..translate(transformOrigin.dx, transformOrigin.dy) + ..multiply(transformation.matrix) + ..translate(-transformOrigin.dx, -transformOrigin.dy); + + return magnifierMatrix..multiply(transformMatrix); + } + + CropRegion _regionFromOutline(ViewState viewState, Rect outline) { + final regionToOutlineMatrix = _getRegionToOutlineMatrix(viewState); + final outlineToRegionMatrix = regionToOutlineMatrix..invert(); + + final rect = Offset.zero & viewState.contentSize!; + double clampX(double dx) => dx.clamp(rect.left, rect.right); + double clampY(double dy) => dy.clamp(rect.top, rect.bottom); + Offset clampPoint(Offset v) => Offset(clampX(v.dx), clampY(v.dy)); + Offset transform(Offset v) => clampPoint(outlineToRegionMatrix.transformOffset(v)); + final clampedRegion = CropRegion( + topLeft: transform(outline.topLeft), + topRight: transform(outline.topRight), + bottomRight: transform(outline.bottomRight), + bottomLeft: transform(outline.bottomLeft), + ); + return clampedRegion; + } + + Rect _containingOutlineFromRegion(ViewState viewState, CropRegion region) { + final regionToOutlineMatrix = _getRegionToOutlineMatrix(viewState); + final points = region.corners.map(regionToOutlineMatrix.transformOffset).toList(); + final dxSet = points.map((v) => v.dx).toSet(); + final dySet = points.map((v) => v.dy).toSet(); + final topLeft = Offset(dxSet.reduce(min), dySet.reduce(min)); + final bottomRight = Offset(dxSet.reduce(max), dySet.reduce(max)); + return Rect.fromPoints(topLeft, bottomRight); + } + + Rect _containedOutlineFromRegion(ViewState viewState, CropRegion region) { + final regionToOutlineMatrix = _getRegionToOutlineMatrix(viewState); + final points = region.corners.map(regionToOutlineMatrix.transformOffset).toList(); + final sortedX = points.map((v) => v.dx).toList()..sort(); + final sortedY = points.map((v) => v.dy).toList()..sort(); + final topLeft = Offset(sortedX[1], sortedY[1]); + final bottomRight = Offset(sortedX[2], sortedY[2]); + return Rect.fromPoints(topLeft, bottomRight); + } + + Rect _applyCropRatioToOutline(Rect outline, _RatioStrategy strategy) { + final currentState = _getViewState(); + final boundaries = magnifierController.scaleBoundaries; + if (currentState == null || boundaries == null) return outline; + + final contentSize = boundaries.contentSize; + + late int longCoef; + late int shortCoef; + switch (cropAspectRatio) { + case CropAspectRatio.free: + return outline; + case CropAspectRatio.original: + longCoef = contentSize.longestSide.round(); + shortCoef = contentSize.shortestSide.round(); + case CropAspectRatio.square: + longCoef = 1; + shortCoef = 1; + case CropAspectRatio.ar_16_9: + longCoef = 16; + shortCoef = 9; + case CropAspectRatio.ar_4_3: + longCoef = 4; + shortCoef = 3; + } + + final contentRect = Offset.zero & contentSize; + final isLandscape = (outline.width - outline.height).abs() > precisionErrorTolerance ? outline.width > outline.height : contentSize.width > contentSize.height; + final newRatio = isLandscape ? longCoef / shortCoef : shortCoef / longCoef; + + Size sizeToKeepArea() { + final f = (outline.longestSide + outline.shortestSide) / (longCoef + shortCoef); + final newLongest = f * longCoef; + final newShortest = f * shortCoef; + return isLandscape ? Size(newLongest, newShortest) : Size(newShortest, newLongest); + } + + final regionToOutlineMatrix = _getRegionToOutlineMatrix(currentState); + final outlineToRegionMatrix = Matrix4.inverted(regionToOutlineMatrix); + + Rect pinnedRect(Rect Function(Size targetSize) forSize) { + final targetSize = sizeToKeepArea(); + final rect = forSize(targetSize); + + // do not try to coerce outline handled outside tilted image + if (transformation.straightenDegrees != 0) return rect; + + final regionCorners = { + rect.topLeft, + rect.topRight, + rect.bottomRight, + rect.bottomLeft, + }.map(outlineToRegionMatrix.transformOffset).toSet(); + + if (regionCorners.every((v) => contentRect.containsIncludingBottomRight(v, tolerance: precisionErrorTolerance))) return rect; + + final clampedOutlineCorners = regionCorners.map((v) => regionToOutlineMatrix.transformOffset(Offset(v.dx.clamp(0, contentSize.width), v.dy.clamp(0, contentSize.height)))).toSet(); + final minX = clampedOutlineCorners.map((v) => v.dx).min; + final maxX = clampedOutlineCorners.map((v) => v.dx).max; + final minY = clampedOutlineCorners.map((v) => v.dy).min; + final maxY = clampedOutlineCorners.map((v) => v.dy).max; + + var width = rect.width; + var height = rect.height; + if (rect.left < minX - precisionErrorTolerance) { + width = rect.right - minX; + height = width / newRatio; + } else if (rect.top < minY - precisionErrorTolerance) { + height = rect.bottom - minY; + width = height * newRatio; + } else if (rect.right > maxX + precisionErrorTolerance) { + width = maxX - rect.left; + height = width / newRatio; + } else if (rect.bottom > maxY + precisionErrorTolerance) { + height = maxY - rect.top; + width = height * newRatio; + } + final clampedSize = Size(width, height); + return clampedSize < targetSize ? forSize(clampedSize) : rect; + } + + switch (strategy) { + case _RatioStrategy.keepArea: + final targetSize = sizeToKeepArea(); + return Rect.fromCenter( + center: outline.center, + width: targetSize.width, + height: targetSize.height, + ); + case _RatioStrategy.contain: + final currentRatio = outline.width / outline.height; + if ((newRatio - currentRatio).abs() < precisionErrorTolerance) { + return outline; + } else { + late final Size targetSize; + if (newRatio > currentRatio) { + targetSize = Size(outline.width, outline.width / newRatio); + } else { + targetSize = Size(outline.height * newRatio, outline.height); + } + return Rect.fromCenter( + center: outline.center, + width: targetSize.width, + height: targetSize.height, + ); + } + case _RatioStrategy.pinTopLeft: + return pinnedRect((targetSize) => Rect.fromPoints( + outline.topLeft, + outline.topLeft.translate(targetSize.width, targetSize.height), + )); + case _RatioStrategy.pinTopRight: + return pinnedRect((targetSize) => Rect.fromPoints( + outline.topRight, + outline.topRight.translate(-targetSize.width, targetSize.height), + )); + case _RatioStrategy.pinBottomRight: + return pinnedRect((targetSize) => Rect.fromPoints( + outline.bottomRight, + outline.bottomRight.translate(-targetSize.width, -targetSize.height), + )); + case _RatioStrategy.pinBottomLeft: + return pinnedRect((targetSize) => Rect.fromPoints( + outline.bottomLeft, + outline.bottomLeft.translate(targetSize.width, -targetSize.height), + )); + case _RatioStrategy.pinLeft: + return pinnedRect((targetSize) => Rect.fromLTRB( + outline.left, + outline.center.dy - targetSize.height / 2, + outline.left + targetSize.width, + outline.center.dy + targetSize.height / 2, + )); + case _RatioStrategy.pinTop: + return pinnedRect((targetSize) => Rect.fromLTRB( + outline.center.dx - targetSize.width / 2, + outline.top, + outline.center.dx + targetSize.width / 2, + outline.top + targetSize.height, + )); + case _RatioStrategy.pinRight: + return pinnedRect((targetSize) => Rect.fromLTRB( + outline.right - targetSize.width, + outline.center.dy - targetSize.height / 2, + outline.right, + outline.center.dy + targetSize.height / 2, + )); + case _RatioStrategy.pinBottom: + return pinnedRect((targetSize) => Rect.fromLTRB( + outline.center.dx - targetSize.width / 2, + outline.bottom - targetSize.height, + outline.center.dx + targetSize.width / 2, + outline.bottom, + )); + } + } +} + +enum _RatioStrategy { keepArea, contain, pinTopLeft, pinTopRight, pinBottomRight, pinBottomLeft, pinLeft, pinTop, pinRight, pinBottom } diff --git a/lib/widgets/editor/transform/handles.dart b/lib/widgets/editor/transform/handles.dart new file mode 100644 index 0000000..50884c4 --- /dev/null +++ b/lib/widgets/editor/transform/handles.dart @@ -0,0 +1,120 @@ +import 'package:aves/widgets/editor/transform/cropper.dart'; +import 'package:flutter/material.dart'; + +class VertexHandle extends StatefulWidget { + final EdgeInsets margin; + final ValueGetter<Offset> getPosition; + final ValueSetter<Offset> setPosition; + final VoidCallback onDragStart, onDragEnd; + + const VertexHandle({ + super.key, + required this.margin, + required this.getPosition, + required this.setPosition, + required this.onDragStart, + required this.onDragEnd, + }); + + @override + State<VertexHandle> createState() => _VertexHandleState(); +} + +class _VertexHandleState extends State<VertexHandle> { + Offset _start = Offset.zero; + Offset _totalDelta = Offset.zero; + + static const double _handleDim = Cropper.handleDimension; + + EdgeInsets get margin => widget.margin; + + @override + Widget build(BuildContext context) { + return Positioned.fromRect( + rect: Rect.fromCenter( + center: widget.getPosition().translate(margin.left, margin.right), + width: _handleDim, + height: _handleDim, + ), + child: GestureDetector( + onPanStart: (details) { + _totalDelta = Offset.zero; + _start = widget.getPosition(); + widget.onDragStart(); + }, + onPanUpdate: (details) { + _totalDelta += details.delta; + widget.setPosition(_start + _totalDelta); + }, + onPanEnd: (details) { + widget.onDragEnd(); + }, + child: const ColoredBox( + color: Colors.transparent, + ), + ), + ); + } +} + +class EdgeHandle extends StatefulWidget { + final EdgeInsets margin; + final ValueGetter<Rect> getEdge; + final ValueSetter<Rect> setEdge; + final VoidCallback onDragStart, onDragEnd; + + const EdgeHandle({ + super.key, + required this.margin, + required this.getEdge, + required this.setEdge, + required this.onDragStart, + required this.onDragEnd, + }); + + @override + State<EdgeHandle> createState() => _EdgeHandleState(); +} + +class _EdgeHandleState extends State<EdgeHandle> { + Rect _start = Rect.zero; + Offset _totalDelta = Offset.zero; + + static const double _handleDim = Cropper.handleDimension; + + EdgeInsets get margin => widget.margin; + + @override + Widget build(BuildContext context) { + var edge = widget.getEdge(); + if (edge.width > _handleDim && edge.height == 0) { + // horizontal edge + edge = Rect.fromLTWH(edge.left + _handleDim / 2, edge.top - _handleDim / 2, edge.width - _handleDim, _handleDim); + } else if (edge.height > _handleDim && edge.width == 0) { + // vertical edge + edge = Rect.fromLTWH(edge.left - _handleDim / 2, edge.top + _handleDim / 2, _handleDim, edge.height - _handleDim); + } + edge = edge.translate(margin.left, margin.right); + + return Positioned.fromRect( + rect: edge, + child: GestureDetector( + onPanStart: (details) { + _totalDelta = Offset.zero; + _start = widget.getEdge(); + widget.onDragStart(); + }, + onPanUpdate: (details) { + _totalDelta += details.delta; + widget.setEdge(Rect.fromLTWH(_start.left + _totalDelta.dx, _start.top + _totalDelta.dy, _start.width, _start.height)); + }, + onPanEnd: (details) { + widget.onDragEnd(); + }, + child: const ColoredBox( + color: Colors.transparent, + ), + ), + ); + } +} diff --git a/lib/widgets/editor/transform/painter.dart b/lib/widgets/editor/transform/painter.dart new file mode 100644 index 0000000..bbc6e2d --- /dev/null +++ b/lib/widgets/editor/transform/painter.dart @@ -0,0 +1,131 @@ +import 'dart:ui'; + +import 'package:flutter/material.dart'; + +class CropperPainter extends CustomPainter { + final Rect rect; + final double gridOpacity; + final int gridDivision; + + const CropperPainter({ + required this.rect, + required this.gridOpacity, + required this.gridDivision, + }); + + static const double handleLength = kMinInteractiveDimension / 3 - 4; + static const double handleWidth = 3; + static const double borderWidth = 1; + static const double gridWidth = 1; + + static const cornerColor = Colors.white; + static final borderColor = Colors.white.withValues(alpha: .5); + static final gridColor = Colors.white.withValues(alpha: .5); + + @override + void paint(Canvas canvas, Size size) { + final cornerPaint = Paint() + ..style = PaintingStyle.fill + ..strokeCap = StrokeCap.round + ..strokeWidth = handleWidth + ..color = cornerColor; + final gridPaint = Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = gridWidth + ..color = gridColor.withValues(alpha: gridColor.a * gridOpacity); + + final xLeft = rect.left; + final yTop = rect.top; + final xRight = rect.right; + final yBottom = rect.bottom; + + final gridLeft = xLeft + borderWidth / 2; + final gridRight = xRight - borderWidth / 2; + final yStep = (yBottom - yTop) / gridDivision; + for (var i = 1; i < gridDivision; i++) { + canvas.drawLine( + Offset(gridLeft, yTop + i * yStep), + Offset(gridRight, yTop + i * yStep), + gridPaint, + ); + } + final gridTop = yTop + borderWidth / 2; + final gridBottom = yBottom - borderWidth / 2; + final xStep = (xRight - xLeft) / gridDivision; + for (var i = 1; i < gridDivision; i++) { + canvas.drawLine( + Offset(xLeft + i * xStep, gridTop), + Offset(xLeft + i * xStep, gridBottom), + gridPaint, + ); + } + + canvas.drawPoints( + PointMode.polygon, + [ + rect.topLeft.translate(0, handleLength), + rect.topLeft, + rect.topLeft.translate(handleLength, 0), + ], + cornerPaint); + + canvas.drawPoints( + PointMode.polygon, + [ + rect.topRight.translate(-handleLength, 0), + rect.topRight, + rect.topRight.translate(0, handleLength), + ], + cornerPaint); + + canvas.drawPoints( + PointMode.polygon, + [ + rect.bottomRight.translate(0, -handleLength), + rect.bottomRight, + rect.bottomRight.translate(-handleLength, 0), + ], + cornerPaint); + + canvas.drawPoints( + PointMode.polygon, + [ + rect.bottomLeft.translate(handleLength, 0), + rect.bottomLeft, + rect.bottomLeft.translate(0, -handleLength), + ], + cornerPaint); + } + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => true; +} + +class ScrimPainter extends CustomPainter { + final Path excludePath; + final double opacity; + + const ScrimPainter({ + required this.excludePath, + required this.opacity, + }); + + static const double borderWidth = 1; + + static const scrimColor = Colors.black; + + @override + void paint(Canvas canvas, Size size) { + final scrimPaint = Paint() + ..style = PaintingStyle.fill + ..color = scrimColor.withValues(alpha: opacity); + + final outside = Path() + ..addRect(Rect.fromLTWH(0, 0, size.width, size.height).inflate(.5)) + ..close(); + canvas.drawPath(Path.combine(PathOperation.difference, outside, excludePath), scrimPaint); + } + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => true; +} diff --git a/lib/widgets/editor/transform/transformation.dart b/lib/widgets/editor/transform/transformation.dart new file mode 100644 index 0000000..10d732a --- /dev/null +++ b/lib/widgets/editor/transform/transformation.dart @@ -0,0 +1,71 @@ +import 'dart:math' as math; + +import 'package:aves/widgets/editor/transform/crop_region.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:equatable/equatable.dart'; +import 'package:flutter/foundation.dart'; +import 'package:latlong2/latlong.dart'; +import 'package:vector_math/vector_math_64.dart'; + +@immutable +class Transformation extends Equatable { + final TransformOrientation orientation; + final double straightenDegrees; + final CropRegion region; + + @override + List<Object?> get props => [orientation, straightenDegrees, region]; + + static const zero = Transformation( + orientation: TransformOrientation.normal, + straightenDegrees: 0, + region: CropRegion.zero, + ); + + const Transformation({ + required this.orientation, + required this.straightenDegrees, + required this.region, + }); + + Transformation copyWith({ + TransformOrientation? orientation, + double? straightenDegrees, + CropRegion? region, + }) { + return Transformation( + orientation: orientation ?? this.orientation, + straightenDegrees: straightenDegrees ?? this.straightenDegrees, + region: region ?? this.region, + ); + } + + Matrix4 get matrix => _orientationMatrix..multiply(_straightenMatrix); + + Matrix4 get _orientationMatrix { + final matrix = Matrix4.identity(); + switch (orientation) { + case TransformOrientation.normal: + break; + case TransformOrientation.rotate90: + matrix.rotateZ(math.pi / 2); + case TransformOrientation.rotate180: + matrix.rotateZ(math.pi); + case TransformOrientation.rotate270: + matrix.rotateZ(3 * math.pi / 2); + case TransformOrientation.transverse: + matrix.scale(-1.0, 1.0, 1.0); + matrix.rotateZ(-3 * math.pi / 2); + case TransformOrientation.flipVertical: + matrix.scale(1.0, -1.0, 1.0); + case TransformOrientation.transpose: + matrix.scale(-1.0, 1.0, 1.0); + matrix.rotateZ(-1 * math.pi / 2); + case TransformOrientation.flipHorizontal: + matrix.scale(-1.0, 1.0, 1.0); + } + return matrix; + } + + Matrix4 get _straightenMatrix => Matrix4.rotationZ(degToRadian((orientation.isFlipped ? -1 : 1) * straightenDegrees)); +} diff --git a/lib/widgets/explorer/app_bar.dart b/lib/widgets/explorer/app_bar.dart new file mode 100644 index 0000000..c0da008 --- /dev/null +++ b/lib/widgets/explorer/app_bar.dart @@ -0,0 +1,209 @@ +import 'dart:async'; + +import 'package:aves/app_mode.dart'; +import 'package:aves/model/settings/enums/accessibility_animations.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/utils/android_file_utils.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/app_bar/app_bar_subtitle.dart'; +import 'package:aves/widgets/common/app_bar/app_bar_title.dart'; +import 'package:aves/widgets/common/app_bar/crumb_line.dart'; +import 'package:aves/widgets/common/basic/font_size_icon_theme.dart'; +import 'package:aves/widgets/common/basic/popup/menu_row.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/aves_app_bar.dart'; +import 'package:aves/widgets/common/search/route.dart'; +import 'package:aves/widgets/dialogs/select_storage_dialog.dart'; +import 'package:aves/widgets/explorer/crumb_line.dart'; +import 'package:aves/widgets/explorer/explorer_action_delegate.dart'; +import 'package:aves/widgets/search/collection_search_delegate.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:provider/provider.dart'; + +class ExplorerAppBar extends StatefulWidget { + final ValueNotifier<VolumeRelativeDirectory?> directoryNotifier; + final void Function(VolumeRelativeDirectory? dir) goToDir; + + const ExplorerAppBar({ + super.key, + required this.directoryNotifier, + required this.goToDir, + }); + + @override + State<ExplorerAppBar> createState() => _ExplorerAppBarState(); +} + +class _ExplorerAppBarState extends State<ExplorerAppBar> with WidgetsBindingObserver { + Set<StorageVolume> get _volumes => androidFileUtils.storageVolumes; + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addObserver(this); + } + + @override + void dispose() { + WidgetsBinding.instance.removeObserver(this); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return AvesAppBar( + contentHeight: appBarContentHeight, + pinned: true, + leading: const DrawerButton(), + title: _buildAppBarTitle(context), + actions: _buildActions, + bottom: LayoutBuilder( + builder: (context, constraints) { + return Container( + padding: CrumbLine.padding, + width: constraints.maxWidth, + height: CrumbLine.getPreferredHeight(MediaQuery.textScalerOf(context)), + child: ValueListenableBuilder<VolumeRelativeDirectory?>( + valueListenable: widget.directoryNotifier, + builder: (context, directory, child) { + return ExplorerCrumbLine( + key: const Key('crumbs'), + directory: directory, + onTap: widget.goToDir, + ); + }, + ), + ); + }, + ), + ); + } + + InteractiveAppBarTitle _buildAppBarTitle(BuildContext context) { + final appMode = context.watch<ValueNotifier<AppMode>>().value; + Widget title = Text( + context.l10n.explorerPageTitle, + softWrap: false, + overflow: TextOverflow.fade, + maxLines: 1, + ); + if (appMode == AppMode.main) { + title = SourceStateAwareAppBarTitle( + title: title, + source: context.read<CollectionSource>(), + ); + } + return InteractiveAppBarTitle( + onTap: () => _goToSearch(context), + child: title, + ); + } + + List<Widget> _buildActions(BuildContext context, double maxWidth) { + final animations = context.select<Settings, AccessibilityAnimations>((v) => v.accessibilityAnimations); + return [ + IconButton( + icon: const Icon(AIcons.search), + onPressed: () => _goToSearch(context), + tooltip: MaterialLocalizations.of(context).searchFieldLabel, + ), + if (_volumes.length > 1) _buildVolumeSelector(context), + PopupMenuButton<ExplorerAction>( + itemBuilder: (context) { + return [ + ExplorerAction.addShortcut, + ExplorerAction.setHome, + ExplorerAction.hide, + null, + ExplorerAction.stats, + ].map<PopupMenuEntry<ExplorerAction>>((v) { + if (v == null) return const PopupMenuDivider(); + return PopupMenuItem( + value: v, + child: MenuRow(text: v.getText(context), icon: v.getIcon()), + ); + }).toList(); + }, + onSelected: (action) async { + // wait for the popup menu to hide before proceeding with the action + await Future.delayed(animations.popUpAnimationDelay * timeDilation); + final directory = widget.directoryNotifier.value; + if (directory != null) { + ExplorerActionDelegate(directory: directory).onActionSelected(context, action); + } + }, + popUpAnimationStyle: animations.popUpAnimationStyle, + ), + ].map((v) => FontSizeIconTheme(child: v)).toList(); + } + + Widget _buildVolumeSelector(BuildContext context) { + if (_volumes.length == 2) { + return ValueListenableBuilder<VolumeRelativeDirectory?>( + valueListenable: widget.directoryNotifier, + builder: (context, directory, child) { + final currentVolume = directory?.volumePath; + final otherVolume = _volumes.firstWhere((volume) => volume.path != currentVolume); + final icon = otherVolume.isRemovable ? AIcons.storageCard : AIcons.storageMain; + return IconButton( + icon: Icon(icon), + onPressed: () => widget.goToDir(VolumeRelativeDirectory.volume(otherVolume)), + tooltip: otherVolume.getDescription(context), + ); + }, + ); + } else { + return IconButton( + icon: const Icon(AIcons.storageCard), + onPressed: () async { + _volumes.map((v) { + final selected = widget.directoryNotifier.value?.volumePath == v.path; + final icon = v.isRemovable ? AIcons.storageCard : AIcons.storageMain; + return PopupMenuItem( + value: v, + enabled: !selected, + child: MenuRow( + text: v.getDescription(context), + icon: Icon(icon), + ), + ); + }).toList(); + final volumePath = widget.directoryNotifier.value?.volumePath; + final initialVolume = _volumes.firstWhereOrNull((v) => v.path == volumePath); + final volume = await showDialog<StorageVolume?>( + context: context, + builder: (context) => SelectStorageDialog(initialVolume: initialVolume), + routeSettings: const RouteSettings(name: SelectStorageDialog.routeName), + ); + if (volume != null) { + widget.goToDir(VolumeRelativeDirectory.volume(volume)); + } + }, + tooltip: context.l10n.explorerActionSelectStorageVolume, + ); + } + } + + double get appBarContentHeight { + final textScaler = MediaQuery.textScalerOf(context); + return textScaler.scale(kToolbarHeight) + CrumbLine.getPreferredHeight(textScaler); + } + + void _goToSearch(BuildContext context) { + Navigator.maybeOf(context)?.push( + SearchPageRoute( + delegate: CollectionSearchDelegate( + searchFieldLabel: context.l10n.searchCollectionFieldHint, + searchFieldStyle: Themes.searchFieldStyle(context), + source: context.read<CollectionSource>(), + ), + ), + ); + } +} diff --git a/lib/widgets/explorer/crumb_line.dart b/lib/widgets/explorer/crumb_line.dart new file mode 100644 index 0000000..596a626 --- /dev/null +++ b/lib/widgets/explorer/crumb_line.dart @@ -0,0 +1,46 @@ +import 'package:aves/services/common/services.dart'; +import 'package:aves/utils/android_file_utils.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/app_bar/crumb_line.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; + +class ExplorerCrumbLine extends StatelessWidget { + final VolumeRelativeDirectory? directory; + final void Function(VolumeRelativeDirectory? combinedPath) onTap; + + const ExplorerCrumbLine({ + super.key, + required this.directory, + required this.onTap, + }); + + @override + Widget build(BuildContext context) { + return CrumbLine<VolumeRelativeDirectory?>( + split: _split, + combine: _combine, + onTap: onTap, + ); + } + + List<String> _split(BuildContext context) { + final _directory = directory; + if (_directory == null) return []; + return [ + _directory.getVolumeDescription(context), + ...pContext.split(_directory.relativeDir), + ]; + } + + VolumeRelativeDirectory? _combine(BuildContext context, int index) { + final _directory = directory; + if (_directory == null) return null; + + final path = pContext.joinAll([ + _directory.volumePath, + ..._split(context).skip(1).take(index), + ]); + return androidFileUtils.relativeDirectoryFromPath(path); + } +} diff --git a/lib/widgets/explorer/explorer_action_delegate.dart b/lib/widgets/explorer/explorer_action_delegate.dart new file mode 100644 index 0000000..3d8641c --- /dev/null +++ b/lib/widgets/explorer/explorer_action_delegate.dart @@ -0,0 +1,124 @@ +import 'package:aves/app_mode.dart'; +import 'package:aves/model/device.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/filters/path.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/widgets/common/action_mixins/feedback.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/dialogs/add_shortcut_dialog.dart'; +import 'package:aves/widgets/explorer/explorer_page.dart'; +import 'package:aves/widgets/filter_grids/common/action_delegates/chip.dart'; +import 'package:aves/widgets/stats/stats_page.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class ExplorerActionDelegate with FeedbackMixin { + final VolumeRelativeDirectory directory; + + ExplorerActionDelegate({required this.directory}); + + bool isVisible( + ExplorerAction action, { + required AppMode appMode, + }) { + final isMain = appMode == AppMode.main; + final useTvLayout = settings.useTvLayout; + switch (action) { + case ExplorerAction.addShortcut: + return isMain && device.canPinShortcut; + case ExplorerAction.setHome: + return isMain && !useTvLayout; + case ExplorerAction.hide: + case ExplorerAction.stats: + return isMain; + } + } + + bool canApply(ExplorerAction action) { + switch (action) { + case ExplorerAction.addShortcut: + case ExplorerAction.setHome: + case ExplorerAction.hide: + case ExplorerAction.stats: + return true; + } + } + + void onActionSelected(BuildContext context, ExplorerAction action) { + reportService.log('$runtimeType handles $action'); + switch (action) { + case ExplorerAction.addShortcut: + _addShortcut(context); + case ExplorerAction.setHome: + _setHome(context); + case ExplorerAction.hide: + _hide(context); + case ExplorerAction.stats: + _goToStats(context); + } + } + + PathFilter _getPathFilter() => PathFilter(directory.dirPath); + + Future<void> _addShortcut(BuildContext context) async { + final filter = _getPathFilter(); + final defaultName = filter.getLabel(context); + final collection = CollectionLens( + source: context.read<CollectionSource>(), + filters: {filter}, + ); + + final result = await showDialog<(AvesEntry?, String)>( + context: context, + builder: (context) => AddShortcutDialog( + defaultName: defaultName, + collection: collection, + ), + routeSettings: const RouteSettings(name: AddShortcutDialog.routeName), + ); + if (result == null) return; + + final (coverEntry, name) = result; + if (name.isEmpty) return; + + await appService.pinToHomeScreen(name, coverEntry, route: ExplorerPage.routeName, path: filter.path); + if (!device.showPinShortcutFeedback) { + showFeedback(context, FeedbackType.info, context.l10n.genericSuccessFeedback); + } + } + + void _setHome(BuildContext context) async { + settings.setHome(HomePageSetting.explorer, customExplorerPath: directory.dirPath); + showFeedback(context, FeedbackType.info, context.l10n.genericSuccessFeedback); + } + + void _hide(BuildContext context) { + final chipActionDelegate = ChipActionDelegate(); + const action = ChipAction.hide; + final pathFilter = _getPathFilter(); + if (chipActionDelegate.isVisible(action, filter: pathFilter)) { + chipActionDelegate.onActionSelected(context, pathFilter, action); + } + } + + void _goToStats(BuildContext context) { + final collection = CollectionLens( + source: context.read<CollectionSource>(), + filters: {_getPathFilter()}, + ); + + Navigator.maybeOf(context)?.push( + MaterialPageRoute( + settings: const RouteSettings(name: StatsPage.routeName), + builder: (context) => StatsPage( + entries: collection.sortedEntries.toSet(), + source: collection.source, + ), + ), + ); + } +} diff --git a/lib/widgets/explorer/explorer_page.dart b/lib/widgets/explorer/explorer_page.dart new file mode 100644 index 0000000..e03484d --- /dev/null +++ b/lib/widgets/explorer/explorer_page.dart @@ -0,0 +1,297 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:aves/model/filters/covered/stored_album.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/filters/path.dart'; +import 'package:aves/model/source/album.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/utils/android_file_utils.dart'; +import 'package:aves/widgets/collection/collection_page.dart'; +import 'package:aves/widgets/collection/loading.dart'; +import 'package:aves/widgets/common/basic/insets.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/behaviour/pop/double_back.dart'; +import 'package:aves/widgets/common/behaviour/pop/scope.dart'; +import 'package:aves/widgets/common/behaviour/pop/tv_navigation.dart'; +import 'package:aves/widgets/common/identity/aves_filter_chip.dart'; +import 'package:aves/widgets/common/identity/empty.dart'; +import 'package:aves/widgets/explorer/app_bar.dart'; +import 'package:aves/widgets/navigation/drawer/app_drawer.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:flutter_staggered_animations/flutter_staggered_animations.dart'; +import 'package:provider/provider.dart'; + +class ExplorerPage extends StatefulWidget { + static const routeName = '/explorer'; + + final String? path; + + const ExplorerPage({super.key, this.path}); + + @override + State<ExplorerPage> createState() => _ExplorerPageState(); +} + +class _ExplorerPageState extends State<ExplorerPage> { + final Set<StreamSubscription> _subscriptions = {}; + final ValueNotifier<VolumeRelativeDirectory?> _directory = ValueNotifier(null); + final ValueNotifier<VolumeRelativeDirectory?> _contentsDirectory = ValueNotifier(null); + final ValueNotifier<List<Directory>> _contents = ValueNotifier([]); + + Set<StorageVolume> get _volumes => androidFileUtils.storageVolumes; + + String? _pathOf(VolumeRelativeDirectory? dir) => dir != null ? pContext.join(dir.volumePath, dir.relativeDir) : null; + + @override + void initState() { + super.initState(); + final path = widget.path; + if (path != null && androidFileUtils.getStorageVolume(path) != null) { + _goToPath(path); + } else { + final primaryVolume = _volumes.firstWhereOrNull((v) => v.isPrimary); + if (primaryVolume != null) { + _goToPath(primaryVolume.path); + } + } + _contents.addListener(() => PrimaryScrollController.of(context).jumpTo(0)); + WidgetsBinding.instance.addPostFrameCallback((_) { + final source = context.read<CollectionSource>(); + _subscriptions.add(source.eventBus.on<AlbumsChangedEvent>().listen((event) => _updateContents())); + }); + } + + @override + void dispose() { + _subscriptions + ..forEach((sub) => sub.cancel()) + ..clear(); + _directory.dispose(); + _contents.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return ValueListenableBuilder<VolumeRelativeDirectory?>( + valueListenable: _directory, + builder: (context, directory, child) { + final atRoot = directory?.relativeDir.isEmpty ?? true; + final path = _pathOf(directory); + return AvesPopScope( + handlers: [ + APopHandler( + canPop: (context) => atRoot, + onPopBlocked: (context) { + if (path != null) { + _goToPath(pContext.dirname(path)); + } + }, + ), + tvNavigationPopHandler, + doubleBackPopHandler, + ], + child: AvesScaffold( + drawer: AppDrawer(currentExplorerPath: path), + body: GestureAreaProtectorStack( + child: Column( + children: [ + Expanded( + child: ValueListenableBuilder<List<Directory>>( + valueListenable: _contents, + builder: (context, contents, child) { + final durations = context.watch<DurationsData>(); + return CustomScrollView( + // workaround to prevent scrolling the app bar away + // when there is no content and we use `SliverFillRemaining` + physics: contents.isEmpty ? const NeverScrollableScrollPhysics() : null, + slivers: [ + ExplorerAppBar( + key: const Key('appbar'), + directoryNotifier: _directory, + goToDir: _goToDir, + ), + AnimationLimiter( + // animation limiter should not be above the app bar + // so that the crumb line can automatically scroll + key: ValueKey(contents), + child: SliverList.builder( + itemBuilder: (context, index) { + return AnimationConfiguration.staggeredList( + position: index, + duration: durations.staggeredAnimation, + delay: durations.staggeredAnimationDelay * timeDilation, + child: SlideAnimation( + verticalOffset: 50.0, + child: FadeInAnimation( + child: _buildContentLine(context, contents[index]), + ), + ), + ); + }, + itemCount: contents.length, + ), + ), + contents.isEmpty + ? SliverFillRemaining( + hasScrollBody: false, + child: _buildEmptyContent(), + ) + : const SliverPadding(padding: EdgeInsets.only(bottom: 8)), + ], + ); + }, + ), + ), + const Divider(height: 0), + ValueListenableBuilder<VolumeRelativeDirectory?>( + valueListenable: _contentsDirectory, + builder: (context, contentsDirectory, child) { + final dirPath = _pathOf(contentsDirectory); + return dirPath != null + ? SafeArea( + top: false, + bottom: true, + child: Padding( + padding: const EdgeInsets.all(8), + child: AvesFilterChip( + filter: PathFilter(dirPath), + maxWidth: double.infinity, + onTap: (filter) => _goToCollectionPage(context, filter), + onLongPress: null, + ), + ), + ) + : const SizedBox(); + }, + ), + ], + ), + ), + ), + ); + }, + ); + } + + Widget _buildEmptyContent() { + final source = context.read<CollectionSource>(); + return ValueListenableBuilder<SourceState>( + valueListenable: source.stateNotifier, + builder: (context, sourceState, child) { + if (sourceState == SourceState.loading) { + return LoadingEmptyContent(source: source); + } + + Widget? bottom; + final dirPath = _pathOf(_contentsDirectory.value); + if (dirPath != null) { + final album = _getAlbumPath(source, Directory(dirPath)); + if (album != null) { + bottom = AvesFilterChip( + filter: StoredAlbumFilter(album, source.getStoredAlbumDisplayName(context, album)), + maxWidth: double.infinity, + onTap: (filter) => _goToCollectionPage(context, filter), + onLongPress: null, + ); + } + } + + return EmptyContent( + icon: AIcons.folder, + text: '', + bottom: bottom, + ); + }, + ); + } + + String? _getAlbumPath(CollectionSource source, FileSystemEntity content) { + final contentPath = content.path.toLowerCase(); + return source.rawAlbums.firstWhereOrNull((v) => v.toLowerCase() == contentPath); + } + + Widget _buildContentLine(BuildContext context, FileSystemEntity content) { + final source = context.read<CollectionSource>(); + final album = _getAlbumPath(source, content); + final baseIconTheme = IconTheme.of(context); + + const leadingDim = AvesFilterChip.minChipWidth; + return ListTile( + leading: album != null + ? IconTheme.merge( + data: baseIconTheme, + child: AvesFilterChip( + filter: StoredAlbumFilter(album, source.getStoredAlbumDisplayName(context, album)), + showText: false, + maxWidth: leadingDim, + onTap: (filter) => _goToCollectionPage(context, filter), + onLongPress: null, + ), + ) + : const SizedBox( + width: leadingDim, + height: leadingDim, + child: Icon(AIcons.folder), + ), + title: Text('${Unicode.FSI}${pContext.split(content.path).last}${Unicode.PDI}'), + onTap: () => _goToPath(content.path), + ); + } + + void _goToDir(VolumeRelativeDirectory? dir) { + if (dir != null) { + _directory.value = dir; + _updateContents(); + } + } + + void _goToPath(String path) => _goToDir(androidFileUtils.relativeDirectoryFromPath(path)); + + void _updateContents() { + final directory = _directory.value; + final dirPath = _pathOf(directory); + if (dirPath == null) return; + + final contents = <Directory>[]; + final source = context.read<CollectionSource>(); + final albums = source.rawAlbums.map((v) => v.toLowerCase()).toSet(); + Directory(dirPath).list().listen((event) { + final entity = event.absolute; + if (entity is Directory) { + final dirPath = entity.path.toLowerCase(); + if (albums.any((v) => v.startsWith(dirPath))) { + contents.add(entity); + } + } + }, onDone: () { + _contents.value = contents + ..sort((a, b) { + final nameA = pContext.split(a.path).last; + final nameB = pContext.split(b.path).last; + return compareAsciiUpperCaseNatural(nameA, nameB); + }); + _contentsDirectory.value = directory; + }); + } + + void _goToCollectionPage(BuildContext context, CollectionFilter filter) { + Navigator.maybeOf(context)?.push( + MaterialPageRoute( + settings: const RouteSettings(name: CollectionPage.routeName), + builder: (context) => CollectionPage( + source: context.read<CollectionSource>(), + filters: {filter}, + ), + ), + ); + } +} diff --git a/lib/widgets/filter_grids/albums_page.dart b/lib/widgets/filter_grids/albums_page.dart new file mode 100644 index 0000000..5d86969 --- /dev/null +++ b/lib/widgets/filter_grids/albums_page.dart @@ -0,0 +1,250 @@ +import 'package:aves/model/app_inventory.dart'; +import 'package:aves/model/covers.dart'; +import 'package:aves/model/dynamic_albums.dart'; +import 'package:aves/model/entry/extensions/props.dart'; +import 'package:aves/model/filters/container/album_group.dart'; +import 'package:aves/model/filters/container/dynamic_album.dart'; +import 'package:aves/model/filters/covered/stored_album.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/grouping/common.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/album.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/empty.dart'; +import 'package:aves/widgets/common/providers/filter_group_provider.dart'; +import 'package:aves/widgets/filter_grids/common/action_delegates/album_set.dart'; +import 'package:aves/widgets/filter_grids/common/enums.dart'; +import 'package:aves/widgets/filter_grids/common/filter_nav_page.dart'; +import 'package:aves/widgets/filter_grids/common/section_keys.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class AlbumListPage extends StatelessWidget { + static const routeName = '/albums'; + + final Uri? initialGroup; + + const AlbumListPage({ + super.key, + required this.initialGroup, + }); + + @override + Widget build(BuildContext context) { + return MultiProvider( + providers: [ + ChangeNotifierProvider<FilterGrouping>.value(value: albumGrouping), + FilterGroupProvider(initialValue: initialGroup), + ], + child: Builder( + // to access filter group provider from subtree context + builder: (context) { + final source = context.read<CollectionSource>(); + return Selector<Settings, (AlbumChipSectionFactor, ChipSortFactor, bool, Set<CollectionFilter>, Set<CollectionFilter>)>( + selector: (context, s) => (s.albumSectionFactor, s.albumSortFactor, s.albumSortReverse, s.hiddenFilters, s.pinnedFilters), + shouldRebuild: (t1, t2) { + // `Selector` by default uses `DeepCollectionEquality`, which does not go deep in collections within records + const eq = DeepCollectionEquality(); + return !(eq.equals(t1.$1, t2.$1) && eq.equals(t1.$2, t2.$2) && eq.equals(t1.$3, t2.$3) && eq.equals(t1.$4, t2.$4) && eq.equals(t1.$5, t2.$5)); + }, + builder: (context, s, child) { + return ValueListenableBuilder<bool>( + valueListenable: appInventory.areAppNamesReadyNotifier, + builder: (context, areAppNamesReady, child) { + return AnimatedBuilder( + animation: Listenable.merge({albumGrouping, dynamicAlbums}), + builder: (context, child) => StreamBuilder( + stream: source.eventBus.on<AlbumsChangedEvent>(), + builder: (context, snapshot) { + final groupUri = context.watch<FilterGroupNotifier>().value; + final gridItems = getGridItems(context, source, AlbumChipType.values, groupUri); + return StreamBuilder<Set<CollectionFilter>?>( + // to update sections by tier + stream: covers.packageChangeStream, + builder: (context, snapshot) => FilterNavigationPage<AlbumBaseFilter, AlbumChipSetActionDelegate>( + source: source, + title: context.l10n.albumPageTitle, + sortFactor: settings.albumSortFactor, + showHeaders: settings.albumSectionFactor != AlbumChipSectionFactor.none, + actionDelegate: AlbumChipSetActionDelegate(gridItems), + filterSections: groupToSections(context, source, gridItems), + newFilters: source.getNewAlbumFilters(context), + emptyBuilder: () => EmptyContent( + icon: AIcons.album, + text: context.l10n.albumEmpty, + ), + ), + ); + }, + ), + ); + }, + ); + }, + ); + }, + ), + ); + } + + // common with picking page + + static List<FilterGridItem<AlbumBaseFilter>> getGridItems( + BuildContext context, + CollectionSource source, + Iterable<AlbumChipType> albumChipTypes, + Uri? groupUri, + ) { + final groupContent = albumGrouping.getDirectChildren(groupUri); + + Set<T> whereTypeRecursively<T>(Set<CollectionFilter> filters) { + return { + ...filters.whereType<T>(), + ...filters.whereType<AlbumGroupFilter>().expand((v) => whereTypeRecursively<T>(v.filter.innerFilters)), + }; + } + + // show hidden filters when they are pinned + final pinned = settings.pinnedFilters.whereType<AlbumBaseFilter>(); + final hidden = settings.hiddenFilters.whereNot(pinned.contains).toSet(); + + final listedStoredAlbumPaths = <String>{}; + if (albumChipTypes.contains(AlbumChipType.stored)) { + final allAlbums = source.rawAlbums; + if (groupUri == null) { + final withinGroups = whereTypeRecursively<StoredAlbumFilter>(groupContent).map((v) => v.album).toSet(); + listedStoredAlbumPaths.addAll(allAlbums.whereNot(withinGroups.contains)); + } else { + // check that group content is listed from source, to prevent displaying hidden content + listedStoredAlbumPaths.addAll(groupContent.whereType<StoredAlbumFilter>().map((v) => v.album).where(allAlbums.contains)); + } + } + final listedStoredAlbums = listedStoredAlbumPaths.map((album) => StoredAlbumFilter(album, source.getStoredAlbumDisplayName(context, album))).whereNot(hidden.contains).toSet(); + + final listedDynamicAlbums = <DynamicAlbumFilter>{}; + if (albumChipTypes.contains(AlbumChipType.dynamic)) { + final allDynamicAlbums = dynamicAlbums.all.whereNot(hidden.contains).toSet(); + if (groupUri == null) { + final withinGroups = whereTypeRecursively<DynamicAlbumFilter>(groupContent).toSet(); + listedDynamicAlbums.addAll(allDynamicAlbums.whereNot(withinGroups.contains)); + } else { + // check that group content is listed from source, to prevent displaying hidden content + listedDynamicAlbums.addAll(groupContent.whereType<DynamicAlbumFilter>().where(allDynamicAlbums.contains)); + } + } + + // always show groups, which are needed to navigate to other types + final albumGroupFilters = groupContent.whereType<AlbumGroupFilter>().whereNot(hidden.contains).toSet(); + + final filters = <AlbumBaseFilter>{ + ...albumGroupFilters, + ...listedStoredAlbums, + ...listedDynamicAlbums, + }; + + return FilterNavigationPage.sort(settings.albumSortFactor, settings.albumSortReverse, source, filters); + } + + static Map<ChipSectionKey, List<FilterGridItem<AlbumBaseFilter>>> groupToSections(BuildContext context, CollectionSource source, Iterable<FilterGridItem<AlbumBaseFilter>> sortedMapEntries) { + final newFilters = source.getNewAlbumFilters(context); + final pinned = settings.pinnedFilters.whereType<AlbumBaseFilter>(); + + final List<FilterGridItem<AlbumBaseFilter>> newMapEntries = [], pinnedMapEntries = [], unpinnedMapEntries = []; + for (final item in sortedMapEntries) { + final filter = item.filter; + if (newFilters.contains(filter)) { + newMapEntries.add(item); + } else if (pinned.contains(filter)) { + pinnedMapEntries.add(item); + } else { + unpinnedMapEntries.add(item); + } + } + + var sections = <ChipSectionKey, List<FilterGridItem<AlbumBaseFilter>>>{}; + switch (settings.albumSectionFactor) { + case AlbumChipSectionFactor.importance: + final groupKey = AlbumImportanceSectionKey.group(context); + final specialKey = AlbumImportanceSectionKey.special(context); + final appsKey = AlbumImportanceSectionKey.apps(context); + final vaultKey = AlbumImportanceSectionKey.vault(context); + final regularKey = AlbumImportanceSectionKey.regular(context); + final dynamicKey = AlbumImportanceSectionKey.dynamic(context); + sections = groupBy<FilterGridItem<AlbumBaseFilter>, ChipSectionKey>(unpinnedMapEntries, (kv) { + final filter = kv.filter; + switch (filter) { + case StoredAlbumFilter _: + switch (covers.effectiveAlbumType(filter.album)) { + case AlbumType.regular: + return regularKey; + case AlbumType.app: + return appsKey; + case AlbumType.vault: + return vaultKey; + default: + return specialKey; + } + case DynamicAlbumFilter _: + return dynamicKey; + case AlbumGroupFilter _: + return groupKey; + } + return specialKey; + }); + + sections = { + // group ordering + if (sections.containsKey(groupKey)) groupKey: sections[groupKey]!, + if (sections.containsKey(specialKey)) specialKey: sections[specialKey]!, + if (sections.containsKey(appsKey)) appsKey: sections[appsKey]!, + if (sections.containsKey(vaultKey)) vaultKey: sections[vaultKey]!, + if (sections.containsKey(dynamicKey)) dynamicKey: sections[dynamicKey]!, + if (sections.containsKey(regularKey)) regularKey: sections[regularKey]!, + }; + case AlbumChipSectionFactor.mimeType: + final visibleEntries = source.visibleEntries; + sections = groupBy<FilterGridItem<AlbumBaseFilter>, ChipSectionKey>(unpinnedMapEntries, (kv) { + final matches = visibleEntries.where(kv.filter.test); + final hasImage = matches.any((v) => v.isImage); + final hasVideo = matches.any((v) => v.isVideo); + if (hasImage && !hasVideo) return MimeTypeSectionKey.images(context); + if (!hasImage && hasVideo) return MimeTypeSectionKey.videos(context); + return MimeTypeSectionKey.mixed(context); + }); + case AlbumChipSectionFactor.volume: + sections = groupBy<FilterGridItem<AlbumBaseFilter>, ChipSectionKey>(unpinnedMapEntries, (kv) { + final filter = kv.filter; + return StorageVolumeSectionKey(context, filter is StoredAlbumFilter ? filter.storageVolume : null); + }); + case AlbumChipSectionFactor.none: + return { + if (sortedMapEntries.isNotEmpty) + const ChipSectionKey(): [ + ...newMapEntries, + ...pinnedMapEntries, + ...unpinnedMapEntries, + ], + }; + } + + if (pinnedMapEntries.isNotEmpty) { + sections = Map.fromEntries([ + MapEntry(AlbumImportanceSectionKey.pinned(context), pinnedMapEntries), + ...sections.entries, + ]); + } + + if (newMapEntries.isNotEmpty) { + sections = Map.fromEntries([ + MapEntry(AlbumImportanceSectionKey.newAlbum(context), newMapEntries), + ...sections.entries, + ]); + } + + return sections; + } +} diff --git a/lib/widgets/filter_grids/common/action_delegates/album_set.dart b/lib/widgets/filter_grids/common/action_delegates/album_set.dart new file mode 100644 index 0000000..32a03a0 --- /dev/null +++ b/lib/widgets/filter_grids/common/action_delegates/album_set.dart @@ -0,0 +1,627 @@ +import 'dart:collection'; +import 'dart:io'; + +import 'package:aves/app_mode.dart'; +import 'package:aves/model/covers.dart'; +import 'package:aves/model/dynamic_albums.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/filters/container/album_group.dart'; +import 'package:aves/model/filters/container/dynamic_album.dart'; +import 'package:aves/model/filters/covered/stored_album.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/grouping/common.dart'; +import 'package:aves/model/grouping/convert.dart'; +import 'package:aves/model/highlight.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/model/vaults/details.dart'; +import 'package:aves/model/vaults/vaults.dart'; +import 'package:aves/services/common/image_op_events.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/services/media/enums.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/utils/android_file_utils.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/action_mixins/entry_storage.dart'; +import 'package:aves/widgets/common/action_mixins/feedback.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/providers/filter_group_provider.dart'; +import 'package:aves/widgets/common/tile_extent_controller.dart'; +import 'package:aves/widgets/dialogs/aves_confirmation_dialog.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:aves/widgets/dialogs/filter_editors/create_stored_album_dialog.dart'; +import 'package:aves/widgets/dialogs/filter_editors/edit_vault_dialog.dart'; +import 'package:aves/widgets/dialogs/filter_editors/rename_dynamic_album_dialog.dart'; +import 'package:aves/widgets/dialogs/filter_editors/rename_group_dialog.dart'; +import 'package:aves/widgets/dialogs/filter_editors/rename_stored_album_dialog.dart'; +import 'package:aves/widgets/dialogs/pick_dialogs/album_pick_page.dart'; +import 'package:aves/widgets/dialogs/tile_view_dialog.dart'; +import 'package:aves/widgets/filter_grids/albums_page.dart'; +import 'package:aves/widgets/filter_grids/common/action_delegates/chip_set.dart'; +import 'package:aves/widgets/filter_grids/common/enums.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:provider/provider.dart'; + +class AlbumChipSetActionDelegate extends ChipSetActionDelegate<AlbumBaseFilter> with EntryStorageMixin { + final Iterable<FilterGridItem<AlbumBaseFilter>> _items; + + AlbumChipSetActionDelegate(Iterable<FilterGridItem<AlbumBaseFilter>> items) : _items = items; + + @override + Iterable<FilterGridItem<AlbumBaseFilter>> get allItems => _items; + + @override + ChipSortFactor get sortFactor => settings.albumSortFactor; + + @override + set sortFactor(ChipSortFactor factor) => settings.albumSortFactor = factor; + + @override + bool get sortReverse => settings.albumSortReverse; + + @override + set sortReverse(bool value) => settings.albumSortReverse = value; + + @override + TileLayout get tileLayout => settings.getTileLayout(AlbumListPage.routeName); + + @override + set tileLayout(TileLayout tileLayout) => settings.setTileLayout(AlbumListPage.routeName, tileLayout); + + static const _sectionOptions = [ + AlbumChipSectionFactor.importance, + AlbumChipSectionFactor.mimeType, + AlbumChipSectionFactor.volume, + AlbumChipSectionFactor.none, + ]; + + @override + bool isVisible( + ChipSetAction action, { + required AppMode appMode, + required bool isSelecting, + required int itemCount, + required Set<AlbumBaseFilter> selectedFilters, + }) { + final selectedSingleItem = selectedFilters.length == 1; + final isMain = appMode == AppMode.main; + bool isVault(CollectionFilter filter) => filter is StoredAlbumFilter && filter.isVault; + + switch (action) { + case ChipSetAction.createGroup: + return true; + case ChipSetAction.createAlbum: + case ChipSetAction.createVault: + return !settings.isReadOnly && appMode.canCreateFilter && !isSelecting; + case ChipSetAction.group: + return isMain && isSelecting; + case ChipSetAction.delete: + return isMain && isSelecting && !settings.isReadOnly && (selectedFilters.isEmpty || selectedFilters.every((v) => v is StoredAlbumFilter)); + case ChipSetAction.remove: + return isMain && isSelecting && !settings.isReadOnly && selectedFilters.isNotEmpty && selectedFilters.every((v) => v is DynamicAlbumFilter); + case ChipSetAction.rename: + return isMain && isSelecting && !settings.isReadOnly; + case ChipSetAction.configureVault: + return isMain && selectedSingleItem && isVault(selectedFilters.first); + case ChipSetAction.lockVault: + return isMain && selectedFilters.any(isVault); + default: + return super.isVisible( + action, + appMode: appMode, + isSelecting: isSelecting, + itemCount: itemCount, + selectedFilters: selectedFilters, + ); + } + } + + @override + bool canApply( + ChipSetAction action, { + required bool isSelecting, + required int itemCount, + required Set<AlbumBaseFilter> selectedFilters, + }) { + switch (action) { + case ChipSetAction.delete: + return selectedFilters.isNotEmpty && selectedFilters.every((v) => v is StoredAlbumFilter); + case ChipSetAction.rename: + if (selectedFilters.length != 1) return false; + final filter = selectedFilters.first; + if (filter is StoredAlbumFilter) return filter.canRename; + return true; + case ChipSetAction.lockVault: + return selectedFilters.whereType<StoredAlbumFilter>().map((v) => v.album).any((v) => vaults.isVault(v) && !vaults.isLocked(v)); + case ChipSetAction.configureVault: + return true; + default: + return super.canApply( + action, + isSelecting: isSelecting, + itemCount: itemCount, + selectedFilters: selectedFilters, + ); + } + } + + @override + void onActionSelected(BuildContext context, ChipSetAction action) { + reportService.log('$runtimeType handles $action'); + switch (action) { + // general + case ChipSetAction.createAlbum: + _createStoredAlbum(context, locked: false); + case ChipSetAction.createVault: + _createStoredAlbum(context, locked: true); + // single/multiple filters + case ChipSetAction.delete: + _deleteStoredAlbums(context); + case ChipSetAction.remove: + _removeDynamicAlbum(context); + case ChipSetAction.group: + _group(context); + case ChipSetAction.lockVault: + lockFilters(_getSelectedStoredAlbumFilters(context)); + browse(context); + // single filter + case ChipSetAction.rename: + _rename(context); + case ChipSetAction.configureVault: + _configureVault(context); + default: + break; + } + super.onActionSelected(context, action); + } + + Set<StoredAlbumFilter> _getSelectedStoredAlbumFilters(BuildContext context) { + return getSelectedFilters(context).whereType<StoredAlbumFilter>().toSet(); + } + + Set<DynamicAlbumFilter> _getSelectedDynamicAlbumFilters(BuildContext context) { + return getSelectedFilters(context).whereType<DynamicAlbumFilter>().toSet(); + } + + @override + Future<void> configureView(BuildContext context) async { + final initialValue = ( + sortFactor, + settings.albumSectionFactor, + tileLayout, + sortReverse, + ); + final extentController = context.read<TileExtentController>(); + final value = await showDialog<(ChipSortFactor?, AlbumChipSectionFactor?, TileLayout?, bool)>( + context: context, + builder: (context) { + return TileViewDialog<ChipSortFactor, AlbumChipSectionFactor, TileLayout>( + initialValue: initialValue, + sortOptions: ChipSetActionDelegate.albumSortOptions.map((v) => TileViewDialogOption(value: v, title: v.getName(context), icon: v.icon)).toList(), + sectionOptions: _sectionOptions.map((v) => TileViewDialogOption(value: v, title: v.getName(context), icon: v.icon)).toList(), + layoutOptions: ChipSetActionDelegate.layoutOptions.map((v) => TileViewDialogOption(value: v, title: v.getName(context), icon: v.icon)).toList(), + sortOrder: (factor, reverse) => factor.getOrderName(context, reverse), + tileExtentController: extentController, + ); + }, + routeSettings: const RouteSettings(name: TileViewDialog.routeName), + ); + // wait for the dialog to hide + await Future.delayed(ADurations.dialogTransitionLoose * timeDilation); + if (value != null && initialValue != value) { + sortFactor = value.$1!; + settings.albumSectionFactor = value.$2!; + tileLayout = value.$3!; + sortReverse = value.$4; + } + } + + void _createStoredAlbum(BuildContext context, {required bool locked}) async { + final l10n = context.l10n; + final source = context.read<CollectionSource>(); + + // get navigator beforehand because + // local context may be deactivated when action is triggered after navigation + final navigator = Navigator.maybeOf(context); + + late final String? directory; + if (locked) { + if (!await showSkippableConfirmationDialog( + context: context, + type: ConfirmationDialog.createVault, + message: l10n.newVaultWarningDialogMessage, + confirmationButtonLabel: l10n.continueButtonLabel, + )) { + return; + } + + final details = await showDialog<VaultDetails>( + context: context, + builder: (context) => const EditVaultDialog(), + routeSettings: const RouteSettings(name: CreateStoredAlbumDialog.routeName), + ); + if (details == null) return; + + await vaults.create(details); + directory = details.path; + } else { + directory = await showDialog<String>( + context: context, + builder: (context) => const CreateStoredAlbumDialog(), + routeSettings: const RouteSettings(name: CreateStoredAlbumDialog.routeName), + ); + if (directory == null) return; + + // wait for the dialog to hide + await Future.delayed(ADurations.dialogTransitionLoose * timeDilation); + } + final filter = StoredAlbumFilter(directory, source.getStoredAlbumDisplayName(context, directory)); + + final albumExists = source.rawAlbums.contains(directory); + if (albumExists) { + // album already exists, so we just need to highlight it + await _showAlbum(navigator, filter); + } else { + // create the album and mark it as new + source.createStoredAlbum(directory); + + final showAction = SnackBarAction( + label: l10n.showButtonLabel, + onPressed: () => _showAlbum(navigator, filter), + ); + showFeedback(context, FeedbackType.info, l10n.genericSuccessFeedback, showAction); + } + } + + Future<void> _showAlbum(NavigatorState? navigator, StoredAlbumFilter filter) async { + // local context may be deactivated when action is triggered after navigation + if (navigator != null) { + final context = navigator.context; + final highlightInfo = context.read<HighlightInfo>(); + if (context.currentRouteName == AlbumListPage.routeName) { + highlightInfo.trackItem(FilterGridItem(filter, null), highlightItem: filter); + } else { + highlightInfo.set(filter); + final initialGroup = albumGrouping.getFilterParent(filter); + await navigator.pushAndRemoveUntil( + MaterialPageRoute( + settings: const RouteSettings(name: AlbumListPage.routeName), + builder: (_) => AlbumListPage(initialGroup: initialGroup), + ), + (route) => false, + ); + } + } + } + + Future<void> _deleteStoredAlbums(BuildContext context) async { + final filters = _getSelectedStoredAlbumFilters(context); + final byBinUsage = groupBy<StoredAlbumFilter, bool>(filters, (filter) { + final details = vaults.getVault(filter.album); + return details?.useBin ?? settings.enableBin; + }); + await Future.forEach( + byBinUsage.entries, + (kv) => _doDelete( + context: context, + filters: kv.value.toSet(), + enableBin: kv.key, + )); + browse(context); + } + + Future<void> _doDelete({ + required BuildContext context, + required Set<StoredAlbumFilter> filters, + required bool enableBin, + }) async { + if (!await unlockFilters(context, filters)) return; + + final source = context.read<CollectionSource>(); + final todoEntries = source.visibleEntries.where((entry) => filters.any((f) => f.test(entry))).toSet(); + final todoAlbums = filters.map((v) => v.album).toSet(); + final filledAlbums = todoEntries.map((e) => e.directory).nonNulls.toSet(); + final emptyAlbums = todoAlbums.whereNot(filledAlbums.contains).toSet(); + + if (enableBin && filledAlbums.isNotEmpty) { + await doMove( + context, + moveType: MoveType.toBin, + entries: todoEntries, + onSuccess: () { + source.forgetNewAlbums(todoAlbums); + source.cleanEmptyAlbums(emptyAlbums); + browse(context); + }, + ); + return; + } + + final l10n = context.l10n; + final todoCount = todoEntries.length; + + final confirmed = await showDialog<bool>( + context: context, + builder: (context) => AvesDialog( + content: Text(filters.length == 1 ? l10n.deleteSingleAlbumConfirmationDialogMessage(todoCount) : l10n.deleteMultiAlbumConfirmationDialogMessage(todoCount)), + actions: [ + const CancelButton(), + TextButton( + onPressed: () => Navigator.maybeOf(context)?.pop(true), + child: Text(l10n.deleteButtonLabel), + ), + ], + ), + routeSettings: const RouteSettings(name: AvesDialog.confirmationRouteName), + ); + if (confirmed == null || !confirmed) return; + + settings.pinnedFilters = settings.pinnedFilters..removeAll(filters); + source.forgetNewAlbums(todoAlbums); + source.cleanEmptyAlbums(emptyAlbums); + + if (!await checkStoragePermissionForAlbums(context, filledAlbums)) return; + + await _deleteEntriesForever(context, todoEntries); + + final vaultAlbumFilters = filters.where((v) => vaults.isVault(v.album)).toSet(); + if (vaultAlbumFilters.isNotEmpty) { + final allEntries = source.allEntries; + final emptyVaultAlbums = vaultAlbumFilters.whereNot((v) => allEntries.any(v.test)).map((v) => v.album).toSet(); + await vaults.remove(emptyVaultAlbums); + } + } + + Future<void> _deleteEntriesForever(BuildContext context, Set<AvesEntry> todoEntries) async { + if (todoEntries.isEmpty) return; + + final source = context.read<CollectionSource>(); + final filledAlbums = todoEntries.map((e) => e.directory).nonNulls.toSet(); + + final l10n = context.l10n; + final messenger = ScaffoldMessenger.of(context); + final todoCount = todoEntries.length; + + source.pauseMonitoring(); + final opId = mediaEditService.newOpId; + await showOpReport<ImageOpEvent>( + context: context, + opStream: mediaEditService.delete(opId: opId, entries: todoEntries), + itemCount: todoCount, + onCancel: () => mediaEditService.cancelFileOp(opId), + onDone: (processed) async { + final successOps = processed.where((op) => op.success); + final deletedOps = successOps.where((op) => !op.skipped).toSet(); + final deletedUris = deletedOps.map((op) => op.uri).toSet(); + await source.removeEntries(deletedUris, includeTrash: true); + browse(context); + source.resumeMonitoring(); + + final successCount = successOps.length; + if (successCount < todoCount) { + final count = todoCount - successCount; + showFeedbackWithMessenger(context, messenger, FeedbackType.warn, l10n.collectionDeleteFailureFeedback(count)); + } + + // cleanup + await storageService.deleteEmptyRegularDirectories(filledAlbums); + }, + ); + } + + Future<void> _removeDynamicAlbum(BuildContext context) async { + final l10n = context.l10n; + final confirmed = await showDialog<bool>( + context: context, + builder: (context) => AvesDialog( + content: Text(l10n.genericDangerWarningDialogMessage), + actions: [ + const CancelButton(), + TextButton( + onPressed: () => Navigator.maybeOf(context)?.pop(true), + child: Text(l10n.applyButtonLabel), + ), + ], + ), + routeSettings: const RouteSettings(name: AvesDialog.warningRouteName), + ); + if (confirmed == null || !confirmed) return; + + final albumFilters = _getSelectedDynamicAlbumFilters(context); + final names = albumFilters.map((v) => v.name).toSet(); + bool isRemoved(CollectionFilter v) => v is DynamicAlbumFilter && names.contains(v.name); + + await dynamicAlbums.remove(albumFilters); + + // cleanup + await covers.removeAll(albumFilters, notify: true); + settings.drawerAlbumBookmarks = settings.drawerAlbumBookmarks?..removeWhere(isRemoved); + settings.pinnedFilters = settings.pinnedFilters..removeWhere(isRemoved); + + browse(context); + } + + Future<void> _group(BuildContext context) async { + final filters = getSelectedFilters(context); + final childrenUris = filters.map(GroupingConversion.filterToUri).nonNulls.toSet(); + + final initialGroup = albumGrouping.getFilterParent(filters.first); + final filter = await pickAlbum( + context: context, + moveType: null, + chipTypes: {AlbumChipType.group}, + initialGroup: initialGroup, + ); + if (filter == null) return; + + final destinationGroupUri = filter is AlbumGroupFilter ? filter.uri : null; + albumGrouping.addToGroup(childrenUris, destinationGroupUri); + context.read<FilterGroupNotifier>().value = destinationGroupUri; + + final source = context.read<CollectionSource>(); + source.invalidateAlbumGroupFilterSummary(notify: true); + browse(context); + } + + Future<void> _rename(BuildContext context) async { + final filters = getSelectedFilters(context); + if (filters.isEmpty) return; + + final filter = filters.first; + if (filter is StoredAlbumFilter) { + if (!await unlockFilter(context, filter)) return; + + final album = filter.album; + if (!vaults.isVault(album)) { + final dir = androidFileUtils.relativeDirectoryFromPath(album); + // do not allow renaming volume root + if (dir == null || dir.relativeDir.isEmpty) return; + + // check whether renaming is possible given OS restrictions, + // before asking to input a new name + final restrictedDirsLowerCase = await storageService.getRestrictedDirectoriesLowerCase(); + if (restrictedDirsLowerCase.contains(dir.copyWith(relativeDir: dir.relativeDir.toLowerCase()))) { + await showRestrictedDirectoryDialog(context, dir); + return; + } + } + + final newName = await showDialog<String>( + context: context, + builder: (context) => RenameStoredAlbumDialog(album: album), + routeSettings: const RouteSettings(name: RenameStoredAlbumDialog.routeName), + ); + if (newName == null || newName.isEmpty) return; + + await _doRenameStoredAlbum(context, filter, newName); + } else if (filter is DynamicAlbumFilter) { + final newName = await showDialog<String>( + context: context, + builder: (context) => RenameDynamicAlbumDialog(name: filter.name), + routeSettings: const RouteSettings(name: RenameDynamicAlbumDialog.routeName), + ); + if (newName == null || newName.isEmpty) return; + + await _doRenameDynamicAlbum(context, filter, newName); + } else if (filter is AlbumGroupFilter) { + final newGroupUri = await showDialog<Uri>( + context: context, + builder: (context) => RenameGroupDialog(grouping: albumGrouping, groupUri: filter.uri), + routeSettings: const RouteSettings(name: RenameGroupDialog.routeName), + ); + if (newGroupUri == null) return; + + await _doRenameAlbumGroup(context, filter, newGroupUri); + } + } + + Future<void> _doRenameAlbumGroup(BuildContext context, AlbumGroupFilter oldFilter, Uri newUri) async { + albumGrouping.rename(oldFilter.uri, newUri); + final newFilter = albumGrouping.uriToFilter(newUri); + if (newFilter == null) { + showFeedback(context, FeedbackType.warn, context.l10n.genericFailureFeedback); + return; + } + browse(context); + } + + Future<void> _doRenameDynamicAlbum(BuildContext context, DynamicAlbumFilter oldFilter, String newName) async { + await dynamicAlbums.rename(oldFilter, newName); + browse(context); + } + + Future<void> _doRenameStoredAlbum(BuildContext context, StoredAlbumFilter albumFilter, String newName) async { + final l10n = context.l10n; + final messenger = ScaffoldMessenger.of(context); + final source = context.read<CollectionSource>(); + final album = albumFilter.album; + final todoEntries = source.visibleEntries.where(albumFilter.test).toSet(); + final todoCount = todoEntries.length; + + final destinationAlbumParent = pContext.dirname(album); + final destinationAlbum = pContext.join(destinationAlbumParent, newName); + if (!await checkFreeSpaceForMove(context, todoEntries, destinationAlbum, MoveType.move)) return; + + if (!await checkStoragePermissionForAlbums(context, {album})) return; + + if (!await File(destinationAlbum).exists()) { + // access to the destination parent is required to create the underlying destination folder + if (!await checkStoragePermissionForAlbums(context, {destinationAlbumParent})) return; + } + + source.pauseMonitoring(); + final opId = mediaEditService.newOpId; + await showOpReport<MoveOpEvent>( + context: context, + opStream: mediaEditService.move( + opId: opId, + entriesByDestination: {destinationAlbum: todoEntries}, + copy: false, + // there should be no file conflict, as the target directory itself does not exist + nameConflictStrategy: NameConflictStrategy.rename, + ), + itemCount: todoCount, + onCancel: () => mediaEditService.cancelFileOp(opId), + onDone: (processed) async { + final successOps = processed.where((op) => op.success).toSet(); + final movedOps = successOps.where((op) => !op.skipped).toSet(); + await source.renameStoredAlbum(album, destinationAlbum, todoEntries, movedOps); + browse(context); + source.resumeMonitoring(); + + final successCount = successOps.length; + if (successCount < todoCount) { + final count = todoCount - successCount; + showFeedbackWithMessenger(context, messenger, FeedbackType.warn, l10n.collectionMoveFailureFeedback(count)); + } else { + showFeedbackWithMessenger(context, messenger, FeedbackType.info, l10n.genericSuccessFeedback); + } + + // cleanup + await storageService.deleteEmptyRegularDirectories({album}); + }, + ); + } + + Future<void> _configureVault(BuildContext context) async { + final filters = getSelectedFilters(context); + if (filters.isEmpty) return; + + final filter = filters.first; + if (filter is! StoredAlbumFilter) return; + + if (!await unlockFilter(context, filter)) return; + + final oldDetails = vaults.getVault(filter.album); + if (oldDetails == null) return; + + final newDetails = await showDialog<VaultDetails>( + context: context, + builder: (context) => EditVaultDialog(initialDetails: oldDetails), + routeSettings: const RouteSettings(name: EditVaultDialog.routeName), + ); + if (newDetails == null || oldDetails == newDetails) return; + + if (oldDetails.useBin && !newDetails.useBin) { + final filter = StoredAlbumFilter(oldDetails.path, null); + final source = context.read<CollectionSource>(); + await _deleteEntriesForever(context, source.trashedEntries.where(filter.test).toSet()); + } + + final oldName = oldDetails.name; + final newName = newDetails.name; + if (oldName != newName) { + await vaults.update(newDetails.copyWith(name: oldName)); + // wipe the old pass, if any, so that it does not overwrite the new pass + // when renaming the vault afterwards + await securityService.writeValue(oldDetails.passKey, null); + await _doRenameStoredAlbum(context, filter, newName); + } else { + await vaults.update(newDetails); + browse(context); + } + } +} diff --git a/lib/widgets/filter_grids/common/action_delegates/chip.dart b/lib/widgets/filter_grids/common/action_delegates/chip.dart new file mode 100644 index 0000000..7af39ea --- /dev/null +++ b/lib/widgets/filter_grids/common/action_delegates/chip.dart @@ -0,0 +1,141 @@ +import 'package:aves/model/filters/container/album_group.dart'; +import 'package:aves/model/filters/container/dynamic_album.dart'; +import 'package:aves/model/filters/covered/location.dart'; +import 'package:aves/model/filters/covered/stored_album.dart'; +import 'package:aves/model/filters/covered/tag.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/filters/path.dart'; +import 'package:aves/model/filters/rating.dart'; +import 'package:aves/model/grouping/common.dart'; +import 'package:aves/model/highlight.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/vaults/vaults.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/widgets/common/action_mixins/feedback.dart'; +import 'package:aves/widgets/common/action_mixins/vault_aware.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:aves/widgets/explorer/explorer_page.dart'; +import 'package:aves/widgets/filter_grids/albums_page.dart'; +import 'package:aves/widgets/filter_grids/countries_page.dart'; +import 'package:aves/widgets/filter_grids/places_page.dart'; +import 'package:aves/widgets/filter_grids/tags_page.dart'; +import 'package:aves/widgets/viewer/controls/notifications.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class ChipActionDelegate with FeedbackMixin, VaultAwareMixin { + bool isVisible( + ChipAction action, { + required CollectionFilter filter, + }) { + switch (action) { + case ChipAction.goToAlbumPage: + return filter is AlbumBaseFilter; + case ChipAction.goToCountryPage: + return filter is LocationFilter && filter.level == LocationLevel.country; + case ChipAction.goToPlacePage: + return filter is LocationFilter && filter.level == LocationLevel.place; + case ChipAction.goToTagPage: + return filter is TagFilter; + case ChipAction.goToExplorerPage: + return filter is StoredAlbumFilter || filter is PathFilter; + case ChipAction.ratingOrGreater: + return filter is RatingFilter && 1 <= filter.rating && filter.rating < 5 && filter.op != RatingFilter.opOrGreater; + case ChipAction.ratingOrLower: + return filter is RatingFilter && 1 < filter.rating && filter.rating <= 5 && filter.op != RatingFilter.opOrLower; + case ChipAction.decompose: + return filter is DynamicAlbumFilter; + case ChipAction.reverse: + case ChipAction.hide: + return true; + case ChipAction.lockVault: + return (filter is StoredAlbumFilter && vaults.isVault(filter.album) && !vaults.isLocked(filter.album)); + } + } + + void onActionSelected(BuildContext context, CollectionFilter filter, ChipAction action) { + reportService.log('$runtimeType handles $action'); + switch (action) { + case ChipAction.goToAlbumPage: + final initialGroup = albumGrouping.getFilterParent(filter); + _goTo(context, filter, AlbumListPage.routeName, (context) => AlbumListPage(initialGroup: initialGroup)); + case ChipAction.goToCountryPage: + _goTo(context, filter, CountryListPage.routeName, (context) => const CountryListPage()); + case ChipAction.goToPlacePage: + _goTo(context, filter, PlaceListPage.routeName, (context) => const PlaceListPage()); + case ChipAction.goToTagPage: + final initialGroup = tagGrouping.getFilterParent(filter); + _goTo(context, filter, TagListPage.routeName, (context) => TagListPage(initialGroup: initialGroup)); + case ChipAction.goToExplorerPage: + String? path; + if (filter is StoredAlbumFilter) { + path = filter.album; + } else if (filter is PathFilter) { + path = filter.path; + } + if (path != null) { + Navigator.maybeOf(context)?.pushAndRemoveUntil( + MaterialPageRoute( + settings: const RouteSettings(name: ExplorerPage.routeName), + builder: (context) => ExplorerPage(path: path), + ), + (route) => false, + ); + } + case ChipAction.ratingOrGreater: + SelectFilterNotification((filter as RatingFilter).copyWith(RatingFilter.opOrGreater)).dispatch(context); + case ChipAction.ratingOrLower: + SelectFilterNotification((filter as RatingFilter).copyWith(RatingFilter.opOrLower)).dispatch(context); + case ChipAction.decompose: + DecomposeFilterNotification(filter).dispatch(context); + case ChipAction.reverse: + SelectFilterNotification(filter.reverse()).dispatch(context); + case ChipAction.hide: + _hide(context, filter); + case ChipAction.lockVault: + if (filter is StoredAlbumFilter) { + lockFilters({filter}); + } + } + } + + void _goTo( + BuildContext context, + CollectionFilter filter, + String routeName, + WidgetBuilder pageBuilder, + ) { + context.read<HighlightInfo>().set(filter); + Navigator.maybeOf(context)?.pushAndRemoveUntil( + MaterialPageRoute( + settings: RouteSettings(name: routeName), + builder: pageBuilder, + ), + (route) => false, + ); + } + + Future<void> _hide(BuildContext context, CollectionFilter filter) async { + final confirmed = await showDialog<bool>( + context: context, + builder: (context) => AvesDialog( + content: Text(context.l10n.hideFilterConfirmationDialogMessage), + actions: [ + const CancelButton(), + TextButton( + onPressed: () => Navigator.maybeOf(context)?.pop(true), + child: Text(context.l10n.hideButtonLabel), + ), + ], + ), + routeSettings: const RouteSettings(name: AvesDialog.confirmationRouteName), + ); + if (confirmed == null || !confirmed) return; + + if (!await unlockFilter(context, filter)) return; + + settings.changeFilterVisibility({filter}, false); + } +} diff --git a/lib/widgets/filter_grids/common/action_delegates/chip_set.dart b/lib/widgets/filter_grids/common/action_delegates/chip_set.dart new file mode 100644 index 0000000..254e3d6 --- /dev/null +++ b/lib/widgets/filter_grids/common/action_delegates/chip_set.dart @@ -0,0 +1,435 @@ +import 'package:aves/app_mode.dart'; +import 'package:aves/model/covers.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/filters/container/set_or.dart'; +import 'package:aves/model/filters/covered/stored_album.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/grouping/common.dart'; +import 'package:aves/model/query.dart'; +import 'package:aves/model/selection.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/theme/colors.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/collection/collection_page.dart'; +import 'package:aves/widgets/common/action_mixins/feedback.dart'; +import 'package:aves/widgets/common/action_mixins/permission_aware.dart'; +import 'package:aves/widgets/common/action_mixins/size_aware.dart'; +import 'package:aves/widgets/common/action_mixins/vault_aware.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/providers/filter_group_provider.dart'; +import 'package:aves/widgets/common/search/route.dart'; +import 'package:aves/widgets/common/tile_extent_controller.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:aves/widgets/dialogs/filter_editors/cover_selection_dialog.dart'; +import 'package:aves/widgets/dialogs/tile_view_dialog.dart'; +import 'package:aves/widgets/map/map_page.dart'; +import 'package:aves/widgets/search/collection_search_delegate.dart'; +import 'package:aves/widgets/stats/stats_page.dart'; +import 'package:aves/widgets/viewer/slideshow_page.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:provider/provider.dart'; + +abstract class ChipSetActionDelegate<T extends CollectionFilter> with FeedbackMixin, PermissionAwareMixin, SizeAwareMixin, VaultAwareMixin { + Iterable<FilterGridItem<T>> get allItems; + + ChipSortFactor get sortFactor; + + set sortFactor(ChipSortFactor factor); + + bool get sortReverse; + + set sortReverse(bool value); + + TileLayout get tileLayout; + + set tileLayout(TileLayout tileLayout); + + static const sortOptions = [ + ChipSortFactor.date, + ChipSortFactor.name, + ChipSortFactor.count, + ChipSortFactor.size, + ]; + + static const albumSortOptions = [ + ...sortOptions, + ChipSortFactor.path, + ]; + + static const layoutOptions = [ + TileLayout.mosaic, + TileLayout.grid, + TileLayout.list, + ]; + + bool isVisible( + ChipSetAction action, { + required AppMode appMode, + required bool isSelecting, + required int itemCount, + required Set<T> selectedFilters, + }) { + final selectedItemCount = selectedFilters.length; + final hasSelection = selectedFilters.isNotEmpty; + final isMain = appMode == AppMode.main; + final useTvLayout = settings.useTvLayout; + switch (action) { + // general + case ChipSetAction.configureView: + return true; + case ChipSetAction.select: + return appMode.canSelectFilter && !isSelecting; + case ChipSetAction.selectAll: + return isSelecting && selectedItemCount < itemCount; + case ChipSetAction.selectNone: + return isSelecting && selectedItemCount == itemCount; + // browsing + case ChipSetAction.search: + return !useTvLayout && appMode.canNavigate && !isSelecting; + case ChipSetAction.toggleTitleSearch: + return !useTvLayout && !isSelecting; + case ChipSetAction.createGroup: + case ChipSetAction.createAlbum: + case ChipSetAction.createVault: + return false; + // browsing or selecting + case ChipSetAction.map: + case ChipSetAction.slideshow: + case ChipSetAction.stats: + return isMain; + // selecting (single/multiple filters) + case ChipSetAction.hide: + return isMain; + case ChipSetAction.pin: + return isMain && (!hasSelection || !settings.pinnedFilters.containsAll(selectedFilters)); + case ChipSetAction.unpin: + return isMain && (hasSelection && settings.pinnedFilters.containsAll(selectedFilters)); + case ChipSetAction.showCollection: + return appMode.canNavigate; + case ChipSetAction.delete: + case ChipSetAction.remove: + case ChipSetAction.group: + case ChipSetAction.lockVault: + case ChipSetAction.showCountryStates: + return false; + // selecting (single filter) + case ChipSetAction.setCover: + return isMain; + case ChipSetAction.rename: + case ChipSetAction.configureVault: + return false; + } + } + + bool canApply( + ChipSetAction action, { + required bool isSelecting, + required int itemCount, + required Set<T> selectedFilters, + }) { + final selectedItemCount = selectedFilters.length; + final hasItems = itemCount > 0; + final hasSelection = selectedItemCount > 0; + + switch (action) { + // general + case ChipSetAction.select: + return hasItems; + case ChipSetAction.configureView: + case ChipSetAction.selectAll: + case ChipSetAction.selectNone: + // browsing + case ChipSetAction.search: + case ChipSetAction.toggleTitleSearch: + case ChipSetAction.createGroup: + case ChipSetAction.createAlbum: + case ChipSetAction.createVault: + return true; + // browsing or selecting + case ChipSetAction.map: + case ChipSetAction.slideshow: + case ChipSetAction.stats: + return (!isSelecting && hasItems) || (isSelecting && hasSelection); + // selecting (single/multiple filters) + case ChipSetAction.delete: + case ChipSetAction.remove: + case ChipSetAction.hide: + case ChipSetAction.pin: + case ChipSetAction.unpin: + case ChipSetAction.group: + case ChipSetAction.lockVault: + case ChipSetAction.showCountryStates: + case ChipSetAction.showCollection: + return hasSelection; + // selecting (single filter) + case ChipSetAction.rename: + case ChipSetAction.setCover: + case ChipSetAction.configureVault: + return selectedItemCount == 1; + } + } + + void onActionSelected(BuildContext context, ChipSetAction action) { + reportService.log('$runtimeType handles $action'); + switch (action) { + // general + case ChipSetAction.configureView: + configureView(context); + case ChipSetAction.select: + context.read<Selection<FilterGridItem<T>>>().select(); + case ChipSetAction.selectAll: + context.read<Selection<FilterGridItem<T>>>().addToSelection(allItems); + case ChipSetAction.selectNone: + context.read<Selection<FilterGridItem<T>>>().clearSelection(); + // browsing + case ChipSetAction.search: + _goToSearch(context); + case ChipSetAction.toggleTitleSearch: + final routeName = context.currentRouteName!; + settings.setShowTitleQuery(routeName, !settings.getShowTitleQuery(routeName)); + context.read<Query>().toggle(); + case ChipSetAction.createGroup: + case ChipSetAction.createAlbum: + case ChipSetAction.createVault: + break; + // browsing or selecting + case ChipSetAction.map: + _goToMap(context); + case ChipSetAction.slideshow: + _goToSlideshow(context); + case ChipSetAction.stats: + _goToStats(context); + // selecting (single/multiple filters) + case ChipSetAction.hide: + _hide(context); + case ChipSetAction.pin: + settings.pinnedFilters = settings.pinnedFilters..addAll(getSelectedFilters(context)); + browse(context); + case ChipSetAction.unpin: + settings.pinnedFilters = settings.pinnedFilters..removeAll(getSelectedFilters(context)); + browse(context); + case ChipSetAction.showCollection: + _goToCollection(context); + case ChipSetAction.delete: + case ChipSetAction.remove: + case ChipSetAction.group: + case ChipSetAction.lockVault: + case ChipSetAction.showCountryStates: + break; + // selecting (single filter) + case ChipSetAction.setCover: + _setCover(context); + case ChipSetAction.rename: + case ChipSetAction.configureVault: + break; + } + } + + void browse(BuildContext context) => context.read<Selection<FilterGridItem<T>>?>()?.browse(); + + Set<T> getSelectedFilters(BuildContext context) { + final selection = context.read<Selection<FilterGridItem<T>>>(); + return selection.isSelecting ? selection.selectedItems.map((v) => v.filter).toSet() : {}; + } + + Iterable<AvesEntry> _selectedEntries(BuildContext context) { + final source = context.read<CollectionSource>(); + final visibleEntries = source.visibleEntries; + + final filters = <CollectionFilter>{}; + // use user selected filters, if any + filters.addAll(getSelectedFilters(context)); + + if (filters.isEmpty) { + // use current group filters, if any + final groupUri = context.read<FilterGroupNotifier?>()?.value; + if (groupUri != null) { + final grouping = FilterGrouping.forUri(groupUri); + if (grouping != null) { + final groupContent = grouping.getDirectChildren(groupUri); + filters.addAll(groupContent); + } + } + } + + if (filters.isNotEmpty) { + return visibleEntries.where((entry) => filters.any((f) => f.test(entry))); + } + + // default to all content + return visibleEntries; + } + + Future<void> configureView(BuildContext context) async { + final initialValue = ( + sortFactor, + null, + tileLayout, + sortReverse, + ); + final extentController = context.read<TileExtentController>(); + final value = await showDialog<(ChipSortFactor?, void, TileLayout?, bool)>( + context: context, + builder: (context) { + return TileViewDialog<ChipSortFactor, void, TileLayout>( + initialValue: initialValue, + sortOptions: sortOptions.map((v) => TileViewDialogOption(value: v, title: v.getName(context), icon: v.icon)).toList(), + layoutOptions: layoutOptions.map((v) => TileViewDialogOption(value: v, title: v.getName(context), icon: v.icon)).toList(), + sortOrder: (factor, reverse) => factor.getOrderName(context, reverse), + tileExtentController: extentController, + ); + }, + routeSettings: const RouteSettings(name: TileViewDialog.routeName), + ); + // wait for the dialog to hide + await Future.delayed(ADurations.dialogTransitionLoose * timeDilation); + if (value != null && initialValue != value) { + sortFactor = value.$1!; + tileLayout = value.$3!; + sortReverse = value.$4; + } + } + + Future<void> _goToCollection(context) async { + final filters = getSelectedFilters(context); + if (filters.isEmpty) return; + + final filter = filters.length > 1 ? SetOrFilter(filters) : filters.first; + await Navigator.maybeOf(context)?.push( + MaterialPageRoute( + settings: const RouteSettings(name: CollectionPage.routeName), + builder: (context) => CollectionPage( + source: context.read<CollectionSource>(), + filters: {filter}, + ), + ), + ); + } + + Future<void> _goToMap(BuildContext context) async { + final mapCollection = CollectionLens( + source: context.read<CollectionSource>(), + fixedSelection: _selectedEntries(context).where((entry) => entry.hasGps).toList(), + ); + await Navigator.maybeOf(context)?.push( + MaterialPageRoute( + settings: const RouteSettings(name: MapPage.routeName), + builder: (context) => MapPage(collection: mapCollection), + ), + ); + } + + Future<void> _goToSlideshow(BuildContext context) async { + final entries = _selectedEntries(context).toList(); + await Navigator.maybeOf(context)?.push( + MaterialPageRoute( + settings: const RouteSettings(name: SlideshowPage.routeName), + builder: (context) { + return SlideshowPage( + collection: CollectionLens( + source: context.read<CollectionSource>(), + fixedSelection: entries, + ), + ); + }, + ), + ); + } + + Future<void> _goToStats(BuildContext context) async { + final entries = _selectedEntries(context).toSet(); + await Navigator.maybeOf(context)?.push( + MaterialPageRoute( + settings: const RouteSettings(name: StatsPage.routeName), + builder: (context) { + return StatsPage( + entries: entries, + source: context.read<CollectionSource>(), + ); + }, + ), + ); + } + + Future<void> _goToSearch(BuildContext context) async { + await Navigator.maybeOf(context)?.push( + SearchPageRoute( + delegate: CollectionSearchDelegate( + searchFieldLabel: context.l10n.searchCollectionFieldHint, + searchFieldStyle: Themes.searchFieldStyle(context), + source: context.read<CollectionSource>(), + ), + ), + ); + } + + Future<void> _hide(BuildContext context) async { + final confirmed = await showDialog<bool>( + context: context, + builder: (context) => AvesDialog( + content: Text(context.l10n.hideFilterConfirmationDialogMessage), + actions: [ + const CancelButton(), + TextButton( + onPressed: () => Navigator.maybeOf(context)?.pop(true), + child: Text(context.l10n.hideButtonLabel), + ), + ], + ), + routeSettings: const RouteSettings(name: AvesDialog.confirmationRouteName), + ); + if (confirmed == null || !confirmed) return; + + final filters = getSelectedFilters(context); + if (!await unlockFilters(context, filters)) return; + + settings.changeFilterVisibility(filters, false); + + browse(context); + } + + void _setCover(BuildContext context) async { + final filters = getSelectedFilters(context); + if (filters.isEmpty) return; + + final filter = filters.first; + if (!await unlockFilter(context, filter)) return; + + final existingCover = covers.of(filter); + final entryId = existingCover?.$1; + final customEntry = entryId != null ? context.read<CollectionSource>().visibleEntries.firstWhereOrNull((entry) => entry.id == entryId) : null; + final selectedCover = await showDialog<(AvesEntry?, String?, Color?)>( + context: context, + builder: (context) => CoverSelectionDialog( + filter: filter, + customEntry: customEntry, + customPackage: existingCover?.$2, + customColor: existingCover?.$3, + ), + routeSettings: const RouteSettings(name: CoverSelectionDialog.routeName), + ); + if (selectedCover == null) return; + + if (filter is StoredAlbumFilter) { + context.read<AvesColorsData>().clearAppColor(filter.album); + } + + final (selectedEntry, selectedPackage, selectedColor) = selectedCover; + await covers.set( + filter: filter, + entryId: selectedEntry?.id, + packageName: selectedPackage, + color: selectedColor, + ); + + browse(context); + } +} diff --git a/lib/widgets/filter_grids/common/action_delegates/country_set.dart b/lib/widgets/filter_grids/common/action_delegates/country_set.dart new file mode 100644 index 0000000..8aae1fc --- /dev/null +++ b/lib/widgets/filter_grids/common/action_delegates/country_set.dart @@ -0,0 +1,105 @@ +import 'package:aves/app_mode.dart'; +import 'package:aves/geo/states.dart'; +import 'package:aves/model/filters/covered/location.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/widgets/filter_grids/common/action_delegates/chip_set.dart'; +import 'package:aves/widgets/filter_grids/countries_page.dart'; +import 'package:aves/widgets/filter_grids/states_page.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; + +class CountryChipSetActionDelegate extends ChipSetActionDelegate<LocationFilter> { + final Iterable<FilterGridItem<LocationFilter>> _items; + + CountryChipSetActionDelegate(Iterable<FilterGridItem<LocationFilter>> items) : _items = items; + + @override + Iterable<FilterGridItem<LocationFilter>> get allItems => _items; + + @override + ChipSortFactor get sortFactor => settings.countrySortFactor; + + @override + set sortFactor(ChipSortFactor factor) => settings.countrySortFactor = factor; + + @override + bool get sortReverse => settings.countrySortReverse; + + @override + set sortReverse(bool value) => settings.countrySortReverse = value; + + @override + TileLayout get tileLayout => settings.getTileLayout(CountryListPage.routeName); + + @override + set tileLayout(TileLayout tileLayout) => settings.setTileLayout(CountryListPage.routeName, tileLayout); + + @override + bool isVisible( + ChipSetAction action, { + required AppMode appMode, + required bool isSelecting, + required int itemCount, + required Set<LocationFilter> selectedFilters, + }) { + switch (action) { + case ChipSetAction.showCountryStates: + return isSelecting; + default: + return super.isVisible( + action, + appMode: appMode, + isSelecting: isSelecting, + itemCount: itemCount, + selectedFilters: selectedFilters, + ); + } + } + + @override + bool canApply( + ChipSetAction action, { + required bool isSelecting, + required int itemCount, + required Set<LocationFilter> selectedFilters, + }) { + switch (action) { + case ChipSetAction.showCountryStates: + return selectedFilters.any((v) => GeoStates.stateCountryCodes.contains(v.code)); + default: + return super.canApply( + action, + isSelecting: isSelecting, + itemCount: itemCount, + selectedFilters: selectedFilters, + ); + } + } + + @override + void onActionSelected(BuildContext context, ChipSetAction action) { + reportService.log('$runtimeType handles $action'); + switch (action) { + // single/multiple filters + case ChipSetAction.showCountryStates: + _showStates(context); + browse(context); + default: + break; + } + super.onActionSelected(context, action); + } + + void _showStates(BuildContext context) { + final filters = getSelectedFilters(context); + final countryCodes = filters.map((v) => v.code).where(GeoStates.stateCountryCodes.contains).nonNulls.toSet(); + Navigator.maybeOf(context)?.push( + MaterialPageRoute( + settings: const RouteSettings(name: StateListPage.routeName), + builder: (_) => StateListPage(countryCodes: countryCodes), + ), + ); + } +} diff --git a/lib/widgets/filter_grids/common/action_delegates/place_set.dart b/lib/widgets/filter_grids/common/action_delegates/place_set.dart new file mode 100644 index 0000000..3d80882 --- /dev/null +++ b/lib/widgets/filter_grids/common/action_delegates/place_set.dart @@ -0,0 +1,33 @@ +import 'package:aves/model/filters/covered/location.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/widgets/filter_grids/common/action_delegates/chip_set.dart'; +import 'package:aves/widgets/filter_grids/places_page.dart'; +import 'package:aves_model/aves_model.dart'; + +class PlaceChipSetActionDelegate extends ChipSetActionDelegate<LocationFilter> { + final Iterable<FilterGridItem<LocationFilter>> _items; + + PlaceChipSetActionDelegate(Iterable<FilterGridItem<LocationFilter>> items) : _items = items; + + @override + Iterable<FilterGridItem<LocationFilter>> get allItems => _items; + + @override + ChipSortFactor get sortFactor => settings.placeSortFactor; + + @override + set sortFactor(ChipSortFactor factor) => settings.placeSortFactor = factor; + + @override + bool get sortReverse => settings.placeSortReverse; + + @override + set sortReverse(bool value) => settings.placeSortReverse = value; + + @override + TileLayout get tileLayout => settings.getTileLayout(PlaceListPage.routeName); + + @override + set tileLayout(TileLayout tileLayout) => settings.setTileLayout(PlaceListPage.routeName, tileLayout); +} diff --git a/lib/widgets/filter_grids/common/action_delegates/state_set.dart b/lib/widgets/filter_grids/common/action_delegates/state_set.dart new file mode 100644 index 0000000..469c655 --- /dev/null +++ b/lib/widgets/filter_grids/common/action_delegates/state_set.dart @@ -0,0 +1,33 @@ +import 'package:aves/model/filters/covered/location.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/widgets/filter_grids/common/action_delegates/chip_set.dart'; +import 'package:aves/widgets/filter_grids/states_page.dart'; +import 'package:aves_model/aves_model.dart'; + +class StateChipSetActionDelegate extends ChipSetActionDelegate<LocationFilter> { + final Iterable<FilterGridItem<LocationFilter>> _items; + + StateChipSetActionDelegate(Iterable<FilterGridItem<LocationFilter>> items) : _items = items; + + @override + Iterable<FilterGridItem<LocationFilter>> get allItems => _items; + + @override + ChipSortFactor get sortFactor => settings.stateSortFactor; + + @override + set sortFactor(ChipSortFactor factor) => settings.stateSortFactor = factor; + + @override + bool get sortReverse => settings.stateSortReverse; + + @override + set sortReverse(bool value) => settings.stateSortReverse = value; + + @override + TileLayout get tileLayout => settings.getTileLayout(StateListPage.routeName); + + @override + set tileLayout(TileLayout tileLayout) => settings.setTileLayout(StateListPage.routeName, tileLayout); +} diff --git a/lib/widgets/filter_grids/common/action_delegates/tag_set.dart b/lib/widgets/filter_grids/common/action_delegates/tag_set.dart new file mode 100644 index 0000000..90c63b6 --- /dev/null +++ b/lib/widgets/filter_grids/common/action_delegates/tag_set.dart @@ -0,0 +1,160 @@ +import 'package:aves/app_mode.dart'; +import 'package:aves/model/filters/container/tag_group.dart'; +import 'package:aves/model/filters/covered/tag.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/grouping/common.dart'; +import 'package:aves/model/grouping/convert.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/widgets/collection/entry_set_action_delegate.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/providers/filter_group_provider.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:aves/widgets/dialogs/pick_dialogs/tag_pick_page.dart'; +import 'package:aves/widgets/filter_grids/common/action_delegates/chip_set.dart'; +import 'package:aves/widgets/filter_grids/common/enums.dart'; +import 'package:aves/widgets/filter_grids/tags_page.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class TagChipSetActionDelegate extends ChipSetActionDelegate<TagBaseFilter> { + final Iterable<FilterGridItem<TagBaseFilter>> _items; + + TagChipSetActionDelegate(Iterable<FilterGridItem<TagBaseFilter>> items) : _items = items; + + @override + Iterable<FilterGridItem<TagBaseFilter>> get allItems => _items; + + @override + ChipSortFactor get sortFactor => settings.tagSortFactor; + + @override + set sortFactor(ChipSortFactor factor) => settings.tagSortFactor = factor; + + @override + bool get sortReverse => settings.tagSortReverse; + + @override + set sortReverse(bool value) => settings.tagSortReverse = value; + + @override + TileLayout get tileLayout => settings.getTileLayout(TagListPage.routeName); + + @override + set tileLayout(TileLayout tileLayout) => settings.setTileLayout(TagListPage.routeName, tileLayout); + + @override + bool isVisible( + ChipSetAction action, { + required AppMode appMode, + required bool isSelecting, + required int itemCount, + required Set<TagBaseFilter> selectedFilters, + }) { + final isMain = appMode == AppMode.main; + + switch (action) { + case ChipSetAction.createGroup: + return true; + case ChipSetAction.group: + return isMain && isSelecting; + case ChipSetAction.remove: + return isMain && isSelecting && !settings.isReadOnly && (selectedFilters.isEmpty || selectedFilters.every((v) => v is TagFilter)); + default: + return super.isVisible( + action, + appMode: appMode, + isSelecting: isSelecting, + itemCount: itemCount, + selectedFilters: selectedFilters, + ); + } + } + + @override + bool canApply( + ChipSetAction action, { + required bool isSelecting, + required int itemCount, + required Set<TagBaseFilter> selectedFilters, + }) { + switch (action) { + case ChipSetAction.delete: + return selectedFilters.isNotEmpty && selectedFilters.every((v) => v is TagFilter); + default: + return super.canApply( + action, + isSelecting: isSelecting, + itemCount: itemCount, + selectedFilters: selectedFilters, + ); + } + } + + @override + void onActionSelected(BuildContext context, ChipSetAction action) { + reportService.log('$runtimeType handles $action'); + switch (action) { + // single/multiple filters + case ChipSetAction.remove: + _remove(context); + case ChipSetAction.group: + _group(context); + default: + break; + } + super.onActionSelected(context, action); + } + + Future<void> _remove(BuildContext context) async { + final filters = getSelectedFilters(context).whereType<TagFilter>().toSet(); + + final source = context.read<CollectionSource>(); + final todoEntries = source.visibleEntries.where((entry) => filters.any((f) => f.test(entry))).toSet(); + final todoTags = filters.map((v) => v.tag).toSet(); + + final l10n = context.l10n; + final confirmed = await showDialog<bool>( + context: context, + builder: (context) => AvesDialog( + content: Text(l10n.genericDangerWarningDialogMessage), + actions: [ + const CancelButton(), + TextButton( + onPressed: () => Navigator.maybeOf(context)?.pop(true), + child: Text(l10n.applyButtonLabel), + ), + ], + ), + routeSettings: const RouteSettings(name: AvesDialog.warningRouteName), + ); + if (confirmed == null || !confirmed) return; + + await EntrySetActionDelegate().removeTags(context, entries: todoEntries, tags: todoTags); + + browse(context); + } + + Future<void> _group(BuildContext context) async { + final filters = getSelectedFilters(context); + final childrenUris = filters.map(GroupingConversion.filterToUri).nonNulls.toSet(); + + final initialGroup = tagGrouping.getFilterParent(filters.first); + final filter = await pickTag( + context: context, + chipTypes: {ChipType.group}, + initialGroup: initialGroup, + ); + if (filter == null) return; + + final destinationGroupUri = filter is TagGroupFilter ? filter.uri : null; + tagGrouping.addToGroup(childrenUris, destinationGroupUri); + context.read<FilterGroupNotifier>().value = destinationGroupUri; + + final source = context.read<CollectionSource>(); + source.invalidateTagGroupFilterSummary(notify: true); + browse(context); + } +} diff --git a/lib/widgets/filter_grids/common/app_bar.dart b/lib/widgets/filter_grids/common/app_bar.dart new file mode 100644 index 0000000..8ce17ee --- /dev/null +++ b/lib/widgets/filter_grids/common/app_bar.dart @@ -0,0 +1,519 @@ +import 'dart:async'; + +import 'package:aves/app_mode.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/grouping/common.dart'; +import 'package:aves/model/query.dart'; +import 'package:aves/model/selection.dart'; +import 'package:aves/model/settings/enums/accessibility_animations.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/aves_app.dart'; +import 'package:aves/widgets/common/action_controls/togglers/title_search.dart'; +import 'package:aves/widgets/common/app_bar/app_bar_subtitle.dart'; +import 'package:aves/widgets/common/app_bar/app_bar_title.dart'; +import 'package:aves/widgets/common/app_bar/crumb_line.dart'; +import 'package:aves/widgets/common/basic/popup/menu_row.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/aves_app_bar.dart'; +import 'package:aves/widgets/common/identity/buttons/captioned_button.dart'; +import 'package:aves/widgets/common/providers/filter_group_provider.dart'; +import 'package:aves/widgets/common/search/route.dart'; +import 'package:aves/widgets/filter_grids/common/action_delegates/chip_set.dart'; +import 'package:aves/widgets/filter_grids/common/group_crumb_line.dart'; +import 'package:aves/widgets/filter_grids/common/query_bar.dart'; +import 'package:aves/widgets/search/collection_search_delegate.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:provider/provider.dart'; + +typedef ActionsBuilder<T extends CollectionFilter, CSAD extends ChipSetActionDelegate<T>> = List<Widget> Function( + BuildContext context, + AppMode appMode, + Selection<FilterGridItem<T>> selection, + CSAD actionDelegate, +); + +class FilterGridAppBar<T extends CollectionFilter, CSAD extends ChipSetActionDelegate<T>> extends StatefulWidget { + final CollectionSource source; + final String title; + final CSAD actionDelegate; + final ActionsBuilder<T, CSAD>? actionsBuilder; + final bool isEmpty; + final ValueNotifier<double> appBarHeightNotifier; + final ScrollController scrollController; + + const FilterGridAppBar({ + super.key, + required this.source, + required this.title, + required this.actionDelegate, + this.actionsBuilder, + required this.isEmpty, + required this.appBarHeightNotifier, + required this.scrollController, + }); + + @override + State<FilterGridAppBar<T, CSAD>> createState() => _FilterGridAppBarState<T, CSAD>(); + + static PopupMenuEntry<ChipSetAction> toMenuItem(BuildContext context, ChipSetAction action, {required bool enabled}) { + late Widget child; + switch (action) { + case ChipSetAction.toggleTitleSearch: + child = TitleSearchToggler( + queryEnabled: context.read<Query>().enabled, + isMenuItem: true, + ); + default: + child = MenuRow(text: action.getText(context), icon: action.getIcon()); + } + + return PopupMenuItem( + value: action, + enabled: enabled, + child: child, + ); + } +} + +class _FilterGridAppBarState<T extends CollectionFilter, CSAD extends ChipSetActionDelegate<T>> extends State<FilterGridAppBar<T, CSAD>> with RouteAware, SingleTickerProviderStateMixin, WidgetsBindingObserver { + final Set<StreamSubscription> _subscriptions = {}; + late AnimationController _browseToSelectAnimation; + final ValueNotifier<bool> _isSelectingNotifier = ValueNotifier(false); + final FocusNode _queryBarFocusNode = FocusNode(); + late final Listenable _queryFocusRequestNotifier; + + CollectionSource get source => widget.source; + + static const browsingQuickActions = [ + ChipSetAction.search, + ]; + static const selectionQuickActions = [ + ChipSetAction.setCover, + ChipSetAction.pin, + ChipSetAction.unpin, + ]; + + @override + void initState() { + super.initState(); + final query = context.read<Query>(); + _subscriptions.add(query.enabledStream.listen((e) => _updateAppBarHeight())); + _queryFocusRequestNotifier = query.focusRequestNotifier; + _queryFocusRequestNotifier.addListener(_onQueryFocusRequest); + _queryBarFocusNode.addListener(_onQueryBarFocusChanged); + _browseToSelectAnimation = AnimationController( + duration: context.read<DurationsData>().iconAnimation, + vsync: this, + ); + _isSelectingNotifier.addListener(_onActivityChanged); + WidgetsBinding.instance.addObserver(this); + WidgetsBinding.instance.addPostFrameCallback((_) => _updateAppBarHeight()); + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + final route = ModalRoute.of(context); + if (route is PageRoute) { + AvesApp.pageRouteObserver.subscribe(this, route); + } + } + + @override + void dispose() { + _queryBarFocusNode.dispose(); + _queryFocusRequestNotifier.removeListener(_onQueryFocusRequest); + _queryBarFocusNode.removeListener(_onQueryBarFocusChanged); + _isSelectingNotifier.dispose(); + _browseToSelectAnimation.dispose(); + _subscriptions + ..forEach((sub) => sub.cancel()) + ..clear(); + WidgetsBinding.instance.removeObserver(this); + AvesApp.pageRouteObserver.unsubscribe(this); + super.dispose(); + } + + @override + void didPushNext() { + // unfocus when navigating away, so that when navigating back, + // the query bar does not get back focus and bring the keyboard + _queryBarFocusNode.unfocus(); + } + + @override + void didChangeMetrics() { + // when text scale factor changes + _updateAppBarHeight(); + } + + @override + Widget build(BuildContext context) { + final appMode = context.watch<ValueNotifier<AppMode>>().value; + final selection = context.watch<Selection<FilterGridItem<T>>>(); + final isSelecting = selection.isSelecting; + _isSelectingNotifier.value = isSelecting; + return NotificationListener<ScrollNotification>( + // cancel notification bubbling so that the draggable scroll bar + // does not misinterpret filter bar scrolling for collection scrolling + onNotification: (notification) => true, + child: Selector<Query, bool>( + selector: (context, query) => query.enabled, + builder: (context, queryEnabled, child) { + final actionDelegate = widget.actionDelegate; + final ActionsBuilder<T, CSAD> actionsBuilder = widget.actionsBuilder ?? _buildActions; + final useTvLayout = settings.useTvLayout; + return AvesAppBar( + contentHeight: appBarContentHeight, + pinned: context.select<Selection<FilterGridItem<T>>, bool>((selection) => selection.isSelecting), + leading: _buildAppBarLeading( + hasDrawer: appMode.canNavigate, + isSelecting: isSelecting, + ), + title: _buildAppBarTitle(isSelecting), + actions: (context, maxWidth) => useTvLayout ? [] : actionsBuilder(context, appMode, selection, actionDelegate), + bottom: Column( + children: [ + if (useTvLayout) + SizedBox( + height: CaptionedButton.getTelevisionButtonHeight(context), + child: ListView( + padding: const EdgeInsets.symmetric(horizontal: 8), + scrollDirection: Axis.horizontal, + children: actionsBuilder(context, appMode, selection, actionDelegate), + ), + ), + if (_showGroupCrumbLine(context)) + LayoutBuilder( + builder: (context, constraints) { + return Container( + padding: CrumbLine.padding, + width: constraints.maxWidth, + height: CrumbLine.getPreferredHeight(MediaQuery.textScalerOf(context)), + child: Selector<FilterGroupNotifier, Uri?>( + selector: (context, notifier) => notifier.value, + builder: (context, groupUri, child) { + return FilterGroupCrumbLine( + key: const Key('crumbs'), + groupUri: groupUri, + onTap: (uri) => context.read<FilterGroupNotifier?>()?.value = uri, + ); + }, + ), + ); + }, + ), + if (queryEnabled) + FilterQueryBar<T>( + queryNotifier: context.select<Query, ValueNotifier<String>>((query) => query.queryNotifier), + focusNode: _queryBarFocusNode, + ), + ], + ), + transitionKey: isSelecting, + ); + }, + ), + ); + } + + bool _showGroupCrumbLine(BuildContext context) => context.read<FilterGrouping?>()?.isNotEmpty ?? false; + + double get appBarContentHeight { + final textScaler = MediaQuery.textScalerOf(context); + double height = textScaler.scale(kToolbarHeight); + if (settings.useTvLayout) { + height += CaptionedButton.getTelevisionButtonHeight(context); + } + if (_showGroupCrumbLine(context)) { + height += CrumbLine.getPreferredHeight(textScaler); + } + if (context.read<Query>().enabled) { + height += FilterQueryBar.getPreferredHeight(textScaler); + } + return height; + } + + Widget? _buildAppBarLeading({required bool hasDrawer, required bool isSelecting}) { + if (settings.useTvLayout) return null; + + if (!hasDrawer) { + return const CloseButton(); + } + + VoidCallback? onPressed; + String? tooltip; + if (isSelecting) { + onPressed = () => context.read<Selection<FilterGridItem<T>>>().browse(); + tooltip = MaterialLocalizations.of(context).backButtonTooltip; + } else { + onPressed = Scaffold.of(context).openDrawer; + tooltip = MaterialLocalizations.of(context).openAppDrawerTooltip; + } + return IconButton( + // key is expected by test driver + key: const Key('appbar-leading-button'), + icon: AnimatedIcon( + icon: AnimatedIcons.menu_arrow, + progress: _browseToSelectAnimation, + ), + onPressed: onPressed, + tooltip: tooltip, + ); + } + + Widget _buildAppBarTitle(bool isSelecting) { + if (isSelecting) { + final l10n = context.l10n; + return Selector<Selection<FilterGridItem<T>>?, int>( + selector: (context, selection) => selection?.selectedItems.length ?? 0, + builder: (context, count, child) => Text( + count == 0 ? l10n.collectionSelectPageTitle : l10n.itemCount(count), + softWrap: false, + overflow: TextOverflow.fade, + maxLines: 1, + ), + ); + } else { + final appMode = context.watch<ValueNotifier<AppMode>>().value; + return InteractiveAppBarTitle( + onTap: appMode.canNavigate ? _goToSearch : null, + child: SourceStateAwareAppBarTitle( + title: Text( + widget.title, + softWrap: false, + overflow: TextOverflow.fade, + maxLines: 1, + ), + source: source, + ), + ); + } + } + + List<Widget> _buildActions( + BuildContext context, + AppMode appMode, + Selection<FilterGridItem<T>> selection, + CSAD actionDelegate, + ) { + final itemCount = actionDelegate.allItems.length; + final isSelecting = selection.isSelecting; + final selectedItems = selection.selectedItems; + final selectedFilters = selectedItems.map((v) => v.filter).toSet(); + + bool isVisible(ChipSetAction action) => actionDelegate.isVisible( + action, + appMode: appMode, + isSelecting: isSelecting, + itemCount: itemCount, + selectedFilters: selectedFilters, + ); + bool canApply(ChipSetAction action) => actionDelegate.canApply( + action, + isSelecting: isSelecting, + itemCount: itemCount, + selectedFilters: selectedFilters, + ); + + return settings.useTvLayout + ? _buildTelevisionActions( + context: context, + selection: selection, + isVisible: isVisible, + canApply: canApply, + actionDelegate: actionDelegate, + ) + : _buildMobileActions( + context: context, + selection: selection, + isVisible: isVisible, + canApply: canApply, + actionDelegate: actionDelegate, + ); + } + + List<Widget> _buildTelevisionActions({ + required BuildContext context, + required Selection<FilterGridItem<T>> selection, + required bool Function(ChipSetAction action) isVisible, + required bool Function(ChipSetAction action) canApply, + required CSAD actionDelegate, + }) { + final isSelecting = selection.isSelecting; + + return [ + ...ChipSetActions.general, + ...isSelecting ? ChipSetActions.selection : ChipSetActions.browsing, + ].nonNulls.where(isVisible).map((action) { + final enabled = canApply(action); + return CaptionedButton( + iconButtonBuilder: (context, focusNode) => _buildButtonIcon( + context, + actionDelegate, + action, + enabled: enabled, + focusNode: focusNode, + ), + captionText: _buildButtonCaption(context, action, enabled: enabled), + onPressed: enabled ? () => _onActionSelected(context, action, actionDelegate) : null, + ); + }).toList(); + } + + List<Widget> _buildMobileActions({ + required BuildContext context, + required Selection<FilterGridItem<T>> selection, + required bool Function(ChipSetAction action) isVisible, + required bool Function(ChipSetAction action) canApply, + required CSAD actionDelegate, + }) { + final isSelecting = selection.isSelecting; + + final quickActionButtons = (isSelecting ? selectionQuickActions : browsingQuickActions).where(isVisible).map( + (action) => _buildButtonIcon(context, actionDelegate, action, enabled: canApply(action)), + ); + + final animations = context.select<Settings, AccessibilityAnimations>((v) => v.accessibilityAnimations); + return [ + ...quickActionButtons, + PopupMenuButton<ChipSetAction>( + itemBuilder: (context) { + final generalMenuItems = ChipSetActions.general.where(isVisible).map( + (action) => FilterGridAppBar.toMenuItem(context, action, enabled: canApply(action)), + ); + + final browsingMenuActions = ChipSetActions.browsing.where((v) => !browsingQuickActions.contains(v)); + final selectionMenuActions = ChipSetActions.selection.where((v) => !selectionQuickActions.contains(v)); + final contextualMenuActions = (isSelecting ? selectionMenuActions : browsingMenuActions).where((v) => v == null || isVisible(v)).fold(<ChipSetAction?>[], (prev, v) { + if (v == null && (prev.isEmpty || prev.last == null)) return prev; + return [...prev, v]; + }); + if (contextualMenuActions.isNotEmpty && contextualMenuActions.last == null) { + contextualMenuActions.removeLast(); + } + + return [ + ...generalMenuItems, + if (contextualMenuActions.isNotEmpty) ...[ + const PopupMenuDivider(), + ...contextualMenuActions.map( + (action) { + if (action == null) return const PopupMenuDivider(); + return FilterGridAppBar.toMenuItem(context, action, enabled: canApply(action)); + }, + ), + ], + ]; + }, + onSelected: (action) async { + // remove focus, if any, to prevent the keyboard from showing up + // after the user is done with the popup menu + FocusManager.instance.primaryFocus?.unfocus(); + + // wait for the popup menu to hide before proceeding with the action + await Future.delayed(animations.popUpAnimationDelay * timeDilation); + _onActionSelected(context, action, actionDelegate); + }, + popUpAnimationStyle: animations.popUpAnimationStyle, + ), + ]; + } + + Widget _buildButtonIcon( + BuildContext context, + CSAD actionDelegate, + ChipSetAction action, { + required bool enabled, + FocusNode? focusNode, + }) { + final onPressed = enabled ? () => _onActionSelected(context, action, actionDelegate) : null; + switch (action) { + case ChipSetAction.toggleTitleSearch: + // `Query` may not be available during hero + return Selector<Query?, bool>( + selector: (context, query) => query?.enabled ?? false, + builder: (context, queryEnabled, child) { + return TitleSearchToggler( + queryEnabled: queryEnabled, + focusNode: focusNode, + onPressed: onPressed, + ); + }, + ); + default: + return IconButton( + icon: action.getIcon(), + onPressed: onPressed, + focusNode: focusNode, + tooltip: action.getText(context), + ); + } + } + + Widget _buildButtonCaption( + BuildContext context, + ChipSetAction action, { + required bool enabled, + }) { + switch (action) { + case ChipSetAction.toggleTitleSearch: + return TitleSearchTogglerCaption( + enabled: enabled, + ); + default: + return CaptionedButtonText( + text: action.getText(context), + enabled: enabled, + ); + } + } + + void _onActivityChanged() { + if (context.read<Selection<FilterGridItem<T>>>().isSelecting) { + _browseToSelectAnimation.forward(); + } else { + _browseToSelectAnimation.reverse(); + } + } + + void _onQueryFocusRequest() => _queryBarFocusNode.requestFocus(); + + void _onQueryBarFocusChanged() { + if (_queryBarFocusNode.hasFocus) { + // the query bar is in the top sliver of the page scrollable, + // so when the bar text field gets focus and requests to be on screen, + // it will scroll to show it by default, but it may not end at the very top, + // so we do it manually for a more predicable end position + _scrollToTop(); + } + } + + void _scrollToTop() => widget.scrollController.jumpTo(0); + + void _updateAppBarHeight() { + widget.appBarHeightNotifier.value = AvesAppBar.appBarHeightForContentHeight(appBarContentHeight); + } + + void _onActionSelected(BuildContext context, ChipSetAction action, ChipSetActionDelegate<T> actionDelegate) { + actionDelegate.onActionSelected(context, action); + } + + void _goToSearch() { + Navigator.maybeOf(context)?.push( + SearchPageRoute( + delegate: CollectionSearchDelegate( + searchFieldLabel: context.l10n.searchCollectionFieldHint, + searchFieldStyle: Themes.searchFieldStyle(context), + source: source, + ), + ), + ); + } +} diff --git a/lib/widgets/filter_grids/common/covered_filter_chip.dart b/lib/widgets/filter_grids/common/covered_filter_chip.dart new file mode 100644 index 0000000..a609778 --- /dev/null +++ b/lib/widgets/filter_grids/common/covered_filter_chip.dart @@ -0,0 +1,253 @@ +import 'dart:math'; + +import 'package:aves/model/app_inventory.dart'; +import 'package:aves/model/covers.dart'; +import 'package:aves/model/filters/container/album_group.dart'; +import 'package:aves/model/filters/container/dynamic_album.dart'; +import 'package:aves/model/filters/container/tag_group.dart'; +import 'package:aves/model/filters/covered/location.dart'; +import 'package:aves/model/filters/covered/stored_album.dart'; +import 'package:aves/model/filters/covered/tag.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/grouping/common.dart'; +import 'package:aves/model/source/album.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/model/source/location/country.dart'; +import 'package:aves/model/source/tag.dart'; +import 'package:aves/model/vaults/vaults.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/theme/text.dart'; +import 'package:aves/utils/android_file_utils.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/aves_filter_chip.dart'; +import 'package:aves/widgets/common/thumbnail/image.dart'; +import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; +import 'package:provider/provider.dart'; + +class CoveredFilterChip<T extends CollectionFilter> extends StatelessWidget { + final T filter; + final double extent, thumbnailExtent; + final bool showText, pinned, locked; + final String? banner; + final AFilterCallback? onTap; + final HeroType heroType; + + const CoveredFilterChip({ + super.key, + required this.filter, + required this.extent, + double? thumbnailExtent, + this.showText = true, + this.pinned = false, + required this.locked, + this.banner, + this.onTap, + this.heroType = HeroType.onTap, + }) : thumbnailExtent = thumbnailExtent ?? extent; + + static double tileHeight({required double extent, required TextScaler textScaler, required bool showText}) { + return extent + infoHeight(extent: extent, textScaler: textScaler, showText: showText); + } + + // info includes title and content details + static double infoHeight({required double extent, required TextScaler textScaler, required bool showText}) { + if (!showText) return 0; + + // height can actually be a little larger or smaller, when info includes icons or non-latin scripts + // but it's not worth measuring text metrics, as the widget is flexible enough to absorb the difference + return textScaler.scale(AvesFilterChip.fontSize + detailFontSize(extent) + 4) + AvesFilterChip.decoratedContentVerticalPadding * 2; + } + + static Radius radius(double extent) => Radius.circular(min<double>(AvesFilterChip.defaultRadius, extent / 4)); + + static double detailIconSize(double extent) => min<double>(AvesFilterChip.fontSize, extent / 7); + + static double detailFontSize(double extent) => min<double>(AvesFilterChip.fontSize, extent / 7); + + static double detailIconPadding(double extent) => min<double>(8.0, extent / 16); + + static double detailIconTextPadding(double extent) => detailIconPadding(extent) / 2; + + @override + Widget build(BuildContext context) { + return StreamBuilder<Set<CollectionFilter>?>( + stream: covers.entryChangeStream.where((event) => event == null || event.contains(filter)), + builder: (context, snapshot) => Consumer<CollectionSource>( + builder: (context, source, child) { + switch (filter) { + case StoredAlbumFilter filter: + { + final album = filter.album; + return StreamBuilder<StoredAlbumSummaryInvalidatedEvent>( + stream: source.eventBus.on<StoredAlbumSummaryInvalidatedEvent>().where((event) => event.directories == null || event.directories!.contains(album)), + builder: (context, snapshot) => _buildChip(context, source), + ); + } + case DynamicAlbumFilter _: + { + return StreamBuilder<DynamicAlbumSummaryInvalidatedEvent>( + stream: source.eventBus.on<DynamicAlbumSummaryInvalidatedEvent>(), + builder: (context, snapshot) => _buildChip(context, source), + ); + } + case AlbumGroupFilter _: + { + return StreamBuilder<AlbumGroupSummaryInvalidatedEvent>( + stream: source.eventBus.on<AlbumGroupSummaryInvalidatedEvent>(), + builder: (context, snapshot) => _buildChip(context, source), + ); + } + case TagGroupFilter _: + { + return StreamBuilder<TagGroupSummaryInvalidatedEvent>( + stream: source.eventBus.on<TagGroupSummaryInvalidatedEvent>(), + builder: (context, snapshot) => _buildChip(context, source), + ); + } + case LocationFilter filter: + { + final countryCode = filter.code; + return StreamBuilder<CountrySummaryInvalidatedEvent>( + stream: source.eventBus.on<CountrySummaryInvalidatedEvent>().where((event) => event.countryCodes == null || event.countryCodes!.contains(countryCode)), + builder: (context, snapshot) => _buildChip(context, source), + ); + } + case TagFilter filter: + { + final tag = filter.tag; + return StreamBuilder<TagSummaryInvalidatedEvent>( + stream: source.eventBus.on<TagSummaryInvalidatedEvent>().where((event) => event.tags == null || event.tags!.contains(tag)), + builder: (context, snapshot) => _buildChip(context, source), + ); + } + default: + return const SizedBox(); + } + }, + ), + ); + } + + Widget _buildChip(BuildContext context, CollectionSource source) { + final _filter = filter; + final entry = _filter is StoredAlbumFilter && vaults.isLocked(_filter.album) ? null : source.coverEntry(_filter); + final titlePadding = min<double>(4.0, extent / 32); + Key? chipKey; + if (_filter is StoredAlbumFilter) { + // when we asynchronously fetch installed app names, + // album filters themselves do not change, but decoration derived from it does + chipKey = ValueKey(appInventory.areAppNamesReadyNotifier.value); + } + final textScaler = MediaQuery.textScalerOf(context); + return AvesFilterChip( + key: chipKey, + filter: _filter, + showLeading: showText, + showText: showText, + allowGenericIcon: false, + decoration: AvesFilterDecoration( + radius: radius(extent), + widget: Padding( + padding: EdgeInsets.only( + bottom: infoHeight( + extent: extent, + textScaler: textScaler, + showText: showText, + ), + ), + child: entry == null + ? StreamBuilder<Set<CollectionFilter>?>( + stream: covers.colorChangeStream.where((event) => event == null || event.contains(_filter)), + builder: (context, snapshot) { + return FutureBuilder<Color>( + future: _filter.color(context), + builder: (context, snapshot) { + final color = snapshot.data; + const neutral = Colors.white; + return Container( + decoration: BoxDecoration( + gradient: LinearGradient( + begin: Alignment.topLeft, + end: Alignment.bottomRight, + colors: [ + neutral, + color ?? neutral, + ], + ), + ), + ); + }, + ); + }, + ) + : ThumbnailImage( + entry: entry, + extent: thumbnailExtent, + devicePixelRatio: MediaQuery.devicePixelRatioOf(context), + ), + ), + ), + banner: banner, + details: showText ? _buildDetails(context, source, _filter) : null, + padding: titlePadding, + heroType: heroType, + onTap: onTap, + onLongPress: null, + ); + } + + Color _detailColor(BuildContext context) => Theme.of(context).colorScheme.onSurfaceVariant; + + Widget _buildDetails(BuildContext context, CollectionSource source, T filter) { + final textStyle = TextStyle( + color: _detailColor(context), + fontSize: detailFontSize(extent), + ); + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (pinned) _buildDetailIcon(context, AIcons.pin), + if (filter is StoredAlbumFilter && androidFileUtils.isOnRemovableStorage(filter.album)) _buildDetailIcon(context, AIcons.storageCard), + if (filter is StoredAlbumFilter && vaults.isVault(filter.album)) _buildDetailIcon(context, AIcons.locked), + if (filter is DynamicAlbumFilter) _buildDetailIcon(context, AIcons.dynamicAlbum), + if (filter is AlbumGroupFilter) ...[ + _buildDetailIcon(context, AIcons.album, padding: detailIconTextPadding(extent)), + Text( + '${NumberFormat.decimalPattern(context.locale).format(albumGrouping.countLeaves(filter.uri))}${AText.separator}', + style: textStyle, + ), + ], + if (filter is TagGroupFilter) ...[ + _buildDetailIcon(context, AIcons.tag, padding: detailIconTextPadding(extent)), + Text( + '${NumberFormat.decimalPattern(context.locale).format(tagGrouping.countLeaves(filter.uri))}${AText.separator}', + style: textStyle, + ), + ], + Flexible( + child: Text( + locked ? AText.valueNotAvailable : NumberFormat.decimalPattern(context.locale).format(source.count(filter)), + style: textStyle, + softWrap: false, + overflow: TextOverflow.fade, + maxLines: 1, + ), + ), + ], + ); + } + + Widget _buildDetailIcon(BuildContext context, IconData icon, {double? padding}) { + return AnimatedPadding( + padding: EdgeInsetsDirectional.only(end: padding ?? detailIconPadding(extent)), + duration: ADurations.chipDecorationAnimation, + child: Icon( + icon, + color: _detailColor(context), + size: detailIconSize(extent), + ), + ); + } +} diff --git a/lib/widgets/filter_grids/common/draggable_thumb_label.dart b/lib/widgets/filter_grids/common/draggable_thumb_label.dart new file mode 100644 index 0000000..bff3488 --- /dev/null +++ b/lib/widgets/filter_grids/common/draggable_thumb_label.dart @@ -0,0 +1,47 @@ +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/utils/file_utils.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/grid/draggable_thumb_label.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class FilterDraggableThumbLabel<T extends CollectionFilter> extends StatelessWidget { + final ChipSortFactor sortFactor; + final double offsetY; + + const FilterDraggableThumbLabel({ + super.key, + required this.sortFactor, + required this.offsetY, + }); + + @override + Widget build(BuildContext context) { + return DraggableThumbLabel<FilterGridItem<T>>( + offsetY: offsetY, + lineBuilder: (context, filterGridItem) { + switch (sortFactor) { + case ChipSortFactor.date: + return [ + DraggableThumbLabel.formatMonthThumbLabel(context, filterGridItem.entry?.bestDate), + ]; + case ChipSortFactor.name: + case ChipSortFactor.path: + return [ + filterGridItem.filter.getLabel(context), + ]; + case ChipSortFactor.count: + return [ + context.l10n.itemCount(context.read<CollectionSource>().count(filterGridItem.filter)), + ]; + case ChipSortFactor.size: + return [ + formatFileSize(context.locale, context.read<CollectionSource>().size(filterGridItem.filter)), + ]; + } + }, + ); + } +} diff --git a/lib/widgets/filter_grids/common/enums.dart b/lib/widgets/filter_grids/common/enums.dart new file mode 100644 index 0000000..806e640 --- /dev/null +++ b/lib/widgets/filter_grids/common/enums.dart @@ -0,0 +1,59 @@ +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:flutter/material.dart'; + +enum ChipType { regular, group } + +enum AlbumChipType { stored, dynamic, group } + +enum AlbumImportance { newAlbum, pinned, group, special, apps, vaults, dynamic, regular } + +extension ExtraAlbumImportance on AlbumImportance { + String getText(BuildContext context) { + final l10n = context.l10n; + return switch (this) { + AlbumImportance.newAlbum => l10n.albumTierNew, + AlbumImportance.pinned => l10n.albumTierPinned, + AlbumImportance.group => l10n.albumTierGroups, + AlbumImportance.special => l10n.albumTierSpecial, + AlbumImportance.apps => l10n.albumTierApps, + AlbumImportance.vaults => l10n.albumTierVaults, + AlbumImportance.dynamic => l10n.albumTierDynamic, + AlbumImportance.regular => l10n.albumTierRegular, + }; + } + + IconData getIcon() { + return switch (this) { + AlbumImportance.newAlbum => AIcons.newTier, + AlbumImportance.pinned => AIcons.pin, + AlbumImportance.group => AIcons.group, + AlbumImportance.special => AIcons.important, + AlbumImportance.apps => AIcons.app, + AlbumImportance.vaults => AIcons.locked, + AlbumImportance.dynamic => AIcons.dynamicAlbum, + AlbumImportance.regular => AIcons.album, + }; + } +} + +enum AlbumMimeType { images, videos, mixed } + +extension ExtraAlbumMimeType on AlbumMimeType { + String getText(BuildContext context) { + final l10n = context.l10n; + return switch (this) { + AlbumMimeType.images => l10n.drawerCollectionImages, + AlbumMimeType.videos => l10n.drawerCollectionVideos, + AlbumMimeType.mixed => l10n.albumMimeTypeMixed, + }; + } + + IconData getIcon() { + return switch (this) { + AlbumMimeType.images => AIcons.image, + AlbumMimeType.videos => AIcons.video, + AlbumMimeType.mixed => AIcons.mimeType, + }; + } +} diff --git a/lib/widgets/filter_grids/common/filter_chip_grid_decorator.dart b/lib/widgets/filter_grids/common/filter_chip_grid_decorator.dart new file mode 100644 index 0000000..1ed8368 --- /dev/null +++ b/lib/widgets/filter_grids/common/filter_chip_grid_decorator.dart @@ -0,0 +1,48 @@ +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/widgets/common/grid/overlay.dart'; +import 'package:aves/widgets/filter_grids/common/covered_filter_chip.dart'; +import 'package:aves/widgets/filter_grids/common/overlay.dart'; +import 'package:flutter/widgets.dart'; + +class FilterChipGridDecorator<T extends CollectionFilter, U extends FilterGridItem<T>> extends StatelessWidget { + final U gridItem; + final double extent; + final bool selectable, highlightable; + final Widget child; + + const FilterChipGridDecorator({ + super.key, + required this.gridItem, + required this.extent, + this.selectable = true, + this.highlightable = true, + required this.child, + }); + + @override + Widget build(BuildContext context) { + final borderRadius = BorderRadius.all(CoveredFilterChip.radius(extent)); + return SizedBox( + width: extent, + height: extent, + child: Stack( + fit: StackFit.passthrough, + children: [ + child, + if (selectable) + GridItemSelectionOverlay<FilterGridItem<T>>( + item: gridItem, + borderRadius: borderRadius, + padding: EdgeInsets.all(extent / 24), + ), + if (highlightable) + ChipHighlightOverlay( + filter: gridItem.filter, + extent: extent, + borderRadius: borderRadius, + ), + ], + ), + ); + } +} diff --git a/lib/widgets/filter_grids/common/filter_grid_page.dart b/lib/widgets/filter_grids/common/filter_grid_page.dart new file mode 100644 index 0000000..ec28225 --- /dev/null +++ b/lib/widgets/filter_grids/common/filter_grid_page.dart @@ -0,0 +1,764 @@ +import 'dart:async'; + +import 'package:aves/app_mode.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/grouping/common.dart'; +import 'package:aves/model/highlight.dart'; +import 'package:aves/model/query.dart'; +import 'package:aves/model/selection.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/model/vaults/vaults.dart'; +import 'package:aves/theme/colors.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/widgets/collection/loading.dart'; +import 'package:aves/widgets/common/basic/draggable_scrollbar/notifications.dart'; +import 'package:aves/widgets/common/basic/draggable_scrollbar/scrollbar.dart'; +import 'package:aves/widgets/common/basic/insets.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/behaviour/pop/double_back.dart'; +import 'package:aves/widgets/common/behaviour/pop/scope.dart'; +import 'package:aves/widgets/common/behaviour/pop/tv_navigation.dart'; +import 'package:aves/widgets/common/behaviour/sloppy_scroll_physics.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/extensions/media_query.dart'; +import 'package:aves/widgets/common/grid/item_tracker.dart'; +import 'package:aves/widgets/common/grid/scaling.dart'; +import 'package:aves/widgets/common/grid/sections/fixed/scale_grid.dart'; +import 'package:aves/widgets/common/grid/sections/list_layout.dart'; +import 'package:aves/widgets/common/grid/selector.dart'; +import 'package:aves/widgets/common/grid/sliver.dart'; +import 'package:aves/widgets/common/grid/theme.dart'; +import 'package:aves/widgets/common/identity/aves_filter_chip.dart'; +import 'package:aves/widgets/common/identity/scroll_thumb.dart'; +import 'package:aves/widgets/common/providers/filter_group_provider.dart'; +import 'package:aves/widgets/common/providers/tile_extent_controller_provider.dart'; +import 'package:aves/widgets/common/thumbnail/image.dart'; +import 'package:aves/widgets/common/tile_extent_controller.dart'; +import 'package:aves/widgets/filter_grids/common/covered_filter_chip.dart'; +import 'package:aves/widgets/filter_grids/common/draggable_thumb_label.dart'; +import 'package:aves/widgets/filter_grids/common/filter_tile.dart'; +import 'package:aves/widgets/filter_grids/common/list_details_theme.dart'; +import 'package:aves/widgets/filter_grids/common/section_keys.dart'; +import 'package:aves/widgets/filter_grids/common/section_layout.dart'; +import 'package:aves/widgets/navigation/drawer/app_drawer.dart'; +import 'package:aves/widgets/navigation/nav_bar/nav_bar.dart'; +import 'package:aves/widgets/navigation/tv_rail.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_staggered_animations/flutter_staggered_animations.dart'; +import 'package:provider/provider.dart'; + +typedef QueryTest<T extends CollectionFilter> = List<FilterGridItem<T>> Function(BuildContext context, List<FilterGridItem<T>> filters, String query); + +class FilterGridPage<T extends CollectionFilter> extends StatelessWidget { + final String? settingsRouteKey; + final Widget appBar; + final ValueNotifier<double> appBarHeightNotifier; + final ScrollController scrollController; + final Map<ChipSectionKey, List<FilterGridItem<T>>> sections; + final Set<T> newFilters; + final ChipSortFactor sortFactor; + final bool showHeaders, selectable; + final Widget Function() emptyBuilder; + final HeroType heroType; + final Widget? floatingActionButton; + final FilterTileTapCallback<T> onTileTap; + final StreamController<DraggableScrollbarEvent> _draggableScrollBarEventStreamController = StreamController.broadcast(); + + FilterGridPage({ + super.key, + this.settingsRouteKey, + required this.appBar, + required this.appBarHeightNotifier, + required this.scrollController, + required this.sections, + required this.newFilters, + required this.sortFactor, + required this.showHeaders, + required this.selectable, + required this.emptyBuilder, + required this.heroType, + this.floatingActionButton, + required this.onTileTap, + }); + + @override + Widget build(BuildContext context) { + final useTvLayout = settings.useTvLayout; + final body = GestureAreaProtectorStack( + child: DirectionalSafeArea( + start: !useTvLayout, + top: false, + bottom: false, + child: ValueListenableBuilder<double>( + valueListenable: appBarHeightNotifier, + builder: (context, appBarHeight, child) { + return _FilterGrid<T>( + // key is expected by test driver + key: const Key('filter-grid'), + settingsRouteKey: settingsRouteKey, + appBar: appBar, + appBarHeight: MediaQuery.paddingOf(context).top + appBarHeight, + scrollController: scrollController, + sections: sections, + newFilters: newFilters, + sortFactor: sortFactor, + showHeaders: showHeaders, + selectable: selectable, + emptyBuilder: emptyBuilder, + heroType: heroType, + onTileTap: onTileTap, + ); + }, + ), + ), + ); + + if (useTvLayout) { + final canNavigate = context.select<ValueNotifier<AppMode>, bool>((v) => v.value.canNavigate); + return AvesScaffold( + body: canNavigate + ? Row( + children: [ + TvRail( + controller: context.read<TvRailController>(), + ), + Expanded(child: body), + ], + ) + : DirectionalSafeArea( + top: false, + end: false, + bottom: false, + child: body, + ), + resizeToAvoidBottomInset: false, + extendBody: true, + ); + } else { + return Selector<Settings, bool>( + selector: (context, s) => s.enableBottomNavigationBar, + builder: (context, enableBottomNavigationBar, child) { + final canNavigate = context.select<ValueNotifier<AppMode>, bool>((v) => v.value.canNavigate); + final showBottomNavigationBar = canNavigate && enableBottomNavigationBar; + + return NotificationListener<DraggableScrollbarNotification>( + onNotification: (notification) { + _draggableScrollBarEventStreamController.add(notification.event); + return false; + }, + child: AvesScaffold( + body: body, + floatingActionButton: floatingActionButton, + drawer: canNavigate ? const AppDrawer() : null, + bottomNavigationBar: showBottomNavigationBar + ? AppBottomNavBar( + events: _draggableScrollBarEventStreamController.stream, + ) + : null, + resizeToAvoidBottomInset: false, + extendBody: true, + ), + ); + }, + ); + } + } +} + +class _FilterGrid<T extends CollectionFilter> extends StatefulWidget { + final String? settingsRouteKey; + final Widget appBar; + final double appBarHeight; + final ScrollController scrollController; + final Map<ChipSectionKey, List<FilterGridItem<T>>> sections; + final Set<T> newFilters; + final ChipSortFactor sortFactor; + final bool showHeaders, selectable; + final Widget Function() emptyBuilder; + final HeroType heroType; + final FilterTileTapCallback<T> onTileTap; + + const _FilterGrid({ + super.key, + required this.settingsRouteKey, + required this.appBar, + required this.appBarHeight, + required this.scrollController, + required this.sections, + required this.newFilters, + required this.sortFactor, + required this.showHeaders, + required this.selectable, + required this.emptyBuilder, + required this.heroType, + required this.onTileTap, + }); + + @override + State<_FilterGrid<T>> createState() => _FilterGridState<T>(); +} + +class _FilterGridState<T extends CollectionFilter> extends State<_FilterGrid<T>> { + TileExtentController? _tileExtentController; + + @override + void dispose() { + _tileExtentController?.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + _tileExtentController ??= TileExtentController( + settingsRouteKey: widget.settingsRouteKey ?? context.currentRouteName!, + columnCountDefault: settings.useTvLayout ? 4 : 3, + extentMin: 60, + extentMax: 300, + spacing: 8, + horizontalPadding: 2, + ); + return AvesPopScope( + handlers: [ + APopHandler( + canPop: (context) => context.select<Selection<FilterGridItem<T>>, bool>((v) => !v.isSelecting), + onPopBlocked: (context) => context.read<Selection<FilterGridItem<T>>>().browse(), + ), + APopHandler( + canPop: (context) => context.read<FilterGroupNotifier?>()?.value == null, + onPopBlocked: (context) { + final filterGroupNotifier = context.read<FilterGroupNotifier>(); + filterGroupNotifier.value = FilterGrouping.getParentGroup(filterGroupNotifier.value); + }, + ), + tvNavigationPopHandler, + doubleBackPopHandler, + ], + child: TileExtentControllerProvider( + controller: _tileExtentController!, + child: _FilterGridContent<T>( + appBar: widget.appBar, + appBarHeight: widget.appBarHeight, + scrollController: widget.scrollController, + sections: widget.sections, + newFilters: widget.newFilters, + sortFactor: widget.sortFactor, + showHeaders: widget.showHeaders, + selectable: widget.selectable, + emptyBuilder: widget.emptyBuilder, + heroType: widget.heroType, + onTileTap: widget.onTileTap, + ), + ), + ); + } +} + +class _FilterGridContent<T extends CollectionFilter> extends StatefulWidget { + final Widget appBar; + final double appBarHeight; + final ScrollController scrollController; + final Map<ChipSectionKey, List<FilterGridItem<T>>> sections; + final Set<T> newFilters; + final ChipSortFactor sortFactor; + final bool showHeaders, selectable; + final Widget Function() emptyBuilder; + final HeroType heroType; + final FilterTileTapCallback<T> onTileTap; + + const _FilterGridContent({ + super.key, + required this.appBar, + required this.appBarHeight, + required this.scrollController, + required this.sections, + required this.newFilters, + required this.sortFactor, + required this.showHeaders, + required this.selectable, + required this.emptyBuilder, + required this.heroType, + required this.onTileTap, + }); + + @override + State<_FilterGridContent<T>> createState() => _FilterGridContentState<T>(); +} + +class _FilterGridContentState<T extends CollectionFilter> extends State<_FilterGridContent<T>> { + final ValueNotifier<double> _appBarHeightNotifier = ValueNotifier(0); + final ValueNotifier<FilterGridItem<T>?> _focusedItemNotifier = ValueNotifier(null); + + @override + void didUpdateWidget(covariant _FilterGridContent<T> oldWidget) { + super.didUpdateWidget(oldWidget); + _appBarHeightNotifier.value = widget.appBarHeight; + } + + @override + void dispose() { + _appBarHeightNotifier.dispose(); + _focusedItemNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final source = context.read<CollectionSource>(); + final settingsRouteKey = context.read<TileExtentController>().settingsRouteKey; + final tileLayout = context.select<Settings, TileLayout>((v) => v.getTileLayout(settingsRouteKey)); + return Selector<Query, bool>( + selector: (context, query) => query.enabled, + builder: (context, queryEnabled, child) { + return ValueListenableBuilder<String>( + valueListenable: context.select<Query, ValueNotifier<String>>((query) => query.queryNotifier), + builder: (context, query, child) { + Map<ChipSectionKey, List<FilterGridItem<T>>> visibleSections; + if (queryEnabled && query.isNotEmpty) { + visibleSections = {}; + final queryUp = query.toUpperCase(); + widget.sections.forEach((sectionKey, sectionFilters) { + final visibleFilters = sectionFilters.where((item) => item.filter.matchLabel(context, queryUp)).toList(); + if (visibleFilters.isNotEmpty) { + visibleSections[sectionKey] = visibleFilters; + } + }); + } else { + visibleSections = widget.sections; + } + + final sectionedListLayoutProvider = ValueListenableBuilder<double>( + valueListenable: context.select<TileExtentController, ValueNotifier<double>>((controller) => controller.extentNotifier), + builder: (context, thumbnailExtent, child) { + return Selector<TileExtentController, (double, int, double, double)>( + selector: (context, c) => (c.viewportSize.width, c.columnCount, c.spacing, c.horizontalPadding), + builder: (context, c, child) { + final (scrollableWidth, columnCount, tileSpacing, horizontalPadding) = c; + // do not listen for animation delay change + final target = context.read<DurationsData>().staggeredAnimationPageTarget; + final tileAnimationDelay = context.read<TileExtentController>().getTileAnimationDelay(target); + + final textScaler = MediaQuery.textScalerOf(context); + final tileHeight = CoveredFilterChip.tileHeight( + extent: thumbnailExtent, + textScaler: textScaler, + showText: tileLayout != TileLayout.list, + ); + return GridTheme( + extent: thumbnailExtent, + child: FilterListDetailsTheme( + extent: thumbnailExtent, + child: AnimatedBuilder( + animation: vaults, + builder: (context, child) { + return SectionedFilterListLayoutProvider<T>( + sections: visibleSections, + showHeaders: widget.showHeaders, + selectable: widget.selectable, + tileLayout: tileLayout, + scrollableWidth: scrollableWidth, + columnCount: columnCount, + spacing: tileSpacing, + horizontalPadding: horizontalPadding, + tileWidth: thumbnailExtent, + tileHeight: tileHeight, + tileBuilder: (gridItem, tileSize) { + final extent = tileSize.shortestSide; + final tile = InteractiveFilterTile( + gridItem: gridItem, + chipExtent: extent, + thumbnailExtent: extent, + tileLayout: tileLayout, + banner: _getFilterBanner(context, gridItem.filter), + heroType: widget.heroType, + onTap: widget.onTileTap, + ); + if (!settings.useTvLayout) return tile; + + return Focus( + onFocusChange: (focused) { + if (focused) { + _focusedItemNotifier.value = gridItem; + } else if (_focusedItemNotifier.value == gridItem) { + _focusedItemNotifier.value = null; + } + }, + child: ValueListenableBuilder<FilterGridItem<T>?>( + valueListenable: _focusedItemNotifier, + builder: (context, focusedItem, child) { + return AnimatedScale( + scale: focusedItem == gridItem ? 1 : .9, + curve: Curves.fastOutSlowIn, + duration: context.select<DurationsData, Duration>((v) => v.tvImageFocusAnimation), + child: child!, + ); + }, + child: tile, + ), + ); + }, + tileAnimationDelay: tileAnimationDelay, + coverRatioResolver: (item) { + final coverEntry = source.coverEntry(item.filter) ?? item.entry; + return coverEntry?.displayAspectRatio ?? 1; + }, + child: child!, + ); + }, + child: child, + ), + ), + ); + }, + child: child, + ); + }, + child: _FilterSectionedContent<T>( + appBar: widget.appBar, + appBarHeightNotifier: _appBarHeightNotifier, + visibleSections: visibleSections, + sortFactor: widget.sortFactor, + selectable: widget.selectable, + emptyBuilder: widget.emptyBuilder, + bannerBuilder: _getFilterBanner, + scrollController: widget.scrollController, + tileLayout: tileLayout, + ), + ); + return sectionedListLayoutProvider; + }, + ); + }, + ); + } + + String? _getFilterBanner(BuildContext context, T filter) { + final isNew = widget.newFilters.contains(filter); + return isNew ? context.l10n.newFilterBanner : null; + } +} + +class _FilterSectionedContent<T extends CollectionFilter> extends StatefulWidget { + final Widget appBar; + final ValueNotifier<double> appBarHeightNotifier; + final Map<ChipSectionKey, List<FilterGridItem<T>>> visibleSections; + final ChipSortFactor sortFactor; + final bool selectable; + final Widget Function() emptyBuilder; + final String? Function(BuildContext context, T filter) bannerBuilder; + final ScrollController scrollController; + final TileLayout tileLayout; + + const _FilterSectionedContent({ + required this.appBar, + required this.appBarHeightNotifier, + required this.visibleSections, + required this.sortFactor, + required this.selectable, + required this.emptyBuilder, + required this.bannerBuilder, + required this.scrollController, + required this.tileLayout, + }); + + @override + State<_FilterSectionedContent<T>> createState() => _FilterSectionedContentState<T>(); +} + +class _FilterSectionedContentState<T extends CollectionFilter> extends State<_FilterSectionedContent<T>> { + Widget get appBar => widget.appBar; + + ValueNotifier<double> get appBarHeightNotifier => widget.appBarHeightNotifier; + + TileLayout get tileLayout => widget.tileLayout; + + Map<ChipSectionKey, List<FilterGridItem<T>>> get visibleSections => widget.visibleSections; + + Widget Function() get emptyBuilder => widget.emptyBuilder; + + ScrollController get scrollController => widget.scrollController; + + final GlobalKey scrollableKey = GlobalKey(debugLabel: 'filter-grid-page-scrollable'); + + FilterGroupNotifier? _groupNotifier; + + @override + void initState() { + super.initState(); + _registerWidget(widget); + WidgetsBinding.instance.addPostFrameCallback((_) => _checkInitHighlight()); + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + _unregisterDependencies(); + _groupNotifier = context.read<FilterGroupNotifier?>(); + _registerDependencies(); + } + + @override + void didUpdateWidget(covariant _FilterSectionedContent<T> oldWidget) { + super.didUpdateWidget(oldWidget); + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + + @override + void dispose() { + _unregisterDependencies(); + _unregisterWidget(widget); + super.dispose(); + } + + void _registerDependencies() { + _groupNotifier?.addListener(_scrollToTop); + } + + void _unregisterDependencies() { + _groupNotifier?.removeListener(_scrollToTop); + } + + void _registerWidget(_FilterSectionedContent<T> widget) { + widget.appBarHeightNotifier.addListener(_onAppBarHeightChanged); + } + + void _unregisterWidget(_FilterSectionedContent<T> widget) { + widget.appBarHeightNotifier.removeListener(_onAppBarHeightChanged); + } + + @override + Widget build(BuildContext context) { + final scrollView = _FilterScrollView<T>( + scrollableKey: scrollableKey, + appBar: appBar, + appBarHeightNotifier: appBarHeightNotifier, + sortFactor: widget.sortFactor, + emptyBuilder: emptyBuilder, + scrollController: scrollController, + ); + + final scaler = _FilterScaler<T>( + scrollableKey: scrollableKey, + appBarHeightNotifier: appBarHeightNotifier, + tileLayout: tileLayout, + bannerBuilder: widget.bannerBuilder, + child: scrollView, + ); + + final selector = GridSelectionGestureDetector<FilterGridItem<T>>( + scrollableKey: scrollableKey, + selectable: context.select<ValueNotifier<AppMode>, bool>((v) => v.value.canSelectFilter) && widget.selectable, + items: visibleSections.values.expand((v) => v).toList(), + scrollController: scrollController, + appBarHeightNotifier: appBarHeightNotifier, + child: scaler, + ); + + return GridItemTracker<FilterGridItem<T>>( + scrollableKey: scrollableKey, + tileLayout: tileLayout, + appBarHeightNotifier: appBarHeightNotifier, + scrollController: scrollController, + child: selector, + ); + } + + void _onAppBarHeightChanged() => setState(() {}); + + Future<void> _checkInitHighlight() async { + final highlightInfo = context.read<HighlightInfo>(); + final filter = highlightInfo.clear(); + if (filter is! T) return; + + final item = visibleSections.values.expand((list) => list).firstWhereOrNull((gridItem) => gridItem.filter == filter); + if (item == null) return; + + await Future.delayed(ADurations.highlightScrollInitDelay); + + final animate = context.read<Settings>().animate; + highlightInfo.trackItem(item, animate: animate, highlightItem: filter); + } + + void _scrollToTop() => widget.scrollController.jumpTo(0); +} + +class _FilterScaler<T extends CollectionFilter> extends StatelessWidget { + final GlobalKey scrollableKey; + final ValueNotifier<double> appBarHeightNotifier; + final TileLayout tileLayout; + final String? Function(BuildContext context, T filter) bannerBuilder; + final Widget child; + + const _FilterScaler({ + required this.scrollableKey, + required this.appBarHeightNotifier, + required this.tileLayout, + required this.bannerBuilder, + required this.child, + }); + + @override + Widget build(BuildContext context) { + final textScaler = MediaQuery.textScalerOf(context); + final (tileSpacing, horizontalPadding) = context.select<TileExtentController, (double, double)>((v) => (v.spacing, v.horizontalPadding)); + final brightness = Theme.of(context).brightness; + return GridScaleGestureDetector<FilterGridItem<T>>( + scrollableKey: scrollableKey, + tileLayout: tileLayout, + heightForWidth: (width) => CoveredFilterChip.tileHeight(extent: width, textScaler: textScaler, showText: true), + gridBuilder: (center, tileSize, child) => CustomPaint( + painter: FixedExtentGridPainter( + tileLayout: tileLayout, + tileCenter: center, + tileSize: tileSize, + spacing: tileSpacing, + horizontalPadding: horizontalPadding, + borderWidth: AvesFilterChip.outlineWidth, + borderRadius: CoveredFilterChip.radius(tileSize.shortestSide), + color: Colors.grey.shade700, + textDirection: Directionality.of(context), + ), + child: child, + ), + scaledItemBuilder: (item, tileSize) => FilterListDetailsTheme( + extent: tileSize.height, + child: FilterTile( + gridItem: item, + chipExtent: tileLayout == TileLayout.grid ? tileSize.width : tileSize.height, + thumbnailExtent: context.read<TileExtentController>().effectiveExtentMax, + tileLayout: tileLayout, + banner: bannerBuilder(context, item.filter), + ), + ), + mosaicItemBuilder: (index, targetExtent) => DecoratedBox( + decoration: BoxDecoration( + color: ThumbnailImage.computeLoadingBackgroundColor(index * 10, brightness).withValues(alpha: .9), + border: Border.all( + color: context.read<AvesColorsData>().neutral, + width: AvesFilterChip.outlineWidth, + ), + borderRadius: BorderRadius.all(CoveredFilterChip.radius(targetExtent)), + ), + ), + highlightItem: (item) => item.filter, + child: child, + ); + } +} + +class _FilterScrollView<T extends CollectionFilter> extends StatelessWidget { + final GlobalKey scrollableKey; + final Widget appBar; + final ValueNotifier<double> appBarHeightNotifier; + final ChipSortFactor sortFactor; + final Widget Function() emptyBuilder; + final ScrollController scrollController; + + const _FilterScrollView({ + required this.scrollableKey, + required this.appBar, + required this.appBarHeightNotifier, + required this.sortFactor, + required this.emptyBuilder, + required this.scrollController, + }); + + @override + Widget build(BuildContext context) { + final scrollView = _buildScrollView(context); + return settings.useTvLayout ? scrollView : _buildDraggableScrollView(scrollView); + } + + Widget _buildDraggableScrollView(Widget scrollView) { + return ValueListenableBuilder<double>( + valueListenable: appBarHeightNotifier, + builder: (context, appBarHeight, child) { + return Selector<MediaQueryData, double>( + selector: (context, mq) => mq.effectiveBottomPadding, + builder: (context, mqPaddingBottom, child) { + return Selector<Settings, bool>( + selector: (context, s) => s.enableBottomNavigationBar, + builder: (context, enableBottomNavigationBar, child) { + final canNavigate = context.select<ValueNotifier<AppMode>, bool>((v) => v.value.canNavigate); + final showBottomNavigationBar = canNavigate && enableBottomNavigationBar; + final navBarHeight = showBottomNavigationBar ? AppBottomNavBar.height : 0; + return DraggableScrollbar( + backgroundColor: Colors.white, + scrollThumbSize: Size(avesScrollThumbWidth, avesScrollThumbHeight), + scrollThumbBuilder: avesScrollThumbBuilder( + height: avesScrollThumbHeight, + backgroundColor: Colors.white, + ), + controller: scrollController, + padding: EdgeInsets.only( + // padding to keep scroll thumb between app bar above and nav bar below + top: appBarHeight, + bottom: navBarHeight + mqPaddingBottom, + ), + labelTextBuilder: (offsetY) => FilterDraggableThumbLabel<T>( + sortFactor: sortFactor, + offsetY: offsetY, + ), + crumbTextBuilder: (offsetY) => const SizedBox(), + child: scrollView, + ); + }, + ); + }, + ); + }, + ); + } + + Widget _buildScrollView(BuildContext context) { + return Selector<SectionedListLayout<FilterGridItem<T>>, bool>( + selector: (context, layout) => layout.sections.isEmpty, + builder: (context, isEmpty, child) { + return CustomScrollView( + key: scrollableKey, + controller: scrollController, + // workaround to prevent scrolling the app bar away + // when there is no content and we use `SliverFillRemaining` + physics: isEmpty + ? const NeverScrollableScrollPhysics() + : SloppyScrollPhysics( + gestureSettings: MediaQuery.gestureSettingsOf(context), + parent: const AlwaysScrollableScrollPhysics(), + ), + slivers: [ + appBar, + AnimationLimiter( + key: ValueKey(context.select<FilterGroupNotifier?, Uri?>((v) => v?.value)), + child: isEmpty + ? SliverFillRemaining( + hasScrollBody: false, + child: _buildEmptyContent(context), + ) + : SectionedListSliver<FilterGridItem<T>>(), + ), + const NavBarPaddingSliver(), + const BottomPaddingSliver(), + const TvTileGridBottomPaddingSliver(), + ], + ); + }, + ); + } + + Widget _buildEmptyContent(BuildContext context) { + final source = context.read<CollectionSource>(); + return ValueListenableBuilder<SourceState>( + valueListenable: source.stateNotifier, + builder: (context, sourceState, child) { + if (sourceState == SourceState.loading) { + return LoadingEmptyContent(source: source); + } + + return emptyBuilder(); + }, + ); + } +} diff --git a/lib/widgets/filter_grids/common/filter_nav_page.dart b/lib/widgets/filter_grids/common/filter_nav_page.dart new file mode 100644 index 0000000..9902091 --- /dev/null +++ b/lib/widgets/filter_grids/common/filter_nav_page.dart @@ -0,0 +1,192 @@ +import 'package:aves/model/filters/container/album_group.dart'; +import 'package:aves/model/filters/container/group_base.dart'; +import 'package:aves/model/filters/covered/stored_album.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/selection.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/utils/time_utils.dart'; +import 'package:aves/widgets/collection/collection_page.dart'; +import 'package:aves/widgets/common/action_mixins/feedback.dart'; +import 'package:aves/widgets/common/action_mixins/vault_aware.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/aves_filter_chip.dart'; +import 'package:aves/widgets/common/providers/filter_group_provider.dart'; +import 'package:aves/widgets/common/providers/query_provider.dart'; +import 'package:aves/widgets/common/providers/selection_provider.dart'; +import 'package:aves/widgets/filter_grids/common/action_delegates/chip_set.dart'; +import 'package:aves/widgets/filter_grids/common/app_bar.dart'; +import 'package:aves/widgets/filter_grids/common/filter_grid_page.dart'; +import 'package:aves/widgets/filter_grids/common/section_keys.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class FilterNavigationPage<T extends CollectionFilter, CSAD extends ChipSetActionDelegate<T>> extends StatefulWidget { + final CollectionSource source; + final String title; + final ChipSortFactor sortFactor; + final bool showHeaders; + final CSAD actionDelegate; + final Map<ChipSectionKey, List<FilterGridItem<T>>> filterSections; + final Set<T>? newFilters; + final Widget Function() emptyBuilder; + + const FilterNavigationPage({ + super.key, + required this.source, + required this.title, + required this.sortFactor, + this.showHeaders = false, + required this.actionDelegate, + required this.filterSections, + this.newFilters, + required this.emptyBuilder, + }); + + @override + State<FilterNavigationPage<T, CSAD>> createState() => _FilterNavigationPageState<T, CSAD>(); + + static int compareFiltersByDate(FilterGridItem<CollectionFilter> a, FilterGridItem<CollectionFilter> b) { + final c = (b.entry?.bestDate ?? epoch).compareTo(a.entry?.bestDate ?? epoch); + return c != 0 ? c : a.filter.compareTo(b.filter); + } + + static int compareFiltersByEntryCount(MapEntry<CollectionFilter, num> a, MapEntry<CollectionFilter, num> b) { + final c = b.value.compareTo(a.value); + return c != 0 ? c : a.key.compareTo(b.key); + } + + static int compareFiltersBySize(MapEntry<CollectionFilter, num> a, MapEntry<CollectionFilter, num> b) { + final c = b.value.compareTo(a.value); + return c != 0 ? c : a.key.compareTo(b.key); + } + + static int compareFiltersByName(FilterGridItem<CollectionFilter> a, FilterGridItem<CollectionFilter> b) { + return a.filter.compareTo(b.filter); + } + + static int compareFiltersByPath<T extends CollectionFilter>(FilterGridItem<T> a, FilterGridItem<T> b) { + if (T == AlbumBaseFilter) { + final filterA = a.filter; + final filterB = b.filter; + final pathA = filterA is StoredAlbumFilter ? filterA.album : ''; + final pathB = filterB is StoredAlbumFilter ? filterB.album : ''; + final c = pathA.compareTo(pathB); + return c != 0 ? c : a.filter.compareTo(b.filter); + } + return 0; + } + + static List<FilterGridItem<T>> sort<T extends CollectionFilter, CSAD extends ChipSetActionDelegate<T>>( + ChipSortFactor sortFactor, + bool reverse, + CollectionSource source, + Set<T> filters, + ) { + List<FilterGridItem<T>> toGridItem(CollectionSource source, Set<T> filters) { + return filters + .map((filter) => FilterGridItem( + filter, + source.recentEntry(filter), + )) + .toList(); + } + + List<FilterGridItem<T>> allMapEntries = []; + switch (sortFactor) { + case ChipSortFactor.name: + allMapEntries = toGridItem(source, filters)..sort(compareFiltersByName); + case ChipSortFactor.date: + allMapEntries = toGridItem(source, filters)..sort(compareFiltersByDate); + case ChipSortFactor.count: + final filtersWithCount = List.of(filters.map((filter) => MapEntry(filter, source.count(filter)))); + filtersWithCount.sort(compareFiltersByEntryCount); + filters = filtersWithCount.map((kv) => kv.key).toSet(); + allMapEntries = toGridItem(source, filters); + case ChipSortFactor.size: + final filtersWithSize = List.of(filters.map((filter) => MapEntry(filter, source.size(filter)))); + filtersWithSize.sort(compareFiltersBySize); + filters = filtersWithSize.map((kv) => kv.key).toSet(); + allMapEntries = toGridItem(source, filters); + case ChipSortFactor.path: + allMapEntries = toGridItem(source, filters)..sort(compareFiltersByPath); + } + if (reverse) { + allMapEntries = allMapEntries.reversed.toList(); + } + return allMapEntries; + } +} + +class _FilterNavigationPageState<T extends CollectionFilter, CSAD extends ChipSetActionDelegate<T>> extends State<FilterNavigationPage<T, CSAD>> with FeedbackMixin, VaultAwareMixin { + final ValueNotifier<double> _appBarHeightNotifier = ValueNotifier(0); + + @override + void dispose() { + _appBarHeightNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return SelectionProvider<FilterGridItem<T>>( + child: Builder( + builder: (context) { + final scrollController = PrimaryScrollController.of(context); + return QueryProvider( + startEnabled: settings.getShowTitleQuery(context.currentRouteName!), + child: FilterGridPage<T>( + appBar: FilterGridAppBar<T, CSAD>( + source: widget.source, + title: widget.title, + actionDelegate: widget.actionDelegate, + isEmpty: widget.filterSections.isEmpty, + appBarHeightNotifier: _appBarHeightNotifier, + scrollController: scrollController, + ), + appBarHeightNotifier: _appBarHeightNotifier, + scrollController: scrollController, + sections: widget.filterSections, + newFilters: widget.newFilters ?? {}, + sortFactor: widget.sortFactor, + showHeaders: widget.showHeaders, + selectable: true, + emptyBuilder: () => ValueListenableBuilder<SourceState>( + valueListenable: widget.source.stateNotifier, + builder: (context, sourceState, child) { + return sourceState != SourceState.loading ? widget.emptyBuilder() : const SizedBox(); + }, + ), + // do not always enable hero, otherwise unwanted hero gets triggered + // when using `Show in [...]` action from a chip in the Collection filter bar + heroType: HeroType.onTap, + onTileTap: (gridItem, navigate) async { + final selection = context.read<Selection<FilterGridItem<T>>?>(); + if (selection != null && selection.isSelecting) { + selection.toggleSelection(gridItem); + } else { + final filter = gridItem.filter; + if (!await unlockFilter(context, filter)) return; + + if (filter is GroupBaseFilter) { + context.read<FilterGroupNotifier>().value = filter.uri; + } else { + final route = MaterialPageRoute( + settings: const RouteSettings(name: CollectionPage.routeName), + builder: (context) => CollectionPage( + source: context.read<CollectionSource>(), + filters: {gridItem.filter}, + ), + ); + navigate(route); + } + } + }, + ), + ); + }, + ), + ); + } +} diff --git a/lib/widgets/filter_grids/common/filter_tile.dart b/lib/widgets/filter_grids/common/filter_tile.dart new file mode 100644 index 0000000..6386dd1 --- /dev/null +++ b/lib/widgets/filter_grids/common/filter_tile.dart @@ -0,0 +1,167 @@ +import 'package:aves/model/filters/covered/stored_album.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/vaults/vaults.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/grid/scaling.dart'; +import 'package:aves/widgets/common/identity/aves_filter_chip.dart'; +import 'package:aves/widgets/filter_grids/common/covered_filter_chip.dart'; +import 'package:aves/widgets/filter_grids/common/filter_chip_grid_decorator.dart'; +import 'package:aves/widgets/filter_grids/common/list_details.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; + +typedef FilterTileTapCallback<T extends CollectionFilter> = void Function(FilterGridItem<T> gridItem, void Function(Route route) navigate); + +class InteractiveFilterTile<T extends CollectionFilter> extends StatefulWidget { + final FilterGridItem<T> gridItem; + final double chipExtent, thumbnailExtent; + final TileLayout tileLayout; + final String? banner; + final HeroType heroType; + final FilterTileTapCallback<T> onTap; + + const InteractiveFilterTile({ + super.key, + required this.gridItem, + required this.chipExtent, + required this.thumbnailExtent, + required this.tileLayout, + this.banner, + required this.heroType, + required this.onTap, + }); + + @override + State<InteractiveFilterTile<T>> createState() => _InteractiveFilterTileState<T>(); +} + +class _InteractiveFilterTileState<T extends CollectionFilter> extends State<InteractiveFilterTile<T>> { + HeroType? _heroTypeOverride; + + FilterGridItem<T> get gridItem => widget.gridItem; + + HeroType get effectiveHeroType => _heroTypeOverride ?? widget.heroType; + + @override + Widget build(BuildContext context) { + return MetaData( + metaData: ScalerMetadata(gridItem), + child: FilterTile( + gridItem: gridItem, + chipExtent: widget.chipExtent, + thumbnailExtent: widget.thumbnailExtent, + tileLayout: widget.tileLayout, + banner: widget.banner, + selectable: true, + highlightable: true, + onTap: (_) => widget.onTap(gridItem, _navigate), + heroType: effectiveHeroType, + ), + ); + } + + void _navigate(Route route) { + if (effectiveHeroType == HeroType.onTap) { + // make sure the chip hero triggers, even when tapping on the list view details + setState(() => _heroTypeOverride = HeroType.always); + } + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; + Navigator.maybeOf(context)?.push(route); + }); + } +} + +class FilterTile<T extends CollectionFilter> extends StatelessWidget { + final FilterGridItem<T> gridItem; + final double chipExtent, thumbnailExtent; + final TileLayout tileLayout; + final String? banner; + final bool selectable, highlightable; + final AFilterCallback? onTap; + final HeroType heroType; + + const FilterTile({ + super.key, + required this.gridItem, + required this.chipExtent, + required this.thumbnailExtent, + required this.tileLayout, + this.banner, + this.selectable = false, + this.highlightable = false, + this.onTap, + this.heroType = HeroType.never, + }); + + @override + Widget build(BuildContext context) { + final filter = gridItem.filter; + final pinned = settings.pinnedFilters.contains(filter); + final locked = filter is StoredAlbumFilter && vaults.isLocked(filter.album); + final _onTap = onTap; + + switch (tileLayout) { + case TileLayout.mosaic: + case TileLayout.grid: + return FilterChipGridDecorator<T, FilterGridItem<T>>( + gridItem: gridItem, + extent: chipExtent, + selectable: selectable, + highlightable: highlightable, + child: CoveredFilterChip( + filter: filter, + extent: chipExtent, + thumbnailExtent: thumbnailExtent, + showText: true, + pinned: pinned, + locked: locked, + banner: banner, + onTap: _onTap, + heroType: heroType, + ), + ); + case TileLayout.list: + Widget child = Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + FilterChipGridDecorator<T, FilterGridItem<T>>( + gridItem: gridItem, + extent: chipExtent, + selectable: selectable, + highlightable: highlightable, + child: CoveredFilterChip( + filter: filter, + extent: chipExtent, + thumbnailExtent: thumbnailExtent, + showText: false, + locked: locked, + banner: banner, + onTap: _onTap, + heroType: heroType, + ), + ), + Expanded( + child: FilterListDetails( + gridItem: gridItem, + pinned: pinned, + locked: locked, + ), + ), + ], + ); + if (_onTap != null) { + // larger than the chip corner radius, so ink effects will be effectively clipped from the leading chip corners + const radius = Radius.circular(123); + child = InkWell( + // as of Flutter v2.8.1, `InkWell` does not use `BorderRadiusGeometry` + borderRadius: context.isRtl ? const BorderRadius.only(topRight: radius, bottomRight: radius) : const BorderRadius.only(topLeft: radius, bottomLeft: radius), + onTap: () => _onTap(filter), + child: child, + ); + } + return child; + } + } +} diff --git a/lib/widgets/filter_grids/common/group_crumb_line.dart b/lib/widgets/filter_grids/common/group_crumb_line.dart new file mode 100644 index 0000000..b0d8546 --- /dev/null +++ b/lib/widgets/filter_grids/common/group_crumb_line.dart @@ -0,0 +1,44 @@ +import 'package:aves/model/grouping/common.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/widgets/common/app_bar/crumb_line.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:flutter/material.dart'; + +class FilterGroupCrumbLine extends StatelessWidget { + final Uri? groupUri; + final void Function(Uri? groupUri) onTap; + + const FilterGroupCrumbLine({ + super.key, + required this.groupUri, + required this.onTap, + }); + + @override + Widget build(BuildContext context) { + return CrumbLine<Uri?>( + split: _split, + combine: _combine, + onTap: onTap, + ); + } + + List<String> _split(BuildContext context) { + final path = FilterGrouping.getGroupPath(groupUri); + final crumbs = [context.l10n.ungrouped]; + if (path != null) { + crumbs.addAll(pContext.split(path)); + } + return crumbs; + } + + Uri? _combine(BuildContext context, int index) { + if (groupUri == null || index == 0) return null; + + var targetGroupUri = groupUri; + for (var i = _split(context).length - 1; i > index; i--) { + targetGroupUri = FilterGrouping.getParentGroup(targetGroupUri); + } + return targetGroupUri; + } +} diff --git a/lib/widgets/filter_grids/common/list_details.dart b/lib/widgets/filter_grids/common/list_details.dart new file mode 100644 index 0000000..fa09fdd --- /dev/null +++ b/lib/widgets/filter_grids/common/list_details.dart @@ -0,0 +1,167 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/filters/container/dynamic_album.dart'; +import 'package:aves/model/filters/container/group_base.dart'; +import 'package:aves/model/filters/covered/stored_album.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/theme/format.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/theme/text.dart'; +import 'package:aves/utils/android_file_utils.dart'; +import 'package:aves/utils/file_utils.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/fx/borders.dart'; +import 'package:aves/widgets/filter_grids/common/list_details_theme.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class FilterListDetails<T extends CollectionFilter> extends StatelessWidget { + final FilterGridItem<T> gridItem; + final bool pinned, locked; + + T get filter => gridItem.filter; + + AvesEntry? get entry => gridItem.entry; + + const FilterListDetails({ + super.key, + required this.gridItem, + required this.pinned, + required this.locked, + }); + + @override + Widget build(BuildContext context) { + final detailsTheme = context.watch<FilterListDetailsThemeData>(); + + final leading = filter.iconBuilder(context, detailsTheme.titleIconSize, allowGenericIcon: false); + final hasTitleLeading = leading != null; + + return Container( + padding: FilterListDetailsTheme.contentPadding, + foregroundDecoration: BoxDecoration( + border: Border(top: AvesBorder.straightSide(context)), + ), + margin: FilterListDetailsTheme.contentMargin, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text.rich( + TextSpan( + children: [ + if (hasTitleLeading) + WidgetSpan( + alignment: PlaceholderAlignment.middle, + child: Padding( + padding: const EdgeInsetsDirectional.only(end: FilterListDetailsTheme.titleIconPadding), + child: IconTheme( + data: IconThemeData(color: detailsTheme.titleStyle.color), + child: leading, + ), + ), + ), + TextSpan( + text: filter.getLabel(context), + style: detailsTheme.titleStyle, + ), + ], + ), + softWrap: false, + overflow: detailsTheme.titleMaxLines == 1 ? TextOverflow.fade : TextOverflow.ellipsis, + maxLines: detailsTheme.titleMaxLines, + // `textScaler` is applied to font size and icon size at the theme level, + // otherwise the leading icon will be low-res scaled up/down + textScaler: TextScaler.noScaling, + ), + if (!locked) ...[ + const SizedBox(height: FilterListDetailsTheme.titleDetailPadding), + if (detailsTheme.showDate) _buildDateRow(context, detailsTheme, hasTitleLeading), + if (detailsTheme.showCount) _buildCountRow(context, detailsTheme, hasTitleLeading), + ], + ], + ), + ); + } + + Widget _buildDateRow(BuildContext context, FilterListDetailsThemeData detailsTheme, bool hasTitleLeading) { + final use24hour = MediaQuery.alwaysUse24HourFormatOf(context); + final date = entry?.bestDate; + final dateText = date != null ? formatDateTime(date, context.locale, use24hour) : AText.valueNotAvailable; + + Widget leading = const Icon(AIcons.date); + if (hasTitleLeading) { + leading = ConstrainedBox( + constraints: BoxConstraints(minWidth: detailsTheme.titleIconSize), + child: leading, + ); + } + return IconTheme.merge( + data: detailsTheme.captionIconTheme, + child: Row( + children: [ + leading, + const SizedBox(width: 8), + Expanded( + child: Text( + dateText, + style: detailsTheme.captionStyle, + softWrap: false, + overflow: TextOverflow.fade, + ), + ), + ], + ), + ); + } + + Widget _buildCountRow(BuildContext context, FilterListDetailsThemeData detailsTheme, bool hasTitleLeading) { + final _filter = filter; + final removableStorage = _filter is StoredAlbumFilter && androidFileUtils.isOnRemovableStorage(_filter.album); + + List<Widget> leadingIcons = [ + if (pinned) const Icon(AIcons.pin), + if (removableStorage) const Icon(AIcons.storageCard), + if (_filter is DynamicAlbumFilter) const Icon(AIcons.dynamicAlbum), + if (_filter is GroupBaseFilter) const Icon(AIcons.group), + ]; + + Widget? leading; + if (leadingIcons.isNotEmpty) { + leading = Row( + children: leadingIcons + .mapIndexed((i, child) => i > 0 + ? Padding( + padding: const EdgeInsetsDirectional.only(start: 8), + child: child, + ) + : child) + .toList(), + ); + } + + leading = ConstrainedBox( + constraints: BoxConstraints(minWidth: hasTitleLeading ? detailsTheme.titleIconSize : detailsTheme.captionIconTheme.size!), + child: Center(child: leading ?? const SizedBox()), + ); + + final source = context.read<CollectionSource>(); + + return IconTheme.merge( + data: detailsTheme.captionIconTheme, + child: Row( + children: [ + leading, + const SizedBox(width: 8), + Text( + '${context.l10n.itemCount(source.count(filter))} • ${formatFileSize(context.locale, source.size(filter))}', + style: detailsTheme.captionStyle, + softWrap: false, + overflow: TextOverflow.fade, + ), + ], + ), + ); + } +} diff --git a/lib/widgets/filter_grids/common/list_details_theme.dart b/lib/widgets/filter_grids/common/list_details_theme.dart new file mode 100644 index 0000000..b828d16 --- /dev/null +++ b/lib/widgets/filter_grids/common/list_details_theme.dart @@ -0,0 +1,120 @@ +import 'dart:math'; + +import 'package:aves/theme/format.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/aves_filter_chip.dart'; +import 'package:aves/widgets/common/tile_extent_controller.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:provider/provider.dart'; + +class FilterListDetailsTheme extends StatelessWidget { + final double extent; + final Widget child; + + static const EdgeInsets contentMargin = EdgeInsets.symmetric(horizontal: 8); + static const EdgeInsets contentPadding = EdgeInsets.symmetric(vertical: 4); + static const double titleIconPadding = 8; + static const double titleDetailPadding = 6; + + const FilterListDetailsTheme({ + super.key, + required this.extent, + required this.child, + }); + + @override + Widget build(BuildContext context) { + return ProxyProvider<MediaQueryData, FilterListDetailsThemeData>( + update: (context, mq, previous) { + final use24hour = mq.alwaysUse24HourFormat; + final textScaler = mq.textScaler; + + final textTheme = Theme.of(context).textTheme; + var titleStyle = textTheme.bodyMedium!; + var captionStyle = textTheme.bodySmall!; + // specify `height` for accurate paragraph height measurement + final defaultTextHeight = DefaultTextStyle.of(context).style.height; + titleStyle = titleStyle.copyWith( + fontSize: textScaler.scale(titleStyle.fontSize!), + height: titleStyle.height ?? defaultTextHeight, + ); + captionStyle = captionStyle.copyWith(height: captionStyle.height ?? defaultTextHeight); + + final titleIconSize = textScaler.scale(AvesFilterChip.iconSize); + final titleLineHeightParagraph = RenderParagraph( + TextSpan(text: 'Fake Title', style: titleStyle), + textDirection: TextDirection.ltr, + textScaler: textScaler, + )..layout(const BoxConstraints(), parentUsesSize: true); + final titleLineHeight = titleLineHeightParagraph.getMaxIntrinsicHeight(double.infinity); + titleLineHeightParagraph.dispose(); + + final captionLineHeightParagraph = RenderParagraph( + TextSpan(text: formatDateTime(DateTime.now(), context.locale, use24hour), style: captionStyle), + textDirection: TextDirection.ltr, + textScaler: textScaler, + )..layout(const BoxConstraints(), parentUsesSize: true); + final captionLineHeight = captionLineHeightParagraph.getMaxIntrinsicHeight(double.infinity); + captionLineHeightParagraph.dispose(); + + var titleMaxLines = 1; + var showCount = false; + var showDate = false; + + final gridExtentMin = context.read<TileExtentController>().effectiveExtentMin; + final isMinExtent = (extent - gridExtentMin).abs() < precisionErrorTolerance; + + var availableHeight = extent - contentMargin.vertical - contentPadding.vertical; + final firstTitleLineHeight = max(titleLineHeight, titleIconSize); + if (availableHeight >= firstTitleLineHeight + titleDetailPadding + captionLineHeight) { + showCount = true; + availableHeight -= firstTitleLineHeight + titleDetailPadding + captionLineHeight; + if (availableHeight >= captionLineHeight) { + showDate = true; + availableHeight -= captionLineHeight; + titleMaxLines += availableHeight ~/ titleLineHeight; + } + } + + return FilterListDetailsThemeData( + extent: extent, + titleMaxLines: titleMaxLines, + isMinExtent: isMinExtent, + showCount: showCount, + showDate: showDate, + titleStyle: titleStyle, + captionStyle: captionStyle, + titleIconSize: titleIconSize, + captionIconTheme: IconThemeData( + color: captionStyle.color, + size: textScaler.scale(captionStyle.fontSize!), + ), + ); + }, + child: child, + ); + } +} + +class FilterListDetailsThemeData { + final double extent; + final int titleMaxLines; + final bool isMinExtent, showCount, showDate; + final TextStyle titleStyle, captionStyle; + final double titleIconSize; + final IconThemeData captionIconTheme; + + const FilterListDetailsThemeData({ + required this.extent, + required this.titleMaxLines, + required this.isMinExtent, + required this.showCount, + required this.showDate, + required this.titleStyle, + required this.captionStyle, + required this.titleIconSize, + required this.captionIconTheme, + }); +} diff --git a/lib/widgets/filter_grids/common/overlay.dart b/lib/widgets/filter_grids/common/overlay.dart new file mode 100644 index 0000000..c2fb1f0 --- /dev/null +++ b/lib/widgets/filter_grids/common/overlay.dart @@ -0,0 +1,56 @@ +import 'dart:math'; + +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/highlight.dart'; +import 'package:aves/widgets/common/fx/sweeper.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class ChipHighlightOverlay extends StatefulWidget { + final CollectionFilter filter; + final double extent; + final BorderRadius borderRadius; + + const ChipHighlightOverlay({ + super.key, + required this.filter, + required this.extent, + required this.borderRadius, + }); + + @override + State<ChipHighlightOverlay> createState() => _ChipHighlightOverlayState(); +} + +class _ChipHighlightOverlayState extends State<ChipHighlightOverlay> { + final ValueNotifier<bool> _highlightedNotifier = ValueNotifier(false); + + CollectionFilter get filter => widget.filter; + + @override + void dispose() { + _highlightedNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final highlightInfo = context.watch<HighlightInfo>(); + _highlightedNotifier.value = highlightInfo.contains(filter); + return Sweeper( + builder: (context) => Container( + decoration: BoxDecoration( + border: Border.fromBorderSide(BorderSide( + color: Theme.of(context).colorScheme.primary, + width: widget.extent * .1, + )), + borderRadius: widget.borderRadius, + ), + ), + toggledNotifier: _highlightedNotifier, + startAngle: pi * -3 / 4, + centerSweep: false, + onSweepEnd: highlightInfo.clear, + ); + } +} diff --git a/lib/widgets/filter_grids/common/query_bar.dart b/lib/widgets/filter_grids/common/query_bar.dart new file mode 100644 index 0000000..5e4452b --- /dev/null +++ b/lib/widgets/filter_grids/common/query_bar.dart @@ -0,0 +1,37 @@ +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/selection.dart'; +import 'package:aves/widgets/common/basic/query_bar.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class FilterQueryBar<T extends CollectionFilter> extends StatelessWidget { + final ValueNotifier<String> queryNotifier; + final FocusNode focusNode; + + const FilterQueryBar({ + super.key, + required this.queryNotifier, + required this.focusNode, + }); + + @override + Widget build(BuildContext context) { + final textScaler = MediaQuery.textScalerOf(context); + return Container( + height: getPreferredHeight(textScaler), + alignment: Alignment.topCenter, + child: Selector<Selection<FilterGridItem<T>>, bool>( + selector: (context, selection) => !selection.isSelecting, + builder: (context, editable, child) => QueryBar( + queryNotifier: queryNotifier, + focusNode: focusNode, + hintText: context.l10n.collectionSearchTitlesHintText, + editable: editable, + ), + ), + ); + } + + static double getPreferredHeight(TextScaler textScaler) => QueryBar.getPreferredHeight(textScaler); +} diff --git a/lib/widgets/filter_grids/common/section_header.dart b/lib/widgets/filter_grids/common/section_header.dart new file mode 100644 index 0000000..597f0ab --- /dev/null +++ b/lib/widgets/filter_grids/common/section_header.dart @@ -0,0 +1,29 @@ +import 'package:aves/widgets/common/grid/header.dart'; +import 'package:aves/widgets/filter_grids/common/section_keys.dart'; +import 'package:flutter/material.dart'; + +class FilterChipSectionHeader<T> extends StatelessWidget { + final ChipSectionKey sectionKey; + final bool selectable; + + const FilterChipSectionHeader({ + super.key, + required this.sectionKey, + required this.selectable, + }); + + @override + Widget build(BuildContext context) { + return SectionHeader<T>( + sectionKey: sectionKey, + leading: sectionKey.leading, + title: sectionKey.title, + selectable: selectable, + ); + } + + static double getPreferredHeight(BuildContext context) { + final textScaler = MediaQuery.textScalerOf(context); + return textScaler.scale(SectionHeader.leadingSize.height) + SectionHeader.padding.vertical + SectionHeader.margin.vertical; + } +} diff --git a/lib/widgets/filter_grids/common/section_keys.dart b/lib/widgets/filter_grids/common/section_keys.dart new file mode 100644 index 0000000..6d8a1ea --- /dev/null +++ b/lib/widgets/filter_grids/common/section_keys.dart @@ -0,0 +1,70 @@ +import 'package:aves/model/source/section_keys.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/filter_grids/common/enums.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:equatable/equatable.dart'; +import 'package:flutter/material.dart'; + +class ChipSectionKey extends SectionKey with EquatableMixin { + final String title; + + @override + List<Object?> get props => [title]; + + const ChipSectionKey({ + this.title = '', + }); + + Widget? get leading => null; +} + +class AlbumImportanceSectionKey extends ChipSectionKey { + final AlbumImportance importance; + + AlbumImportanceSectionKey._private(BuildContext context, this.importance) : super(title: importance.getText(context)); + + factory AlbumImportanceSectionKey.newAlbum(BuildContext context) => AlbumImportanceSectionKey._private(context, AlbumImportance.newAlbum); + + factory AlbumImportanceSectionKey.pinned(BuildContext context) => AlbumImportanceSectionKey._private(context, AlbumImportance.pinned); + + factory AlbumImportanceSectionKey.group(BuildContext context) => AlbumImportanceSectionKey._private(context, AlbumImportance.group); + + factory AlbumImportanceSectionKey.special(BuildContext context) => AlbumImportanceSectionKey._private(context, AlbumImportance.special); + + factory AlbumImportanceSectionKey.apps(BuildContext context) => AlbumImportanceSectionKey._private(context, AlbumImportance.apps); + + factory AlbumImportanceSectionKey.vault(BuildContext context) => AlbumImportanceSectionKey._private(context, AlbumImportance.vaults); + + factory AlbumImportanceSectionKey.dynamic(BuildContext context) => AlbumImportanceSectionKey._private(context, AlbumImportance.dynamic); + + factory AlbumImportanceSectionKey.regular(BuildContext context) => AlbumImportanceSectionKey._private(context, AlbumImportance.regular); + + @override + Widget get leading => Icon(importance.getIcon()); +} + +class MimeTypeSectionKey extends ChipSectionKey { + final AlbumMimeType mimeType; + + MimeTypeSectionKey._private(BuildContext context, this.mimeType) : super(title: mimeType.getText(context)); + + factory MimeTypeSectionKey.images(BuildContext context) => MimeTypeSectionKey._private(context, AlbumMimeType.images); + + factory MimeTypeSectionKey.videos(BuildContext context) => MimeTypeSectionKey._private(context, AlbumMimeType.videos); + + factory MimeTypeSectionKey.mixed(BuildContext context) => MimeTypeSectionKey._private(context, AlbumMimeType.mixed); + + @override + Widget get leading => Icon(mimeType.getIcon()); +} + +class StorageVolumeSectionKey extends ChipSectionKey { + final StorageVolume? volume; + + StorageVolumeSectionKey(BuildContext context, this.volume) : super(title: volume?.getDescription(context) ?? context.l10n.sectionUnknown); + + @override + Widget? get leading => (volume?.isRemovable ?? false) ? const Icon(AIcons.storageCard) : null; +} diff --git a/lib/widgets/filter_grids/common/section_layout.dart b/lib/widgets/filter_grids/common/section_layout.dart new file mode 100644 index 0000000..c275b9e --- /dev/null +++ b/lib/widgets/filter_grids/common/section_layout.dart @@ -0,0 +1,47 @@ +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/source/section_keys.dart'; +import 'package:aves/widgets/common/grid/sections/provider.dart'; +import 'package:aves/widgets/filter_grids/common/section_header.dart'; +import 'package:aves/widgets/filter_grids/common/section_keys.dart'; +import 'package:flutter/material.dart'; + +class SectionedFilterListLayoutProvider<T extends CollectionFilter> extends SectionedListLayoutProvider<FilterGridItem<T>> { + final bool selectable; + + const SectionedFilterListLayoutProvider({ + super.key, + required this.sections, + required this.showHeaders, + required this.selectable, + required super.scrollableWidth, + required super.tileLayout, + required super.columnCount, + required super.spacing, + required super.horizontalPadding, + required super.tileWidth, + required super.tileHeight, + required super.tileBuilder, + required super.tileAnimationDelay, + required super.coverRatioResolver, + required super.child, + }); + + @override + final Map<SectionKey, List<FilterGridItem<T>>> sections; + + @override + final bool showHeaders; + + @override + double getHeaderExtent(BuildContext context, SectionKey sectionKey) { + return FilterChipSectionHeader.getPreferredHeight(context); + } + + @override + Widget buildHeader(BuildContext context, SectionKey sectionKey, double headerExtent) { + return FilterChipSectionHeader<FilterGridItem<T>>( + sectionKey: sectionKey as ChipSectionKey, + selectable: selectable, + ); + } +} diff --git a/lib/widgets/filter_grids/countries_page.dart b/lib/widgets/filter_grids/countries_page.dart new file mode 100644 index 0000000..d0c9934 --- /dev/null +++ b/lib/widgets/filter_grids/countries_page.dart @@ -0,0 +1,74 @@ +import 'package:aves/model/filters/covered/location.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/model/source/location/country.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/empty.dart'; +import 'package:aves/widgets/filter_grids/common/action_delegates/country_set.dart'; +import 'package:aves/widgets/filter_grids/common/filter_nav_page.dart'; +import 'package:aves/widgets/filter_grids/common/section_keys.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class CountryListPage extends StatelessWidget { + static const routeName = '/countries'; + + const CountryListPage({super.key}); + + @override + Widget build(BuildContext context) { + final source = context.read<CollectionSource>(); + return Selector<Settings, (ChipSortFactor, bool, Set<CollectionFilter>)>( + selector: (context, s) => (s.countrySortFactor, s.countrySortReverse, s.pinnedFilters), + shouldRebuild: (t1, t2) { + // `Selector` by default uses `DeepCollectionEquality`, which does not go deep in collections within records + const eq = DeepCollectionEquality(); + return !(eq.equals(t1.$1, t2.$1) && eq.equals(t1.$2, t2.$2) && eq.equals(t1.$3, t2.$3)); + }, + builder: (context, s, child) { + return StreamBuilder( + stream: source.eventBus.on<CountriesChangedEvent>(), + builder: (context, snapshot) { + final gridItems = _getGridItems(source); + return FilterNavigationPage<LocationFilter, CountryChipSetActionDelegate>( + source: source, + title: context.l10n.countryPageTitle, + sortFactor: settings.countrySortFactor, + actionDelegate: CountryChipSetActionDelegate(gridItems), + filterSections: _groupToSections(gridItems), + emptyBuilder: () => EmptyContent( + icon: AIcons.country, + text: context.l10n.countryEmpty, + ), + ); + }, + ); + }, + ); + } + + List<FilterGridItem<LocationFilter>> _getGridItems(CollectionSource source) { + final filters = source.sortedCountries.map((location) => LocationFilter(LocationLevel.country, location)).toSet(); + + return FilterNavigationPage.sort(settings.countrySortFactor, settings.countrySortReverse, source, filters); + } + + static Map<ChipSectionKey, List<FilterGridItem<LocationFilter>>> _groupToSections(Iterable<FilterGridItem<LocationFilter>> sortedMapEntries) { + final pinned = settings.pinnedFilters.whereType<LocationFilter>(); + final byPin = groupBy<FilterGridItem<LocationFilter>, bool>(sortedMapEntries, (e) => pinned.contains(e.filter)); + final pinnedMapEntries = (byPin[true] ?? []); + final unpinnedMapEntries = (byPin[false] ?? []); + + return { + if (pinnedMapEntries.isNotEmpty || unpinnedMapEntries.isNotEmpty) + const ChipSectionKey(): [ + ...pinnedMapEntries, + ...unpinnedMapEntries, + ], + }; + } +} diff --git a/lib/widgets/filter_grids/places_page.dart b/lib/widgets/filter_grids/places_page.dart new file mode 100644 index 0000000..8a0af4a --- /dev/null +++ b/lib/widgets/filter_grids/places_page.dart @@ -0,0 +1,74 @@ +import 'package:aves/model/filters/covered/location.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/model/source/location/place.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/empty.dart'; +import 'package:aves/widgets/filter_grids/common/action_delegates/place_set.dart'; +import 'package:aves/widgets/filter_grids/common/filter_nav_page.dart'; +import 'package:aves/widgets/filter_grids/common/section_keys.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class PlaceListPage extends StatelessWidget { + static const routeName = '/places'; + + const PlaceListPage({super.key}); + + @override + Widget build(BuildContext context) { + final source = context.read<CollectionSource>(); + return Selector<Settings, (ChipSortFactor, bool, Set<CollectionFilter>)>( + selector: (context, s) => (s.placeSortFactor, s.placeSortReverse, s.pinnedFilters), + shouldRebuild: (t1, t2) { + // `Selector` by default uses `DeepCollectionEquality`, which does not go deep in collections within records + const eq = DeepCollectionEquality(); + return !(eq.equals(t1.$1, t2.$1) && eq.equals(t1.$2, t2.$2) && eq.equals(t1.$3, t2.$3)); + }, + builder: (context, s, child) { + return StreamBuilder( + stream: source.eventBus.on<PlacesChangedEvent>(), + builder: (context, snapshot) { + final gridItems = _getGridItems(source); + return FilterNavigationPage<LocationFilter, PlaceChipSetActionDelegate>( + source: source, + title: context.l10n.placePageTitle, + sortFactor: settings.placeSortFactor, + actionDelegate: PlaceChipSetActionDelegate(gridItems), + filterSections: _groupToSections(gridItems), + emptyBuilder: () => EmptyContent( + icon: AIcons.place, + text: context.l10n.placeEmpty, + ), + ); + }, + ); + }, + ); + } + + List<FilterGridItem<LocationFilter>> _getGridItems(CollectionSource source) { + final filters = source.sortedPlaces.map((location) => LocationFilter(LocationLevel.place, location)).toSet(); + + return FilterNavigationPage.sort(settings.placeSortFactor, settings.placeSortReverse, source, filters); + } + + static Map<ChipSectionKey, List<FilterGridItem<LocationFilter>>> _groupToSections(Iterable<FilterGridItem<LocationFilter>> sortedMapEntries) { + final pinned = settings.pinnedFilters.whereType<LocationFilter>(); + final byPin = groupBy<FilterGridItem<LocationFilter>, bool>(sortedMapEntries, (e) => pinned.contains(e.filter)); + final pinnedMapEntries = (byPin[true] ?? []); + final unpinnedMapEntries = (byPin[false] ?? []); + + return { + if (pinnedMapEntries.isNotEmpty || unpinnedMapEntries.isNotEmpty) + const ChipSectionKey(): [ + ...pinnedMapEntries, + ...unpinnedMapEntries, + ], + }; + } +} diff --git a/lib/widgets/filter_grids/states_page.dart b/lib/widgets/filter_grids/states_page.dart new file mode 100644 index 0000000..1402926 --- /dev/null +++ b/lib/widgets/filter_grids/states_page.dart @@ -0,0 +1,81 @@ +import 'package:aves/geo/states.dart'; +import 'package:aves/model/filters/covered/location.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/model/source/location/place.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/empty.dart'; +import 'package:aves/widgets/filter_grids/common/action_delegates/state_set.dart'; +import 'package:aves/widgets/filter_grids/common/filter_nav_page.dart'; +import 'package:aves/widgets/filter_grids/common/section_keys.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class StateListPage extends StatelessWidget { + static const routeName = '/states'; + + final Set<String> countryCodes; + + const StateListPage({ + super.key, + required this.countryCodes, + }); + + @override + Widget build(BuildContext context) { + final source = context.read<CollectionSource>(); + return Selector<Settings, (ChipSortFactor, bool, Set<CollectionFilter>)>( + selector: (context, s) => (s.stateSortFactor, s.stateSortReverse, s.pinnedFilters), + shouldRebuild: (t1, t2) { + // `Selector` by default uses `DeepCollectionEquality`, which does not go deep in collections within records + const eq = DeepCollectionEquality(); + return !(eq.equals(t1.$1, t2.$1) && eq.equals(t1.$2, t2.$2) && eq.equals(t1.$3, t2.$3)); + }, + builder: (context, s, child) { + return StreamBuilder( + stream: source.eventBus.on<PlacesChangedEvent>(), + builder: (context, snapshot) { + final gridItems = _getGridItems(source); + return FilterNavigationPage<LocationFilter, StateChipSetActionDelegate>( + source: source, + title: context.l10n.statePageTitle, + sortFactor: settings.stateSortFactor, + actionDelegate: StateChipSetActionDelegate(gridItems), + filterSections: _groupToSections(gridItems), + emptyBuilder: () => EmptyContent( + icon: AIcons.state, + text: context.l10n.stateEmpty, + ), + ); + }, + ); + }, + ); + } + + List<FilterGridItem<LocationFilter>> _getGridItems(CollectionSource source) { + final selectedStateCodes = countryCodes.expand((v) => GeoStates.stateCodesByCountryCode[v] ?? <String>{}).toSet(); + final filters = source.sortedStates.where((v) => selectedStateCodes.any(v.endsWith)).map((location) => LocationFilter(LocationLevel.state, location)).toSet(); + + return FilterNavigationPage.sort(settings.stateSortFactor, settings.stateSortReverse, source, filters); + } + + static Map<ChipSectionKey, List<FilterGridItem<LocationFilter>>> _groupToSections(Iterable<FilterGridItem<LocationFilter>> sortedMapEntries) { + final pinned = settings.pinnedFilters.whereType<LocationFilter>(); + final byPin = groupBy<FilterGridItem<LocationFilter>, bool>(sortedMapEntries, (e) => pinned.contains(e.filter)); + final pinnedMapEntries = (byPin[true] ?? []); + final unpinnedMapEntries = (byPin[false] ?? []); + + return { + if (pinnedMapEntries.isNotEmpty || unpinnedMapEntries.isNotEmpty) + const ChipSectionKey(): [ + ...pinnedMapEntries, + ...unpinnedMapEntries, + ], + }; + } +} diff --git a/lib/widgets/filter_grids/tags_page.dart b/lib/widgets/filter_grids/tags_page.dart new file mode 100644 index 0000000..8054699 --- /dev/null +++ b/lib/widgets/filter_grids/tags_page.dart @@ -0,0 +1,131 @@ +import 'package:aves/model/filters/container/tag_group.dart'; +import 'package:aves/model/filters/covered/tag.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/grouping/common.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/model/source/tag.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/empty.dart'; +import 'package:aves/widgets/common/providers/filter_group_provider.dart'; +import 'package:aves/widgets/filter_grids/common/action_delegates/tag_set.dart'; +import 'package:aves/widgets/filter_grids/common/enums.dart'; +import 'package:aves/widgets/filter_grids/common/filter_nav_page.dart'; +import 'package:aves/widgets/filter_grids/common/section_keys.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class TagListPage extends StatelessWidget { + static const routeName = '/tags'; + + final Uri? initialGroup; + + const TagListPage({ + super.key, + required this.initialGroup, + }); + + @override + Widget build(BuildContext context) { + return MultiProvider( + providers: [ + ChangeNotifierProvider<FilterGrouping>.value(value: tagGrouping), + FilterGroupProvider(initialValue: initialGroup), + ], + child: Builder( + // to access filter group provider from subtree context + builder: (context) { + final source = context.read<CollectionSource>(); + return Selector<Settings, (ChipSortFactor, bool, Set<CollectionFilter>)>( + selector: (context, s) => (s.tagSortFactor, s.tagSortReverse, s.pinnedFilters), + shouldRebuild: (t1, t2) { + // `Selector` by default uses `DeepCollectionEquality`, which does not go deep in collections within records + const eq = DeepCollectionEquality(); + return !(eq.equals(t1.$1, t2.$1) && eq.equals(t1.$2, t2.$2) && eq.equals(t1.$3, t2.$3)); + }, + builder: (context, s, child) { + return AnimatedBuilder( + animation: tagGrouping, + builder: (context, child) => StreamBuilder( + stream: source.eventBus.on<TagsChangedEvent>(), + builder: (context, snapshot) { + final groupUri = context.watch<FilterGroupNotifier>().value; + final gridItems = getGridItems(source, ChipType.values, groupUri); + return FilterNavigationPage<TagBaseFilter, TagChipSetActionDelegate>( + source: source, + title: context.l10n.tagPageTitle, + sortFactor: settings.tagSortFactor, + actionDelegate: TagChipSetActionDelegate(gridItems), + filterSections: groupToSections(gridItems), + emptyBuilder: () => EmptyContent( + icon: AIcons.tag, + text: context.l10n.tagEmpty, + ), + ); + }, + ), + ); + }, + ); + }, + ), + ); + } + + // common with picking page + + static List<FilterGridItem<TagBaseFilter>> getGridItems( + CollectionSource source, + Iterable<ChipType> chipTypes, + Uri? groupUri, + ) { + final groupContent = tagGrouping.getDirectChildren(groupUri); + + Set<T> whereTypeRecursively<T>(Set<CollectionFilter> filters) { + return { + ...filters.whereType<T>(), + ...filters.whereType<TagGroupFilter>().expand((v) => whereTypeRecursively<T>(v.filter.innerFilters)), + }; + } + + final listedTags = <String>{}; + if (chipTypes.contains(ChipType.regular)) { + final allTags = source.sortedTags; + if (groupUri == null) { + final withinGroups = whereTypeRecursively<TagFilter>(groupContent).map((v) => v.tag).toSet(); + listedTags.addAll(allTags.whereNot(withinGroups.contains)); + } else { + // check that group content is listed from source, to prevent displaying hidden content + listedTags.addAll(groupContent.whereType<TagFilter>().map((v) => v.tag).where(allTags.contains)); + } + } + + // always show groups, which are needed to navigate to other types + final tagGroupFilters = groupContent.whereType<TagGroupFilter>().whereNot(settings.hiddenFilters.contains).toSet(); + + final filters = <TagBaseFilter>{ + ...tagGroupFilters, + ...listedTags.map(TagFilter.new), + }; + + return FilterNavigationPage.sort(settings.tagSortFactor, settings.tagSortReverse, source, filters); + } + + static Map<ChipSectionKey, List<FilterGridItem<TagBaseFilter>>> groupToSections(Iterable<FilterGridItem<TagBaseFilter>> sortedMapEntries) { + final pinned = settings.pinnedFilters.whereType<TagFilter>(); + final byPin = groupBy<FilterGridItem<TagBaseFilter>, bool>(sortedMapEntries, (e) => pinned.contains(e.filter)); + final pinnedMapEntries = (byPin[true] ?? []); + final unpinnedMapEntries = (byPin[false] ?? []); + + return { + if (pinnedMapEntries.isNotEmpty || unpinnedMapEntries.isNotEmpty) + const ChipSectionKey(): [ + ...pinnedMapEntries, + ...unpinnedMapEntries, + ], + }; + } +} diff --git a/lib/widgets/home/home_error.dart b/lib/widgets/home/home_error.dart new file mode 100644 index 0000000..296ffb4 --- /dev/null +++ b/lib/widgets/home/home_error.dart @@ -0,0 +1,107 @@ +import 'package:aves/ref/locales.dart'; +import 'package:aves/ref/mime_types.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/widgets/about/bug_report.dart'; +import 'package:aves/widgets/common/action_mixins/feedback.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/aves_expansion_tile.dart'; +import 'package:aves/widgets/common/identity/buttons/outlined_button.dart'; +import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; + +class HomeError extends StatefulWidget { + final Object error; + final StackTrace stack; + + const HomeError({ + super.key, + required this.error, + required this.stack, + }); + + @override + State<HomeError> createState() => _HomeErrorState(); +} + +class _HomeErrorState extends State<HomeError> with FeedbackMixin { + final ValueNotifier<String?> _expandedNotifier = ValueNotifier(null); + + @override + void dispose() { + _expandedNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + return SafeArea( + bottom: false, + child: CustomScrollView( + slivers: [ + SliverPadding( + padding: const EdgeInsets.symmetric(horizontal: 8), + sliver: SliverList( + delegate: SliverChildListDelegate( + [ + AvesExpansionTile( + title: 'Error', + expandedNotifier: _expandedNotifier, + showHighlight: false, + children: [ + Padding( + padding: const EdgeInsets.all(8), + child: SelectableText( + '${widget.error}:\n${widget.stack}', + style: Theme.of(context).textTheme.bodySmall, + ), + ), + ], + ), + AvesExpansionTile( + title: l10n.aboutBugSectionTitle, + expandedNotifier: _expandedNotifier, + showHighlight: false, + children: const [BugReportContent()], + ), + AvesExpansionTile( + title: l10n.aboutDataUsageDatabase, + expandedNotifier: _expandedNotifier, + showHighlight: false, + children: [ + Row( + children: [ + Padding( + padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16), + child: AvesOutlinedButton( + label: l10n.settingsActionExport, + onPressed: () async { + final sourcePath = await localMediaDb.path; + final success = await storageService.copyFile( + 'aves-database-${DateFormat('yyyyMMdd_HHmmss', asciiLocale).format(DateTime.now())}.db', + MimeTypes.sqlite3, + Uri.file(sourcePath).toString(), + ); + if (success != null) { + if (success) { + showFeedback(context, FeedbackType.info, context.l10n.genericSuccessFeedback); + } else { + showFeedback(context, FeedbackType.warn, context.l10n.genericFailureFeedback); + } + } + }, + ), + ), + ], + ), + ], + ), + ], + ), + ), + ), + ], + ), + ); + } +} diff --git a/lib/widgets/home/home_page.dart b/lib/widgets/home/home_page.dart new file mode 100644 index 0000000..0ab23e1 --- /dev/null +++ b/lib/widgets/home/home_page.dart @@ -0,0 +1,437 @@ +import 'dart:async'; + +import 'package:aves/app_mode.dart'; +import 'package:aves/geo/uri.dart'; +import 'package:aves/model/app/intent.dart'; +import 'package:aves/model/app/permissions.dart'; +import 'package:aves/model/app_inventory.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/catalog.dart'; +import 'package:aves/model/filters/covered/location.dart'; +import 'package:aves/model/filters/covered/stored_album.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/services/analysis_service.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/services/global_search.dart'; +import 'package:aves/services/intent_service.dart'; +import 'package:aves/services/widget_service.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/utils/android_file_utils.dart'; +import 'package:aves/widgets/collection/collection_page.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/behaviour/routes.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/search/page.dart'; +import 'package:aves/widgets/common/search/route.dart'; +import 'package:aves/widgets/editor/entry_editor_page.dart'; +import 'package:aves/widgets/explorer/explorer_page.dart'; +import 'package:aves/widgets/filter_grids/albums_page.dart'; +import 'package:aves/widgets/filter_grids/tags_page.dart'; +import 'package:aves/widgets/home/home_error.dart'; +import 'package:aves/widgets/map/map_page.dart'; +import 'package:aves/widgets/search/collection_search_delegate.dart'; +import 'package:aves/widgets/settings/home_widget_settings_page.dart'; +import 'package:aves/widgets/settings/screen_saver_settings_page.dart'; +import 'package:aves/widgets/viewer/entry_viewer_page.dart'; +import 'package:aves/widgets/viewer/screen_saver_page.dart'; +import 'package:aves/widgets/wallpaper_page.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:latlong2/latlong.dart'; +import 'package:permission_handler/permission_handler.dart'; +import 'package:provider/provider.dart'; + +class HomePage extends StatefulWidget { + static const routeName = '/'; + + // untyped map as it is coming from the platform + final Map? intentData; + + const HomePage({ + super.key, + this.intentData, + }); + + @override + State<HomePage> createState() => _HomePageState(); +} + +class _HomePageState extends State<HomePage> { + AvesEntry? _viewerEntry; + int? _widgetId; + String? _initialRouteName, _initialSearchQuery; + Set<CollectionFilter>? _initialFilters; + String? _initialExplorerPath; + (LatLng, double?)? _initialLocationZoom; + List<String>? _secureUris; + (Object, StackTrace)? _setupError; + + static const allowedShortcutRoutes = [ + AlbumListPage.routeName, + CollectionPage.routeName, + ExplorerPage.routeName, + MapPage.routeName, + SearchPage.routeName, + ]; + + @override + void initState() { + super.initState(); + _setup(); + imageCache.maximumSizeBytes = 512 * (1 << 20); + } + + @override + Widget build(BuildContext context) => AvesScaffold( + body: _setupError != null + ? HomeError( + error: _setupError!.$1, + stack: _setupError!.$2, + ) + : null, + ); + + Future<void> _setup() async { + try { + final stopwatch = Stopwatch()..start(); + if (await windowService.isActivity()) { + // do not check whether permission was granted, because some app stores + // hide in some countries apps that force quit on permission denial + await Permissions.mediaAccess.request(); + } + + var appMode = AppMode.main; + var error = false; + final intentData = widget.intentData ?? await IntentService.getIntentData(); + final intentAction = intentData[IntentDataKeys.action] as String?; + _initialFilters = null; + _initialExplorerPath = null; + _secureUris = null; + + await availability.onNewIntent(); + await androidFileUtils.init(); + if (!{ + IntentActions.edit, + IntentActions.screenSaver, + IntentActions.setWallpaper, + }.contains(intentAction) && + settings.isInstalledAppAccessAllowed) { + unawaited(appInventory.initAppNames()); + } + + if (intentData.values.nonNulls.isNotEmpty) { + await reportService.log('Intent data=$intentData'); + var intentUri = intentData[IntentDataKeys.uri] as String?; + final intentMimeType = intentData[IntentDataKeys.mimeType] as String?; + + switch (intentAction) { + case IntentActions.view: + appMode = AppMode.view; + _secureUris = (intentData[IntentDataKeys.secureUris] as List?)?.cast<String>(); + case IntentActions.viewGeo: + error = true; + if (intentUri != null) { + final locationZoom = parseGeoUri(intentUri); + if (locationZoom != null) { + _initialRouteName = MapPage.routeName; + _initialLocationZoom = locationZoom; + error = false; + } + } + break; + case IntentActions.edit: + appMode = AppMode.edit; + case IntentActions.setWallpaper: + appMode = AppMode.setWallpaper; + case IntentActions.pickItems: + // TODO TLAD apply pick mimetype(s) + // some apps define multiple types, separated by a space (maybe other signs too, like `,` `;`?) + final multiple = (intentData[IntentDataKeys.allowMultiple] as bool?) ?? false; + debugPrint('pick mimeType=$intentMimeType multiple=$multiple'); + appMode = multiple ? AppMode.pickMultipleMediaExternal : AppMode.pickSingleMediaExternal; + case IntentActions.pickCollectionFilters: + appMode = AppMode.pickCollectionFiltersExternal; + case IntentActions.screenSaver: + appMode = AppMode.screenSaver; + _initialRouteName = ScreenSaverPage.routeName; + case IntentActions.screenSaverSettings: + _initialRouteName = ScreenSaverSettingsPage.routeName; + case IntentActions.search: + _initialRouteName = SearchPage.routeName; + _initialSearchQuery = intentData[IntentDataKeys.query] as String?; + case IntentActions.widgetSettings: + _initialRouteName = HomeWidgetSettingsPage.routeName; + _widgetId = (intentData[IntentDataKeys.widgetId] as int?) ?? 0; + case IntentActions.widgetOpen: + final widgetId = intentData[IntentDataKeys.widgetId] as int?; + if (widgetId == null) { + error = true; + } else { + // widget settings may be modified in a different process after channel setup + await settings.reload(); + final page = settings.getWidgetOpenPage(widgetId); + switch (page) { + case WidgetOpenPage.collection: + _initialFilters = settings.getWidgetCollectionFilters(widgetId); + case WidgetOpenPage.viewer: + appMode = AppMode.view; + intentUri = settings.getWidgetUri(widgetId); + case WidgetOpenPage.home: + case WidgetOpenPage.updateWidget: + break; + } + unawaited(WidgetService.update(widgetId)); + } + default: + // do not use 'route' as extra key, as the Flutter framework acts on it + final extraRoute = intentData[IntentDataKeys.page] as String?; + if (allowedShortcutRoutes.contains(extraRoute)) { + _initialRouteName = extraRoute; + } + } + if (_initialFilters == null) { + final extraFilters = (intentData[IntentDataKeys.filters] as List?)?.cast<String>(); + _initialFilters = extraFilters?.map(CollectionFilter.fromJson).nonNulls.toSet(); + } + _initialExplorerPath = intentData[IntentDataKeys.explorerPath] as String?; + + switch (appMode) { + case AppMode.view: + case AppMode.edit: + case AppMode.setWallpaper: + if (intentUri != null) { + _viewerEntry = await _initViewerEntry( + uri: intentUri, + mimeType: intentMimeType, + ); + } + error = _viewerEntry == null; + default: + break; + } + } + + if (error) { + debugPrint('Failed to init app mode=$appMode for intent data=$intentData. Fallback to main mode.'); + appMode = AppMode.main; + } + + context.read<ValueNotifier<AppMode>>().value = appMode; + unawaited(reportService.setCustomKey('app_mode', appMode.toString())); + + switch (appMode) { + case AppMode.main: + case AppMode.pickCollectionFiltersExternal: + case AppMode.pickSingleMediaExternal: + case AppMode.pickMultipleMediaExternal: + unawaited(GlobalSearch.registerCallback()); + unawaited(AnalysisService.registerCallback()); + final source = context.read<CollectionSource>(); + if (source.loadedScope != CollectionSource.fullScope) { + await reportService.log('Initialize source to start app with mode=$appMode, loaded scope=${source.loadedScope}'); + final loadTopEntriesFirst = settings.homeNavItem.route == CollectionPage.routeName && settings.homeCustomCollection.isEmpty; + source.canAnalyze = true; + await source.init(scope: CollectionSource.fullScope, loadTopEntriesFirst: loadTopEntriesFirst); + } + case AppMode.screenSaver: + await reportService.log('Initialize source to start screen saver'); + final source = context.read<CollectionSource>(); + source.canAnalyze = false; + await source.init(scope: settings.screenSaverCollectionFilters); + case AppMode.view: + if (_isViewerSourceable(_viewerEntry) && _secureUris == null) { + final directory = _viewerEntry?.directory; + if (directory != null) { + unawaited(AnalysisService.registerCallback()); + await reportService.log('Initialize source to view item in directory $directory'); + final source = context.read<CollectionSource>(); + // analysis is necessary to display neighbour items when the initial item is a new one + source.canAnalyze = true; + await source.init(scope: {StoredAlbumFilter(directory, null)}); + } + } else { + await _initViewerEssentials(); + } + case AppMode.edit: + case AppMode.setWallpaper: + await _initViewerEssentials(); + default: + break; + } + + debugPrint('Home setup complete in ${stopwatch.elapsed.inMilliseconds}ms'); + + // `pushReplacement` is not enough in some edge cases + // e.g. when opening the viewer in `view` mode should replace a viewer in `main` mode + unawaited(Navigator.maybeOf(context)?.pushAndRemoveUntil( + await _getRedirectRoute(appMode), + (route) => false, + )); + } catch (error, stack) { + debugPrint('failed to setup app with error=$error\n$stack'); + setState(() => _setupError = (error, stack)); + } + } + + Future<void> _initViewerEssentials() async { + // for video playback storage + await localMediaDb.init(); + } + + bool _isViewerSourceable(AvesEntry? viewerEntry) { + return viewerEntry != null && viewerEntry.directory != null && !settings.hiddenFilters.any((filter) => filter.test(viewerEntry)); + } + + Future<AvesEntry?> _initViewerEntry({required String uri, required String? mimeType}) async { + if (uri.startsWith('/')) { + // convert this file path to a proper URI + uri = Uri.file(uri).toString(); + } + final entry = await mediaFetchService.getEntry(uri, mimeType); + if (entry != null) { + // cataloguing is essential for coordinates and video rotation + await entry.catalog(background: false, force: false, persist: false); + } + return entry; + } + + Future<Route> _getRedirectRoute(AppMode appMode) async { + String routeName; + Set<CollectionFilter?>? filters; + switch (appMode) { + case AppMode.setWallpaper: + return DirectMaterialPageRoute( + settings: const RouteSettings(name: WallpaperPage.routeName), + builder: (_) { + return WallpaperPage( + entry: _viewerEntry, + ); + }, + ); + case AppMode.view: + AvesEntry viewerEntry = _viewerEntry!; + CollectionLens? collection; + + final source = context.read<CollectionSource>(); + final album = viewerEntry.directory; + if (album != null) { + // wait for collection to pass the `loading` state + final loadingCompleter = Completer(); + final stateNotifier = source.stateNotifier; + void _onSourceStateChanged() { + if (stateNotifier.value != SourceState.loading) { + stateNotifier.removeListener(_onSourceStateChanged); + loadingCompleter.complete(); + } + } + + stateNotifier.addListener(_onSourceStateChanged); + _onSourceStateChanged(); + await loadingCompleter.future; + + collection = CollectionLens( + source: source, + filters: {StoredAlbumFilter(album, source.getStoredAlbumDisplayName(context, album))}, + listenToSource: false, + // if we group bursts, opening a burst sub-entry should: + // - identify and select the containing main entry, + // - select the sub-entry in the Viewer page. + stackBursts: false, + ); + final viewerEntryPath = viewerEntry.path; + final collectionEntry = collection.sortedEntries.firstWhereOrNull((entry) => entry.path == viewerEntryPath); + if (collectionEntry != null) { + viewerEntry = collectionEntry; + } else { + debugPrint('collection does not contain viewerEntry=$viewerEntry'); + collection = null; + } + } + + return DirectMaterialPageRoute( + settings: const RouteSettings(name: EntryViewerPage.routeName), + builder: (_) { + return EntryViewerPage( + collection: collection, + initialEntry: viewerEntry, + ); + }, + ); + case AppMode.edit: + return DirectMaterialPageRoute( + settings: const RouteSettings(name: EntryViewerPage.routeName), + builder: (_) { + return ImageEditorPage( + entry: _viewerEntry!, + ); + }, + ); + case AppMode.initialization: + case AppMode.main: + case AppMode.pickCollectionFiltersExternal: + case AppMode.pickSingleMediaExternal: + case AppMode.pickMultipleMediaExternal: + case AppMode.pickFilteredMediaInternal: + case AppMode.pickUnfilteredMediaInternal: + case AppMode.pickFilterInternal: + case AppMode.previewMap: + case AppMode.screenSaver: + case AppMode.slideshow: + routeName = _initialRouteName ?? settings.homeNavItem.route; + filters = _initialFilters ?? (settings.homeNavItem.route == CollectionPage.routeName ? settings.homeCustomCollection : {}); + } + Route buildRoute(WidgetBuilder builder) => DirectMaterialPageRoute( + settings: RouteSettings(name: routeName), + builder: builder, + ); + + final source = context.read<CollectionSource>(); + switch (routeName) { + case AlbumListPage.routeName: + return buildRoute((context) => const AlbumListPage(initialGroup: null)); + case TagListPage.routeName: + return buildRoute((context) => const TagListPage(initialGroup: null)); + case MapPage.routeName: + return buildRoute((context) { + final mapCollection = CollectionLens( + source: source, + filters: { + LocationFilter.located, + if (filters != null) ...filters, + }, + ); + return MapPage( + collection: mapCollection, + initialLocation: _initialLocationZoom?.$1, + initialZoom: _initialLocationZoom?.$2, + ); + }); + case ExplorerPage.routeName: + final path = _initialExplorerPath ?? settings.homeCustomExplorerPath; + return buildRoute((context) => ExplorerPage(path: path)); + case HomeWidgetSettingsPage.routeName: + return buildRoute((context) => HomeWidgetSettingsPage(widgetId: _widgetId!)); + case ScreenSaverPage.routeName: + return buildRoute((context) => ScreenSaverPage(source: source)); + case ScreenSaverSettingsPage.routeName: + return buildRoute((context) => const ScreenSaverSettingsPage()); + case SearchPage.routeName: + return SearchPageRoute( + delegate: CollectionSearchDelegate( + searchFieldLabel: context.l10n.searchCollectionFieldHint, + searchFieldStyle: Themes.searchFieldStyle(context), + source: source, + canPop: false, + initialQuery: _initialSearchQuery, + ), + ); + case CollectionPage.routeName: + default: + return buildRoute((context) => CollectionPage(source: source, filters: filters)); + } + } +} diff --git a/lib/widgets/home_widget.dart b/lib/widgets/home_widget.dart new file mode 100644 index 0000000..5344627 --- /dev/null +++ b/lib/widgets/home_widget.dart @@ -0,0 +1,97 @@ +import 'dart:async'; +import 'dart:typed_data'; +import 'dart:ui' as ui; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/images.dart'; +import 'package:aves/model/settings/enums/widget_shape.dart'; +import 'package:aves/theme/colors.dart'; +import 'package:aves/widgets/common/identity/aves_filter_chip.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; + +class HomeWidgetPainter { + final AvesEntry? entry; + final double devicePixelRatio; + + // do not use `AlignmentDirectional` as there is no `TextDirection` in context + static const backgroundGradient = LinearGradient( + begin: Alignment.bottomLeft, + end: Alignment.topRight, + colors: AColors.boraBoraGradient, + ); + + HomeWidgetPainter({ + required this.entry, + required this.devicePixelRatio, + }); + + Future<Uint8List> drawWidget({ + required Size sizeDip, + required double? cornerRadiusPx, + required Color? outline, + required WidgetShape shape, + ui.ImageByteFormat format = ui.ImageByteFormat.rawRgba, + }) async { + final widthPx = sizeDip.width * devicePixelRatio; + final heightPx = sizeDip.height * devicePixelRatio; + final widgetSizePx = Size(widthPx, heightPx); + debugPrint('Draw widget for ${sizeDip.width}x${sizeDip.height} dp (${widgetSizePx.width}x${widgetSizePx.height} px), entry=$entry'); + final ui.Image? entryImage; + if (entry != null) { + final extent = shape.extentPx(widgetSizePx, entry!) / devicePixelRatio; + entryImage = await _getEntryImage(entry, extent); + } else { + entryImage = null; + } + + final recorder = ui.PictureRecorder(); + final rect = Offset.zero & widgetSizePx; + final canvas = Canvas(recorder, rect); + final path = shape.path(widgetSizePx, devicePixelRatio, cornerRadiusPx: cornerRadiusPx); + canvas.clipPath(path); + if (entryImage != null) { + canvas.drawImage(entryImage, Offset(widgetSizePx.width - entryImage.width, widgetSizePx.height - entryImage.height) / 2, Paint()); + entryImage.dispose(); + } else { + canvas.drawPaint(Paint()..shader = backgroundGradient.createShader(rect)); + } + if (outline != null) { + drawOutline(canvas, path, devicePixelRatio, outline); + } + final widgetImage = await recorder.endRecording().toImage(widthPx.round(), heightPx.round()); + final byteData = await widgetImage.toByteData(format: format); + return byteData?.buffer.asUint8List() ?? Uint8List(0); + } + + static void drawOutline(ui.Canvas canvas, ui.Path outlinePath, double devicePixelRatio, Color color) { + canvas.drawPath( + outlinePath, + Paint() + ..style = PaintingStyle.stroke + ..color = color + ..strokeWidth = AvesFilterChip.outlineWidth * devicePixelRatio * 2 + ..strokeCap = StrokeCap.round); + } + + FutureOr<ui.Image?> _getEntryImage(AvesEntry? entry, double extent) async { + if (entry == null) return null; + + final provider = entry.getThumbnail(extent: extent); + + final imageInfoCompleter = Completer<ImageInfo?>(); + final imageStream = provider.resolve(ImageConfiguration.empty); + final imageStreamListener = ImageStreamListener((image, synchronousCall) async { + imageInfoCompleter.complete(image); + }, onError: imageInfoCompleter.completeError); + imageStream.addListener(imageStreamListener); + ImageInfo? regionImageInfo; + try { + regionImageInfo = await imageInfoCompleter.future; + } catch (error) { + debugPrint('failed to get widget image for entry=$entry with error=$error'); + } + imageStream.removeListener(imageStreamListener); + return regionImageInfo?.image; + } +} diff --git a/lib/widgets/map/address_row.dart b/lib/widgets/map/address_row.dart new file mode 100644 index 0000000..252b6c5 --- /dev/null +++ b/lib/widgets/map/address_row.dart @@ -0,0 +1,108 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/location.dart'; +import 'package:aves/model/settings/enums/coordinate_format.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/services/geocoding_service.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/theme/text.dart'; +import 'package:flutter/material.dart'; + +import 'info_row.dart'; + +class MapAddressRow extends StatefulWidget { + final AvesEntry? entry; + + const MapAddressRow({ + super.key, + required this.entry, + }); + + @override + State<MapAddressRow> createState() => _MapAddressRowState(); +} + +class _MapAddressRowState extends State<MapAddressRow> { + final ValueNotifier<String?> _addressLineNotifier = ValueNotifier(null); + + @override + void initState() { + super.initState(); + _updateAddress(); + } + + @override + void didUpdateWidget(covariant MapAddressRow oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.entry != widget.entry) { + _updateAddress(); + } + } + + @override + void dispose() { + _addressLineNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final textScaler = MediaQuery.textScalerOf(context); + return Container( + alignment: AlignmentDirectional.centerStart, + // addresses can include non-latin scripts with inconsistent line height, + // which is especially an issue for relayout/painting of heavy Google map, + // so we give extra height to give breathing room to the text and stabilize layout + height: textScaler.scale(Theme.of(context).textTheme.bodyMedium!.fontSize!) * 2, + child: ValueListenableBuilder<String?>( + valueListenable: _addressLineNotifier, + builder: (context, addressLine, child) { + final entry = widget.entry; + final location = addressLine ?? + (entry == null + ? AText.valueNotAvailable + : entry.hasAddress + ? entry.shortAddress + : settings.coordinateFormat.format(context, entry.latLng!)); + return Text.rich( + TextSpan( + children: [ + WidgetSpan( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: MapInfoRow.iconPadding), + child: Icon(AIcons.location, size: MapInfoRow.getIconSize(context)), + ), + alignment: PlaceholderAlignment.middle, + ), + TextSpan(text: location), + ], + ), + softWrap: false, + overflow: TextOverflow.fade, + maxLines: 1, + ); + }, + ), + ); + } + + Future<void> _updateAddress() async { + final entry = widget.entry; + final addressLine = await _getAddressLine(entry); + if (!mounted) return; + if (entry == widget.entry) { + _addressLineNotifier.value = addressLine; + } + } + + Future<String?> _getAddressLine(AvesEntry? entry) async { + if (entry != null && await availability.canLocatePlaces) { + final addresses = await GeocodingService.getAddress(entry.latLng!, settings.appliedLocale); + if (addresses.isNotEmpty) { + final address = addresses.first; + return address.addressLine; + } + } + return null; + } +} diff --git a/lib/widgets/map/date_row.dart b/lib/widgets/map/date_row.dart new file mode 100644 index 0000000..d83e715 --- /dev/null +++ b/lib/widgets/map/date_row.dart @@ -0,0 +1,41 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/theme/format.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/theme/text.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/map/info_row.dart'; +import 'package:flutter/material.dart'; + +class MapDateRow extends StatelessWidget { + final AvesEntry? entry; + + const MapDateRow({ + super.key, + required this.entry, + }); + + @override + Widget build(BuildContext context) { + final use24hour = MediaQuery.alwaysUse24HourFormatOf(context); + + final date = entry?.bestDate; + final dateText = date != null ? formatDateTime(date, context.locale, use24hour) : AText.valueNotAvailable; + return Text.rich( + TextSpan( + children: [ + WidgetSpan( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: MapInfoRow.iconPadding), + child: Icon(AIcons.date, size: MapInfoRow.getIconSize(context)), + ), + alignment: PlaceholderAlignment.middle, + ), + TextSpan(text: dateText), + ], + ), + softWrap: false, + overflow: TextOverflow.fade, + maxLines: 1, + ); + } +} diff --git a/lib/widgets/map/info_row.dart b/lib/widgets/map/info_row.dart new file mode 100644 index 0000000..2313c47 --- /dev/null +++ b/lib/widgets/map/info_row.dart @@ -0,0 +1,64 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/widgets/map/address_row.dart'; +import 'package:aves/widgets/map/date_row.dart'; +import 'package:aves_map/aves_map.dart'; +import 'package:flutter/material.dart'; + +class MapInfoRow extends StatelessWidget { + final ValueNotifier<AvesEntry?> entryNotifier; + + static const double iconPadding = 8.0; + static const double _interRowPadding = 2.0; + + const MapInfoRow({ + super.key, + required this.entryNotifier, + }); + + @override + Widget build(BuildContext context) { + return ValueListenableBuilder<AvesEntry?>( + valueListenable: entryNotifier, + builder: (context, entry, child) { + final isPortrait = MediaQuery.orientationOf(context) == Orientation.portrait; + final content = isPortrait + ? [ + Expanded( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + MapAddressRow(entry: entry), + const SizedBox(height: _interRowPadding), + MapDateRow(entry: entry), + ], + ), + ), + ] + : [ + MapDateRow(entry: entry), + Expanded( + child: MapAddressRow(entry: entry), + ), + ]; + + return Opacity( + opacity: entry != null ? 1 : 0, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + const SizedBox(width: iconPadding), + const DotMarker(), + ...content, + ], + ), + ); + }, + ); + } + + static double getIconSize(BuildContext context) { + final textScaler = MediaQuery.textScalerOf(context); + return textScaler.scale(16); + } +} diff --git a/lib/widgets/map/map_page.dart b/lib/widgets/map/map_page.dart new file mode 100644 index 0000000..a9ff2b5 --- /dev/null +++ b/lib/widgets/map/map_page.dart @@ -0,0 +1,570 @@ +import 'dart:async'; + +import 'package:aves/app_mode.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/location.dart'; +import 'package:aves/model/filters/coordinate.dart'; +import 'package:aves/model/filters/covered/location.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/highlight.dart'; +import 'package:aves/model/media/geotiff.dart'; +import 'package:aves/model/settings/enums/accessibility_animations.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/model/source/tag.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/collection/collection_page.dart'; +import 'package:aves/widgets/collection/entry_set_action_delegate.dart'; +import 'package:aves/widgets/common/basic/font_size_icon_theme.dart'; +import 'package:aves/widgets/common/basic/insets.dart'; +import 'package:aves/widgets/common/basic/popup/menu_row.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/behaviour/routes.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/buttons/captioned_button.dart'; +import 'package:aves/widgets/common/map/geo_map.dart'; +import 'package:aves/widgets/common/map/map_action_delegate.dart'; +import 'package:aves/widgets/common/providers/highlight_info_provider.dart'; +import 'package:aves/widgets/common/providers/map_theme_provider.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:aves/widgets/map/scroller.dart'; +import 'package:aves/widgets/viewer/controls/notifications.dart'; +import 'package:aves/widgets/viewer/entry_viewer_page.dart'; +import 'package:aves_map/aves_map.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:latlong2/latlong.dart'; +import 'package:provider/provider.dart'; + +class MapPage extends StatelessWidget { + static const routeName = '/map'; + + final CollectionLens collection; + final LatLng? initialLocation; + final double? initialZoom; + final AvesEntry? initialEntry; + final MappedGeoTiff? overlayEntry; + final Set<List<LatLng>>? tracks; + + const MapPage({ + super.key, + required this.collection, + this.initialLocation, + this.initialZoom, + this.initialEntry, + this.overlayEntry, + this.tracks, + }); + + @override + Widget build(BuildContext context) { + return MultiProvider( + providers: [ + // do not rely on the `HighlightInfoProvider` app level + // as the map can be stacked on top of other pages + // that catch highlight events and will not let it bubble up + HighlightInfoProvider(), + // opening collection can be used by map actions + ChangeNotifierProvider<CollectionLens>.value(value: collection), + ], + child: AvesScaffold( + body: SafeArea( + left: false, + top: false, + right: false, + bottom: true, + child: _Content( + collection: collection, + initialLocation: initialLocation, + initialZoom: initialZoom, + initialEntry: initialEntry, + overlayEntry: overlayEntry, + tracks: tracks, + ), + ), + ), + ); + } +} + +class _Content extends StatefulWidget { + final CollectionLens collection; + final LatLng? initialLocation; + final double? initialZoom; + final AvesEntry? initialEntry; + final MappedGeoTiff? overlayEntry; + final Set<List<LatLng>>? tracks; + + const _Content({ + required this.collection, + this.initialLocation, + this.initialZoom, + this.initialEntry, + this.overlayEntry, + this.tracks, + }); + + @override + State<_Content> createState() => _ContentState(); +} + +class _ContentState extends State<_Content> with SingleTickerProviderStateMixin { + final Set<StreamSubscription> _subscriptions = {}; + final AvesMapController _mapController = AvesMapController(); + final ValueNotifier<bool> _isPageAnimatingNotifier = ValueNotifier(false); + final ValueNotifier<int?> _selectedIndexNotifier = ValueNotifier(0); + final ValueNotifier<CollectionLens?> _regionCollectionNotifier = ValueNotifier(null); + final ValueNotifier<LatLng?> _dotLocationNotifier = ValueNotifier(null); + final ValueNotifier<AvesEntry?> _dotEntryNotifier = ValueNotifier(null); + final ValueNotifier<double> _overlayOpacityNotifier = ValueNotifier(1); + final ValueNotifier<bool> _overlayVisible = ValueNotifier(true); + late AnimationController _overlayAnimationController; + late CurvedAnimation _overlayScale, _scrollerSize; + CoordinateFilter? _regionFilter; + + CollectionLens? get regionCollection => _regionCollectionNotifier.value; + + CollectionLens get openingCollection => widget.collection; + + @override + void initState() { + super.initState(); + + if (settings.mapStyle?.isHeavy ?? false) { + _isPageAnimatingNotifier.value = true; + Future.delayed(ADurations.pageTransitionLoose * timeDilation).then((_) { + if (!mounted) return; + _isPageAnimatingNotifier.value = false; + }); + } + + _overlayAnimationController = AnimationController( + duration: context.read<DurationsData>().viewerOverlayAnimation, + vsync: this, + ); + _overlayScale = CurvedAnimation( + parent: _overlayAnimationController, + curve: Curves.easeOutBack, + ); + _scrollerSize = CurvedAnimation( + parent: _overlayAnimationController, + curve: Curves.easeOutQuad, + ); + _overlayVisible.addListener(_onOverlayVisibleChanged); + + _subscriptions.add(_mapController.idleUpdates.listen((event) => _onIdle(event.bounds))); + _subscriptions.add(openingCollection.source.eventBus.on<CatalogMetadataChangedEvent>().listen((e) => _updateRegionCollection())); + + _selectedIndexNotifier.addListener(_onThumbnailIndexChanged); + Future.delayed(ADurations.pageTransitionLoose * timeDilation + const Duration(seconds: 1), () { + if (!mounted) return; + final regionEntries = regionCollection?.sortedEntries ?? []; + final initialEntry = widget.initialEntry ?? regionEntries.firstOrNull; + if (initialEntry != null) { + final index = regionEntries.indexOf(initialEntry); + if (index != -1) { + _selectedIndexNotifier.value = index; + } + _onEntrySelected(initialEntry); + } + }); + + WidgetsBinding.instance.addPostFrameCallback((_) => _onOverlayVisibleChanged(animate: false)); + } + + @override + void dispose() { + _subscriptions + ..forEach((sub) => sub.cancel()) + ..clear(); + _mapController.dispose(); + _isPageAnimatingNotifier.dispose(); + _selectedIndexNotifier.dispose(); + _regionCollectionNotifier.value?.dispose(); + _regionCollectionNotifier.dispose(); + _dotLocationNotifier.dispose(); + _dotEntryNotifier.value?.metadataChangeNotifier.removeListener(_onMarkerEntryMetadataChanged); + _dotEntryNotifier.dispose(); + _overlayOpacityNotifier.dispose(); + _overlayVisible.dispose(); + _overlayScale.dispose(); + _scrollerSize.dispose(); + _overlayAnimationController.dispose(); + + // provided collection should be a new instance specifically created + // for the `MapPage` widget, so it can be safely disposed here + widget.collection.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return NotificationListener( + onNotification: (notification) { + if (notification is SelectFilterNotification) { + _goToCollection(notification.filter); + } else if (notification is OpenMapAppNotification) { + _openMapApp(); + } else { + return false; + } + return true; + }, + child: Selector<Settings, EntryMapStyle?>( + selector: (context, s) => s.mapStyle, + builder: (context, mapStyle, child) { + late Widget scroller; + if (mapStyle?.isHeavy ?? false) { + // the map widget is too heavy for a smooth resizing animation + // so we just toggle visibility when overlay animation is done + scroller = ValueListenableBuilder<double>( + valueListenable: _overlayAnimationController, + builder: (context, animation, child) { + return Visibility( + visible: !_overlayAnimationController.isDismissed, + child: child!, + ); + }, + child: child, + ); + } else { + // the map widget is light enough for a smooth resizing animation + scroller = FadeTransition( + opacity: _scrollerSize, + child: SizeTransition( + sizeFactor: _scrollerSize, + axisAlignment: 1.0, + child: child, + ), + ); + } + + return Column( + children: [ + Expanded(child: _buildMap()), + scroller, + ], + ); + }, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const SizedBox(height: 8), + const Divider(height: 0), + _buildOverlayControls(), + MapEntryScroller( + regionCollectionNotifier: _regionCollectionNotifier, + dotEntryNotifier: _dotEntryNotifier, + selectedIndexNotifier: _selectedIndexNotifier, + onTap: (index) => _goToViewer(_getRegionEntry(index)), + ), + ], + ), + ), + ); + } + + Widget _buildMap() { + final appMode = context.watch<ValueNotifier<AppMode>>().value; + final canPop = Navigator.maybeOf(context)?.canPop() == true; + Widget child = MapTheme( + interactive: true, + showCoordinateFilter: true, + navigationButton: canPop ? MapNavigationButton.back : MapNavigationButton.close, + scale: _overlayScale, + attributionPadding: const EdgeInsets.symmetric(horizontal: 8), + child: GeoMap( + // key is expected by test driver + key: const Key('map_view'), + controller: _mapController, + collection: openingCollection, + availableSize: MediaQuery.sizeOf(context), + initialCenter: widget.initialLocation ?? widget.initialEntry?.latLng ?? widget.overlayEntry?.center, + initialZoom: widget.initialZoom, + isAnimatingNotifier: _isPageAnimatingNotifier, + dotLocationNotifier: _dotLocationNotifier, + overlayOpacityNotifier: _overlayOpacityNotifier, + overlayEntry: widget.overlayEntry, + tracks: widget.tracks, + onMapTap: (_) => _toggleOverlay(), + onMarkerTap: (location, entry) async { + final index = regionCollection?.sortedEntries.indexOf(entry); + if (index != null && _selectedIndexNotifier.value != index) { + _selectedIndexNotifier.value = index; + } + await Future.delayed(const Duration(milliseconds: 500)); + context.read<HighlightInfo>().set(entry); + }, + onMarkerLongPress: appMode.canEditEntry ? _onMarkerLongPress : null, + ), + ); + if (settings.useTvLayout) { + child = DirectionalSafeArea( + top: false, + end: false, + bottom: false, + child: Row( + children: [ + Column( + mainAxisSize: MainAxisSize.min, + children: [ + MapAction.selectStyle, + MapAction.zoomIn, + MapAction.zoomOut, + ] + .mapIndexed((i, action) => Padding( + padding: const EdgeInsets.symmetric(vertical: 8), + child: CaptionedButton( + icon: action.getIcon(), + caption: action.getText(context), + autofocus: i == 0, + onPressed: () => MapActionDelegate(_mapController).onActionSelected(context, action), + ), + )) + .toList(), + ), + const SizedBox(width: 16), + Expanded(child: child), + ], + ), + ); + } + return child; + } + + Widget _buildOverlayControls() { + if (widget.overlayEntry == null) return const SizedBox(); + + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: ValueListenableBuilder<double>( + valueListenable: _overlayOpacityNotifier, + builder: (context, overlayOpacity, child) { + return Row( + children: [ + const Icon(AIcons.opacity), + Expanded( + child: Slider( + value: _overlayOpacityNotifier.value, + onChanged: (v) => _overlayOpacityNotifier.value = v, + min: 0, + max: 1, + ), + ), + ], + ); + }, + ), + ); + } + + void _onIdle(ZoomedBounds bounds) { + _regionFilter = CoordinateFilter(bounds.sw, bounds.ne); + _updateRegionCollection(); + } + + void _updateRegionCollection() { + final regionFilter = _regionFilter; + if (regionFilter == null) return; + + AvesEntry? selectedEntry; + if (regionCollection != null) { + final regionEntries = regionCollection!.sortedEntries; + final selectedIndex = _selectedIndexNotifier.value; + selectedEntry = selectedIndex != null && 0 <= selectedIndex && selectedIndex < regionEntries.length ? regionEntries[selectedIndex] : null; + } + + final oldRegionCollection = regionCollection; + final newRegionCollection = openingCollection.copyWith( + filters: { + ...openingCollection.filters.whereNot((v) => v is CoordinateFilter), + regionFilter, + }, + ); + _regionCollectionNotifier.value = newRegionCollection; + oldRegionCollection?.dispose(); + + // get entries from the new collection, so the entry order is the same + // as the one used by the thumbnail scroller (considering sort/section/group) + final regionEntries = regionCollection!.sortedEntries; + final selectedIndex = (selectedEntry != null && regionEntries.contains(selectedEntry)) + ? regionEntries.indexOf(selectedEntry) + : regionEntries.isEmpty + ? null + : 0; + _selectedIndexNotifier.value = selectedIndex; + // force update, as the region entries may change without a change of index + _onThumbnailIndexChanged(); + } + + AvesEntry? _getRegionEntry(int? index) { + if (index != null && index >= 0 && regionCollection != null) { + final regionEntries = regionCollection!.sortedEntries; + if (index < regionEntries.length) { + return regionEntries[index]; + } + } + return null; + } + + void _onThumbnailIndexChanged() => _onEntrySelected(_getRegionEntry(_selectedIndexNotifier.value)); + + void _onEntrySelected(AvesEntry? selectedEntry) { + _dotEntryNotifier.value?.metadataChangeNotifier.removeListener(_onMarkerEntryMetadataChanged); + _dotEntryNotifier.value = selectedEntry; + selectedEntry?.metadataChangeNotifier.addListener(_onMarkerEntryMetadataChanged); + _onMarkerEntryMetadataChanged(); + } + + void _onMarkerEntryMetadataChanged() { + _dotLocationNotifier.value = _dotEntryNotifier.value?.latLng; + } + + void _goToViewer(AvesEntry? initialEntry) { + if (initialEntry == null) return; + + final appModeNotifier = context.read<ValueNotifier<AppMode>>(); + Navigator.maybeOf(context)?.push( + TransparentMaterialPageRoute( + settings: const RouteSettings(name: EntryViewerPage.routeName), + pageBuilder: (context, a, sa) { + final viewerCollection = regionCollection?.copyWith( + listenToSource: false, + ); + // propagate app mode from the map page, as it could be locally overridden + // and differ from the real app mode above the `Navigator` + return ListenableProvider<ValueNotifier<AppMode>>.value( + value: appModeNotifier, + child: EntryViewerPage( + collection: viewerCollection, + initialEntry: initialEntry, + ), + ); + }, + ), + ); + } + + void _goToCollection(CollectionFilter filter) { + final isMainMode = context.read<ValueNotifier<AppMode>>().value == AppMode.main; + if (!isMainMode) return; + + Navigator.maybeOf(context)?.pushAndRemoveUntil( + MaterialPageRoute( + settings: const RouteSettings(name: CollectionPage.routeName), + builder: (context) { + final filters = {...openingCollection.filters, filter}; + if (filter is CoordinateFilter) { + filters.removeWhere((v) => (v is CoordinateFilter && v != filter) || v == LocationFilter.located); + } + return CollectionPage( + source: openingCollection.source, + filters: filters, + ); + }, + ), + (route) => false, + ); + } + + Future<void> _openMapApp() async { + final latLng = _dotEntryNotifier.value?.latLng ?? _mapController.idleBounds?.projectedCenter; + if (latLng != null) { + await appService.openMap(latLng).then((success) { + if (!success) showNoMatchingAppDialog(context); + }); + } + } + + // overlay + + void _toggleOverlay() => _overlayVisible.value = !_overlayVisible.value; + + Future<void> _onOverlayVisibleChanged({bool animate = true}) async { + if (_overlayVisible.value) { + if (animate) { + await _overlayAnimationController.forward(); + } else { + _overlayAnimationController.value = _overlayAnimationController.upperBound; + } + } else { + if (animate) { + await _overlayAnimationController.reverse(); + } else { + _overlayAnimationController.reset(); + } + } + } + + // cluster context menu + + Future<void> _onMarkerLongPress( + LatLng markerLocation, + AvesEntry markerEntry, + Set<AvesEntry> clusterEntries, + Offset tapLocalPosition, + WidgetBuilder markerBuilder, + ) async { + final overlay = Overlay.of(context).context.findRenderObject() as RenderBox; + const touchArea = Size(kMinInteractiveDimension, kMinInteractiveDimension); + final animations = context.read<Settings>().accessibilityAnimations; + final selectedAction = await showMenu<MapClusterAction>( + context: context, + position: RelativeRect.fromRect(tapLocalPosition & touchArea, Offset.zero & overlay.size), + items: [ + PopupMenuItem( + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + markerBuilder(context), + const SizedBox(width: 16), + Text(context.l10n.itemCount(clusterEntries.length)), + ], + ), + ), + const PopupMenuDivider(), + ...[ + MapClusterAction.editLocation, + MapClusterAction.removeLocation, + ].map(_buildMenuItem), + ], + popUpAnimationStyle: animations.popUpAnimationStyle, + ); + if (selectedAction != null) { + // wait for the popup menu to hide before proceeding with the action + await Future.delayed(animations.popUpAnimationDelay * timeDilation); + final delegate = EntrySetActionDelegate(); + switch (selectedAction) { + case MapClusterAction.editLocation: + final regionEntries = regionCollection?.sortedEntries ?? []; + final markerIndex = regionEntries.indexOf(markerEntry); + final location = await delegate.editLocationByMap(context, clusterEntries, markerLocation, openingCollection.copyWith()); + if (location != null) { + if (markerIndex != -1) { + _selectedIndexNotifier.value = markerIndex; + } + _mapController.moveTo(location); + } + case MapClusterAction.removeLocation: + await delegate.removeLocation(context, clusterEntries); + } + } + } + + PopupMenuItem<MapClusterAction> _buildMenuItem(MapClusterAction action) { + return PopupMenuItem( + value: action, + child: FontSizeIconTheme( + child: MenuRow( + text: action.getText(context), + icon: action.getIcon(), + ), + ), + ); + } +} diff --git a/lib/widgets/map/scroller.dart b/lib/widgets/map/scroller.dart new file mode 100644 index 0000000..f58f19e --- /dev/null +++ b/lib/widgets/map/scroller.dart @@ -0,0 +1,130 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/utils/debouncer.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/empty.dart'; +import 'package:aves/widgets/common/thumbnail/scroller.dart'; +import 'package:aves/widgets/map/info_row.dart'; +import 'package:aves/widgets/viewer/hero.dart'; +import 'package:flutter/material.dart'; + +class MapEntryScroller extends StatefulWidget { + final ValueNotifier<CollectionLens?> regionCollectionNotifier; + final ValueNotifier<AvesEntry?> dotEntryNotifier; + final ValueNotifier<int?> selectedIndexNotifier; + final void Function(int index) onTap; + + const MapEntryScroller({ + super.key, + required this.regionCollectionNotifier, + required this.dotEntryNotifier, + required this.selectedIndexNotifier, + required this.onTap, + }); + + @override + State<MapEntryScroller> createState() => _MapEntryScrollerState(); +} + +class _MapEntryScrollerState extends State<MapEntryScroller> { + final ValueNotifier<AvesEntry?> _infoEntryNotifier = ValueNotifier(null); + final Debouncer _infoDebouncer = Debouncer(delay: ADurations.mapInfoDebounceDelay); + + @override + void initState() { + super.initState(); + _registerWidget(widget); + WidgetsBinding.instance.addPostFrameCallback((_) => _onSelectedEntryChanged()); + } + + @override + void didUpdateWidget(covariant MapEntryScroller oldWidget) { + super.didUpdateWidget(oldWidget); + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + + @override + void dispose() { + _unregisterWidget(widget); + super.dispose(); + } + + void _registerWidget(MapEntryScroller widget) { + widget.dotEntryNotifier.addListener(_onSelectedEntryChanged); + } + + void _unregisterWidget(MapEntryScroller widget) { + widget.dotEntryNotifier.removeListener(_onSelectedEntryChanged); + } + + @override + Widget build(BuildContext context) { + return Stack( + children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SafeArea( + top: false, + bottom: false, + child: MapInfoRow(entryNotifier: _infoEntryNotifier), + ), + const SizedBox(height: 8), + ValueListenableBuilder<CollectionLens?>( + valueListenable: widget.regionCollectionNotifier, + builder: (context, regionCollection, child) { + return AnimatedBuilder( + // update when entries are added/removed + animation: regionCollection ?? ChangeNotifier(), + builder: (context, child) { + final regionEntries = regionCollection?.sortedEntries ?? []; + return ThumbnailScroller( + availableWidth: MediaQuery.sizeOf(context).width, + entryCount: regionEntries.length, + entryBuilder: (index) => index < regionEntries.length ? regionEntries[index] : null, + indexNotifier: widget.selectedIndexNotifier, + onTap: widget.onTap, + heroTagger: (entry) => EntryHeroInfo(regionCollection, entry).tag, + highlightable: true, + showLocation: false, + ); + }, + ); + }, + ), + ], + ), + Positioned.fill( + child: ValueListenableBuilder<AvesEntry?>( + valueListenable: _infoEntryNotifier, + builder: (context, infoEntry, child) { + return ValueListenableBuilder<CollectionLens?>( + valueListenable: widget.regionCollectionNotifier, + builder: (context, regionCollection, child) { + return infoEntry == null && regionCollection != null && regionCollection.isEmpty + ? EmptyContent( + text: context.l10n.mapEmptyRegion, + alignment: Alignment.center, + fontSize: 18, + ) + : const SizedBox(); + }, + ); + }, + ), + ), + ], + ); + } + + void _onSelectedEntryChanged() { + final selectedEntry = widget.dotEntryNotifier.value; + if (_infoEntryNotifier.value == null || selectedEntry == null) { + _infoEntryNotifier.value = selectedEntry; + } else { + _infoDebouncer(() => _infoEntryNotifier.value = selectedEntry); + } + } +} diff --git a/lib/widgets/navigation/drawer/app_drawer.dart b/lib/widgets/navigation/drawer/app_drawer.dart new file mode 100644 index 0000000..fddd09a --- /dev/null +++ b/lib/widgets/navigation/drawer/app_drawer.dart @@ -0,0 +1,432 @@ +import 'package:aves/model/filters/container/album_group.dart'; +import 'package:aves/model/filters/container/dynamic_album.dart'; +import 'package:aves/model/filters/covered/stored_album.dart'; +import 'package:aves/model/filters/trash.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/album.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/model/source/location/country.dart'; +import 'package:aves/model/source/location/place.dart'; +import 'package:aves/model/source/tag.dart'; +import 'package:aves/ref/locales.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/utils/android_file_utils.dart'; +import 'package:aves/utils/file_utils.dart'; +import 'package:aves/widgets/about/about_page.dart'; +import 'package:aves/widgets/collection/collection_page.dart'; +import 'package:aves/widgets/common/basic/text/outlined.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/extensions/media_query.dart'; +import 'package:aves/widgets/common/identity/aves_logo.dart'; +import 'package:aves/widgets/debug/app_debug_page.dart'; +import 'package:aves/widgets/explorer/explorer_page.dart'; +import 'package:aves/widgets/filter_grids/albums_page.dart'; +import 'package:aves/widgets/filter_grids/countries_page.dart'; +import 'package:aves/widgets/filter_grids/places_page.dart'; +import 'package:aves/widgets/filter_grids/tags_page.dart'; +import 'package:aves/widgets/home/home_page.dart'; +import 'package:aves/widgets/navigation/drawer/collection_nav_tile.dart'; +import 'package:aves/widgets/navigation/drawer/page_nav_tile.dart'; +import 'package:aves/widgets/navigation/drawer/tile.dart'; +import 'package:aves/widgets/navigation/nav_item.dart'; +import 'package:aves/widgets/settings/settings_page.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class AppDrawer extends StatefulWidget { + // collection loaded in the `CollectionPage`, if any + final CollectionLens? currentCollection; + + // current path loaded in the `ExplorerPage`, if any + final String? currentExplorerPath; + + const AppDrawer({ + super.key, + this.currentCollection, + this.currentExplorerPath, + }); + + @override + State<AppDrawer> createState() => _AppDrawerState(); + + static List<AlbumBaseFilter> _getDefaultAlbums(BuildContext context) { + final source = context.read<CollectionSource>(); + final specialAlbums = source.rawAlbums.where((album) { + final type = androidFileUtils.getAlbumType(album); + return [AlbumType.camera, AlbumType.download, AlbumType.screenshots].contains(type); + }).toList() + ..sort(source.compareAlbumsByName); + return specialAlbums.map((v) => StoredAlbumFilter(v, source.getStoredAlbumDisplayName(context, v))).toList(); + } + + static List<AlbumBaseFilter>? _getCustomAlbums(BuildContext context) { + final source = context.read<CollectionSource>(); + return settings.drawerAlbumBookmarks?.map((v) { + if (v is StoredAlbumFilter) { + final album = v.album; + return StoredAlbumFilter(album, source.getStoredAlbumDisplayName(context, album)); + } + return v; + }).toList(); + } + + static List<AlbumBaseFilter> effectiveAlbumBookmarks(BuildContext context) { + return _getCustomAlbums(context) ?? _getDefaultAlbums(context); + } +} + +class _AppDrawerState extends State<AppDrawer> with WidgetsBindingObserver { + // using the default controller conflicts + // with bottom nav bar primary scroll monitoring + final ScrollController _scrollController = ScrollController(); + late Future<List<dynamic>> _profileSwitchFuture; + bool _profileSwitchPermissionRequested = false; + + CollectionLens? get currentCollection => widget.currentCollection; + + @override + void initState() { + super.initState(); + _initProfileSwitchFuture(); + WidgetsBinding.instance.addObserver(this); + } + + @override + void dispose() { + WidgetsBinding.instance.removeObserver(this); + super.dispose(); + } + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + switch (state) { + case AppLifecycleState.resumed: + if (_profileSwitchPermissionRequested) { + _profileSwitchPermissionRequested = false; + _initProfileSwitchFuture(); + setState(() {}); + } + default: + break; + } + } + + void _initProfileSwitchFuture() { + _profileSwitchFuture = Future.wait([ + appProfileService.canRequestInteractAcrossProfiles(), + appProfileService.canInteractAcrossProfiles(), + appProfileService.getProfileSwitchingLabel(), + ]); + } + + @override + Widget build(BuildContext context) { + final drawerItems = <Widget>[ + _buildHeader(context), + _buildHomeLink(), + ..._buildTypeLinks(), + _buildAlbumLinks(context), + ..._buildPageLinks(context), + if (settings.enableBin) ...[ + const Divider(), + binTile(context), + ], + if (!kReleaseMode) ...[ + const Divider(), + debugTile, + ], + ]; + + return Drawer( + child: ListTileTheme.merge( + selectedColor: Theme.of(context).colorScheme.primary, + horizontalTitleGap: 20, + visualDensity: VisualDensity.comfortable, + child: Selector<MediaQueryData, double>( + selector: (context, mq) => mq.effectiveBottomPadding, + builder: (context, mqPaddingBottom, child) { + final textScaler = MediaQuery.textScalerOf(context); + final iconTheme = IconTheme.of(context); + return SingleChildScrollView( + controller: _scrollController, + // key is expected by test driver + key: const Key('drawer-scrollview'), + padding: EdgeInsets.only(bottom: mqPaddingBottom), + child: IconTheme( + data: iconTheme.copyWith( + size: textScaler.scale(iconTheme.size!), + ), + child: Column( + children: drawerItems, + ), + ), + ); + }, + ), + ), + ); + } + + Widget _buildHeader(BuildContext context) { + final l10n = context.l10n; + + Future<void> goTo(String routeName, WidgetBuilder pageBuilder) async { + Navigator.maybeOf(context)?.pop(); + await Future.delayed(ADurations.drawerTransitionLoose); + await Navigator.maybeOf(context)?.push(MaterialPageRoute( + settings: RouteSettings(name: routeName), + builder: pageBuilder, + )); + } + + final colorScheme = Theme.of(context).colorScheme; + final onPrimary = colorScheme.onPrimary; + + final drawerButtonStyle = ButtonStyle( + padding: WidgetStateProperty.all(const EdgeInsetsDirectional.only(start: 12, end: 16)), + ); + return Container( + padding: const EdgeInsets.symmetric(horizontal: 16), + color: colorScheme.primary, + child: SafeArea( + bottom: false, + child: OutlinedButtonTheme( + data: OutlinedButtonThemeData( + style: ButtonStyle( + foregroundColor: WidgetStateProperty.all<Color>(onPrimary), + overlayColor: WidgetStateProperty.all<Color>(onPrimary.withValues(alpha: .12)), + iconColor: WidgetStateProperty.all<Color>(onPrimary), + side: WidgetStateProperty.all<BorderSide>(BorderSide(width: 1, color: onPrimary.withValues(alpha: .24))), + ), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const SizedBox(height: 6), + Align( + alignment: AlignmentDirectional.centerStart, + child: Wrap( + spacing: 16, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + const AvesLogo(size: 48), + OutlinedText( + textSpans: [ + TextSpan( + text: l10n.appName, + style: TextStyle( + color: Colors.white, + fontSize: 38, + fontWeight: FontWeight.w300, + letterSpacing: canHaveLetterSpacing(context.locale) ? 1 : 0, + fontFeatures: const [FontFeature.enable('smcp')], + ), + ), + ], + ), + ], + ), + ), + const SizedBox(height: 8), + Wrap( + spacing: 8, + children: [ + OutlinedButton.icon( + // key is expected by test driver + key: const Key('drawer-about-button'), + onPressed: () => goTo(AboutPage.routeName, (_) => const AboutPage()), + style: drawerButtonStyle, + icon: const Icon(AIcons.info), + label: Text(l10n.drawerAboutButton), + ), + OutlinedButton.icon( + // key is expected by test driver + key: const Key('drawer-settings-button'), + onPressed: () => goTo(SettingsPage.routeName, (_) => const SettingsPage()), + style: drawerButtonStyle, + icon: const Icon(AIcons.settings), + label: Text(l10n.drawerSettingsButton), + ), + ], + ), + FutureBuilder<List<dynamic>>( + future: _profileSwitchFuture, + builder: (context, snapshot) { + final flags = snapshot.data; + if (flags == null) return const SizedBox(); + + final [ + bool canRequestInteractAcrossProfiles, + bool canSwitchProfile, + String profileSwitchingLabel, + ] = flags; + if ((!canRequestInteractAcrossProfiles && !canSwitchProfile) || profileSwitchingLabel.isEmpty) return const SizedBox(); + + return OutlinedButton( + onPressed: () async { + if (canSwitchProfile) { + await appProfileService.switchProfile(); + } else { + _profileSwitchPermissionRequested = await appProfileService.requestInteractAcrossProfiles(); + } + }, + child: Text(profileSwitchingLabel), + ); + }, + ), + const SizedBox(height: 8), + ], + ), + ), + ), + ); + } + + Widget _buildHomeLink() { + // route name used for display purposes, no actual routing + const displayRoute = HomePage.routeName; + const leading = DrawerPageIcon(route: displayRoute); + const title = DrawerPageTitle(route: displayRoute); + + switch (settings.homeNavItem.route) { + case CollectionPage.routeName: + final filters = settings.homeCustomCollection; + if (filters.isNotEmpty) { + return CollectionNavTile( + leading: leading, + title: title, + filters: filters, + isSelected: () => setEquals(currentCollection?.filters, filters), + ); + } + case ExplorerPage.routeName: + final path = settings.homeCustomExplorerPath; + if (path != null) { + return PageNavTile( + leading: leading, + title: title, + navItem: AvesNavItem(route: ExplorerPage.routeName, path: path), + isSelected: () => widget.currentExplorerPath == path, + ); + } + } + return const SizedBox(); + } + + List<Widget> _buildTypeLinks() { + final hiddenFilters = settings.hiddenFilters; + final typeBookmarks = settings.drawerTypeBookmarks; + final currentFilters = currentCollection?.filters; + return typeBookmarks + .where((filter) => !hiddenFilters.contains(filter)) + .map((filter) => CollectionNavTile( + // key is expected by test driver + key: Key('drawer-type-${filter?.key}'), + leading: DrawerFilterIcon(filter: filter), + title: DrawerFilterTitle(filter: filter), + filters: {filter}, + isSelected: () { + if (currentFilters == null || currentFilters.length > 1) return false; + return currentFilters.firstOrNull == filter; + }, + )) + .toList(); + } + + Widget _buildAlbumLinks(BuildContext context) { + final source = context.read<CollectionSource>(); + final currentFilters = currentCollection?.filters; + return StreamBuilder( + stream: source.eventBus.on<AlbumsChangedEvent>(), + builder: (context, snapshot) { + final albums = AppDrawer.effectiveAlbumBookmarks(context); + if (albums.isEmpty) return const SizedBox(); + return Column( + children: [ + const Divider(), + ...albums.map((filter) => AlbumNavTile( + filter: filter, + isSelected: () { + if (currentFilters == null || currentFilters.length > 1) return false; + final currentFilter = currentFilters.firstOrNull; + if (currentFilter is StoredAlbumFilter && filter is StoredAlbumFilter) { + return currentFilter.album == filter.album; + } else if (currentFilter is DynamicAlbumFilter && filter is DynamicAlbumFilter) { + return currentFilter.name == filter.name; + } + return false; + }, + )), + ], + ); + }); + } + + List<Widget> _buildPageLinks(BuildContext context) { + final pageBookmarks = settings.drawerPageBookmarks; + if (pageBookmarks.isEmpty) return []; + + final source = context.read<CollectionSource>(); + return [ + const Divider(), + ...pageBookmarks.map((route) { + Widget? trailing; + switch (route) { + case AlbumListPage.routeName: + trailing = StreamBuilder( + stream: source.eventBus.on<AlbumsChangedEvent>(), + builder: (context, _) => Text('${source.rawAlbums.length}'), + ); + case CountryListPage.routeName: + trailing = StreamBuilder( + stream: source.eventBus.on<CountriesChangedEvent>(), + builder: (context, _) => Text('${source.sortedCountries.length}'), + ); + case PlaceListPage.routeName: + trailing = StreamBuilder( + stream: source.eventBus.on<PlacesChangedEvent>(), + builder: (context, _) => Text('${source.sortedPlaces.length}'), + ); + case TagListPage.routeName: + trailing = StreamBuilder( + stream: source.eventBus.on<TagsChangedEvent>(), + builder: (context, _) => Text('${source.sortedTags.length}'), + ); + } + + return PageNavTile( + // key is expected by test driver + key: Key('drawer-page-$route'), + trailing: trailing, + navItem: AvesNavItem(route: route), + ); + }), + ]; + } + + Widget binTile(BuildContext context) { + final source = context.read<CollectionSource>(); + final trashSize = source.trashedEntries.fold<int>(0, (sum, entry) => sum + (entry.sizeBytes ?? 0)); + + const filter = TrashFilter.instance; + return CollectionNavTile( + leading: const DrawerFilterIcon(filter: filter), + title: const DrawerFilterTitle(filter: filter), + trailing: Text(formatFileSize(context.locale, trashSize, round: 0)), + filters: {filter}, + isSelected: () => currentCollection?.filters.contains(filter) ?? false, + ); + } + + Widget get debugTile => const PageNavTile( + // key is expected by test driver + key: Key('drawer-debug'), + navItem: AvesNavItem(route: AppDebugPage.routeName), + ); +} diff --git a/lib/widgets/navigation/drawer/collection_nav_tile.dart b/lib/widgets/navigation/drawer/collection_nav_tile.dart new file mode 100644 index 0000000..abc03b5 --- /dev/null +++ b/lib/widgets/navigation/drawer/collection_nav_tile.dart @@ -0,0 +1,111 @@ +import 'dart:async'; + +import 'package:aves/model/filters/container/album_group.dart'; +import 'package:aves/model/filters/covered/stored_album.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/collection/collection_page.dart'; +import 'package:aves/widgets/common/action_mixins/feedback.dart'; +import 'package:aves/widgets/common/action_mixins/vault_aware.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/navigation/drawer/tile.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class CollectionNavTile extends StatelessWidget with FeedbackMixin, VaultAwareMixin { + final Widget? leading; + final Widget title; + final Widget? trailing; + final Set<CollectionFilter?>? filters; + final bool Function() isSelected; + + const CollectionNavTile({ + super.key, + required this.leading, + required this.title, + this.trailing, + required this.filters, + required this.isSelected, + }); + + @override + Widget build(BuildContext context) { + return SafeArea( + top: false, + bottom: false, + child: ListTile( + leading: leading, + title: title, + trailing: trailing != null + ? Builder( + builder: (context) { + final trailingColor = IconTheme.of(context).color!.withValues(alpha: .6); + return IconTheme.merge( + data: IconThemeData(color: trailingColor), + child: DefaultTextStyle.merge( + style: TextStyle(color: trailingColor), + child: trailing!, + ), + ); + }, + ) + : null, + onTap: () => _goToCollection(context), + selected: context.currentRouteName == CollectionPage.routeName && isSelected(), + ), + ); + } + + Future<void> _goToCollection(BuildContext context) async { + final _filters = filters; + if (_filters != null) { + for (final filter in _filters) { + if (filter != null) { + if (!await unlockFilter(context, filter)) return; + } + } + } + + Navigator.maybeOf(context)?.pop(); + unawaited(Navigator.maybeOf(context)?.pushAndRemoveUntil( + MaterialPageRoute( + settings: const RouteSettings(name: CollectionPage.routeName), + builder: (context) => CollectionPage( + source: context.read<CollectionSource>(), + filters: _filters, + ), + ), + (route) => false, + )); + } +} + +class AlbumNavTile extends StatelessWidget { + final AlbumBaseFilter filter; + final bool Function() isSelected; + + const AlbumNavTile({ + super.key, + required this.filter, + required this.isSelected, + }); + + @override + Widget build(BuildContext context) { + final _filter = filter; + final storageVolume = _filter is StoredAlbumFilter ? _filter.storageVolume : null; + return CollectionNavTile( + leading: DrawerFilterIcon(filter: _filter), + title: DrawerFilterTitle(filter: _filter), + trailing: storageVolume?.isRemovable ?? false + ? const Icon( + AIcons.storageCard, + size: 16, + ) + : null, + filters: {_filter}, + isSelected: isSelected, + ); + } +} diff --git a/lib/widgets/navigation/drawer/page_nav_tile.dart b/lib/widgets/navigation/drawer/page_nav_tile.dart new file mode 100644 index 0000000..a5332b4 --- /dev/null +++ b/lib/widgets/navigation/drawer/page_nav_tile.dart @@ -0,0 +1,53 @@ +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/navigation/drawer/tile.dart'; +import 'package:aves/widgets/navigation/nav_item.dart'; +import 'package:flutter/material.dart'; + +typedef TileRouteBuilder = Route Function(BuildContext context, String routeName, bool topLevel); + +class PageNavTile extends StatelessWidget { + final Widget? leading; + final Widget? title; + final Widget? trailing; + final AvesNavItem navItem; + final bool Function()? isSelected; + + const PageNavTile({ + super.key, + this.leading, + this.title, + this.trailing, + required this.navItem, + this.isSelected, + }); + + @override + Widget build(BuildContext context) { + final routeName = navItem.route; + return SafeArea( + top: false, + bottom: false, + child: ListTile( + // key is expected by test driver + key: Key('$routeName-tile'), + leading: leading ?? DrawerPageIcon(route: routeName), + title: title ?? DrawerPageTitle(route: routeName), + trailing: trailing != null + ? Builder( + builder: (context) => DefaultTextStyle.merge( + style: TextStyle( + color: IconTheme.of(context).color!.withValues(alpha: .6), + ), + child: trailing!, + ), + ) + : null, + onTap: () { + Navigator.maybeOf(context)?.pop(); + navItem.goTo(context); + }, + selected: context.currentRouteName == routeName && (isSelected?.call() ?? true), + ), + ); + } +} diff --git a/lib/widgets/navigation/drawer/tile.dart b/lib/widgets/navigation/drawer/tile.dart new file mode 100644 index 0000000..10b5a7e --- /dev/null +++ b/lib/widgets/navigation/drawer/tile.dart @@ -0,0 +1,76 @@ +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/theme/colors.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/debug/app_debug_page.dart'; +import 'package:aves/widgets/navigation/nav_display.dart'; +import 'package:flutter/material.dart'; + +class DrawerFilterIcon extends StatelessWidget { + final CollectionFilter? filter; + + const DrawerFilterIcon({ + super.key, + required this.filter, + }); + + @override + Widget build(BuildContext context) { + final textScaler = MediaQuery.textScalerOf(context); + final iconSize = textScaler.scale(24); + + final _filter = filter; + if (_filter == null) return Icon(AIcons.allCollection, size: iconSize); + return _filter.iconBuilder(context, iconSize) ?? const SizedBox(); + } +} + +class DrawerFilterTitle extends StatelessWidget { + final CollectionFilter? filter; + + const DrawerFilterTitle({ + super.key, + required this.filter, + }); + + @override + Widget build(BuildContext context) => Text(NavigationDisplay.getFilterTitle(context, filter)); +} + +class DrawerPageIcon extends StatelessWidget { + final String route; + + const DrawerPageIcon({ + super.key, + required this.route, + }); + + @override + Widget build(BuildContext context) { + final icon = NavigationDisplay.getPageIcon(route); + if (icon != null) { + switch (route) { + case AppDebugPage.routeName: + return ShaderMask( + shaderCallback: AvesColorsData.debugGradient.createShader, + blendMode: BlendMode.srcIn, + child: Icon(icon), + ); + default: + return Icon(icon); + } + } + return const SizedBox(); + } +} + +class DrawerPageTitle extends StatelessWidget { + final String route; + + const DrawerPageTitle({ + super.key, + required this.route, + }); + + @override + Widget build(BuildContext context) => Text(NavigationDisplay.getPageTitle(context, route)); +} diff --git a/lib/widgets/navigation/nav_bar/floating.dart b/lib/widgets/navigation/nav_bar/floating.dart new file mode 100644 index 0000000..da0e7d5 --- /dev/null +++ b/lib/widgets/navigation/nav_bar/floating.dart @@ -0,0 +1,123 @@ +import 'dart:async'; +import 'dart:math'; + +import 'package:aves/widgets/common/basic/draggable_scrollbar/notifications.dart'; +import 'package:flutter/material.dart'; + +class FloatingNavBar extends StatefulWidget { + final ScrollController? scrollController; + final Stream<DraggableScrollbarEvent> events; + final double childHeight; + final Widget child; + + const FloatingNavBar({ + super.key, + required this.scrollController, + required this.events, + required this.childHeight, + required this.child, + }); + + @override + State<FloatingNavBar> createState() => _FloatingNavBarState(); +} + +class _FloatingNavBarState extends State<FloatingNavBar> with SingleTickerProviderStateMixin { + final Set<StreamSubscription> _subscriptions = {}; + late AnimationController _controller; + late CurvedAnimation _animation; + late Animation<Offset> _offset; + double? _lastOffset; + bool _isDragging = false; + + @override + void initState() { + super.initState(); + _controller = AnimationController( + duration: const Duration(milliseconds: 200), + vsync: this, + ); + _animation = CurvedAnimation( + parent: _controller, + curve: Curves.linear, + ); + _offset = Tween<Offset>( + begin: const Offset(0, 0), + end: const Offset(0, 1), + ).animate(_animation) + ..addListener(() { + if (!mounted) return; + setState(() {}); + }); + _registerWidget(widget); + } + + @override + void didUpdateWidget(covariant FloatingNavBar oldWidget) { + super.didUpdateWidget(oldWidget); + + if (oldWidget.scrollController != widget.scrollController) { + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + } + + @override + void dispose() { + _unregisterWidget(widget); + _animation.dispose(); + _controller.dispose(); + super.dispose(); + } + + void _registerWidget(FloatingNavBar widget) { + _lastOffset = null; + widget.scrollController?.addListener(_onScrollChanged); + _subscriptions.add(widget.events.listen(_onDraggableScrollBarEvent)); + } + + void _unregisterWidget(FloatingNavBar widget) { + widget.scrollController?.removeListener(_onScrollChanged); + _subscriptions + ..forEach((sub) => sub.cancel()) + ..clear(); + } + + @override + Widget build(BuildContext context) { + return SlideTransition( + position: _offset, + child: widget.child, + ); + } + + void _onScrollChanged() { + final scrollController = widget.scrollController; + if (scrollController == null) return; + + final offset = scrollController.offset; + final delta = offset - (_lastOffset ?? offset); + _lastOffset = offset; + + double? newValue; + final childHeight = widget.childHeight; + final after = scrollController.position.extentAfter; + if (after < childHeight && delta > 0) { + newValue = min(_controller.value, after / childHeight); + } else if (!_isDragging || delta > 0) { + newValue = _controller.value + delta / childHeight; + } + if (newValue != null) { + _controller.value = newValue.clamp(0.0, 1.0); + } + } + + void _onDraggableScrollBarEvent(DraggableScrollbarEvent event) { + switch (event) { + case DraggableScrollbarEvent.dragStart: + _isDragging = true; + case DraggableScrollbarEvent.dragEnd: + _isDragging = false; + } + } +} diff --git a/lib/widgets/navigation/nav_bar/nav_bar.dart b/lib/widgets/navigation/nav_bar/nav_bar.dart new file mode 100644 index 0000000..3ec4b5e --- /dev/null +++ b/lib/widgets/navigation/nav_bar/nav_bar.dart @@ -0,0 +1,153 @@ +import 'package:aves/app_mode.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/widgets/collection/collection_page.dart'; +import 'package:aves/widgets/common/basic/draggable_scrollbar/notifications.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/extensions/media_query.dart'; +import 'package:aves/widgets/common/identity/aves_app_bar.dart'; +import 'package:aves/widgets/navigation/nav_bar/floating.dart'; +import 'package:aves/widgets/navigation/nav_item.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class AppBottomNavBar extends StatefulWidget { + final Stream<DraggableScrollbarEvent> events; + + // collection loaded in the `CollectionPage`, if any + final CollectionLens? currentCollection; + + static double get height => kBottomNavigationBarHeight + AvesFloatingBar.margin.vertical; + + const AppBottomNavBar({ + super.key, + required this.events, + this.currentCollection, + }); + + @override + State<AppBottomNavBar> createState() => _AppBottomNavBarState(); +} + +class _AppBottomNavBarState extends State<AppBottomNavBar> { + String? _lastRoute; + + @override + void initState() { + super.initState(); + _registerWidget(widget); + } + + @override + void didUpdateWidget(covariant AppBottomNavBar oldWidget) { + super.didUpdateWidget(oldWidget); + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + + @override + void dispose() { + _unregisterWidget(widget); + super.dispose(); + } + + void _registerWidget(AppBottomNavBar widget) { + widget.currentCollection?.filterChangeNotifier.addListener(_onCollectionFilterChanged); + } + + void _unregisterWidget(AppBottomNavBar widget) { + widget.currentCollection?.filterChangeNotifier.removeListener(_onCollectionFilterChanged); + } + + @override + Widget build(BuildContext context) { + final items = context.select<Settings, List<AvesNavItem>>((v) => v.bottomNavigationActions); + if (items.length < 2) return const SizedBox(); + + Widget child = FloatingNavBar( + scrollController: PrimaryScrollController.of(context), + events: widget.events, + childHeight: AppBottomNavBar.height + context.select<MediaQueryData, double>((mq) => mq.effectiveBottomPadding), + child: SafeArea( + child: AvesFloatingBar( + builder: (context, backgroundColor, child) => BottomNavigationBar( + items: items.map((item) { + final label = item.getText(context); + return BottomNavigationBarItem( + icon: item.getIcon(context), + label: label, + tooltip: label, + ); + }).toList(), + onTap: (index) => _goTo(context, items, index), + currentIndex: _getCurrentIndex(context, items), + type: BottomNavigationBarType.fixed, + backgroundColor: backgroundColor, + showSelectedLabels: false, + showUnselectedLabels: false, + ), + ), + ), + ); + + final animate = context.select<Settings, bool>((v) => v.animate); + if (animate) { + child = Hero( + tag: 'nav-bar', + flightShuttleBuilder: (flightContext, animation, flightDirection, fromHeroContext, toHeroContext) { + return MediaQuery.removeViewInsets( + context: context, + removeBottom: true, + child: toHeroContext.widget, + ); + }, + child: child, + ); + } + + return child; + } + + void _onCollectionFilterChanged() => setState(() {}); + + int _getCurrentIndex(BuildContext context, List<AvesNavItem> items) { + // current route may be null during navigation + final currentRoute = context.currentRouteName ?? _lastRoute; + _lastRoute = currentRoute; + + final currentItem = items.firstWhereOrNull((item) { + final itemRoute = item.route; + if (currentRoute != itemRoute) return false; + + switch (itemRoute) { + case CollectionPage.routeName: + final currentFilters = widget.currentCollection?.filters ?? {}; + return const SetEquality().equals(currentFilters, item.filters ?? {}); + default: + return true; + } + }); + final currentIndex = currentItem != null ? items.indexOf(currentItem) : 0; + return currentIndex; + } + + void _goTo(BuildContext context, List<AvesNavItem> items, int index) { + final item = items[index]; + item.goTo(context, topLevel: null); + } +} + +class NavBarPaddingSliver extends StatelessWidget { + const NavBarPaddingSliver({super.key}); + + @override + Widget build(BuildContext context) { + final canNavigate = context.select<ValueNotifier<AppMode>, bool>((v) => v.value.canNavigate); + final enableBottomNavigationBar = context.select<Settings, bool>((v) => v.enableBottomNavigationBar); + final showBottomNavigationBar = canNavigate && enableBottomNavigationBar; + return SliverToBoxAdapter( + child: SizedBox(height: showBottomNavigationBar ? AppBottomNavBar.height : 0), + ); + } +} diff --git a/lib/widgets/navigation/nav_display.dart b/lib/widgets/navigation/nav_display.dart new file mode 100644 index 0000000..20ac5dd --- /dev/null +++ b/lib/widgets/navigation/nav_display.dart @@ -0,0 +1,88 @@ +import 'package:aves/model/filters/favourite.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/filters/mime.dart'; +import 'package:aves/model/filters/type.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/about/about_page.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/search/page.dart'; +import 'package:aves/widgets/debug/app_debug_page.dart'; +import 'package:aves/widgets/explorer/explorer_page.dart'; +import 'package:aves/widgets/filter_grids/albums_page.dart'; +import 'package:aves/widgets/filter_grids/countries_page.dart'; +import 'package:aves/widgets/filter_grids/places_page.dart'; +import 'package:aves/widgets/filter_grids/tags_page.dart'; +import 'package:aves/widgets/home/home_page.dart'; +import 'package:aves/widgets/settings/settings_page.dart'; +import 'package:flutter/material.dart'; + +class NavigationDisplay { + static String getFilterTitle(BuildContext context, CollectionFilter? filter) { + final l10n = context.l10n; + if (filter == null) return l10n.drawerCollectionAll; + if (filter == FavouriteFilter.instance) return l10n.drawerCollectionFavourites; + if (filter == MimeFilter.image) return l10n.drawerCollectionImages; + if (filter == MimeFilter.video) return l10n.drawerCollectionVideos; + if (filter == TypeFilter.animated) return l10n.drawerCollectionAnimated; + if (filter == TypeFilter.motionPhoto) return l10n.drawerCollectionMotionPhotos; + if (filter == TypeFilter.panorama) return l10n.drawerCollectionPanoramas; + if (filter == TypeFilter.raw) return l10n.drawerCollectionRaws; + if (filter == TypeFilter.sphericalVideo) return l10n.drawerCollectionSphericalVideos; + return filter.getLabel(context); + } + + static String getPageTitle(BuildContext context, route) { + final l10n = context.l10n; + switch (route) { + case HomePage.routeName: + return l10n.settingsHomeTile; + case AlbumListPage.routeName: + return l10n.drawerAlbumPage; + case CountryListPage.routeName: + return l10n.drawerCountryPage; + case PlaceListPage.routeName: + return l10n.drawerPlacePage; + case TagListPage.routeName: + return l10n.drawerTagPage; + case AboutPage.routeName: + return l10n.aboutPageTitle; + case AppDebugPage.routeName: + return 'Debug'; + case ExplorerPage.routeName: + return l10n.explorerPageTitle; + case SearchPage.routeName: + return MaterialLocalizations.of(context).searchFieldLabel; + case SettingsPage.routeName: + return l10n.settingsPageTitle; + default: + return route; + } + } + + static IconData? getPageIcon(String route) { + switch (route) { + case HomePage.routeName: + return AIcons.home; + case AlbumListPage.routeName: + return AIcons.album; + case CountryListPage.routeName: + return AIcons.country; + case PlaceListPage.routeName: + return AIcons.place; + case TagListPage.routeName: + return AIcons.tag; + case AboutPage.routeName: + return AIcons.info; + case AppDebugPage.routeName: + return AIcons.debug; + case ExplorerPage.routeName: + return AIcons.explorer; + case SearchPage.routeName: + return AIcons.search; + case SettingsPage.routeName: + return AIcons.settings; + default: + return null; + } + } +} diff --git a/lib/widgets/navigation/nav_item.dart b/lib/widgets/navigation/nav_item.dart new file mode 100644 index 0000000..8ba896a --- /dev/null +++ b/lib/widgets/navigation/nav_item.dart @@ -0,0 +1,167 @@ +import 'dart:convert'; + +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/widgets/about/about_page.dart'; +import 'package:aves/widgets/collection/collection_page.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/search/page.dart'; +import 'package:aves/widgets/common/search/route.dart'; +import 'package:aves/widgets/debug/app_debug_page.dart'; +import 'package:aves/widgets/explorer/explorer_page.dart'; +import 'package:aves/widgets/filter_grids/albums_page.dart'; +import 'package:aves/widgets/filter_grids/countries_page.dart'; +import 'package:aves/widgets/filter_grids/places_page.dart'; +import 'package:aves/widgets/filter_grids/tags_page.dart'; +import 'package:aves/widgets/home/home_page.dart'; +import 'package:aves/widgets/navigation/drawer/tile.dart'; +import 'package:aves/widgets/navigation/nav_display.dart'; +import 'package:aves/widgets/search/collection_search_delegate.dart'; +import 'package:aves/widgets/settings/settings_page.dart'; +import 'package:equatable/equatable.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class AvesNavItem extends Equatable { + final String route; + final Set<CollectionFilter>? filters; + final String? path; + + @override + List<Object?> get props => [route, filters, path]; + + const AvesNavItem({ + required this.route, + this.filters, + this.path, + }); + + Widget getIcon(BuildContext context) { + if (route == CollectionPage.routeName) { + return DrawerFilterIcon(filter: filters?.firstOrNull); + } + + final textScaler = MediaQuery.textScalerOf(context); + final iconSize = textScaler.scale(24); + return Icon(NavigationDisplay.getPageIcon(route), size: iconSize); + } + + String getText(BuildContext context) { + if (route == CollectionPage.routeName) { + return NavigationDisplay.getFilterTitle(context, filters?.firstOrNull); + } + return NavigationDisplay.getPageTitle(context, route); + } + + Future<void> goTo(BuildContext context, {bool? topLevel}) async { + topLevel ??= _defaultTopLevel; + final route = routeBuilder(context, topLevel: topLevel); + if (topLevel) { + await Navigator.maybeOf(context)?.pushAndRemoveUntil( + route, + (route) => false, + ); + } else { + await Navigator.maybeOf(context)?.push(route); + } + } + + bool get _defaultTopLevel { + switch (route) { + case AboutPage.routeName: + case AppDebugPage.routeName: + case SearchPage.routeName: + case SettingsPage.routeName: + return false; + default: + return true; + } + } + + Route routeBuilder(BuildContext context, {required bool topLevel}) { + switch (route) { + case HomePage.routeName: + return settings.homeNavItem.routeBuilder(context, topLevel: topLevel); + case SearchPage.routeName: + final currentCollection = context.read<CollectionLens?>(); + return SearchPageRoute( + delegate: CollectionSearchDelegate( + searchFieldLabel: context.l10n.searchCollectionFieldHint, + searchFieldStyle: Themes.searchFieldStyle(context), + source: context.read<CollectionSource>(), + parentCollection: topLevel ? currentCollection?.copyWith() : currentCollection, + ), + ); + default: + return MaterialPageRoute( + settings: RouteSettings(name: route), + builder: _materialPageBuilder(route), + ); + } + } + + WidgetBuilder _materialPageBuilder(String route) { + switch (route) { + case CollectionPage.routeName: + return (context) => CollectionPage( + source: context.read<CollectionSource>(), + filters: filters, + ); + case AlbumListPage.routeName: + return (_) => const AlbumListPage(initialGroup: null); + case CountryListPage.routeName: + return (_) => const CountryListPage(); + case PlaceListPage.routeName: + return (_) => const PlaceListPage(); + case TagListPage.routeName: + return (_) => const TagListPage(initialGroup: null); + case AboutPage.routeName: + return (_) => const AboutPage(); + case AppDebugPage.routeName: + return (_) => const AppDebugPage(); + case ExplorerPage.routeName: + return (_) => ExplorerPage(path: path); + case SettingsPage.routeName: + return (_) => const SettingsPage(); + default: + throw Exception('unknown route=$route'); + } + } + + // serialization + + static AvesNavItem _fromMap(Map<String, dynamic> json) { + return AvesNavItem( + route: json['route'], + filters: (json['filters'] as List?)?.cast<String>().map(CollectionFilter.fromJson).nonNulls.toSet(), + path: json['path'], + ); + } + + Map<String, dynamic> _toMap() => { + 'route': route, + if (filters != null) 'filters': filters?.map((v) => v.toJson()).toList(), + if (path != null) 'path': path, + }; + + String toJson() => jsonEncode(_toMap()); + + static AvesNavItem? fromJson(String? jsonString) { + if (jsonString == null || jsonString.isEmpty) return null; + + try { + final jsonMap = jsonDecode(jsonString); + if (jsonMap is Map<String, dynamic>) { + return _fromMap(jsonMap); + } + debugPrint('failed to parse navigation item from json=$jsonString'); + } catch (error) { + // no need for stack + debugPrint('failed to parse navigation item from json=$jsonString error=$error'); + } + return null; + } +} diff --git a/lib/widgets/navigation/tv_page_transitions.dart b/lib/widgets/navigation/tv_page_transitions.dart new file mode 100644 index 0000000..69f21d0 --- /dev/null +++ b/lib/widgets/navigation/tv_page_transitions.dart @@ -0,0 +1,36 @@ +import 'package:flutter/material.dart'; + +class TvPageTransitionsBuilder extends PageTransitionsBuilder { + const TvPageTransitionsBuilder(); + + @override + Widget buildTransitions<T>( + PageRoute<T>? route, + BuildContext? context, + Animation<double> animation, + Animation<double>? secondaryAnimation, + Widget child, + ) { + return _TvPageTransition(routeAnimation: animation, child: child); + } +} + +class _TvPageTransition extends StatelessWidget { + final Animation<double> _opacityAnimation; + final Widget child; + + static final Animatable<double> _easeInTween = CurveTween(curve: Curves.easeIn); + + _TvPageTransition({ + required Animation<double> routeAnimation, + required this.child, + }) : _opacityAnimation = routeAnimation.drive(_easeInTween); + + @override + Widget build(BuildContext context) { + return FadeTransition( + opacity: _opacityAnimation, + child: child, + ); + } +} diff --git a/lib/widgets/navigation/tv_rail.dart b/lib/widgets/navigation/tv_rail.dart new file mode 100644 index 0000000..6714b1b --- /dev/null +++ b/lib/widgets/navigation/tv_rail.dart @@ -0,0 +1,300 @@ +import 'dart:math'; + +import 'package:aves/model/filters/container/dynamic_album.dart'; +import 'package:aves/model/filters/covered/stored_album.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/ref/locales.dart'; +import 'package:aves/widgets/about/about_page.dart'; +import 'package:aves/widgets/collection/collection_page.dart'; +import 'package:aves/widgets/common/basic/insets.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/aves_logo.dart'; +import 'package:aves/widgets/debug/app_debug_page.dart'; +import 'package:aves/widgets/navigation/drawer/app_drawer.dart'; +import 'package:aves/widgets/navigation/drawer/tile.dart'; +import 'package:aves/widgets/navigation/nav_item.dart'; +import 'package:aves/widgets/settings/settings_page.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class TvRailController { + int? focusedIndex; + double offset = 0; +} + +class TvRail extends StatefulWidget { + // collection loaded in the `CollectionPage`, if any + final CollectionLens? currentCollection; + final TvRailController controller; + + static const double minExtendedWidth = 256; + + const TvRail({ + super.key, + required this.controller, + this.currentCollection, + }); + + @override + State<TvRail> createState() => _TvRailState(); +} + +class _TvRailState extends State<TvRail> { + late final ScrollController _scrollController; + final ValueNotifier<bool> _extendedNotifier = ValueNotifier(true); + final FocusNode _focusNode = FocusNode(); + + TvRailController get controller => widget.controller; + + CollectionLens? get currentCollection => widget.currentCollection; + + @override + void initState() { + super.initState(); + _scrollController = ScrollController(initialScrollOffset: controller.offset); + _scrollController.addListener(_onScrollChanged); + + _registerWidget(widget); + WidgetsBinding.instance.addPostFrameCallback((_) => _initFocus()); + } + + @override + void didUpdateWidget(covariant TvRail oldWidget) { + super.didUpdateWidget(oldWidget); + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + + @override + void dispose() { + _unregisterWidget(widget); + _scrollController.removeListener(_onScrollChanged); + _scrollController.dispose(); + _extendedNotifier.dispose(); + _focusNode.dispose(); + super.dispose(); + } + + void _registerWidget(TvRail widget) { + widget.currentCollection?.filterChangeNotifier.addListener(_onCollectionFilterChanged); + } + + void _unregisterWidget(TvRail widget) { + widget.currentCollection?.filterChangeNotifier.removeListener(_onCollectionFilterChanged); + } + + @override + Widget build(BuildContext context) { + final navEntries = _getNavEntries(context); + return DirectionalSafeArea( + end: false, + child: ValueListenableBuilder<bool>( + valueListenable: _extendedNotifier, + builder: (context, extended, child) { + const logo = AvesLogo(size: 48); + final header = extended + ? Row( + children: [ + logo, + const SizedBox(width: 16), + Text( + context.l10n.appName, + style: TextStyle( + color: Colors.white, + fontSize: 32, + fontWeight: FontWeight.w300, + letterSpacing: canHaveLetterSpacing(context.locale) ? 1 : 0, + fontFeatures: const [FontFeature.enable('smcp')], + ), + ), + ], + ) + : logo; + + final railTheme = Theme.of(context).navigationRailTheme; + const double labelFontSize = 16; + final rail = Focus( + focusNode: _focusNode, + skipTraversal: true, + child: NavigationRail( + extended: extended, + destinations: navEntries + .map((v) => NavigationRailDestination( + icon: v.icon, + label: v.label, + padding: const EdgeInsets.symmetric(vertical: 8), + )) + .toList(), + selectedIndex: max(0, navEntries.indexWhere(((v) => v.isSelected))), + onDestinationSelected: (index) { + controller.focusedIndex = index; + navEntries[index].onSelection(); + }, + unselectedLabelTextStyle: railTheme.unselectedLabelTextStyle?.copyWith(fontSize: labelFontSize), + selectedLabelTextStyle: railTheme.selectedLabelTextStyle?.copyWith(fontSize: labelFontSize), + minExtendedWidth: TvRail.minExtendedWidth, + ), + ); + + return Column( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + const SizedBox(height: 8), + header, + const SizedBox(height: 4), + Expanded( + child: LayoutBuilder( + builder: (context, constraints) { + return SingleChildScrollView( + controller: _scrollController, + child: ConstrainedBox( + constraints: BoxConstraints(minHeight: constraints.maxHeight), + child: IntrinsicHeight(child: rail), + ), + ); + }, + ), + ), + ], + ); + }, + ), + ); + } + + void _initFocus() { + var index = controller.focusedIndex ?? -1; + controller.focusedIndex = null; + + if (index == -1) { + final navEntries = _getNavEntries(context); + index = navEntries.indexWhere((v) => v.isHome); + } + + final nodes = _focusNode.children.toList(); + if (0 <= index && index < nodes.length) { + nodes[index].requestFocus(); + } + } + + List<_NavEntry> _getNavEntries(BuildContext context) { + final navEntries = <_NavEntry>[ + ..._buildTypeLinks(), + ..._buildAlbumLinks(context), + ..._buildPageLinks(context), + ...[ + SettingsPage.routeName, + AboutPage.routeName, + if (!kReleaseMode) AppDebugPage.routeName, + ].map(_routeNavEntry), + ]; + return navEntries; + } + + List<_NavEntry> _buildTypeLinks() { + final hiddenFilters = settings.hiddenFilters; + final typeBookmarks = settings.drawerTypeBookmarks; + final currentFilters = currentCollection?.filters; + return typeBookmarks.where((filter) => !hiddenFilters.contains(filter)).map((filter) { + bool isSelected() { + if (currentFilters == null || currentFilters.length > 1) return false; + return currentFilters.firstOrNull == filter; + } + + final homeRoute = settings.homeNavItem.route; + return _NavEntry( + icon: DrawerFilterIcon(filter: filter), + label: DrawerFilterTitle(filter: filter), + isHome: homeRoute == CollectionPage.routeName && filter == null, + isSelected: isSelected(), + onSelection: () => _goToCollection(context, filter), + ); + }).toList(); + } + + List<_NavEntry> _buildAlbumLinks(BuildContext context) { + final currentFilters = currentCollection?.filters; + final albums = AppDrawer.effectiveAlbumBookmarks(context); + return albums.map((filter) { + bool isSelected() { + if (currentFilters == null || currentFilters.length > 1) return false; + final currentFilter = currentFilters.firstOrNull; + if (currentFilter is StoredAlbumFilter && filter is StoredAlbumFilter) { + return currentFilter.album == filter.album; + } else if (currentFilter is DynamicAlbumFilter && filter is DynamicAlbumFilter) { + return currentFilter.name == filter.name; + } + return false; + } + + return _NavEntry( + icon: DrawerFilterIcon(filter: filter), + label: DrawerFilterTitle(filter: filter), + isHome: false, + isSelected: isSelected(), + onSelection: () => _goToCollection(context, filter), + ); + }).toList(); + } + + List<_NavEntry> _buildPageLinks(BuildContext context) { + final pageBookmarks = settings.drawerPageBookmarks; + return pageBookmarks.map(_routeNavEntry).toList(); + } + + _NavEntry _routeNavEntry(String routeName) { + final homeRoute = settings.homeNavItem.route; + return _NavEntry( + icon: DrawerPageIcon(route: routeName), + label: DrawerPageTitle(route: routeName), + isHome: homeRoute != CollectionPage.routeName && routeName == homeRoute, + isSelected: context.currentRouteName == routeName, + onSelection: () => _goTo(routeName), + ); + } + + void _goTo(String routeName) { + final navItem = AvesNavItem(route: routeName); + Navigator.maybeOf(context)?.pushAndRemoveUntil( + navItem.routeBuilder(context, topLevel: true), + (route) => false, + ); + } + + void _goToCollection(BuildContext context, CollectionFilter? filter) { + Navigator.maybeOf(context)?.pushAndRemoveUntil( + MaterialPageRoute( + settings: const RouteSettings(name: CollectionPage.routeName), + builder: (context) => CollectionPage( + source: context.read<CollectionSource>(), + filters: {filter}, + ), + ), + (route) => false, + ); + } + + void _onScrollChanged() => controller.offset = _scrollController.offset; + + void _onCollectionFilterChanged() => setState(() {}); +} + +@immutable +class _NavEntry { + final Widget icon, label; + final bool isHome, isSelected; + final VoidCallback onSelection; + + const _NavEntry({ + required this.icon, + required this.label, + required this.isHome, + required this.isSelected, + required this.onSelection, + }); +} diff --git a/lib/widgets/search/collection_search_delegate.dart b/lib/widgets/search/collection_search_delegate.dart new file mode 100644 index 0000000..fa0c19f --- /dev/null +++ b/lib/widgets/search/collection_search_delegate.dart @@ -0,0 +1,406 @@ +import 'package:aves/model/dynamic_albums.dart'; +import 'package:aves/model/filters/aspect_ratio.dart'; +import 'package:aves/model/filters/container/dynamic_album.dart'; +import 'package:aves/model/filters/container/set_and.dart'; +import 'package:aves/model/filters/covered/location.dart'; +import 'package:aves/model/filters/covered/stored_album.dart'; +import 'package:aves/model/filters/covered/tag.dart'; +import 'package:aves/model/filters/date.dart'; +import 'package:aves/model/filters/favourite.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/filters/mime.dart'; +import 'package:aves/model/filters/missing.dart'; +import 'package:aves/model/filters/query.dart'; +import 'package:aves/model/filters/rating.dart'; +import 'package:aves/model/filters/recent.dart'; +import 'package:aves/model/filters/type.dart'; +import 'package:aves/model/filters/weekday.dart'; +import 'package:aves/model/grouping/common.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/album.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/model/source/location/country.dart'; +import 'package:aves/model/source/location/place.dart'; +import 'package:aves/model/source/tag.dart'; +import 'package:aves/widgets/collection/collection_page.dart'; +import 'package:aves/widgets/common/action_mixins/feedback.dart'; +import 'package:aves/widgets/common/action_mixins/vault_aware.dart'; +import 'package:aves/widgets/common/basic/tv_edge_focus.dart'; +import 'package:aves/widgets/common/expandable_filter_row.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/aves_filter_chip.dart'; +import 'package:aves/widgets/common/search/delegate.dart'; +import 'package:aves/widgets/common/search/page.dart'; +import 'package:aves/widgets/viewer/controls/notifications.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class CollectionSearchDelegate extends AvesSearchDelegate with FeedbackMixin, VaultAwareMixin { + final CollectionSource source; + final CollectionLens? parentCollection; + final ValueNotifier<String?> _expandedSectionNotifier = ValueNotifier(null); + final FocusNode _suggestionsTopFocusNode = FocusNode(); + final ScrollController _suggestionsScrollController = ScrollController(); + late final List<MimeFilter> _mimeTypeFilters; + + @override + FocusNode? get suggestionsFocusNode => _suggestionsTopFocusNode; + + @override + ScrollController get suggestionsScrollController => _suggestionsScrollController; + + static const int searchHistoryCount = 10; + static final typeFilters = [ + FavouriteFilter.instance, + MimeFilter.image, + MimeFilter.video, + TypeFilter.animated, + TypeFilter.motionPhoto, + AspectRatioFilter.portrait, + AspectRatioFilter.landscape, + TypeFilter.panorama, + TypeFilter.sphericalVideo, + TypeFilter.geotiff, + TypeFilter.hdr, + TypeFilter.raw, + ]; + + static final _monthFilters = List.generate(12, (i) => DateFilter(DateLevel.m, DateTime(1, i + 1))); + + CollectionSearchDelegate({ + required super.searchFieldLabel, + required super.searchFieldStyle, + required this.source, + this.parentCollection, + super.canPop, + String? initialQuery, + }) : super( + routeName: SearchPage.routeName, + ) { + query = initialQuery ?? ''; + _mimeTypeFilters = source.visibleEntries.map((entry) => entry.mimeType).toSet().map(MimeFilter.new).toList()..sort(); + } + + @override + void dispose() { + _expandedSectionNotifier.dispose(); + _suggestionsTopFocusNode.dispose(); + _suggestionsScrollController.dispose(); + super.dispose(); + } + + @override + Widget buildSuggestions(BuildContext context) { + final upQuery = query.trim().toUpperCase(); + bool containQuery(CollectionFilter filter) => filter.matchLabel(context, upQuery); + return SafeArea( + child: NotificationListener( + onNotification: (notification) { + if (notification is SelectFilterNotification) { + _select(context, {notification.filter}); + return true; + } else if (notification is DecomposeFilterNotification) { + final filter = notification.filter; + if (filter is DynamicAlbumFilter) { + final innerFilter = filter.filter; + final newFilters = innerFilter is SetAndFilter ? innerFilter.innerFilters : {innerFilter}; + _select(context, newFilters); + return true; + } + } + return false; + }, + child: ValueListenableBuilder<String?>( + valueListenable: _expandedSectionNotifier, + builder: (context, expandedSection, child) { + final queryFilter = _buildQueryFilter(false); + return Selector<Settings, Set<CollectionFilter>>( + selector: (context, s) => s.hiddenFilters, + builder: (context, hiddenFilters, child) { + bool notHidden(CollectionFilter filter) => !hiddenFilters.contains(filter); + bool isVisible(CollectionFilter filter) => containQuery(filter) && notHidden(filter); + + final visibleTypeFilters = typeFilters.where(notHidden).toList(); + if (hiddenFilters.contains(MimeFilter.video)) { + [MimeFilter.image, TypeFilter.sphericalVideo].forEach(visibleTypeFilters.remove); + } + + final history = settings.searchHistory.where(isVisible).toList(); + + return ListView( + controller: _suggestionsScrollController, + padding: const EdgeInsets.only(top: 8), + children: [ + TvEdgeFocus( + focusNode: _suggestionsTopFocusNode, + ), + _buildFilterRow( + context: context, + filters: [ + queryFilter, + ...visibleTypeFilters, + ].nonNulls.where(isVisible).toList(), + // usually perform hero animation only on tapped chips, + // but we also need to animate the query chip when it is selected by submitting the search query + heroTypeBuilder: (filter) => filter == queryFilter ? HeroType.always : HeroType.onTap, + ), + if (upQuery.isEmpty && history.isNotEmpty) + _buildFilterRow( + context: context, + title: context.l10n.searchRecentSectionTitle, + filters: history, + ), + _buildDateFilters(context, isVisible), + _buildMimeTypeFilters(context, isVisible), + _buildAlbumFilters(isVisible), + _buildCountryFilters(isVisible), + _buildStateFilters(isVisible), + _buildPlaceFilters(isVisible), + _buildTagFilters(isVisible), + _buildRatingFilters(context, isVisible), + _buildMetadataFilters(context, isVisible), + ], + ); + }, + ); + }, + ), + ), + ); + } + + Widget _buildFilterRow({ + required BuildContext context, + String? title, + required List<CollectionFilter> filters, + HeroType Function(CollectionFilter filter)? heroTypeBuilder, + }) { + void onTap(filter) => _select(context, {filter is QueryFilter ? QueryFilter(filter.query) : filter}); + const onLongPress = AvesFilterChip.showDefaultLongPressMenu; + return title != null + ? TitledExpandableFilterRow( + title: title, + filters: filters, + expandedNotifier: _expandedSectionNotifier, + heroTypeBuilder: heroTypeBuilder, + onTap: onTap, + onLongPress: onLongPress, + ) + : ExpandableFilterRow( + filters: filters, + isExpanded: false, + heroTypeBuilder: heroTypeBuilder, + onTap: onTap, + onLongPress: onLongPress, + ); + } + + Widget _buildDateFilters(BuildContext context, CollectionFilterPredicate containQuery) { + final firstDayOfWeekIndex = MaterialLocalizations.of(context).firstDayOfWeekIndex; + const daysPerWeek = DateTime.daysPerWeek; + final _weekdayFilters = List.generate(daysPerWeek, (i) => WeekDayFilter((i + firstDayOfWeekIndex - 1) % daysPerWeek + 1)); + + final filters = [ + DateFilter.onThisDay, + RecentlyAddedFilter.instance, + ..._monthFilters, + ..._weekdayFilters, + ].where(containQuery).toList(); + + return _buildFilterRow( + context: context, + title: context.l10n.searchDateSectionTitle, + filters: filters, + ); + } + + Widget _buildMimeTypeFilters(BuildContext context, CollectionFilterPredicate containQuery) { + final filters = _mimeTypeFilters.where(containQuery).toList(); + return _buildFilterRow( + context: context, + title: context.l10n.searchFormatSectionTitle, + filters: filters, + ); + } + + Widget _buildAlbumFilters(CollectionFilterPredicate containQuery) { + return AnimatedBuilder( + animation: dynamicAlbums, + builder: (context, child) => StreamBuilder( + stream: source.eventBus.on<AlbumsChangedEvent>(), + builder: (context, snapshot) { + final filters = [ + ...albumGrouping.getGroups().map(albumGrouping.uriToFilter), + ...source.rawAlbums.map((album) => StoredAlbumFilter( + album, + source.getStoredAlbumDisplayName(context, album), + )), + ...dynamicAlbums.all, + ].nonNulls.where(containQuery).toList() + ..sort(); + return _buildFilterRow( + context: context, + title: context.l10n.searchAlbumsSectionTitle, + filters: filters, + ); + }, + ), + ); + } + + Widget _buildCountryFilters(CollectionFilterPredicate containQuery) { + return StreamBuilder( + stream: source.eventBus.on<CountriesChangedEvent>(), + builder: (context, snapshot) { + return _buildFilterRow( + context: context, + title: context.l10n.searchCountriesSectionTitle, + filters: source.sortedCountries.map((s) => LocationFilter(LocationLevel.country, s)).where(containQuery).toList(), + ); + }, + ); + } + + Widget _buildStateFilters(CollectionFilterPredicate containQuery) { + return StreamBuilder( + stream: source.eventBus.on<PlacesChangedEvent>(), + builder: (context, snapshot) { + return _buildFilterRow( + context: context, + title: context.l10n.searchStatesSectionTitle, + filters: source.sortedStates.map((s) => LocationFilter(LocationLevel.state, s)).where(containQuery).toList(), + ); + }, + ); + } + + Widget _buildPlaceFilters(CollectionFilterPredicate containQuery) { + return StreamBuilder( + stream: source.eventBus.on<PlacesChangedEvent>(), + builder: (context, snapshot) { + return _buildFilterRow( + context: context, + title: context.l10n.searchPlacesSectionTitle, + filters: source.sortedPlaces.map((s) => LocationFilter(LocationLevel.place, s)).where(containQuery).toList(), + ); + }, + ); + } + + Widget _buildTagFilters(CollectionFilterPredicate containQuery) { + return StreamBuilder( + stream: source.eventBus.on<TagsChangedEvent>(), + builder: (context, snapshot) { + final filters = [ + ...tagGrouping.getGroups().map(tagGrouping.uriToFilter), + ...source.sortedTags.map(TagFilter.new), + ].nonNulls.where(containQuery).toList() + ..sort(); + return _buildFilterRow( + context: context, + title: context.l10n.searchTagsSectionTitle, + filters: filters, + ); + }, + ); + } + + Widget _buildRatingFilters(BuildContext context, CollectionFilterPredicate containQuery) { + return _buildFilterRow( + context: context, + title: context.l10n.searchRatingSectionTitle, + filters: [5, 4, 3, 2, 1, -1].map(RatingFilter.new).where(containQuery).toList(), + ); + } + + Widget _buildMetadataFilters(BuildContext context, CollectionFilterPredicate containQuery) { + return _buildFilterRow( + context: context, + title: context.l10n.searchMetadataSectionTitle, + filters: [ + MissingFilter.date, + LocationFilter.unlocated, + MissingFilter.fineAddress, + TagFilter(''), + RatingFilter(0), + MissingFilter.title, + ].where(containQuery).toList(), + ); + } + + var _selectingFromQuery = false; + + @override + Widget buildResults(BuildContext context) { + // guard against multiple build calls + if (!_selectingFromQuery) { + _selectingFromQuery = true; + WidgetsBinding.instance.addPostFrameCallback((_) { + // `buildResults` is called in the build phase, + // so we post the call that will filter the collection + // and possibly trigger a rebuild here + _select(context, {_buildQueryFilter(true)}); + }); + } + return const SizedBox(); + } + + QueryFilter? _buildQueryFilter(bool colorful) { + final cleanQuery = query.trim(); + return cleanQuery.isNotEmpty ? QueryFilter(cleanQuery, colorful: colorful) : null; + } + + Future<void> _select(BuildContext context, Set<CollectionFilter?> filters) async { + final newFilters = filters.nonNulls.toSet(); + if (newFilters.isEmpty) { + goBack(context); + return; + } + + for (final filter in newFilters) { + if (!await unlockFilter(context, filter)) return; + + if (settings.saveSearchHistory) { + final history = settings.searchHistory + ..remove(filter) + ..insert(0, filter); + settings.searchHistory = history.take(searchHistoryCount).toList(); + } + } + + if (parentCollection != null) { + _applyToParentCollectionPage(context, newFilters); + } else { + _jumpToCollectionPage(context, newFilters); + } + } + + void _applyToParentCollectionPage(BuildContext context, Set<CollectionFilter> filters) { + parentCollection!.addFilters(filters); + if (Navigator.canPop(context)) { + // We delay closing the current page after applying the filter selection + // so that hero animation target is ready in the `FilterBar`, + // even when the target is a child of an `AnimatedList`. + // Do not use `WidgetsBinding.instance.addPostFrameCallback`, + // as it may not trigger if there is no subsequent build. + Future.delayed(const Duration(milliseconds: 100), () => goBack(context)); + } else { + _jumpToCollectionPage(context, parentCollection!.filters); + } + } + + void _jumpToCollectionPage(BuildContext context, Set<CollectionFilter> filters) { + clean(); + Navigator.maybeOf(context)?.pushAndRemoveUntil( + MaterialPageRoute( + settings: const RouteSettings(name: CollectionPage.routeName), + builder: (context) => CollectionPage( + source: source, + filters: filters, + ), + ), + (route) => false, + ); + } +} diff --git a/lib/widgets/settings/accessibility/accessibility.dart b/lib/widgets/settings/accessibility/accessibility.dart new file mode 100644 index 0000000..f7f558f --- /dev/null +++ b/lib/widgets/settings/accessibility/accessibility.dart @@ -0,0 +1,70 @@ +import 'dart:async'; + +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/colors.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/settings/accessibility/time_to_take_action.dart'; +import 'package:aves/widgets/settings/common/tile_leading.dart'; +import 'package:aves/widgets/settings/common/tiles.dart'; +import 'package:aves/widgets/settings/settings_definition.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class AccessibilitySection extends SettingsSection { + @override + String get key => 'accessibility'; + + @override + Widget icon(BuildContext context) => SettingsTileLeading( + icon: AIcons.accessibility, + color: context.select<AvesColorsData, Color>((v) => v.accessibility), + ); + + @override + String title(BuildContext context) => context.l10n.settingsAccessibilitySectionTitle; + + @override + FutureOr<List<SettingsTile>> tiles(BuildContext context) => [ + if (!settings.useTvLayout) SettingsTileAccessibilityShowPinchGestureAlternatives(), + SettingsTileAccessibilityAnimations(), + SettingsTileAccessibilityTimeToTakeAction(), + ]; +} + +class SettingsTileAccessibilityShowPinchGestureAlternatives extends SettingsTile { + @override + String title(BuildContext context) => context.l10n.settingsAccessibilityShowPinchGestureAlternatives; + + @override + Widget build(BuildContext context) => SettingsSwitchListTile( + selector: (context, s) => s.showPinchGestureAlternatives, + onChanged: (v) => settings.showPinchGestureAlternatives = v, + title: title(context), + ); +} + +class SettingsTileAccessibilityAnimations extends SettingsTile { + @override + String title(BuildContext context) => context.l10n.settingsRemoveAnimationsTile; + + @override + Widget build(BuildContext context) => SettingsSelectionListTile<AccessibilityAnimations>( + values: AccessibilityAnimations.values, + getName: (context, v) => v.getName(context), + selector: (context, s) => s.accessibilityAnimations, + onSelection: (v) => settings.accessibilityAnimations = v, + tileTitle: title(context), + dialogTitle: context.l10n.settingsRemoveAnimationsDialogTitle, + ); +} + +class SettingsTileAccessibilityTimeToTakeAction extends SettingsTile { + @override + String title(BuildContext context) => context.l10n.settingsTimeToTakeActionTile; + + @override + Widget build(BuildContext context) => const TimeToTakeActionTile(); +} diff --git a/lib/widgets/settings/accessibility/time_to_take_action.dart b/lib/widgets/settings/accessibility/time_to_take_action.dart new file mode 100644 index 0000000..34455b6 --- /dev/null +++ b/lib/widgets/settings/accessibility/time_to_take_action.dart @@ -0,0 +1,44 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/services/accessibility_service.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/settings/common/tiles.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; + +class TimeToTakeActionTile extends StatefulWidget { + const TimeToTakeActionTile({super.key}); + + @override + State<TimeToTakeActionTile> createState() => _TimeToTakeActionTileState(); +} + +class _TimeToTakeActionTileState extends State<TimeToTakeActionTile> { + late Future<bool> _hasSystemOptionLoader; + + @override + void initState() { + super.initState(); + _hasSystemOptionLoader = AccessibilityService.hasRecommendedTimeouts(); + } + + @override + Widget build(BuildContext context) { + return FutureBuilder<bool>( + future: _hasSystemOptionLoader, + builder: (context, snapshot) { + if (snapshot.hasError || !snapshot.hasData) return const SizedBox(); + final hasSystemOption = snapshot.data!; + final optionValues = hasSystemOption ? AccessibilityTimeout.values : AccessibilityTimeout.values.where((v) => v != AccessibilityTimeout.system).toList(); + + return SettingsSelectionListTile<AccessibilityTimeout>( + values: optionValues, + getName: (context, v) => v.getName(context), + selector: (context, s) => s.timeToTakeAction, + onSelection: (v) => settings.timeToTakeAction = v, + tileTitle: context.l10n.settingsTimeToTakeActionTile, + ); + }, + ); + } +} diff --git a/lib/widgets/settings/app_export/items.dart b/lib/widgets/settings/app_export/items.dart new file mode 100644 index 0000000..ce52d84 --- /dev/null +++ b/lib/widgets/settings/app_export/items.dart @@ -0,0 +1,46 @@ +import 'package:aves/model/covers.dart'; +import 'package:aves/model/dynamic_albums.dart'; +import 'package:aves/model/favourites.dart'; +import 'package:aves/model/grouping/common.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:flutter/widgets.dart'; + +enum AppExportItem { covers, dynamicAlbums, favourites, settings } + +extension ExtraAppExportItem on AppExportItem { + String getText(BuildContext context) { + final l10n = context.l10n; + return switch (this) { + AppExportItem.covers => l10n.appExportCovers, + AppExportItem.dynamicAlbums => l10n.appExportDynamicAlbums, + AppExportItem.favourites => l10n.appExportFavourites, + AppExportItem.settings => l10n.appExportSettings, + }; + } + + dynamic export(CollectionSource source) { + return switch (this) { + AppExportItem.covers => covers.export(source), + AppExportItem.dynamicAlbums => dynamicAlbums.export(), + AppExportItem.favourites => favourites.export(source), + AppExportItem.settings => settings.export(), + }; + } + + Future<void> import(dynamic jsonMap, CollectionSource source) async { + switch (this) { + case AppExportItem.covers: + covers.import(jsonMap, source); + case AppExportItem.dynamicAlbums: + dynamicAlbums.import(jsonMap); + case AppExportItem.favourites: + favourites.import(jsonMap, source); + case AppExportItem.settings: + await settings.import(jsonMap); + albumGrouping.setGroups(settings.albumGroups); + tagGrouping.setGroups(settings.tagGroups); + } + } +} diff --git a/lib/widgets/settings/app_export/selection_dialog.dart b/lib/widgets/settings/app_export/selection_dialog.dart new file mode 100644 index 0000000..b057741 --- /dev/null +++ b/lib/widgets/settings/app_export/selection_dialog.dart @@ -0,0 +1,65 @@ +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:aves/widgets/settings/app_export/items.dart'; +import 'package:flutter/material.dart'; + +class AppExportItemSelectionDialog extends StatefulWidget { + final String title; + final Set<AppExportItem>? selectableItems, initialSelection; + + const AppExportItemSelectionDialog({ + super.key, + required this.title, + this.selectableItems, + this.initialSelection, + }); + + @override + State<AppExportItemSelectionDialog> createState() => _AppExportItemSelectionDialogState(); +} + +class _AppExportItemSelectionDialogState extends State<AppExportItemSelectionDialog> { + final Set<AppExportItem> _selectableItems = {}, _selectedItems = {}; + + @override + void initState() { + super.initState(); + _selectableItems.addAll(widget.selectableItems ?? AppExportItem.values); + _selectedItems.addAll(widget.initialSelection ?? _selectableItems); + } + + @override + Widget build(BuildContext context) { + return AvesDialog( + title: widget.title, + scrollableContent: AppExportItem.values.map((v) { + return SwitchListTile( + value: _selectedItems.contains(v), + onChanged: _selectableItems.contains(v) + ? (selected) { + if (selected == true) { + _selectedItems.add(v); + } else { + _selectedItems.remove(v); + } + setState(() {}); + } + : null, + title: Text( + v.getText(context), + softWrap: false, + overflow: TextOverflow.fade, + maxLines: 1, + ), + ); + }).toList(), + actions: [ + const CancelButton(), + TextButton( + onPressed: _selectedItems.isEmpty ? null : () => Navigator.maybeOf(context)?.pop(_selectedItems), + child: Text(context.l10n.applyButtonLabel), + ), + ], + ); + } +} diff --git a/lib/widgets/settings/common/collection_tile.dart b/lib/widgets/settings/common/collection_tile.dart new file mode 100644 index 0000000..6543bd7 --- /dev/null +++ b/lib/widgets/settings/common/collection_tile.dart @@ -0,0 +1,71 @@ +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/services/intent_service.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/collection/filter_bar.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/aves_caption.dart'; +import 'package:flutter/material.dart'; + +class SettingsCollectionTile extends StatelessWidget { + final Set<CollectionFilter> filters; + final void Function(Set<CollectionFilter>) onSelection; + + const SettingsCollectionTile({ + super.key, + required this.filters, + required this.onSelection, + }); + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + final theme = Theme.of(context); + final hasSubtitle = filters.isEmpty; + + // size and padding to match `ListTile` + return ConstrainedBox( + constraints: BoxConstraints( + minHeight: (hasSubtitle ? 72.0 : 56.0) + theme.visualDensity.baseSizeAdjustment.dy, + ), + child: Center( + child: Column( + children: [ + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Row( + children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + l10n.settingsCollectionTile, + // fallback to `ListTile` M3 default style + style: theme.listTileTheme.titleTextStyle ?? theme.textTheme.bodyLarge!.copyWith(color: theme.colorScheme.onSurface), + ), + if (hasSubtitle) AvesCaption(l10n.drawerCollectionAll), + ], + ), + const Spacer(), + IconButton( + onPressed: () async { + final selection = await IntentService.pickCollectionFilters(filters); + if (selection != null) { + onSelection(selection); + } + }, + icon: const Icon(AIcons.edit), + ), + ], + ), + ), + if (filters.isNotEmpty) + FilterBar( + filters: filters, + interactive: false, + ), + ], + ), + ), + ); + } +} diff --git a/lib/widgets/settings/common/quick_actions/action_panel.dart b/lib/widgets/settings/common/quick_actions/action_panel.dart new file mode 100644 index 0000000..a57645e --- /dev/null +++ b/lib/widgets/settings/common/quick_actions/action_panel.dart @@ -0,0 +1,36 @@ +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:flutter/material.dart'; + +class ActionPanel extends StatelessWidget { + final bool highlight; + final Widget child; + + const ActionPanel({ + super.key, + this.highlight = false, + required this.child, + }); + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final color = highlight ? theme.colorScheme.primary : Color.alphaBlend(theme.colorScheme.surfaceTint.withValues(alpha: .2), Themes.secondLayerColor(context)); + return AnimatedContainer( + foregroundDecoration: BoxDecoration( + color: color.withValues(alpha: .2), + border: Border.fromBorderSide(BorderSide( + color: color, + width: highlight ? 2 : 1, + )), + borderRadius: const BorderRadius.all(Radius.circular(8)), + ), + margin: const EdgeInsets.all(16), + duration: ADurations.quickActionHighlightAnimation, + child: ClipRRect( + borderRadius: const BorderRadius.all(Radius.circular(8)), + child: child, + ), + ); + } +} diff --git a/lib/widgets/settings/common/quick_actions/available_actions.dart b/lib/widgets/settings/common/quick_actions/available_actions.dart new file mode 100644 index 0000000..9230e9e --- /dev/null +++ b/lib/widgets/settings/common/quick_actions/available_actions.dart @@ -0,0 +1,136 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/widgets/common/identity/buttons/captioned_button.dart'; +import 'package:aves/widgets/common/identity/buttons/overlay_button.dart'; +import 'package:aves/widgets/common/providers/media_query_data_provider.dart'; +import 'package:aves/widgets/settings/common/quick_actions/placeholder.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/widgets.dart'; + +class AvailableActionPanel<T extends Object> extends StatelessWidget { + final List<T> allActions, quickActions; + final Listenable quickActionsChangeNotifier; + final ValueNotifier<bool> panelHighlight; + final ValueNotifier<T?> draggedQuickAction; + final ValueNotifier<T?> draggedAvailableAction; + final bool Function(T? action) removeQuickAction; + final Widget Function(BuildContext context, T action) actionIcon; + final String Function(BuildContext context, T action) actionText; + + static const double spacing = 8; + static const double runSpacing = 20; + static const padding = EdgeInsets.symmetric(vertical: 16, horizontal: 8); + + const AvailableActionPanel({ + super.key, + required this.allActions, + required this.quickActions, + required this.quickActionsChangeNotifier, + required this.panelHighlight, + required this.draggedQuickAction, + required this.draggedAvailableAction, + required this.removeQuickAction, + required this.actionIcon, + required this.actionText, + }); + + @override + Widget build(BuildContext context) { + return DragTarget<T>( + onWillAcceptWithDetails: (details) { + if (draggedQuickAction.value != null) { + _setPanelHighlight(true); + } + return true; + }, + onAcceptWithDetails: (details) { + removeQuickAction(draggedQuickAction.value); + _setDraggedQuickAction(null); + _setPanelHighlight(false); + }, + onLeave: (data) => _setPanelHighlight(false), + builder: (context, accepted, rejected) { + return AnimatedBuilder( + animation: Listenable.merge([quickActionsChangeNotifier, draggedAvailableAction]), + builder: (context, child) { + return Padding( + padding: padding, + child: Wrap( + alignment: WrapAlignment.spaceEvenly, + spacing: spacing, + runSpacing: runSpacing, + children: allActions.map((action) { + final dragged = action == draggedAvailableAction.value; + final enabled = dragged || !quickActions.contains(action); + var child = _buildActionButton(context, action, enabled: enabled); + if (dragged) { + child = DraggedPlaceholder(child: child); + } + if (enabled) { + child = _buildDraggable(context, action, child); + } + return child; + }).toList(), + ), + ); + }, + ); + }, + ); + } + + Widget _buildDraggable( + BuildContext context, + T action, + Widget child, + ) => + LongPressDraggable<T>( + feedback: MediaQueryDataProvider( + child: _buildActionButton( + context, + action, + showCaption: false, + ), + ), + data: action, + dragAnchorStrategy: (draggable, context, position) { + return childDragAnchorStrategy(draggable, context, position) + Offset(0, OverlayButton.getSize(context)); + }, + maxSimultaneousDrags: 1, + onDragStarted: () => _setDraggedAvailableAction(action), + onDragEnd: (details) => _setDraggedAvailableAction(null), + delay: settings.longPressTimeout, + childWhenDragging: child, + child: child, + ); + + Widget _buildActionButton( + BuildContext context, + T action, { + bool enabled = true, + bool showCaption = true, + }) => + CaptionedButton( + icon: actionIcon(context, action), + caption: actionText(context, action), + showCaption: showCaption, + onPressed: enabled ? () {} : null, + ); + + void _setDraggedQuickAction(T? action) => draggedQuickAction.value = action; + + void _setDraggedAvailableAction(T? action) => draggedAvailableAction.value = action; + + void _setPanelHighlight(bool flag) => panelHighlight.value = flag; + + static double heightFor(BuildContext context, List<String> captions, double width) { + final buttonSizes = captions.map((v) => CaptionedButton.getSize(context, v, showCaption: true)); + final actionsPerRun = (width - padding.horizontal + spacing) ~/ (buttonSizes.first.width + spacing); + final runCount = (captions.length / actionsPerRun).ceil(); + var height = runSpacing * (runCount - 1) + padding.vertical / 2; + for (var i = 0; i < runCount; i++) { + height += buttonSizes.skip(i * actionsPerRun).take(actionsPerRun).map((v) => v.height).max; + } + return height; + } +} diff --git a/lib/widgets/settings/common/quick_actions/editor_page.dart b/lib/widgets/settings/common/quick_actions/editor_page.dart new file mode 100644 index 0000000..f611cd4 --- /dev/null +++ b/lib/widgets/settings/common/quick_actions/editor_page.dart @@ -0,0 +1,458 @@ +import 'dart:async'; + +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/theme/styles.dart'; +import 'package:aves/widgets/common/basic/font_size_icon_theme.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/buttons/captioned_button.dart'; +import 'package:aves/widgets/common/identity/buttons/overlay_button.dart'; +import 'package:aves/widgets/settings/common/quick_actions/action_panel.dart'; +import 'package:aves/widgets/settings/common/quick_actions/available_actions.dart'; +import 'package:aves/widgets/settings/common/quick_actions/placeholder.dart'; +import 'package:aves/widgets/settings/common/quick_actions/quick_actions.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:smooth_page_indicator/smooth_page_indicator.dart'; + +class QuickActionEditorController<T extends Object> with ChangeNotifier { + final List<T> Function() load; + final void Function(List<T> actions) save; + + List<T> _currentItems = []; + final StreamController<EditorControllerEvent<T>> _eventsController = StreamController.broadcast(); + + Stream<EditorControllerEvent<T>> get events => _eventsController.stream; + + QuickActionEditorController({ + required this.load, + required this.save, + }); + + void notify() { + notifyListeners(); + } + + bool add(T? item) => insert(_currentItems.length, item); + + bool insert(int index, T? item) { + if (item == null || _currentItems.contains(item)) return false; + + _currentItems.insert(index, item); + _eventsController.add(_ItemAddedEvent(index, item)); + notify(); + return true; + } + + bool remove(T? item) { + if (item == null || !_currentItems.contains(item)) return false; + + final index = _currentItems.indexOf(item); + _currentItems.removeAt(index); + _eventsController.add(_ItemRemovedEvent(index, item)); + notify(); + return true; + } +} + +class EditorControllerEvent<T> { + final int index; + final T item; + + EditorControllerEvent(this.index, this.item); +} + +class _ItemAddedEvent<T> extends EditorControllerEvent<T> { + _ItemAddedEvent(super.index, super.item); +} + +class _ItemRemovedEvent<T> extends EditorControllerEvent<T> { + _ItemRemovedEvent(super.index, super.item); +} + +class QuickActionEditorPage<T extends Object> extends StatelessWidget { + final String title, bannerText; + final List<Widget>? appBarActions; + final TextDirection? displayedButtonsDirection; + final List<List<T>> allAvailableActions; + final Widget Function(BuildContext context, T action) actionIcon; + final String Function(BuildContext context, T action) actionText; + final QuickActionEditorController<T> controller; + + const QuickActionEditorPage({ + super.key, + required this.title, + this.appBarActions, + required this.bannerText, + this.displayedButtonsDirection, + required this.allAvailableActions, + required this.actionIcon, + required this.actionText, + required this.controller, + }); + + @override + Widget build(BuildContext context) { + return AvesScaffold( + appBar: AppBar( + title: Text(title), + actions: appBarActions, + ), + body: SafeArea( + bottom: false, + child: QuickActionEditorBody( + bannerText: bannerText, + displayedButtonsDirection: displayedButtonsDirection, + allAvailableActions: allAvailableActions, + actionIcon: actionIcon, + actionText: actionText, + controller: controller, + ), + ), + ); + } +} + +class QuickActionEditorBody<T extends Object> extends StatefulWidget { + final String bannerText; + final TextDirection? displayedButtonsDirection; + final List<List<T>> allAvailableActions; + final Widget Function(BuildContext context, T action) actionIcon; + final String Function(BuildContext context, T action) actionText; + final QuickActionEditorController<T> controller; + + const QuickActionEditorBody({ + super.key, + required this.bannerText, + this.displayedButtonsDirection, + required this.allAvailableActions, + required this.actionIcon, + required this.actionText, + required this.controller, + }); + + @override + State<QuickActionEditorBody<T>> createState() => _QuickActionEditorBodyState<T>(); +} + +class _QuickActionEditorBodyState<T extends Object> extends State<QuickActionEditorBody<T>> with AutomaticKeepAliveClientMixin { + final Set<StreamSubscription> _subscriptions = {}; + final GlobalKey<AnimatedListState> _animatedListKey = GlobalKey(debugLabel: 'quick-actions-animated-list'); + Timer? _targetLeavingTimer; + final ValueNotifier<T?> _draggedQuickAction = ValueNotifier(null); + final ValueNotifier<T?> _draggedAvailableAction = ValueNotifier(null); + final ValueNotifier<bool> _quickActionHighlight = ValueNotifier(false); + final ValueNotifier<bool> _availableActionHighlight = ValueNotifier(false); + final PageController _availableActionPageController = PageController(); + + // use a flag to prevent quick action target accept/leave when already animating reorder + // as dragging a button against axis direction messes index resolution while items pop in and out + bool _reordering = false; + + QuickActionEditorController<T> get controller => widget.controller; + + static const _listAnimation = ADurations.quickActionListAnimation; + static const double _quickActionVerticalPadding = 16.0; + + @override + void initState() { + super.initState(); + controller._currentItems = controller.load().toList(); + _subscriptions.add(controller.events.listen((e) { + switch (e) { + case _ItemAddedEvent(): + _animatedListKey.currentState!.insertItem( + e.index, + duration: _listAnimation, + ); + case _ItemRemovedEvent(): + _animatedListKey.currentState!.removeItem( + e.index, + (context, animation) => DraggedPlaceholder(child: _buildQuickActionButton(e.item, animation)), + duration: _listAnimation, + ); + } + })); + } + + @override + void dispose() { + _draggedQuickAction.dispose(); + _draggedAvailableAction.dispose(); + _quickActionHighlight.dispose(); + _availableActionHighlight.dispose(); + _availableActionPageController.dispose(); + + _stopLeavingTimer(); + super.dispose(); + } + + void _onQuickActionTargetLeave() { + _stopLeavingTimer(); + final action = _draggedAvailableAction.value; + _targetLeavingTimer = Timer(_listAnimation + const Duration(milliseconds: 50), () { + _removeQuickAction(action); + _quickActionHighlight.value = false; + }); + } + + @override + Widget build(BuildContext context) { + super.build(context); + + final _quickActions = controller._currentItems; + final theme = Theme.of(context); + final colorScheme = theme.colorScheme; + final header = QuickActionButton<T>( + placement: QuickActionPlacement.header, + panelHighlight: _quickActionHighlight, + draggedQuickAction: _draggedQuickAction, + draggedAvailableAction: _draggedAvailableAction, + insertAction: _insertQuickAction, + removeAction: _removeQuickAction, + onTargetLeave: _onQuickActionTargetLeave, + ); + final footer = QuickActionButton<T>( + placement: QuickActionPlacement.footer, + panelHighlight: _quickActionHighlight, + draggedQuickAction: _draggedQuickAction, + draggedAvailableAction: _draggedAvailableAction, + insertAction: _insertQuickAction, + removeAction: _removeQuickAction, + onTargetLeave: _onQuickActionTargetLeave, + ); + final originalDirection = Directionality.of(context); + return PopScope( + onPopInvokedWithResult: (didPop, result) => widget.controller.save(_quickActions), + child: ListView( + children: [ + Padding( + padding: const EdgeInsets.all(16), + child: Row( + children: [ + const FontSizeIconTheme(child: Icon(AIcons.info)), + const SizedBox(width: 16), + Expanded(child: Text(widget.bannerText)), + ], + ), + ), + const Divider(height: 0), + Padding( + padding: const EdgeInsets.only(left: 16, top: 16, right: 16), + child: Text( + context.l10n.settingsViewerQuickActionEditorDisplayedButtonsSectionTitle, + style: AStyles.knownTitleText, + ), + ), + ValueListenableBuilder<bool>( + valueListenable: _quickActionHighlight, + builder: (context, highlight, child) => ActionPanel( + highlight: highlight, + child: child!, + ), + child: Directionality( + textDirection: widget.displayedButtonsDirection ?? originalDirection, + child: SizedBox( + height: OverlayButton.getSize(context) + _quickActionVerticalPadding * 2, + child: Stack( + children: [ + Positioned.fill( + child: FractionallySizedBox( + alignment: AlignmentDirectional.centerStart, + widthFactor: .5, + child: header, + ), + ), + Positioned.fill( + child: FractionallySizedBox( + alignment: AlignmentDirectional.centerEnd, + widthFactor: .5, + child: footer, + ), + ), + Container( + alignment: Alignment.center, + child: AnimatedList( + key: _animatedListKey, + initialItemCount: _quickActions.length, + scrollDirection: Axis.horizontal, + shrinkWrap: true, + padding: EdgeInsets.zero, + itemBuilder: (context, index, animation) { + if (index >= _quickActions.length) return const SizedBox(); + final action = _quickActions[index]; + return Directionality( + textDirection: originalDirection, + child: QuickActionButton<T>( + placement: QuickActionPlacement.action, + action: action, + panelHighlight: _quickActionHighlight, + draggedQuickAction: _draggedQuickAction, + draggedAvailableAction: _draggedAvailableAction, + insertAction: _insertQuickAction, + removeAction: _removeQuickAction, + onTargetLeave: _onQuickActionTargetLeave, + draggableFeedbackBuilder: (action) => CaptionedButton( + icon: widget.actionIcon(context, action), + caption: widget.actionText(context, action), + showCaption: false, + onPressed: () {}, + ), + child: _buildQuickActionButton(action, animation), + ), + ); + }, + ), + ), + AnimatedBuilder( + animation: controller, + builder: (context, child) => _quickActions.isEmpty + ? Center( + child: Text( + context.l10n.settingsViewerQuickActionEmpty, + style: theme.textTheme.bodySmall, + ), + ) + : const SizedBox(), + ), + ], + ), + ), + ), + ), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Text( + context.l10n.settingsViewerQuickActionEditorAvailableButtonsSectionTitle, + style: AStyles.knownTitleText, + ), + ), + ValueListenableBuilder<bool>( + valueListenable: _availableActionHighlight, + builder: (context, highlight, child) => ActionPanel( + highlight: highlight, + child: child!, + ), + child: LayoutBuilder( + builder: (context, constraints) { + final allAvailableActions = widget.allAvailableActions; + final maxWidth = constraints.maxWidth; + final maxHeight = allAvailableActions + .map((page) => AvailableActionPanel.heightFor( + context, + page.map((v) => widget.actionText(context, v)).toList(), + maxWidth, + )) + .max; + return Column( + children: [ + if (allAvailableActions.length > 1) + Padding( + padding: const EdgeInsets.only(top: 8), + child: SmoothPageIndicator( + controller: _availableActionPageController, + count: allAvailableActions.length, + effect: WormEffect( + dotWidth: 8, + dotHeight: 8, + dotColor: colorScheme.onSurface.withValues(alpha: .2), + activeDotColor: colorScheme.primary, + ), + ), + ), + SizedBox( + height: maxHeight, + child: PageView( + controller: _availableActionPageController, + children: allAvailableActions + .map((allActions) => AvailableActionPanel<T>( + allActions: allActions, + quickActions: _quickActions, + quickActionsChangeNotifier: controller, + panelHighlight: _availableActionHighlight, + draggedQuickAction: _draggedQuickAction, + draggedAvailableAction: _draggedAvailableAction, + removeQuickAction: _removeQuickAction, + actionIcon: widget.actionIcon, + actionText: widget.actionText, + )) + .toList(), + ), + ), + ], + ); + }, + ), + ), + ], + ), + ); + } + + void _stopLeavingTimer() => _targetLeavingTimer?.cancel(); + + bool _insertQuickAction(T action, QuickActionPlacement placement, T? overAction) { + _stopLeavingTimer(); + if (_reordering) return false; + + final _quickActions = controller._currentItems; + final currentIndex = _quickActions.indexOf(action); + final contained = currentIndex != -1; + int? targetIndex; + switch (placement) { + case QuickActionPlacement.header: + targetIndex = 0; + case QuickActionPlacement.footer: + targetIndex = _quickActions.length - (contained ? 1 : 0); + case QuickActionPlacement.action: + targetIndex = _quickActions.indexOf(overAction!); + } + if (currentIndex == targetIndex) return false; + + _reordering = true; + _removeQuickAction(action); + controller.insert(targetIndex, action); + Future.delayed(_listAnimation).then((value) => _reordering = false); + return true; + } + + bool _removeQuickAction(T? action) => controller.remove(action); + + Widget _buildQuickActionButton(T action, Animation<double> animation) { + animation = animation.drive(CurveTween(curve: Curves.easeInOut)); + Widget child = FadeTransition( + opacity: animation, + child: SizeTransition( + axis: Axis.horizontal, + sizeFactor: animation, + child: Padding( + padding: const EdgeInsets.symmetric(vertical: _QuickActionEditorBodyState._quickActionVerticalPadding, horizontal: 4), + child: OverlayButton( + child: IconButton( + icon: widget.actionIcon(context, action), + onPressed: () {}, + ), + ), + ), + ), + ); + + child = AnimatedBuilder( + animation: Listenable.merge([_draggedQuickAction, _draggedAvailableAction]), + builder: (context, child) { + final dragged = _draggedQuickAction.value == action || _draggedAvailableAction.value == action; + if (dragged) { + child = DraggedPlaceholder(child: child!); + } + return child!; + }, + child: child, + ); + + return child; + } + + @override + bool get wantKeepAlive => true; +} diff --git a/lib/widgets/settings/common/quick_actions/placeholder.dart b/lib/widgets/settings/common/quick_actions/placeholder.dart new file mode 100644 index 0000000..8024dcc --- /dev/null +++ b/lib/widgets/settings/common/quick_actions/placeholder.dart @@ -0,0 +1,18 @@ +import 'package:flutter/widgets.dart'; + +class DraggedPlaceholder extends StatelessWidget { + final Widget child; + + const DraggedPlaceholder({ + super.key, + required this.child, + }); + + @override + Widget build(BuildContext context) { + return Opacity( + opacity: .2, + child: child, + ); + } +} diff --git a/lib/widgets/settings/common/quick_actions/quick_actions.dart b/lib/widgets/settings/common/quick_actions/quick_actions.dart new file mode 100644 index 0000000..73eb14a --- /dev/null +++ b/lib/widgets/settings/common/quick_actions/quick_actions.dart @@ -0,0 +1,84 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/widgets/common/identity/buttons/overlay_button.dart'; +import 'package:aves/widgets/common/providers/media_query_data_provider.dart'; +import 'package:flutter/widgets.dart'; + +enum QuickActionPlacement { header, action, footer } + +class QuickActionButton<T extends Object> extends StatelessWidget { + final QuickActionPlacement placement; + final T? action; + final ValueNotifier<bool> panelHighlight; + final ValueNotifier<T?> draggedQuickAction; + final ValueNotifier<T?> draggedAvailableAction; + final bool Function(T action, QuickActionPlacement placement, T? overAction) insertAction; + final bool Function(T action) removeAction; + final VoidCallback onTargetLeave; + final Widget Function(T action)? draggableFeedbackBuilder; + final Widget? child; + + const QuickActionButton({ + super.key, + required this.placement, + this.action, + required this.panelHighlight, + required this.draggedQuickAction, + required this.draggedAvailableAction, + required this.insertAction, + required this.removeAction, + required this.onTargetLeave, + this.draggableFeedbackBuilder, + this.child, + }); + + @override + Widget build(BuildContext context) { + var child = this.child; + child = _buildDragTarget(child); + if (action != null) { + child = _buildDraggable(child, action!); + } + return child; + } + + DragTarget<T> _buildDragTarget(Widget? child) { + return DragTarget<T>( + onWillAcceptWithDetails: (details) { + if (draggedQuickAction.value != null) { + insertAction(draggedQuickAction.value!, placement, action); + } + if (draggedAvailableAction.value != null) { + insertAction(draggedAvailableAction.value!, placement, action); + _setPanelHighlight(true); + } + return true; + }, + onAcceptWithDetails: (details) => _setPanelHighlight(false), + onLeave: (data) => onTargetLeave(), + builder: (context, accepted, rejected) => child ?? const SizedBox(), + ); + } + + Widget _buildDraggable(Widget child, T action) => LongPressDraggable( + feedback: MediaQueryDataProvider( + child: draggableFeedbackBuilder!(action), + ), + data: action, + dragAnchorStrategy: (draggable, context, position) { + return childDragAnchorStrategy(draggable, context, position) + Offset(0, OverlayButton.getSize(context)); + }, + maxSimultaneousDrags: 1, + onDragStarted: () => _setDraggedQuickAction(action), + // `onDragEnd` is only called when the widget is mounted, + // so we rely on `onDraggableCanceled` and `onDragCompleted` instead + onDraggableCanceled: (velocity, offset) => _setDraggedQuickAction(null), + onDragCompleted: () => _setDraggedQuickAction(null), + delay: settings.longPressTimeout, + childWhenDragging: child, + child: child, + ); + + void _setDraggedQuickAction(T? action) => draggedQuickAction.value = action; + + void _setPanelHighlight(bool flag) => panelHighlight.value = flag; +} diff --git a/lib/widgets/settings/common/switch_icon.dart b/lib/widgets/settings/common/switch_icon.dart new file mode 100644 index 0000000..ff176a2 --- /dev/null +++ b/lib/widgets/settings/common/switch_icon.dart @@ -0,0 +1,40 @@ +import 'package:aves/theme/colors.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/widgets/settings/common/tiles.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class SettingSwitchTrailingIcon extends StatelessWidget { + final IconData icon; + final bool disabled; + + const SettingSwitchTrailingIcon({ + super.key, + required this.icon, + required this.disabled, + }); + + @override + Widget build(BuildContext context) { + return Padding( + // Switch width (`_kSwitchWidth`) + tile content padding + padding: const EdgeInsetsDirectional.only(end: 59 + 16), + child: AnimatedSwitcher( + duration: context.read<DurationsData>().iconAnimation, + child: Icon( + icon, + key: key, + size: getIconSize(context), + color: getIconColor(context).withValues(alpha: disabled ? SettingsSwitchListTile.disabledOpacity : 1), + ), + ), + ); + } + + static double getIconSize(BuildContext context) { + final textScaler = MediaQuery.textScalerOf(context); + return textScaler.scale(IconTheme.of(context).size!); + } + + static Color getIconColor(BuildContext context) => context.select<AvesColorsData, Color>((v) => v.neutral); +} diff --git a/lib/widgets/settings/common/tile_leading.dart b/lib/widgets/settings/common/tile_leading.dart new file mode 100644 index 0000000..b19b76b --- /dev/null +++ b/lib/widgets/settings/common/tile_leading.dart @@ -0,0 +1,40 @@ +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/styles.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/widgets/common/extensions/theme.dart'; +import 'package:aves/widgets/common/identity/aves_filter_chip.dart'; +import 'package:decorated_icon/decorated_icon.dart'; +import 'package:flutter/material.dart'; + +class SettingsTileLeading extends StatelessWidget { + final IconData icon; + final Color color; + + const SettingsTileLeading({ + super.key, + required this.icon, + required this.color, + }); + + @override + Widget build(BuildContext context) { + return AnimatedContainer( + padding: const EdgeInsets.all(6), + decoration: BoxDecoration( + color: Themes.firstLayerColor(context), + border: Border.fromBorderSide(BorderSide( + color: color, + width: AvesFilterChip.outlineWidth, + )), + shape: BoxShape.circle, + ), + duration: ADurations.themeColorModeAnimation, + child: DecoratedIcon( + icon, + size: 18, + color: DefaultTextStyle.of(context).style.color, + shadows: Theme.of(context).isDark ? AStyles.embossShadows : null, + ), + ); + } +} diff --git a/lib/widgets/settings/common/tiles.dart b/lib/widgets/settings/common/tiles.dart new file mode 100644 index 0000000..706c221 --- /dev/null +++ b/lib/widgets/settings/common/tiles.dart @@ -0,0 +1,241 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/text.dart'; +import 'package:aves/utils/time_utils.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/aves_caption.dart'; +import 'package:aves/widgets/dialogs/duration_dialog.dart'; +import 'package:aves/widgets/dialogs/selection_dialogs/common.dart'; +import 'package:aves/widgets/dialogs/selection_dialogs/multi_selection.dart'; +import 'package:aves/widgets/dialogs/selection_dialogs/single_selection.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class SettingsSubPageTile extends StatelessWidget { + final String title, routeName; + final WidgetBuilder builder; + + const SettingsSubPageTile({ + super.key, + required this.title, + required this.routeName, + required this.builder, + }); + + @override + Widget build(BuildContext context) { + return ListTile( + title: Text(title), + onTap: () { + Navigator.maybeOf(context)?.push( + MaterialPageRoute( + settings: RouteSettings(name: routeName), + builder: builder, + ), + ); + }, + ); + } +} + +class SettingsSwitchListTile extends StatelessWidget { + final bool Function(BuildContext, Settings) selector; + final ValueChanged<bool>? onChanged; + final String title; + final String? subtitle; + final Widget? trailing; + + static const disabledOpacity = .2; + + const SettingsSwitchListTile({ + super.key, + required this.selector, + required this.onChanged, + required this.title, + this.subtitle, + this.trailing, + }); + + @override + Widget build(BuildContext context) { + return Selector<Settings, bool>( + selector: selector, + builder: (context, current, child) { + Widget titleWidget = Text(title); + if (trailing != null) { + titleWidget = Row( + children: [ + Expanded(child: titleWidget), + AnimatedOpacity( + opacity: current && onChanged != null ? 1 : disabledOpacity, + duration: ADurations.toggleableTransitionLoose, + child: trailing, + ), + ], + ); + } + return SwitchListTile( + value: current, + onChanged: onChanged, + title: titleWidget, + subtitle: subtitle != null ? Text(subtitle!) : null, + ); + }, + ); + } +} + +class SettingsSelectionListTile<T> extends StatelessWidget { + final List<T> values; + final String Function(BuildContext, T) getName; + final T Function(BuildContext, Settings) selector; + final ValueChanged<T> onSelection; + final String tileTitle; + final WidgetBuilder? trailingBuilder; + final String? dialogTitle; + final TextBuilder<T>? optionSubtitleBuilder; + + const SettingsSelectionListTile({ + super.key, + required this.values, + required this.getName, + required this.selector, + required this.onSelection, + required this.tileTitle, + this.trailingBuilder, + this.dialogTitle, + this.optionSubtitleBuilder, + }); + + @override + Widget build(BuildContext context) { + return Selector<Settings, T>( + selector: selector, + builder: (context, current, child) { + Widget titleWidget = Text(tileTitle); + if (trailingBuilder != null) { + titleWidget = Row( + children: [ + Expanded(child: titleWidget), + trailingBuilder!(context), + ], + ); + } + return ListTile( + title: titleWidget, + subtitle: AvesCaption(getName(context, current)), + onTap: () => showSelectionDialog<T>( + context: context, + builder: (context) => AvesSingleSelectionDialog<T>( + initialValue: current, + options: Map.fromEntries(values.map((v) => MapEntry(v, getName(context, v)))), + optionSubtitleBuilder: optionSubtitleBuilder, + title: dialogTitle, + ), + onSelection: onSelection, + ), + ); + }, + ); + } +} + +class SettingsMultiSelectionListTile<T> extends StatelessWidget { + final List<T> values; + final String Function(BuildContext, T) getName; + final List<T> Function(BuildContext, Settings) selector; + final ValueChanged<List<T>> onSelection; + final String tileTitle, noneSubtitle; + final WidgetBuilder? trailingBuilder; + final String? dialogTitle; + final TextBuilder<T>? optionSubtitleBuilder; + + const SettingsMultiSelectionListTile({ + super.key, + required this.values, + required this.getName, + required this.selector, + required this.onSelection, + required this.tileTitle, + required this.noneSubtitle, + this.trailingBuilder, + this.dialogTitle, + this.optionSubtitleBuilder, + }); + + @override + Widget build(BuildContext context) { + return Selector<Settings, List<T>>( + selector: selector, + builder: (context, current, child) { + Widget titleWidget = Text(tileTitle); + if (trailingBuilder != null) { + titleWidget = Row( + children: [ + Expanded(child: titleWidget), + trailingBuilder!(context), + ], + ); + } + return ListTile( + title: titleWidget, + subtitle: AvesCaption(current.isEmpty ? noneSubtitle : current.map((v) => getName(context, v)).join(AText.separator)), + onTap: () => showSelectionDialog<List<T>>( + context: context, + builder: (context) => AvesMultiSelectionDialog<T>( + initialValue: current.toSet(), + options: Map.fromEntries(values.map((v) => MapEntry(v, getName(context, v)))), + optionSubtitleBuilder: optionSubtitleBuilder, + title: dialogTitle, + ), + onSelection: onSelection, + ), + ); + }, + ); + } +} + +class SettingsDurationListTile extends StatelessWidget { + final int Function(BuildContext, Settings) selector; + final ValueChanged<int> onChanged; + final String title; + + const SettingsDurationListTile({ + super.key, + required this.selector, + required this.onChanged, + required this.title, + }); + + @override + Widget build(BuildContext context) { + return Selector<Settings, int>( + selector: selector, + builder: (context, current, child) { + final currentMinutes = current ~/ secondsInMinute; + final currentSeconds = current % secondsInMinute; + + final l10n = context.l10n; + final subtitle = [ + if (currentMinutes > 0) l10n.timeMinutes(currentMinutes), + if (currentSeconds > 0) l10n.timeSeconds(currentSeconds), + ].join(' '); + + return ListTile( + title: Text(title), + subtitle: AvesCaption(subtitle), + onTap: () async { + final v = await showDialog<int>( + context: context, + builder: (context) => DurationDialog(initialSeconds: current), + ); + if (v != null) { + onChanged(v); + } + }, + ); + }, + ); + } +} diff --git a/lib/widgets/settings/display/display.dart b/lib/widgets/settings/display/display.dart new file mode 100644 index 0000000..4021055 --- /dev/null +++ b/lib/widgets/settings/display/display.dart @@ -0,0 +1,158 @@ +import 'dart:async'; + +import 'package:aves/model/device.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/colors.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:aves/widgets/settings/common/tile_leading.dart'; +import 'package:aves/widgets/settings/common/tiles.dart'; +import 'package:aves/widgets/settings/privacy/privacy.dart'; +import 'package:aves/widgets/settings/settings_definition.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class DisplaySection extends SettingsSection { + @override + String get key => 'display'; + + @override + Widget icon(BuildContext context) => SettingsTileLeading( + icon: AIcons.display, + color: context.select<AvesColorsData, Color>((v) => v.display), + ); + + @override + String title(BuildContext context) => context.l10n.settingsDisplaySectionTitle; + + @override + FutureOr<List<SettingsTile>> tiles(BuildContext context) => [ + if (!settings.useTvLayout) SettingsTileDisplayThemeBrightness(), + SettingsTileDisplayThemeColorMode(), + if (device.isDynamicColorAvailable) SettingsTileDisplayEnableDynamicColor(), + SettingsTileDisplayEnableBlurEffect(), + if (!settings.useTvLayout) SettingsTileDisplayMaxBrightness(), + if (!settings.useTvLayout) SettingsTileDisplayRefreshRateMode(), + if (!device.isTelevision) SettingsTileDisplayForceTvLayout(), + ]; +} + +class SettingsTileDisplayThemeBrightness extends SettingsTile { + @override + String title(BuildContext context) => context.l10n.settingsThemeBrightnessTile; + + @override + Widget build(BuildContext context) => SettingsSelectionListTile<AvesThemeBrightness>( + values: AvesThemeBrightness.values, + getName: (context, v) => v.getName(context), + selector: (context, s) => s.themeBrightness, + onSelection: (v) => settings.themeBrightness = v, + tileTitle: title(context), + dialogTitle: context.l10n.settingsThemeBrightnessDialogTitle, + ); +} + +class SettingsTileDisplayThemeColorMode extends SettingsTile { + @override + String title(BuildContext context) => context.l10n.settingsThemeColorHighlights; + + @override + Widget build(BuildContext context) => SettingsSwitchListTile( + selector: (context, s) => s.themeColorMode == AvesThemeColorMode.polychrome, + onChanged: (v) => settings.themeColorMode = v ? AvesThemeColorMode.polychrome : AvesThemeColorMode.monochrome, + title: title(context), + ); +} + +class SettingsTileDisplayEnableDynamicColor extends SettingsTile { + @override + String title(BuildContext context) => context.l10n.settingsThemeEnableDynamicColor; + + @override + Widget build(BuildContext context) => SettingsSwitchListTile( + selector: (context, s) => s.enableDynamicColor, + onChanged: (v) => settings.enableDynamicColor = v, + title: title(context), + ); +} + +class SettingsTileDisplayEnableBlurEffect extends SettingsTile { + @override + String title(BuildContext context) => context.l10n.settingsViewerEnableOverlayBlurEffect; + + @override + Widget build(BuildContext context) => SettingsSwitchListTile( + selector: (context, s) => s.enableBlurEffect, + onChanged: (v) => settings.enableBlurEffect = v, + title: title(context), + ); +} + +class SettingsTileDisplayMaxBrightness extends SettingsTile { + @override + String title(BuildContext context) => context.l10n.settingsViewerMaximumBrightness; + + @override + Widget build(BuildContext context) => SettingsSelectionListTile<MaxBrightness>( + values: MaxBrightness.values, + getName: (context, v) => v.getName(context), + selector: (context, s) => s.maxBrightness, + onSelection: (v) => settings.maxBrightness = v, + tileTitle: title(context), + ); +} + +class SettingsTileDisplayRefreshRateMode extends SettingsTile { + @override + String title(BuildContext context) => context.l10n.settingsDisplayRefreshRateModeTile; + + @override + Widget build(BuildContext context) => SettingsSelectionListTile<DisplayRefreshRateMode>( + values: DisplayRefreshRateMode.values, + getName: (context, v) => v.getName(context), + selector: (context, s) => s.displayRefreshRateMode, + onSelection: (v) => settings.displayRefreshRateMode = v, + tileTitle: title(context), + dialogTitle: context.l10n.settingsDisplayRefreshRateModeDialogTitle, + ); +} + +class SettingsTileDisplayForceTvLayout extends SettingsTile { + @override + String title(BuildContext context) => context.l10n.settingsDisplayUseTvInterface; + + @override + Widget build(BuildContext context) => SettingsSwitchListTile( + selector: (context, s) => s.forceTvLayout, + onChanged: (v) async { + if (v) { + final l10n = context.l10n; + final confirmed = await showDialog<bool>( + context: context, + builder: (context) => AvesDialog( + content: Text([ + l10n.settingsModificationWarningDialogMessage, + l10n.genericDangerWarningDialogMessage, + ].join('\n\n')), + actions: [ + const CancelButton(), + TextButton( + onPressed: () => Navigator.maybeOf(context)?.pop(true), + child: Text(l10n.applyButtonLabel), + ), + ], + ), + ); + if (confirmed == null || !confirmed) return; + } + + if (v && !(await SettingsTilePrivacyEnableBin.setBinUsage(context, false))) return; + + settings.forceTvLayout = v; + }, + title: title(context), + ); +} diff --git a/lib/widgets/settings/home_widget_settings_page.dart b/lib/widgets/settings/home_widget_settings_page.dart new file mode 100644 index 0000000..6e40805 --- /dev/null +++ b/lib/widgets/settings/home_widget_settings_page.dart @@ -0,0 +1,316 @@ +import 'package:aves/model/device.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/settings/enums/widget_outline.dart'; +import 'package:aves/model/settings/enums/widget_shape.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/services/widget_service.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/basic/color_indicator.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/buttons/outlined_button.dart'; +import 'package:aves/widgets/home_widget.dart'; +import 'package:aves/widgets/settings/common/collection_tile.dart'; +import 'package:aves/widgets/settings/common/tiles.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class HomeWidgetSettingsPage extends StatefulWidget { + static const routeName = '/settings/home_widget'; + + final int widgetId; + + const HomeWidgetSettingsPage({ + super.key, + required this.widgetId, + }); + + @override + State<HomeWidgetSettingsPage> createState() => _HomeWidgetSettingsPageState(); +} + +class _HomeWidgetSettingsPageState extends State<HomeWidgetSettingsPage> { + late Future<double?> _cornerRadiusPxLoader; + late WidgetShape _shape; + late WidgetOutline _outline; + late WidgetOpenPage _openPage; + late WidgetDisplayedItem _displayedItem; + late Set<CollectionFilter> _collectionFilters; + Future<Map<Brightness, Map<WidgetOutline, Color?>>> _outlineColorsByBrightness = Future.value({}); + + int get widgetId => widget.widgetId; + + static const gradient = HomeWidgetPainter.backgroundGradient; + static final deselectedGradient = LinearGradient( + begin: gradient.begin, + end: gradient.end, + colors: gradient.colors.map((v) { + final l = v.computeLuminance(); + return Color.from(alpha: 1, red: l, green: l, blue: l); + }).toList(), + stops: gradient.stops, + tileMode: gradient.tileMode, + transform: gradient.transform, + ); + + @override + void initState() { + super.initState(); + _cornerRadiusPxLoader = deviceService.getWidgetCornerRadiusPx(); + _shape = settings.getWidgetShape(widgetId); + _outline = settings.getWidgetOutline(widgetId); + _openPage = settings.getWidgetOpenPage(widgetId); + _displayedItem = settings.getWidgetDisplayedItem(widgetId); + _collectionFilters = settings.getWidgetCollectionFilters(widgetId); + WidgetsBinding.instance.addPostFrameCallback((_) => _updateOutlineColors()); + } + + void _updateOutlineColors() { + _outlineColorsByBrightness = _loadOutlineColors(); + setState(() {}); + } + + Future<Map<Brightness, Map<WidgetOutline, Color?>>> _loadOutlineColors() async { + final byBrightness = <Brightness, Map<WidgetOutline, Color?>>{}; + await Future.forEach(Brightness.values, (brightness) async { + final byOutline = <WidgetOutline, Color?>{}; + await Future.forEach(WidgetOutline.values, (outline) async { + byOutline[outline] = await outline.color(brightness); + }); + byBrightness[brightness] = byOutline; + }); + return byBrightness; + } + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + return AvesScaffold( + appBar: AppBar( + title: Text(l10n.settingsWidgetPageTitle), + ), + body: SafeArea( + child: FutureBuilder<Map<Brightness, Map<WidgetOutline, Color?>>>( + future: _outlineColorsByBrightness, + builder: (context, snapshot) { + final outlineColorsByBrightness = snapshot.data; + if (outlineColorsByBrightness == null) return const SizedBox(); + + final effectiveOutlineColors = outlineColorsByBrightness[Theme.of(context).brightness]; + if (effectiveOutlineColors == null) return const SizedBox(); + + return Column( + children: [ + Expanded( + child: ListView( + children: [ + FutureBuilder<double?>( + future: _cornerRadiusPxLoader, + builder: (context, snapshot) { + final cornerRadiusPx = snapshot.data; + final cornerRadius = cornerRadiusPx != null ? cornerRadiusPx / MediaQuery.devicePixelRatioOf(context) : null; + return _buildShapeSelector(effectiveOutlineColors, cornerRadius); + }, + ), + ListTile( + title: Text(l10n.settingsWidgetShowOutline), + trailing: HomeWidgetOutlineSelector( + getter: () => _outline, + setter: (v) => setState(() => _outline = v), + outlineColorsByBrightness: outlineColorsByBrightness, + ), + ), + SettingsSelectionListTile<WidgetOpenPage>( + values: WidgetOpenPage.values, + getName: (context, v) => v.getName(context), + selector: (context, s) => _openPage, + onSelection: (v) => setState(() => _openPage = v), + tileTitle: l10n.settingsWidgetOpenPage, + ), + SettingsSelectionListTile<WidgetDisplayedItem>( + values: WidgetDisplayedItem.values, + getName: (context, v) => v.getName(context), + selector: (context, s) => _displayedItem, + onSelection: (v) => setState(() => _displayedItem = v), + tileTitle: l10n.settingsWidgetDisplayedItem, + ), + SettingsCollectionTile( + filters: _collectionFilters, + onSelection: (v) => setState(() => _collectionFilters = v), + ), + ], + ), + ), + const Divider(height: 0), + Padding( + padding: const EdgeInsets.all(8), + child: AvesOutlinedButton( + label: l10n.saveTooltip, + onPressed: () { + _saveSettings(); + WidgetService.configure(); + }, + ), + ), + ], + ); + }, + ), + ), + ); + } + + Widget _buildShapeSelector(Map<WidgetOutline, Color?> outlineColors, double? cornerRadius) { + const shapeHeight = 124.0; + const shapes = WidgetShape.values; + return Container( + height: shapeHeight, + margin: const EdgeInsets.symmetric(vertical: 8), + child: ListView.builder( + scrollDirection: Axis.horizontal, + padding: const EdgeInsets.symmetric(horizontal: 8), + itemBuilder: (context, index) { + final shape = WidgetShape.values[index]; + final selected = shape == _shape; + final duration = context.read<DurationsData>().formTransition; + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 8), + child: GestureDetector( + onTap: () => setState(() => _shape = shape), + child: AnimatedOpacity( + duration: duration, + // as of Flutter beta v3.3.0-0.0.pre, decoration rendering is at the wrong position if opacity is > .998 + opacity: selected ? .998 : .4, + child: AnimatedContainer( + duration: duration, + width: 96, + height: shapeHeight, + decoration: ShapeDecoration( + gradient: selected ? gradient : deselectedGradient, + shape: _WidgetShapeBorder(_outline, shape, outlineColors, cornerRadius), + ), + ), + ), + ), + ); + }, + itemCount: shapes.length, + ), + ); + } + + void _saveSettings() { + final invalidateUri = _displayedItem != settings.getWidgetDisplayedItem(widgetId) || !const SetEquality().equals(_collectionFilters, settings.getWidgetCollectionFilters(widgetId)); + + settings.setWidgetShape(widgetId, _shape); + settings.setWidgetOutline(widgetId, _outline); + settings.setWidgetOpenPage(widgetId, _openPage); + settings.setWidgetDisplayedItem(widgetId, _displayedItem); + settings.setWidgetCollectionFilters(widgetId, _collectionFilters); + + if (invalidateUri) { + settings.setWidgetUri(widgetId, null); + } + } +} + +class _WidgetShapeBorder extends ShapeBorder { + final WidgetOutline outline; + final WidgetShape shape; + final Map<WidgetOutline, Color?> outlineColors; + final double? cornerRadius; + + static const _devicePixelRatio = 1.0; + + const _WidgetShapeBorder(this.outline, this.shape, this.outlineColors, this.cornerRadius); + + @override + EdgeInsetsGeometry get dimensions => EdgeInsets.zero; + + @override + Path getInnerPath(Rect rect, {TextDirection? textDirection}) { + return getOuterPath(rect, textDirection: textDirection); + } + + @override + Path getOuterPath(Rect rect, {TextDirection? textDirection}) { + return shape.path(rect.size, _devicePixelRatio, cornerRadiusPx: cornerRadius); + } + + @override + void paint(Canvas canvas, Rect rect, {TextDirection? textDirection}) { + final outlineColor = outlineColors[outline]; + if (outlineColor != null) { + final path = shape.path(rect.size, _devicePixelRatio, cornerRadiusPx: cornerRadius); + canvas.clipPath(path); + HomeWidgetPainter.drawOutline(canvas, path, _devicePixelRatio, outlineColor); + } + } + + @override + ShapeBorder scale(double t) => this; +} + +class HomeWidgetOutlineSelector extends StatefulWidget { + final ValueGetter<WidgetOutline> getter; + final ValueSetter<WidgetOutline> setter; + final Map<Brightness, Map<WidgetOutline, Color?>> outlineColorsByBrightness; + + const HomeWidgetOutlineSelector({ + super.key, + required this.getter, + required this.setter, + required this.outlineColorsByBrightness, + }); + + @override + State<HomeWidgetOutlineSelector> createState() => _HomeWidgetOutlineSelectorState(); +} + +class _HomeWidgetOutlineSelectorState extends State<HomeWidgetOutlineSelector> { + @override + Widget build(BuildContext context) { + return DropdownButtonHideUnderline( + child: DropdownButton<WidgetOutline>( + items: _buildItems(context), + value: widget.getter(), + onChanged: (selected) { + widget.setter(selected ?? WidgetOutline.none); + setState(() {}); + }, + ), + ); + } + + List<DropdownMenuItem<WidgetOutline>> _buildItems(BuildContext context) { + return supportedWidgetOutlines.map((selected) { + final lightColors = widget.outlineColorsByBrightness[Brightness.light]; + final darkColors = widget.outlineColorsByBrightness[Brightness.dark]; + return DropdownMenuItem<WidgetOutline>( + value: selected, + child: ColorIndicator( + value: lightColors?[selected], + alternate: darkColors?[selected], + child: lightColors?[selected] == null ? const Icon(AIcons.clear) : null, + ), + ); + }).toList(); + } + + List<WidgetOutline> get supportedWidgetOutlines => [ + WidgetOutline.none, + WidgetOutline.black, + WidgetOutline.white, + WidgetOutline.systemBlackAndWhite, + WidgetOutline.systemBlackAndWhiteHighContrast, + if (device.isDynamicColorAvailable) ...[ + WidgetOutline.systemDynamicLowContrast, + WidgetOutline.systemDynamic, + ], + ]; +} diff --git a/lib/widgets/settings/language/language.dart b/lib/widgets/settings/language/language.dart new file mode 100644 index 0000000..3bba84d --- /dev/null +++ b/lib/widgets/settings/language/language.dart @@ -0,0 +1,89 @@ +import 'dart:async'; + +import 'package:aves/model/settings/enums/coordinate_format.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/ref/poi.dart'; +import 'package:aves/theme/colors.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/settings/common/tile_leading.dart'; +import 'package:aves/widgets/settings/common/tiles.dart'; +import 'package:aves/widgets/settings/language/locale_tile.dart'; +import 'package:aves/widgets/settings/settings_definition.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class LanguageSection extends SettingsSection { + @override + String get key => 'language'; + + @override + Widget icon(BuildContext context) => SettingsTileLeading( + icon: AIcons.language, + color: context.select<AvesColorsData, Color>((v) => v.language), + ); + + @override + String title(BuildContext context) => context.l10n.settingsLanguageSectionTitle; + + @override + FutureOr<List<SettingsTile>> tiles(BuildContext context) => [ + SettingsTileLanguageLocale(), + SettingsTileLanguageCoordinateFormat(), + SettingsTileLanguageUnitSystem(), + SettingsTileLanguageNumerals(), + ]; +} + +class SettingsTileLanguageLocale extends SettingsTile { + @override + String title(BuildContext context) => context.l10n.settingsLanguageTile; + + @override + Widget build(BuildContext context) => const LocaleTile(); +} + +class SettingsTileLanguageCoordinateFormat extends SettingsTile { + @override + String title(BuildContext context) => context.l10n.settingsCoordinateFormatTile; + + @override + Widget build(BuildContext context) => SettingsSelectionListTile<CoordinateFormat>( + values: CoordinateFormat.values, + getName: (context, v) => v.getName(context), + selector: (context, s) => s.coordinateFormat, + onSelection: (v) => settings.coordinateFormat = v, + tileTitle: title(context), + dialogTitle: context.l10n.settingsCoordinateFormatDialogTitle, + optionSubtitleBuilder: (value) => value.format(context, PointsOfInterest.pointNemo), + ); +} + +class SettingsTileLanguageUnitSystem extends SettingsTile { + @override + String title(BuildContext context) => context.l10n.settingsUnitSystemTile; + + @override + Widget build(BuildContext context) => SettingsSelectionListTile<UnitSystem>( + values: UnitSystem.values, + getName: (context, v) => v.getName(context), + selector: (context, s) => s.unitSystem, + onSelection: (v) => settings.unitSystem = v, + tileTitle: title(context), + dialogTitle: context.l10n.settingsUnitSystemDialogTitle, + ); +} + +class SettingsTileLanguageNumerals extends SettingsTile { + @override + String title(BuildContext context) => context.l10n.settingsForceWesternArabicNumeralsTile; + + @override + Widget build(BuildContext context) => SettingsSwitchListTile( + selector: (context, s) => s.forceWesternArabicNumerals, + onChanged: (v) => settings.forceWesternArabicNumerals = v, + title: title(context), + ); +} diff --git a/lib/widgets/settings/language/locale_selection_page.dart b/lib/widgets/settings/language/locale_selection_page.dart new file mode 100644 index 0000000..fcf76cf --- /dev/null +++ b/lib/widgets/settings/language/locale_selection_page.dart @@ -0,0 +1,97 @@ +import 'dart:collection'; + +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/widgets/aves_app.dart'; +import 'package:aves/widgets/common/basic/list_tiles/reselectable_radio.dart'; +import 'package:aves/widgets/common/basic/query_bar.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/settings/language/locale_tile.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; + +class LocaleSelectionPage extends StatefulWidget { + static const routeName = '/settings/locale'; + + const LocaleSelectionPage({super.key}); + + @override + State<LocaleSelectionPage> createState() => _LocaleSelectionPageState(); +} + +class _LocaleSelectionPageState extends State<LocaleSelectionPage> { + late Locale _selectedValue; + final ValueNotifier<String> _queryNotifier = ValueNotifier(''); + + @override + void initState() { + super.initState(); + _selectedValue = settings.locale ?? LocaleTile.systemLocaleOption; + } + + @override + void dispose() { + _queryNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final useTvLayout = settings.useTvLayout; + return AvesScaffold( + appBar: AppBar( + automaticallyImplyLeading: !useTvLayout, + title: Text(context.l10n.settingsLanguagePageTitle), + ), + body: SafeArea( + bottom: false, + child: ValueListenableBuilder<String>( + valueListenable: _queryNotifier, + builder: (context, query, child) { + final upQuery = query.toUpperCase().trim(); + return ListView( + children: [ + if (!useTvLayout) + QueryBar( + queryNotifier: _queryNotifier, + leadingPadding: const EdgeInsetsDirectional.only(start: 24, end: 8), + ), + ..._getLocaleOptions(context).entries.where((kv) { + if (upQuery.isEmpty) return true; + final title = kv.value; + return title.toUpperCase().contains(upQuery); + }).map((kv) { + final value = kv.key; + final title = kv.value; + return ReselectableRadioListTile<Locale>( + // key is expected by test driver + key: Key(value.toString()), + value: value, + groupValue: _selectedValue, + onChanged: (v) => Navigator.maybeOf(context)?.pop(v), + reselectable: true, + title: Text( + title, + softWrap: false, + overflow: TextOverflow.fade, + maxLines: 1, + ), + ); + }), + ], + ); + }, + ), + ), + ); + } + + LinkedHashMap<Locale, String> _getLocaleOptions(BuildContext context) { + final displayLocales = AvesApp.supportedLocales.map((locale) => MapEntry(locale, LocaleTile.getLocaleName(locale))).toList()..sort((a, b) => compareAsciiUpperCase(a.value, b.value)); + + return LinkedHashMap.of({ + LocaleTile.systemLocaleOption: context.l10n.settingsSystemDefault, + ...LinkedHashMap.fromEntries(displayLocales), + }); + } +} diff --git a/lib/widgets/settings/language/locale_tile.dart b/lib/widgets/settings/language/locale_tile.dart new file mode 100644 index 0000000..2469286 --- /dev/null +++ b/lib/widgets/settings/language/locale_tile.dart @@ -0,0 +1,49 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/settings/language/locale_selection_page.dart'; +import 'package:aves/widgets/settings/language/locales.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:provider/provider.dart'; + +class LocaleTile extends StatelessWidget { + static const systemLocaleOption = Locale('system'); + + const LocaleTile({super.key}); + + @override + Widget build(BuildContext context) { + return ListTile( + // key is expected by test driver + key: const Key('tile-language'), + title: Text(context.l10n.settingsLanguageTile), + subtitle: Selector<Settings, Locale?>( + selector: (context, s) => settings.locale, + builder: (context, locale, child) { + return Text(locale == null ? context.l10n.settingsSystemDefault : getLocaleName(locale)); + }, + ), + onTap: () async { + final value = await Navigator.maybeOf(context)?.push<Locale>( + MaterialPageRoute( + settings: const RouteSettings(name: LocaleSelectionPage.routeName), + builder: (context) => const LocaleSelectionPage(), + ), + ); + // wait for the dialog to hide + await Future.delayed(ADurations.pageTransitionLoose * timeDilation); + if (value != null) { + settings.locale = value == systemLocaleOption ? null : value; + } + }, + ); + } + + static String getLocaleName(Locale locale) { + // the package `flutter_localized_locales` has the answer for all locales + // but it comes with 3 MB of assets + final localeString = locale.toString(); + return SupportedLocales.languagesByLanguageCode[localeString] ?? localeString; + } +} diff --git a/lib/widgets/settings/language/locales.dart b/lib/widgets/settings/language/locales.dart new file mode 100644 index 0000000..50598e6 --- /dev/null +++ b/lib/widgets/settings/language/locales.dart @@ -0,0 +1,47 @@ +// this class is kept minimal, without import +// so it can be reused in driver tests + +class SupportedLocales { + static const languagesByLanguageCode = { + 'ar': 'العربية', + 'be': 'Беларуская мова', + 'bg': 'Български', + 'ca': 'Català', + 'cs': 'Čeština', + 'da': 'Dansk', + 'de': 'Deutsch', + 'el': 'Ελληνικά', + 'en': 'English', + 'en_Shaw': '𐑦𐑙𐑜𐑤𐑦𐑖 (𐑖𐑱𐑝𐑰𐑩𐑯)', + 'es': 'Español (México)', + 'et': 'Eesti', + 'eu': 'Euskara', + 'fa': 'فارسی', + 'fr': 'Français', + 'fi': 'Suomi', + 'gl': 'Galego', + 'hu': 'Magyar', + 'id': 'Bahasa Indonesia', + 'is': 'Íslenska', + 'it': 'Italiano', + 'ja': '日本語', + 'kn': 'ಕನ್ನಡ', + 'ko': '한국어', + 'lt': 'Lietuvių', + 'nb': 'Norsk (Bokmål)', + 'nn': 'Norsk (Nynorsk)', + 'nl': 'Nederlands', + 'pl': 'Polski', + 'pt': 'Português (Brasil)', + 'ro': 'Română', + 'ru': 'Русский', + 'sk': 'Slovenčina', + 'sv': 'Svenska', + 'ta': 'தமிழ்', + 'tr': 'Türkçe', + 'uk': 'Українська', + 'vi': 'Tiếng Việt', + 'zh': '简体中文', + 'zh_Hant': '繁體中文', + }; +} diff --git a/lib/widgets/settings/navigation/bottom_nav_actions_editor.dart b/lib/widgets/settings/navigation/bottom_nav_actions_editor.dart new file mode 100644 index 0000000..8af9f19 --- /dev/null +++ b/lib/widgets/settings/navigation/bottom_nav_actions_editor.dart @@ -0,0 +1,151 @@ +import 'dart:async'; + +import 'package:aves/model/settings/enums/accessibility_animations.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/collection/collection_page.dart'; +import 'package:aves/widgets/common/basic/font_size_icon_theme.dart'; +import 'package:aves/widgets/common/basic/popup/menu_row.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/dialogs/pick_dialogs/album_pick_page.dart'; +import 'package:aves/widgets/dialogs/pick_dialogs/tag_pick_page.dart'; +import 'package:aves/widgets/filter_grids/common/enums.dart'; +import 'package:aves/widgets/home/home_page.dart'; +import 'package:aves/widgets/navigation/nav_item.dart'; +import 'package:aves/widgets/settings/common/quick_actions/editor_page.dart'; +import 'package:aves/widgets/settings/navigation/drawer.dart'; +import 'package:aves/widgets/settings/settings_page.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:provider/provider.dart'; + +class BottomNavigationActionEditorPage extends StatefulWidget { + static const routeName = '/settings/navigation/bottom_actions'; + + const BottomNavigationActionEditorPage({super.key}); + + @override + State<BottomNavigationActionEditorPage> createState() => _BottomNavigationActionEditorPageState(); +} + +class _BottomNavigationActionEditorPageState extends State<BottomNavigationActionEditorPage> { + late final QuickActionEditorController<AvesNavItem> _controller; + + static final allAvailableActions = [ + NavigationDrawerEditorPage.collectionFilterOptions.map((filter) { + return AvesNavItem( + route: CollectionPage.routeName, + filters: filter != null ? {filter} : null, + ); + }).toList(), + [ + HomePage.routeName, + SettingsPage.routeName, + ...NavigationDrawerEditorPage.pageOptions, + ].map((v) { + return AvesNavItem( + route: v, + ); + }).toList(), + ]; + + @override + void initState() { + super.initState(); + _controller = QuickActionEditorController( + load: () => settings.bottomNavigationActions, + save: (actions) => settings.bottomNavigationActions = actions, + ); + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return QuickActionEditorPage<AvesNavItem>( + title: context.l10n.settingsNavigationBottomActionEditorPageTitle, + appBarActions: _buildActions(context), + bannerText: context.l10n.settingsNavigationBottomActionEditorBanner, + allAvailableActions: allAvailableActions, + actionIcon: (context, action) => action.getIcon(context), + actionText: (context, action) => action.getText(context), + controller: _controller, + ); + } + + List<Widget> _buildActions(BuildContext context) { + final animations = context.select<Settings, AccessibilityAnimations>((v) => v.accessibilityAnimations); + return [ + PopupMenuButton<_EditorAction>( + itemBuilder: (context) { + return [ + _EditorAction.addAlbum, + _EditorAction.addTag, + ].map<PopupMenuEntry<_EditorAction>>((v) { + return PopupMenuItem( + value: v, + child: MenuRow(text: v.getText(context), icon: v.getIcon()), + ); + }).toList(); + }, + onSelected: (action) async { + // wait for the popup menu to hide before proceeding with the action + await Future.delayed(animations.popUpAnimationDelay * timeDilation); + await _onActionSelected(context, action); + }, + popUpAnimationStyle: animations.popUpAnimationStyle, + ), + ].map((v) => FontSizeIconTheme(child: v)).toList(); + } + + Future<void> _onActionSelected(BuildContext context, _EditorAction action) async { + switch (action) { + case _EditorAction.addAlbum: + final albumFilter = await pickAlbum( + context: context, + moveType: null, + chipTypes: AlbumChipType.values, + initialGroup: null, + ); + if (albumFilter == null) return; + _controller.add(AvesNavItem(route: CollectionPage.routeName, filters: {albumFilter})); + case _EditorAction.addTag: + final tagFilter = await pickTag( + context: context, + chipTypes: ChipType.values, + initialGroup: null, + ); + if (tagFilter == null) return; + _controller.add(AvesNavItem(route: CollectionPage.routeName, filters: {tagFilter})); + } + } +} + +enum _EditorAction { + addAlbum, + addTag, +} + +extension _ExtraEditorActionView on _EditorAction { + String getText(BuildContext context) { + final l10n = context.l10n; + return switch (this) { + _EditorAction.addAlbum => l10n.settingsNavigationDrawerAddAlbum, + _EditorAction.addTag => l10n.tagEditorPageAddTagTooltip, + }; + } + + Widget getIcon() => Icon(_getIconData()); + + IconData _getIconData() { + return switch (this) { + _EditorAction.addAlbum => AIcons.album, + _EditorAction.addTag => AIcons.tag, + }; + } +} diff --git a/lib/widgets/settings/navigation/confirmation_dialogs.dart b/lib/widgets/settings/navigation/confirmation_dialogs.dart new file mode 100644 index 0000000..2e80643 --- /dev/null +++ b/lib/widgets/settings/navigation/confirmation_dialogs.dart @@ -0,0 +1,52 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/settings/common/tiles.dart'; +import 'package:flutter/material.dart'; + +class ConfirmationDialogPage extends StatelessWidget { + static const routeName = '/settings/navigation_confirmation'; + + const ConfirmationDialogPage({super.key}); + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + return AvesScaffold( + appBar: AppBar( + title: Text(l10n.settingsConfirmationDialogTitle), + ), + body: SafeArea( + child: ListView(children: [ + SettingsSwitchListTile( + selector: (context, s) => s.confirmMoveUndatedItems, + onChanged: (v) => settings.confirmMoveUndatedItems = v, + title: l10n.settingsConfirmationBeforeMoveUndatedItems, + ), + SettingsSwitchListTile( + selector: (context, s) => s.confirmMoveToBin, + onChanged: (v) => settings.confirmMoveToBin = v, + title: l10n.settingsConfirmationBeforeMoveToBinItems, + ), + SettingsSwitchListTile( + selector: (context, s) => s.confirmDeleteForever, + onChanged: (v) => settings.confirmDeleteForever = v, + title: l10n.settingsConfirmationBeforeDeleteItems, + ), + const Divider(height: 32), + SettingsSwitchListTile( + selector: (context, s) => s.confirmAfterMoveToBin, + onChanged: (v) => settings.confirmAfterMoveToBin = v, + title: l10n.settingsConfirmationAfterMoveToBinItems, + ), + const Divider(height: 32), + SettingsSwitchListTile( + selector: (context, s) => s.confirmCreateVault, + onChanged: (v) => settings.confirmCreateVault = v, + title: l10n.settingsConfirmationVaultDataLoss, + ), + ]), + ), + ); + } +} diff --git a/lib/widgets/settings/navigation/drawer.dart b/lib/widgets/settings/navigation/drawer.dart new file mode 100644 index 0000000..bbff15d --- /dev/null +++ b/lib/widgets/settings/navigation/drawer.dart @@ -0,0 +1,125 @@ +import 'package:aves/model/filters/container/album_group.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/filters/mime.dart'; +import 'package:aves/model/filters/recent.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/ref/mime_types.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/search/page.dart'; +import 'package:aves/widgets/explorer/explorer_page.dart'; +import 'package:aves/widgets/filter_grids/albums_page.dart'; +import 'package:aves/widgets/filter_grids/countries_page.dart'; +import 'package:aves/widgets/filter_grids/places_page.dart'; +import 'package:aves/widgets/filter_grids/tags_page.dart'; +import 'package:aves/widgets/navigation/drawer/app_drawer.dart'; +import 'package:aves/widgets/navigation/drawer/tile.dart'; +import 'package:aves/widgets/search/collection_search_delegate.dart'; +import 'package:aves/widgets/settings/navigation/drawer_tab_albums.dart'; +import 'package:aves/widgets/settings/navigation/drawer_tab_fixed.dart'; +import 'package:flutter/material.dart'; + +class NavigationDrawerEditorPage extends StatefulWidget { + static const routeName = '/settings/navigation/drawer'; + + static final List<CollectionFilter?> collectionFilterOptions = [ + null, + RecentlyAddedFilter.instance, + ...CollectionSearchDelegate.typeFilters, + MimeFilter(MimeTypes.svg), + ]; + static const List<String> pageOptions = [ + AlbumListPage.routeName, + CountryListPage.routeName, + PlaceListPage.routeName, + TagListPage.routeName, + ExplorerPage.routeName, + SearchPage.routeName, + ]; + + const NavigationDrawerEditorPage({super.key}); + + @override + State<NavigationDrawerEditorPage> createState() => _NavigationDrawerEditorPageState(); +} + +class _NavigationDrawerEditorPageState extends State<NavigationDrawerEditorPage> { + final List<CollectionFilter?> _typeItems = []; + final Set<CollectionFilter?> _visibleTypes = {}; + final List<AlbumBaseFilter> _albumItems = []; + final List<String> _pageItems = []; + final Set<String> _visiblePages = {}; + + @override + void initState() { + super.initState(); + final userTypeLinks = settings.drawerTypeBookmarks; + _visibleTypes.addAll(userTypeLinks); + _typeItems.addAll(userTypeLinks); + _typeItems.addAll(NavigationDrawerEditorPage.collectionFilterOptions.where((v) => !userTypeLinks.contains(v))); + + _albumItems.addAll(AppDrawer.effectiveAlbumBookmarks(context)); + + final userPageLinks = settings.drawerPageBookmarks; + _visiblePages.addAll(userPageLinks); + _pageItems.addAll(userPageLinks); + _pageItems.addAll(NavigationDrawerEditorPage.pageOptions.where((v) => !userPageLinks.contains(v))); + } + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + final tabs = <(Tab, Widget)>[ + ( + Tab(text: l10n.settingsNavigationDrawerTabTypes), + DrawerFixedListTab<CollectionFilter?>( + items: _typeItems, + visibleItems: _visibleTypes, + leading: (item) => DrawerFilterIcon(filter: item), + title: (item) => DrawerFilterTitle(filter: item), + ), + ), + ( + Tab(text: l10n.settingsNavigationDrawerTabAlbums), + DrawerAlbumTab( + items: _albumItems, + ), + ), + ( + Tab(text: l10n.settingsNavigationDrawerTabPages), + DrawerFixedListTab<String>( + items: _pageItems, + visibleItems: _visiblePages, + leading: (item) => DrawerPageIcon(route: item), + title: (item) => DrawerPageTitle(route: item), + ), + ), + ]; + + return DefaultTabController( + length: tabs.length, + child: AvesScaffold( + appBar: AppBar( + automaticallyImplyLeading: !settings.useTvLayout, + title: Text(l10n.settingsNavigationDrawerEditorPageTitle), + bottom: TabBar( + tabs: tabs.map((t) => t.$1).toList(), + ), + ), + body: PopScope( + onPopInvokedWithResult: (didPop, result) { + settings.drawerTypeBookmarks = _typeItems.where(_visibleTypes.contains).toList(); + settings.drawerAlbumBookmarks = _albumItems; + settings.drawerPageBookmarks = _pageItems.where(_visiblePages.contains).toList(); + }, + child: SafeArea( + bottom: false, + child: TabBarView( + children: tabs.map((t) => t.$2).toList(), + ), + ), + ), + ), + ); + } +} diff --git a/lib/widgets/settings/navigation/drawer_editor_banner.dart b/lib/widgets/settings/navigation/drawer_editor_banner.dart new file mode 100644 index 0000000..b05e639 --- /dev/null +++ b/lib/widgets/settings/navigation/drawer_editor_banner.dart @@ -0,0 +1,22 @@ +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/basic/font_size_icon_theme.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:flutter/material.dart'; + +class DrawerEditorBanner extends StatelessWidget { + const DrawerEditorBanner({super.key}); + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.all(16), + child: Row( + children: [ + const FontSizeIconTheme(child: Icon(AIcons.info)), + const SizedBox(width: 16), + Expanded(child: Text(context.l10n.settingsNavigationDrawerBanner)), + ], + ), + ); + } +} diff --git a/lib/widgets/settings/navigation/drawer_tab_albums.dart b/lib/widgets/settings/navigation/drawer_tab_albums.dart new file mode 100644 index 0000000..3ade24a --- /dev/null +++ b/lib/widgets/settings/navigation/drawer_tab_albums.dart @@ -0,0 +1,83 @@ +import 'package:aves/model/filters/container/album_group.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/buttons/outlined_button.dart'; +import 'package:aves/widgets/dialogs/pick_dialogs/album_pick_page.dart'; +import 'package:aves/widgets/filter_grids/common/enums.dart'; +import 'package:aves/widgets/navigation/drawer/tile.dart'; +import 'package:aves/widgets/settings/navigation/drawer_editor_banner.dart'; +import 'package:flutter/material.dart'; + +class DrawerAlbumTab extends StatefulWidget { + final List<AlbumBaseFilter> items; + + const DrawerAlbumTab({ + super.key, + required this.items, + }); + + @override + State<DrawerAlbumTab> createState() => _DrawerAlbumTabState(); +} + +class _DrawerAlbumTabState extends State<DrawerAlbumTab> { + List<AlbumBaseFilter> get items => widget.items; + + @override + Widget build(BuildContext context) { + return Column( + children: [ + if (!settings.useTvLayout) ...[ + const DrawerEditorBanner(), + const Divider(height: 0), + ], + Flexible( + child: ReorderableListView.builder( + itemBuilder: (context, index) { + final filter = items[index]; + void onPressed() => setState(() => items.remove(filter)); + return ListTile( + key: ValueKey(filter.key), + leading: DrawerFilterIcon(filter: filter), + title: DrawerFilterTitle(filter: filter), + trailing: IconButton( + icon: const Icon(AIcons.clear), + onPressed: onPressed, + tooltip: context.l10n.actionRemove, + ), + onTap: settings.useTvLayout ? onPressed : null, + ); + }, + itemCount: items.length, + onReorder: (oldIndex, newIndex) { + setState(() { + if (oldIndex < newIndex) newIndex -= 1; + items.insert(newIndex, items.removeAt(oldIndex)); + }); + }, + shrinkWrap: true, + ), + ), + const Divider(height: 0), + const SizedBox(height: 8), + SafeArea( + child: AvesOutlinedButton( + icon: const Icon(AIcons.add), + label: context.l10n.settingsNavigationDrawerAddAlbum, + onPressed: () async { + final albumFilter = await pickAlbum( + context: context, + moveType: null, + chipTypes: AlbumChipType.values, + initialGroup: null, + ); + if (albumFilter == null || items.contains(albumFilter)) return; + setState(() => items.add(albumFilter)); + }, + ), + ), + ], + ); + } +} diff --git a/lib/widgets/settings/navigation/drawer_tab_fixed.dart b/lib/widgets/settings/navigation/drawer_tab_fixed.dart new file mode 100644 index 0000000..0c38b81 --- /dev/null +++ b/lib/widgets/settings/navigation/drawer_tab_fixed.dart @@ -0,0 +1,90 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/extensions/media_query.dart'; +import 'package:aves/widgets/settings/navigation/drawer_editor_banner.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +typedef ItemWidgetBuilder<T> = Widget Function(T item); + +class DrawerFixedListTab<T> extends StatefulWidget { + final List<T> items; + final Set<T> visibleItems; + final ItemWidgetBuilder<T> leading; + final ItemWidgetBuilder<T> title; + + const DrawerFixedListTab({ + super.key, + required this.items, + required this.visibleItems, + required this.leading, + required this.title, + }); + + @override + State<DrawerFixedListTab<T>> createState() => _DrawerFixedListTabState<T>(); +} + +class _DrawerFixedListTabState<T> extends State<DrawerFixedListTab<T>> { + Set<T> get visibleItems => widget.visibleItems; + + @override + Widget build(BuildContext context) { + return Column( + children: [ + if (!settings.useTvLayout) ...[ + const DrawerEditorBanner(), + const Divider(height: 0), + ], + Flexible( + child: Selector<MediaQueryData, double>( + selector: (context, mq) => mq.effectiveBottomPadding, + builder: (context, mqPaddingBottom, child) { + // `ReorderableListView` does not automatically pad + // for `MediaQuery` insets, like regular `ListView` + return ReorderableListView.builder( + padding: EdgeInsets.only(bottom: mqPaddingBottom), + itemBuilder: (context, index) { + final filter = widget.items[index]; + final visible = visibleItems.contains(filter); + void onPressed() { + setState(() { + if (visible) { + visibleItems.remove(filter); + } else { + visibleItems.add(filter); + } + }); + } + + return Opacity( + key: ValueKey(filter), + opacity: visible ? 1 : .4, + child: ListTile( + leading: widget.leading(filter), + title: widget.title(filter), + trailing: IconButton( + icon: Icon(visible ? AIcons.hide : AIcons.show), + onPressed: onPressed, + tooltip: visible ? context.l10n.hideTooltip : context.l10n.showTooltip, + ), + onTap: settings.useTvLayout ? onPressed : null, + ), + ); + }, + itemCount: widget.items.length, + onReorder: (oldIndex, newIndex) { + setState(() { + if (oldIndex < newIndex) newIndex -= 1; + widget.items.insert(newIndex, widget.items.removeAt(oldIndex)); + }); + }, + ); + }, + ), + ), + ], + ); + } +} diff --git a/lib/widgets/settings/navigation/navigation.dart b/lib/widgets/settings/navigation/navigation.dart new file mode 100644 index 0000000..cb0e5a9 --- /dev/null +++ b/lib/widgets/settings/navigation/navigation.dart @@ -0,0 +1,177 @@ +import 'dart:async'; + +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/theme/colors.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/theme/text.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/settings/common/tile_leading.dart'; +import 'package:aves/widgets/settings/common/tiles.dart'; +import 'package:aves/widgets/settings/navigation/bottom_nav_actions_editor.dart'; +import 'package:aves/widgets/settings/navigation/confirmation_dialogs.dart'; +import 'package:aves/widgets/settings/navigation/drawer.dart'; +import 'package:aves/widgets/settings/settings_definition.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class NavigationSection extends SettingsSection { + @override + String get key => 'navigation'; + + @override + Widget icon(BuildContext context) => SettingsTileLeading( + icon: AIcons.home, + color: context.select<AvesColorsData, Color>((v) => v.navigation), + ); + + @override + String title(BuildContext context) => context.l10n.settingsNavigationSectionTitle; + + @override + FutureOr<List<SettingsTile>> tiles(BuildContext context) => [ + SettingsTileNavigationHomePage(), + if (!settings.useTvLayout) SettingsTileNavigationKeepScreenOn(), + if (!settings.useTvLayout) SettingsTileNavigationDoubleBackExit(), + SettingsTileNavigationDrawer(), + if (!settings.useTvLayout) SettingsTileNavigationBottomActions(), + if (!settings.useTvLayout) SettingsTileNavigationConfirmationDialog(), + ]; +} + +class _HomeOption { + final HomePageSetting page; + final Set<CollectionFilter> customCollection; + final String? customExplorerPath; + + const _HomeOption( + this.page, { + this.customCollection = const {}, + this.customExplorerPath, + }); + + String getName(BuildContext context) { + final pageName = page.getName(context); + switch (page) { + case HomePageSetting.collection: + return customCollection.isNotEmpty ? context.l10n.setHomeCustom : pageName; + case HomePageSetting.explorer: + return customExplorerPath != null ? context.l10n.setHomeCustom : pageName; + default: + return pageName; + } + } + + String? getDetails(BuildContext context) { + switch (page) { + case HomePageSetting.collection: + final filters = customCollection; + return filters.isNotEmpty ? [context.l10n.collectionPageTitle, filters.map((v) => v.getLabel(context)).join(', ')].join(AText.separator) : null; + case HomePageSetting.explorer: + final path = customExplorerPath; + return path != null ? [context.l10n.explorerPageTitle, pContext.basename(path)].join(AText.separator) : null; + default: + return null; + } + } + + @override + bool operator ==(Object other) => identical(this, other) || (other is _HomeOption && runtimeType == other.runtimeType && page == other.page && const DeepCollectionEquality().equals(customCollection, other.customCollection) && customExplorerPath == other.customExplorerPath); + + @override + int get hashCode => page.hashCode ^ customCollection.hashCode ^ customExplorerPath.hashCode; +} + +class SettingsTileNavigationHomePage extends SettingsTile { + @override + String title(BuildContext context) => context.l10n.settingsHomeTile; + + @override + Widget build(BuildContext context) => SettingsSelectionListTile<_HomeOption>( + values: [ + const _HomeOption(HomePageSetting.collection), + const _HomeOption(HomePageSetting.albums), + const _HomeOption(HomePageSetting.tags), + const _HomeOption(HomePageSetting.explorer), + if (settings.homeCustomCollection.isNotEmpty) _HomeOption(HomePageSetting.collection, customCollection: settings.homeCustomCollection), + if (settings.homeCustomExplorerPath != null) _HomeOption(HomePageSetting.explorer, customExplorerPath: settings.homeCustomExplorerPath), + ], + getName: (context, v) => v.getName(context), + selector: (context, s) => _HomeOption(s.homePage, customCollection: s.homeCustomCollection, customExplorerPath: s.homeCustomExplorerPath), + onSelection: (v) => settings.setHome( + v.page, + customCollection: v.customCollection, + customExplorerPath: v.customExplorerPath, + ), + tileTitle: title(context), + dialogTitle: context.l10n.settingsHomeDialogTitle, + optionSubtitleBuilder: (v) => v.getDetails(context), + ); +} + +class SettingsTileNavigationDrawer extends SettingsTile { + @override + String title(BuildContext context) => context.l10n.settingsNavigationDrawerTile; + + @override + Widget build(BuildContext context) => SettingsSubPageTile( + title: title(context), + routeName: NavigationDrawerEditorPage.routeName, + builder: (context) => const NavigationDrawerEditorPage(), + ); +} + +class SettingsTileNavigationBottomActions extends SettingsTile { + @override + String title(BuildContext context) => context.l10n.settingsNavigationBottomActionsTile; + + @override + Widget build(BuildContext context) => SettingsSubPageTile( + title: title(context), + routeName: BottomNavigationActionEditorPage.routeName, + builder: (context) => const BottomNavigationActionEditorPage(), + ); +} + +class SettingsTileNavigationConfirmationDialog extends SettingsTile { + @override + String title(BuildContext context) => context.l10n.settingsConfirmationTile; + + @override + Widget build(BuildContext context) => SettingsSubPageTile( + title: title(context), + routeName: ConfirmationDialogPage.routeName, + builder: (context) => const ConfirmationDialogPage(), + ); +} + +class SettingsTileNavigationKeepScreenOn extends SettingsTile { + @override + String title(BuildContext context) => context.l10n.settingsKeepScreenOnTile; + + @override + Widget build(BuildContext context) => SettingsSelectionListTile<KeepScreenOn>( + values: KeepScreenOn.values, + getName: (context, v) => v.getName(context), + selector: (context, s) => s.keepScreenOn, + onSelection: (v) => settings.keepScreenOn = v, + tileTitle: title(context), + dialogTitle: context.l10n.settingsKeepScreenOnDialogTitle, + ); +} + +class SettingsTileNavigationDoubleBackExit extends SettingsTile { + @override + String title(BuildContext context) => context.l10n.settingsDoubleBackExit; + + @override + Widget build(BuildContext context) => SettingsSwitchListTile( + selector: (context, s) => s.mustBackTwiceToExit, + onChanged: (v) => settings.mustBackTwiceToExit = v, + title: title(context), + ); +} diff --git a/lib/widgets/settings/privacy/access_grants_page.dart b/lib/widgets/settings/privacy/access_grants_page.dart new file mode 100644 index 0000000..36c0e02 --- /dev/null +++ b/lib/widgets/settings/privacy/access_grants_page.dart @@ -0,0 +1,107 @@ +import 'package:aves/services/common/services.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/basic/font_size_icon_theme.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/empty.dart'; +import 'package:flutter/material.dart'; + +class StorageAccessPage extends StatefulWidget { + static const routeName = '/settings/storage_access'; + + const StorageAccessPage({super.key}); + + @override + State<StorageAccessPage> createState() => _StorageAccessPageState(); +} + +class _StorageAccessPageState extends State<StorageAccessPage> { + late Future<List<String>> _pathLoader; + List<String>? _lastPaths; + + @override + void initState() { + super.initState(); + _load(); + } + + void _load() => _pathLoader = storageService.getGrantedDirectories(); + + @override + Widget build(BuildContext context) { + return AvesScaffold( + appBar: AppBar( + title: Text(context.l10n.settingsStorageAccessPageTitle), + ), + body: SafeArea( + child: FutureBuilder<List<String>>( + future: _pathLoader, + builder: (context, snapshot) { + if (snapshot.hasError) { + return Text(snapshot.error.toString()); + } + if (snapshot.connectionState != ConnectionState.done && _lastPaths == null) { + return const SizedBox(); + } + _lastPaths = snapshot.data!..sort(); + if (_lastPaths!.isEmpty) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const _Header(), + const Divider(), + Expanded( + child: Padding( + padding: const EdgeInsets.all(8), + child: EmptyContent( + text: context.l10n.settingsStorageAccessEmpty, + ), + ), + ), + ], + ); + } + + return ListView( + children: [ + const _Header(), + const Divider(), + ..._lastPaths!.map((path) => ListTile( + title: Text(path), + dense: true, + trailing: IconButton( + icon: const Icon(AIcons.clear), + onPressed: () async { + await storageService.revokeDirectoryAccess(path); + _load(); + setState(() {}); + }, + tooltip: context.l10n.settingsStorageAccessRevokeTooltip, + ), + )), + ], + ); + }, + ), + ), + ); + } +} + +class _Header extends StatelessWidget { + const _Header(); + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16), + child: Row( + children: [ + const FontSizeIconTheme(child: Icon(AIcons.info)), + const SizedBox(width: 16), + Expanded(child: Text(context.l10n.settingsStorageAccessBanner)), + ], + ), + ); + } +} diff --git a/lib/widgets/settings/privacy/hidden_items_page.dart b/lib/widgets/settings/privacy/hidden_items_page.dart new file mode 100644 index 0000000..9337f62 --- /dev/null +++ b/lib/widgets/settings/privacy/hidden_items_page.dart @@ -0,0 +1,123 @@ +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/basic/font_size_icon_theme.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/aves_filter_chip.dart'; +import 'package:aves/widgets/common/identity/empty.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class HiddenItemsPage extends StatelessWidget { + static const routeName = '/settings/hidden_items'; + + const HiddenItemsPage({super.key}); + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + return AvesScaffold( + appBar: AppBar( + automaticallyImplyLeading: !settings.useTvLayout, + title: Text(l10n.settingsHiddenItemsPageTitle), + ), + body: SafeArea( + child: Selector<Settings, Set<CollectionFilter>>( + selector: (context, s) => settings.hiddenFilters.toSet(), + builder: (context, activatedHiddenFilters, child) { + return Selector<Settings, Set<CollectionFilter>>( + selector: (context, s) => settings.deactivatedHiddenFilters.toSet(), + builder: (context, deactivatedHiddenFilters, child) { + final allHiddenFilters = { + ...activatedHiddenFilters, + ...deactivatedHiddenFilters, + }; + if (allHiddenFilters.isEmpty) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _Banner(bannerText: context.l10n.settingsHiddenFiltersBanner), + const Divider(height: 0), + Expanded( + child: Padding( + padding: const EdgeInsets.all(8), + child: EmptyContent( + icon: AIcons.hide, + text: context.l10n.settingsHiddenFiltersEmpty, + ), + ), + ), + ], + ); + } + + final filterList = allHiddenFilters.toList()..sort(); + return ListView( + children: [ + _Banner(bannerText: context.l10n.settingsHiddenFiltersBanner), + const Divider(height: 0), + const SizedBox(height: 8), + ...filterList.map((filter) { + void onRemove(CollectionFilter filter) => settings.changeFilterVisibility({filter}, true); + return Padding( + padding: const EdgeInsets.symmetric(vertical: 4, horizontal: 8), + child: Row( + children: [ + Expanded( + child: LayoutBuilder( + builder: (context, constraints) { + return Row( + children: [ + AvesFilterChip( + filter: filter, + maxWidth: constraints.maxWidth, + onTap: onRemove, + onRemove: onRemove, + onLongPress: null, + ), + const Spacer(), + ], + ); + }, + ), + ), + const SizedBox(width: 8), + Switch( + value: activatedHiddenFilters.contains(filter), + onChanged: (v) => settings.activateHiddenFilter(filter, v), + ), + ], + ), + ); + }), + ], + ); + }, + ); + }, + ), + ), + ); + } +} + +class _Banner extends StatelessWidget { + final String bannerText; + + const _Banner({required this.bannerText}); + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.all(16), + child: Row( + children: [ + const FontSizeIconTheme(child: Icon(AIcons.info)), + const SizedBox(width: 16), + Expanded(child: Text(bannerText)), + ], + ), + ); + } +} diff --git a/lib/widgets/settings/privacy/privacy.dart b/lib/widgets/settings/privacy/privacy.dart new file mode 100644 index 0000000..d49a481 --- /dev/null +++ b/lib/widgets/settings/privacy/privacy.dart @@ -0,0 +1,233 @@ +import 'dart:async'; + +import 'package:aves/app_flavor.dart'; +import 'package:aves/model/device.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/model/vaults/vaults.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/theme/colors.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/collection/entry_set_action_delegate.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/dialogs/aves_confirmation_dialog.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:aves/widgets/settings/common/tile_leading.dart'; +import 'package:aves/widgets/settings/common/tiles.dart'; +import 'package:aves/widgets/settings/privacy/access_grants_page.dart'; +import 'package:aves/widgets/settings/privacy/hidden_items_page.dart'; +import 'package:aves/widgets/settings/settings_definition.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class PrivacySection extends SettingsSection { + @override + String get key => 'privacy'; + + @override + Widget icon(BuildContext context) => SettingsTileLeading( + icon: AIcons.privacy, + color: context.select<AvesColorsData, Color>((v) => v.privacy), + ); + + @override + String title(BuildContext context) => context.l10n.settingsPrivacySectionTitle; + + @override + FutureOr<List<SettingsTile>> tiles(BuildContext context) async { + final canEnableErrorReporting = context.select<AppFlavor, bool>((v) => v.canEnableErrorReporting); + return [ + SettingsTilePrivacyAllowInstalledAppAccess(), + if (canEnableErrorReporting) SettingsTilePrivacyAllowErrorReporting(), + if (!settings.useTvLayout && device.canRequestManageMedia) SettingsTilePrivacyManageMedia(), + SettingsTilePrivacySaveSearchHistory(), + if (!settings.useTvLayout) SettingsTilePrivacyEnableBin(), + SettingsTilePrivacyHiddenItems(), + if (!settings.useTvLayout) SettingsTilePrivacyStorageAccess(), + ]; + } +} + +class SettingsTilePrivacyAllowInstalledAppAccess extends SettingsTile { + @override + String title(BuildContext context) => context.l10n.settingsAllowInstalledAppAccess; + + @override + Widget build(BuildContext context) => SettingsSwitchListTile( + selector: (context, s) => s.isInstalledAppAccessAllowed, + onChanged: (v) => settings.isInstalledAppAccessAllowed = v, + title: title(context), + subtitle: context.l10n.settingsAllowInstalledAppAccessSubtitle, + ); +} + +class SettingsTilePrivacyAllowErrorReporting extends SettingsTile { + @override + String title(BuildContext context) => context.l10n.settingsAllowErrorReporting; + + @override + Widget build(BuildContext context) => SettingsSwitchListTile( + selector: (context, s) => s.isErrorReportingAllowed, + onChanged: (v) => settings.isErrorReportingAllowed = v, + title: title(context), + ); +} + +class SettingsTilePrivacySaveSearchHistory extends SettingsTile { + @override + String title(BuildContext context) => context.l10n.settingsSaveSearchHistory; + + @override + Widget build(BuildContext context) => SettingsSwitchListTile( + selector: (context, s) => s.saveSearchHistory, + onChanged: (v) { + settings.saveSearchHistory = v; + if (!v) { + settings.searchHistory = []; + } + }, + title: title(context), + ); +} + +class SettingsTilePrivacyEnableBin extends SettingsTile { + @override + String title(BuildContext context) => context.l10n.settingsEnableBin; + + @override + Widget build(BuildContext context) => SettingsSwitchListTile( + selector: (context, s) => s.enableBin, + onChanged: (v) => setBinUsage(context, v), + title: title(context), + subtitle: context.l10n.settingsEnableBinSubtitle, + ); + + static Future<bool> setBinUsage(BuildContext context, bool enabled) async { + final l10n = context.l10n; + if (!enabled) { + if (vaults.all.any((v) => v.useBin)) { + await showDialog<bool>( + context: context, + builder: (context) => AvesDialog( + content: Text(l10n.vaultBinUsageDialogMessage), + actions: const [OkButton()], + ), + ); + return false; + } + + final source = context.read<CollectionSource>(); + final trashedEntries = source.trashedEntries; + if (trashedEntries.isNotEmpty) { + if (!await showConfirmationDialog( + context: context, + message: l10n.settingsDisablingBinWarningDialogMessage, + confirmationButtonLabel: l10n.applyButtonLabel, + )) { + return false; + } + + // delete forever trashed items + await EntrySetActionDelegate().doDelete( + context: context, + entries: trashedEntries, + enableBin: false, + ); + + // in case of failure or cancellation + if (source.trashedEntries.isNotEmpty) return false; + } + + settings.searchHistory = []; + } + + settings.enableBin = enabled; + return true; + } +} + +class SettingsTilePrivacyHiddenItems extends SettingsTile { + @override + String title(BuildContext context) => context.l10n.settingsHiddenItemsTile; + + @override + Widget build(BuildContext context) => SettingsSubPageTile( + title: title(context), + routeName: HiddenItemsPage.routeName, + builder: (context) => const HiddenItemsPage(), + ); +} + +class SettingsTilePrivacyStorageAccess extends SettingsTile { + @override + String title(BuildContext context) => context.l10n.settingsStorageAccessTile; + + @override + Widget build(BuildContext context) => SettingsSubPageTile( + title: title(context), + routeName: StorageAccessPage.routeName, + builder: (context) => const StorageAccessPage(), + ); +} + +class SettingsTilePrivacyManageMedia extends SettingsTile { + @override + String title(BuildContext context) => context.l10n.settingsAllowMediaManagement; + + @override + Widget build(BuildContext context) => _ManageMediaTile(title: title(context)); +} + +class _ManageMediaTile extends StatefulWidget { + final String title; + + const _ManageMediaTile({ + required this.title, + }); + + @override + State<_ManageMediaTile> createState() => _ManageMediaTileState(); +} + +class _ManageMediaTileState extends State<_ManageMediaTile> with WidgetsBindingObserver { + late Future<bool> _loader; + + @override + void initState() { + super.initState(); + _initLoader(); + WidgetsBinding.instance.addObserver(this); + } + + @override + void dispose() { + WidgetsBinding.instance.removeObserver(this); + super.dispose(); + } + + void _initLoader() => _loader = deviceService.canManageMedia(); + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + if (state == AppLifecycleState.resumed) { + _initLoader(); + setState(() {}); + } + } + + @override + Widget build(BuildContext context) { + return FutureBuilder<bool>( + future: _loader, + builder: (context, snapshot) { + final loading = snapshot.connectionState != ConnectionState.done; + final current = snapshot.data ?? false; + return SwitchListTile( + value: current, + onChanged: loading ? null : (v) => deviceService.requestMediaManagePermission(), + title: Text(widget.title), + ); + }, + ); + } +} diff --git a/lib/widgets/settings/screen_saver_settings_page.dart b/lib/widgets/settings/screen_saver_settings_page.dart new file mode 100644 index 0000000..ca356f9 --- /dev/null +++ b/lib/widgets/settings/screen_saver_settings_page.dart @@ -0,0 +1,71 @@ +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/settings/common/collection_tile.dart'; +import 'package:aves/widgets/settings/common/tiles.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class ScreenSaverSettingsPage extends StatelessWidget { + static const routeName = '/settings/screen_saver'; + + const ScreenSaverSettingsPage({super.key}); + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + return AvesScaffold( + appBar: AppBar( + title: Text(l10n.settingsScreenSaverPageTitle), + ), + body: SafeArea( + child: ListView( + children: [ + SettingsSwitchListTile( + selector: (context, s) => s.screenSaverFillScreen, + onChanged: (v) => settings.screenSaverFillScreen = v, + title: l10n.settingsSlideshowFillScreen, + ), + SettingsSwitchListTile( + selector: (context, s) => s.screenSaverAnimatedZoomEffect, + onChanged: (v) => settings.screenSaverAnimatedZoomEffect = v, + title: l10n.settingsSlideshowAnimatedZoomEffect, + ), + SettingsSelectionListTile<ViewerTransition>( + values: ViewerTransition.values, + getName: (context, v) => v.getName(context), + selector: (context, s) => s.screenSaverTransition, + onSelection: (v) => settings.screenSaverTransition = v, + tileTitle: l10n.settingsSlideshowTransitionTile, + ), + SettingsDurationListTile( + selector: (context, s) => s.screenSaverInterval, + onChanged: (v) => settings.screenSaverInterval = v, + title: l10n.settingsSlideshowIntervalTile, + ), + SettingsSelectionListTile<SlideshowVideoPlayback>( + values: SlideshowVideoPlayback.values, + getName: (context, v) => v.getName(context), + selector: (context, s) => s.screenSaverVideoPlayback, + onSelection: (v) => settings.screenSaverVideoPlayback = v, + tileTitle: l10n.settingsSlideshowVideoPlaybackTile, + dialogTitle: l10n.settingsSlideshowVideoPlaybackDialogTitle, + ), + Selector<Settings, Set<CollectionFilter>>( + selector: (context, s) => s.screenSaverCollectionFilters, + builder: (context, filters, child) { + return SettingsCollectionTile( + filters: filters, + onSelection: (v) => settings.screenSaverCollectionFilters = v, + ); + }, + ), + ], + ), + ), + ); + } +} diff --git a/lib/widgets/settings/settings_definition.dart b/lib/widgets/settings/settings_definition.dart new file mode 100644 index 0000000..3548e86 --- /dev/null +++ b/lib/widgets/settings/settings_definition.dart @@ -0,0 +1,44 @@ +import 'dart:async'; + +import 'package:aves/widgets/common/identity/aves_expansion_tile.dart'; +import 'package:flutter/widgets.dart'; + +abstract class SettingsSection { + String get key; + + Widget icon(BuildContext context); + + String title(BuildContext context); + + FutureOr<List<SettingsTile>> tiles(BuildContext context); + + Widget build(BuildContext sectionContext, ValueNotifier<String?> expandedNotifier) { + return FutureBuilder<List<SettingsTile>>( + future: Future.value(tiles(sectionContext)), + builder: (tileContext, snapshot) { + final tiles = snapshot.data; + if (tiles == null) return const SizedBox(); + + return AvesExpansionTile( + // key is expected by test driver + key: Key('section-$key'), + // use a fixed value instead of the title to identify this expansion tile + // so that the tile state is kept when the language is modified + value: key, + leading: icon(tileContext), + title: title(tileContext), + expandedNotifier: expandedNotifier, + showHighlight: false, + // reuse section context so that dialogs opened from tiles have the right text theme + children: tiles.map((v) => v.build(sectionContext)).toList(), + ); + }, + ); + } +} + +abstract class SettingsTile { + String title(BuildContext context); + + Widget build(BuildContext context); +} diff --git a/lib/widgets/settings/settings_mobile_page.dart b/lib/widgets/settings/settings_mobile_page.dart new file mode 100644 index 0000000..90ca603 --- /dev/null +++ b/lib/widgets/settings/settings_mobile_page.dart @@ -0,0 +1,193 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:aves/model/settings/enums/accessibility_animations.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/ref/locales.dart'; +import 'package:aves/ref/mime_types.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/widgets/common/action_mixins/feedback.dart'; +import 'package:aves/widgets/common/app_bar/app_bar_title.dart'; +import 'package:aves/widgets/common/basic/font_size_icon_theme.dart'; +import 'package:aves/widgets/common/basic/insets.dart'; +import 'package:aves/widgets/common/basic/popup/menu_row.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/search/route.dart'; +import 'package:aves/widgets/settings/app_export/items.dart'; +import 'package:aves/widgets/settings/app_export/selection_dialog.dart'; +import 'package:aves/widgets/settings/settings_page.dart'; +import 'package:aves/widgets/settings/settings_search_delegate.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:flutter_staggered_animations/flutter_staggered_animations.dart'; +import 'package:intl/intl.dart'; +import 'package:provider/provider.dart'; + +class SettingsMobilePage extends StatefulWidget { + const SettingsMobilePage({super.key}); + + @override + State<SettingsMobilePage> createState() => _SettingsMobilePageState(); +} + +class _SettingsMobilePageState extends State<SettingsMobilePage> with FeedbackMixin { + final ValueNotifier<String?> _expandedNotifier = ValueNotifier(null); + + @override + void dispose() { + _expandedNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final animations = context.select<Settings, AccessibilityAnimations>((v) => v.accessibilityAnimations); + return AvesScaffold( + appBar: AppBar( + title: InteractiveAppBarTitle( + onTap: () => _goToSearch(context), + child: Text(context.l10n.settingsPageTitle), + ), + actions: [ + IconButton( + icon: const Icon(AIcons.search), + onPressed: () => _goToSearch(context), + tooltip: MaterialLocalizations.of(context).searchFieldLabel, + ), + PopupMenuButton<SettingsAction>( + itemBuilder: (context) { + return [ + PopupMenuItem( + value: SettingsAction.export, + child: MenuRow(text: context.l10n.settingsActionExport, icon: Icon(AIcons.fileExport)), + ), + PopupMenuItem( + value: SettingsAction.import, + child: MenuRow(text: context.l10n.settingsActionImport, icon: Icon(AIcons.fileImport)), + ), + ]; + }, + onSelected: (action) async { + // wait for the popup menu to hide before proceeding with the action + await Future.delayed(animations.popUpAnimationDelay * timeDilation); + _onActionSelected(action); + }, + popUpAnimationStyle: animations.popUpAnimationStyle, + ), + ].map((v) => FontSizeIconTheme(child: v)).toList(), + ), + body: GestureAreaProtectorStack( + child: SafeArea( + bottom: false, + child: AnimationLimiter( + child: SettingsListView( + children: SettingsPage.sections.map((v) => v.build(context, _expandedNotifier)).toList(), + ), + ), + ), + ), + ); + } + + static const String exportVersionKey = 'version'; + static const int exportVersion = 1; + + void _onActionSelected(SettingsAction action) async { + final source = context.read<CollectionSource>(); + switch (action) { + case SettingsAction.export: + final toExport = await showDialog<Set<AppExportItem>>( + context: context, + builder: (context) => AppExportItemSelectionDialog( + title: context.l10n.settingsActionExportDialogTitle, + ), + ); + if (toExport == null || toExport.isEmpty) return; + + final allMap = Map.fromEntries(toExport.map((v) { + final jsonMap = v.export(source); + return jsonMap != null ? MapEntry(v.name, jsonMap) : null; + }).nonNulls); + allMap[exportVersionKey] = exportVersion; + final allJsonString = jsonEncode(allMap); + + const mimeType = MimeTypes.json; + final success = await storageService.createFile( + 'aves-settings-${DateFormat('yyyyMMdd_HHmmss', asciiLocale).format(DateTime.now())}${MimeTypes.extensionFor(mimeType)}', + mimeType, + Uint8List.fromList(utf8.encode(allJsonString)), + ); + if (success != null) { + if (success) { + showFeedback(context, FeedbackType.info, context.l10n.genericSuccessFeedback); + } else { + showFeedback(context, FeedbackType.warn, context.l10n.genericFailureFeedback); + } + } + case SettingsAction.import: + // specifying the JSON MIME type to restrict openable files is correct in theory, + // but older devices (e.g. SM-P580, API 27) that do not recognize JSON files as such would filter them out + final bytes = await storageService.openFile(); + if (bytes.isNotEmpty) { + try { + final allJsonString = utf8.decode(bytes); + final allJsonMap = jsonDecode(allJsonString); + + final version = allJsonMap[exportVersionKey]; + final importable = <AppExportItem, dynamic>{}; + if (version == null) { + // backward compatibility before versioning + importable[AppExportItem.settings] = allJsonMap; + } else { + if (allJsonMap is! Map) { + debugPrint('failed to import app json=$allJsonMap'); + showFeedback(context, FeedbackType.warn, context.l10n.genericFailureFeedback); + return; + } + allJsonMap.keys.where((v) => v != exportVersionKey).forEach((k) { + try { + importable[AppExportItem.values.byName(k)] = allJsonMap[k]; + } catch (error, stack) { + debugPrint('failed to identify import app item=$k with error=$error\n$stack'); + } + }); + } + + final toImport = await showDialog<Set<AppExportItem>>( + context: context, + builder: (context) => AppExportItemSelectionDialog( + title: context.l10n.settingsActionImportDialogTitle, + selectableItems: importable.keys.toSet(), + ), + ); + if (toImport == null || toImport.isEmpty) return; + + await Future.forEach<AppExportItem>(toImport, (item) async { + return item.import(importable[item], source); + }); + showFeedback(context, FeedbackType.info, context.l10n.genericSuccessFeedback); + } catch (error, stack) { + debugPrint('failed to import app json, error=$error\n$stack'); + showFeedback(context, FeedbackType.warn, context.l10n.genericFailureFeedback); + } + } + } + } + + void _goToSearch(BuildContext context) { + Navigator.maybeOf(context)?.push( + SearchPageRoute( + delegate: SettingsSearchDelegate( + searchFieldLabel: context.l10n.settingsSearchFieldLabel, + searchFieldStyle: Themes.searchFieldStyle(context), + sections: SettingsPage.sections, + ), + ), + ); + } +} diff --git a/lib/widgets/settings/settings_page.dart b/lib/widgets/settings/settings_page.dart new file mode 100644 index 0000000..f5eb8e0 --- /dev/null +++ b/lib/widgets/settings/settings_page.dart @@ -0,0 +1,88 @@ +import 'dart:math'; + +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/widgets/common/extensions/media_query.dart'; +import 'package:aves/widgets/settings/accessibility/accessibility.dart'; +import 'package:aves/widgets/settings/display/display.dart'; +import 'package:aves/widgets/settings/language/language.dart'; +import 'package:aves/widgets/settings/navigation/navigation.dart'; +import 'package:aves/widgets/settings/privacy/privacy.dart'; +import 'package:aves/widgets/settings/settings_definition.dart'; +import 'package:aves/widgets/settings/settings_mobile_page.dart'; +import 'package:aves/widgets/settings/settings_tv_page.dart'; +import 'package:aves/widgets/settings/thumbnails/thumbnails.dart'; +import 'package:aves/widgets/settings/video/video.dart'; +import 'package:aves/widgets/settings/viewer/viewer.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:flutter_staggered_animations/flutter_staggered_animations.dart'; +import 'package:provider/provider.dart'; + +class SettingsPage extends StatelessWidget { + static const routeName = '/settings'; + + static final List<SettingsSection> sections = [ + NavigationSection(), + ThumbnailsSection(), + ViewerSection(), + VideoSection(), + PrivacySection(), + AccessibilitySection(), + DisplaySection(), + LanguageSection(), + ]; + + const SettingsPage({super.key}); + + @override + Widget build(BuildContext context) { + if (settings.useTvLayout) { + return const SettingsTvPage(); + } else { + return const SettingsMobilePage(); + } + } +} + +class SettingsListView extends StatelessWidget { + final List<Widget> children; + + const SettingsListView({ + super.key, + required this.children, + }); + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return Theme( + data: theme.copyWith( + textTheme: theme.textTheme.copyWith( + // dense style font for tile subtitles, without modifying title font + bodyMedium: const TextStyle(fontSize: 12), + ), + ), + child: Selector<MediaQueryData, double>( + selector: (context, mq) => max(mq.effectiveBottomPadding, mq.systemGestureInsets.bottom), + builder: (context, mqPaddingBottom, child) { + final durations = context.watch<DurationsData>(); + return ListView( + padding: const EdgeInsets.all(8) + EdgeInsets.only(bottom: mqPaddingBottom), + children: AnimationConfiguration.toStaggeredList( + duration: durations.staggeredAnimation, + delay: durations.staggeredAnimationDelay * timeDilation, + childAnimationBuilder: (child) => SlideAnimation( + verticalOffset: 50.0, + child: FadeInAnimation( + child: child, + ), + ), + children: children, + ), + ); + }, + ), + ); + } +} diff --git a/lib/widgets/settings/settings_search_delegate.dart b/lib/widgets/settings/settings_search_delegate.dart new file mode 100644 index 0000000..a9403ea --- /dev/null +++ b/lib/widgets/settings/settings_search_delegate.dart @@ -0,0 +1,84 @@ +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/empty.dart'; +import 'package:aves/widgets/common/identity/highlight_title.dart'; +import 'package:aves/widgets/common/providers/media_query_data_provider.dart'; +import 'package:aves/widgets/common/search/delegate.dart'; +import 'package:aves/widgets/settings/settings_definition.dart'; +import 'package:flutter/material.dart'; + +class SettingsSearchDelegate extends AvesSearchDelegate { + final List<SettingsSection> sections; + + static const pageRouteName = '/settings/search'; + + SettingsSearchDelegate({ + required super.searchFieldLabel, + required super.searchFieldStyle, + required this.sections, + }) : super( + routeName: pageRouteName, + ); + + @override + Widget buildSuggestions(BuildContext context) { + final upQuery = query.toUpperCase().trim(); + if (upQuery.isEmpty) return const SizedBox(); + + bool testKey(String key) => key.toUpperCase().contains(upQuery); + + final loader = Future.wait(sections.map((section) async { + final allTiles = await section.tiles(context); + final filteredTiles = testKey(section.title(context)) ? allTiles : allTiles.where((v) => testKey(v.title(context))).toList(); + if (filteredTiles.isEmpty) return null; + + return (context) { + return <Widget>[ + Padding( + // match header layout in Settings page + padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 13), + child: Row( + children: [ + section.icon(context), + const SizedBox(width: 8), + Expanded( + child: HighlightTitle( + title: section.title(context), + showHighlight: false, + ), + ), + ], + ), + ), + ...filteredTiles.map((v) => v.build(context)), + ]; + }; + })); + + return MediaQueryDataProvider( + child: SafeArea( + child: FutureBuilder<List<List<Widget> Function(BuildContext)?>>( + future: loader, + builder: (context, snapshot) { + final loaders = snapshot.data; + if (loaders == null) return const SizedBox(); + + final children = loaders.nonNulls.expand((builder) => builder(context)).toList(); + return children.isEmpty + ? EmptyContent( + icon: AIcons.settings, + text: context.l10n.settingsSearchEmpty, + ) + : ListView( + padding: const EdgeInsets.all(8), + children: children, + ); + }, + ), + ), + ); + } + + @override + Widget buildResults(BuildContext context) => buildSuggestions(context); +} diff --git a/lib/widgets/settings/settings_tv_page.dart b/lib/widgets/settings/settings_tv_page.dart new file mode 100644 index 0000000..cfff499 --- /dev/null +++ b/lib/widgets/settings/settings_tv_page.dart @@ -0,0 +1,143 @@ +import 'package:aves/widgets/common/basic/insets.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/behaviour/pop/scope.dart'; +import 'package:aves/widgets/common/behaviour/pop/tv_navigation.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/navigation/tv_rail.dart'; +import 'package:aves/widgets/settings/settings_definition.dart'; +import 'package:aves/widgets/settings/settings_page.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class SettingsTvPage extends StatelessWidget { + const SettingsTvPage({super.key}); + + @override + Widget build(BuildContext context) { + return AvesScaffold( + body: AvesPopScope( + handlers: [tvNavigationPopHandler], + child: Row( + children: [ + TvRail( + controller: context.read<TvRailController>(), + ), + Expanded( + child: Column( + children: [ + const SizedBox(height: 8), + DirectionalSafeArea( + start: false, + bottom: false, + child: AppBar( + automaticallyImplyLeading: false, + title: Text(context.l10n.settingsPageTitle), + elevation: 0, + primary: false, + ), + ), + const Expanded( + child: _Content(), + ), + ], + ), + ), + ], + ), + ), + ); + } +} + +class _Content extends StatefulWidget { + const _Content(); + + @override + State<_Content> createState() => _ContentState(); +} + +class _ContentState extends State<_Content> { + final ValueNotifier<int> _indexNotifier = ValueNotifier(0); + + @override + void dispose() { + _indexNotifier.dispose(); + super.dispose(); + } + + static final List<SettingsSection> sections = SettingsPage.sections; + + @override + Widget build(BuildContext context) { + return ValueListenableBuilder<int>( + valueListenable: _indexNotifier, + builder: (context, selectedIndex, child) { + final rail = NavigationRail( + extended: true, + destinations: sections + .map((section) => NavigationRailDestination( + icon: section.icon(context), + label: Text(section.title(context)), + )) + .toList(), + selectedIndex: selectedIndex, + onDestinationSelected: (index) => _indexNotifier.value = index, + minExtendedWidth: TvRail.minExtendedWidth, + ); + return LayoutBuilder( + builder: (context, constraints) { + return Row( + children: [ + MediaQuery.removePadding( + context: context, + removeLeft: true, + removeTop: true, + removeRight: true, + removeBottom: true, + child: SingleChildScrollView( + child: ConstrainedBox( + constraints: BoxConstraints(minHeight: constraints.maxHeight), + child: IntrinsicHeight(child: rail), + ), + ), + ), + Expanded( + child: MediaQuery.removePadding( + context: context, + removeLeft: !context.isRtl, + removeRight: context.isRtl, + child: _Section( + loader: Future.value(sections[selectedIndex].tiles(context)), + ), + ), + ), + ], + ); + }, + ); + }, + ); + } +} + +class _Section extends StatelessWidget { + final Future<List<SettingsTile>> loader; + + const _Section({required this.loader}); + + @override + Widget build(BuildContext context) { + return FutureBuilder<List<SettingsTile>>( + future: loader, + builder: (context, snapshot) { + final tiles = snapshot.data; + if (tiles == null) return const SizedBox(); + + return SettingsListView( + key: ValueKey(loader), + children: tiles.map((v) => v.build(context)).toList(), + ); + }, + ); + } +} diff --git a/lib/widgets/settings/thumbnails/collection_actions_editor_page.dart b/lib/widgets/settings/thumbnails/collection_actions_editor_page.dart new file mode 100644 index 0000000..af5be42 --- /dev/null +++ b/lib/widgets/settings/thumbnails/collection_actions_editor_page.dart @@ -0,0 +1,90 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/settings/common/quick_actions/editor_page.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; + +class CollectionActionEditorPage extends StatefulWidget { + static const routeName = '/settings/collection_actions'; + + const CollectionActionEditorPage({super.key}); + + @override + State<CollectionActionEditorPage> createState() => _CollectionActionEditorPageState(); +} + +class _CollectionActionEditorPageState extends State<CollectionActionEditorPage> { + late final QuickActionEditorController<EntrySetAction> _browsingController; + late final QuickActionEditorController<EntrySetAction> _selectingController; + + @override + void initState() { + super.initState(); + _browsingController = QuickActionEditorController( + load: () => settings.collectionBrowsingQuickActions, + save: (actions) => settings.collectionBrowsingQuickActions = actions, + ); + _selectingController = QuickActionEditorController( + load: () => settings.collectionSelectionQuickActions, + save: (actions) => settings.collectionSelectionQuickActions = actions, + ); + } + + @override + void dispose() { + _browsingController.dispose(); + _selectingController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + final tabs = <(Tab, Widget)>[ + ( + Tab(text: l10n.settingsCollectionQuickActionTabBrowsing), + QuickActionEditorBody<EntrySetAction>( + bannerText: context.l10n.settingsCollectionBrowsingQuickActionEditorBanner, + allAvailableActions: const [ + EntrySetActions.collectionEditorBrowsing, + ], + actionIcon: (context, action) => action.getIcon(), + actionText: (context, action) => action.getText(context), + controller: _browsingController, + ), + ), + ( + Tab(text: l10n.settingsCollectionQuickActionTabSelecting), + QuickActionEditorBody<EntrySetAction>( + bannerText: context.l10n.settingsCollectionSelectionQuickActionEditorBanner, + allAvailableActions: const [ + EntrySetActions.collectionEditorSelectionRegular, + EntrySetActions.collectionEditorSelectionEdit, + ], + actionIcon: (context, action) => action.getIcon(), + actionText: (context, action) => action.getText(context), + controller: _selectingController, + ), + ), + ]; + + return DefaultTabController( + length: tabs.length, + child: AvesScaffold( + appBar: AppBar( + title: Text(context.l10n.settingsCollectionQuickActionEditorPageTitle), + bottom: TabBar( + tabs: tabs.map((t) => t.$1).toList(), + ), + ), + body: SafeArea( + child: TabBarView( + children: tabs.map((t) => t.$2).toList(), + ), + ), + ), + ); + } +} diff --git a/lib/widgets/settings/thumbnails/overlay.dart b/lib/widgets/settings/thumbnails/overlay.dart new file mode 100644 index 0000000..7001222 --- /dev/null +++ b/lib/widgets/settings/thumbnails/overlay.dart @@ -0,0 +1,148 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/aves_icons.dart'; +import 'package:aves/widgets/settings/common/switch_icon.dart'; +import 'package:aves/widgets/settings/common/tiles.dart'; +import 'package:aves/widgets/settings/settings_definition.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class ThumbnailOverlayPage extends StatelessWidget { + static const routeName = '/settings/thumbnail_overlay'; + + const ThumbnailOverlayPage({super.key}); + + @override + Widget build(BuildContext context) { + final iconSize = SettingSwitchTrailingIcon.getIconSize(context); + final iconColor = SettingSwitchTrailingIcon.getIconColor(context); + + return AvesScaffold( + appBar: AppBar( + automaticallyImplyLeading: !settings.useTvLayout, + title: Text(context.l10n.settingsThumbnailOverlayPageTitle), + ), + body: SafeArea( + child: ListView( + children: [ + SettingsSwitchListTile( + selector: (context, s) => s.showThumbnailFavourite, + onChanged: (v) => settings.showThumbnailFavourite = v, + title: context.l10n.settingsThumbnailShowFavouriteIcon, + trailing: Padding( + padding: EdgeInsets.symmetric(horizontal: iconSize * (1 - FavouriteIcon.scale) / 2), + child: Icon( + AIcons.favourite, + size: iconSize * FavouriteIcon.scale, + color: iconColor, + ), + ), + ), + SettingsSwitchListTile( + selector: (context, s) => s.showThumbnailMotionPhoto, + onChanged: (v) => settings.showThumbnailMotionPhoto = v, + title: context.l10n.settingsThumbnailShowMotionPhotoIcon, + trailing: Padding( + padding: EdgeInsets.symmetric(horizontal: iconSize * (1 - MotionPhotoIcon.scale) / 2), + child: Icon( + AIcons.motionPhoto, + size: iconSize * MotionPhotoIcon.scale, + color: iconColor, + ), + ), + ), + SettingsSwitchListTile( + selector: (context, s) => s.showThumbnailRating, + onChanged: (v) => settings.showThumbnailRating = v, + title: context.l10n.settingsThumbnailShowRating, + trailing: Icon( + AIcons.rating, + size: iconSize, + color: iconColor, + ), + ), + SettingsSwitchListTile( + selector: (context, s) => s.showThumbnailHdr, + onChanged: (v) => settings.showThumbnailHdr = v, + title: context.l10n.settingsThumbnailShowHdrIcon, + trailing: Icon( + AIcons.hdr, + size: iconSize, + color: iconColor, + ), + ), + SettingsSwitchListTile( + selector: (context, s) => s.showThumbnailRaw, + onChanged: (v) => settings.showThumbnailRaw = v, + title: context.l10n.settingsThumbnailShowRawIcon, + trailing: Icon( + AIcons.raw, + size: iconSize, + color: iconColor, + ), + ), + SettingsSwitchListTile( + selector: (context, s) => s.showThumbnailVideoDuration, + onChanged: (v) => settings.showThumbnailVideoDuration = v, + title: context.l10n.settingsThumbnailShowVideoDuration, + ), + SettingsTileThumbnailLocationIcon().build(context), + SettingsTileThumbnailTagIcon().build(context), + ], + ), + ), + ); + } +} + +class SettingsTileThumbnailLocationIcon extends SettingsTile { + @override + String title(BuildContext context) => context.l10n.settingsThumbnailShowLocationIcon; + + @override + Widget build(BuildContext context) => SettingsSelectionListTile<ThumbnailOverlayLocationIcon>( + values: ThumbnailOverlayLocationIcon.values, + getName: (context, v) => v.getName(context), + selector: (context, s) => s.thumbnailLocationIcon, + onSelection: (v) => settings.thumbnailLocationIcon = v, + tileTitle: title(context), + trailingBuilder: _buildTrailing, + ); + + Widget _buildTrailing(BuildContext context) { + final iconType = context.select<Settings, ThumbnailOverlayLocationIcon>((v) => v.thumbnailLocationIcon); + return SettingSwitchTrailingIcon( + key: ValueKey(iconType), + icon: iconType.getIcon(context), + disabled: iconType == ThumbnailOverlayLocationIcon.none, + ); + } +} + +class SettingsTileThumbnailTagIcon extends SettingsTile { + @override + String title(BuildContext context) => context.l10n.settingsThumbnailShowTagIcon; + + @override + Widget build(BuildContext context) => SettingsSelectionListTile<ThumbnailOverlayTagIcon>( + values: ThumbnailOverlayTagIcon.values, + getName: (context, v) => v.getName(context), + selector: (context, s) => s.thumbnailTagIcon, + onSelection: (v) => settings.thumbnailTagIcon = v, + tileTitle: title(context), + trailingBuilder: _buildTrailing, + ); + + Widget _buildTrailing(BuildContext context) { + final iconType = context.select<Settings, ThumbnailOverlayTagIcon>((v) => v.thumbnailTagIcon); + return SettingSwitchTrailingIcon( + key: ValueKey(iconType), + icon: iconType.getIcon(context), + disabled: iconType == ThumbnailOverlayTagIcon.none, + ); + } +} diff --git a/lib/widgets/settings/thumbnails/thumbnails.dart b/lib/widgets/settings/thumbnails/thumbnails.dart new file mode 100644 index 0000000..361b41b --- /dev/null +++ b/lib/widgets/settings/thumbnails/thumbnails.dart @@ -0,0 +1,74 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/ref/bursts.dart'; +import 'package:aves/theme/colors.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/settings/common/tile_leading.dart'; +import 'package:aves/widgets/settings/common/tiles.dart'; +import 'package:aves/widgets/settings/settings_definition.dart'; +import 'package:aves/widgets/settings/thumbnails/collection_actions_editor_page.dart'; +import 'package:aves/widgets/settings/thumbnails/overlay.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class ThumbnailsSection extends SettingsSection { + @override + String get key => 'thumbnails'; + + @override + Widget icon(BuildContext context) => SettingsTileLeading( + icon: AIcons.thumbnails, + color: context.select<AvesColorsData, Color>((v) => v.thumbnails), + ); + + @override + String title(BuildContext context) => context.l10n.settingsThumbnailSectionTitle; + + @override + List<SettingsTile> tiles(BuildContext context) => [ + if (!settings.useTvLayout) SettingsTileCollectionQuickActions(), + SettingsTileThumbnailOverlay(), + SettingsTileBurstPatterns(), + ]; +} + +class SettingsTileCollectionQuickActions extends SettingsTile { + @override + String title(BuildContext context) => context.l10n.settingsCollectionQuickActionsTile; + + @override + Widget build(BuildContext context) => SettingsSubPageTile( + title: title(context), + routeName: CollectionActionEditorPage.routeName, + builder: (context) => const CollectionActionEditorPage(), + ); +} + +class SettingsTileThumbnailOverlay extends SettingsTile { + @override + String title(BuildContext context) => context.l10n.settingsThumbnailOverlayTile; + + @override + Widget build(BuildContext context) => SettingsSubPageTile( + title: title(context), + routeName: ThumbnailOverlayPage.routeName, + builder: (context) => const ThumbnailOverlayPage(), + ); +} + +class SettingsTileBurstPatterns extends SettingsTile { + @override + String title(BuildContext context) => context.l10n.settingsCollectionBurstPatternsTile; + + @override + Widget build(BuildContext context) => SettingsMultiSelectionListTile<String>( + values: BurstPatterns.options, + getName: (context, v) => BurstPatterns.getName(v), + selector: (context, s) => s.collectionBurstPatterns, + onSelection: (v) => settings.collectionBurstPatterns = v, + tileTitle: title(context), + noneSubtitle: context.l10n.settingsCollectionBurstPatternsNone, + optionSubtitleBuilder: (value) => '${Unicode.FSI}${BurstPatterns.getExample(value)}${Unicode.PDI}', + ); +} diff --git a/lib/widgets/settings/video/control_actions.dart b/lib/widgets/settings/video/control_actions.dart new file mode 100644 index 0000000..62dbb20 --- /dev/null +++ b/lib/widgets/settings/video/control_actions.dart @@ -0,0 +1,70 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/buttons/overlay_button.dart'; +import 'package:aves/widgets/settings/common/quick_actions/action_panel.dart'; +import 'package:aves/widgets/viewer/overlay/video/controls.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class VideoControlButtonsPage extends StatelessWidget { + static const routeName = '/settings/video/control_buttons'; + static const _availableActions = [...EntryActions.videoPlayback, EntryAction.openVideoPlayer]; + + const VideoControlButtonsPage({super.key}); + + @override + Widget build(BuildContext context) { + return AvesScaffold( + appBar: AppBar( + automaticallyImplyLeading: !settings.useTvLayout, + title: Text(context.l10n.settingsVideoButtonsTile), + ), + body: SafeArea( + child: Selector<Settings, List<EntryAction>>( + selector: (context, s) => s.videoControlActions, + builder: (context, selectedActionList, child) { + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + ActionPanel( + child: Container( + alignment: AlignmentDirectional.center, + height: OverlayButton.getSize(context) + 48, + child: selectedActionList.isNotEmpty + ? VideoControlRow(onActionSelected: (_) {}) + : Text( + context.l10n.settingsViewerQuickActionEmpty, + style: Theme.of(context).textTheme.bodySmall, + ), + ), + ), + Expanded( + child: ListView( + children: _availableActions.map((action) { + return SwitchListTile( + value: selectedActionList.contains(action), + onChanged: (v) { + final selectedActionSet = settings.videoControlActions.toSet(); + if (v) { + selectedActionSet.add(action); + } else { + selectedActionSet.remove(action); + } + settings.videoControlActions = _availableActions.where(selectedActionSet.contains).toList(); + }, + title: Text(action.getText(context)), + ); + }).toList(), + ), + ), + ], + ); + }, + ), + ), + ); + } +} diff --git a/lib/widgets/settings/video/controls.dart b/lib/widgets/settings/video/controls.dart new file mode 100644 index 0000000..da1ceee --- /dev/null +++ b/lib/widgets/settings/video/controls.dart @@ -0,0 +1,47 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/settings/common/tiles.dart'; +import 'package:aves/widgets/settings/video/control_actions.dart'; +import 'package:flutter/material.dart'; + +class VideoControlsPage extends StatelessWidget { + static const routeName = '/settings/video/controls'; + + const VideoControlsPage({super.key}); + + @override + Widget build(BuildContext context) { + return AvesScaffold( + appBar: AppBar( + title: Text(context.l10n.settingsVideoControlsPageTitle), + ), + body: SafeArea( + child: ListView( + children: [ + SettingsSubPageTile( + title: context.l10n.settingsVideoButtonsTile, + routeName: VideoControlButtonsPage.routeName, + builder: (context) => const VideoControlButtonsPage(), + ), + SettingsSwitchListTile( + selector: (context, s) => s.videoGestureDoubleTapTogglePlay, + onChanged: (v) => settings.videoGestureDoubleTapTogglePlay = v, + title: context.l10n.settingsVideoGestureDoubleTapTogglePlay, + ), + SettingsSwitchListTile( + selector: (context, s) => s.videoGestureSideDoubleTapSeek, + onChanged: (v) => settings.videoGestureSideDoubleTapSeek = v, + title: context.l10n.settingsVideoGestureSideDoubleTapSeek, + ), + SettingsSwitchListTile( + selector: (context, s) => s.videoGestureVerticalDragBrightnessVolume, + onChanged: (v) => settings.videoGestureVerticalDragBrightnessVolume = v, + title: context.l10n.settingsVideoGestureVerticalDragBrightnessVolume, + ), + ], + ), + ), + ); + } +} diff --git a/lib/widgets/settings/video/playback.dart b/lib/widgets/settings/video/playback.dart new file mode 100644 index 0000000..4d82ac0 --- /dev/null +++ b/lib/widgets/settings/video/playback.dart @@ -0,0 +1,66 @@ +import 'package:aves/model/device.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/settings/common/tiles.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; + +class VideoPlaybackPage extends StatelessWidget { + static const routeName = '/settings/video/playback'; + + const VideoPlaybackPage({super.key}); + + @override + Widget build(BuildContext context) { + return AvesScaffold( + appBar: AppBar( + title: Text(context.l10n.settingsVideoPlaybackPageTitle), + ), + body: SafeArea( + child: ListView( + children: [ + SettingsSwitchListTile( + selector: (context, s) => s.enableVideoHardwareAcceleration, + onChanged: (v) => settings.enableVideoHardwareAcceleration = v, + title: context.l10n.settingsVideoEnableHardwareAcceleration, + ), + SettingsSelectionListTile<VideoAutoPlayMode>( + values: VideoAutoPlayMode.values, + getName: (context, v) => v.getName(context), + selector: (context, s) => s.videoAutoPlayMode, + onSelection: (v) => settings.videoAutoPlayMode = v, + tileTitle: context.l10n.settingsVideoAutoPlay, + ), + SettingsSelectionListTile<VideoLoopMode>( + values: VideoLoopMode.values, + getName: (context, v) => v.getName(context), + selector: (context, s) => s.videoLoopMode, + onSelection: (v) => settings.videoLoopMode = v, + tileTitle: context.l10n.settingsVideoLoopModeTile, + dialogTitle: context.l10n.settingsVideoLoopModeDialogTitle, + ), + SettingsSelectionListTile<VideoResumptionMode>( + values: VideoResumptionMode.values, + getName: (context, v) => v.getName(context), + selector: (context, s) => s.videoResumptionMode, + onSelection: (v) => settings.videoResumptionMode = v, + tileTitle: context.l10n.settingsVideoResumptionModeTile, + dialogTitle: context.l10n.settingsVideoResumptionModeDialogTitle, + ), + if (!settings.useTvLayout && device.supportPictureInPicture) + SettingsSelectionListTile<VideoBackgroundMode>( + values: VideoBackgroundMode.values, + getName: (context, v) => v.getName(context), + selector: (context, s) => s.videoBackgroundMode, + onSelection: (v) => settings.videoBackgroundMode = v, + tileTitle: context.l10n.settingsVideoBackgroundMode, + dialogTitle: context.l10n.settingsVideoBackgroundModeDialogTitle, + ), + ], + ), + ), + ); + } +} diff --git a/lib/widgets/settings/video/subtitle_sample.dart b/lib/widgets/settings/video/subtitle_sample.dart new file mode 100644 index 0000000..89d4f7a --- /dev/null +++ b/lib/widgets/settings/video/subtitle_sample.dart @@ -0,0 +1,104 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/colors.dart'; +import 'package:aves/widgets/common/basic/text/background_painter.dart'; +import 'package:aves/widgets/common/basic/text/outlined.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/fx/borders.dart'; +import 'package:aves/widgets/viewer/visual/video/subtitle/subtitle.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class SubtitleSample extends StatelessWidget { + const SubtitleSample({super.key}); + + @override + Widget build(BuildContext context) { + final textSpans = [ + TextSpan(text: context.l10n.settingsSubtitleThemeSample), + ]; + + return Consumer<Settings>( + builder: (context, settings, child) { + final textAlign = settings.subtitleTextAlignment; + final textPosition = settings.subtitleTextPosition; + final outlineColor = Colors.black.withValues(alpha: settings.subtitleTextColor.a); + final shadows = [ + Shadow( + color: outlineColor, + offset: VideoSubtitles.baseShadowOffset, + ), + ]; + + return Container( + decoration: BoxDecoration( + gradient: const LinearGradient( + begin: AlignmentDirectional.bottomStart, + end: AlignmentDirectional.topEnd, + colors: AColors.boraBoraGradient, + ), + border: AvesBorder.border(context), + borderRadius: const BorderRadius.all(Radius.circular(24)), + ), + height: 128, + child: AnimatedAlign( + alignment: _getAlignment(textAlign, textPosition), + curve: Curves.easeInOutCubic, + duration: const Duration(milliseconds: 400), + child: Padding( + padding: const EdgeInsets.all(16), + child: AnimatedDefaultTextStyle( + style: TextStyle( + color: settings.subtitleTextColor, + fontSize: settings.subtitleFontSize, + shadows: settings.subtitleShowOutline ? shadows : null, + ), + textAlign: textAlign, + duration: const Duration(milliseconds: 200), + child: Builder( + builder: (context) => TextBackgroundPainter( + spans: textSpans, + style: DefaultTextStyle.of(context).style.copyWith( + backgroundColor: settings.subtitleBackgroundColor, + ), + textAlign: textAlign, + child: OutlinedText( + textSpans: textSpans, + outlineWidth: settings.subtitleShowOutline ? 1 : 0, + outlineColor: outlineColor, + ), + ), + ), + ), + ), + ), + ); + }, + ); + } + + Alignment _getAlignment(TextAlign textAlign, SubtitlePosition textPosition) { + switch (textPosition) { + case SubtitlePosition.top: + switch (textAlign) { + case TextAlign.left: + return Alignment.topLeft; + case TextAlign.right: + return Alignment.topRight; + case TextAlign.center: + default: + return Alignment.topCenter; + } + case SubtitlePosition.bottom: + switch (textAlign) { + case TextAlign.left: + return Alignment.bottomLeft; + case TextAlign.right: + return Alignment.bottomRight; + case TextAlign.center: + default: + return Alignment.bottomCenter; + } + } + } +} diff --git a/lib/widgets/settings/video/subtitle_theme.dart b/lib/widgets/settings/video/subtitle_theme.dart new file mode 100644 index 0000000..a68447d --- /dev/null +++ b/lib/widgets/settings/video/subtitle_theme.dart @@ -0,0 +1,108 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/basic/list_tiles/color.dart'; +import 'package:aves/widgets/common/basic/list_tiles/slider.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/settings/common/tiles.dart'; +import 'package:aves/widgets/settings/video/subtitle_sample.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class SubtitleThemePage extends StatelessWidget { + static const routeName = '/settings/video/subtitle_theme'; + + const SubtitleThemePage({super.key}); + + @override + Widget build(BuildContext context) { + return AvesScaffold( + appBar: AppBar( + automaticallyImplyLeading: !settings.useTvLayout, + title: Text(context.l10n.settingsSubtitleThemePageTitle), + ), + body: SafeArea( + child: Consumer<Settings>( + builder: (context, settings, child) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Padding( + padding: EdgeInsets.all(16), + child: SubtitleSample(), + ), + const Divider(height: 0), + Expanded( + child: ListView( + children: [ + SettingsSelectionListTile<TextAlign>( + values: const [TextAlign.left, TextAlign.center, TextAlign.right], + getName: _getTextAlignName, + selector: (context, s) => s.subtitleTextAlignment, + onSelection: (v) => settings.subtitleTextAlignment = v, + tileTitle: context.l10n.settingsSubtitleThemeTextAlignmentTile, + dialogTitle: context.l10n.settingsSubtitleThemeTextAlignmentDialogTitle, + ), + SettingsSelectionListTile<SubtitlePosition>( + values: const [SubtitlePosition.top, SubtitlePosition.bottom], + getName: (context, v) => v.getName(context), + selector: (context, s) => s.subtitleTextPosition, + onSelection: (v) => settings.subtitleTextPosition = v, + tileTitle: context.l10n.settingsSubtitleThemeTextPositionTile, + dialogTitle: context.l10n.settingsSubtitleThemeTextPositionDialogTitle, + ), + SliderListTile( + title: context.l10n.settingsSubtitleThemeTextSize, + value: settings.subtitleFontSize, + onChanged: (v) => settings.subtitleFontSize = v, + min: 10, + max: 40, + divisions: 6, + ), + ColorListTile( + title: context.l10n.settingsSubtitleThemeTextColor, + value: settings.subtitleTextColor.withValues(alpha: 1), + onChanged: (v) => settings.subtitleTextColor = v.withValues(alpha: settings.subtitleTextColor.a), + ), + SliderListTile( + title: context.l10n.settingsSubtitleThemeTextOpacity, + value: settings.subtitleTextColor.a, + onChanged: (v) => settings.subtitleTextColor = settings.subtitleTextColor.withValues(alpha: v), + ), + ColorListTile( + title: context.l10n.settingsSubtitleThemeBackgroundColor, + value: settings.subtitleBackgroundColor.withValues(alpha: 1), + onChanged: (v) => settings.subtitleBackgroundColor = v.withValues(alpha: settings.subtitleBackgroundColor.a), + ), + SliderListTile( + title: context.l10n.settingsSubtitleThemeBackgroundOpacity, + value: settings.subtitleBackgroundColor.a, + onChanged: (v) => settings.subtitleBackgroundColor = settings.subtitleBackgroundColor.withValues(alpha: v), + ), + SettingsSwitchListTile( + selector: (context, s) => s.subtitleShowOutline, + onChanged: (v) => settings.subtitleShowOutline = v, + title: context.l10n.settingsSubtitleThemeShowOutline, + ), + ], + ), + ), + ], + ); + }, + ), + ), + ); + } + + String _getTextAlignName(BuildContext context, TextAlign align) { + final l10n = context.l10n; + return switch (align) { + TextAlign.left => l10n.settingsSubtitleThemeTextAlignmentLeft, + TextAlign.center => l10n.settingsSubtitleThemeTextAlignmentCenter, + TextAlign.right => l10n.settingsSubtitleThemeTextAlignmentRight, + _ => '', + }; + } +} diff --git a/lib/widgets/settings/video/video.dart b/lib/widgets/settings/video/video.dart new file mode 100644 index 0000000..6c06037 --- /dev/null +++ b/lib/widgets/settings/video/video.dart @@ -0,0 +1,93 @@ +import 'dart:async'; + +import 'package:aves/model/filters/mime.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/colors.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/settings/common/tile_leading.dart'; +import 'package:aves/widgets/settings/common/tiles.dart'; +import 'package:aves/widgets/settings/settings_definition.dart'; +import 'package:aves/widgets/settings/video/controls.dart'; +import 'package:aves/widgets/settings/video/playback.dart'; +import 'package:aves/widgets/settings/video/subtitle_theme.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class VideoSection extends SettingsSection { + final bool standalonePage; + + VideoSection({ + this.standalonePage = false, + }); + + @override + String get key => 'video'; + + @override + Widget icon(BuildContext context) => SettingsTileLeading( + icon: AIcons.video, + color: context.select<AvesColorsData, Color>((v) => v.video), + ); + + @override + String title(BuildContext context) => context.l10n.settingsVideoSectionTitle; + + @override + FutureOr<List<SettingsTile>> tiles(BuildContext context) async { + return [ + if (!standalonePage) SettingsTileVideoShowVideos(), + SettingsTileVideoPlayback(), + if (!settings.useTvLayout) SettingsTileVideoControls(), + SettingsTileVideoSubtitleTheme(), + ]; + } +} + +class SettingsTileVideoShowVideos extends SettingsTile { + @override + String title(BuildContext context) => context.l10n.settingsVideoShowVideos; + + @override + Widget build(BuildContext context) => SettingsSwitchListTile( + selector: (context, s) => !s.hiddenFilters.contains(MimeFilter.video), + onChanged: (v) => settings.changeFilterVisibility({MimeFilter.video}, v), + title: title(context), + ); +} + +class SettingsTileVideoPlayback extends SettingsTile { + @override + String title(BuildContext context) => context.l10n.settingsVideoPlaybackTile; + + @override + Widget build(BuildContext context) => SettingsSubPageTile( + title: title(context), + routeName: VideoPlaybackPage.routeName, + builder: (context) => const VideoPlaybackPage(), + ); +} + +class SettingsTileVideoControls extends SettingsTile { + @override + String title(BuildContext context) => context.l10n.settingsVideoControlsTile; + + @override + Widget build(BuildContext context) => SettingsSubPageTile( + title: title(context), + routeName: VideoControlsPage.routeName, + builder: (context) => const VideoControlsPage(), + ); +} + +class SettingsTileVideoSubtitleTheme extends SettingsTile { + @override + String title(BuildContext context) => context.l10n.settingsSubtitleThemeTile; + + @override + Widget build(BuildContext context) => SettingsSubPageTile( + title: title(context), + routeName: SubtitleThemePage.routeName, + builder: (context) => const SubtitleThemePage(), + ); +} diff --git a/lib/widgets/settings/video/video_settings_page.dart b/lib/widgets/settings/video/video_settings_page.dart new file mode 100644 index 0000000..5343960 --- /dev/null +++ b/lib/widgets/settings/video/video_settings_page.dart @@ -0,0 +1,51 @@ +import 'dart:async'; + +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/settings/settings_definition.dart'; +import 'package:aves/widgets/settings/video/video.dart'; +import 'package:flutter/material.dart'; + +class VideoSettingsPage extends StatefulWidget { + static const routeName = '/settings/video'; + + const VideoSettingsPage({super.key}); + + @override + State<VideoSettingsPage> createState() => _VideoSettingsPageState(); +} + +class _VideoSettingsPageState extends State<VideoSettingsPage> { + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return AvesScaffold( + appBar: AppBar( + automaticallyImplyLeading: !settings.useTvLayout, + title: Text(context.l10n.settingsVideoPageTitle), + ), + body: Theme( + data: theme.copyWith( + textTheme: theme.textTheme.copyWith( + // dense style font for tile subtitles, without modifying title font + bodyMedium: const TextStyle(fontSize: 12), + ), + ), + child: SafeArea( + child: FutureBuilder<List<SettingsTile>>( + future: Future.value(VideoSection(standalonePage: true).tiles(context)), + builder: (context, snapshot) { + final tiles = snapshot.data; + if (tiles == null) return const SizedBox(); + + return ListView( + children: tiles.map((v) => v.build(context)).toList(), + ); + }, + ), + ), + ), + ); + } +} diff --git a/lib/widgets/settings/viewer/entry_background.dart b/lib/widgets/settings/viewer/entry_background.dart new file mode 100644 index 0000000..53a3a0b --- /dev/null +++ b/lib/widgets/settings/viewer/entry_background.dart @@ -0,0 +1,61 @@ +import 'package:aves/model/settings/enums/entry_background.dart'; +import 'package:aves/widgets/common/basic/color_indicator.dart'; +import 'package:aves/widgets/common/fx/checkered_decoration.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; + +class EntryBackgroundSelector extends StatefulWidget { + final ValueGetter<EntryBackground> getter; + final ValueSetter<EntryBackground> setter; + + const EntryBackgroundSelector({ + super.key, + required this.getter, + required this.setter, + }); + + @override + State<EntryBackgroundSelector> createState() => _EntryBackgroundSelectorState(); +} + +class _EntryBackgroundSelectorState extends State<EntryBackgroundSelector> { + @override + Widget build(BuildContext context) { + return DropdownButtonHideUnderline( + child: DropdownButton<EntryBackground>( + items: _buildItems(context), + value: widget.getter(), + onChanged: (selected) { + if (selected != null) { + widget.setter(selected); + setState(() {}); + } + }, + ), + ); + } + + List<DropdownMenuItem<EntryBackground>> _buildItems(BuildContext context) { + return [ + EntryBackground.white, + EntryBackground.black, + EntryBackground.checkered, + ].map((selected) { + return DropdownMenuItem<EntryBackground>( + value: selected, + child: ColorIndicator( + value: selected.isColor ? selected.color : null, + child: selected == EntryBackground.checkered + ? ClipOval( + child: CustomPaint( + painter: CheckeredPainter( + checkSize: ColorIndicator.radius, + ), + ), + ) + : null, + ), + ); + }).toList(); + } +} diff --git a/lib/widgets/settings/viewer/overlay.dart b/lib/widgets/settings/viewer/overlay.dart new file mode 100644 index 0000000..ba133c1 --- /dev/null +++ b/lib/widgets/settings/viewer/overlay.dart @@ -0,0 +1,125 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/settings/common/switch_icon.dart'; +import 'package:aves/widgets/settings/common/tiles.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class ViewerOverlayPage extends StatelessWidget { + static const routeName = '/settings/viewer/overlay'; + + const ViewerOverlayPage({super.key}); + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + final useTvLayout = settings.useTvLayout; + + Widget _trailingIcon(BuildContext context, IconData data) => Icon( + data, + size: SettingSwitchTrailingIcon.getIconSize(context), + color: SettingSwitchTrailingIcon.getIconColor(context), + ); + + return AvesScaffold( + appBar: AppBar( + automaticallyImplyLeading: !useTvLayout, + title: Text(l10n.settingsViewerOverlayPageTitle), + ), + body: SafeArea( + child: ListView( + children: [ + if (!useTvLayout) ...[ + SettingsSwitchListTile( + selector: (context, s) => s.showOverlayOnOpening, + onChanged: (v) => settings.showOverlayOnOpening = v, + title: l10n.settingsViewerShowOverlayOnOpening, + ), + const Divider(height: 32), + ], + SettingsSwitchListTile( + selector: (context, s) => s.showOverlayInfo, + onChanged: (v) => settings.showOverlayInfo = v, + title: l10n.settingsViewerShowInformation, + subtitle: l10n.settingsViewerShowInformationSubtitle, + ), + Selector<Settings, bool>( + selector: (context, s) => s.showOverlayInfo, + builder: (context, showInfo, child) { + return SettingsSwitchListTile( + selector: (context, s) => s.showOverlayShootingDetails, + onChanged: showInfo ? (v) => settings.showOverlayShootingDetails = v : null, + title: l10n.settingsViewerShowShootingDetails, + trailing: _trailingIcon(context, AIcons.shooting), + ); + }, + ), + Selector<Settings, bool>( + selector: (context, s) => s.showOverlayInfo, + builder: (context, showInfo, child) { + return SettingsSwitchListTile( + selector: (context, s) => s.showOverlayRatingTags, + onChanged: showInfo ? (v) => settings.showOverlayRatingTags = v : null, + title: l10n.settingsViewerShowRatingTags, + trailing: _trailingIcon(context, AIcons.tag), + ); + }, + ), + Selector<Settings, bool>( + selector: (context, s) => s.showOverlayInfo, + builder: (context, showInfo, child) { + return SettingsSwitchListTile( + selector: (context, s) => s.showOverlayDescription, + onChanged: showInfo ? (v) => settings.showOverlayDescription = v : null, + title: l10n.settingsViewerShowDescription, + trailing: _trailingIcon(context, AIcons.description), + ); + }, + ), + if (!useTvLayout) ...[ + const Divider(height: 32), + SettingsSwitchListTile( + selector: (context, s) => s.showOverlayZoomLevel, + onChanged: (v) => settings.showOverlayZoomLevel = v, + title: l10n.settingsViewerShowZoomLevel, + trailing: _trailingIcon(context, AIcons.zoomLevel), + ), + SettingsSwitchListTile( + selector: (context, s) => s.showOverlayMinimap, + onChanged: (v) => settings.showOverlayMinimap = v, + title: l10n.settingsViewerShowMinimap, + trailing: _trailingIcon(context, AIcons.minimap), + ), + SettingsSelectionListTile<OverlayHistogramStyle>( + values: OverlayHistogramStyle.values, + getName: (context, v) => v.getName(context), + selector: (context, s) => s.overlayHistogramStyle, + onSelection: (v) => settings.overlayHistogramStyle = v, + tileTitle: l10n.settingsViewerShowHistogram, + trailingBuilder: (context) { + final style = context.select<Settings, OverlayHistogramStyle>((v) => v.overlayHistogramStyle); + return SettingSwitchTrailingIcon( + key: ValueKey(style), + icon: AIcons.histogram, + disabled: style == OverlayHistogramStyle.none, + ); + }, + ), + const Divider(height: 32), + SettingsSwitchListTile( + selector: (context, s) => s.showOverlayThumbnailPreview, + onChanged: (v) => settings.showOverlayThumbnailPreview = v, + title: l10n.settingsViewerShowOverlayThumbnails, + trailing: _trailingIcon(context, AIcons.thumbnailBar), + ), + ], + ], + ), + ), + ); + } +} diff --git a/lib/widgets/settings/viewer/slideshow.dart b/lib/widgets/settings/viewer/slideshow.dart new file mode 100644 index 0000000..7a9294d --- /dev/null +++ b/lib/widgets/settings/viewer/slideshow.dart @@ -0,0 +1,70 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/settings/common/tiles.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; + +class ViewerSlideshowPage extends StatelessWidget { + static const routeName = '/settings/viewer/slideshow'; + + const ViewerSlideshowPage({super.key}); + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + return AvesScaffold( + appBar: AppBar( + automaticallyImplyLeading: !settings.useTvLayout, + title: Text(l10n.settingsViewerSlideshowPageTitle), + ), + body: SafeArea( + child: ListView( + children: [ + SettingsSwitchListTile( + selector: (context, s) => s.slideshowRepeat, + onChanged: (v) => settings.slideshowRepeat = v, + title: l10n.settingsSlideshowRepeat, + ), + SettingsSwitchListTile( + selector: (context, s) => s.slideshowShuffle, + onChanged: (v) => settings.slideshowShuffle = v, + title: l10n.settingsSlideshowShuffle, + ), + SettingsSwitchListTile( + selector: (context, s) => s.slideshowFillScreen, + onChanged: (v) => settings.slideshowFillScreen = v, + title: l10n.settingsSlideshowFillScreen, + ), + SettingsSwitchListTile( + selector: (context, s) => s.slideshowAnimatedZoomEffect, + onChanged: (v) => settings.slideshowAnimatedZoomEffect = v, + title: l10n.settingsSlideshowAnimatedZoomEffect, + ), + SettingsSelectionListTile<ViewerTransition>( + values: ViewerTransition.values, + getName: (context, v) => v.getName(context), + selector: (context, s) => s.slideshowTransition, + onSelection: (v) => settings.slideshowTransition = v, + tileTitle: l10n.settingsSlideshowTransitionTile, + ), + SettingsDurationListTile( + selector: (context, s) => s.slideshowInterval, + onChanged: (v) => settings.slideshowInterval = v, + title: l10n.settingsSlideshowIntervalTile, + ), + SettingsSelectionListTile<SlideshowVideoPlayback>( + values: SlideshowVideoPlayback.values, + getName: (context, v) => v.getName(context), + selector: (context, s) => s.slideshowVideoPlayback, + onSelection: (v) => settings.slideshowVideoPlayback = v, + tileTitle: l10n.settingsSlideshowVideoPlaybackTile, + dialogTitle: l10n.settingsSlideshowVideoPlaybackDialogTitle, + ), + ], + ), + ), + ); + } +} diff --git a/lib/widgets/settings/viewer/viewer.dart b/lib/widgets/settings/viewer/viewer.dart new file mode 100644 index 0000000..c2e7525 --- /dev/null +++ b/lib/widgets/settings/viewer/viewer.dart @@ -0,0 +1,134 @@ +import 'dart:async'; + +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/theme/colors.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/settings/common/tile_leading.dart'; +import 'package:aves/widgets/settings/common/tiles.dart'; +import 'package:aves/widgets/settings/settings_definition.dart'; +import 'package:aves/widgets/settings/viewer/entry_background.dart'; +import 'package:aves/widgets/settings/viewer/overlay.dart'; +import 'package:aves/widgets/settings/viewer/slideshow.dart'; +import 'package:aves/widgets/settings/viewer/viewer_actions_editor.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class ViewerSection extends SettingsSection { + @override + String get key => 'viewer'; + + @override + Widget icon(BuildContext context) => SettingsTileLeading( + icon: AIcons.image, + color: context.select<AvesColorsData, Color>((v) => v.image), + ); + + @override + String title(BuildContext context) => context.l10n.settingsViewerSectionTitle; + + @override + FutureOr<List<SettingsTile>> tiles(BuildContext context) async { + final isCutoutAware = await windowService.isCutoutAware(); + return [ + if (!settings.useTvLayout) SettingsTileViewerQuickActions(), + SettingsTileViewerOverlay(), + SettingsTileViewerSlideshow(), + if (!settings.useTvLayout) SettingsTileViewerGestureSideTapNext(), + if (!settings.useTvLayout && isCutoutAware) SettingsTileViewerUseCutout(), + SettingsTileViewerMotionPhotoAutoPlay(), + SettingsTileViewerImageBackground(), + ]; + } +} + +class SettingsTileViewerQuickActions extends SettingsTile { + @override + String title(BuildContext context) => context.l10n.settingsViewerQuickActionsTile; + + @override + Widget build(BuildContext context) => SettingsSubPageTile( + title: title(context), + routeName: ViewerActionEditorPage.routeName, + builder: (context) => const ViewerActionEditorPage(), + ); +} + +class SettingsTileViewerOverlay extends SettingsTile { + @override + String title(BuildContext context) => context.l10n.settingsViewerOverlayTile; + + @override + Widget build(BuildContext context) => SettingsSubPageTile( + title: title(context), + routeName: ViewerOverlayPage.routeName, + builder: (context) => const ViewerOverlayPage(), + ); +} + +class SettingsTileViewerSlideshow extends SettingsTile { + @override + String title(BuildContext context) => context.l10n.settingsViewerSlideshowTile; + + @override + Widget build(BuildContext context) => SettingsSubPageTile( + title: title(context), + routeName: ViewerSlideshowPage.routeName, + builder: (context) => const ViewerSlideshowPage(), + ); +} + +class SettingsTileViewerGestureSideTapNext extends SettingsTile { + @override + String title(BuildContext context) => context.l10n.settingsViewerGestureSideTapNext; + + @override + Widget build(BuildContext context) => SettingsSwitchListTile( + selector: (context, s) => s.viewerGestureSideTapNext, + onChanged: (v) => settings.viewerGestureSideTapNext = v, + title: title(context), + ); +} + +class SettingsTileViewerUseCutout extends SettingsTile { + @override + String title(BuildContext context) => context.l10n.settingsViewerUseCutout; + + @override + Widget build(BuildContext context) => SettingsSwitchListTile( + selector: (context, s) => s.viewerUseCutout, + onChanged: (v) => settings.viewerUseCutout = v, + title: title(context), + ); +} + +class SettingsTileViewerMotionPhotoAutoPlay extends SettingsTile { + @override + String title(BuildContext context) => context.l10n.settingsMotionPhotoAutoPlay; + + @override + Widget build(BuildContext context) => SettingsSwitchListTile( + selector: (context, s) => s.enableMotionPhotoAutoPlay, + onChanged: (v) => settings.enableMotionPhotoAutoPlay = v, + title: title(context), + ); +} + +class SettingsTileViewerImageBackground extends SettingsTile { + @override + String title(BuildContext context) => context.l10n.settingsImageBackground; + + @override + Widget build(BuildContext context) => Selector<Settings, EntryBackground>( + selector: (context, s) => s.imageBackground, + builder: (context, current, child) => ListTile( + title: Text(title(context)), + trailing: EntryBackgroundSelector( + getter: () => current, + setter: (value) => settings.imageBackground = value, + ), + ), + ); +} diff --git a/lib/widgets/settings/viewer/viewer_actions_editor.dart b/lib/widgets/settings/viewer/viewer_actions_editor.dart new file mode 100644 index 0000000..4871082 --- /dev/null +++ b/lib/widgets/settings/viewer/viewer_actions_editor.dart @@ -0,0 +1,73 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/settings/common/quick_actions/editor_page.dart'; +import 'package:aves/widgets/viewer/overlay/bottom.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; + +class ViewerActionEditorPage extends StatefulWidget { + static const routeName = '/settings/viewer/actions'; + + const ViewerActionEditorPage({super.key}); + + @override + State<ViewerActionEditorPage> createState() => _ViewerActionEditorPageState(); +} + +class _ViewerActionEditorPageState extends State<ViewerActionEditorPage> { + late final QuickActionEditorController<EntryAction> _controller; + + static final allAvailableActions = [ + [ + EntryAction.share, + EntryAction.edit, + EntryAction.rename, + EntryAction.delete, + EntryAction.copy, + EntryAction.move, + EntryAction.toggleFavourite, + EntryAction.rotateScreen, + EntryAction.viewSource, + EntryAction.rotateCCW, + EntryAction.rotateCW, + EntryAction.flip, + ], + [ + ...EntryActions.export, + ], + [ + ...EntryActions.video.whereNot((v) => v == EntryAction.videoSettings), + ], + EntryActions.commonMetadataActions, + ]; + + @override + void initState() { + super.initState(); + _controller = QuickActionEditorController( + load: () => settings.viewerQuickActions, + save: (actions) => settings.viewerQuickActions = actions, + ); + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return QuickActionEditorPage<EntryAction>( + title: context.l10n.settingsViewerQuickActionEditorPageTitle, + bannerText: context.l10n.settingsViewerQuickActionEditorBanner, + displayedButtonsDirection: ViewerBottomOverlay.actionsDirection, + allAvailableActions: allAvailableActions, + actionIcon: (context, action) => action.getIcon(), + actionText: (context, action) => action.getText(context), + controller: _controller, + ); + } +} diff --git a/lib/widgets/stats/date/axis.dart b/lib/widgets/stats/date/axis.dart new file mode 100644 index 0000000..01bca20 --- /dev/null +++ b/lib/widgets/stats/date/axis.dart @@ -0,0 +1,97 @@ +import 'dart:math'; + +import 'package:aves/model/filters/date.dart'; +import 'package:aves/utils/time_utils.dart'; +import 'package:charts_flutter/flutter.dart' as charts; +import 'package:intl/intl.dart'; + +// cf charts.DateTimeTickFormatter factory internals for default formats +class TimeAxisSpec { + final List<charts.TickSpec<DateTime>> tickSpecs; + + TimeAxisSpec(this.tickSpecs); + + factory TimeAxisSpec.forLevel({ + required String locale, + required DateLevel level, + required DateTime first, + required DateTime last, + }) { + switch (level) { + case DateLevel.ymd: + return TimeAxisSpec.days(locale, first, last); + case DateLevel.ym: + return TimeAxisSpec.months(locale, first, last); + case DateLevel.y: + default: + return TimeAxisSpec.years(locale, first, last); + } + } + + factory TimeAxisSpec.days(String locale, DateTime first, DateTime last) { + final daysTickLongFormat = DateFormat.MMMd(locale); + final daysTickShortFormat = DateFormat.d(locale); + + first = first.date; + last = last.date; + final rangeDays = last.difference(first).inHumanDays; + final delta = max(1, (rangeDays / 5).ceil()); + + List<charts.TickSpec<DateTime>> ticks = []; + int lastContext = -1; + DateFormat dateFormat; + for (int i = 0; i < rangeDays; i += delta) { + final tickDate = first.addDays(i); + if (lastContext != tickDate.month) { + lastContext = tickDate.month; + dateFormat = daysTickLongFormat; + } else { + dateFormat = daysTickShortFormat; + } + ticks.add(charts.TickSpec<DateTime>(tickDate, label: dateFormat.format(tickDate))); + } + return TimeAxisSpec(ticks); + } + + factory TimeAxisSpec.months(String locale, DateTime first, DateTime last) { + final monthsTickLongFormat = DateFormat.yMMM(locale); + final monthsTickShortFormat = DateFormat.MMM(locale); + + first = DateTime(first.year, first.month); + last = DateTime(last.year, last.month); + final rangeMonths = last.month - first.month + (last.month < first.month ? 12 : 0); + if (rangeMonths < 12) { + first = first.addMonths(-((12 - rangeMonths) / 2).floor()); + } + + List<charts.TickSpec<DateTime>> ticks = []; + int lastContext = -1; + DateFormat dateFormat; + for (int i = 0; i < DateTime.monthsPerYear; i += 3) { + final tickDate = first.addMonths(2 + i); + if (lastContext != tickDate.year) { + lastContext = tickDate.year; + dateFormat = monthsTickLongFormat; + } else { + dateFormat = monthsTickShortFormat; + } + ticks.add(charts.TickSpec<DateTime>(tickDate, label: dateFormat.format(tickDate))); + } + return TimeAxisSpec(ticks); + } + + factory TimeAxisSpec.years(String locale, DateTime first, DateTime last) { + final dateFormat = DateFormat.y(locale); + + final firstYear = first.year; + final lastYear = last.year; + final delta = max(1, ((lastYear - firstYear) / 5).ceil()); + + List<charts.TickSpec<DateTime>> ticks = []; + for (int year = firstYear; year <= lastYear; year += delta) { + final tickDate = DateTime(year); + ticks.add(charts.TickSpec<DateTime>(tickDate, label: dateFormat.format(tickDate))); + } + return TimeAxisSpec(ticks); + } +} diff --git a/lib/widgets/stats/date/histogram.dart b/lib/widgets/stats/date/histogram.dart new file mode 100644 index 0000000..acc6cb2 --- /dev/null +++ b/lib/widgets/stats/date/histogram.dart @@ -0,0 +1,386 @@ +import 'dart:async'; +import 'dart:math'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/sort.dart'; +import 'package:aves/model/filters/date.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/utils/time_utils.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/fx/transitions.dart'; +import 'package:aves/widgets/common/identity/aves_filter_chip.dart'; +import 'package:aves/widgets/stats/date/axis.dart'; +import 'package:charts_flutter/flutter.dart' as charts; +import 'package:collection/collection.dart'; +import 'package:equatable/equatable.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:intl/intl.dart'; +import 'package:provider/provider.dart'; + +class Histogram extends StatefulWidget { + final Set<AvesEntry> entries; + final Duration animationDuration; + final AFilterCallback onFilterSelection; + + const Histogram({ + super.key, + required this.entries, + required this.animationDuration, + required this.onFilterSelection, + }); + + @override + State<Histogram> createState() => _HistogramState(); +} + +class _HistogramState extends State<Histogram> with AutomaticKeepAliveClientMixin { + DateLevel _level = DateLevel.y; + DateTime? _firstDate, _lastDate; + final Map<DateTime, int> _entryCountPerDate = {}; + final ValueNotifier<_EntryByDate?> _selection = ValueNotifier(null); + List<_EntryByDate>? _seriesData; + late Future<List<_EntryByDate>?> _interpolatedDataLoader; + late Future<void> _areaChartLoader; + + static const histogramHeight = 200.0; + + Duration get animationDuration => widget.animationDuration; + + @override + void initState() { + super.initState(); + + final entriesByDateDescending = List.of(widget.entries)..sort(AvesEntrySort.compareByDate); + var lastDate = entriesByDateDescending.firstWhereOrNull((entry) => entry.bestDate != null)?.bestDate; + var firstDate = entriesByDateDescending.lastWhereOrNull((entry) => entry.bestDate != null)?.bestDate; + + if (lastDate != null && firstDate != null) { + final rangeDays = lastDate.difference(firstDate).inHumanDays; + if (rangeDays > 1) { + if (rangeDays <= 31) { + _level = DateLevel.ymd; + } else if (rangeDays <= 365) { + _level = DateLevel.ym; + } + + late DateTime Function(DateTime) normalizeDate; + switch (_level) { + case DateLevel.ymd: + normalizeDate = (v) => DateTime(v.year, v.month, v.day); + case DateLevel.ym: + normalizeDate = (v) => DateTime(v.year, v.month); + default: + normalizeDate = (v) => DateTime(v.year); + } + _firstDate = normalizeDate(firstDate); + _lastDate = normalizeDate(lastDate); + + final dates = entriesByDateDescending.map((entry) => entry.bestDate).nonNulls; + _entryCountPerDate.addAll(groupBy<DateTime, DateTime>(dates, normalizeDate).map((k, v) => MapEntry(k, v.length))); + if (_entryCountPerDate.isNotEmpty) { + // discrete points + _seriesData = _entryCountPerDate.entries.map((kv) { + return _EntryByDate(date: kv.key, entryCount: kv.value); + }).toList(); + + // smooth curve + _interpolatedDataLoader = compute<_DataInterpolationArg, List<_EntryByDate>?>( + _computeInterpolatedData, + _DataInterpolationArg( + firstDate: _firstDate, + lastDate: _lastDate, + level: _level, + entryCountPerDate: _entryCountPerDate, + )); + _areaChartLoader = _interpolatedDataLoader.then((_) => Future.delayed(animationDuration * timeDilation)); + } + } + } + } + + static List<_EntryByDate>? _computeInterpolatedData(_DataInterpolationArg arg) { + final firstDate = arg.firstDate; + final lastDate = arg.lastDate; + final level = arg.level; + final entryCountPerDate = arg.entryCountPerDate; + + if (firstDate == null || lastDate == null) return null; + + final xRange = lastDate.difference(firstDate); + final xRangeInMillis = xRange.inMilliseconds; + late int xCount; + late DateTime Function(DateTime date) incrementDate; + switch (level) { + case DateLevel.ymd: + xCount = xRange.inHumanDays; + incrementDate = (date) => DateTime(date.year, date.month, date.day + 1); + case DateLevel.ym: + xCount = (xRange.inHumanDays / 30.5).round(); + incrementDate = (date) => DateTime(date.year, date.month + 1); + default: + xCount = lastDate.year - firstDate.year; + incrementDate = (date) => DateTime(date.year + 1); + } + final yMax = entryCountPerDate.values.reduce(max).toDouble(); + final xInterval = yMax / xCount; + final controlPoints = <Offset>[]; + var date = firstDate; + for (int i = 0; i <= xCount; i++) { + controlPoints.add(Offset(i * xInterval, (entryCountPerDate[date] ?? 0).toDouble())); + date = incrementDate(date); + } + final interpolatedPoints = controlPoints.length > 3 ? CatmullRomSpline(controlPoints).generateSamples().map((sample) => sample.value).toList() : controlPoints; + final interpolatedData = interpolatedPoints.map((p) { + final date = firstDate.add(Duration(milliseconds: p.dx * xRangeInMillis ~/ yMax)); + final entryCount = p.dy.clamp(0, yMax); + return _EntryByDate(date: date, entryCount: entryCount); + }).toList(); + + return interpolatedData; + } + + @override + Widget build(BuildContext context) { + super.build(context); + + if (_seriesData == null) return const SizedBox(); + + return FutureBuilder<List<_EntryByDate>?>( + future: _interpolatedDataLoader, + builder: (context, snapshot) { + final interpolatedData = snapshot.data; + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + padding: const EdgeInsets.symmetric(horizontal: 8), + height: histogramHeight, + child: AnimatedSwitcher( + duration: animationDuration, + child: interpolatedData != null + ? Stack( + children: [ + FutureBuilder<void>( + future: _areaChartLoader, + builder: (context, snapshot) { + Widget child = const SizedBox(); + if (snapshot.connectionState == ConnectionState.done) { + child = _buildChart(context, interpolatedData, isInterpolated: true, isArea: true); + } + return AnimatedSwitcher( + duration: animationDuration, + child: child, + ); + }, + ), + _buildChart(context, interpolatedData, isInterpolated: true, isArea: false), + _buildChart(context, _seriesData!, isInterpolated: false, isArea: false), + ], + ) + : const SizedBox(), + ), + ), + _buildSelectionRow(), + ], + ); + }, + ); + } + + Widget _buildChart(BuildContext context, List<_EntryByDate> seriesData, {required bool isInterpolated, required bool isArea}) { + final drawArea = isInterpolated && isArea; + final drawLine = isInterpolated && !isArea; + final drawPoints = !isInterpolated; + + final colorScheme = Theme.of(context).colorScheme; + final accentColor = colorScheme.primary; + final axisColor = charts.ColorUtil.fromDartColor(drawPoints ? colorScheme.onSurface : Colors.transparent); + final measureLineColor = charts.ColorUtil.fromDartColor(drawPoints ? colorScheme.onSurface.withValues(alpha: .1) : Colors.transparent); + final histogramLineColor = charts.ColorUtil.fromDartColor(drawLine ? accentColor : Colors.white); + final histogramPointStrikeColor = charts.ColorUtil.fromDartColor(drawPoints ? colorScheme.onSurface : Colors.transparent); + final histogramPointFillColor = charts.ColorUtil.fromDartColor(Themes.firstLayerColor(context)); + + final series = [ + if (drawLine || drawArea) + charts.Series<_EntryByDate, DateTime>( + id: 'curve', + data: seriesData, + domainFn: (d, i) => d.date, + measureFn: (d, i) => d.entryCount, + colorFn: (d, i) => histogramLineColor, + ), + if (drawPoints && !drawArea) + charts.Series<_EntryByDate, DateTime>( + id: 'points', + data: seriesData, + domainFn: (d, i) => d.date, + measureFn: (d, i) => d.entryCount, + colorFn: (d, i) => histogramPointStrikeColor, + fillColorFn: (d, i) => histogramPointFillColor, + )..setAttribute(charts.rendererIdKey, 'customPoint'), + ]; + + final locale = context.locale; + final timeAxisSpec = _firstDate != null && _lastDate != null + ? TimeAxisSpec.forLevel( + locale: locale, + level: _level, + first: _firstDate!, + last: _lastDate!, + ) + : null; + final tickFormatter = NumberFormat.decimalPattern(locale); + + final domainAxis = charts.DateTimeAxisSpec( + renderSpec: charts.SmallTickRendererSpec( + labelStyle: charts.TextStyleSpec(color: axisColor), + lineStyle: charts.LineStyleSpec(color: axisColor), + ), + tickProviderSpec: timeAxisSpec != null && timeAxisSpec.tickSpecs.isNotEmpty ? charts.StaticDateTimeTickProviderSpec(timeAxisSpec.tickSpecs) : null, + ); + + Widget chart = charts.TimeSeriesChart( + series, + animate: false, + animationDuration: animationDuration, + domainAxis: domainAxis, + primaryMeasureAxis: charts.NumericAxisSpec( + renderSpec: charts.GridlineRendererSpec( + labelStyle: charts.TextStyleSpec(color: axisColor), + lineStyle: charts.LineStyleSpec(color: measureLineColor), + ), + tickFormatterSpec: charts.BasicNumericTickFormatterSpec((v) { + // localize and hide 0 + return (v == null || v == 0) ? '' : tickFormatter.format(v); + }), + ), + defaultRenderer: charts.LineRendererConfig( + includeArea: drawArea, + areaOpacity: 1, + ), + customSeriesRenderers: [ + charts.PointRendererConfig( + customRendererId: 'customPoint', + strokeWidthPx: 2, + symbolRenderer: _CircleSymbolRenderer(isSolid: false), + ), + ], + defaultInteractions: false, + behaviors: drawPoints + ? [ + charts.SelectNearest(), + charts.LinePointHighlighter( + defaultRadiusPx: 8, + radiusPaddingPx: 2, + showHorizontalFollowLine: charts.LinePointHighlighterFollowLineType.nearest, + showVerticalFollowLine: charts.LinePointHighlighterFollowLineType.nearest, + ), + ] + : null, + selectionModels: [ + charts.SelectionModelConfig( + changedListener: (model) => _selection.value = model.selectedDatum.firstOrNull?.datum as _EntryByDate?, + ) + ], + ); + if (drawArea) { + chart = ShaderMask( + shaderCallback: LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [ + accentColor, + accentColor.withAlpha(0), + ], + ).createShader, + blendMode: BlendMode.srcIn, + child: chart, + ); + } + return chart; + } + + Widget _buildSelectionRow() { + final countFormatter = NumberFormat.decimalPattern(context.locale); + + return ValueListenableBuilder<_EntryByDate?>( + valueListenable: _selection, + builder: (context, selection, child) { + late Widget child; + if (selection == null) { + child = const SizedBox(); + } else { + final filter = DateFilter(_level, selection.date); + final count = selection.entryCount; + child = Padding( + padding: const EdgeInsets.all(8), + child: Row( + children: [ + AvesFilterChip( + filter: filter, + onTap: widget.onFilterSelection, + ), + const Spacer(), + Text( + countFormatter.format(count), + style: TextStyle( + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + textAlign: TextAlign.end, + ), + ], + ), + ); + } + + return AnimatedSwitcher( + duration: context.read<DurationsData>().formTransition, + switchInCurve: Curves.easeInOutCubic, + switchOutCurve: Curves.easeInOutCubic, + transitionBuilder: AvesTransitions.formTransitionBuilder, + child: child, + ); + }, + ); + } + + @override + bool get wantKeepAlive => true; +} + +@immutable +class _EntryByDate extends Equatable { + final DateTime date; + final num entryCount; + + @override + List<Object?> get props => [date, entryCount]; + + const _EntryByDate({ + required this.date, + required this.entryCount, + }); +} + +class _CircleSymbolRenderer extends charts.CircleSymbolRenderer { + _CircleSymbolRenderer({super.isSolid = true}); + + @override + charts.Color? getSolidFillColor(charts.Color? fillColor) => fillColor; +} + +class _DataInterpolationArg { + final DateLevel level; + final DateTime? firstDate, lastDate; + final Map<DateTime, int> entryCountPerDate; + + const _DataInterpolationArg({ + required this.level, + required this.firstDate, + required this.lastDate, + required this.entryCountPerDate, + }); +} diff --git a/lib/widgets/stats/filter_table.dart b/lib/widgets/stats/filter_table.dart new file mode 100644 index 0000000..b3d36a4 --- /dev/null +++ b/lib/widgets/stats/filter_table.dart @@ -0,0 +1,124 @@ +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/aves_filter_chip.dart'; +import 'package:aves/widgets/stats/percent_text.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; +import 'package:percent_indicator/linear_percent_indicator.dart'; +import 'package:provider/provider.dart'; + +class FilterTable<T extends Comparable> extends StatelessWidget { + final int totalEntryCount; + final Map<T, int> entryCountMap; + final CollectionFilter Function(T key) filterBuilder; + final bool sortByCount; + final int? maxRowCount; + final AFilterCallback onFilterSelection; + + const FilterTable({ + super.key, + required this.totalEntryCount, + required this.entryCountMap, + required this.filterBuilder, + required this.sortByCount, + required this.maxRowCount, + required this.onFilterSelection, + }); + + static const chipWidth = 160.0; + static const countWidth = 32.0; + static const percentIndicatorMinWidth = 80.0; + + @override + Widget build(BuildContext context) { + final countFormatter = NumberFormat.decimalPattern(context.locale); + final animate = context.select<Settings, bool>((v) => v.animate); + + final sortedEntries = entryCountMap.entries.toList(); + if (sortByCount) { + sortedEntries.sort((kv1, kv2) { + final c = kv2.value.compareTo(kv1.value); + return c != 0 ? c : kv1.key.compareTo(kv2.key); + }); + } + + final textScaler = MediaQuery.textScalerOf(context); + final lineHeight = textScaler.scale(16); + final barRadius = Radius.circular(lineHeight / 2); + final isRtl = context.isRtl; + + return Padding( + padding: const EdgeInsetsDirectional.only(start: AvesFilterChip.outlineWidth / 2 + 6, end: 8), + child: LayoutBuilder( + builder: (context, constraints) { + final showPercentIndicator = constraints.maxWidth - (chipWidth + countWidth) > percentIndicatorMinWidth; + final displayedEntries = maxRowCount != null ? sortedEntries.take(maxRowCount!) : sortedEntries; + final isMonochrome = settings.themeColorMode == AvesThemeColorMode.monochrome; + return Table( + children: displayedEntries.map((kv) { + final filter = filterBuilder(kv.key); + final count = kv.value; + final percent = count / totalEntryCount; + final colorScheme = Theme.of(context).colorScheme; + return TableRow( + children: [ + Container( + // the `Table` `border` property paints on the cells and does not add margins, + // so we define margins here instead, but they should be symmetric + // to keep all cells vertically aligned on the center/middle + margin: const EdgeInsets.symmetric(vertical: 4), + alignment: AlignmentDirectional.centerStart, + child: AvesFilterChip( + filter: filter, + onTap: onFilterSelection, + ), + ), + if (showPercentIndicator) + FutureBuilder<Color>( + future: filter.color(context), + builder: (context, snapshot) { + final color = snapshot.data; + return Stack( + // use a stack instead of `center` field, so that the widgets + // are centered even when the center child has larger height + alignment: Alignment.center, + children: [ + LinearPercentIndicator( + percent: percent, + lineHeight: lineHeight, + backgroundColor: Themes.secondLayerColor(context), + progressColor: isMonochrome ? colorScheme.primary : color, + animation: animate, + isRTL: isRtl, + barRadius: barRadius, + padding: EdgeInsets.symmetric(horizontal: lineHeight), + ), + LinearPercentIndicatorText(percent: percent), + ], + ); + }, + ), + Text( + countFormatter.format(count), + style: TextStyle( + color: colorScheme.onSurfaceVariant, + ), + textAlign: TextAlign.end, + ), + ], + ); + }).toList(), + columnWidths: const { + 0: MaxColumnWidth(IntrinsicColumnWidth(), FixedColumnWidth(chipWidth)), + 2: MaxColumnWidth(IntrinsicColumnWidth(), FixedColumnWidth(countWidth)), + }, + defaultVerticalAlignment: TableCellVerticalAlignment.middle, + ); + }, + ), + ); + } +} diff --git a/lib/widgets/stats/mime_donut.dart b/lib/widgets/stats/mime_donut.dart new file mode 100644 index 0000000..45fcf5a --- /dev/null +++ b/lib/widgets/stats/mime_donut.dart @@ -0,0 +1,43 @@ +import 'package:aves/model/filters/mime.dart'; +import 'package:aves/theme/colors.dart'; +import 'package:aves/utils/mime_utils.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/aves_donut.dart'; +import 'package:aves/widgets/common/identity/aves_filter_chip.dart'; +import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; +import 'package:provider/provider.dart'; + +class MimeDonut extends StatelessWidget { + final IconData icon; + final Map<String, int> byMimeTypes; + final Duration animationDuration; + final AFilterCallback onFilterSelection; + + const MimeDonut({ + super.key, + required this.icon, + required this.byMimeTypes, + required this.animationDuration, + required this.onFilterSelection, + }); + + @override + Widget build(BuildContext context) { + final countFormatter = NumberFormat.decimalPattern(context.locale); + + String formatKey(d) => MimeUtils.displayType(d.key); + return AvesDonut( + title: Icon(icon), + byTypes: byMimeTypes, + animationDuration: animationDuration, + formatKey: formatKey, + formatValue: countFormatter.format, + colorize: (context, d) { + final colors = context.read<AvesColorsData>(); + return colors.fromString(formatKey(d)); + }, + onTap: (d) => onFilterSelection(MimeFilter(d.key)), + ); + } +} diff --git a/lib/widgets/stats/percent_text.dart b/lib/widgets/stats/percent_text.dart new file mode 100644 index 0000000..ed7247b --- /dev/null +++ b/lib/widgets/stats/percent_text.dart @@ -0,0 +1,33 @@ +import 'package:aves/theme/styles.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/widgets/common/basic/text/outlined.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/extensions/theme.dart'; +import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; + +class LinearPercentIndicatorText extends StatelessWidget { + final double percent; + + const LinearPercentIndicatorText({ + super.key, + required this.percent, + }); + + @override + Widget build(BuildContext context) { + final percentFormatter = NumberFormat.percentPattern(context.locale); + + return OutlinedText( + textSpans: [ + TextSpan( + text: percentFormatter.format(percent), + style: TextStyle( + shadows: Theme.of(context).isDark ? AStyles.embossShadows : null, + ), + ) + ], + outlineColor: Themes.firstLayerColor(context), + ); + } +} diff --git a/lib/widgets/stats/stats_page.dart b/lib/widgets/stats/stats_page.dart new file mode 100644 index 0000000..0cf3b93 --- /dev/null +++ b/lib/widgets/stats/stats_page.dart @@ -0,0 +1,439 @@ +import 'dart:async'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/filters/covered/location.dart'; +import 'package:aves/model/filters/covered/stored_album.dart'; +import 'package:aves/model/filters/covered/tag.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/filters/rating.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/format.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/theme/styles.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/utils/file_utils.dart'; +import 'package:aves/widgets/collection/collection_page.dart'; +import 'package:aves/widgets/common/action_mixins/feedback.dart'; +import 'package:aves/widgets/common/action_mixins/vault_aware.dart'; +import 'package:aves/widgets/common/basic/insets.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/basic/tv_edge_focus.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/empty.dart'; +import 'package:aves/widgets/stats/date/histogram.dart'; +import 'package:aves/widgets/stats/filter_table.dart'; +import 'package:aves/widgets/stats/mime_donut.dart'; +import 'package:aves/widgets/stats/percent_text.dart'; +import 'package:aves/widgets/stats/top_page.dart'; +import 'package:aves/widgets/viewer/controls/notifications.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:flutter_staggered_animations/flutter_staggered_animations.dart'; +import 'package:percent_indicator/linear_percent_indicator.dart'; +import 'package:provider/provider.dart'; + +class StatsPage extends StatefulWidget { + static const routeName = '/collection/stats'; + + final Set<AvesEntry> entries; + final CollectionSource source; + final CollectionLens? parentCollection; + + const StatsPage({ + super.key, + required this.entries, + required this.source, + this.parentCollection, + }); + + @override + State<StatsPage> createState() => _StatsPageState(); +} + +class _StatsPageState extends State<StatsPage> with FeedbackMixin, VaultAwareMixin { + final Map<String, int> _entryCountPerCountry = {}, _entryCountPerState = {}, _entryCountPerPlace = {}; + final Map<String, int> _entryCountPerTag = {}, _entryCountPerAlbum = {}; + final Map<int, int> _entryCountPerRating = Map.fromEntries(List.generate(7, (i) => MapEntry(5 - i, 0))); + late final ValueNotifier<bool> _isPageAnimatingNotifier; + int _totalSizeBytes = 0; + int _totalDurationMillis = 0; + + Set<AvesEntry> get entries => widget.entries; + + @override + void initState() { + super.initState(); + + _isPageAnimatingNotifier = ValueNotifier(true); + Future.delayed(ADurations.pageTransitionLoose * timeDilation).then((_) { + if (!mounted) return; + _isPageAnimatingNotifier.value = false; + }); + + entries.forEach((entry) { + _totalSizeBytes += entry.sizeBytes ?? 0; + _totalDurationMillis += entry.durationMillis ?? 0; + + if (entry.hasAddress) { + final address = entry.addressDetails!; + var country = address.countryName; + if (country != null && country.isNotEmpty) { + country += '${LocationFilter.locationSeparator}${address.countryCode}'; + _entryCountPerCountry[country] = (_entryCountPerCountry[country] ?? 0) + 1; + } + var state = address.stateName; + if (state != null && state.isNotEmpty) { + state += '${LocationFilter.locationSeparator}${address.stateCode}'; + _entryCountPerState[state] = (_entryCountPerState[state] ?? 0) + 1; + } + final place = address.place; + if (place != null && place.isNotEmpty) { + _entryCountPerPlace[place] = (_entryCountPerPlace[place] ?? 0) + 1; + } + } + + entry.tags.forEach((tag) { + _entryCountPerTag[tag] = (_entryCountPerTag[tag] ?? 0) + 1; + }); + + final album = entry.directory; + if (album != null) { + _entryCountPerAlbum[album] = (_entryCountPerAlbum[album] ?? 0) + 1; + } + + final rating = entry.rating; + _entryCountPerRating[rating] = (_entryCountPerRating[rating] ?? 0) + 1; + }); + } + + @override + void dispose() { + _isPageAnimatingNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final useTvLayout = settings.useTvLayout; + return ValueListenableBuilder<bool>( + valueListenable: _isPageAnimatingNotifier, + builder: (context, animating, child) { + final l10n = context.l10n; + + Widget child = const SizedBox(); + + if (!animating) { + final durations = context.watch<DurationsData>(); + + if (entries.isEmpty) { + child = EmptyContent( + icon: AIcons.image, + text: l10n.collectionEmptyImages, + ); + } else { + final chartAnimationDuration = context.read<DurationsData>().chartTransition; + + final byMimeTypes = groupBy<AvesEntry, String>(entries, (entry) => entry.mimeType).map<String, int>((k, v) => MapEntry(k, v.length)); + final imagesByMimeTypes = Map.fromEntries(byMimeTypes.entries.where((kv) => kv.key.startsWith('image'))); + final videoByMimeTypes = Map.fromEntries(byMimeTypes.entries.where((kv) => kv.key.startsWith('video'))); + final mimeDonuts = Wrap( + alignment: WrapAlignment.center, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + MimeDonut( + icon: AIcons.image, + byMimeTypes: imagesByMimeTypes, + animationDuration: chartAnimationDuration, + onFilterSelection: (filter) => _onFilterSelection(context, filter), + ), + MimeDonut( + icon: AIcons.video, + byMimeTypes: videoByMimeTypes, + animationDuration: chartAnimationDuration, + onFilterSelection: (filter) => _onFilterSelection(context, filter), + ), + ], + ); + + final showRatings = _entryCountPerRating.entries.any((kv) => kv.key != 0 && kv.value > 0); + final source = widget.source; + child = NotificationListener<SelectFilterNotification>( + onNotification: (notification) { + _onFilterSelection(context, notification.filter); + return true; + }, + child: AnimationLimiter( + child: ListView( + children: AnimationConfiguration.toStaggeredList( + duration: durations.staggeredAnimation, + delay: durations.staggeredAnimationDelay * timeDilation, + childAnimationBuilder: (child) => SlideAnimation( + verticalOffset: 50.0, + child: FadeInAnimation( + child: child, + ), + ), + children: [ + const TvEdgeFocus(), + mimeDonuts, + Histogram( + entries: entries, + animationDuration: chartAnimationDuration, + onFilterSelection: (filter) => _onFilterSelection(context, filter), + ), + const SizedBox(height: 16), + _buildTotalSizeIndicator(context), + if (_totalDurationMillis > 0) ...[ + const SizedBox(height: 16), + _buildTotalDurationIndicator(), + ], + const SizedBox(height: 16), + _LocationIndicator(entries: entries), + ..._buildFilterSection<String>(context, l10n.statsTopCountriesSectionTitle, _entryCountPerCountry, (v) => LocationFilter(LocationLevel.country, v)), + ..._buildFilterSection<String>(context, l10n.statsTopStatesSectionTitle, _entryCountPerState, (v) => LocationFilter(LocationLevel.state, v)), + ..._buildFilterSection<String>(context, l10n.statsTopPlacesSectionTitle, _entryCountPerPlace, (v) => LocationFilter(LocationLevel.place, v)), + ..._buildFilterSection<String>(context, l10n.statsTopTagsSectionTitle, _entryCountPerTag, TagFilter.new), + ..._buildFilterSection<String>(context, l10n.statsTopAlbumsSectionTitle, _entryCountPerAlbum, (v) => StoredAlbumFilter(v, source.getStoredAlbumDisplayName(context, v))), + if (showRatings) ..._buildFilterSection<int>(context, l10n.searchRatingSectionTitle, _entryCountPerRating, RatingFilter.new, sortByCount: false, maxRowCount: null), + ], + ), + ), + ), + ); + } + } + + return AvesScaffold( + appBar: AppBar( + automaticallyImplyLeading: !useTvLayout, + title: Text(l10n.statsPageTitle), + ), + body: GestureAreaProtectorStack( + child: SafeArea( + bottom: false, + child: TooltipTheme( + data: TooltipTheme.of(context).copyWith( + preferBelow: false, + ), + child: child, + ), + ), + ), + ); + }, + ); + } + + Widget _buildTotalSizeIndicator(BuildContext context) { + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + const Icon(AIcons.size), + const SizedBox(width: 16), + Expanded( + child: Text(formatFileSize(context.locale, _totalSizeBytes)), + ), + ], + ), + ); + } + + Widget _buildTotalDurationIndicator() { + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + const Icon(AIcons.videoPlay), + const SizedBox(width: 16), + Expanded( + child: Text(formatFriendlyDuration(Duration(milliseconds: _totalDurationMillis))), + ), + ], + ), + ); + } + + List<Widget> _buildFilterSection<T extends Comparable>( + BuildContext context, + String title, + Map<T, int> entryCountMap, + CollectionFilter Function(T key) filterBuilder, { + bool sortByCount = true, + int? maxRowCount = 3, + }) { + if (entryCountMap.isEmpty) return []; + + final totalEntryCount = entries.length; + final hasMore = maxRowCount != null && entryCountMap.length > maxRowCount; + final onHeaderPressed = hasMore + ? () => Navigator.maybeOf(context)?.push( + MaterialPageRoute( + settings: const RouteSettings(name: StatsTopPage.routeName), + builder: (context) => StatsTopPage( + title: title, + totalEntryCount: totalEntryCount, + entryCountMap: entryCountMap, + filterBuilder: filterBuilder, + sortByCount: sortByCount, + onFilterSelection: (filter) => _onFilterSelection(context, filter), + ), + ), + ) + : null; + Widget header = Text( + title, + style: AStyles.knownTitleText, + ); + if (settings.useTvLayout) { + header = Padding( + padding: const EdgeInsets.all(16), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + header, + const SizedBox(width: 16), + Icon(AIcons.next, color: hasMore ? null : Theme.of(context).disabledColor), + ], + ), + ); + header = Container( + padding: const EdgeInsets.symmetric(vertical: 12), + alignment: AlignmentDirectional.centerStart, + // prevent ink response when tapping the header does nothing, + // because otherwise Play Store reviewers think it is broken navigation + child: onHeaderPressed != null + ? InkWell( + onTap: onHeaderPressed, + borderRadius: const BorderRadius.all(Radius.circular(123)), + child: header, + ) + : Focus(child: header), + ); + } else { + header = Padding( + padding: const EdgeInsets.all(16), + child: Row( + children: [ + header, + const Spacer(), + IconButton( + icon: const Icon(AIcons.next), + onPressed: onHeaderPressed, + tooltip: MaterialLocalizations.of(context).moreButtonTooltip, + ), + ], + ), + ); + } + + return [ + header, + FilterTable( + totalEntryCount: totalEntryCount, + entryCountMap: entryCountMap, + filterBuilder: filterBuilder, + sortByCount: sortByCount, + maxRowCount: maxRowCount, + onFilterSelection: (filter) => _onFilterSelection(context, filter), + ), + ]; + } + + Future<void> _onFilterSelection(BuildContext context, CollectionFilter filter) async { + if (!await unlockFilter(context, filter)) return; + + if (widget.parentCollection != null) { + _applyToParentCollectionPage(context, filter); + } else { + _jumpToCollectionPage(context, filter); + } + } + + void _applyToParentCollectionPage(BuildContext context, CollectionFilter filter) { + widget.parentCollection!.addFilters({filter}); + // We delay closing the current page after applying the filter selection + // so that hero animation target is ready in the `FilterBar`, + // even when the target is a child of an `AnimatedList`. + // Do not use `WidgetsBinding.instance.addPostFrameCallback`, + // as it may not trigger if there is no subsequent build. + Future.delayed(const Duration(milliseconds: 100), () => Navigator.maybeOf(context)?.popUntil((route) => route.settings.name == CollectionPage.routeName)); + } + + void _jumpToCollectionPage(BuildContext context, CollectionFilter filter) { + Navigator.maybeOf(context)?.pushAndRemoveUntil( + MaterialPageRoute( + settings: const RouteSettings(name: CollectionPage.routeName), + builder: (context) => CollectionPage( + source: widget.source, + filters: {filter}, + ), + ), + (route) => false, + ); + } +} + +class _LocationIndicator extends StatelessWidget { + final Set<AvesEntry> entries; + + const _LocationIndicator({required this.entries}); + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final catalogued = entries.where((entry) => entry.isCatalogued); + final withGps = catalogued.where((entry) => entry.hasGps); + final withGpsCount = withGps.length; + final withGpsPercent = withGpsCount / entries.length; + final textScaler = MediaQuery.textScalerOf(context); + final lineHeight = textScaler.scale(16); + final barRadius = Radius.circular(lineHeight / 2); + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Column( + children: [ + Row( + mainAxisSize: MainAxisSize.min, + children: [ + const Icon(AIcons.location), + Expanded( + child: Stack( + // use a stack instead of `center` field, so that the widgets + // are centered even when the center child has larger height + alignment: Alignment.center, + children: [ + LinearPercentIndicator( + percent: withGpsPercent, + lineHeight: lineHeight, + backgroundColor: Themes.secondLayerColor(context), + progressColor: theme.colorScheme.primary, + animation: context.select<Settings, bool>((v) => v.animate), + isRTL: context.isRtl, + barRadius: barRadius, + padding: EdgeInsets.symmetric(horizontal: lineHeight), + ), + LinearPercentIndicatorText(percent: withGpsPercent), + ], + ), + ), + // end padding to match leading, so that inside label is aligned with outside label below + const SizedBox(width: 24), + ], + ), + const SizedBox(height: 8), + Text( + context.l10n.statsWithGps(withGpsCount), + textAlign: TextAlign.center, + ), + ], + ), + ); + } +} diff --git a/lib/widgets/stats/top_page.dart b/lib/widgets/stats/top_page.dart new file mode 100644 index 0000000..3531a0e --- /dev/null +++ b/lib/widgets/stats/top_page.dart @@ -0,0 +1,128 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:aves/model/filters/covered/stored_album.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/ref/locales.dart'; +import 'package:aves/ref/mime_types.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/action_mixins/feedback.dart'; +import 'package:aves/widgets/common/basic/insets.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/extensions/media_query.dart'; +import 'package:aves/widgets/common/identity/aves_filter_chip.dart'; +import 'package:aves/widgets/stats/filter_table.dart'; +import 'package:aves/widgets/viewer/controls/notifications.dart'; +import 'package:csv/csv.dart'; +import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; +import 'package:provider/provider.dart'; + +class StatsTopPage<T extends Comparable> extends StatelessWidget with FeedbackMixin { + static const routeName = '/collection/stats/top'; + + final String title; + final int totalEntryCount; + final Map<T, int> entryCountMap; + final CollectionFilter Function(T key) filterBuilder; + final bool sortByCount; + final AFilterCallback onFilterSelection; + + const StatsTopPage({ + super.key, + required this.title, + required this.totalEntryCount, + required this.entryCountMap, + required this.filterBuilder, + required this.sortByCount, + required this.onFilterSelection, + }); + + @override + Widget build(BuildContext context) { + return AvesScaffold( + appBar: AppBar( + automaticallyImplyLeading: !settings.useTvLayout, + title: Text(title), + actions: [ + IconButton( + icon: Icon(AIcons.fileExport), + onPressed: () => _export(context), + tooltip: context.l10n.settingsActionExport, + ), + ], + ), + body: GestureAreaProtectorStack( + child: SafeArea( + bottom: false, + child: Builder(builder: (context) { + return NotificationListener<SelectFilterNotification>( + onNotification: (notification) { + onFilterSelection(notification.filter); + return true; + }, + child: SingleChildScrollView( + padding: const EdgeInsets.symmetric(vertical: 8) + + EdgeInsets.only( + bottom: context.select<MediaQueryData, double>((mq) => mq.effectiveBottomPadding), + ), + child: FilterTable( + totalEntryCount: totalEntryCount, + entryCountMap: entryCountMap, + filterBuilder: filterBuilder, + sortByCount: sortByCount, + maxRowCount: null, + onFilterSelection: onFilterSelection, + ), + ), + ); + }), + ), + ), + ); + } + + Future<void> _export(BuildContext context) async { + final sortedEntries = entryCountMap.entries.toList(); + if (sortByCount) { + sortedEntries.sort((kv1, kv2) { + final c = kv2.value.compareTo(kv1.value); + return c != 0 ? c : kv1.key.compareTo(kv2.key); + }); + } + + final csv = const ListToCsvConverter().convert([ + [title, '#'], + ...sortedEntries.map((kv) { + final filter = filterBuilder(kv.key); + final count = kv.value; + + String label; + switch (filter) { + case StoredAlbumFilter _: + label = filter.album; + default: + label = filter.getLabel(context); + } + return [label, count]; + }) + ]); + + const mimeType = MimeTypes.csv; + final success = await storageService.createFile( + 'aves-stats-${DateFormat('yyyyMMdd_HHmmss', asciiLocale).format(DateTime.now())}${MimeTypes.extensionFor(mimeType)}', + mimeType, + Uint8List.fromList(utf8.encode(csv)), + ); + if (success != null) { + if (success) { + showFeedback(context, FeedbackType.info, context.l10n.genericSuccessFeedback); + } else { + showFeedback(context, FeedbackType.warn, context.l10n.genericFailureFeedback); + } + } + } +} diff --git a/lib/widgets/viewer/action/entry_action_delegate.dart b/lib/widgets/viewer/action/entry_action_delegate.dart new file mode 100644 index 0000000..4186f92 --- /dev/null +++ b/lib/widgets/viewer/action/entry_action_delegate.dart @@ -0,0 +1,518 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:aves/app_mode.dart'; +import 'package:aves/model/device.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/favourites.dart'; +import 'package:aves/model/entry/extensions/location.dart'; +import 'package:aves/model/entry/extensions/metadata_edition.dart'; +import 'package:aves/model/entry/extensions/multipage.dart'; +import 'package:aves/model/entry/extensions/props.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/model/vaults/vaults.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/services/media/media_edit_service.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/widgets/collection/collection_page.dart'; +import 'package:aves/widgets/common/action_mixins/entry_storage.dart'; +import 'package:aves/widgets/common/action_mixins/feedback.dart'; +import 'package:aves/widgets/common/action_mixins/permission_aware.dart'; +import 'package:aves/widgets/common/action_mixins/size_aware.dart'; +import 'package:aves/widgets/common/action_mixins/vault_aware.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/dialogs/add_shortcut_dialog.dart'; +import 'package:aves/widgets/dialogs/aves_confirmation_dialog.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:aves/widgets/dialogs/convert_entry_dialog.dart'; +import 'package:aves/widgets/dialogs/entry_editors/rename_entry_dialog.dart'; +import 'package:aves/widgets/viewer/action/entry_info_action_delegate.dart'; +import 'package:aves/widgets/viewer/action/printer.dart'; +import 'package:aves/widgets/viewer/action/single_entry_editor.dart'; +import 'package:aves/widgets/viewer/controls/notifications.dart'; +import 'package:aves/widgets/viewer/debug/debug_page.dart'; +import 'package:aves/widgets/viewer/entry_viewer_page.dart'; +import 'package:aves/widgets/viewer/multipage/conductor.dart'; +import 'package:aves/widgets/viewer/source_viewer_page.dart'; +import 'package:aves/widgets/viewer/video/conductor.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:provider/provider.dart'; + +class EntryActionDelegate with FeedbackMixin, PermissionAwareMixin, SizeAwareMixin, SingleEntryEditorMixin, EntryStorageMixin, VaultAwareMixin { + final AvesEntry mainEntry, pageEntry; + final CollectionLens? collection; + final EntryInfoActionDelegate _metadataActionDelegate = EntryInfoActionDelegate(); + + EntryActionDelegate(this.mainEntry, this.pageEntry, this.collection); + + bool isVisible({ + required AppMode appMode, + required EntryAction action, + }) { + if (mainEntry.trashed) { + switch (action) { + case EntryAction.delete: + case EntryAction.restore: + return true; + case EntryAction.debug: + return !kReleaseMode; + default: + return false; + } + } else { + final targetEntry = EntryActions.pageActions.contains(action) ? pageEntry : mainEntry; + final canWrite = appMode.canEditEntry && !settings.isReadOnly; + switch (action) { + case EntryAction.toggleFavourite: + return collection != null; + case EntryAction.delete: + case EntryAction.rename: + case EntryAction.move: + return canWrite && targetEntry.canEdit; + case EntryAction.copy: + return canWrite; + case EntryAction.rotateCCW: + case EntryAction.rotateCW: + return canWrite && targetEntry.canRotate; + case EntryAction.flip: + return canWrite && targetEntry.canFlip; + case EntryAction.convert: + return canWrite && !targetEntry.isPureVideo; + case EntryAction.print: + return !targetEntry.isPureVideo; + case EntryAction.openMap: + return !settings.useTvLayout && targetEntry.hasGps; + case EntryAction.viewSource: + return targetEntry.isSvg; + case EntryAction.videoCaptureFrame: + return canWrite && targetEntry.isPureVideo; + case EntryAction.lockViewer: + case EntryAction.videoToggleMute: + return !settings.useTvLayout && targetEntry.isPureVideo; + case EntryAction.videoSelectStreams: + case EntryAction.videoSetSpeed: + case EntryAction.videoABRepeat: + case EntryAction.videoSettings: + case EntryAction.videoTogglePlay: + case EntryAction.videoReplay10: + case EntryAction.videoSkip10: + case EntryAction.videoShowPreviousFrame: + case EntryAction.videoShowNextFrame: + case EntryAction.openVideoPlayer: + return targetEntry.isPureVideo; + case EntryAction.rotateScreen: + return !settings.useTvLayout && settings.isRotationLocked; + case EntryAction.addShortcut: + return device.canPinShortcut; + case EntryAction.edit: + return canWrite; + case EntryAction.copyToClipboard: + case EntryAction.open: + case EntryAction.setAs: + case EntryAction.cast: + return !settings.useTvLayout; + case EntryAction.info: + case EntryAction.share: + return true; + case EntryAction.restore: + return false; + case EntryAction.editDate: + case EntryAction.editLocation: + case EntryAction.editTitleDescription: + case EntryAction.editRating: + case EntryAction.editTags: + case EntryAction.removeMetadata: + case EntryAction.exportMetadata: + case EntryAction.showGeoTiffOnMap: + case EntryAction.convertMotionPhotoToStillImage: + case EntryAction.viewMotionPhotoVideo: + return _metadataActionDelegate.isVisible( + appMode: appMode, + targetEntry: targetEntry, + action: action, + ); + case EntryAction.debug: + return !kReleaseMode; + } + } + } + + bool canApply(EntryAction action) { + final targetEntry = EntryActions.pageActions.contains(action) ? pageEntry : mainEntry; + switch (action) { + case EntryAction.rotateCCW: + case EntryAction.rotateCW: + case EntryAction.flip: + case EntryAction.editDate: + case EntryAction.editLocation: + case EntryAction.editTitleDescription: + case EntryAction.editRating: + case EntryAction.editTags: + case EntryAction.removeMetadata: + case EntryAction.exportMetadata: + case EntryAction.showGeoTiffOnMap: + case EntryAction.convertMotionPhotoToStillImage: + case EntryAction.viewMotionPhotoVideo: + return _metadataActionDelegate.canApply(targetEntry, action); + case EntryAction.convert: + case EntryAction.rename: + case EntryAction.copy: + case EntryAction.move: + return !availability.isLocked; + default: + return true; + } + } + + AvesEntry _getTargetEntry(BuildContext context, EntryAction action) { + if (mainEntry.isMultiPage && (mainEntry.isStack || EntryActions.pageActions.contains(action))) { + final multiPageController = context.read<MultiPageConductor>().getController(mainEntry); + if (multiPageController != null) { + final multiPageInfo = multiPageController.info; + final pageEntry = multiPageInfo?.getPageEntryByIndex(multiPageController.page); + if (pageEntry != null) { + return pageEntry; + } + } + } + return mainEntry; + } + + void onActionSelected(BuildContext context, EntryAction action) { + reportService.log('$runtimeType handles $action'); + final targetEntry = _getTargetEntry(context, action); + + switch (action) { + case EntryAction.info: + ShowInfoPageNotification().dispatch(context); + case EntryAction.addShortcut: + _addShortcut(context, targetEntry); + case EntryAction.copyToClipboard: + appService.copyToClipboard(targetEntry.uri, targetEntry.bestTitle).then((success) { + if (success) { + showFeedback(context, FeedbackType.info, context.l10n.genericSuccessFeedback); + } else { + showFeedback(context, FeedbackType.warn, context.l10n.genericFailureFeedback); + } + }); + case EntryAction.delete: + _delete(context, targetEntry); + case EntryAction.restore: + _move(context, targetEntry, moveType: MoveType.fromBin); + case EntryAction.convert: + _convert(context, targetEntry); + case EntryAction.print: + EntryPrinter(targetEntry).print(context); + case EntryAction.rename: + _rename(context, targetEntry); + case EntryAction.copy: + _move(context, targetEntry, moveType: MoveType.copy); + case EntryAction.move: + _move(context, targetEntry, moveType: MoveType.move); + case EntryAction.share: + appService.shareEntries({targetEntry}).then((success) { + if (!success) showNoMatchingAppDialog(context); + }); + case EntryAction.toggleFavourite: + targetEntry.toggleFavourite(); + // raster + case EntryAction.rotateCCW: + _rotate(context, targetEntry, clockwise: false); + case EntryAction.rotateCW: + _rotate(context, targetEntry, clockwise: true); + case EntryAction.flip: + _flip(context, targetEntry); + // vector + case EntryAction.viewSource: + _goToSourceViewer(context, targetEntry); + case EntryAction.lockViewer: + const LockViewNotification(locked: true).dispatch(context); + // video + case EntryAction.videoCaptureFrame: + case EntryAction.videoToggleMute: + case EntryAction.videoSelectStreams: + case EntryAction.videoSetSpeed: + case EntryAction.videoABRepeat: + case EntryAction.videoSettings: + case EntryAction.videoTogglePlay: + case EntryAction.videoReplay10: + case EntryAction.videoSkip10: + case EntryAction.videoShowPreviousFrame: + case EntryAction.videoShowNextFrame: + case EntryAction.openVideoPlayer: + final controller = context.read<VideoConductor>().getController(targetEntry); + if (controller != null) { + VideoActionNotification( + controller: controller, + entry: targetEntry, + action: action, + ).dispatch(context); + } + case EntryAction.edit: + appService.edit(targetEntry.uri, targetEntry.mimeType).then((fields) async { + final error = fields['error'] as String?; + if (error == null) { + final resultUri = fields['uri'] as String?; + final mimeType = fields['mimeType'] as String?; + await _handleEditResult(context, resultUri, mimeType); + } else if (error == 'edit-resolve') { + await showNoMatchingAppDialog(context); + } + }); + case EntryAction.open: + appService.open(targetEntry.uri, targetEntry.mimeTypeAnySubtype, forceChooser: true).then((success) { + if (!success) showNoMatchingAppDialog(context); + }); + case EntryAction.openMap: + appService.openMap(targetEntry.latLng!).then((success) { + if (!success) showNoMatchingAppDialog(context); + }); + case EntryAction.setAs: + appService.setAs(targetEntry.uri, targetEntry.mimeType).then((success) { + if (!success) showNoMatchingAppDialog(context); + }); + case EntryAction.cast: + const CastNotification(true).dispatch(context); + // platform + case EntryAction.rotateScreen: + _rotateScreen(context); + // metadata + case EntryAction.editDate: + case EntryAction.editLocation: + case EntryAction.editTitleDescription: + case EntryAction.editRating: + case EntryAction.editTags: + case EntryAction.removeMetadata: + case EntryAction.exportMetadata: + case EntryAction.showGeoTiffOnMap: + case EntryAction.convertMotionPhotoToStillImage: + case EntryAction.viewMotionPhotoVideo: + _metadataActionDelegate.onActionSelected(context, targetEntry, collection, action); + // debug + case EntryAction.debug: + _goToDebug(context, targetEntry); + } + } + + Future<void> _handleEditResult(BuildContext context, String? resultUri, String? mimeType) async { + final _collection = collection; + if (_collection == null || resultUri == null) return; + + final editedEntry = await mediaFetchService.getEntry(resultUri, mimeType); + if (editedEntry == null) { + debugPrint('failed to find edited entry with mimeType=$mimeType uri=$resultUri'); + return; + } + + final editedUri = editedEntry.uri; + final matchCurrentFilters = _collection.filters.every((filter) => filter.test(editedEntry)); + + final l10n = context.l10n; + // get navigator beforehand because + // local context may be deactivated when action is triggered after navigation + final navigator = Navigator.maybeOf(context); + final showAction = SnackBarAction( + label: l10n.showButtonLabel, + onPressed: () { + if (navigator != null) { + final source = _collection.source; + navigator.pushAndRemoveUntil( + MaterialPageRoute( + settings: const RouteSettings(name: CollectionPage.routeName), + builder: (context) => CollectionPage( + source: source, + filters: matchCurrentFilters ? _collection.filters : {}, + highlightTest: (entry) => entry.uri == editedUri, + ), + ), + (route) => false, + ); + } + }, + ); + showFeedback(context, FeedbackType.info, l10n.genericSuccessFeedback, showAction); + } + + Future<void> quickMove(BuildContext context, String destinationAlbum, {required bool copy}) async { + if (!await unlockAlbum(context, destinationAlbum)) return; + + final targetEntry = _getTargetEntry(context, copy ? EntryAction.copy : EntryAction.move); + if (!copy && targetEntry.directory == destinationAlbum) return; + + await doQuickMove( + context, + moveType: copy ? MoveType.copy : MoveType.move, + entriesByDestination: { + destinationAlbum: {targetEntry}, + }, + ); + } + + Future<void> quickShare(BuildContext context, ShareAction action) async { + switch (action) { + case ShareAction.imageOnly: + if (mainEntry.isMotionPhoto) { + final fields = await embeddedDataService.extractMotionPhotoImage(mainEntry); + await _shareMotionPhotoPart(context, fields); + } + case ShareAction.videoOnly: + if (mainEntry.isMotionPhoto) { + final fields = await embeddedDataService.extractMotionPhotoVideo(mainEntry); + await _shareMotionPhotoPart(context, fields); + } + } + } + + Future<void> _shareMotionPhotoPart(BuildContext context, Map fields) async { + final uri = fields['uri'] as String?; + final mimeType = fields['mimeType'] as String?; + if (uri != null && mimeType != null) { + await appService.shareSingle(uri, mimeType).then((success) { + if (!success) showNoMatchingAppDialog(context); + }); + } + } + + void quickRate(BuildContext context, int rating) { + final targetEntry = _getTargetEntry(context, EntryAction.editRating); + _metadataActionDelegate.quickRate(context, targetEntry, rating); + } + + void quickTag(BuildContext context, CollectionFilter filter) { + final targetEntry = _getTargetEntry(context, EntryAction.editTags); + _metadataActionDelegate.quickTag(context, targetEntry, filter); + } + + Future<void> _addShortcut(BuildContext context, AvesEntry targetEntry) async { + final result = await showDialog<(AvesEntry?, String)>( + context: context, + builder: (context) => AddShortcutDialog( + defaultName: targetEntry.bestTitle ?? '', + ), + routeSettings: const RouteSettings(name: AddShortcutDialog.routeName), + ); + if (result == null) return; + + final name = result.$2; + if (name.isEmpty) return; + + await appService.pinToHomeScreen(name, targetEntry, route: EntryViewerPage.routeName, viewUri: targetEntry.uri); + if (!device.showPinShortcutFeedback) { + showFeedback(context, FeedbackType.info, context.l10n.genericSuccessFeedback); + } + } + + Future<void> _flip(BuildContext context, AvesEntry targetEntry) async { + await edit(context, targetEntry, targetEntry.flip); + } + + Future<void> _rotate(BuildContext context, AvesEntry targetEntry, {required bool clockwise}) async { + await edit(context, targetEntry, () => targetEntry.rotate(clockwise: clockwise)); + } + + Future<void> _rotateScreen(BuildContext context) async { + final isPortrait = MediaQuery.orientationOf(context) == Orientation.portrait; + await windowService.requestOrientation(isPortrait ? Orientation.landscape : Orientation.portrait); + } + + Future<void> _delete(BuildContext context, AvesEntry targetEntry) async { + final vault = vaults.getVault(targetEntry.directory); + final enableBin = vault?.useBin ?? settings.enableBin; + + if (enableBin && !targetEntry.trashed) { + await _move(context, targetEntry, moveType: MoveType.toBin); + return; + } + + final l10n = context.l10n; + if (!await showSkippableConfirmationDialog( + context: context, + type: ConfirmationDialog.deleteForever, + message: l10n.deleteEntriesConfirmationDialogMessage(1), + confirmationButtonLabel: l10n.deleteButtonLabel, + )) { + return; + } + + if (!await checkStoragePermission(context, {targetEntry})) return; + + if (!await targetEntry.delete()) { + showFeedback(context, FeedbackType.warn, l10n.genericFailureFeedback); + } else { + final source = context.read<CollectionSource>(); + await source.removeEntries({targetEntry.uri}, includeTrash: true); + EntryDeletedNotification({targetEntry}).dispatch(context); + } + } + + Future<void> _move(BuildContext context, AvesEntry targetEntry, {required MoveType moveType}) => doMove( + context, + moveType: moveType, + entries: {targetEntry}, + ); + + Future<void> _convert(BuildContext context, AvesEntry targetEntry) async { + final options = await showDialog<EntryConvertOptions>( + context: context, + builder: (context) => ConvertEntryDialog(entries: {targetEntry}), + routeSettings: const RouteSettings(name: ConvertEntryDialog.routeName), + ); + if (options == null) return; + + switch (options.action) { + case EntryConvertAction.convert: + await doExport(context, {targetEntry}, options); + case EntryConvertAction.convertMotionPhotoToStillImage: + await _metadataActionDelegate.onActionSelected(context, targetEntry, collection, EntryAction.convertMotionPhotoToStillImage); + } + } + + Future<void> _rename(BuildContext context, AvesEntry targetEntry) async { + final newName = await showDialog<String>( + context: context, + builder: (context) => RenameEntryDialog(entry: targetEntry), + routeSettings: const RouteSettings(name: RenameEntryDialog.routeName), + ); + if (newName == null || newName.isEmpty || newName == targetEntry.filenameWithoutExtension) return; + + // wait for the dialog to hide + await Future.delayed(ADurations.dialogTransitionLoose * timeDilation); + await rename( + context, + entriesToNewName: {targetEntry: '$newName${targetEntry.extension}'}, + persist: _isMainMode(context), + onSuccess: targetEntry.metadataChangeNotifier.notify, + ); + } + + bool _isMainMode(BuildContext context) => context.read<ValueNotifier<AppMode>>().value == AppMode.main; + + void _goToSourceViewer(BuildContext context, AvesEntry targetEntry) { + Navigator.maybeOf(context)?.push( + MaterialPageRoute( + settings: const RouteSettings(name: SourceViewerPage.routeName), + builder: (context) => SourceViewerPage( + loader: () async { + final data = await mediaFetchService.getOriginalBytes(targetEntry); + return utf8.decode(data); + }, + ), + ), + ); + } + + void _goToDebug(BuildContext context, AvesEntry targetEntry) { + Navigator.maybeOf(context)?.push( + MaterialPageRoute( + settings: const RouteSettings(name: ViewerDebugPage.routeName), + builder: (context) => ViewerDebugPage(entry: targetEntry), + ), + ); + } +} diff --git a/lib/widgets/viewer/action/entry_info_action_delegate.dart b/lib/widgets/viewer/action/entry_info_action_delegate.dart new file mode 100644 index 0000000..86c48c0 --- /dev/null +++ b/lib/widgets/viewer/action/entry_info_action_delegate.dart @@ -0,0 +1,294 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:aves/app_mode.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/info.dart'; +import 'package:aves/model/entry/extensions/metadata_edition.dart'; +import 'package:aves/model/entry/extensions/multipage.dart'; +import 'package:aves/model/entry/extensions/props.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/media/geotiff.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/ref/mime_types.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/widgets/common/action_mixins/entry_editor.dart'; +import 'package:aves/widgets/common/action_mixins/feedback.dart'; +import 'package:aves/widgets/common/action_mixins/permission_aware.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:aves/widgets/map/map_page.dart'; +import 'package:aves/widgets/viewer/action/single_entry_editor.dart'; +import 'package:aves/widgets/viewer/debug/debug_page.dart'; +import 'package:aves/widgets/viewer/info/embedded/notifications.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; + +class EntryInfoActionDelegate with FeedbackMixin, PermissionAwareMixin, EntryEditorMixin, SingleEntryEditorMixin { + final StreamController<ActionEvent<EntryAction>> _eventStreamController = StreamController.broadcast(); + + Stream<ActionEvent<EntryAction>> get eventStream => _eventStreamController.stream; + + bool isVisible({ + required AppMode appMode, + required AvesEntry targetEntry, + required EntryAction action, + }) { + final canWrite = appMode.canEditEntry && !settings.isReadOnly; + switch (action) { + // general + case EntryAction.editDate: + case EntryAction.editLocation: + case EntryAction.editTitleDescription: + case EntryAction.editRating: + case EntryAction.editTags: + case EntryAction.removeMetadata: + return canWrite; + case EntryAction.exportMetadata: + return true; + // GeoTIFF + case EntryAction.showGeoTiffOnMap: + return appMode.canNavigate && targetEntry.isGeotiff; + // motion photo + case EntryAction.convertMotionPhotoToStillImage: + return canWrite && targetEntry.isMotionPhoto; + case EntryAction.viewMotionPhotoVideo: + return appMode.canNavigate && targetEntry.isMotionPhoto; + // debug + case EntryAction.debug: + return !kReleaseMode; + default: + return false; + } + } + + bool canApply(AvesEntry targetEntry, EntryAction action) { + switch (action) { + // general + case EntryAction.rotateCCW: + case EntryAction.rotateCW: + return targetEntry.canRotate; + case EntryAction.flip: + return targetEntry.canFlip; + case EntryAction.editDate: + return targetEntry.canEditDate; + case EntryAction.editLocation: + return targetEntry.canEditLocation; + case EntryAction.editTitleDescription: + return targetEntry.canEditTitleDescription; + case EntryAction.editRating: + return targetEntry.canEditRating; + case EntryAction.editTags: + return targetEntry.canEditTags; + case EntryAction.removeMetadata: + return targetEntry.canEdit && targetEntry.isMetadataRemovalSupported; + case EntryAction.exportMetadata: + return !availability.isLocked; + // GeoTIFF + case EntryAction.showGeoTiffOnMap: + return true; + // motion photo + case EntryAction.convertMotionPhotoToStillImage: + return targetEntry.canEdit && targetEntry.isXmpEditionSupported; + case EntryAction.viewMotionPhotoVideo: + return true; + default: + return false; + } + } + + Future<void> onActionSelected(BuildContext context, AvesEntry targetEntry, CollectionLens? collection, EntryAction action) async { + await reportService.log('$runtimeType handles $action'); + _eventStreamController.add(ActionStartedEvent(action)); + switch (action) { + // general + case EntryAction.editDate: + await _editDate(context, targetEntry, collection); + case EntryAction.editLocation: + await _editLocation(context, targetEntry, collection); + case EntryAction.editTitleDescription: + await _editTitleDescription(context, targetEntry); + case EntryAction.editRating: + await _editRating(context, targetEntry); + case EntryAction.editTags: + await _editTags(context, targetEntry); + case EntryAction.removeMetadata: + await _removeMetadata(context, targetEntry); + case EntryAction.exportMetadata: + await _exportMetadata(context, targetEntry); + // GeoTIFF + case EntryAction.showGeoTiffOnMap: + await _showGeoTiffOnMap(context, targetEntry, collection); + // motion photo + case EntryAction.convertMotionPhotoToStillImage: + await _convertMotionPhotoToStillImage(context, targetEntry); + case EntryAction.viewMotionPhotoVideo: + OpenEmbeddedDataNotification.motionPhotoVideo().dispatch(context); + // debug + case EntryAction.debug: + _goToDebug(context, targetEntry); + default: + break; + } + _eventStreamController.add(ActionEndedEvent(action)); + } + + Future<void> _editDate(BuildContext context, AvesEntry targetEntry, CollectionLens? collection) async { + final modifier = await selectDateModifier(context, {targetEntry}, collection); + if (modifier == null) return; + + await edit(context, targetEntry, () => targetEntry.editDate(modifier)); + } + + Future<void> _editLocation(BuildContext context, AvesEntry targetEntry, CollectionLens? collection) async { + final locationByEntry = await selectLocation(context, {targetEntry}, collection); + if (locationByEntry == null) return; + + if (locationByEntry.containsKey(targetEntry)) { + await edit(context, targetEntry, () => targetEntry.editLocation(locationByEntry[targetEntry])); + } + } + + Future<void> _editTitleDescription(BuildContext context, AvesEntry targetEntry) async { + final modifier = await selectTitleDescriptionModifier(context, {targetEntry}); + if (modifier == null) return; + + await edit(context, targetEntry, () => targetEntry.editTitleDescription(modifier)); + } + + Future<void> _editRating(BuildContext context, AvesEntry targetEntry) async { + final rating = await selectRating(context, {targetEntry}); + if (rating == null) return; + + await quickRate(context, targetEntry, rating); + } + + Future<void> quickRate(BuildContext context, AvesEntry targetEntry, int rating) async { + if (targetEntry.rating == rating) return; + + await edit(context, targetEntry, () => targetEntry.editRating(rating)); + } + + Future<void> _editTags(BuildContext context, AvesEntry targetEntry) async { + final tagsByEntry = await selectTags(context, {targetEntry}); + if (tagsByEntry == null) return; + + final newTags = tagsByEntry[targetEntry] ?? targetEntry.tags; + await _applyTags(context, targetEntry, newTags); + } + + Future<void> quickTag(BuildContext context, AvesEntry targetEntry, CollectionFilter filter) async { + final newTags = { + ...targetEntry.tags, + ...await getTagsFromFilters({filter}, targetEntry), + }; + await _applyTags(context, targetEntry, newTags); + } + + Future<void> _applyTags(BuildContext context, AvesEntry targetEntry, Set<String> newTags) async { + final currentTags = targetEntry.tags; + if (newTags.length == currentTags.length && newTags.every(currentTags.contains)) return; + + await edit(context, targetEntry, () => targetEntry.editTags(newTags)); + } + + Future<void> _removeMetadata(BuildContext context, AvesEntry targetEntry) async { + final types = await selectMetadataToRemove(context, {targetEntry}); + if (types == null) return; + + await edit(context, targetEntry, () => targetEntry.removeMetadata(types)); + } + + Future<void> _exportMetadata(BuildContext context, AvesEntry targetEntry) async { + final lines = <String>[]; + final padding = ' ' * 2; + final titledDirectories = await targetEntry.getMetadataDirectories(context); + titledDirectories.forEach((kv) { + final title = kv.key; + final dir = kv.value; + + lines.add('[$title]'); + final dirContent = dir.allTags; + final tags = dirContent.keys.toList()..sort(); + tags.forEach((tag) { + final value = dirContent[tag]; + lines.add('$padding$tag: $value'); + }); + }); + final metadataString = lines.join('\n'); + + final success = await storageService.createFile( + '${targetEntry.filenameWithoutExtension}-metadata.txt', + MimeTypes.plainText, + Uint8List.fromList(utf8.encode(metadataString)), + ); + if (success != null) { + if (success) { + showFeedback(context, FeedbackType.info, context.l10n.genericSuccessFeedback); + } else { + showFeedback(context, FeedbackType.warn, context.l10n.genericFailureFeedback); + } + } + } + + Future<void> _convertMotionPhotoToStillImage(BuildContext context, AvesEntry targetEntry) async { + final l10n = context.l10n; + final confirmed = await showDialog<bool>( + context: context, + builder: (context) => AvesDialog( + content: Text(l10n.genericDangerWarningDialogMessage), + actions: [ + const CancelButton(), + TextButton( + onPressed: () => Navigator.maybeOf(context)?.pop(true), + child: Text(l10n.applyButtonLabel), + ), + ], + ), + routeSettings: const RouteSettings(name: AvesDialog.warningRouteName), + ); + if (confirmed == null || !confirmed) return; + + await edit(context, targetEntry, targetEntry.removeTrailerVideo); + } + + Future<void> _showGeoTiffOnMap(BuildContext context, AvesEntry targetEntry, CollectionLens? collection) async { + final info = await metadataFetchService.getGeoTiffInfo(targetEntry); + if (info == null) return; + + final mappedGeoTiff = MappedGeoTiff( + info: info, + entry: targetEntry, + devicePixelRatio: MediaQuery.devicePixelRatioOf(context), + ); + if (!mappedGeoTiff.canOverlay) return; + + final baseCollection = collection; + if (baseCollection == null) return; + + final mapCollection = baseCollection.copyWith( + listenToSource: true, + fixedSelection: baseCollection.sortedEntries.where((entry) => entry.hasGps).where((entry) => entry != targetEntry).toList(), + ); + await Navigator.maybeOf(context)?.push( + MaterialPageRoute( + settings: const RouteSettings(name: MapPage.routeName), + builder: (context) => MapPage( + collection: mapCollection, + overlayEntry: mappedGeoTiff, + ), + ), + ); + } + + void _goToDebug(BuildContext context, AvesEntry targetEntry) { + Navigator.maybeOf(context)?.push( + MaterialPageRoute( + settings: const RouteSettings(name: ViewerDebugPage.routeName), + builder: (context) => ViewerDebugPage(entry: targetEntry), + ), + ); + } +} diff --git a/lib/widgets/viewer/action/printer.dart b/lib/widgets/viewer/action/printer.dart new file mode 100644 index 0000000..cad13fb --- /dev/null +++ b/lib/widgets/viewer/action/printer.dart @@ -0,0 +1,127 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:math'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/images.dart'; +import 'package:aves/model/entry/extensions/multipage.dart'; +import 'package:aves/model/entry/extensions/props.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/widgets/common/action_mixins/feedback.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:flutter/widgets.dart'; +import 'package:pdf/pdf.dart'; +import 'package:pdf/widgets.dart' as pdf; +import 'package:printing/printing.dart'; + +class EntryPrinter with FeedbackMixin { + final AvesEntry entry; + + static const _fit = pdf.BoxFit.contain; + + EntryPrinter(this.entry); + + Future<void> print(BuildContext context) async { + final documentName = entry.bestTitle ?? context.l10n.appName; + + final imageWidgets = await _buildImageWidgets(context); + if (imageWidgets.isNotEmpty) { + unawaited(Printing.layoutPdf( + onLayout: (pageFormat) { + final doc = pdf.Document(title: documentName); + imageWidgets.map((v) => _buildPdfPage(v, pageFormat)).forEach(doc.addPage); + return doc.save(); + }, + name: documentName, + )); + } + } + + pdf.Page _buildPdfPage(pdf.Widget imageWidget, PdfPageFormat pageFormat) { + final displaySize = entry.displaySize; + final pageTheme = pdf.PageTheme( + pageFormat: pageFormat, + orientation: displaySize.aspectRatio < 1 ? pdf.PageOrientation.portrait : pdf.PageOrientation.landscape, + margin: pdf.EdgeInsets.zero, + theme: null, + clip: false, + textDirection: null, + ); + return pdf.Page( + pageTheme: pageTheme, + build: (context) => pdf.FullPage( + ignoreMargins: true, + child: pdf.Center( + child: pdf.Transform.scale( + scale: min(pageFormat.availableWidth / displaySize.width, pageFormat.availableHeight / displaySize.height), + child: pdf.Transform.rotateBox( + angle: 0, + unconstrained: true, + child: imageWidget, + ), + ), + ), + ), + ); + } + + Future<List<pdf.Widget>> _buildImageWidgets(BuildContext context) async { + final widgets = <pdf.Widget>[]; + + if (entry.isMultiPage && !entry.isMotionPhoto) { + final multiPageInfo = await entry.getMultiPageInfo(); + if (multiPageInfo != null) { + final pageCount = multiPageInfo.pageCount; + if (pageCount > 1) { + final streamController = StreamController<AvesEntry>.broadcast(); + unawaited(showOpReport<AvesEntry>( + context: context, + opStream: streamController.stream, + itemCount: pageCount, + )); + for (var page = 0; page < pageCount; page++) { + final pageEntry = multiPageInfo.getPageEntryByIndex(page); + final widget = await _buildPageImage(context, pageEntry); + if (widget != null) { + widgets.add(widget); + } + streamController.add(pageEntry); + } + await streamController.close(); + } + } + } + + if (widgets.isEmpty) { + final widget = await _buildPageImage(context, entry); + if (widget != null) { + widgets.add(widget); + } + } + + return widgets; + } + + Future<pdf.Widget?> _buildPageImage(BuildContext context, AvesEntry entry) async { + try { + if (entry.isSvg) { + final data = await mediaFetchService.getOriginalBytes(entry); + if (data.isNotEmpty) { + return pdf.SvgImage( + svg: utf8.decode(data), + fit: _fit, + ); + } + } else { + return pdf.Image( + await flutterImageProvider(entry.fullImage), + fit: _fit, + ); + } + } catch (error) { + debugPrint('failed to load image for entry=$entry, error=$error'); + } + showFeedback(context, FeedbackType.warn, context.l10n.genericFailureFeedback); + return null; + } +} diff --git a/lib/widgets/viewer/action/single_entry_editor.dart b/lib/widgets/viewer/action/single_entry_editor.dart new file mode 100644 index 0000000..46adba9 --- /dev/null +++ b/lib/widgets/viewer/action/single_entry_editor.dart @@ -0,0 +1,69 @@ +import 'dart:async'; + +import 'package:aves/app_mode.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/catalog.dart'; +import 'package:aves/model/entry/extensions/location.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/widgets/common/action_mixins/feedback.dart'; +import 'package:aves/widgets/common/action_mixins/permission_aware.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +mixin SingleEntryEditorMixin on FeedbackMixin, PermissionAwareMixin { + bool _isMainMode(BuildContext context) => context.read<ValueNotifier<AppMode>>().value == AppMode.main; + + Future<void> edit(BuildContext context, AvesEntry targetEntry, Future<Set<EntryDataType>> Function() apply) async { + if (!await checkStoragePermission(context, {targetEntry})) return; + + // check before applying, because it relies on provider + // but the widget tree may be disposed if the user navigated away + final isMainMode = _isMainMode(context); + + final l10n = context.l10n; + final source = context.read<CollectionSource?>(); + source?.pauseMonitoring(); + + final dataTypes = await apply(); + final success = dataTypes.isNotEmpty; + try { + if (success) { + if (isMainMode && source != null) { + Set<String> obsoleteTags = targetEntry.tags; + String? obsoleteCountryCode = targetEntry.addressDetails?.countryCode; + String? obsoleteStateCode = targetEntry.addressDetails?.stateCode; + + await source.refreshEntries({targetEntry}, dataTypes); + + // invalidate filters derived from values before edition + // this invalidation must happen after the source is refreshed, + // otherwise filter chips may eagerly rebuild in between with the old state + if (obsoleteCountryCode != null) { + source.invalidateCountryFilterSummary(countryCodes: {obsoleteCountryCode}); + } + if (obsoleteStateCode != null) { + source.invalidateStateFilterSummary(stateCodes: {obsoleteStateCode}); + } + if (obsoleteTags.isNotEmpty) { + source.invalidateTagFilterSummary(tags: obsoleteTags); + } + } else { + const background = false; + const persist = false; + await targetEntry.refresh(background: background, persist: persist, dataTypes: dataTypes); + await targetEntry.catalog(background: background, force: dataTypes.contains(EntryDataType.catalog), persist: persist); + await targetEntry.locate(background: background, force: dataTypes.contains(EntryDataType.address), geocoderLocale: settings.appliedLocale); + } + showFeedback(context, FeedbackType.info, l10n.genericSuccessFeedback); + } else { + showFeedback(context, FeedbackType.warn, l10n.genericFailureFeedback); + } + } catch (e, stack) { + await reportService.recordError(e, stack); + } + source?.resumeMonitoring(); + } +} diff --git a/lib/widgets/viewer/action/video_action_delegate.dart b/lib/widgets/viewer/action/video_action_delegate.dart new file mode 100644 index 0000000..bab287e --- /dev/null +++ b/lib/widgets/viewer/action/video_action_delegate.dart @@ -0,0 +1,238 @@ +import 'dart:async'; +import 'dart:math'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/keys.dart'; +import 'package:aves/model/entry/extensions/location.dart'; +import 'package:aves/model/entry/extensions/props.dart'; +import 'package:aves/model/filters/covered/stored_album.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/services/media/enums.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/utils/android_file_utils.dart'; +import 'package:aves/widgets/collection/collection_page.dart'; +import 'package:aves/widgets/common/action_mixins/feedback.dart'; +import 'package:aves/widgets/common/action_mixins/permission_aware.dart'; +import 'package:aves/widgets/common/action_mixins/size_aware.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:aves/widgets/dialogs/video_speed_dialog.dart'; +import 'package:aves/widgets/dialogs/video_stream_selection_dialog.dart'; +import 'package:aves/widgets/settings/video/video_settings_page.dart'; +import 'package:aves/widgets/viewer/controls/notifications.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:aves_video/aves_video.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:leak_tracker/leak_tracker.dart'; +import 'package:provider/provider.dart'; + +class VideoActionDelegate with FeedbackMixin, PermissionAwareMixin, SizeAwareMixin { + Timer? _overlayHidingTimer; + final CollectionLens? collection; + + VideoActionDelegate({ + required this.collection, + }) { + if (kFlutterMemoryAllocationsEnabled) { + LeakTracking.dispatchObjectCreated( + library: 'aves', + className: '$VideoActionDelegate', + object: this, + ); + } + } + + void dispose() { + if (kFlutterMemoryAllocationsEnabled) { + LeakTracking.dispatchObjectDisposed(object: this); + } + stopOverlayHidingTimer(); + } + + Future<void> onActionSelected(BuildContext context, AvesEntry entry, AvesVideoController controller, EntryAction action) async { + // make sure overlay is not disappearing when selecting an action + stopOverlayHidingTimer(); + const ToggleOverlayNotification(visible: true).dispatch(context); + + switch (action) { + case EntryAction.videoCaptureFrame: + await _captureFrame(context, entry, controller); + case EntryAction.videoToggleMute: + await controller.mute(!controller.isMuted); + case EntryAction.videoSelectStreams: + await _showStreamSelectionDialog(context, controller); + case EntryAction.videoSetSpeed: + await _showSpeedDialog(context, controller); + case EntryAction.videoABRepeat: + controller.toggleABRepeat(); + case EntryAction.videoSettings: + await _showSettings(context, controller); + case EntryAction.videoTogglePlay: + await _togglePlayPause(context, controller); + case EntryAction.videoReplay10: + await controller.seekTo(max(controller.currentPosition - 10000, 0)); + case EntryAction.videoSkip10: + await controller.seekTo(controller.currentPosition + 10000); + case EntryAction.videoShowPreviousFrame: + await controller.skipFrames(-1); + case EntryAction.videoShowNextFrame: + await controller.skipFrames(1); + case EntryAction.openVideoPlayer: + await appService.open(entry.uri, entry.mimeTypeAnySubtype, forceChooser: false).then((success) { + if (!success) showNoMatchingAppDialog(context); + }); + default: + throw UnsupportedError('$action is not a video action'); + } + } + + Future<void> _captureFrame(BuildContext context, AvesEntry entry, AvesVideoController controller) async { + final destinationAlbum = androidFileUtils.avesVideoCapturesPath; + final positionMillis = controller.currentPosition; + final Map<String, dynamic> newFields = {}; + + final bytes = await controller.captureFrame(); + if (bytes != null) { + if (!await checkStoragePermissionForAlbums(context, {destinationAlbum})) return; + + if (!await checkFreeSpace(context, bytes.length, destinationAlbum)) return; + + final rotationDegrees = entry.rotationDegrees; + final dateTimeMillis = entry.catalogMetadata?.dateMillis; + final latLng = entry.latLng; + final exif = { + if (rotationDegrees != 0) 'rotationDegrees': rotationDegrees, + if (dateTimeMillis != null && dateTimeMillis != 0) 'dateTimeMillis': dateTimeMillis, + if (latLng != null) ...{ + 'latitude': latLng.latitude, + 'longitude': latLng.longitude, + } + }; + + newFields.addAll(await mediaEditService.captureFrame( + entry, + desiredName: '${entry.bestTitle}_${'$positionMillis'.padLeft(8, '0')}', + exif: exif, + bytes: bytes, + destinationAlbum: destinationAlbum, + nameConflictStrategy: NameConflictStrategy.rename, + )); + } + final success = newFields.isNotEmpty; + + final l10n = context.l10n; + if (success) { + final _collection = collection; + // get navigator beforehand because + // local context may be deactivated when action is triggered after navigation + final navigator = Navigator.maybeOf(context); + final showAction = _collection != null + ? SnackBarAction( + label: l10n.showButtonLabel, + onPressed: () { + if (navigator != null) { + final source = _collection.source; + final newUri = newFields[EntryFields.uri] as String?; + navigator.pushAndRemoveUntil( + MaterialPageRoute( + settings: const RouteSettings(name: CollectionPage.routeName), + builder: (context) => CollectionPage( + source: source, + filters: {StoredAlbumFilter(destinationAlbum, source.getStoredAlbumDisplayName(context, destinationAlbum))}, + highlightTest: (entry) => entry.uri == newUri, + ), + ), + (route) => false, + ); + } + }, + ) + : null; + showFeedback(context, FeedbackType.info, l10n.genericSuccessFeedback, showAction); + } else { + showFeedback(context, FeedbackType.warn, l10n.genericFailureFeedback); + } + } + + Future<void> _showStreamSelectionDialog(BuildContext context, AvesVideoController controller) async { + final streams = controller.streams; + final currentSelectedStreams = await Future.wait(MediaStreamType.values.map(controller.getSelectedStream)); + + final userSelectedStreams = await showDialog<Map<MediaStreamType, MediaStreamSummary?>>( + context: context, + builder: (context) => VideoStreamSelectionDialog( + streams: Map.fromEntries(streams.map((stream) { + final selectedStream = currentSelectedStreams.nonNulls.firstWhereOrNull((v) => v.type == stream.type); + final selected = selectedStream != null && selectedStream.index == stream.index; + return MapEntry(stream, selected); + })), + ), + routeSettings: const RouteSettings(name: VideoStreamSelectionDialog.routeName), + ); + if (userSelectedStreams == null || userSelectedStreams.isEmpty) return; + + await Future.forEach<MapEntry<MediaStreamType, MediaStreamSummary?>>( + userSelectedStreams.entries, + (kv) => controller.selectStream(kv.key, kv.value), + ); + } + + Future<void> _showSpeedDialog(BuildContext context, AvesVideoController controller) async { + final newSpeed = await showDialog<double>( + context: context, + builder: (context) => VideoSpeedDialog( + current: controller.speed, + min: controller.minSpeed, + max: controller.maxSpeed, + ), + routeSettings: const RouteSettings(name: VideoSpeedDialog.routeName), + ); + if (newSpeed == null) return; + + controller.speed = newSpeed; + } + + Future<void> _showSettings(BuildContext context, AvesVideoController controller) async { + int? resumePosition; + if (controller.isPlaying) { + resumePosition = controller.currentPosition; + await controller.pause(); + } + await Navigator.maybeOf(context)?.push( + MaterialPageRoute( + settings: const RouteSettings(name: VideoSettingsPage.routeName), + builder: (context) => const VideoSettingsPage(), + ), + ); + if (resumePosition != null) { + if (!controller.isReady) { + await controller.seekTo(resumePosition); + } + await controller.play(); + } + } + + Future<void> _togglePlayPause(BuildContext context, AvesVideoController controller) async { + if (!context.mounted) return; + + if (controller.isPlaying) { + await controller.pause(); + } else { + final resumeTimeMillis = await controller.getResumeTime(context); + if (resumeTimeMillis != null) { + await controller.seekTo(resumeTimeMillis); + } else { + await controller.play(); + } + // hide overlay + _overlayHidingTimer = Timer(context.read<DurationsData>().iconAnimation + ADurations.videoOverlayHideDelay, () { + const ToggleOverlayNotification(visible: false).dispatch(context); + }); + } + } + + void stopOverlayHidingTimer() => _overlayHidingTimer?.cancel(); +} diff --git a/lib/widgets/viewer/controls/cast.dart b/lib/widgets/viewer/controls/cast.dart new file mode 100644 index 0000000..e442fc9 --- /dev/null +++ b/lib/widgets/viewer/controls/cast.dart @@ -0,0 +1,167 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/props.dart'; +import 'package:aves/ref/upnp.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/widgets/dialogs/cast_dialog.dart'; +import 'package:collection/collection.dart'; +import 'package:dlna_dart/dlna.dart'; +import 'package:dlna_dart/xmlParser.dart'; +import 'package:flutter/material.dart'; +import 'package:network_info_plus/network_info_plus.dart'; +import 'package:shelf/shelf.dart'; +import 'package:shelf/shelf_io.dart' as shelf_io; +import 'package:xml/xml.dart'; + +mixin CastMixin { + DLNADevice? _renderer; + HttpServer? _mediaServer; + + bool get isCasting => _renderer != null && _mediaServer != null; + + Future<void> initCast(BuildContext context, List<AvesEntry> entries) async { + await stopCast(); + + final renderer = await _selectRenderer(context); + _renderer = renderer; + if (renderer == null) return; + debugPrint('cast: select renderer `${renderer.info.friendlyName}` at ${renderer.info.URLBase}'); + + final ip = await NetworkInfo().getWifiIP(); + if (ip == null) return; + + Set<String>? supportedMimeTypes; + + final handler = const Pipeline().addHandler((request) async { + debugPrint('cast: received request for id=${request.url}'); + final id = int.tryParse(request.url.path); + if (id == null) { + return Response.notFound('invalid url=${request.url}'); + } + + final entry = entries.firstWhereOrNull((v) => v.id == id); + if (entry == null) { + return Response.notFound('no resource for url=${request.url}'); + } + + if (supportedMimeTypes == null) { + // do not call `GetProtocolInfo` before serving files, + // as it somehow makes `Play` time out (but not `SetAVTransportURI`) + supportedMimeTypes = await renderer.getSinkSupportedMimeTypes(); + debugPrint('cast: supported MIME types=$supportedMimeTypes'); + } + + // TODO TLAD [cast] transcode when MIME type is not supported by renderer + + return await _sendEntry(entry); + }); + _mediaServer = await shelf_io.serve(handler, ip, 8080); + debugPrint('cast: serving media on $_serverBaseUrl'); + } + + Future<void> stopCast() async { + if (isCasting) { + debugPrint('cast: stop'); + } + + await _mediaServer?.close(); + _mediaServer = null; + + await _renderer?.stop(); + _renderer = null; + } + + Future<DLNADevice?> _selectRenderer(BuildContext context) async { + return await showDialog<DLNADevice?>( + context: context, + builder: (context) => const CastDialog(), + routeSettings: const RouteSettings(name: CastDialog.routeName), + ); + } + + Future<void> castEntry(AvesEntry entry) async { + final server = _mediaServer; + final renderer = _renderer; + if (server == null || renderer == null) return; + + try { + debugPrint('cast: set entry=$entry'); + await renderer.setUrl( + '$_serverBaseUrl/${entry.id}', + title: entry.bestTitle ?? '', + type: entry.isVideo ? PlayType.Video : PlayType.Image, + ); + debugPrint('cast: play entry=$entry'); + unawaited(renderer.play()); + } catch (e, stack) { + await reportService.recordError(e, stack); + } + } + + String? get _serverBaseUrl { + final server = _mediaServer; + return server != null ? 'http://${server.address.host}:${server.port}' : null; + } + + Future<Response> _sendEntry(AvesEntry entry) async { + // TODO TLAD [cast] providing downscaled versions is suitable when properly serving with `MediaServer`, as the renderer can pick what is best + final bytes = await mediaFetchService.getOriginalBytes(entry); + + debugPrint('cast: send ${bytes.length} bytes for entry=$entry'); + return Response.ok( + bytes, + headers: { + 'Content-Type': entry.mimeType, + }, + ); + } +} + +extension ExtraDLNADevice on DLNADevice { + Future<String> requestCustom({ + required String serviceId, + required String serviceType, + required String action, + required String data, + }) async { + return DLNAHttp.post( + Uri.parse(controlURL(serviceId)), + Map.from({ + 'SOAPAction': '"$serviceType#$action"', + 'Content-Type': 'text/xml', + }), + const Utf8Encoder().convert(data), + ); + } + + Future<Map<String, UpnpProtocolInfo>> getProtocolInfo() async { + final result = await requestCustom( + serviceId: 'ConnectionManager', + serviceType: Upnp.upnpServiceTypeConnectionManager, + action: 'GetProtocolInfo', + data: Upnp.getProtocolInfoActionXml(), + ); + final doc = XmlDocument.parse(result); + final sink = UpnpProtocolInfo(doc.findAllElements('Sink').first.innerText); + final source = UpnpProtocolInfo(doc.findAllElements('Source').first.innerText); + return { + 'sink': sink, + 'source': source, + }; + } + + Future<Set<String>?> getSinkSupportedMimeTypes() async { + final sinkProtocolInfo = (await getProtocolInfo())['sink']; + if (sinkProtocolInfo != null) { + final byProtocol = groupBy<UpnpProtocolInfoEntry, String>(sinkProtocolInfo.entries, (v) => v.protocol); + final httpGet = byProtocol['http-get']; + if (httpGet != null) { + return httpGet.map((v) => v.contentFormat).toSet(); + } + } + return null; + } +} diff --git a/lib/widgets/viewer/controls/controller.dart b/lib/widgets/viewer/controls/controller.dart new file mode 100644 index 0000000..78d55c1 --- /dev/null +++ b/lib/widgets/viewer/controls/controller.dart @@ -0,0 +1,155 @@ +import 'dart:async'; +import 'dart:math'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/widgets/viewer/controls/cast.dart'; +import 'package:aves/widgets/viewer/controls/events.dart'; +import 'package:aves_magnifier/aves_magnifier.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; +import 'package:leak_tracker/leak_tracker.dart'; + +class ViewerController with CastMixin { + final ValueNotifier<AvesEntry?> entryNotifier = ValueNotifier(null); + final ViewerTransition transition; + final Duration? autopilotInterval; + final bool autopilotAnimatedZoom; + final bool repeat; + + late final ScaleLevel _initialScale; + late final ValueNotifier<bool> _autopilotNotifier; + Timer? _playTimer; + final StreamController _streamController = StreamController.broadcast(); + final Map<TickerProvider, _AutopilotAnimators> _autopilotAnimators = {}; + ScaleLevel? _autopilotInitialScale; + + Stream<dynamic> get _events => _streamController.stream; + + Stream<ViewerShowNextEvent> get showNextCommands => _events.where((event) => event is ViewerShowNextEvent).cast<ViewerShowNextEvent>(); + + Stream<ViewerOverlayToggleEvent> get overlayCommands => _events.where((event) => event is ViewerOverlayToggleEvent).cast<ViewerOverlayToggleEvent>(); + + bool get autopilot => _autopilotNotifier.value; + + set autopilot(bool enabled) => _autopilotNotifier.value = enabled; + + ScaleLevel get initialScale => _autopilotInitialScale ?? _initialScale; + + static final _autopilotScaleTweens = [ + Tween<double>(begin: 1, end: 1.2), + Tween<double>(begin: 1.2, end: 1), + ]; + + ViewerController({ + ScaleLevel initialScale = const ScaleLevel(ref: ScaleReference.contained), + this.transition = ViewerTransition.parallax, + this.repeat = false, + bool autopilot = false, + this.autopilotInterval, + this.autopilotAnimatedZoom = false, + }) { + if (kFlutterMemoryAllocationsEnabled) { + LeakTracking.dispatchObjectCreated( + library: 'aves', + className: '$ViewerController', + object: this, + ); + } + _initialScale = initialScale; + entryNotifier.addListener(_onEntryChanged); + _autopilotNotifier = ValueNotifier(autopilot); + _autopilotNotifier.addListener(_onAutopilotChanged); + _onAutopilotChanged(); + } + + void dispose() { + if (kFlutterMemoryAllocationsEnabled) { + LeakTracking.dispatchObjectDisposed(object: this); + } + entryNotifier.removeListener(_onEntryChanged); + windowService.setColorMode(wideColorGamut: false, hdr: false); + _autopilotNotifier.dispose(); + _clearAutopilotAnimations(); + _stopPlayTimer(); + _streamController.close(); + } + + Future<void> _onEntryChanged() async { + if (await windowService.supportsHdr()) { + await windowService.setColorMode( + wideColorGamut: false, + hdr: entryNotifier.value?.isHdr ?? false, + ); + } + } + + void _onAutopilotChanged() { + _clearAutopilotAnimations(); + _stopPlayTimer(); + if (autopilot && autopilotInterval != null) { + _playTimer = Timer.periodic(autopilotInterval!, (_) => _streamController.add(ViewerShowNextEvent())); + _streamController.add(const ViewerOverlayToggleEvent(visible: false)); + } + } + + void _stopPlayTimer() => _playTimer?.cancel(); + + void _clearAutopilotAnimations() => _autopilotAnimators.keys.toSet().forEach((v) => stopAutopilotAnimation(vsync: v)); + + void stopAutopilotAnimation({required TickerProvider vsync}) { + final animationController = _autopilotAnimators.remove(vsync); + return animationController?.dispose(); + } + + void startAutopilotAnimation({ + required TickerProvider vsync, + required void Function({required ScaleLevel scaleLevel}) onUpdate, + }) { + stopAutopilotAnimation(vsync: vsync); + if (!autopilot || !autopilotAnimatedZoom) return; + + final scaleLevelRef = _initialScale.ref; + final scaleFactorTween = _autopilotScaleTweens[Random().nextInt(_autopilotScaleTweens.length)]; + _autopilotInitialScale = ScaleLevel(ref: scaleLevelRef, factor: scaleFactorTween.begin!); + + final animationController = AnimationController( + duration: autopilotInterval, + vsync: vsync, + ); + final animation = CurvedAnimation( + parent: animationController, + curve: Curves.linear, + ); + animationController.addListener(() { + return onUpdate.call( + scaleLevel: ScaleLevel( + ref: scaleLevelRef, + factor: scaleFactorTween.evaluate(animation), + ), + ); + }); + _autopilotAnimators[vsync] = _AutopilotAnimators( + controller: animationController, + animation: animation, + ); + Future.delayed(ADurations.viewerHorizontalPageAnimation).then((_) => _autopilotAnimators[vsync]?.controller.forward()); + } +} + +class _AutopilotAnimators { + final AnimationController controller; + final CurvedAnimation animation; + + _AutopilotAnimators({ + required this.controller, + required this.animation, + }); + + void dispose() { + animation.dispose(); + controller.dispose(); + } +} diff --git a/lib/widgets/viewer/controls/events.dart b/lib/widgets/viewer/controls/events.dart new file mode 100644 index 0000000..e39c97e --- /dev/null +++ b/lib/widgets/viewer/controls/events.dart @@ -0,0 +1,11 @@ +import 'package:flutter/foundation.dart'; + +@immutable +class ViewerShowNextEvent {} + +@immutable +class ViewerOverlayToggleEvent { + final bool? visible; + + const ViewerOverlayToggleEvent({required this.visible}); +} diff --git a/lib/widgets/viewer/controls/intents.dart b/lib/widgets/viewer/controls/intents.dart new file mode 100644 index 0000000..66c76de --- /dev/null +++ b/lib/widgets/viewer/controls/intents.dart @@ -0,0 +1,50 @@ +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/widgets.dart'; + +class ShowPreviousIntent extends Intent { + const ShowPreviousIntent(); +} + +class ShowNextIntent extends Intent { + const ShowNextIntent(); +} + +class LeaveIntent extends Intent { + const LeaveIntent(); +} + +class ShowInfoIntent extends Intent { + const ShowInfoIntent(); +} + +class TvShowLessInfoIntent extends Intent { + const TvShowLessInfoIntent(); +} + +class TvShowMoreInfoIntent extends Intent { + const TvShowMoreInfoIntent(); +} + +class PlayPauseIntent extends Intent { + final TvPlayPauseType type; + + const PlayPauseIntent.play() : type = TvPlayPauseType.play; + + const PlayPauseIntent.pause() : type = TvPlayPauseType.pause; + + const PlayPauseIntent.toggle() : type = TvPlayPauseType.toggle; +} + +enum TvPlayPauseType { + play, + pause, + toggle, +} + +class EntryActionIntent extends Intent { + final EntryAction action; + + const EntryActionIntent({ + required this.action, + }); +} diff --git a/lib/widgets/viewer/controls/notifications.dart b/lib/widgets/viewer/controls/notifications.dart new file mode 100644 index 0000000..29ac67f --- /dev/null +++ b/lib/widgets/viewer/controls/notifications.dart @@ -0,0 +1,141 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:aves_video/aves_video.dart'; +import 'package:equatable/equatable.dart'; +import 'package:flutter/widgets.dart'; + +@immutable +class LockViewNotification extends Notification { + final bool locked; + + const LockViewNotification({required this.locked}); +} + +@immutable +class PopVisualNotification extends Notification {} + +@immutable +class ShowImageNotification extends Notification {} + +@immutable +class ShowInfoPageNotification extends Notification {} + +@immutable +class ShowPreviousEntryNotification extends Notification { + final bool animate; + + const ShowPreviousEntryNotification({required this.animate}); +} + +@immutable +class ShowNextEntryNotification extends Notification { + final bool animate; + + const ShowNextEntryNotification({required this.animate}); +} + +@immutable +class ShowEntryNotification extends Notification { + final bool animate; + final int index; + + const ShowEntryNotification({ + required this.animate, + required this.index, + }); +} + +@immutable +class ShowPreviousVideoNotification extends Notification {} + +@immutable +class ShowNextVideoNotification extends Notification {} + +@immutable +class ToggleOverlayNotification extends Notification { + final bool? visible; + + const ToggleOverlayNotification({this.visible}); +} + +@immutable +class TvShowLessInfoNotification extends Notification {} + +@immutable +class TvShowMoreInfoNotification extends Notification {} + +@immutable +class VideoActionNotification extends Notification { + final AvesVideoController controller; + final AvesEntry entry; + final EntryAction action; + + const VideoActionNotification({ + required this.controller, + required this.entry, + required this.action, + }); +} + +@immutable +class CastNotification extends Notification with EquatableMixin { + final bool enabled; + + @override + List<Object?> get props => [enabled]; + + const CastNotification(this.enabled); +} + +@immutable +class SelectFilterNotification extends Notification with EquatableMixin { + final CollectionFilter filter; + + @override + List<Object?> get props => [filter]; + + const SelectFilterNotification(this.filter); +} + +@immutable +class DecomposeFilterNotification extends Notification with EquatableMixin { + final CollectionFilter filter; + + @override + List<Object?> get props => [filter]; + + const DecomposeFilterNotification(this.filter); +} + +@immutable +class EntryDeletedNotification extends Notification with EquatableMixin { + final Set<AvesEntry> entries; + + @override + List<Object?> get props => [entries]; + + const EntryDeletedNotification(this.entries); +} + +@immutable +class EntryMovedNotification extends Notification with EquatableMixin { + final MoveType moveType; + final Set<AvesEntry> entries; + + @override + List<Object?> get props => [moveType, entries]; + + const EntryMovedNotification(this.moveType, this.entries); +} + +@immutable +class FullImageLoadedNotification extends Notification { + final AvesEntry entry; + final ImageProvider image; + + const FullImageLoadedNotification(this.entry, this.image); +} + +@immutable +class PopupMenuOpenedNotification extends Notification {} diff --git a/lib/widgets/viewer/controls/shortcuts.dart b/lib/widgets/viewer/controls/shortcuts.dart new file mode 100644 index 0000000..25c0b0a --- /dev/null +++ b/lib/widgets/viewer/controls/shortcuts.dart @@ -0,0 +1,34 @@ +import 'package:aves/widgets/viewer/controls/intents.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; + +class ViewerShortcuts { + static const entryActions = { + SingleActivator(LogicalKeyboardKey.delete): EntryActionIntent(action: EntryAction.delete), + }; + +// cf https://developer.android.com/training/tv/start/controllers#media-events + static const media = { + // KEYCODE_MEDIA_PLAY_PAUSE / 85 / play/pause + SingleActivator(LogicalKeyboardKey.mediaPlayPause): PlayPauseIntent.toggle(), + // KEYCODE_MEDIA_STOP / 86 / stop + SingleActivator(LogicalKeyboardKey.mediaStop): PlayPauseIntent.pause(), + // KEYCODE_MEDIA_NEXT / 87 / skip to next + SingleActivator(LogicalKeyboardKey.mediaTrackNext): ShowNextIntent(), + // KEYCODE_MEDIA_PREVIOUS / 88 / skip to previous + SingleActivator(LogicalKeyboardKey.mediaTrackPrevious): ShowPreviousIntent(), + // KEYCODE_MEDIA_PLAY / 126 / play + SingleActivator(LogicalKeyboardKey.mediaPlay): PlayPauseIntent.play(), + // KEYCODE_MEDIA_PAUSE / 127 / pause + SingleActivator(LogicalKeyboardKey.mediaPause): PlayPauseIntent.pause(), + // KEYCODE_BUTTON_L1 / 102 / skip to previous + SingleActivator(LogicalKeyboardKey.gameButtonLeft1): ShowPreviousIntent(), + // KEYCODE_BUTTON_R1 / 103 / skip to next + SingleActivator(LogicalKeyboardKey.gameButtonRight1): ShowNextIntent(), + // KEYCODE_BUTTON_START / 108 / pause + SingleActivator(LogicalKeyboardKey.gameButtonStart): PlayPauseIntent.pause(), + // KEYCODE_BUTTON_SELECT / 109 / play/pause + SingleActivator(LogicalKeyboardKey.gameButtonSelect): PlayPauseIntent.toggle(), + }; +} diff --git a/lib/widgets/viewer/controls/transitions.dart b/lib/widgets/viewer/controls/transitions.dart new file mode 100644 index 0000000..0adf9b8 --- /dev/null +++ b/lib/widgets/viewer/controls/transitions.dart @@ -0,0 +1,78 @@ +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:flutter/widgets.dart'; + +class PageTransitionEffects { + static TransitionBuilder fade( + PageController pageController, + int index, { + required bool zoomIn, + }) => + (context, child) { + double opacity = 0; + double dx = 0; + double scale = 1; + if (pageController.hasClients && pageController.position.haveDimensions) { + final position = (pageController.page! - index).clamp(-1.0, 1.0); + final width = pageController.position.viewportDimension; + opacity = (1 - position.abs()).clamp(0, 1); + dx = position * width * (context.isRtl ? -1 : 1); + if (zoomIn) { + scale = 1 + position; + } + } + return Opacity( + opacity: opacity, + child: Transform.translate( + offset: Offset(dx, 0), + child: Transform.scale( + scale: scale, + child: child, + ), + ), + ); + }; + + static TransitionBuilder slide( + PageController pageController, + int index, { + required bool parallax, + }) => + (context, child) { + double dx = 0; + if (pageController.hasClients && pageController.position.haveDimensions) { + final position = (pageController.page! - index).clamp(-1.0, 1.0); + final width = pageController.position.viewportDimension; + if (parallax) { + dx = position * width / 2 * (context.isRtl ? -1 : 1); + } + } + return ClipRect( + child: Transform.translate( + offset: Offset(dx, 0), + child: child, + ), + ); + }; + + static TransitionBuilder none( + PageController pageController, + int index, + ) => + (context, child) { + double opacity = 0; + double dx = 0; + if (pageController.hasClients && pageController.position.haveDimensions) { + final position = (pageController.page! - index).clamp(-1.0, 1.0); + final width = pageController.position.viewportDimension; + opacity = (1 - position.abs()).roundToDouble().clamp(0, 1); + dx = position * width * (context.isRtl ? -1 : 1); + } + return Opacity( + opacity: opacity, + child: Transform.translate( + offset: Offset(dx, 0), + child: child, + ), + ); + }; +} diff --git a/lib/widgets/viewer/debug/db.dart b/lib/widgets/viewer/debug/db.dart new file mode 100644 index 0000000..c0dfe4c --- /dev/null +++ b/lib/widgets/viewer/debug/db.dart @@ -0,0 +1,206 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/metadata/address.dart'; +import 'package:aves/model/metadata/catalog.dart'; +import 'package:aves/model/metadata/trash.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/model/viewer/video_playback.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/widgets/viewer/info/common.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class DbTab extends StatefulWidget { + final AvesEntry entry; + + const DbTab({ + super.key, + required this.entry, + }); + + @override + State<DbTab> createState() => _DbTabState(); +} + +class _DbTabState extends State<DbTab> { + late Future<int?> _dbDateLoader; + late Future<AvesEntry?> _dbEntryLoader; + late Future<CatalogMetadata?> _dbMetadataLoader; + late Future<AddressDetails?> _dbAddressLoader; + late Future<TrashDetails?> _dbTrashDetailsLoader; + late Future<VideoPlaybackRow?> _dbVideoPlaybackLoader; + + AvesEntry get entry => widget.entry; + + @override + void initState() { + super.initState(); + _loadDatabase(); + } + + void _loadDatabase() { + final id = entry.id; + _dbDateLoader = localMediaDb.loadDates().then((values) => values[id]); + _dbEntryLoader = localMediaDb.loadEntriesById({id}).then((values) => values.firstOrNull); + _dbMetadataLoader = localMediaDb.loadCatalogMetadata().then((values) => values.firstWhereOrNull((row) => row.id == id)); + _dbAddressLoader = localMediaDb.loadAddresses().then((values) => values.firstWhereOrNull((row) => row.id == id)); + _dbTrashDetailsLoader = localMediaDb.loadAllTrashDetails().then((values) => values.firstWhereOrNull((row) => row.id == id)); + _dbVideoPlaybackLoader = localMediaDb.loadVideoPlayback(id); + setState(() {}); + } + + @override + Widget build(BuildContext context) { + return ListView( + padding: const EdgeInsets.all(16), + children: [ + FutureBuilder<int?>( + future: _dbDateLoader, + builder: (context, snapshot) { + if (snapshot.hasError) return Text(snapshot.error.toString()); + if (snapshot.connectionState != ConnectionState.done) return const SizedBox(); + final data = snapshot.data; + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('DB date:${data == null ? ' no row' : ''}'), + if (data != null) + InfoRowGroup( + info: { + 'dateMillis': '$data', + }, + ), + ], + ); + }, + ), + const SizedBox(height: 16), + FutureBuilder<AvesEntry?>( + future: _dbEntryLoader, + builder: (context, snapshot) { + if (snapshot.hasError) return Text(snapshot.error.toString()); + if (snapshot.connectionState != ConnectionState.done) return const SizedBox(); + final data = snapshot.data; + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('DB entry:${data == null ? ' no row' : ''}'), + if (data != null) ...[ + ElevatedButton( + onPressed: () async { + final source = context.read<CollectionSource>(); + await source.removeEntries({entry.uri}, includeTrash: true); + }, + child: const Text('Untrack entry'), + ), + ElevatedButton( + onPressed: () async { + final duplicates = {entry.copyWith(id: localMediaDb.nextId)}; + final source = context.read<CollectionSource>(); + source.addEntries(duplicates); + await localMediaDb.insertEntries(duplicates); + }, + child: const Text('Duplicate entry'), + ), + InfoRowGroup( + info: Map.fromEntries(data.toDatabaseMap().entries.map((kv) => MapEntry(kv.key, kv.value?.toString() ?? ''))), + ), + ], + ], + ); + }, + ), + const SizedBox(height: 16), + FutureBuilder<CatalogMetadata?>( + future: _dbMetadataLoader, + builder: (context, snapshot) { + if (snapshot.hasError) return Text(snapshot.error.toString()); + if (snapshot.connectionState != ConnectionState.done) return const SizedBox(); + final data = snapshot.data; + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('DB metadata:${data == null ? ' no row' : ''}'), + if (data != null) + InfoRowGroup( + info: Map.fromEntries(data.toMap().entries.map((kv) => MapEntry(kv.key, kv.value?.toString() ?? ''))), + ), + ], + ); + }, + ), + const SizedBox(height: 16), + FutureBuilder<AddressDetails?>( + future: _dbAddressLoader, + builder: (context, snapshot) { + if (snapshot.hasError) return Text(snapshot.error.toString()); + if (snapshot.connectionState != ConnectionState.done) return const SizedBox(); + final data = snapshot.data; + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('DB address:${data == null ? ' no row' : ''}'), + if (data != null) + InfoRowGroup( + info: Map.fromEntries(data.toMap().entries.map((kv) => MapEntry(kv.key, kv.value?.toString() ?? ''))), + ), + ], + ); + }, + ), + const SizedBox(height: 16), + FutureBuilder<TrashDetails?>( + future: _dbTrashDetailsLoader, + builder: (context, snapshot) { + if (snapshot.hasError) return Text(snapshot.error.toString()); + if (snapshot.connectionState != ConnectionState.done) return const SizedBox(); + final data = snapshot.data; + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('DB trash details:${data == null ? ' no row' : ''}'), + if (data != null) ...[ + ElevatedButton( + onPressed: () async { + entry.trashDetails = null; + await localMediaDb.updateTrash(entry.id, entry.trashDetails); + _loadDatabase(); + }, + child: const Text('Remove details'), + ), + InfoRowGroup( + info: { + 'dateMillis': '${data.dateMillis}', + 'path': data.path, + }, + ), + ], + ], + ); + }, + ), + const SizedBox(height: 16), + FutureBuilder<VideoPlaybackRow?>( + future: _dbVideoPlaybackLoader, + builder: (context, snapshot) { + if (snapshot.hasError) return Text(snapshot.error.toString()); + if (snapshot.connectionState != ConnectionState.done) return const SizedBox(); + final data = snapshot.data; + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('DB video playback:${data == null ? ' no row' : ''}'), + if (data != null) + InfoRowGroup( + info: { + 'resumeTimeMillis': '${data.resumeTimeMillis}', + }, + ), + ], + ); + }, + ), + ], + ); + } +} diff --git a/lib/widgets/viewer/debug/debug_page.dart b/lib/widgets/viewer/debug/debug_page.dart new file mode 100644 index 0000000..2fca031 --- /dev/null +++ b/lib/widgets/viewer/debug/debug_page.dart @@ -0,0 +1,188 @@ +import 'package:aves/app_mode.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/favourites.dart'; +import 'package:aves/model/entry/extensions/images.dart'; +import 'package:aves/model/entry/extensions/location.dart'; +import 'package:aves/model/entry/extensions/multipage.dart'; +import 'package:aves/model/entry/extensions/props.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/viewer/debug/db.dart'; +import 'package:aves/widgets/viewer/debug/metadata.dart'; +import 'package:aves/widgets/viewer/info/common.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class ViewerDebugPage extends StatelessWidget { + static const routeName = '/viewer/debug'; + + final AvesEntry entry; + + const ViewerDebugPage({ + super.key, + required this.entry, + }); + + @override + Widget build(BuildContext context) { + final tabs = <(Tab, Widget)>[ + (const Tab(text: 'Entry'), _buildEntryTabView()), + if (context.select<ValueNotifier<AppMode>, bool>((vn) => vn.value != AppMode.view)) (const Tab(text: 'DB'), DbTab(entry: entry)), + (const Tab(icon: Icon(AIcons.android)), MetadataTab(entry: entry)), + (const Tab(icon: Icon(AIcons.image)), _buildThumbnailsTabView()), + ]; + return Directionality( + textDirection: TextDirection.ltr, + child: DefaultTabController( + length: tabs.length, + child: Scaffold( + appBar: AppBar( + title: const Text('Debug'), + bottom: TabBar( + tabs: tabs.map((t) => t.$1).toList(), + ), + ), + body: SafeArea( + child: TabBarView( + children: tabs.map((t) => t.$2).toList(), + ), + ), + ), + ), + ); + } + + Widget _buildEntryTabView() { + String toDateValue(int? time, {int factor = 1}) { + var value = '$time'; + if (time != null && time > 0) { + try { + value += ' (${DateTime.fromMillisecondsSinceEpoch(time * factor)})'; + } catch (error) { + value += ' (invalid DateTime})'; + } + } + return value; + } + + return ListView( + padding: const EdgeInsets.all(16), + children: [ + InfoRowGroup( + info: { + 'hash': '#${shortHash(entry)}', + 'id': '${entry.id}', + 'origin': '${entry.origin}', + 'contentId': '${entry.contentId}', + 'uri': entry.uri, + 'path': entry.path ?? '', + 'directory': entry.directory ?? '', + 'filenameWithoutExtension': entry.filenameWithoutExtension ?? '', + 'extension': entry.extension ?? '', + 'sourceTitle': entry.sourceTitle ?? '', + 'sourceMimeType': entry.sourceMimeType, + 'mimeType': entry.mimeType, + 'isMissingAtPath': '${entry.isMissingAtPath}', + }, + ), + const Divider(), + InfoRowGroup( + info: { + 'trashed': '${entry.trashed}', + 'trashPath': '${entry.trashDetails?.path}', + 'trashDateMillis': '${entry.trashDetails?.dateMillis}', + }, + ), + const Divider(), + InfoRowGroup( + info: { + 'catalogDateMillis': toDateValue(entry.catalogDateMillis), + 'dateAddedSecs': toDateValue(entry.dateAddedSecs, factor: 1000), + 'dateModifiedMillis': toDateValue(entry.dateModifiedMillis), + 'sourceDateTakenMillis': toDateValue(entry.sourceDateTakenMillis), + 'bestDate': '${entry.bestDate}', + }, + ), + const Divider(), + InfoRowGroup( + info: { + 'width': '${entry.width}', + 'height': '${entry.height}', + 'sourceRotationDegrees': '${entry.sourceRotationDegrees}', + 'rotationDegrees': '${entry.rotationDegrees}', + 'isRotated': '${entry.isRotated}', + 'isFlipped': '${entry.isFlipped}', + 'displayAspectRatio': '${entry.displayAspectRatio}', + 'displaySize': '${entry.displaySize.width}x${entry.displaySize.height}', + }, + ), + const Divider(), + InfoRowGroup( + info: { + 'durationMillis': '${entry.durationMillis}', + 'durationText': entry.durationText, + }, + ), + const Divider(), + InfoRowGroup( + info: { + 'sizeBytes': '${entry.sizeBytes}', + 'isFavourite': '${entry.isFavourite}', + 'isSvg': '${entry.isSvg}', + 'isVideo': '${entry.isVideo}', + 'isCatalogued': '${entry.isCatalogued}', + 'is360': '${entry.is360}', + 'isAnimated': '${entry.isAnimated}', + 'isGeotiff': '${entry.isGeotiff}', + 'isHdr': '${entry.isHdr}', + 'isMultiPage': '${entry.isMultiPage}', + 'isMotionPhoto': '${entry.isMotionPhoto}', + 'canEdit': '${entry.canEdit}', + 'canEditDate': '${entry.canEditDate}', + 'canEditTags': '${entry.canEditTags}', + 'canRotate': '${entry.canRotate}', + 'canFlip': '${entry.canFlip}', + 'tags': '${entry.tags}', + }, + ), + const Divider(), + InfoRowGroup( + info: { + 'hasGps': '${entry.hasGps}', + 'hasAddress': '${entry.hasAddress}', + 'hasFineAddress': '${entry.hasFineAddress}', + 'latLng': '${entry.latLng}', + }, + ), + ], + ); + } + + Widget _buildThumbnailsTabView() { + return ListView( + padding: const EdgeInsets.all(16), + children: entry.cachedThumbnails + .expand((provider) => [ + Text('Thumb extent: ${provider.key.extent}'), + Center( + child: Image( + image: provider, + frameBuilder: (context, child, frame, wasSynchronouslyLoaded) { + return Container( + foregroundDecoration: const BoxDecoration( + border: Border.fromBorderSide(BorderSide( + color: Colors.amber, + width: .1, + )), + ), + child: child, + ); + }, + ), + ), + const SizedBox(height: 16), + ]) + .toList(), + ); + } +} diff --git a/lib/widgets/viewer/debug/metadata.dart b/lib/widgets/viewer/debug/metadata.dart new file mode 100644 index 0000000..8196324 --- /dev/null +++ b/lib/widgets/viewer/debug/metadata.dart @@ -0,0 +1,182 @@ +import 'dart:collection'; +import 'dart:typed_data'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/location.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/ref/mime_types.dart'; +import 'package:aves/services/android_debug_service.dart'; +import 'package:aves/services/geocoding_service.dart'; +import 'package:aves/widgets/common/identity/aves_expansion_tile.dart'; +import 'package:aves/widgets/viewer/info/common.dart'; +import 'package:flutter/material.dart'; + +class MetadataTab extends StatefulWidget { + final AvesEntry entry; + + const MetadataTab({ + super.key, + required this.entry, + }); + + @override + State<MetadataTab> createState() => _MetadataTabState(); +} + +class _MetadataTabState extends State<MetadataTab> { + late Future<Map> _bitmapFactoryLoader, _contentResolverMetadataLoader, _exifInterfaceMetadataLoader; + late Future<Map> _mediaMetadataLoader, _metadataExtractorLoader, _pixyMetaLoader, _tiffStructureLoader, _addressLoader; + late Future<String?> _mp4ParserDumpLoader; + + // MediaStore timestamp keys + static const secondTimestampKeys = ['date_added', 'date_modified', 'date_expires', 'isPlayed']; + static const millisecondTimestampKeys = ['datetaken', 'datetime']; + + AvesEntry get entry => widget.entry; + + @override + void initState() { + super.initState(); + _loadMetadata(); + } + + void _loadMetadata() { + _bitmapFactoryLoader = AndroidDebugService.getBitmapFactoryInfo(entry); + _contentResolverMetadataLoader = AndroidDebugService.getContentResolverMetadata(entry); + _exifInterfaceMetadataLoader = AndroidDebugService.getExifInterfaceMetadata(entry); + _mediaMetadataLoader = AndroidDebugService.getMediaMetadataRetrieverMetadata(entry); + _metadataExtractorLoader = AndroidDebugService.getMetadataExtractorSummary(entry); + _mp4ParserDumpLoader = AndroidDebugService.getMp4ParserDump(entry); + _pixyMetaLoader = AndroidDebugService.getPixyMetadata(entry); + _tiffStructureLoader = AndroidDebugService.getTiffStructure(entry); + _addressLoader = entry.hasGps + ? GeocodingService.getAddress(entry.latLng!, settings.appliedLocale).then((addresses) { + if (addresses.isNotEmpty) { + final address = addresses.first; + return { + 'addressLine': address.addressLine, + 'adminArea': address.adminArea, + 'countryCode': address.countryCode, + 'countryName': address.countryName, + 'featureName': address.featureName, + 'locality': address.locality, + 'postalCode': address.postalCode, + 'subAdminArea': address.subAdminArea, + 'subLocality': address.subLocality, + 'subThoroughfare': address.subThoroughfare, + 'thoroughfare': address.thoroughfare, + }; + } + return {}; + }) + : Future.value({}); + setState(() {}); + } + + @override + Widget build(BuildContext context) { + Widget builderFromSnapshotData(BuildContext context, Map snapshotData, String title) { + final data = SplayTreeMap.of(snapshotData.map((k, v) { + final key = k.toString(); + var value = v?.toString() ?? 'null'; + if ([...secondTimestampKeys, ...millisecondTimestampKeys].contains(key) && v is int && v != 0) { + if (secondTimestampKeys.contains(key)) { + v *= 1000; + } + try { + value += ' (${DateTime.fromMillisecondsSinceEpoch(v)})'; + } catch (error) { + value += ' (invalid DateTime})'; + } + } + if (key == 'xmp' && v != null && v is Uint8List) { + value = String.fromCharCodes(v); + } + return MapEntry(key, value); + })); + return AvesExpansionTile( + title: title, + children: [ + if (data.isNotEmpty) + Padding( + padding: const EdgeInsets.only(left: 8, right: 8, bottom: 8), + child: InfoRowGroup(info: data), + ) + ], + ); + } + + Widget builderFromSnapshot(BuildContext context, AsyncSnapshot<Map> snapshot, String title) { + if (snapshot.hasError) return Text(snapshot.error.toString()); + if (snapshot.connectionState != ConnectionState.done) return const SizedBox(); + return builderFromSnapshotData(context, snapshot.data!, title); + } + + return ListView( + padding: const EdgeInsets.all(8), + children: [ + FutureBuilder<Map>( + future: _bitmapFactoryLoader, + builder: (context, snapshot) => builderFromSnapshot(context, snapshot, 'Bitmap Factory'), + ), + FutureBuilder<Map>( + future: _contentResolverMetadataLoader, + builder: (context, snapshot) => builderFromSnapshot(context, snapshot, 'Content Resolver'), + ), + FutureBuilder<Map>( + future: _exifInterfaceMetadataLoader, + builder: (context, snapshot) => builderFromSnapshot(context, snapshot, 'Exif Interface'), + ), + FutureBuilder<Map>( + future: _mediaMetadataLoader, + builder: (context, snapshot) => builderFromSnapshot(context, snapshot, 'Media Metadata Retriever'), + ), + FutureBuilder<Map>( + future: _metadataExtractorLoader, + builder: (context, snapshot) => builderFromSnapshot(context, snapshot, 'Metadata Extractor'), + ), + FutureBuilder<String?>( + future: _mp4ParserDumpLoader, + builder: (context, snapshot) { + if (snapshot.hasError) return Text(snapshot.error.toString()); + if (snapshot.connectionState != ConnectionState.done) return const SizedBox(); + final data = snapshot.data?.trim(); + return AvesExpansionTile( + title: 'MP4 Parser', + children: [ + if (data != null && data.isNotEmpty) + Padding( + padding: const EdgeInsets.symmetric(horizontal: 8), + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: SelectableText(data), + ), + ) + ], + ); + }, + ), + FutureBuilder<Map>( + future: _pixyMetaLoader, + builder: (context, snapshot) => builderFromSnapshot(context, snapshot, 'Pixy Meta'), + ), + if (entry.mimeType == MimeTypes.tiff) + FutureBuilder<Map>( + future: _tiffStructureLoader, + builder: (context, snapshot) { + if (snapshot.hasError) return Text(snapshot.error.toString()); + if (snapshot.connectionState != ConnectionState.done) return const SizedBox(); + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: snapshot.data!.entries.map((kv) => builderFromSnapshotData(context, kv.value as Map, 'TIFF ${kv.key}')).toList(), + ); + }, + ), + FutureBuilder<Map>( + future: _addressLoader, + builder: (context, snapshot) => builderFromSnapshot(context, snapshot, 'Address'), + ), + ], + ); + } +} diff --git a/lib/widgets/viewer/entry_horizontal_pager.dart b/lib/widgets/viewer/entry_horizontal_pager.dart new file mode 100644 index 0000000..7ba47aa --- /dev/null +++ b/lib/widgets/viewer/entry_horizontal_pager.dart @@ -0,0 +1,189 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/multipage.dart'; +import 'package:aves/model/entry/extensions/props.dart'; +import 'package:aves/model/settings/enums/viewer_transition.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/widgets/viewer/controls/controller.dart'; +import 'package:aves/widgets/viewer/controls/notifications.dart'; +import 'package:aves/widgets/viewer/multipage/conductor.dart'; +import 'package:aves/widgets/viewer/page_entry_builder.dart'; +import 'package:aves/widgets/viewer/visual/entry_page_view.dart'; +import 'package:aves_magnifier/aves_magnifier.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class MultiEntryScroller extends StatefulWidget { + final CollectionLens collection; + final ViewerController viewerController; + final PageController pageController; + final ValueChanged<int> onPageChanged; + final void Function(AvesEntry mainEntry, AvesEntry? pageEntry) onViewDisposed; + + const MultiEntryScroller({ + super.key, + required this.collection, + required this.viewerController, + required this.pageController, + required this.onPageChanged, + required this.onViewDisposed, + }); + + @override + State<StatefulWidget> createState() => _MultiEntryScrollerState(); +} + +class _MultiEntryScrollerState extends State<MultiEntryScroller> with AutomaticKeepAliveClientMixin { + List<AvesEntry> get entries => widget.collection.sortedEntries; + + ViewerController get viewerController => widget.viewerController; + + PageController get pageController => widget.pageController; + + @override + Widget build(BuildContext context) { + super.build(context); + + return MagnifierGestureDetectorScope( + axis: const [Axis.horizontal, Axis.vertical], + child: NotificationListener( + onNotification: _handleNotification, + child: PageView.builder( + // key is expected by test driver + key: const Key('horizontal-pageview'), + scrollDirection: Axis.horizontal, + controller: pageController, + physics: MagnifierScrollerPhysics( + gestureSettings: MediaQuery.gestureSettingsOf(context), + parent: const BouncingScrollPhysics(), + ), + onPageChanged: widget.onPageChanged, + itemBuilder: (context, index) { + final mainEntry = entries[index % entries.length]; + + final child = mainEntry.isMultiPage + ? PageEntryBuilder( + multiPageController: context.read<MultiPageConductor>().getController(mainEntry), + builder: (pageEntry) => _buildViewer(mainEntry, pageEntry: pageEntry), + ) + : _buildViewer(mainEntry); + + return Selector<Settings, bool>( + selector: (context, s) => s.animate, + builder: (context, animate, child) { + if (!animate) return child!; + return AnimatedBuilder( + animation: pageController, + builder: viewerController.transition.builder(pageController, index), + child: child, + ); + }, + child: child, + ); + }, + itemCount: viewerController.repeat ? null : entries.length, + ), + ), + ); + } + + Widget _buildViewer(AvesEntry mainEntry, {AvesEntry? pageEntry}) { + return EntryPageView( + // key is expected by test driver + key: const Key('image_view'), + mainEntry: mainEntry, + pageEntry: pageEntry ?? mainEntry, + viewerController: viewerController, + onDisposed: () => widget.onViewDisposed(mainEntry, pageEntry), + ); + } + + bool _handleNotification(dynamic notification) { + if (notification is ShowPreviousVideoNotification) { + _showPreviousVideo(); + } else if (notification is ShowNextVideoNotification) { + _showNextVideo(); + } else { + return false; + } + return true; + } + + void _showPreviousVideo() { + final currentIndex = pageController.page?.round(); + if (currentIndex != null) { + final previousVideoEntry = entries.take(currentIndex).lastWhereOrNull((entry) => entry.isVideo); + if (previousVideoEntry != null) { + final previousIndex = entries.indexOf(previousVideoEntry); + if (previousIndex != -1) { + ShowEntryNotification(animate: false, index: previousIndex).dispatch(context); + } + } + } + } + + void _showNextVideo() { + final currentIndex = pageController.page?.round(); + if (currentIndex != null) { + final nextVideoEntry = entries.skip(currentIndex + 1).firstWhereOrNull((entry) => entry.isVideo); + if (nextVideoEntry != null) { + final nextIndex = entries.indexOf(nextVideoEntry); + if (nextIndex != -1) { + ShowEntryNotification(animate: false, index: nextIndex).dispatch(context); + } + } + } + } + + @override + bool get wantKeepAlive => true; +} + +class SingleEntryScroller extends StatefulWidget { + final AvesEntry entry; + final ViewerController viewerController; + + const SingleEntryScroller({ + super.key, + required this.entry, + required this.viewerController, + }); + + @override + State<StatefulWidget> createState() => _SingleEntryScrollerState(); +} + +class _SingleEntryScrollerState extends State<SingleEntryScroller> with AutomaticKeepAliveClientMixin { + AvesEntry get mainEntry => widget.entry; + + ViewerController get viewerController => widget.viewerController; + + @override + Widget build(BuildContext context) { + super.build(context); + + var child = mainEntry.isMultiPage + ? PageEntryBuilder( + multiPageController: context.read<MultiPageConductor>().getController(mainEntry), + builder: (pageEntry) => _buildViewer(pageEntry: pageEntry), + ) + : _buildViewer(); + + return MagnifierGestureDetectorScope( + axis: const [Axis.vertical], + child: child, + ); + } + + Widget _buildViewer({AvesEntry? pageEntry}) { + return EntryPageView( + mainEntry: mainEntry, + pageEntry: pageEntry ?? mainEntry, + viewerController: widget.viewerController, + ); + } + + @override + bool get wantKeepAlive => true; +} diff --git a/lib/widgets/viewer/entry_vertical_pager.dart b/lib/widgets/viewer/entry_vertical_pager.dart new file mode 100644 index 0000000..ba3fc60 --- /dev/null +++ b/lib/widgets/viewer/entry_vertical_pager.dart @@ -0,0 +1,419 @@ +import 'dart:async'; +import 'dart:math'; +import 'dart:ui'; + +import 'package:aves/app_mode.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/catalog.dart'; +import 'package:aves/model/entry/extensions/location.dart'; +import 'package:aves/model/entry/extensions/props.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/widgets/aves_app.dart'; +import 'package:aves/widgets/common/behaviour/springy_scroll_physics.dart'; +import 'package:aves/widgets/common/extensions/theme.dart'; +import 'package:aves/widgets/viewer/action/entry_action_delegate.dart'; +import 'package:aves/widgets/viewer/controls/controller.dart'; +import 'package:aves/widgets/viewer/controls/intents.dart'; +import 'package:aves/widgets/viewer/controls/notifications.dart'; +import 'package:aves/widgets/viewer/controls/shortcuts.dart'; +import 'package:aves/widgets/viewer/entry_horizontal_pager.dart'; +import 'package:aves/widgets/viewer/info/info_page.dart'; +import 'package:aves/widgets/viewer/multipage/conductor.dart'; +import 'package:aves/widgets/viewer/video/conductor.dart'; +import 'package:aves_magnifier/aves_magnifier.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:provider/provider.dart'; + +class ViewerVerticalPageView extends StatefulWidget { + final CollectionLens? collection; + final ValueNotifier<AvesEntry?> entryNotifier; + final ViewerController viewerController; + final Animation<double> overlayOpacity; + final PageController verticalPager, horizontalPager; + final void Function(int page) onVerticalPageChanged, onHorizontalPageChanged; + final VoidCallback onImagePageRequested; + final void Function(AvesEntry mainEntry, AvesEntry? pageEntry) onViewDisposed; + + // critically damped spring (ratio = 1) a bit stiffer than `ScrollPhysics._kDefaultSpring` + static final spring = SpringDescription.withDampingRatio( + mass: 0.5, + stiffness: 140.0, + ratio: 1.0, + ); + + const ViewerVerticalPageView({ + super.key, + required this.collection, + required this.entryNotifier, + required this.viewerController, + required this.overlayOpacity, + required this.verticalPager, + required this.horizontalPager, + required this.onVerticalPageChanged, + required this.onHorizontalPageChanged, + required this.onImagePageRequested, + required this.onViewDisposed, + }); + + @override + State<ViewerVerticalPageView> createState() => _ViewerVerticalPageViewState(); +} + +class _ViewerVerticalPageViewState extends State<ViewerVerticalPageView> { + final Set<StreamSubscription> _subscriptions = {}; + final ValueNotifier<double> _backgroundOpacityNotifier = ValueNotifier(1); + final ValueNotifier<bool> _isVerticallyScrollingNotifier = ValueNotifier(false); + final ValueNotifier<bool> _isImageFocusedNotifier = ValueNotifier(true); + Timer? _verticalScrollMonitoringTimer; + AvesEntry? _oldEntry; + Future<double>? _systemBrightness; + + CollectionLens? get collection => widget.collection; + + bool get hasCollection => collection != null; + + AvesEntry? get entry => widget.entryNotifier.value; + + PageController get verticalPager => widget.verticalPager; + + PageController get horizontalPager => widget.horizontalPager; + + static const double maximumBrightness = 1.0; + + @override + void initState() { + super.initState(); + _registerWidget(widget); + + if (settings.maxBrightness == MaxBrightness.viewerOnly) { + _systemBrightness = AvesApp.screenBrightness?.system; + } + } + + @override + void didUpdateWidget(covariant ViewerVerticalPageView oldWidget) { + super.didUpdateWidget(oldWidget); + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + + @override + void dispose() { + _unregisterWidget(widget); + _stopScrollMonitoringTimer(); + _backgroundOpacityNotifier.dispose(); + _isVerticallyScrollingNotifier.dispose(); + _isImageFocusedNotifier.dispose(); + super.dispose(); + } + + void _registerWidget(ViewerVerticalPageView widget) { + _subscriptions.add(widget.viewerController.showNextCommands.listen((event) { + _goToHorizontalPage(1, animate: true); + })); + _subscriptions.add(widget.viewerController.overlayCommands.listen((event) { + ToggleOverlayNotification(visible: event.visible).dispatch(context); + })); + widget.verticalPager.addListener(_onVerticalPageControllerChanged); + widget.entryNotifier.addListener(_onEntryChanged); + if (_oldEntry != entry) _onEntryChanged(); + } + + void _unregisterWidget(ViewerVerticalPageView widget) { + _subscriptions + ..forEach((sub) => sub.cancel()) + ..clear(); + widget.verticalPager.removeListener(_onVerticalPageControllerChanged); + widget.entryNotifier.removeListener(_onEntryChanged); + _oldEntry?.visualChangeNotifier.removeListener(_onVisualChanged); + } + + @override + Widget build(BuildContext context) { + // fake page for opacity transition between collection and viewer + const transitionPage = SizedBox(); + + final pages = [ + transitionPage, + _buildImagePage(), + ]; + + final appMode = context.read<ValueNotifier<AppMode>>().value; + if (!{AppMode.screenSaver, AppMode.slideshow}.contains(appMode)) { + final infoPage = NotificationListener<ShowImageNotification>( + onNotification: (notification) { + widget.onImagePageRequested(); + return true; + }, + child: AnimatedBuilder( + animation: verticalPager, + builder: (context, child) { + return Visibility( + visible: verticalPager.page! > 1, + child: child!, + ); + }, + child: FocusScope( + child: InfoPage( + collection: collection, + entryNotifier: widget.entryNotifier, + isScrollingNotifier: _isVerticallyScrollingNotifier, + ), + ), + ), + ); + + pages.add(infoPage); + } + + return ValueListenableBuilder<double>( + valueListenable: _backgroundOpacityNotifier, + builder: (context, backgroundOpacity, child) { + return ValueListenableBuilder<double>( + valueListenable: widget.overlayOpacity, + builder: (context, overlayOpacity, child) { + final background = Theme.of(context).isDark ? Colors.black : Color.lerp(Colors.black, Colors.white, overlayOpacity)!; + return Container( + color: background.withValues(alpha: backgroundOpacity), + child: child, + ); + }, + child: child, + ); + }, + child: PageView( + // key is expected by test driver + key: const Key('vertical-pageview'), + scrollDirection: Axis.vertical, + controller: verticalPager, + physics: MagnifierScrollerPhysics( + gestureSettings: MediaQuery.gestureSettingsOf(context), + parent: SpringyScrollPhysics( + spring: ViewerVerticalPageView.spring, + ), + ), + onPageChanged: widget.onVerticalPageChanged, + children: pages, + ), + ); + } + + Widget _buildImagePage() { + final useTvLayout = settings.useTvLayout; + + Map<ShortcutActivator, Intent>? shortcuts = { + ...ViewerShortcuts.entryActions, + ...ViewerShortcuts.media, + const SingleActivator(LogicalKeyboardKey.arrowUp): useTvLayout ? const TvShowLessInfoIntent() : const LeaveIntent(), + const SingleActivator(LogicalKeyboardKey.arrowDown): useTvLayout ? const TvShowMoreInfoIntent() : const ShowInfoIntent(), + }; + + Widget? child; + if (hasCollection) { + shortcuts.addAll(const { + SingleActivator(LogicalKeyboardKey.arrowLeft): ShowPreviousIntent(), + SingleActivator(LogicalKeyboardKey.arrowRight): ShowNextIntent(), + }); + child = MultiEntryScroller( + collection: collection!, + viewerController: widget.viewerController, + pageController: horizontalPager, + onPageChanged: widget.onHorizontalPageChanged, + onViewDisposed: widget.onViewDisposed, + ); + } else if (entry != null) { + child = SingleEntryScroller( + viewerController: widget.viewerController, + entry: entry!, + ); + } + if (child != null) { + if (settings.useTvLayout) { + child = ValueListenableBuilder<bool>( + valueListenable: _isImageFocusedNotifier, + builder: (context, isImageFocused, child) { + return AnimatedScale( + scale: isImageFocused ? 1 : .6, + curve: Curves.fastOutSlowIn, + duration: context.select<DurationsData, Duration>((v) => v.tvImageFocusAnimation), + child: child!, + ); + }, + child: child, + ); + } + + // handle mouse wheel to jump to previous/next item + child = Listener( + onPointerSignal: _onPointerSignal, + child: child, + ); + + return FocusableActionDetector( + autofocus: true, + shortcuts: shortcuts, + actions: { + ShowPreviousIntent: CallbackAction<Intent>(onInvoke: (intent) => _goToHorizontalPage(-1, animate: false)), + ShowNextIntent: CallbackAction<Intent>(onInvoke: (intent) => _goToHorizontalPage(1, animate: false)), + LeaveIntent: CallbackAction<Intent>(onInvoke: (intent) => Navigator.maybeOf(context)?.pop()), + ShowInfoIntent: CallbackAction<Intent>(onInvoke: (intent) => ShowInfoPageNotification().dispatch(context)), + TvShowLessInfoIntent: CallbackAction<Intent>(onInvoke: (intent) => TvShowLessInfoNotification().dispatch(context)), + TvShowMoreInfoIntent: CallbackAction<Intent>(onInvoke: (intent) => TvShowMoreInfoNotification().dispatch(context)), + PlayPauseIntent: CallbackAction<PlayPauseIntent>(onInvoke: _onPlayPauseIntent), + EntryActionIntent: CallbackAction<EntryActionIntent>(onInvoke: (intent) => _onEntryActionIntent(intent.action)), + ActivateIntent: CallbackAction<Intent>(onInvoke: (intent) { + if (useTvLayout) { + final _entry = entry; + if (_entry != null && _entry.isVideo) { + // address `TV-PC` requirement from https://developer.android.com/docs/quality-guidelines/tv-app-quality + final controller = context.read<VideoConductor>().getController(_entry); + if (controller != null) { + VideoActionNotification( + controller: controller, + entry: _entry, + action: EntryAction.videoTogglePlay, + ).dispatch(context); + } + } else { + const ToggleOverlayNotification().dispatch(context); + } + } + return null; + }), + }, + onFocusChange: (focused) => _isImageFocusedNotifier.value = focused, + child: child, + ); + } + return const SizedBox(); + } + + void _onPointerSignal(PointerSignalEvent event) { + // use the resolver so that the pager scrollable does not handle the pointer + GestureBinding.instance.pointerSignalResolver.register(event, (event) { + if (event is PointerScrollEvent && event.kind == PointerDeviceKind.mouse) { + final verticalDelta = event.scrollDelta.dy; + _goToHorizontalPage(verticalDelta.sign.round(), animate: false); + } + }); + } + + void _onEntryActionIntent(EntryAction action) { + final mainEntry = entry; + if (mainEntry != null) { + AvesEntry? pageEntry; + final multiPageController = context.read<MultiPageConductor>().getController(mainEntry); + if (multiPageController != null) { + pageEntry = multiPageController.info?.getPageEntryByIndex(multiPageController.page); + } + final appMode = context.read<ValueNotifier<AppMode>>().value; + final actionDelegate = EntryActionDelegate(mainEntry, pageEntry ?? mainEntry, collection); + if (actionDelegate.isVisible(appMode: appMode, action: action) && actionDelegate.canApply(action)) { + actionDelegate.onActionSelected(context, action); + } + } + } + + void _goToHorizontalPage(int delta, {required bool animate}) { + final page = horizontalPager.page?.round(); + final _collection = collection; + if (page != null && _collection != null) { + var target = page + delta; + if (!widget.viewerController.repeat) { + target = target.clamp(0, _collection.entryCount - 1); + } + if (animate) { + horizontalPager.animateToPage( + target, + duration: ADurations.viewerHorizontalPageAnimation, + curve: Curves.easeInOutCubic, + ); + } else { + horizontalPager.jumpToPage(target); + } + } + } + + void _onVerticalPageControllerChanged() { + final page = verticalPager.page!; + + final opacity = min(1.0, page); + _backgroundOpacityNotifier.value = opacity * opacity; + + if (settings.maxBrightness == MaxBrightness.viewerOnly) { + _systemBrightness?.then((system) { + final value = lerpDouble(maximumBrightness, system, ((1 - page).abs() * 2).clamp(0, 1))!; + AvesApp.screenBrightness?.setApplicationScreenBrightness(value); + }); + } + + _isVerticallyScrollingNotifier.value = true; + _stopScrollMonitoringTimer(); + _verticalScrollMonitoringTimer = Timer(ADurations.infoScrollMonitoringTimerDelay, () { + _isVerticallyScrollingNotifier.value = false; + }); + } + + void _stopScrollMonitoringTimer() { + _verticalScrollMonitoringTimer?.cancel(); + } + + // when the entry changed (e.g. by scrolling through the PageView, or if the entry got deleted) + Future<void> _onEntryChanged() async { + _oldEntry?.visualChangeNotifier.removeListener(_onVisualChanged); + _oldEntry = entry; + + final _entry = entry; + if (_entry != null) { + _entry.visualChangeNotifier.addListener(_onVisualChanged); + // make sure to locate the entry, + // so that we can display the address instead of coordinates + // even when initial collection locating has not reached this entry yet + await _entry.catalog(background: false, force: false, persist: true); + await _entry.locate(background: false, force: false, geocoderLocale: settings.appliedLocale); + } else { + Navigator.maybeOf(context)?.pop(); + } + if (!mounted) return; + // needed to refresh when entry changes but the page does not (e.g. on page deletion) + setState(() {}); + } + + // when the entry image itself changed (e.g. after rotation) + void _onVisualChanged() async { + if (!mounted) return; + // rebuild to refresh the `Image` inside `ImagePage` + setState(() {}); + } + + void _onPlayPauseIntent(PlayPauseIntent intent) { + // address `TV-PP` requirement from https://developer.android.com/docs/quality-guidelines/tv-app-quality + final _entry = entry; + if (_entry != null && _entry.isVideo) { + final controller = context.read<VideoConductor>().getController(_entry); + if (controller != null) { + bool toggle; + switch (intent.type) { + case TvPlayPauseType.play: + toggle = !controller.isPlaying; + case TvPlayPauseType.pause: + toggle = controller.isPlaying; + case TvPlayPauseType.toggle: + toggle = true; + } + if (toggle) { + VideoActionNotification( + controller: controller, + entry: _entry, + action: EntryAction.videoTogglePlay, + ).dispatch(context); + } + } + } + } +} diff --git a/lib/widgets/viewer/entry_viewer_page.dart b/lib/widgets/viewer/entry_viewer_page.dart new file mode 100644 index 0000000..ed661bc --- /dev/null +++ b/lib/widgets/viewer/entry_viewer_page.dart @@ -0,0 +1,61 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/extensions/theme.dart'; +import 'package:aves/widgets/viewer/controls/controller.dart'; +import 'package:aves/widgets/viewer/entry_viewer_stack.dart'; +import 'package:aves/widgets/viewer/providers.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class EntryViewerPage extends StatefulWidget { + static const routeName = '/viewer'; + + final CollectionLens? collection; + final AvesEntry initialEntry; + + const EntryViewerPage({ + super.key, + this.collection, + required this.initialEntry, + }); + + @override + State<EntryViewerPage> createState() => _EntryViewerPageState(); + + static Color getBackground(BuildContext context) => Theme.of(context).isDark ? Colors.black : Colors.white; +} + +class _EntryViewerPageState extends State<EntryViewerPage> { + final ViewerController _viewerController = ViewerController(); + + @override + void dispose() { + _viewerController.dispose(); + // provided collection should be a new instance specifically created + // for the `EntryViewerPage` widget, so it can be safely disposed here + widget.collection?.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final collection = widget.collection; + return AvesScaffold( + body: MultiProvider( + providers: [ + ViewStateConductorProvider(), + VideoConductorProvider(collection: collection), + MultiPageConductorProvider(), + ], + child: EntryViewerStack( + collection: collection, + initialEntry: widget.initialEntry, + viewerController: _viewerController, + ), + ), + backgroundColor: Navigator.canPop(context) ? Colors.transparent : EntryViewerPage.getBackground(context), + resizeToAvoidBottomInset: false, + ); + } +} diff --git a/lib/widgets/viewer/entry_viewer_stack.dart b/lib/widgets/viewer/entry_viewer_stack.dart new file mode 100644 index 0000000..b9e17d9 --- /dev/null +++ b/lib/widgets/viewer/entry_viewer_stack.dart @@ -0,0 +1,1021 @@ +import 'dart:async'; +import 'dart:math'; + +import 'package:aves/app_mode.dart'; +import 'package:aves/model/device.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/multipage.dart'; +import 'package:aves/model/entry/extensions/props.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/filters/trash.dart'; +import 'package:aves/model/highlight.dart'; +import 'package:aves/model/settings/enums/accessibility_timeout.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/widgets/aves_app.dart'; +import 'package:aves/widgets/collection/collection_page.dart'; +import 'package:aves/widgets/common/action_mixins/feedback.dart'; +import 'package:aves/widgets/common/basic/insets.dart'; +import 'package:aves/widgets/common/providers/viewer_entry_provider.dart'; +import 'package:aves/widgets/viewer/action/video_action_delegate.dart'; +import 'package:aves/widgets/viewer/controls/controller.dart'; +import 'package:aves/widgets/viewer/controls/notifications.dart'; +import 'package:aves/widgets/viewer/entry_vertical_pager.dart'; +import 'package:aves/widgets/viewer/hero.dart'; +import 'package:aves/widgets/viewer/multipage/conductor.dart'; +import 'package:aves/widgets/viewer/overlay/bottom.dart'; +import 'package:aves/widgets/viewer/overlay/locked.dart'; +import 'package:aves/widgets/viewer/overlay/panorama.dart'; +import 'package:aves/widgets/viewer/overlay/slideshow_buttons.dart'; +import 'package:aves/widgets/viewer/overlay/top.dart'; +import 'package:aves/widgets/viewer/overlay/video/video.dart'; +import 'package:aves/widgets/viewer/page_entry_builder.dart'; +import 'package:aves/widgets/viewer/video/conductor.dart'; +import 'package:aves/widgets/viewer/view/conductor.dart'; +import 'package:aves/widgets/viewer/visual/controller_mixin.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:aves_utils/aves_utils.dart'; +import 'package:aves_video/aves_video.dart'; +import 'package:collection/collection.dart'; +import 'package:floating/floating.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:flutter/services.dart'; +import 'package:provider/provider.dart'; + +class EntryViewerStack extends StatefulWidget { + final CollectionLens? collection; + final AvesEntry initialEntry; + final ViewerController viewerController; + + const EntryViewerStack({ + super.key, + this.collection, + required this.initialEntry, + required this.viewerController, + }); + + @override + State<EntryViewerStack> createState() => _EntryViewerStackState(); +} + +class _EntryViewerStackState extends State<EntryViewerStack> with EntryViewControllerMixin, FeedbackMixin, TickerProviderStateMixin, RouteAware { + late int _currentEntryIndex; + late ValueNotifier<int> _currentVerticalPage; + late PageController _horizontalPager, _verticalPager; + final AChangeNotifier _verticalScrollNotifier = AChangeNotifier(); + bool _overlayInitialized = false; + final ValueNotifier<bool> _overlayVisible = ValueNotifier(true); + final ValueNotifier<bool> _viewLocked = ValueNotifier(false); + final ValueNotifier<bool> _overlayExpandedNotifier = ValueNotifier(false); + late AnimationController _verticalPageAnimationController, _overlayAnimationController; + late CurvedAnimation _overlayButtonScale, _overlayVideoControlScale, _overlayOpacity, _overlayTopOffsetAnimation; + late Animation<Offset> _overlayTopOffset; + EdgeInsets? _frozenViewInsets, _frozenViewPadding; + late VideoActionDelegate _videoActionDelegate; + final ValueNotifier<EntryHeroInfo?> _heroInfoNotifier = ValueNotifier(null); + bool _isEntryTracked = true; + Timer? _overlayHidingTimer; + late ValueNotifier<AvesVideoController?> _playingVideoControllerNotifier; + + @override + bool get isViewingImage => _currentVerticalPage.value == imagePage; + + @override + late final ValueNotifier<AvesEntry?> entryNotifier; + + ViewerController get viewerController => widget.viewerController; + + CollectionLens? get collection => widget.collection; + + bool get hasCollection => collection != null; + + List<AvesEntry> get entries => hasCollection ? collection!.sortedEntries : [widget.initialEntry]; + + static const int transitionPage = 0; + + static const int imagePage = 1; + + static const int infoPage = 2; + + @override + void initState() { + super.initState(); + if (settings.maxBrightness == MaxBrightness.viewerOnly) { + AvesApp.screenBrightness?.setApplicationScreenBrightness(1); + } + if (settings.keepScreenOn == KeepScreenOn.viewerOnly) { + windowService.keepScreenOn(true); + } + + // make sure initial entry is actually among the filtered collection entries + // `initialEntry` may be a dynamic burst entry from another collection lens + // so it is, strictly speaking, not contained in the lens used by the viewer, + // but it can be found by content ID + final initialEntry = widget.initialEntry; + final entry = entries.firstWhereOrNull((entry) => entry.id == initialEntry.id) ?? entries.firstOrNull; + // opening hero, with viewer as target + _heroInfoNotifier.value = EntryHeroInfo(collection, entry); + entryNotifier = viewerController.entryNotifier; + entryNotifier.value = entry; + _currentEntryIndex = max(0, entry != null ? entries.indexOf(entry) : -1); + _currentVerticalPage = ValueNotifier(imagePage); + _horizontalPager = PageController(initialPage: _currentEntryIndex); + _verticalPager = PageController(initialPage: _currentVerticalPage.value)..addListener(_onVerticalPageControllerChanged); + _verticalPageAnimationController = AnimationController.unbounded(vsync: this); + _verticalPageAnimationController.addListener(() { + final offset = _verticalPageAnimationController.value; + final delta = (offset - _verticalPager.offset).abs(); + if (delta > precisionErrorTolerance) { + // snap instead of animating below pixel dimension so that the vertical drag gesture recognizer + // can handle a new gesture as soon as the animation appears to be complete to the user + if (delta >= 1) { + _verticalPager.jumpTo(offset); + } else { + _verticalPageAnimationController.stop(); + _verticalPager.jumpToPage(_verticalPager.page!.round()); + } + } + }); + _overlayAnimationController = AnimationController( + duration: context.read<DurationsData>().viewerOverlayAnimation, + vsync: this, + ); + _overlayButtonScale = CurvedAnimation( + parent: _overlayAnimationController, + // a little bounce at the top + curve: Curves.easeOutBack, + ); + _overlayVideoControlScale = CurvedAnimation( + parent: _overlayAnimationController, + // no bounce at the bottom, to avoid video controller displacement + curve: Curves.easeOutQuad, + ); + _overlayOpacity = CurvedAnimation( + parent: _overlayAnimationController, + curve: Curves.easeOutQuad, + ); + _overlayTopOffsetAnimation = CurvedAnimation( + parent: _overlayAnimationController, + curve: Curves.easeOutQuad, + ); + _overlayTopOffset = Tween(begin: const Offset(0, -1), end: const Offset(0, 0)).animate(_overlayTopOffsetAnimation); + _overlayVisible.value = settings.showOverlayOnOpening && !viewerController.autopilot; + _overlayVisible.addListener(_onOverlayVisibleChanged); + _viewLocked.addListener(_onViewLockedChanged); + _videoActionDelegate = VideoActionDelegate( + collection: collection, + ); + _playingVideoControllerNotifier = context.read<VideoConductor>().playingVideoControllerNotifier; + _playingVideoControllerNotifier.addListener(_onPlayingVideoControllerChanged); + initEntryControllers(entry); + _registerWidget(widget); + AvesApp.lifecycleStateNotifier.addListener(_onAppLifecycleStateChanged); + WidgetsBinding.instance.addPostFrameCallback((_) => _initOverlay()); + } + + @override + void didUpdateWidget(covariant EntryViewerStack oldWidget) { + super.didUpdateWidget(oldWidget); + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + + @override + void dispose() { + AvesApp.pageRouteObserver.unsubscribe(this); + cleanEntryControllers(entryNotifier.value); + _playingVideoControllerNotifier.removeListener(_onPlayingVideoControllerChanged); + updatePictureInPicture(context); + _videoActionDelegate.dispose(); + _verticalPageAnimationController.dispose(); + _overlayButtonScale.dispose(); + _overlayVideoControlScale.dispose(); + _overlayOpacity.dispose(); + _overlayTopOffsetAnimation.dispose(); + _overlayAnimationController.dispose(); + _overlayVisible.dispose(); + _viewLocked.dispose(); + _overlayExpandedNotifier.dispose(); + _currentVerticalPage.dispose(); + _horizontalPager.dispose(); + _verticalPager.dispose(); + _verticalScrollNotifier.dispose(); + _heroInfoNotifier.dispose(); + _stopOverlayHidingTimer(); + AvesApp.lifecycleStateNotifier.removeListener(_onAppLifecycleStateChanged); + _unregisterWidget(widget); + super.dispose(); + } + + void _registerWidget(EntryViewerStack widget) { + widget.collection?.addListener(_onCollectionChanged); + } + + void _unregisterWidget(EntryViewerStack widget) { + widget.collection?.removeListener(_onCollectionChanged); + } + + @override + Widget build(BuildContext context) { + final viewStateConductor = context.read<ViewStateConductor>(); + return PopScope( + canPop: false, + onPopInvokedWithResult: (didPop, result) { + if (didPop) return; + + _onPopInvoked(); + }, + child: ValueListenableProvider<EntryHeroInfo?>.value( + value: _heroInfoNotifier, + child: NotificationListener( + onNotification: _handleNotification, + child: LayoutBuilder( + builder: (context, constraints) { + final availableSize = Size(constraints.maxWidth, constraints.maxHeight); + final viewer = ViewerVerticalPageView( + collection: collection, + entryNotifier: entryNotifier, + viewerController: viewerController, + overlayOpacity: _overlayInitialized + ? _overlayOpacity + : settings.showOverlayOnOpening + ? kAlwaysCompleteAnimation + : kAlwaysDismissedAnimation, + verticalPager: _verticalPager, + horizontalPager: _horizontalPager, + onVerticalPageChanged: _onVerticalPageChanged, + onHorizontalPageChanged: _onHorizontalPageChanged, + onImagePageRequested: () => _goToVerticalPage(imagePage), + onViewDisposed: (mainEntry, pageEntry) => viewStateConductor.reset(pageEntry ?? mainEntry), + ); + return StreamBuilder<PiPStatus>( + // as of floating v2.0.0, plugin assumes activity and fails when bound via service + // so we do not access status stream directly, but check for support first + stream: device.supportPictureInPicture ? Floating().pipStatusStream : Stream.value(PiPStatus.disabled), + builder: (context, snapshot) { + final pipEnabled = snapshot.data == PiPStatus.enabled; + return ValueListenableBuilder<bool>( + valueListenable: _viewLocked, + builder: (context, locked, child) { + final children = [child!]; + if (!pipEnabled) { + if (locked) { + children.addAll([ + const Positioned.fill( + child: AbsorbPointer(), + ), + Positioned.fill( + child: GestureDetector( + onTap: () => _overlayVisible.value = !_overlayVisible.value, + ), + ), + _buildViewerLockedBottomOverlay(), + ]); + } else { + // regular overlay + children.addAll(_buildOverlays(availableSize).map(_decorateOverlay)); + } + + children.addAll([ + const TopGestureAreaProtector(), + const SideGestureAreaProtector(), + const BottomGestureAreaProtector(), + ]); + } + + // TODO TLAD [flutter vNext] wrap into `BackdropGroup` + return Stack( + children: children, + ); + }, + child: viewer, + ); + }, + ); + }, + ), + ), + ), + ); + } + + // route aware + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + final route = ModalRoute.of(context); + if (route is PageRoute) { + AvesApp.pageRouteObserver.subscribe(this, route); + } + } + + @override + void didPopNext() => _overrideSnackBarMargin(); + + @override + void didPush() => _overrideSnackBarMargin(); + + @override + void didPop() => _resetSnackBarMargin(); + + @override + void didPushNext() => _resetSnackBarMargin(); + + void _overrideSnackBarMargin() { + MarginComputer marginComputer; + if (isViewingImage) { + marginComputer = (context) => EdgeInsets.only(bottom: ViewerBottomOverlay.actionSafeHeight(context)); + } else { + marginComputer = FeedbackMixin.snackBarMarginDefault; + } + FeedbackMixin.snackBarMarginOverrideNotifier.value = marginComputer; + } + + void _resetSnackBarMargin() => FeedbackMixin.snackBarMarginOverrideNotifier.value = null; + + // lifecycle + + // app lifecycle states: + // * rotating screen: resumed -> inactive -> resumed + // * going home: resumed -> inactive -> hidden -> paused + // * back from home: paused -> hidden -> inactive -> resumed + // * app switch / settings / etc: resumed -> inactive + void _onAppLifecycleStateChanged() { + switch (AvesApp.lifecycleStateNotifier.value) { + case AppLifecycleState.inactive: + // inactive: when losing focus + // also triggered when app is rotated on Android API >=33 + break; + case AppLifecycleState.hidden: + case AppLifecycleState.paused: + case AppLifecycleState.detached: + // hidden: transient state between `inactive` and `paused` + // paused: when using another app + // detached: when app is without a view + viewerController.autopilot = false; + pauseVideoControllers(); + case AppLifecycleState.resumed: + break; + } + } + + void _onPlayingVideoControllerChanged() => updatePictureInPicture(context); + + Widget _decorateOverlay(Widget overlay) { + return ValueListenableBuilder<double>( + valueListenable: _overlayAnimationController, + builder: (context, animation, child) { + return Visibility( + visible: !_overlayAnimationController.isDismissed, + child: child!, + ); + }, + child: overlay, + ); + } + + List<Widget> _buildOverlays(Size availableSize) { + final appMode = context.read<ValueNotifier<AppMode>>().value; + switch (appMode) { + case AppMode.screenSaver: + return []; + case AppMode.slideshow: + return [ + _buildViewerTopOverlay(availableSize), + _buildSlideshowBottomOverlay(availableSize), + ]; + default: + return [ + _buildViewerTopOverlay(availableSize), + _buildViewerBottomOverlay(availableSize), + ]; + } + } + + Widget _buildViewerLockedBottomOverlay() { + return TooltipTheme( + data: TooltipTheme.of(context).copyWith( + preferBelow: false, + ), + child: ViewerLockedOverlay( + animationController: _overlayAnimationController, + ), + ); + } + + Widget _buildSlideshowBottomOverlay(Size availableSize) { + return TooltipTheme( + data: TooltipTheme.of(context).copyWith( + preferBelow: false, + ), + child: Align( + alignment: AlignmentDirectional.bottomEnd, + child: SlideshowBottomOverlay( + animationController: _overlayAnimationController, + availableSize: availableSize, + viewInsets: _frozenViewInsets, + viewPadding: _frozenViewPadding, + ), + ), + ); + } + + Widget _buildViewerTopOverlay(Size availableSize) { + Widget child = ValueListenableBuilder<AvesEntry?>( + valueListenable: entryNotifier, + builder: (context, mainEntry, child) { + if (mainEntry == null) return const SizedBox(); + + return SlideTransition( + position: _overlayTopOffset, + child: ViewerTopOverlay( + entries: entries, + index: _currentEntryIndex, + mainEntry: mainEntry, + scale: _overlayButtonScale, + hasCollection: hasCollection, + expandedNotifier: _overlayExpandedNotifier, + availableSize: availableSize, + viewInsets: _frozenViewInsets, + viewPadding: _frozenViewPadding, + ), + ); + }, + ); + + child = ValueListenableBuilder<int>( + valueListenable: _currentVerticalPage, + builder: (context, page, child) { + return Visibility( + visible: page == imagePage, + child: child!, + ); + }, + child: child, + ); + + return child; + } + + Widget _buildViewerBottomOverlay(Size availableSize) { + Widget child = ValueListenableBuilder<AvesEntry?>( + valueListenable: entryNotifier, + builder: (context, mainEntry, child) { + if (mainEntry == null) return const SizedBox(); + + final multiPageController = mainEntry.isMultiPage ? context.read<MultiPageConductor>().getController(mainEntry) : null; + + Widget? _buildExtraBottomOverlay({AvesEntry? pageEntry}) { + final targetEntry = pageEntry ?? mainEntry; + Widget? child; + // a 360 video is both a video and a panorama but only the video controls are displayed + if (targetEntry.isPureVideo) { + child = Selector<VideoConductor, AvesVideoController?>( + selector: (context, vc) => vc.getController(targetEntry), + builder: (context, videoController, child) => VideoControlOverlay( + entry: targetEntry, + controller: videoController, + scale: _overlayVideoControlScale, + onActionSelected: (action) { + if (videoController != null) { + _onVideoAction( + context: context, + entry: targetEntry, + controller: videoController, + action: action, + ); + } + }, + ), + ); + } else if (targetEntry.is360) { + child = PanoramaOverlay( + entry: targetEntry, + scale: _overlayButtonScale, + ); + } + return child != null + ? ExtraBottomOverlay( + viewInsets: _frozenViewInsets, + viewPadding: _frozenViewPadding, + child: child, + ) + : null; + } + + final extraBottomOverlay = mainEntry.isMultiPage + ? PageEntryBuilder( + multiPageController: multiPageController, + builder: (pageEntry) => _buildExtraBottomOverlay(pageEntry: pageEntry) ?? const SizedBox(), + ) + : _buildExtraBottomOverlay(); + + return TooltipTheme( + data: TooltipTheme.of(context).copyWith( + preferBelow: false, + ), + child: Column( + children: [ + if (extraBottomOverlay != null) extraBottomOverlay, + ViewerBottomOverlay( + entries: entries, + index: _currentEntryIndex, + collection: collection, + animationController: _overlayAnimationController, + availableSize: availableSize, + viewInsets: _frozenViewInsets, + viewPadding: _frozenViewPadding, + multiPageController: multiPageController, + ), + ], + ), + ); + }, + ); + + child = Selector<MediaQueryData, double>( + selector: (context, mq) => mq.size.height, + builder: (context, mqHeight, child) { + // when orientation change, the `PageController` offset is not updated right away + // and it does not trigger its listeners when it does, so we force a refresh in the next frame + WidgetsBinding.instance.addPostFrameCallback((_) => _onVerticalPageControllerChanged()); + return AnimatedBuilder( + animation: _verticalScrollNotifier, + builder: (context, child) => Positioned( + bottom: (_verticalPager.hasClients && _verticalPager.position.hasPixels ? _verticalPager.offset : 0) - availableSize.height, + child: child!, + ), + child: child, + ); + }, + child: child, + ); + + return child; + } + + bool _handleNotification(dynamic notification) { + if (notification is SelectFilterNotification) { + _goToCollection(notification.filter); + } else if (notification is CastNotification) { + _cast(notification.enabled); + } else if (notification is FullImageLoadedNotification) { + // microtask so that listeners do not trigger during build + scheduleMicrotask(() { + if (!mounted) return; + final viewStateController = context.read<ViewStateConductor>().getController(notification.entry); + viewStateController?.fullImageNotifier.value = notification.image; + }); + } else if (notification is EntryDeletedNotification) { + _onEntryRemoved(context, notification.entries); + } else if (notification is EntryMovedNotification) { + // only add or remove entries following user actions, + // instead of applying all collection source changes + final isBin = collection?.filters.contains(TrashFilter.instance) ?? false; + final entries = notification.entries; + switch (notification.moveType) { + case MoveType.move: + _onEntryRemoved(context, entries); + case MoveType.toBin: + if (!isBin) { + _onEntryRemoved(context, entries); + } + case MoveType.fromBin: + if (isBin) { + _onEntryRemoved(context, entries); + } else { + _onEntryRestored(entries); + } + case MoveType.copy: + case MoveType.export: + break; + } + } else if (notification is PopupMenuOpenedNotification) { + // if the menu is opened while overlay is hiding, + // the popup menu button is disposed and menu items are ineffective, + // so we make sure overlay stays visible + _overlayVisible.value = true; + _videoActionDelegate.stopOverlayHidingTimer(); + dismissFeedback(context); + } else if (notification is ToggleOverlayNotification) { + _overlayVisible.value = notification.visible ?? !_overlayVisible.value; + } else if (notification is LockViewNotification) { + _viewLocked.value = notification.locked; + } else if (notification is VideoActionNotification) { + _onVideoAction( + context: context, + entry: notification.entry, + controller: notification.controller, + action: notification.action, + ); + } else if (notification is TvShowLessInfoNotification) { + if (_overlayVisible.value) { + _overlayVisible.value = false; + } else { + _onPopInvoked(); + } + } else if (notification is TvShowMoreInfoNotification) { + if (!_overlayVisible.value) { + _overlayVisible.value = true; + } + } else if (notification is PopVisualNotification) { + _popVisual(); + } else if (notification is ShowInfoPageNotification) { + _goToVerticalPage(infoPage); + } else if (notification is ShowPreviousEntryNotification) { + _goToHorizontalPageByDelta(delta: -1, animate: notification.animate); + } else if (notification is ShowNextEntryNotification) { + _goToHorizontalPageByDelta(delta: 1, animate: notification.animate); + } else if (notification is ShowEntryNotification) { + _goToHorizontalPageByIndex(page: notification.index, animate: notification.animate); + } else { + return false; + } + return true; + } + + Future<void> _cast(bool enabled) async { + if (enabled) { + final entries = collection?.sortedEntries; + if (entries != null) { + await viewerController.initCast(context, entries); + final entry = entryNotifier.value; + if (entry != null) { + await viewerController.castEntry(entry); + } + } + } else { + await viewerController.stopCast(); + } + } + + Future<void> _onVideoAction({ + required BuildContext context, + required AvesEntry entry, + required AvesVideoController controller, + required EntryAction action, + }) async { + if (action == EntryAction.videoToggleMute) { + final override = !controller.isMuted; + videoMutedOverride = override; + await context.read<VideoConductor>().muteAll(override); + } else { + await _videoActionDelegate.onActionSelected(context, entry, controller, action); + } + } + + void _onVerticalPageControllerChanged() { + if (!_isEntryTracked && _verticalPager.hasClients && _verticalPager.page?.floor() == transitionPage) { + _trackEntry(); + } + _verticalScrollNotifier.notify(); + } + + Future<void> _goToCollection(CollectionFilter filter) async { + final isMainMode = context.read<ValueNotifier<AppMode>>().value == AppMode.main; + if (!isMainMode) return; + + final baseCollection = collection; + if (baseCollection == null) return; + + await _onLeave(); + final uri = entryNotifier.value?.uri; + unawaited(Navigator.maybeOf(context)?.pushAndRemoveUntil( + MaterialPageRoute( + settings: const RouteSettings(name: CollectionPage.routeName), + builder: (context) => CollectionPage( + source: baseCollection.source, + filters: {...baseCollection.filters, filter}, + highlightTest: uri != null ? (entry) => entry.uri == uri : null, + ), + ), + (route) => false, + )); + } + + Future<void> _goToVerticalPage(int page) async { + if (settings.animate) { + final start = _verticalPager.offset; + final end = _verticalPager.position.viewportDimension * page; + final simulation = ScrollSpringSimulation(ViewerVerticalPageView.spring, start, end, 0); + unawaited(_verticalPageAnimationController.animateWith(simulation)); + } else { + _verticalPager.jumpToPage(page); + } + } + + void _onVerticalPageChanged(int page) { + _currentVerticalPage.value = page; + _overrideSnackBarMargin(); + final animate = context.read<Settings>().animate; + switch (page) { + case transitionPage: + dismissFeedback(context); + _popVisual(); + if (!animate) { + _verticalPager.jumpToPage(page); + } + case imagePage: + reportService.log('Nav move to Image page'); + case infoPage: + reportService.log('Nav move to Info page'); + // prevent hero when viewer is offscreen + _heroInfoNotifier.value = null; + if (!animate) { + _verticalPager.jumpToPage(page); + } + } + } + + void _goToHorizontalPageByDelta({required int delta, required bool animate}) { + if (_horizontalPager.positions.isEmpty) return; + + final page = _horizontalPager.page?.round(); + if (page != null) { + _goToHorizontalPageByIndex(page: page + delta, animate: animate); + } + } + + Future<void> _goToHorizontalPageByIndex({required int page, required bool animate}) async { + final _collection = collection; + if (_collection != null) { + if (!widget.viewerController.repeat) { + page = page.clamp(0, _collection.entryCount - 1); + } + if (_currentEntryIndex != page) { + final animationDuration = animate ? context.read<DurationsData>().viewerHorizontalPageScrollAnimation : Duration.zero; + if (animationDuration > Duration.zero) { + // duration & curve should feel similar to changing page by fling + await _horizontalPager.animateToPage( + page, + duration: animationDuration, + curve: Curves.easeOutCubic, + ); + } else { + _horizontalPager.jumpToPage(page); + } + } + } + } + + void _onHorizontalPageChanged(int page) { + _currentEntryIndex = page; + if (viewerController.repeat) { + _currentEntryIndex %= entries.length; + } + _updateEntry(); + } + + void _onCollectionChanged() { + _updateEntry(); + } + + void _onEntryRestored(Set<AvesEntry> restoredEntries) { + if (restoredEntries.isEmpty) return; + + final _collection = collection; + if (_collection != null) { + _collection.refresh(); + final index = _collection.sortedEntries.indexOf(restoredEntries.first); + if (index != -1) { + _onHorizontalPageChanged(index); + } + _onCollectionChanged(); + } + } + + // deleted or moved to another album + void _onEntryRemoved(BuildContext context, Set<AvesEntry> removedEntries) { + if (removedEntries.isEmpty) return; + + if (hasCollection) { + final collectionEntries = collection!.sortedEntries; + removedEntries.forEach((removedEntry) { + // remove from collection + if (collectionEntries.remove(removedEntry)) return; + + // remove from burst + final mainEntry = collectionEntries.firstWhereOrNull((entry) => entry.stackedEntries?.contains(removedEntry) == true); + if (mainEntry != null) { + final multiPageController = context.read<MultiPageConductor>().getController(mainEntry); + if (multiPageController != null) { + mainEntry.stackedEntries!.remove(removedEntry); + multiPageController.reset(); + } + } + }); + if (collectionEntries.isNotEmpty) { + _onCollectionChanged(); + return; + } + } + + if (Navigator.canPop(context)) { + Navigator.maybeOf(context)?.pop(); + } else { + _leaveViewer(); + } + } + + Future<void> _updateEntry() async { + if (entries.isNotEmpty && _currentEntryIndex >= entries.length) { + // as of Flutter v1.22.2, `PageView` does not call `onPageChanged` when the last page is deleted + // so we manually track the page change, and let the entry update follow + _onHorizontalPageChanged(entries.length - 1); + return; + } + + final newEntry = _currentEntryIndex < entries.length ? entries[_currentEntryIndex] : null; + if (entryNotifier.value == newEntry) return; + cleanEntryControllers(entryNotifier.value); + entryNotifier.value = newEntry; + _isEntryTracked = false; + await pauseVideoControllers(); + await initEntryControllers(newEntry); + + if (viewerController.isCasting) { + final entry = entryNotifier.value; + if (entry != null) { + await viewerController.castEntry(entry); + } + } + } + + void _onPopInvoked() { + if (_currentVerticalPage.value == infoPage) { + // back from info to image + _goToVerticalPage(imagePage); + } else { + if (!_isEntryTracked) _trackEntry(); + _popVisual(); + } + } + + void _popVisual() { + if (Navigator.canPop(context)) { + Future<void> pop() async { + await _onLeave(); + Navigator.maybeOf(context)?.pop(); + } + + // closing hero, with viewer as source + final heroInfo = EntryHeroInfo(collection, entryNotifier.value); + if (_heroInfoNotifier.value != heroInfo) { + _heroInfoNotifier.value = heroInfo; + // we post closing the viewer page so that hero animation source is ready + WidgetsBinding.instance.addPostFrameCallback((_) => pop()); + } else { + // viewer already has correct hero info, no need to rebuild + pop(); + } + } else { + // exit app when trying to pop a viewer page + _leaveViewer(); + } + } + + Future<void> _leaveViewer() async { + // widgets do not get disposed normally when popping the `SystemNavigator` + // so we manually clean video controllers and save playback state + await context.read<VideoConductor>().dispose(); + await SystemNavigator.pop(); + } + + // track item when returning to collection, + // if they are not fully visible already + void _trackEntry() { + _isEntryTracked = true; + final entry = entryNotifier.value; + if (entry != null && hasCollection) { + context.read<HighlightInfo>().trackItem( + entry, + predicate: (v) => v < 1, + animate: false, + ); + context.read<ViewerEntryNotifier>().value = entry; + } + } + + Future<void> _onLeave() async { + // get the theme first, as the context is likely + // to be unmounted after the other async steps + final theme = Theme.of(context); + + await viewerController.stopCast(); + + try { + switch (settings.maxBrightness) { + case MaxBrightness.never: + case MaxBrightness.viewerOnly: + await AvesApp.screenBrightness?.resetApplicationScreenBrightness(); + case MaxBrightness.always: + await AvesApp.screenBrightness?.setApplicationScreenBrightness(1); + } + } on PlatformException catch (e, stack) { + // `screen_brightness` plugin may fail + unawaited(reportService.recordError(e, stack)); + } + if (settings.keepScreenOn == KeepScreenOn.viewerOnly) { + await windowService.keepScreenOn(false); + } + await mediaSessionService.release(); + await _showSystemUI(context, true); + AvesApp.setSystemUIStyle(theme); + if (!settings.useTvLayout) { + await windowService.requestOrientation(); + } + // delay to prevent white/black flash on page transition + // from a viewer with a transparent background and no system UI + // to a regular page with system UI + await Future.delayed(const Duration(milliseconds: 50)); + } + + // overlay + + Future<void> _initOverlay() async { + final appMode = context.read<ValueNotifier<AppMode>>().value; + if (appMode == AppMode.screenSaver) { + _overlayVisible.value = false; + await _onOverlayVisibleChanged(animate: false); + } else { + // wait for MaterialPageRoute.transitionDuration + // to show overlay after hero animation is complete + await Future.delayed(ModalRoute.of(context)!.transitionDuration * timeDilation); + await _onOverlayVisibleChanged(); + } + _overlayInitialized = true; + } + + Future<void> _onOverlayVisibleChanged({bool animate = true}) async { + if (!mounted) return; + if (_overlayVisible.value) { + if (_viewLocked.value) { + await _startOverlayHidingTimer(); + } else { + await _showSystemUI(context, true); + AvesApp.setSystemUIStyle(Theme.of(context)); + } + if (animate) { + await _overlayAnimationController.forward(); + } else { + _overlayAnimationController.value = _overlayAnimationController.upperBound; + } + viewerController.autopilot = false; + } else { + final mediaQuery = context.read<MediaQueryData>(); + setState(() { + _frozenViewInsets = mediaQuery.viewInsets; + _frozenViewPadding = mediaQuery.viewPadding; + }); + await _showSystemUI(context, false); + if (animate) { + await _overlayAnimationController.reverse(); + } else { + _overlayAnimationController.reset(); + } + setState(() { + _frozenViewInsets = null; + _frozenViewPadding = null; + }); + } + } + + Future<void> _onViewLockedChanged() async { + if (_viewLocked.value) { + await _showSystemUI(context, false); + await _startOverlayHidingTimer(); + } else { + await _showSystemUI(context, true); + AvesApp.setSystemUIStyle(Theme.of(context)); + _stopOverlayHidingTimer(); + _overlayVisible.value = true; + } + } + + Future<void> _startOverlayHidingTimer() async { + _stopOverlayHidingTimer(); + final duration = await settings.timeToTakeAction.getSnackBarDuration(true); + _overlayHidingTimer = Timer(duration, () => _overlayVisible.value = false); + } + + void _stopOverlayHidingTimer() => _overlayHidingTimer?.cancel(); + + Future<void> _showSystemUI(BuildContext context, bool show) async { + final appMode = context.read<ValueNotifier<AppMode>>().value; + if (appMode == AppMode.screenSaver) { + // as of Flutter v3.22.1, calls to `SystemChrome.setEnabledSystemUIMode` hang when app is used as a screen saver + return; + } + + if (show) { + await AvesApp.showSystemUI(); + } else { + await AvesApp.hideSystemUI(); + } + } +} diff --git a/lib/widgets/viewer/hero.dart b/lib/widgets/viewer/hero.dart new file mode 100644 index 0000000..d1432d3 --- /dev/null +++ b/lib/widgets/viewer/hero.dart @@ -0,0 +1,20 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:equatable/equatable.dart'; +import 'package:flutter/widgets.dart'; + +@immutable +class EntryHeroInfo extends Equatable { + // hero tag should include a collection identifier, so that it animates + // between different views of the entry in the same collection (e.g. thumbnails <-> viewer) + // but not between different collection instances, even with the same attributes (e.g. reloading collection page via drawer) + final CollectionLens? collection; + final AvesEntry? entry; + + @override + List<Object?> get props => [collection?.id, entry?.uri]; + + const EntryHeroInfo(this.collection, this.entry); + + int get tag => Object.hashAll([collection?.id, entry?.uri]); +} diff --git a/lib/widgets/viewer/info/basic_section.dart b/lib/widgets/viewer/info/basic_section.dart new file mode 100644 index 0000000..09cf91f --- /dev/null +++ b/lib/widgets/viewer/info/basic_section.dart @@ -0,0 +1,397 @@ +import 'package:aves/app_mode.dart'; +import 'package:aves/image_providers/app_icon_image_provider.dart'; +import 'package:aves/model/app_inventory.dart'; +import 'package:aves/model/dynamic_albums.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/favourites.dart'; +import 'package:aves/model/entry/extensions/multipage.dart'; +import 'package:aves/model/entry/extensions/props.dart'; +import 'package:aves/model/favourites.dart'; +import 'package:aves/model/filters/covered/stored_album.dart'; +import 'package:aves/model/filters/covered/tag.dart'; +import 'package:aves/model/filters/date.dart'; +import 'package:aves/model/filters/favourite.dart'; +import 'package:aves/model/filters/mime.dart'; +import 'package:aves/model/filters/rating.dart'; +import 'package:aves/model/filters/type.dart'; +import 'package:aves/model/filters/weekday.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/ref/mime_types.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/theme/colors.dart'; +import 'package:aves/theme/format.dart'; +import 'package:aves/utils/file_utils.dart'; +import 'package:aves/utils/time_utils.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/action_controls/quick_choosers/rate_button.dart'; +import 'package:aves/widgets/common/action_controls/quick_choosers/tag_button.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/aves_filter_chip.dart'; +import 'package:aves/widgets/viewer/action/entry_info_action_delegate.dart'; +import 'package:aves/widgets/viewer/info/common.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; +import 'package:provider/provider.dart'; + +class BasicSection extends StatefulWidget { + final AvesEntry entry; + final CollectionLens? collection; + final EntryInfoActionDelegate actionDelegate; + final ValueNotifier<bool> isScrollingNotifier; + final ValueNotifier<EntryAction?> isEditingMetadataNotifier; + final AFilterCallback onFilterSelection; + + const BasicSection({ + super.key, + required this.entry, + this.collection, + required this.actionDelegate, + required this.isScrollingNotifier, + required this.isEditingMetadataNotifier, + required this.onFilterSelection, + }); + + @override + State<BasicSection> createState() => _BasicSectionState(); +} + +class _BasicSectionState extends State<BasicSection> { + final FocusNode _chipFocusNode = FocusNode(); + + CollectionLens? get collection => widget.collection; + + EntryInfoActionDelegate get actionDelegate => widget.actionDelegate; + + @override + void initState() { + super.initState(); + _registerWidget(widget); + _onScrollingChanged(); + } + + @override + void didUpdateWidget(covariant BasicSection oldWidget) { + super.didUpdateWidget(oldWidget); + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + + @override + void dispose() { + _unregisterWidget(widget); + _chipFocusNode.dispose(); + super.dispose(); + } + + void _registerWidget(BasicSection widget) { + widget.isScrollingNotifier.addListener(_onScrollingChanged); + } + + void _unregisterWidget(BasicSection widget) { + widget.isScrollingNotifier.removeListener(_onScrollingChanged); + } + + @override + Widget build(BuildContext context) { + final entry = widget.entry; + return AnimatedBuilder( + animation: entry.metadataChangeNotifier, + builder: (context, child) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _BasicInfo(entry: entry), + Focus( + focusNode: _chipFocusNode, + skipTraversal: true, + canRequestFocus: false, + child: _buildChips(context), + ), + _buildEditButtons(context), + ], + ); + }); + } + + Widget _buildChips(BuildContext context) { + final entry = widget.entry; + final tags = entry.tags.toList()..sort(compareAsciiUpperCaseNatural); + final dateTime = entry.bestDate; + final album = entry.directory; + final filters = { + MimeFilter(entry.mimeType), + if (entry.isAnimated) TypeFilter.animated, + if (entry.isGeotiff) TypeFilter.geotiff, + if (entry.isHdr) TypeFilter.hdr, + if (entry.isMotionPhoto) TypeFilter.motionPhoto, + if (entry.isRaw) TypeFilter.raw, + if (entry.isImage && entry.is360) TypeFilter.panorama, + if (entry.isPureVideo && entry.is360) TypeFilter.sphericalVideo, + if (entry.isPureVideo && !entry.is360) MimeFilter.video, + if (dateTime != null) ...[DateFilter(DateLevel.ymd, dateTime.date), WeekDayFilter(dateTime.weekday)], + if (album != null) StoredAlbumFilter(album, collection?.source.getStoredAlbumDisplayName(context, album)), + ...dynamicAlbums.all.where((v) => v.test(entry)).toSet(), + if (entry.rating != 0) RatingFilter(entry.rating), + ...tags.map(TagFilter.new), + }; + return AnimatedBuilder( + animation: favourites, + builder: (context, child) { + final effectiveFilters = [ + ...filters, + if (entry.isFavourite) FavouriteFilter.instance, + ]..sort(); + + return Padding( + padding: const EdgeInsets.symmetric(horizontal: AvesFilterChip.outlineWidth / 2) + const EdgeInsets.only(top: 8), + child: Wrap( + spacing: 8, + runSpacing: 8, + children: effectiveFilters + .map((filter) => AvesFilterChip( + filter: filter, + onTap: widget.onFilterSelection, + )) + .toList(), + ), + ); + }, + ); + } + + Widget _buildEditButtons(BuildContext context) { + final appMode = context.watch<ValueNotifier<AppMode>>().value; + final entry = widget.entry; + final children = [ + EntryAction.editRating, + EntryAction.editTags, + ] + .where((v) => actionDelegate.isVisible( + appMode: appMode, + targetEntry: entry, + action: v, + )) + .where((v) => actionDelegate.canApply(entry, v)) + .map((v) => _buildEditMetadataButton(context, v)) + .toList(); + + return children.isEmpty + ? const SizedBox() + : TooltipTheme( + data: TooltipTheme.of(context).copyWith( + preferBelow: false, + ), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: AvesFilterChip.outlineWidth / 2) + const EdgeInsets.only(top: 8), + child: Wrap( + spacing: 8, + runSpacing: 8, + children: children, + ), + ), + ); + } + + Widget _buildEditMetadataButton(BuildContext context, EntryAction action) { + final entry = widget.entry; + return ValueListenableBuilder<EntryAction?>( + valueListenable: widget.isEditingMetadataNotifier, + builder: (context, editingAction, child) { + final isEditing = editingAction != null; + final onPressed = isEditing ? null : () => actionDelegate.onActionSelected(context, entry, collection, action); + Widget button; + switch (action) { + case EntryAction.editRating: + button = RateButton( + blurred: false, + onChooserValue: (rating) => actionDelegate.quickRate(context, entry, rating), + onPressed: onPressed, + ); + case EntryAction.editTags: + button = TagButton( + blurred: false, + onChooserValue: (filter) => actionDelegate.quickTag(context, entry, filter), + onPressed: onPressed, + ); + default: + button = IconButton( + icon: action.getIcon(), + onPressed: onPressed, + tooltip: action.getText(context), + ); + } + return Stack( + children: [ + DecoratedBox( + decoration: BoxDecoration( + border: Border.fromBorderSide(BorderSide( + color: isEditing ? Theme.of(context).disabledColor : context.select<AvesColorsData, Color>((v) => v.neutral), + width: AvesFilterChip.outlineWidth, + )), + borderRadius: const BorderRadius.all(Radius.circular(AvesFilterChip.defaultRadius)), + ), + child: button, + ), + Positioned.fill( + child: Visibility( + visible: editingAction == action, + child: const Padding( + padding: EdgeInsets.all(1.0), + child: CircularProgressIndicator( + strokeWidth: AvesFilterChip.outlineWidth, + ), + ), + ), + ), + ], + ); + }, + ); + } + + void _onScrollingChanged() { + if (!widget.isScrollingNotifier.value) { + if (settings.useTvLayout) { + // using `autofocus` while scrolling seems to fail for widget built offscreen + // so we give focus to this page when the screen is no longer scrolling + _chipFocusNode.children.firstOrNull?.requestFocus(); + } + } + } +} + +class _BasicInfo extends StatefulWidget { + final AvesEntry entry; + + const _BasicInfo({ + required this.entry, + }); + + @override + State<_BasicInfo> createState() => _BasicInfoState(); +} + +class _BasicInfoState extends State<_BasicInfo> { + Future<String?> _ownerPackageLoader = SynchronousFuture(null); + Future<void> _appNameLoader = SynchronousFuture(null); + + AvesEntry get entry => widget.entry; + + static const ownerPackageNamePropKey = 'owner_package_name'; + static const iconSize = 20.0; + + @override + void initState() { + super.initState(); + if (!entry.trashed && entry.isMediaStoreMediaContent) { + _ownerPackageLoader = metadataFetchService.hasContentResolverProp(ownerPackageNamePropKey).then((exists) { + return exists ? metadataFetchService.getContentResolverProp(entry, ownerPackageNamePropKey) : SynchronousFuture(null); + }); + final isViewerMode = context.read<ValueNotifier<AppMode>>().value == AppMode.view; + if (isViewerMode && settings.isInstalledAppAccessAllowed) { + _appNameLoader = appInventory.initAppNames(); + } + } + } + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + final infoUnknown = l10n.viewerInfoUnknown; + final locale = context.locale; + final use24hour = MediaQuery.alwaysUse24HourFormatOf(context); + + // TODO TLAD line break on all characters for the following fields when this is fixed: https://github.com/flutter/flutter/issues/61081 + // inserting ZWSP (\u200B) between characters does help, but it messes with width and height computation (another Flutter issue) + final title = entry.bestTitle ?? infoUnknown; + final date = entry.bestDate; + final dateText = date != null ? formatDateTime(date, locale, use24hour) : infoUnknown; + final showResolution = !entry.isSvg && entry.isSized; + final sizeText = entry.sizeBytes != null ? formatFileSize(locale, entry.sizeBytes!) : infoUnknown; + final path = entry.path; + + return FutureBuilder<String?>( + future: _ownerPackageLoader, + builder: (context, snapshot) { + final ownerPackage = snapshot.data; + return FutureBuilder<void>( + future: _appNameLoader, + builder: (context, snapshot) { + return InfoRowGroup( + info: { + l10n.viewerInfoLabelTitle: title, + l10n.viewerInfoLabelDate: dateText, + if (entry.isVideo) ..._buildVideoRows(context), + if (showResolution) l10n.viewerInfoLabelResolution: context.applyDirectionality(getRasterResolutionText(locale)), + l10n.viewerInfoLabelSize: context.applyDirectionality(sizeText), + if (!entry.trashed) l10n.viewerInfoLabelUri: entry.uri, + if (path != null) l10n.viewerInfoLabelPath: path, + if (ownerPackage != null) l10n.viewerInfoLabelOwner: ownerPackage, + }, + spanBuilders: { + l10n.viewerInfoLabelOwner: _ownerHandler(ownerPackage), + }, + ); + }, + ); + }, + ); + } + + Map<String, String> _buildVideoRows(BuildContext context) { + return { + context.l10n.viewerInfoLabelDuration: entry.durationText, + }; + } + + InfoValueSpanBuilder _ownerHandler(String? ownerPackage) { + if (ownerPackage == null) return (context, key, value) => []; + + final appName = appInventory.getCurrentAppName(ownerPackage) ?? ownerPackage; + return (context, key, value) => [ + WidgetSpan( + alignment: PlaceholderAlignment.middle, + child: Padding( + padding: const EdgeInsetsDirectional.only(start: 2, end: 4), + child: ConstrainedBox( + // use constraints instead of sizing `Image`, + // so that it can collapse when handling an empty image + constraints: const BoxConstraints( + maxWidth: iconSize, + maxHeight: iconSize, + ), + child: Image( + image: AppIconImage( + packageName: ownerPackage, + size: iconSize, + ), + ), + ), + ), + ), + TextSpan( + text: appName, + style: InfoRowGroup.valueStyle, + ), + ]; + } + + String getRasterResolutionText(String locale) { + var s = entry.getResolutionText(locale); + + // guess whether this is a photo, according to file type + final isPhoto = [MimeTypes.heic, MimeTypes.heif, MimeTypes.jpeg, MimeTypes.tiff].contains(entry.mimeType) || entry.isRaw; + if (isPhoto) { + final megaPixels = (entry.width * entry.height / 1000000).round(); + if (megaPixels > 0) { + s += ' • ${NumberFormat('0', locale).format(megaPixels)} MP'; + } + } + + return s; + } +} diff --git a/lib/widgets/viewer/info/color_section.dart b/lib/widgets/viewer/info/color_section.dart new file mode 100644 index 0000000..abecb67 --- /dev/null +++ b/lib/widgets/viewer/info/color_section.dart @@ -0,0 +1,124 @@ +import 'dart:async'; +import 'dart:isolate'; +import 'dart:math'; +import 'dart:ui' as ui; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/images.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/basic/color_indicator.dart'; +import 'package:aves/widgets/viewer/info/common.dart'; +import 'package:flex_color_picker/flex_color_picker.dart' as flex; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:flutter_staggered_animations/flutter_staggered_animations.dart'; +import 'package:palette_generator/palette_generator.dart'; +import 'package:provider/provider.dart'; + +class ColorSectionSliver extends StatefulWidget { + final AvesEntry entry; + + const ColorSectionSliver({super.key, required this.entry}); + + @override + State<ColorSectionSliver> createState() => _ColorSectionSliverState(); +} + +class _ColorSectionSliverState extends State<ColorSectionSliver> { + late final Future<List<Color>> _paletteLoader; + + @override + void initState() { + super.initState(); + final provider = widget.entry.getThumbnail(extent: min(200, widget.entry.displaySize.longestSide)); + _paletteLoader = _loadPalette(provider); + } + + @override + Widget build(BuildContext context) { + return SliverToBoxAdapter( + child: FutureBuilder<List<Color>>( + future: _paletteLoader, + builder: (context, snapshot) { + final colors = snapshot.data; + if (colors == null || colors.isEmpty) return const SizedBox(); + + final durations = context.watch<DurationsData>(); + return Wrap( + alignment: WrapAlignment.center, + children: AnimationConfiguration.toStaggeredList( + duration: durations.staggeredAnimation, + delay: durations.staggeredAnimationDelay * timeDilation, + childAnimationBuilder: (child) => SlideAnimation( + verticalOffset: 50.0, + child: FadeInAnimation( + child: child, + ), + ), + children: [ + const SectionRow(icon: AIcons.palette), + ...colors.map( + (v) => Padding( + padding: const EdgeInsets.all(8), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + ColorIndicator(value: v), + const SizedBox(width: 8), + Directionality( + textDirection: TextDirection.ltr, + child: SelectableText( + '#${v.hex}', + style: const TextStyle(fontFamily: 'monospace'), + ), + ), + ], + ), + ), + ), + ], + ), + ); + }, + ), + ); + } + + // `PaletteGenerator.fromImage()` directly blocks the main isolate, + // so we use another isolate to compute the palette + Future<List<Color>> _loadPalette(ImageProvider provider) async { + final stream = provider.resolve(ImageConfiguration.empty); + final imageCompleter = Completer<ui.Image>(); + late ImageStreamListener listener; + listener = ImageStreamListener((info, _) { + stream.removeListener(listener); + imageCompleter.complete(info.image); + }); + stream.addListener(listener); + final image = await imageCompleter.future; + final imageData = await image.toByteData(); + if (imageData == null) { + throw StateError('Failed to encode the image.'); + } + + final encodedImage = EncodedImage( + imageData, + width: image.width, + height: image.height, + ); + final generator = await _getPaletteGenerator(encodedImage); + return generator.paletteColors.map((v) => v.color).toList(); + } + + // the isolate does not start unless called from a static method + static Future<PaletteGenerator> _getPaletteGenerator(EncodedImage encodedImage) { + // `Isolate.run()` closure supports passing `EncodedImage` but not `ui.Image` + return Isolate.run(() => PaletteGenerator.fromByteData( + encodedImage, + maximumColorCount: 10, + // do not use the default palette filter + filters: [], + )); + } +} diff --git a/lib/widgets/viewer/info/common.dart b/lib/widgets/viewer/info/common.dart new file mode 100644 index 0000000..16c4e9d --- /dev/null +++ b/lib/widgets/viewer/info/common.dart @@ -0,0 +1,198 @@ +import 'dart:math'; + +import 'package:aves/widgets/common/basic/link_chip.dart'; +import 'package:aves/widgets/common/identity/aves_filter_chip.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; + +class SectionRow extends StatelessWidget { + final IconData icon; + + const SectionRow({ + super.key, + required this.icon, + }); + + @override + Widget build(BuildContext context) { + const dim = 32.0; + Widget buildDivider() => const SizedBox( + width: dim, + child: Divider( + thickness: AvesFilterChip.outlineWidth, + ), + ); + return Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + buildDivider(), + Padding( + padding: const EdgeInsets.all(16), + child: Icon( + icon, + size: dim, + ), + ), + buildDivider(), + ], + ); + } +} + +class InfoRowGroup extends StatefulWidget { + final Map<String, String> info; + final int maxValueLength; + final Map<String, InfoValueSpanBuilder> spanBuilders; + + static const int defaultMaxValueLength = 140; + static const double keyValuePadding = 16; + static const double fontSize = 13; + static const valueStyle = TextStyle(fontSize: fontSize); + static final _keyStyle = valueStyle.copyWith(height: 2.0); + + static TextStyle keyStyle(BuildContext context) { + final theme = Theme.of(context); + return theme.textTheme.bodySmall!.copyWith(color: theme.colorScheme.onSurfaceVariant).merge(_keyStyle); + } + + const InfoRowGroup({ + super.key, + required this.info, + this.maxValueLength = defaultMaxValueLength, + Map<String, InfoValueSpanBuilder>? spanBuilders, + }) : spanBuilders = spanBuilders ?? const {}; + + @override + State<InfoRowGroup> createState() => _InfoRowGroupState(); + + static InfoValueSpanBuilder linkSpanBuilder({ + required String Function(BuildContext context) linkText, + required void Function(BuildContext context) onTap, + }) { + return (context, key, value) { + value = linkText(context); + // `colorScheme.secondary` is overridden upstream as an `ExpansionTileCard` theming workaround, + // so we use `colorScheme.primary` instead + final linkColor = Theme.of(context).colorScheme.primary; + + return [ + WidgetSpan( + child: LinkChip( + text: value, + color: linkColor, + textStyle: InfoRowGroup.valueStyle, + // open link on tap + onTap: () => onTap(context), + ), + alignment: PlaceholderAlignment.middle, + ), + ]; + }; + } +} + +class _InfoRowGroupState extends State<InfoRowGroup> { + final List<String> _expandedKeys = []; + + Map<String, String> get keyValues => widget.info; + + int get maxValueLength => widget.maxValueLength; + + Map<String, InfoValueSpanBuilder> get spanBuilders => widget.spanBuilders; + + @override + Widget build(BuildContext context) { + if (keyValues.isEmpty) return const SizedBox(); + + final _keyStyle = InfoRowGroup.keyStyle(context); + + // compute the size of keys and space in order to align values + final textScaler = MediaQuery.textScalerOf(context); + final keySizes = Map.fromEntries(keyValues.keys.map((key) => MapEntry(key, _getSpanWidth(TextSpan(text: _buildTextValue(key), style: _keyStyle), textScaler)))); + + final lastKey = keyValues.keys.last; + return LayoutBuilder( + builder: (context, constraints) { + // find longest key below threshold + final maxBaseValueX = constraints.maxWidth / 3; + final baseValueX = keySizes.values.where((size) => size < maxBaseValueX).fold(0.0, max); + + return SelectableText.rich( + TextSpan( + children: keyValues.entries.expand( + (kv) { + final key = kv.key; + final value = kv.value; + final customSpanBuilder = spanBuilders[key]; + final spanBuilder = customSpanBuilder ?? _buildTextValueSpans; + final thisSpaceSize = max(0.0, (baseValueX - keySizes[key]!)) + InfoRowGroup.keyValuePadding; + + InlineSpan paddingSpan; + if (customSpanBuilder != null) { + // add padding using hair spaces instead of a straightforward `SizedBox` in a `WidgetSpan`, + // because ordering of multiple `WidgetSpan`s (e.g. with owner app icon) in Bidi context is tricky + final baseSpaceWidth = _getSpanWidth(TextSpan(text: '\u200A' * 100, style: _keyStyle), textScaler); + final spaceCount = (100 * thisSpaceSize / baseSpaceWidth).round(); + paddingSpan = TextSpan(text: '\u200A' * spaceCount); + } else { + final textScaleFactor = textScaler.scale(thisSpaceSize) / thisSpaceSize; + paddingSpan = WidgetSpan( + child: SizedBox( + width: thisSpaceSize / textScaleFactor, + // as of Flutter v3.0.0, the underline decoration from the following `TextSpan` + // is applied to the `WidgetSpan` too, so we add a dummy `Text` as a workaround + child: const Text(''), + ), + ); + } + + return [ + TextSpan(text: _buildTextValue(key), style: _keyStyle), + paddingSpan, + ...spanBuilder(context, key, value), + if (key != lastKey) const TextSpan(text: '\n'), + ]; + }, + ).toList(), + ), + style: InfoRowGroup.valueStyle, + ); + }, + ); + } + + double _getSpanWidth(TextSpan span, TextScaler textScaler) { + final paragraph = RenderParagraph( + span, + textDirection: TextDirection.ltr, + textScaler: textScaler, + )..layout(const BoxConstraints(), parentUsesSize: true); + final width = paragraph.getMaxIntrinsicWidth(double.infinity); + paragraph.dispose(); + return width; + } + + List<InlineSpan> _buildTextValueSpans(BuildContext context, String key, String value) { + GestureRecognizer? recognizer; + + // long values are clipped, and made expandable by tapping them + final showPreviewOnly = maxValueLength > 0 && value.length > maxValueLength && !_expandedKeys.contains(key); + if (showPreviewOnly) { + value = '${value.substring(0, maxValueLength)}…'; + // show full value on tap + recognizer = TapGestureRecognizer()..onTap = () => setState(() => _expandedKeys.add(key)); + } + + return [TextSpan(text: _buildTextValue(value), recognizer: recognizer)]; + } + + // each text span embeds and pops a Bidi isolate, + // so that layout of the spans follows the directionality of the locale + // (e.g. keys on the right for RTL locale, whatever the key intrinsic directionality) + // and each span respects the directionality of its inner text only + String _buildTextValue(String value) => '${Unicode.FSI}$value${Unicode.PDI}'; +} + +typedef InfoValueSpanBuilder = List<InlineSpan> Function(BuildContext context, String key, String value); diff --git a/lib/widgets/viewer/info/embedded/embedded_data_opener.dart b/lib/widgets/viewer/info/embedded/embedded_data_opener.dart new file mode 100644 index 0000000..917fa63 --- /dev/null +++ b/lib/widgets/viewer/info/embedded/embedded_data_opener.dart @@ -0,0 +1,89 @@ +import 'dart:async'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/keys.dart'; +import 'package:aves/ref/mime_types.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/widgets/common/action_mixins/feedback.dart'; +import 'package:aves/widgets/common/behaviour/routes.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:aves/widgets/viewer/entry_viewer_page.dart'; +import 'package:aves/widgets/viewer/info/embedded/notifications.dart'; +import 'package:flutter/material.dart'; + +class EmbeddedDataOpener extends StatelessWidget with FeedbackMixin { + final bool enabled; + final AvesEntry entry; + final Widget child; + + const EmbeddedDataOpener({ + super.key, + required this.enabled, + required this.entry, + required this.child, + }); + + @override + Widget build(BuildContext context) { + return NotificationListener<OpenEmbeddedDataNotification>( + onNotification: (notification) { + if (enabled) { + _openEmbeddedData(context, notification); + return true; + } + return false; + }, + child: child, + ); + } + + Future<void> _openEmbeddedData(BuildContext context, OpenEmbeddedDataNotification notification) async { + late Map fields; + switch (notification.source) { + case EmbeddedDataSource.googleDevice: + fields = await embeddedDataService.extractGoogleDeviceItem(entry, notification.dataUri!); + case EmbeddedDataSource.motionPhotoVideo: + fields = await embeddedDataService.extractMotionPhotoVideo(entry); + case EmbeddedDataSource.mpf: + fields = await embeddedDataService.extractJpegMpfItem(entry, notification.mpfId!); + case EmbeddedDataSource.videoCover: + fields = await embeddedDataService.extractVideoEmbeddedPicture(entry); + case EmbeddedDataSource.xmp: + fields = await embeddedDataService.extractXmpDataProp(entry, notification.props, notification.mimeType); + } + AvesEntry.normalizeMimeTypeFields(fields); + final mimeType = fields[EntryFields.mimeType] as String?; + final uri = fields[EntryFields.uri] as String?; + if (mimeType == null || uri == null) { + showFeedback(context, FeedbackType.warn, context.l10n.viewerInfoOpenEmbeddedFailureFeedback); + return; + } + + if (!MimeTypes.isImage(mimeType) && !MimeTypes.isVideo(mimeType)) { + // open with another app + unawaited(appService.open(uri, mimeType, forceChooser: true).then((success) { + if (!success) { + // fallback to sharing, so that the file can be saved somewhere + appService.shareSingle(uri, mimeType).then((success) { + if (!success) showNoMatchingAppDialog(context); + }); + } + })); + return; + } + + _openTempEntry(context, AvesEntry.fromMap(fields)); + } + + void _openTempEntry(BuildContext context, AvesEntry tempEntry) { + Navigator.maybeOf(context)?.push( + TransparentMaterialPageRoute( + settings: const RouteSettings(name: EntryViewerPage.routeName), + pageBuilder: (context, a, sa) => EntryViewerPage( + initialEntry: tempEntry, + ), + ), + ); + } +} diff --git a/lib/widgets/viewer/info/embedded/notifications.dart b/lib/widgets/viewer/info/embedded/notifications.dart new file mode 100644 index 0000000..b8401f2 --- /dev/null +++ b/lib/widgets/viewer/info/embedded/notifications.dart @@ -0,0 +1,54 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; + +enum EmbeddedDataSource { googleDevice, motionPhotoVideo, mpf, videoCover, xmp } + +@immutable +class OpenEmbeddedDataNotification extends Notification { + final EmbeddedDataSource source; + final List<dynamic>? props; + final String? mimeType, dataUri; + final int? mpfId; + + const OpenEmbeddedDataNotification._private({ + required this.source, + this.props, + this.mimeType, + this.dataUri, + this.mpfId, + }); + + factory OpenEmbeddedDataNotification.googleDevice({ + required String dataUri, + }) => + OpenEmbeddedDataNotification._private( + source: EmbeddedDataSource.googleDevice, + dataUri: dataUri, + ); + + factory OpenEmbeddedDataNotification.motionPhotoVideo() => const OpenEmbeddedDataNotification._private( + source: EmbeddedDataSource.motionPhotoVideo, + ); + + factory OpenEmbeddedDataNotification.mpf(int id) => OpenEmbeddedDataNotification._private( + source: EmbeddedDataSource.mpf, + mpfId: id, + ); + + factory OpenEmbeddedDataNotification.videoCover() => const OpenEmbeddedDataNotification._private( + source: EmbeddedDataSource.videoCover, + ); + + factory OpenEmbeddedDataNotification.xmp({ + required List<dynamic> props, + required String mimeType, + }) => + OpenEmbeddedDataNotification._private( + source: EmbeddedDataSource.xmp, + props: props, + mimeType: mimeType, + ); + + @override + String toString() => '$runtimeType#${shortHash(this)}{source=$source, props=$props, mimeType=$mimeType, dataUri=$dataUri, index=$mpfId}'; +} diff --git a/lib/widgets/viewer/info/info_app_bar.dart b/lib/widgets/viewer/info/info_app_bar.dart new file mode 100644 index 0000000..566b13d --- /dev/null +++ b/lib/widgets/viewer/info/info_app_bar.dart @@ -0,0 +1,127 @@ +import 'package:aves/app_mode.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/props.dart'; +import 'package:aves/model/selection.dart'; +import 'package:aves/model/settings/enums/accessibility_animations.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/app_bar/app_bar_title.dart'; +import 'package:aves/widgets/common/app_bar/sliver_app_bar_title.dart'; +import 'package:aves/widgets/common/basic/font_size_icon_theme.dart'; +import 'package:aves/widgets/common/basic/popup/menu_row.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/search/route.dart'; +import 'package:aves/widgets/viewer/action/entry_info_action_delegate.dart'; +import 'package:aves/widgets/viewer/info/info_search_delegate.dart'; +import 'package:aves/widgets/viewer/info/metadata/metadata_dir.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:provider/provider.dart'; + +class InfoAppBar extends StatelessWidget { + final AvesEntry entry; + final CollectionLens? collection; + final EntryInfoActionDelegate actionDelegate; + final ValueNotifier<Map<String, MetadataDirectory>> metadataNotifier; + final VoidCallback onBackPressed; + + const InfoAppBar({ + super.key, + required this.entry, + required this.collection, + required this.actionDelegate, + required this.metadataNotifier, + required this.onBackPressed, + }); + + @override + Widget build(BuildContext context) { + final appMode = context.watch<ValueNotifier<AppMode>>().value; + bool isVisible(EntryAction action) => actionDelegate.isVisible( + appMode: appMode, + targetEntry: entry, + action: action, + ); + final commonActions = EntryActions.commonMetadataActions.where(isVisible); + final formatSpecificActions = EntryActions.formatSpecificMetadataActions.where(isVisible); + final useTvLayout = settings.useTvLayout; + final animations = context.select<Settings, AccessibilityAnimations>((v) => v.accessibilityAnimations); + return SliverAppBar( + leading: useTvLayout + ? null + : FontSizeIconTheme( + child: IconButton( + // key is expected by test driver + key: const Key('back-button'), + icon: const Icon(AIcons.goUp), + onPressed: onBackPressed, + tooltip: context.l10n.viewerInfoBackToViewerTooltip, + ), + ), + automaticallyImplyLeading: false, + title: SliverAppBarTitleWrapper( + child: InteractiveAppBarTitle( + onTap: () => _goToSearch(context), + child: Text(context.l10n.viewerInfoPageTitle), + ), + ), + actions: useTvLayout + ? [] + : [ + IconButton( + icon: const Icon(AIcons.search), + onPressed: () => _goToSearch(context), + tooltip: MaterialLocalizations.of(context).searchFieldLabel, + ), + if (entry.canEdit) + PopupMenuButton<EntryAction>( + itemBuilder: (context) => [ + ...commonActions.map((action) => _toMenuItem(context, action, enabled: actionDelegate.canApply(entry, action))), + if (formatSpecificActions.isNotEmpty) ...[ + const PopupMenuDivider(), + ...formatSpecificActions.map((action) => _toMenuItem(context, action, enabled: actionDelegate.canApply(entry, action))), + ], + if (isVisible(EntryAction.debug)) ...[ + const PopupMenuDivider(), + _toMenuItem(context, EntryAction.debug, enabled: true), + ] + ], + onSelected: (action) async { + // wait for the popup menu to hide before proceeding with the action + await Future.delayed(animations.popUpAnimationDelay * timeDilation); + await actionDelegate.onActionSelected(context, entry, collection, action); + }, + popUpAnimationStyle: animations.popUpAnimationStyle, + ), + ].map((v) => FontSizeIconTheme(child: v)).toList(), + floating: true, + ); + } + + PopupMenuItem<EntryAction> _toMenuItem(BuildContext context, EntryAction action, {required bool enabled}) { + return PopupMenuItem( + value: action, + enabled: enabled, + child: MenuRow(text: action.getText(context), icon: action.getIcon()), + ); + } + + void _goToSearch(BuildContext context) { + final isSelecting = context.read<Selection<AvesEntry>?>()?.isSelecting ?? false; + Navigator.maybeOf(context)?.push( + SearchPageRoute( + delegate: InfoSearchDelegate( + searchFieldLabel: context.l10n.viewerInfoSearchFieldLabel, + searchFieldStyle: Themes.searchFieldStyle(context), + entry: entry, + metadataNotifier: metadataNotifier, + isSelecting: isSelecting, + ), + ), + ); + } +} diff --git a/lib/widgets/viewer/info/info_page.dart b/lib/widgets/viewer/info/info_page.dart new file mode 100644 index 0000000..0326d63 --- /dev/null +++ b/lib/widgets/viewer/info/info_page.dart @@ -0,0 +1,292 @@ +import 'dart:async'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/multipage.dart'; +import 'package:aves/model/filters/filters.dart'; +import 'package:aves/model/selection.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/widgets/common/basic/insets.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/basic/tv_edge_focus.dart'; +import 'package:aves/widgets/viewer/action/entry_info_action_delegate.dart'; +import 'package:aves/widgets/viewer/controls/notifications.dart'; +import 'package:aves/widgets/viewer/info/basic_section.dart'; +import 'package:aves/widgets/viewer/info/color_section.dart'; +import 'package:aves/widgets/viewer/info/embedded/embedded_data_opener.dart'; +import 'package:aves/widgets/viewer/info/info_app_bar.dart'; +import 'package:aves/widgets/viewer/info/location_section.dart'; +import 'package:aves/widgets/viewer/info/metadata/metadata_dir.dart'; +import 'package:aves/widgets/viewer/info/metadata/metadata_section.dart'; +import 'package:aves/widgets/viewer/multipage/conductor.dart'; +import 'package:aves/widgets/viewer/page_entry_builder.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class InfoPage extends StatefulWidget { + final CollectionLens? collection; + final ValueNotifier<AvesEntry?> entryNotifier; + final ValueNotifier<bool> isScrollingNotifier; + + const InfoPage({ + super.key, + required this.collection, + required this.entryNotifier, + required this.isScrollingNotifier, + }); + + @override + State<StatefulWidget> createState() => _InfoPageState(); +} + +class _InfoPageState extends State<InfoPage> { + final ScrollController _scrollController = ScrollController(); + bool _scrollStartFromTop = false; + + static const splitScreenWidthThreshold = 600; + + @override + void dispose() { + _scrollController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return AvesScaffold( + body: GestureAreaProtectorStack( + child: SafeArea( + bottom: false, + child: NotificationListener<ScrollNotification>( + onNotification: _handleTopScroll, + child: ValueListenableBuilder<AvesEntry?>( + valueListenable: widget.entryNotifier, + builder: (context, mainEntry, child) { + if (mainEntry == null) return const SizedBox(); + + final isSelecting = context.select<Selection<AvesEntry>?, bool>((v) => v?.isSelecting ?? false); + Widget _buildContent({AvesEntry? pageEntry}) { + final targetEntry = pageEntry ?? mainEntry; + return EmbeddedDataOpener( + enabled: !isSelecting, + entry: targetEntry, + child: _InfoPageContent( + collection: widget.collection, + entry: targetEntry, + isScrollingNotifier: widget.isScrollingNotifier, + scrollController: _scrollController, + split: MediaQuery.sizeOf(context).width > splitScreenWidthThreshold, + goToViewer: _goToViewer, + ), + ); + } + + return mainEntry.isStack + ? PageEntryBuilder( + multiPageController: context.read<MultiPageConductor>().getController(mainEntry), + builder: (pageEntry) => _buildContent(pageEntry: pageEntry), + ) + : _buildContent(); + }, + ), + ), + ), + ), + resizeToAvoidBottomInset: false, + ); + } + + bool _handleTopScroll(ScrollNotification notification) { + if (notification is ScrollStartNotification) { + final metrics = notification.metrics; + _scrollStartFromTop = metrics.pixels == metrics.minScrollExtent; + } + if (_scrollStartFromTop) { + if (notification is ScrollUpdateNotification) { + _scrollStartFromTop = notification.scrollDelta! < 0; + } else if (notification is ScrollEndNotification) { + _scrollStartFromTop = false; + } else if (notification is OverscrollNotification) { + if (notification.overscroll < 0) { + _goToViewer(); + _scrollStartFromTop = false; + } + } + } + return false; + } + + void _goToViewer() { + ShowImageNotification().dispatch(context); + _scrollController.animateTo( + 0, + duration: ADurations.pageTransitionLoose, + curve: Curves.easeInOut, + ); + } +} + +class _InfoPageContent extends StatefulWidget { + final CollectionLens? collection; + final AvesEntry entry; + final ValueNotifier<bool> isScrollingNotifier; + final ScrollController scrollController; + final bool split; + final VoidCallback goToViewer; + + const _InfoPageContent({ + required this.collection, + required this.entry, + required this.isScrollingNotifier, + required this.scrollController, + required this.split, + required this.goToViewer, + }); + + @override + State<_InfoPageContent> createState() => _InfoPageContentState(); +} + +class _InfoPageContentState extends State<_InfoPageContent> { + final Set<StreamSubscription> _subscriptions = {}; + late EntryInfoActionDelegate _actionDelegate; + final ValueNotifier<Map<String, MetadataDirectory>> _metadataNotifier = ValueNotifier({}); + final ValueNotifier<EntryAction?> _isEditingMetadataNotifier = ValueNotifier(null); + + static const horizontalPadding = EdgeInsets.symmetric(horizontal: 8); + + CollectionLens? get collection => widget.collection; + + AvesEntry get entry => widget.entry; + + @override + void initState() { + super.initState(); + _registerWidget(widget); + } + + @override + void didUpdateWidget(covariant _InfoPageContent oldWidget) { + super.didUpdateWidget(oldWidget); + + if (oldWidget.entry != widget.entry) { + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + } + + @override + void dispose() { + _metadataNotifier.dispose(); + _isEditingMetadataNotifier.dispose(); + _unregisterWidget(widget); + super.dispose(); + } + + void _registerWidget(_InfoPageContent widget) { + _actionDelegate = EntryInfoActionDelegate(); + _subscriptions.add(_actionDelegate.eventStream.listen(_onActionDelegateEvent)); + } + + void _unregisterWidget(_InfoPageContent widget) { + _subscriptions + ..forEach((sub) => sub.cancel()) + ..clear(); + } + + @override + Widget build(BuildContext context) { + final basicSection = BasicSection( + entry: entry, + collection: collection, + actionDelegate: _actionDelegate, + isScrollingNotifier: widget.isScrollingNotifier, + isEditingMetadataNotifier: _isEditingMetadataNotifier, + onFilterSelection: _onFilterSelection, + ); + final locationAtTop = widget.split && entry.hasGps; + final locationSection = LocationSection( + collection: collection, + entry: entry, + showTitle: !locationAtTop, + isScrollingNotifier: widget.isScrollingNotifier, + onFilterSelection: _onFilterSelection, + ); + final basicAndLocationSliver = locationAtTop + ? SliverToBoxAdapter( + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded(child: basicSection), + const SizedBox(width: 8), + Expanded(child: locationSection), + ], + ), + ) + : SliverList( + delegate: SliverChildListDelegate.fixed( + [ + basicSection, + locationSection, + ], + ), + ); + + return NotificationListener<SelectFilterNotification>( + onNotification: (notification) { + _onFilterSelection(notification.filter); + return true; + }, + child: CustomScrollView( + controller: widget.scrollController, + slivers: [ + const SliverToBoxAdapter( + child: TvEdgeFocus(), + ), + InfoAppBar( + entry: entry, + collection: collection, + actionDelegate: _actionDelegate, + metadataNotifier: _metadataNotifier, + onBackPressed: widget.goToViewer, + ), + SliverPadding( + padding: horizontalPadding + const EdgeInsets.only(top: 8), + sliver: basicAndLocationSliver, + ), + SliverPadding( + padding: horizontalPadding + const EdgeInsets.only(bottom: 8), + sliver: MetadataSectionSliver( + entry: entry, + metadataNotifier: _metadataNotifier, + ), + ), + if (!settings.useTvLayout) + SliverPadding( + padding: horizontalPadding + const EdgeInsets.only(bottom: 8), + sliver: ColorSectionSliver(entry: entry), + ), + const BottomPaddingSliver(), + ], + ), + ); + } + + void _onActionDelegateEvent(ActionEvent<EntryAction> event) { + Future.delayed(ADurations.dialogTransitionLoose).then((_) { + if (!mounted) return; + if (event is ActionStartedEvent) { + _isEditingMetadataNotifier.value = event.action; + } else if (event is ActionEndedEvent) { + _isEditingMetadataNotifier.value = null; + } + }); + } + + void _onFilterSelection(CollectionFilter filter) { + if (!mounted) return; + SelectFilterNotification(filter).dispatch(context); + } +} diff --git a/lib/widgets/viewer/info/info_search_delegate.dart b/lib/widgets/viewer/info/info_search_delegate.dart new file mode 100644 index 0000000..868d8fd --- /dev/null +++ b/lib/widgets/viewer/info/info_search_delegate.dart @@ -0,0 +1,133 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/empty.dart'; +import 'package:aves/widgets/common/providers/media_query_data_provider.dart'; +import 'package:aves/widgets/common/search/delegate.dart'; +import 'package:aves/widgets/viewer/info/embedded/embedded_data_opener.dart'; +import 'package:aves/widgets/viewer/info/metadata/metadata_dir.dart'; +import 'package:aves/widgets/viewer/info/metadata/metadata_dir_tile.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; + +class InfoSearchDelegate extends AvesSearchDelegate { + final AvesEntry entry; + final ValueNotifier<Map<String, MetadataDirectory>> metadataNotifier; + final bool isSelecting; + + Map<String, MetadataDirectory> get metadata => metadataNotifier.value; + + static const pageRouteName = '/info/search'; + + InfoSearchDelegate({ + required super.searchFieldLabel, + required super.searchFieldStyle, + required this.entry, + required this.metadataNotifier, + required this.isSelecting, + }) : super( + routeName: pageRouteName, + ); + + @override + Widget? buildLeading(BuildContext context) { + return IconButton( + icon: AnimatedIcon( + icon: AnimatedIcons.menu_arrow, + progress: transitionAnimation, + ), + onPressed: () => Navigator.maybeOf(context)?.pop(), + tooltip: MaterialLocalizations.of(context).backButtonTooltip, + ); + } + + @override + List<Widget>? buildActions(BuildContext context) { + return [ + if (query.isNotEmpty) + IconButton( + icon: const Icon(AIcons.clear), + onPressed: () { + query = ''; + showSuggestions(context); + }, + tooltip: context.l10n.clearTooltip, + ), + ]; + } + + @override + Widget buildSuggestions(BuildContext context) { + final l10n = context.l10n; + final suggestions = { + l10n.viewerInfoSearchSuggestionDate: 'date or time or when -timer -uptime -exposure -timeline -verbatim', + l10n.viewerInfoSearchSuggestionDescription: 'description or title or comment or textual or abstract or object name -line', + l10n.viewerInfoSearchSuggestionDimensions: 'width or height or dimension or framesize or imagelength', + l10n.viewerInfoSearchSuggestionResolution: 'resolution', + l10n.viewerInfoSearchSuggestionRights: 'rights or copyright or attribution or license or artist or creator or by-line or credit -tool', + }; + return ListView( + children: suggestions.entries + .map((kv) => ListTile( + title: Text(kv.key), + onTap: () { + query = kv.value; + showResults(context); + }, + )) + .toList(), + ); + } + + @override + Widget buildResults(BuildContext context) { + if (query.isEmpty) { + showSuggestions(context); + return const SizedBox(); + } + + final queryParts = query.toUpperCase().split(' ')..removeWhere((s) => s.isEmpty); + final queryExcludeIncludeGroups = groupBy<String, bool>(queryParts, (s) => s.startsWith('-')); + final queryExcludeAll = (queryExcludeIncludeGroups[true] ?? []).map((s) => s.substring(1)); + final queryIncludeAny = (queryExcludeIncludeGroups[false] ?? []).join(' ').split(' OR '); + + bool testKey(String key) { + key = key.toUpperCase(); + return queryIncludeAny.any(key.contains) && queryExcludeAll.every((q) => !key.contains(q)); + } + + final filteredMetadata = Map.fromEntries(metadata.entries.map((kv) { + final filteredDir = kv.value.filterKeys(testKey); + return MapEntry(kv.key, filteredDir); + })); + + final tiles = filteredMetadata.entries + .where((kv) => kv.value.tags.isNotEmpty) + .map((kv) => MetadataDirTile( + entry: entry, + title: kv.key, + dir: kv.value, + initiallyExpanded: true, + showThumbnails: false, + )) + .toList(); + return MediaQueryDataProvider( + child: SafeArea( + child: tiles.isEmpty + ? EmptyContent( + icon: AIcons.info, + text: context.l10n.viewerInfoSearchEmpty, + ) + : EmbeddedDataOpener( + enabled: !isSelecting, + entry: entry, + child: ListView.builder( + padding: const EdgeInsets.all(8), + itemBuilder: (context, index) => tiles[index], + itemCount: tiles.length, + ), + ), + ), + ); + } +} diff --git a/lib/widgets/viewer/info/location_section.dart b/lib/widgets/viewer/info/location_section.dart new file mode 100644 index 0000000..0119430 --- /dev/null +++ b/lib/widgets/viewer/info/location_section.dart @@ -0,0 +1,231 @@ +import 'package:aves/app_mode.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/location.dart'; +import 'package:aves/model/filters/covered/location.dart'; +import 'package:aves/model/settings/enums/coordinate_format.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/aves_filter_chip.dart'; +import 'package:aves/widgets/common/map/geo_map.dart'; +import 'package:aves/widgets/common/map/map_action_delegate.dart'; +import 'package:aves/widgets/common/providers/map_theme_provider.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:aves/widgets/map/map_page.dart'; +import 'package:aves/widgets/viewer/info/common.dart'; +import 'package:aves_map/aves_map.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class LocationSection extends StatefulWidget { + final CollectionLens? collection; + final AvesEntry entry; + final bool showTitle; + final ValueNotifier<bool> isScrollingNotifier; + final AFilterCallback onFilterSelection; + + const LocationSection({ + super.key, + required this.collection, + required this.entry, + required this.showTitle, + required this.isScrollingNotifier, + required this.onFilterSelection, + }); + + @override + State<LocationSection> createState() => _LocationSectionState(); +} + +class _LocationSectionState extends State<LocationSection> { + final AvesMapController _mapController = AvesMapController(); + + CollectionLens? get collection => widget.collection; + + AvesEntry get entry => widget.entry; + + @override + void initState() { + super.initState(); + _registerWidget(widget); + } + + @override + void didUpdateWidget(covariant LocationSection oldWidget) { + super.didUpdateWidget(oldWidget); + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + + @override + void dispose() { + _unregisterWidget(widget); + super.dispose(); + } + + void _registerWidget(LocationSection widget) { + widget.entry.metadataChangeNotifier.addListener(_onMetadataChanged); + } + + void _unregisterWidget(LocationSection widget) { + widget.entry.metadataChangeNotifier.removeListener(_onMetadataChanged); + } + + @override + Widget build(BuildContext context) { + if (!entry.hasGps) return const SizedBox(); + + final canNavigate = context.select<ValueNotifier<AppMode>, bool>((v) => v.value.canNavigate); + return NotificationListener( + onNotification: (notification) { + if (notification is OpenMapAppNotification) { + _openMapApp(); + return true; + } + return false; + }, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (widget.showTitle) const SectionRow(icon: AIcons.location), + MapTheme( + interactive: false, + showCoordinateFilter: false, + navigationButton: canNavigate ? MapNavigationButton.map : MapNavigationButton.none, + visualDensity: VisualDensity.compact, + mapHeight: 200, + child: GeoMap( + controller: _mapController, + entries: [entry], + availableSize: MediaQuery.sizeOf(context), + isAnimatingNotifier: widget.isScrollingNotifier, + onUserZoomChange: (zoom) => settings.infoMapZoom = zoom.roundToDouble(), + onMarkerTap: collection != null && canNavigate ? (location, entry) => _openMapPage(context) : null, + openMapPage: collection != null ? _openMapPage : null, + ), + ), + AnimatedBuilder( + animation: entry.addressChangeNotifier, + builder: (context, child) { + final filters = <LocationFilter>[]; + if (entry.hasAddress) { + final address = entry.addressDetails!; + final country = address.countryName; + if (country != null && country.isNotEmpty) filters.add(LocationFilter(LocationLevel.country, '$country${LocationFilter.locationSeparator}${address.countryCode}')); + final state = address.stateName; + if (state != null && state.isNotEmpty) filters.add(LocationFilter(LocationLevel.state, '$state${LocationFilter.locationSeparator}${address.stateCode}')); + final place = address.place; + if (place != null && place.isNotEmpty) filters.add(LocationFilter(LocationLevel.place, place)); + } + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _AddressInfoGroup(entry: entry), + if (filters.isNotEmpty) + Padding( + padding: const EdgeInsets.symmetric(horizontal: AvesFilterChip.outlineWidth / 2) + const EdgeInsets.only(top: 8), + child: Wrap( + spacing: 8, + runSpacing: 8, + children: filters + .map((filter) => AvesFilterChip( + filter: filter, + onTap: widget.onFilterSelection, + )) + .toList(), + ), + ), + ], + ); + }, + ), + ], + ), + ); + } + + Future<void> _openMapPage(BuildContext context) async { + final baseCollection = collection; + if (baseCollection == null) return; + + final mapCollection = baseCollection.copyWith( + listenToSource: true, + fixedSelection: baseCollection.sortedEntries.where((entry) => entry.hasGps).toList(), + ); + await Navigator.maybeOf(context)?.push( + MaterialPageRoute( + settings: const RouteSettings(name: MapPage.routeName), + builder: (context) => MapPage( + collection: mapCollection, + initialEntry: entry, + ), + ), + ); + } + + Future<void> _openMapApp() async { + final latLng = entry.latLng; + if (latLng != null) { + await appService.openMap(latLng).then((success) { + if (!success) showNoMatchingAppDialog(context); + }); + } + } + + void _onMetadataChanged() { + setState(() {}); + + final location = entry.latLng; + if (location != null) { + _mapController.notifyMarkerLocationChange(); + _mapController.moveTo(location); + } + } +} + +class _AddressInfoGroup extends StatefulWidget { + final AvesEntry entry; + + const _AddressInfoGroup({required this.entry}); + + @override + State<_AddressInfoGroup> createState() => _AddressInfoGroupState(); +} + +class _AddressInfoGroupState extends State<_AddressInfoGroup> { + late Future<String?> _addressLineLoader; + + AvesEntry get entry => widget.entry; + + @override + void initState() { + super.initState(); + _addressLineLoader = availability.canLocatePlaces.then((connected) { + if (connected) { + return entry.findAddressLine(geocoderLocale: settings.appliedLocale); + } + return null; + }); + } + + @override + Widget build(BuildContext context) { + return FutureBuilder<String?>( + future: _addressLineLoader, + builder: (context, snapshot) { + final fullAddress = !snapshot.hasError && snapshot.connectionState == ConnectionState.done ? snapshot.data : null; + final address = fullAddress ?? entry.shortAddress; + final l10n = context.l10n; + return InfoRowGroup( + info: { + l10n.viewerInfoLabelCoordinates: settings.coordinateFormat.format(context, entry.latLng!), + if (address.isNotEmpty) l10n.viewerInfoLabelAddress: address, + }, + ); + }, + ); + } +} diff --git a/lib/widgets/viewer/info/metadata/geotiff.dart b/lib/widgets/viewer/info/metadata/geotiff.dart new file mode 100644 index 0000000..fb647b9 --- /dev/null +++ b/lib/widgets/viewer/info/metadata/geotiff.dart @@ -0,0 +1,3847 @@ +import 'package:aves/ref/metadata/geotiff.dart'; + +class GeoTiffDirectory { + // TODO TLAD [geotiff] avoid string-based match + static int? tagForName(String name) { + switch (name) { + case 'Model Type': + return GeoTiffKeys.modelType; + case 'Raster Type': + return GeoTiffKeys.rasterType; + case 'Geographic Type': + return GeoTiffKeys.geographicType; + case 'Geographic Geodetic Datum': + return GeoTiffKeys.geogGeodeticDatum; + case 'Geographic Angular Units': + return GeoTiffKeys.geogAngularUnits; + case 'Geographic Ellipsoid': + return GeoTiffKeys.geogEllipsoid; + case 'Projected Coordinate System Type': + return GeoTiffKeys.projCSType; + case 'Projection': + return GeoTiffKeys.projection; + case 'Projected Coordinate Transform': + return GeoTiffKeys.projCoordinateTransform; + case 'Projection Linear Units': + return GeoTiffKeys.projLinearUnits; + case 'Vertical Units': + return GeoTiffKeys.verticalUnits; + default: + return null; + } + } + + static String formatValue(int? tag, String v) { + switch (tag) { + case GeoTiffKeys.modelType: + return getModelTypeDescription(v); + case GeoTiffKeys.rasterType: + return getRasterTypeDescription(v); + case GeoTiffKeys.geographicType: + return getGeographicTypeDescription(v); + case GeoTiffKeys.geogGeodeticDatum: + return getGeogGeodeticDatumDescription(v); + case GeoTiffKeys.geogEllipsoid: + return getGeogEllipsoidDescription(v); + case GeoTiffKeys.projCSType: + return getProjCSTypeDescription(v); + case GeoTiffKeys.projection: + return getProjectionDescription(v); + case GeoTiffKeys.projCoordinateTransform: + return getProjCoordinateTransformDescription(v); + case GeoTiffKeys.projLinearUnits: + case GeoTiffKeys.geogAngularUnits: + case GeoTiffKeys.verticalUnits: + return getGeoTiffUnitsDescription(v); + default: + return v; + } + } + + static String getModelTypeDescription(String valueString) { + final value = int.tryParse(valueString); + if (value == null) return valueString; + switch (value) { + case 1: + return 'Projected'; + case 2: + return 'Geographic'; + case 3: + return 'Geocentric'; + case 32767: + return 'User Defined'; + default: + return 'Unknown ($value)'; + } + } + + static String getRasterTypeDescription(String valueString) { + final value = int.tryParse(valueString); + if (value == null) return valueString; + switch (value) { + case 1: + return 'Pixel Is Area'; + case 2: + return 'Pixel Is Point'; + case 32767: + return 'User Defined'; + default: + return 'Unknown ($value)'; + } + } + + static String getGeographicTypeDescription(String valueString) { + final value = int.tryParse(valueString); + if (value == null) return valueString; + switch (value) { + case 4001: + return 'Airy 1830'; + case 4002: + return 'Airy Modified 1849'; + case 4003: + return 'Australian National Spheroid'; + case 4004: + return 'Bessel 1841'; + case 4005: + return 'Bessel Modified'; + case 4006: + return 'Bessel Namibia'; + case 4007: + return 'Clarke 1858'; + case 4008: + return 'Clarke 1866'; + case 4009: + return 'Clarke 1866 Michigan'; + case 4010: + return 'Clarke 1880 Benoit'; + case 4011: + return 'Clarke 1880 IGN'; + case 4012: + return 'Clarke 1880 RGS'; + case 4013: + return 'Clarke 1880 Arc'; + case 4014: + return 'Clarke 1880 SGA 1922'; + case 4015: + return 'Everest 1830 1937 Adjustment'; + case 4016: + return 'Everest 1830 1967 Definition'; + case 4017: + return 'Everest 1830 1975 Definition'; + case 4018: + return 'Everest 1830 Modified'; + case 4019: + return 'GRS 1980'; + case 4020: + return 'Helmert 1906'; + case 4021: + return 'Indonesian National Spheroid'; + case 4022: + return 'International 1924'; + case 4023: + return 'International 1967'; + case 4024: + return 'Krassowsky 1940'; + case 4025: + return 'NWL9D'; + case 4026: + return 'NWL10D'; + case 4027: + return 'Plessis 1817'; + case 4028: + return 'Struve 1860'; + case 4029: + return 'War Office'; + case 4030: + return 'WGS84'; + case 4031: + return 'GEM10C'; + case 4032: + return 'OSU86F'; + case 4033: + return 'OSU91A'; + case 4034: + return 'Clarke 1880'; + case 4035: + return 'Sphere'; + case 4120: + return 'Greek'; + case 4121: + return 'GGRS87'; + case 4123: + return 'KKJ'; + case 4124: + return 'RT90'; + case 4133: + return 'EST92'; + case 4201: + return 'Adindan'; + case 4202: + return 'AGD66'; + case 4203: + return 'AGD84'; + case 4204: + return 'Ain el Abd'; + case 4205: + return 'Afgooye'; + case 4206: + return 'Agadez'; + case 4207: + return 'Lisbon'; + case 4208: + return 'Aratu'; + case 4209: + return 'Arc 1950'; + case 4210: + return 'Arc 1960'; + case 4211: + return 'Batavia'; + case 4212: + return 'Barbados'; + case 4213: + return 'Beduaram'; + case 4214: + return 'Beijing 1954'; + case 4215: + return 'Belge 1950'; + case 4216: + return 'Bermuda 1957'; + case 4217: + return 'Bern 1898'; + case 4218: + return 'Bogota'; + case 4219: + return 'Bukit Rimpah'; + case 4220: + return 'Camacupa'; + case 4221: + return 'Campo Inchauspe'; + case 4222: + return 'Cape'; + case 4223: + return 'Carthage'; + case 4224: + return 'Chua'; + case 4225: + return 'Corrego Alegre'; + case 4226: + return 'Cote d Ivoire'; + case 4227: + return 'Deir ez Zor'; + case 4228: + return 'Douala'; + case 4229: + return 'Egypt 1907'; + case 4230: + return 'ED50'; + case 4231: + return 'ED87'; + case 4232: + return 'Fahud'; + case 4233: + return 'Gandajika 1970'; + case 4234: + return 'Garoua'; + case 4235: + return 'Guyane Francaise'; + case 4236: + return 'Hu Tzu Shan'; + case 4237: + return 'HD72'; + case 4238: + return 'ID74'; + case 4239: + return 'Indian 1954'; + case 4240: + return 'Indian 1975'; + case 4241: + return 'Jamaica 1875'; + case 4242: + return 'JAD69'; + case 4243: + return 'Kalianpur'; + case 4244: + return 'Kandawala'; + case 4245: + return 'Kertau'; + case 4246: + return 'KOC'; + case 4247: + return 'La Canoa'; + case 4248: + return 'PSAD56'; + case 4249: + return 'Lake'; + case 4250: + return 'Leigon'; + case 4251: + return 'Liberia 1964'; + case 4252: + return 'Lome'; + case 4253: + return 'Luzon 1911'; + case 4254: + return 'Hito XVIII 1963'; + case 4255: + return 'Herat North'; + case 4256: + return 'Mahe 1971'; + case 4257: + return 'Makassar'; + case 4258: + return 'EUREF89'; + case 4259: + return 'Malongo 1987'; + case 4260: + return 'Manoca'; + case 4261: + return 'Merchich'; + case 4262: + return 'Massawa'; + case 4263: + return 'Minna'; + case 4264: + return 'Mhast'; + case 4265: + return 'Monte Mario'; + case 4266: + return 'M poraloko'; + case 4267: + return 'NAD27'; + case 4268: + return 'NAD Michigan'; + case 4269: + return 'NAD83'; + case 4270: + return 'Nahrwan 1967'; + case 4271: + return 'Naparima 1972'; + case 4272: + return 'GD49'; + case 4273: + return 'NGO 1948'; + case 4274: + return '73'; + case 4275: + return 'NTF'; + case 4276: + return 'NSWC 9Z 2'; + case 4277: + return 'OSGB 1936'; + case 4278: + return 'OSGB70'; + case 4279: + return 'OS SN80'; + case 4280: + return 'Padang'; + case 4281: + return 'Palestine 1923'; + case 4282: + return 'Pointe Noire'; + case 4283: + return 'GDA94'; + case 4284: + return 'Pulkovo 1942'; + case 4285: + return 'Qatar'; + case 4286: + return 'Qatar 1948'; + case 4287: + return 'Qornoq'; + case 4288: + return 'Loma Quintana'; + case 4289: + return 'Amersfoort'; + case 4290: + return 'RT38'; + case 4291: + return 'SAD69'; + case 4292: + return 'Sapper Hill 1943'; + case 4293: + return 'Schwarzeck'; + case 4294: + return 'Segora'; + case 4295: + return 'Serindung'; + case 4296: + return 'Sudan'; + case 4297: + return 'Tananarive'; + case 4298: + return 'Timbalai 1948'; + case 4299: + return 'TM65'; + case 4300: + return 'TM75'; + case 4301: + return 'Tokyo'; + case 4302: + return 'Trinidad 1903'; + case 4303: + return 'TC 1948'; + case 4304: + return 'Voirol 1875'; + case 4305: + return 'Voirol Unifie'; + case 4306: + return 'Bern 1938'; + case 4307: + return 'Nord Sahara 1959'; + case 4308: + return 'Stockholm 1938'; + case 4309: + return 'Yacare'; + case 4310: + return 'Yoff'; + case 4311: + return 'Zanderij'; + case 4312: + return 'MGI'; + case 4313: + return 'Belge 1972'; + case 4314: + return 'DHDN'; + case 4315: + return 'Conakry 1905'; + case 4317: + return 'Dealul Piscului 1970'; + case 4322: + return 'WGS 72'; + case 4324: + return 'WGS 72BE'; + case 4326: + return 'WGS 84'; + case 4801: + return 'Bern 1898 Bern'; + case 4802: + return 'Bogota Bogota'; + case 4803: + return 'Lisbon Lisbon'; + case 4804: + return 'Makassar Jakarta'; + case 4805: + return 'MGI Ferro'; + case 4806: + return 'Monte Mario Rome'; + case 4807: + return 'NTF Paris'; + case 4808: + return 'Padang Jakarta'; + case 4809: + return 'Belge 1950 Brussels'; + case 4810: + return 'Tananarive Paris'; + case 4811: + return 'Voirol 1875 Paris'; + case 4812: + return 'Voirol Unifie Paris'; + case 4813: + return 'Batavia Jakarta'; + case 4815: + return 'Greek Athens'; + case 4901: + return 'ATF Paris'; + case 4902: + return 'NDG Paris'; + case 32767: + return 'User Defined'; + default: + return 'Unknown ($value)'; + } + } + + static String getGeogGeodeticDatumDescription(String valueString) { + final value = int.tryParse(valueString); + if (value == null) return valueString; + switch (value) { + case 6001: + return 'Airy 1830'; + case 6002: + return 'Airy Modified 1849'; + case 6003: + return 'Australian National Spheroid'; + case 6004: + return 'Bessel 1841'; + case 6005: + return 'Bessel Modified'; + case 6006: + return 'Bessel Namibia'; + case 6007: + return 'Clarke 1858'; + case 6008: + return 'Clarke 1866'; + case 6009: + return 'Clarke 1866 Michigan'; + case 6010: + return 'Clarke 1880 Benoit'; + case 6011: + return 'Clarke 1880 IGN'; + case 6012: + return 'Clarke 1880 RGS'; + case 6013: + return 'Clarke 1880 Arc'; + case 6014: + return 'Clarke 1880 SGA 1922'; + case 6015: + return 'Everest 1830 1937 Adjustment'; + case 6016: + return 'Everest 1830 1967 Definition'; + case 6017: + return 'Everest 1830 1975 Definition'; + case 6018: + return 'Everest 1830 Modified'; + case 6019: + return 'GRS 1980'; + case 6020: + return 'Helmert 1906'; + case 6021: + return 'Indonesian National Spheroid'; + case 6022: + return 'International 1924'; + case 6023: + return 'International 1967'; + case 6024: + return 'Krassowsky 1960'; + case 6025: + return 'NWL9D'; + case 6026: + return 'NWL10D'; + case 6027: + return 'Plessis 1817'; + case 6028: + return 'Struve 1860'; + case 6029: + return 'War Office'; + case 6030: + return 'WGS84'; + case 6031: + return 'GEM10C'; + case 6032: + return 'OSU86F'; + case 6033: + return 'OSU91A'; + case 6034: + return 'Clarke 1880'; + case 6035: + return 'Sphere'; + case 6201: + return 'Adindan'; + case 6202: + return 'Australian Geodetic Datum 1966'; + case 6203: + return 'Australian Geodetic Datum 1984'; + case 6204: + return 'Ain el Abd 1970'; + case 6205: + return 'Afgooye'; + case 6206: + return 'Agadez'; + case 6207: + return 'Lisbon'; + case 6208: + return 'Aratu'; + case 6209: + return 'Arc 1950'; + case 6210: + return 'Arc 1960'; + case 6211: + return 'Batavia'; + case 6212: + return 'Barbados'; + case 6213: + return 'Beduaram'; + case 6214: + return 'Beijing 1954'; + case 6215: + return 'Reseau National Belge 1950'; + case 6216: + return 'Bermuda 1957'; + case 6217: + return 'Bern 1898'; + case 6218: + return 'Bogota'; + case 6219: + return 'Bukit Rimpah'; + case 6220: + return 'Camacupa'; + case 6221: + return 'Campo Inchauspe'; + case 6222: + return 'Cape'; + case 6223: + return 'Carthage'; + case 6224: + return 'Chua'; + case 6225: + return 'Corrego Alegre'; + case 6226: + return 'Cote d Ivoire'; + case 6227: + return 'Deir ez Zor'; + case 6228: + return 'Douala'; + case 6229: + return 'Egypt 1907'; + case 6230: + return 'European Datum 1950'; + case 6231: + return 'European Datum 1987'; + case 6232: + return 'Fahud'; + case 6233: + return 'Gandajika 1970'; + case 6234: + return 'Garoua'; + case 6235: + return 'Guyane Francaise'; + case 6236: + return 'Hu Tzu Shan'; + case 6237: + return 'Hungarian Datum 1972'; + case 6238: + return 'Indonesian Datum 1974'; + case 6239: + return 'Indian 1954'; + case 6240: + return 'Indian 1975'; + case 6241: + return 'Jamaica 1875'; + case 6242: + return 'Jamaica 1969'; + case 6243: + return 'Kalianpur'; + case 6244: + return 'Kandawala'; + case 6245: + return 'Kertau'; + case 6246: + return 'Kuwait Oil Company'; + case 6247: + return 'La Canoa'; + case 6248: + return 'Provisional S American Datum 1956'; + case 6249: + return 'Lake'; + case 6250: + return 'Leigon'; + case 6251: + return 'Liberia 1964'; + case 6252: + return 'Lome'; + case 6253: + return 'Luzon 1911'; + case 6254: + return 'Hito XVIII 1963'; + case 6255: + return 'Herat North'; + case 6256: + return 'Mahe 1971'; + case 6257: + return 'Makassar'; + case 6258: + return 'European Reference System 1989'; + case 6259: + return 'Malongo 1987'; + case 6260: + return 'Manoca'; + case 6261: + return 'Merchich'; + case 6262: + return 'Massawa'; + case 6263: + return 'Minna'; + case 6264: + return 'Mhast'; + case 6265: + return 'Monte Mario'; + case 6266: + return 'M poraloko'; + case 6267: + return 'North American Datum 1927'; + case 6268: + return 'NAD Michigan'; + case 6269: + return 'North American Datum 1983'; + case 6270: + return 'Nahrwan 1967'; + case 6271: + return 'Naparima 1972'; + case 6272: + return 'New Zealand Geodetic Datum 1949'; + case 6273: + return 'NGO 1948'; + case 6274: + return 'Datum 73'; + case 6275: + return 'Nouvelle Triangulation Francaise'; + case 6276: + return 'NSWC 9Z 2'; + case 6277: + return 'OSGB 1936'; + case 6278: + return 'OSGB 1970 SN'; + case 6279: + return 'OS SN 1980'; + case 6280: + return 'Padang 1884'; + case 6281: + return 'Palestine 1923'; + case 6282: + return 'Pointe Noire'; + case 6283: + return 'Geocentric Datum of Australia 1994'; + case 6284: + return 'Pulkovo 1942'; + case 6285: + return 'Qatar'; + case 6286: + return 'Qatar 1948'; + case 6287: + return 'Qornoq'; + case 6288: + return 'Loma Quintana'; + case 6289: + return 'Amersfoort'; + case 6290: + return 'RT38'; + case 6291: + return 'South American Datum 1969'; + case 6292: + return 'Sapper Hill 1943'; + case 6293: + return 'Schwarzeck'; + case 6294: + return 'Segora'; + case 6295: + return 'Serindung'; + case 6296: + return 'Sudan'; + case 6297: + return 'Tananarive 1925'; + case 6298: + return 'Timbalai 1948'; + case 6299: + return 'TM65'; + case 6300: + return 'TM75'; + case 6301: + return 'Tokyo'; + case 6302: + return 'Trinidad 1903'; + case 6303: + return 'Trucial Coast 1948'; + case 6304: + return 'Voirol 1875'; + case 6305: + return 'Voirol Unifie 1960'; + case 6306: + return 'Bern 1938'; + case 6307: + return 'Nord Sahara 1959'; + case 6308: + return 'Stockholm 1938'; + case 6309: + return 'Yacare'; + case 6310: + return 'Yoff'; + case 6311: + return 'Zanderij'; + case 6312: + return 'Militar Geographische Institut'; + case 6313: + return 'Reseau National Belge 1972'; + case 6314: + return 'Deutsche Hauptdreiecksnetz'; + case 6315: + return 'Conakry 1905'; + case 6317: + return 'Dealul Piscului 1970'; + case 6322: + return 'WGS72'; + case 6324: + return 'WGS72 Transit Broadcast Ephemeris'; + case 6326: + return 'WGS84'; + case 6901: + return 'Ancienne Triangulation Francaise'; + case 6902: + return 'Nord de Guerre'; + case 32767: + return 'User Defined'; + default: + return 'Unknown ($value)'; + } + } + + static String getGeogEllipsoidDescription(String valueString) { + final value = int.tryParse(valueString); + if (value == null) return valueString; + switch (value) { + case 7001: + return 'Airy 1830'; + case 7002: + return 'Airy Modified 1849'; + case 7003: + return 'Australian National Spheroid'; + case 7004: + return 'Bessel 1841'; + case 7005: + return 'Bessel Modified'; + case 7006: + return 'Bessel Namibia'; + case 7007: + return 'Clarke 1858'; + case 7008: + return 'Clarke 1866'; + case 7009: + return 'Clarke 1866 Michigan'; + case 7010: + return 'Clarke 1880 Benoit'; + case 7011: + return 'Clarke 1880 IGN'; + case 7012: + return 'Clarke 1880 RGS'; + case 7013: + return 'Clarke 1880 Arc'; + case 7014: + return 'Clarke 1880 SGA 1922'; + case 7015: + return 'Everest 1830 1937 Adjustment'; + case 7016: + return 'Everest 1830 1967 Definition'; + case 7017: + return 'Everest 1830 1975 Definition'; + case 7018: + return 'Everest 1830 Modified'; + case 7019: + return 'GRS 1980'; + case 7020: + return 'Helmert 1906'; + case 7021: + return 'Indonesian National Spheroid'; + case 7022: + return 'International 1924'; + case 7023: + return 'International 1967'; + case 7024: + return 'Krassowsky 1940'; + case 7025: + return 'NWL 9D'; + case 7026: + return 'NWL 10D'; + case 7027: + return 'Plessis 1817'; + case 7028: + return 'Struve 1860'; + case 7029: + return 'War Office'; + case 7030: + return 'WGS 84'; + case 7031: + return 'GEM 10C'; + case 7032: + return 'OSU86F'; + case 7033: + return 'OSU91A'; + case 7034: + return 'Clarke 1880'; + case 7035: + return 'Sphere'; + case 32767: + return 'User Defined'; + default: + return 'Unknown ($value)'; + } + } + + static String getProjCSTypeDescription(String valueString) { + final value = int.tryParse(valueString); + if (value == null) return valueString; + switch (value) { + case 2100: + return 'GGRS87 Greek Grid'; + case 2176: + return 'ETRS89 Poland CS2000 zone 5'; + case 2177: + return 'ETRS89 Poland CS2000 zone 7'; + case 2178: + return 'ETRS89 Poland CS2000 zone 8'; + case 2180: + return 'ETRS89 Poland CS92'; + case 2204: + return 'NAD27 Tennessee'; + case 2205: + return 'NAD83 Kentucky North'; + case 2391: + return 'KKJ Finland zone 1'; + case 2392: + return 'KKJ Finland zone 2'; + case 2393: + return 'KKJ Finland zone 3'; + case 2394: + return 'KKJ Finland zone 4'; + case 2400: + return 'RT90 2 5 gon W'; + case 2600: + return 'Lietuvos Koordinoei Sistema 1994'; + case 3045: + return 'ETRS89 UTM zone 33N'; + case 3053: + return 'Hjorsey 1955 Lambert'; + case 3057: + return 'ISN93 Lambert 1993'; + case 3300: + return 'Estonian Coordinate System of 1992'; + case 3786: + return 'Popular Visualisation CRS / Mercator'; + case 3857: + return 'WGS 84 / Pseudo-Mercator'; + case 20137: + return 'Adindan UTM zone 37N'; + case 20138: + return 'Adindan UTM zone 38N'; + case 20248: + return 'AGD66 AMG zone 48'; + case 20249: + return 'AGD66 AMG zone 49'; + case 20250: + return 'AGD66 AMG zone 50'; + case 20251: + return 'AGD66 AMG zone 51'; + case 20252: + return 'AGD66 AMG zone 52'; + case 20253: + return 'AGD66 AMG zone 53'; + case 20254: + return 'AGD66 AMG zone 54'; + case 20255: + return 'AGD66 AMG zone 55'; + case 20256: + return 'AGD66 AMG zone 56'; + case 20257: + return 'AGD66 AMG zone 57'; + case 20258: + return 'AGD66 AMG zone 58'; + case 20348: + return 'AGD84 AMG zone 48'; + case 20349: + return 'AGD84 AMG zone 49'; + case 20350: + return 'AGD84 AMG zone 50'; + case 20351: + return 'AGD84 AMG zone 51'; + case 20352: + return 'AGD84 AMG zone 52'; + case 20353: + return 'AGD84 AMG zone 53'; + case 20354: + return 'AGD84 AMG zone 54'; + case 20355: + return 'AGD84 AMG zone 55'; + case 20356: + return 'AGD84 AMG zone 56'; + case 20357: + return 'AGD84 AMG zone 57'; + case 20358: + return 'AGD84 AMG zone 58'; + case 20437: + return 'Ain el Abd UTM zone 37N'; + case 20438: + return 'Ain el Abd UTM zone 38N'; + case 20439: + return 'Ain el Abd UTM zone 39N'; + case 20499: + return 'Ain el Abd Bahrain Grid'; + case 20538: + return 'Afgooye UTM zone 38N'; + case 20539: + return 'Afgooye UTM zone 39N'; + case 20700: + return 'Lisbon Portuguese Grid'; + case 20822: + return 'Aratu UTM zone 22S'; + case 20823: + return 'Aratu UTM zone 23S'; + case 20824: + return 'Aratu UTM zone 24S'; + case 20973: + return 'Arc 1950 Lo13'; + case 20975: + return 'Arc 1950 Lo15'; + case 20977: + return 'Arc 1950 Lo17'; + case 20979: + return 'Arc 1950 Lo19'; + case 20981: + return 'Arc 1950 Lo21'; + case 20983: + return 'Arc 1950 Lo23'; + case 20985: + return 'Arc 1950 Lo25'; + case 20987: + return 'Arc 1950 Lo27'; + case 20989: + return 'Arc 1950 Lo29'; + case 20991: + return 'Arc 1950 Lo31'; + case 20993: + return 'Arc 1950 Lo33'; + case 20995: + return 'Arc 1950 Lo35'; + case 21100: + return 'Batavia NEIEZ'; + case 21148: + return 'Batavia UTM zone 48S'; + case 21149: + return 'Batavia UTM zone 49S'; + case 21150: + return 'Batavia UTM zone 50S'; + case 21413: + return 'Beijing Gauss zone 13'; + case 21414: + return 'Beijing Gauss zone 14'; + case 21415: + return 'Beijing Gauss zone 15'; + case 21416: + return 'Beijing Gauss zone 16'; + case 21417: + return 'Beijing Gauss zone 17'; + case 21418: + return 'Beijing Gauss zone 18'; + case 21419: + return 'Beijing Gauss zone 19'; + case 21420: + return 'Beijing Gauss zone 20'; + case 21421: + return 'Beijing Gauss zone 21'; + case 21422: + return 'Beijing Gauss zone 22'; + case 21423: + return 'Beijing Gauss zone 23'; + case 21473: + return 'Beijing Gauss 13N'; + case 21474: + return 'Beijing Gauss 14N'; + case 21475: + return 'Beijing Gauss 15N'; + case 21476: + return 'Beijing Gauss 16N'; + case 21477: + return 'Beijing Gauss 17N'; + case 21478: + return 'Beijing Gauss 18N'; + case 21479: + return 'Beijing Gauss 19N'; + case 21480: + return 'Beijing Gauss 20N'; + case 21481: + return 'Beijing Gauss 21N'; + case 21482: + return 'Beijing Gauss 22N'; + case 21483: + return 'Beijing Gauss 23N'; + case 21500: + return 'Belge Lambert 50'; + case 21790: + return 'Bern 1898 Swiss Old'; + case 21817: + return 'Bogota UTM zone 17N'; + case 21818: + return 'Bogota UTM zone 18N'; + case 21891: + return 'Bogota Colombia 3W'; + case 21892: + return 'Bogota Colombia Bogota'; + case 21893: + return 'Bogota Colombia 3E'; + case 21894: + return 'Bogota Colombia 6E'; + case 22032: + return 'Camacupa UTM 32S'; + case 22033: + return 'Camacupa UTM 33S'; + case 22191: + return 'C Inchauspe Argentina 1'; + case 22192: + return 'C Inchauspe Argentina 2'; + case 22193: + return 'C Inchauspe Argentina 3'; + case 22194: + return 'C Inchauspe Argentina 4'; + case 22195: + return 'C Inchauspe Argentina 5'; + case 22196: + return 'C Inchauspe Argentina 6'; + case 22197: + return 'C Inchauspe Argentina 7'; + case 22332: + return 'Carthage UTM zone 32N'; + case 22391: + return 'Carthage Nord Tunisie'; + case 22392: + return 'Carthage Sud Tunisie'; + case 22523: + return 'Corrego Alegre UTM 23S'; + case 22524: + return 'Corrego Alegre UTM 24S'; + case 22832: + return 'Douala UTM zone 32N'; + case 22992: + return 'Egypt 1907 Red Belt'; + case 22993: + return 'Egypt 1907 Purple Belt'; + case 22994: + return 'Egypt 1907 Ext Purple'; + case 23028: + return 'ED50 UTM zone 28N'; + case 23029: + return 'ED50 UTM zone 29N'; + case 23030: + return 'ED50 UTM zone 30N'; + case 23031: + return 'ED50 UTM zone 31N'; + case 23032: + return 'ED50 UTM zone 32N'; + case 23033: + return 'ED50 UTM zone 33N'; + case 23034: + return 'ED50 UTM zone 34N'; + case 23035: + return 'ED50 UTM zone 35N'; + case 23036: + return 'ED50 UTM zone 36N'; + case 23037: + return 'ED50 UTM zone 37N'; + case 23038: + return 'ED50 UTM zone 38N'; + case 23239: + return 'Fahud UTM zone 39N'; + case 23240: + return 'Fahud UTM zone 40N'; + case 23433: + return 'Garoua UTM zone 33N'; + case 23700: + return 'HD72 EOV'; + case 23846: + return 'ID74 UTM zone 46N'; + case 23847: + return 'ID74 UTM zone 47N'; + case 23848: + return 'ID74 UTM zone 48N'; + case 23849: + return 'ID74 UTM zone 49N'; + case 23850: + return 'ID74 UTM zone 50N'; + case 23851: + return 'ID74 UTM zone 51N'; + case 23852: + return 'ID74 UTM zone 52N'; + case 23853: + return 'ID74 UTM zone 53N'; + case 23886: + return 'ID74 UTM zone 46S'; + case 23887: + return 'ID74 UTM zone 47S'; + case 23888: + return 'ID74 UTM zone 48S'; + case 23889: + return 'ID74 UTM zone 49S'; + case 23890: + return 'ID74 UTM zone 50S'; + case 23891: + return 'ID74 UTM zone 51S'; + case 23892: + return 'ID74 UTM zone 52S'; + case 23893: + return 'ID74 UTM zone 53S'; + case 23894: + return 'ID74 UTM zone 54S'; + case 23947: + return 'Indian 1954 UTM 47N'; + case 23948: + return 'Indian 1954 UTM 48N'; + case 24047: + return 'Indian 1975 UTM 47N'; + case 24048: + return 'Indian 1975 UTM 48N'; + case 24100: + return 'Jamaica 1875 Old Grid'; + case 24200: + return 'JAD69 Jamaica Grid'; + case 24370: + return 'Kalianpur India 0'; + case 24371: + return 'Kalianpur India I'; + case 24372: + return 'Kalianpur India IIa'; + case 24373: + return 'Kalianpur India IIIa'; + case 24374: + return 'Kalianpur India IVa'; + case 24382: + return 'Kalianpur India IIb'; + case 24383: + return 'Kalianpur India IIIb'; + case 24384: + return 'Kalianpur India IVb'; + case 24500: + return 'Kertau Singapore Grid'; + case 24547: + return 'Kertau UTM zone 47N'; + case 24548: + return 'Kertau UTM zone 48N'; + case 24720: + return 'La Canoa UTM zone 20N'; + case 24721: + return 'La Canoa UTM zone 21N'; + case 24818: + return 'PSAD56 UTM zone 18N'; + case 24819: + return 'PSAD56 UTM zone 19N'; + case 24820: + return 'PSAD56 UTM zone 20N'; + case 24821: + return 'PSAD56 UTM zone 21N'; + case 24877: + return 'PSAD56 UTM zone 17S'; + case 24878: + return 'PSAD56 UTM zone 18S'; + case 24879: + return 'PSAD56 UTM zone 19S'; + case 24880: + return 'PSAD56 UTM zone 20S'; + case 24891: + return 'PSAD56 Peru west zone'; + case 24892: + return 'PSAD56 Peru central'; + case 24893: + return 'PSAD56 Peru east zone'; + case 25000: + return 'Leigon Ghana Grid'; + case 25231: + return 'Lome UTM zone 31N'; + case 25391: + return 'Luzon Philippines I'; + case 25392: + return 'Luzon Philippines II'; + case 25393: + return 'Luzon Philippines III'; + case 25394: + return 'Luzon Philippines IV'; + case 25395: + return 'Luzon Philippines V'; + case 25700: + return 'Makassar NEIEZ'; + case 25932: + return 'Malongo 1987 UTM 32S'; + case 26191: + return 'Merchich Nord Maroc'; + case 26192: + return 'Merchich Sud Maroc'; + case 26193: + return 'Merchich Sahara'; + case 26237: + return 'Massawa UTM zone 37N'; + case 26331: + return 'Minna UTM zone 31N'; + case 26332: + return 'Minna UTM zone 32N'; + case 26391: + return 'Minna Nigeria West'; + case 26392: + return 'Minna Nigeria Mid Belt'; + case 26393: + return 'Minna Nigeria East'; + case 26432: + return 'Mhast UTM zone 32S'; + case 26591: + return 'Monte Mario Italy 1'; + case 26592: + return 'Monte Mario Italy 2'; + case 26632: + return 'M poraloko UTM 32N'; + case 26692: + return 'M poraloko UTM 32S'; + case 26703: + return 'NAD27 UTM zone 3N'; + case 26704: + return 'NAD27 UTM zone 4N'; + case 26705: + return 'NAD27 UTM zone 5N'; + case 26706: + return 'NAD27 UTM zone 6N'; + case 26707: + return 'NAD27 UTM zone 7N'; + case 26708: + return 'NAD27 UTM zone 8N'; + case 26709: + return 'NAD27 UTM zone 9N'; + case 26710: + return 'NAD27 UTM zone 10N'; + case 26711: + return 'NAD27 UTM zone 11N'; + case 26712: + return 'NAD27 UTM zone 12N'; + case 26713: + return 'NAD27 UTM zone 13N'; + case 26714: + return 'NAD27 UTM zone 14N'; + case 26715: + return 'NAD27 UTM zone 15N'; + case 26716: + return 'NAD27 UTM zone 16N'; + case 26717: + return 'NAD27 UTM zone 17N'; + case 26718: + return 'NAD27 UTM zone 18N'; + case 26719: + return 'NAD27 UTM zone 19N'; + case 26720: + return 'NAD27 UTM zone 20N'; + case 26721: + return 'NAD27 UTM zone 21N'; + case 26722: + return 'NAD27 UTM zone 22N'; + case 26729: + return 'NAD27 Alabama East'; + case 26730: + return 'NAD27 Alabama West'; + case 26731: + return 'NAD27 Alaska zone 1'; + case 26732: + return 'NAD27 Alaska zone 2'; + case 26733: + return 'NAD27 Alaska zone 3'; + case 26734: + return 'NAD27 Alaska zone 4'; + case 26735: + return 'NAD27 Alaska zone 5'; + case 26736: + return 'NAD27 Alaska zone 6'; + case 26737: + return 'NAD27 Alaska zone 7'; + case 26738: + return 'NAD27 Alaska zone 8'; + case 26739: + return 'NAD27 Alaska zone 9'; + case 26740: + return 'NAD27 Alaska zone 10'; + case 26741: + return 'NAD27 California I'; + case 26742: + return 'NAD27 California II'; + case 26743: + return 'NAD27 California III'; + case 26744: + return 'NAD27 California IV'; + case 26745: + return 'NAD27 California V'; + case 26746: + return 'NAD27 California VI'; + case 26747: + return 'NAD27 California VII'; + case 26748: + return 'NAD27 Arizona East'; + case 26749: + return 'NAD27 Arizona Central'; + case 26750: + return 'NAD27 Arizona West'; + case 26751: + return 'NAD27 Arkansas North'; + case 26752: + return 'NAD27 Arkansas South'; + case 26753: + return 'NAD27 Colorado North'; + case 26754: + return 'NAD27 Colorado Central'; + case 26755: + return 'NAD27 Colorado South'; + case 26756: + return 'NAD27 Connecticut'; + case 26757: + return 'NAD27 Delaware'; + case 26758: + return 'NAD27 Florida East'; + case 26759: + return 'NAD27 Florida West'; + case 26760: + return 'NAD27 Florida North'; + case 26761: + return 'NAD27 Hawaii zone 1'; + case 26762: + return 'NAD27 Hawaii zone 2'; + case 26763: + return 'NAD27 Hawaii zone 3'; + case 26764: + return 'NAD27 Hawaii zone 4'; + case 26765: + return 'NAD27 Hawaii zone 5'; + case 26766: + return 'NAD27 Georgia East'; + case 26767: + return 'NAD27 Georgia West'; + case 26768: + return 'NAD27 Idaho East'; + case 26769: + return 'NAD27 Idaho Central'; + case 26770: + return 'NAD27 Idaho West'; + case 26771: + return 'NAD27 Illinois East'; + case 26772: + return 'NAD27 Illinois West'; + case 26773: + return 'NAD27 Indiana East'; + case 26774: + return 'NAD27 Indiana West'; + case 26775: + return 'NAD27 Iowa North'; + case 26776: + return 'NAD27 Iowa South'; + case 26777: + return 'NAD27 Kansas North'; + case 26778: + return 'NAD27 Kansas South'; + case 26779: + return 'NAD27 Kentucky North'; + case 26780: + return 'NAD27 Kentucky South'; + case 26781: + return 'NAD27 Louisiana North'; + case 26782: + return 'NAD27 Louisiana South'; + case 26783: + return 'NAD27 Maine East'; + case 26784: + return 'NAD27 Maine West'; + case 26785: + return 'NAD27 Maryland'; + case 26786: + return 'NAD27 Massachusetts'; + case 26787: + return 'NAD27 Massachusetts Is'; + case 26788: + return 'NAD27 Michigan North'; + case 26789: + return 'NAD27 Michigan Central'; + case 26790: + return 'NAD27 Michigan South'; + case 26791: + return 'NAD27 Minnesota North'; + case 26792: + return 'NAD27 Minnesota Cent'; + case 26793: + return 'NAD27 Minnesota South'; + case 26794: + return 'NAD27 Mississippi East'; + case 26795: + return 'NAD27 Mississippi West'; + case 26796: + return 'NAD27 Missouri East'; + case 26797: + return 'NAD27 Missouri Central'; + case 26798: + return 'NAD27 Missouri West'; + case 26801: + return 'NAD Michigan Michigan East'; + case 26802: + return 'NAD Michigan Michigan Old Central'; + case 26803: + return 'NAD Michigan Michigan West'; + case 26903: + return 'NAD83 UTM zone 3N'; + case 26904: + return 'NAD83 UTM zone 4N'; + case 26905: + return 'NAD83 UTM zone 5N'; + case 26906: + return 'NAD83 UTM zone 6N'; + case 26907: + return 'NAD83 UTM zone 7N'; + case 26908: + return 'NAD83 UTM zone 8N'; + case 26909: + return 'NAD83 UTM zone 9N'; + case 26910: + return 'NAD83 UTM zone 10N'; + case 26911: + return 'NAD83 UTM zone 11N'; + case 26912: + return 'NAD83 UTM zone 12N'; + case 26913: + return 'NAD83 UTM zone 13N'; + case 26914: + return 'NAD83 UTM zone 14N'; + case 26915: + return 'NAD83 UTM zone 15N'; + case 26916: + return 'NAD83 UTM zone 16N'; + case 26917: + return 'NAD83 UTM zone 17N'; + case 26918: + return 'NAD83 UTM zone 18N'; + case 26919: + return 'NAD83 UTM zone 19N'; + case 26920: + return 'NAD83 UTM zone 20N'; + case 26921: + return 'NAD83 UTM zone 21N'; + case 26922: + return 'NAD83 UTM zone 22N'; + case 26923: + return 'NAD83 UTM zone 23N'; + case 26929: + return 'NAD83 Alabama East'; + case 26930: + return 'NAD83 Alabama West'; + case 26931: + return 'NAD83 Alaska zone 1'; + case 26932: + return 'NAD83 Alaska zone 2'; + case 26933: + return 'NAD83 Alaska zone 3'; + case 26934: + return 'NAD83 Alaska zone 4'; + case 26935: + return 'NAD83 Alaska zone 5'; + case 26936: + return 'NAD83 Alaska zone 6'; + case 26937: + return 'NAD83 Alaska zone 7'; + case 26938: + return 'NAD83 Alaska zone 8'; + case 26939: + return 'NAD83 Alaska zone 9'; + case 26940: + return 'NAD83 Alaska zone 10'; + case 26941: + return 'NAD83 California 1'; + case 26942: + return 'NAD83 California 2'; + case 26943: + return 'NAD83 California 3'; + case 26944: + return 'NAD83 California 4'; + case 26945: + return 'NAD83 California 5'; + case 26946: + return 'NAD83 California 6'; + case 26948: + return 'NAD83 Arizona East'; + case 26949: + return 'NAD83 Arizona Central'; + case 26950: + return 'NAD83 Arizona West'; + case 26951: + return 'NAD83 Arkansas North'; + case 26952: + return 'NAD83 Arkansas South'; + case 26953: + return 'NAD83 Colorado North'; + case 26954: + return 'NAD83 Colorado Central'; + case 26955: + return 'NAD83 Colorado South'; + case 26956: + return 'NAD83 Connecticut'; + case 26957: + return 'NAD83 Delaware'; + case 26958: + return 'NAD83 Florida East'; + case 26959: + return 'NAD83 Florida West'; + case 26960: + return 'NAD83 Florida North'; + case 26961: + return 'NAD83 Hawaii zone 1'; + case 26962: + return 'NAD83 Hawaii zone 2'; + case 26963: + return 'NAD83 Hawaii zone 3'; + case 26964: + return 'NAD83 Hawaii zone 4'; + case 26965: + return 'NAD83 Hawaii zone 5'; + case 26966: + return 'NAD83 Georgia East'; + case 26967: + return 'NAD83 Georgia West'; + case 26968: + return 'NAD83 Idaho East'; + case 26969: + return 'NAD83 Idaho Central'; + case 26970: + return 'NAD83 Idaho West'; + case 26971: + return 'NAD83 Illinois East'; + case 26972: + return 'NAD83 Illinois West'; + case 26973: + return 'NAD83 Indiana East'; + case 26974: + return 'NAD83 Indiana West'; + case 26975: + return 'NAD83 Iowa North'; + case 26976: + return 'NAD83 Iowa South'; + case 26977: + return 'NAD83 Kansas North'; + case 26978: + return 'NAD83 Kansas South'; + case 26979: + return 'NAD83 Kentucky North'; + case 26980: + return 'NAD83 Kentucky South'; + case 26981: + return 'NAD83 Louisiana North'; + case 26982: + return 'NAD83 Louisiana South'; + case 26983: + return 'NAD83 Maine East'; + case 26984: + return 'NAD83 Maine West'; + case 26985: + return 'NAD83 Maryland'; + case 26986: + return 'NAD83 Massachusetts'; + case 26987: + return 'NAD83 Massachusetts Is'; + case 26988: + return 'NAD83 Michigan North'; + case 26989: + return 'NAD83 Michigan Central'; + case 26990: + return 'NAD83 Michigan South'; + case 26991: + return 'NAD83 Minnesota North'; + case 26992: + return 'NAD83 Minnesota Cent'; + case 26993: + return 'NAD83 Minnesota South'; + case 26994: + return 'NAD83 Mississippi East'; + case 26995: + return 'NAD83 Mississippi West'; + case 26996: + return 'NAD83 Missouri East'; + case 26997: + return 'NAD83 Missouri Central'; + case 26998: + return 'NAD83 Missouri West'; + case 27038: + return 'Nahrwan 1967 UTM 38N'; + case 27039: + return 'Nahrwan 1967 UTM 39N'; + case 27040: + return 'Nahrwan 1967 UTM 40N'; + case 27120: + return 'Naparima UTM 20N'; + case 27200: + return 'GD49 NZ Map Grid'; + case 27291: + return 'GD49 North Island Grid'; + case 27292: + return 'GD49 South Island Grid'; + case 27429: + return 'Datum 73 UTM zone 29N'; + case 27500: + return 'ATF Nord de Guerre'; + case 27581: + return 'NTF France I'; + case 27582: + return 'NTF France II'; + case 27583: + return 'NTF France III'; + case 27591: + return 'NTF Nord France'; + case 27592: + return 'NTF Centre France'; + case 27593: + return 'NTF Sud France'; + case 27700: + return 'British National Grid'; + case 28232: + return 'Point Noire UTM 32S'; + case 28348: + return 'GDA94 MGA zone 48'; + case 28349: + return 'GDA94 MGA zone 49'; + case 28350: + return 'GDA94 MGA zone 50'; + case 28351: + return 'GDA94 MGA zone 51'; + case 28352: + return 'GDA94 MGA zone 52'; + case 28353: + return 'GDA94 MGA zone 53'; + case 28354: + return 'GDA94 MGA zone 54'; + case 28355: + return 'GDA94 MGA zone 55'; + case 28356: + return 'GDA94 MGA zone 56'; + case 28357: + return 'GDA94 MGA zone 57'; + case 28358: + return 'GDA94 MGA zone 58'; + case 28404: + return 'Pulkovo Gauss zone 4'; + case 28405: + return 'Pulkovo Gauss zone 5'; + case 28406: + return 'Pulkovo Gauss zone 6'; + case 28407: + return 'Pulkovo Gauss zone 7'; + case 28408: + return 'Pulkovo Gauss zone 8'; + case 28409: + return 'Pulkovo Gauss zone 9'; + case 28410: + return 'Pulkovo Gauss zone 10'; + case 28411: + return 'Pulkovo Gauss zone 11'; + case 28412: + return 'Pulkovo Gauss zone 12'; + case 28413: + return 'Pulkovo Gauss zone 13'; + case 28414: + return 'Pulkovo Gauss zone 14'; + case 28415: + return 'Pulkovo Gauss zone 15'; + case 28416: + return 'Pulkovo Gauss zone 16'; + case 28417: + return 'Pulkovo Gauss zone 17'; + case 28418: + return 'Pulkovo Gauss zone 18'; + case 28419: + return 'Pulkovo Gauss zone 19'; + case 28420: + return 'Pulkovo Gauss zone 20'; + case 28421: + return 'Pulkovo Gauss zone 21'; + case 28422: + return 'Pulkovo Gauss zone 22'; + case 28423: + return 'Pulkovo Gauss zone 23'; + case 28424: + return 'Pulkovo Gauss zone 24'; + case 28425: + return 'Pulkovo Gauss zone 25'; + case 28426: + return 'Pulkovo Gauss zone 26'; + case 28427: + return 'Pulkovo Gauss zone 27'; + case 28428: + return 'Pulkovo Gauss zone 28'; + case 28429: + return 'Pulkovo Gauss zone 29'; + case 28430: + return 'Pulkovo Gauss zone 30'; + case 28431: + return 'Pulkovo Gauss zone 31'; + case 28432: + return 'Pulkovo Gauss zone 32'; + case 28464: + return 'Pulkovo Gauss 4N'; + case 28465: + return 'Pulkovo Gauss 5N'; + case 28466: + return 'Pulkovo Gauss 6N'; + case 28467: + return 'Pulkovo Gauss 7N'; + case 28468: + return 'Pulkovo Gauss 8N'; + case 28469: + return 'Pulkovo Gauss 9N'; + case 28470: + return 'Pulkovo Gauss 10N'; + case 28471: + return 'Pulkovo Gauss 11N'; + case 28472: + return 'Pulkovo Gauss 12N'; + case 28473: + return 'Pulkovo Gauss 13N'; + case 28474: + return 'Pulkovo Gauss 14N'; + case 28475: + return 'Pulkovo Gauss 15N'; + case 28476: + return 'Pulkovo Gauss 16N'; + case 28477: + return 'Pulkovo Gauss 17N'; + case 28478: + return 'Pulkovo Gauss 18N'; + case 28479: + return 'Pulkovo Gauss 19N'; + case 28480: + return 'Pulkovo Gauss 20N'; + case 28481: + return 'Pulkovo Gauss 21N'; + case 28482: + return 'Pulkovo Gauss 22N'; + case 28483: + return 'Pulkovo Gauss 23N'; + case 28484: + return 'Pulkovo Gauss 24N'; + case 28485: + return 'Pulkovo Gauss 25N'; + case 28486: + return 'Pulkovo Gauss 26N'; + case 28487: + return 'Pulkovo Gauss 27N'; + case 28488: + return 'Pulkovo Gauss 28N'; + case 28489: + return 'Pulkovo Gauss 29N'; + case 28490: + return 'Pulkovo Gauss 30N'; + case 28491: + return 'Pulkovo Gauss 31N'; + case 28492: + return 'Pulkovo Gauss 32N'; + case 28600: + return 'Qatar National Grid'; + case 28991: + return 'RD Netherlands Old'; + case 28992: + return 'RD Netherlands New'; + case 29118: + return 'SAD69 UTM zone 18N'; + case 29119: + return 'SAD69 UTM zone 19N'; + case 29120: + return 'SAD69 UTM zone 20N'; + case 29121: + return 'SAD69 UTM zone 21N'; + case 29122: + return 'SAD69 UTM zone 22N'; + case 29177: + return 'SAD69 UTM zone 17S'; + case 29178: + return 'SAD69 UTM zone 18S'; + case 29179: + return 'SAD69 UTM zone 19S'; + case 29180: + return 'SAD69 UTM zone 20S'; + case 29181: + return 'SAD69 UTM zone 21S'; + case 29182: + return 'SAD69 UTM zone 22S'; + case 29183: + return 'SAD69 UTM zone 23S'; + case 29184: + return 'SAD69 UTM zone 24S'; + case 29185: + return 'SAD69 UTM zone 25S'; + case 29220: + return 'Sapper Hill UTM 20S'; + case 29221: + return 'Sapper Hill UTM 21S'; + case 29333: + return 'Schwarzeck UTM 33S'; + case 29635: + return 'Sudan UTM zone 35N'; + case 29636: + return 'Sudan UTM zone 36N'; + case 29700: + return 'Tananarive Laborde'; + case 29738: + return 'Tananarive UTM 38S'; + case 29739: + return 'Tananarive UTM 39S'; + case 29800: + return 'Timbalai 1948 Borneo'; + case 29849: + return 'Timbalai 1948 UTM 49N'; + case 29850: + return 'Timbalai 1948 UTM 50N'; + case 29900: + return 'TM65 Irish Nat Grid'; + case 30200: + return 'Trinidad 1903 Trinidad'; + case 30339: + return 'TC 1948 UTM zone 39N'; + case 30340: + return 'TC 1948 UTM zone 40N'; + case 30491: + return 'Voirol N Algerie ancien'; + case 30492: + return 'Voirol S Algerie ancien'; + case 30591: + return 'Voirol Unifie N Algerie'; + case 30592: + return 'Voirol Unifie S Algerie'; + case 30600: + return 'Bern 1938 Swiss New'; + case 30729: + return 'Nord Sahara UTM 29N'; + case 30730: + return 'Nord Sahara UTM 30N'; + case 30731: + return 'Nord Sahara UTM 31N'; + case 30732: + return 'Nord Sahara UTM 32N'; + case 31028: + return 'Yoff UTM zone 28N'; + case 31121: + return 'Zanderij UTM zone 21N'; + case 31291: + return 'MGI Austria West'; + case 31292: + return 'MGI Austria Central'; + case 31293: + return 'MGI Austria East'; + case 31300: + return 'Belge Lambert 72'; + case 31491: + return 'DHDN Germany zone 1'; + case 31492: + return 'DHDN Germany zone 2'; + case 31493: + return 'DHDN Germany zone 3'; + case 31494: + return 'DHDN Germany zone 4'; + case 31495: + return 'DHDN Germany zone 5'; + case 31700: + return 'Dealul Piscului 1970 Stereo 70'; + case 32001: + return 'NAD27 Montana North'; + case 32002: + return 'NAD27 Montana Central'; + case 32003: + return 'NAD27 Montana South'; + case 32005: + return 'NAD27 Nebraska North'; + case 32006: + return 'NAD27 Nebraska South'; + case 32007: + return 'NAD27 Nevada East'; + case 32008: + return 'NAD27 Nevada Central'; + case 32009: + return 'NAD27 Nevada West'; + case 32010: + return 'NAD27 New Hampshire'; + case 32011: + return 'NAD27 New Jersey'; + case 32012: + return 'NAD27 New Mexico East'; + case 32013: + return 'NAD27 New Mexico Cent'; + case 32014: + return 'NAD27 New Mexico West'; + case 32015: + return 'NAD27 New York East'; + case 32016: + return 'NAD27 New York Central'; + case 32017: + return 'NAD27 New York West'; + case 32018: + return 'NAD27 New York Long Is'; + case 32019: + return 'NAD27 North Carolina'; + case 32020: + return 'NAD27 North Dakota N'; + case 32021: + return 'NAD27 North Dakota S'; + case 32022: + return 'NAD27 Ohio North'; + case 32023: + return 'NAD27 Ohio South'; + case 32024: + return 'NAD27 Oklahoma North'; + case 32025: + return 'NAD27 Oklahoma South'; + case 32026: + return 'NAD27 Oregon North'; + case 32027: + return 'NAD27 Oregon South'; + case 32028: + return 'NAD27 Pennsylvania N'; + case 32029: + return 'NAD27 Pennsylvania S'; + case 32030: + return 'NAD27 Rhode Island'; + case 32031: + return 'NAD27 South Carolina N'; + case 32033: + return 'NAD27 South Carolina S'; + case 32034: + return 'NAD27 South Dakota N'; + case 32035: + return 'NAD27 South Dakota S'; + case 32036: + return 'NAD27 Tennessee'; + case 32037: + return 'NAD27 Texas North'; + case 32038: + return 'NAD27 Texas North Cen'; + case 32039: + return 'NAD27 Texas Central'; + case 32040: + return 'NAD27 Texas South Cen'; + case 32041: + return 'NAD27 Texas South'; + case 32042: + return 'NAD27 Utah North'; + case 32043: + return 'NAD27 Utah Central'; + case 32044: + return 'NAD27 Utah South'; + case 32045: + return 'NAD27 Vermont'; + case 32046: + return 'NAD27 Virginia North'; + case 32047: + return 'NAD27 Virginia South'; + case 32048: + return 'NAD27 Washington North'; + case 32049: + return 'NAD27 Washington South'; + case 32050: + return 'NAD27 West Virginia N'; + case 32051: + return 'NAD27 West Virginia S'; + case 32052: + return 'NAD27 Wisconsin North'; + case 32053: + return 'NAD27 Wisconsin Cen'; + case 32054: + return 'NAD27 Wisconsin South'; + case 32055: + return 'NAD27 Wyoming East'; + case 32056: + return 'NAD27 Wyoming E Cen'; + case 32057: + return 'NAD27 Wyoming W Cen'; + case 32058: + return 'NAD27 Wyoming West'; + case 32059: + return 'NAD27 Puerto Rico'; + case 32060: + return 'NAD27 St Croix'; + case 32100: + return 'NAD83 Montana'; + case 32104: + return 'NAD83 Nebraska'; + case 32107: + return 'NAD83 Nevada East'; + case 32108: + return 'NAD83 Nevada Central'; + case 32109: + return 'NAD83 Nevada West'; + case 32110: + return 'NAD83 New Hampshire'; + case 32111: + return 'NAD83 New Jersey'; + case 32112: + return 'NAD83 New Mexico East'; + case 32113: + return 'NAD83 New Mexico Cent'; + case 32114: + return 'NAD83 New Mexico West'; + case 32115: + return 'NAD83 New York East'; + case 32116: + return 'NAD83 New York Central'; + case 32117: + return 'NAD83 New York West'; + case 32118: + return 'NAD83 New York Long Is'; + case 32119: + return 'NAD83 North Carolina'; + case 32120: + return 'NAD83 North Dakota N'; + case 32121: + return 'NAD83 North Dakota S'; + case 32122: + return 'NAD83 Ohio North'; + case 32123: + return 'NAD83 Ohio South'; + case 32124: + return 'NAD83 Oklahoma North'; + case 32125: + return 'NAD83 Oklahoma South'; + case 32126: + return 'NAD83 Oregon North'; + case 32127: + return 'NAD83 Oregon South'; + case 32128: + return 'NAD83 Pennsylvania N'; + case 32129: + return 'NAD83 Pennsylvania S'; + case 32130: + return 'NAD83 Rhode Island'; + case 32133: + return 'NAD83 South Carolina'; + case 32134: + return 'NAD83 South Dakota N'; + case 32135: + return 'NAD83 South Dakota S'; + case 32136: + return 'NAD83 Tennessee'; + case 32137: + return 'NAD83 Texas North'; + case 32138: + return 'NAD83 Texas North Cen'; + case 32139: + return 'NAD83 Texas Central'; + case 32140: + return 'NAD83 Texas South Cen'; + case 32141: + return 'NAD83 Texas South'; + case 32142: + return 'NAD83 Utah North'; + case 32143: + return 'NAD83 Utah Central'; + case 32144: + return 'NAD83 Utah South'; + case 32145: + return 'NAD83 Vermont'; + case 32146: + return 'NAD83 Virginia North'; + case 32147: + return 'NAD83 Virginia South'; + case 32148: + return 'NAD83 Washington North'; + case 32149: + return 'NAD83 Washington South'; + case 32150: + return 'NAD83 West Virginia N'; + case 32151: + return 'NAD83 West Virginia S'; + case 32152: + return 'NAD83 Wisconsin North'; + case 32153: + return 'NAD83 Wisconsin Cen'; + case 32154: + return 'NAD83 Wisconsin South'; + case 32155: + return 'NAD83 Wyoming East'; + case 32156: + return 'NAD83 Wyoming E Cen'; + case 32157: + return 'NAD83 Wyoming W Cen'; + case 32158: + return 'NAD83 Wyoming West'; + case 32161: + return 'NAD83 Puerto Rico Virgin Is'; + case 32201: + return 'WGS72 UTM zone 1N'; + case 32202: + return 'WGS72 UTM zone 2N'; + case 32203: + return 'WGS72 UTM zone 3N'; + case 32204: + return 'WGS72 UTM zone 4N'; + case 32205: + return 'WGS72 UTM zone 5N'; + case 32206: + return 'WGS72 UTM zone 6N'; + case 32207: + return 'WGS72 UTM zone 7N'; + case 32208: + return 'WGS72 UTM zone 8N'; + case 32209: + return 'WGS72 UTM zone 9N'; + case 32210: + return 'WGS72 UTM zone 10N'; + case 32211: + return 'WGS72 UTM zone 11N'; + case 32212: + return 'WGS72 UTM zone 12N'; + case 32213: + return 'WGS72 UTM zone 13N'; + case 32214: + return 'WGS72 UTM zone 14N'; + case 32215: + return 'WGS72 UTM zone 15N'; + case 32216: + return 'WGS72 UTM zone 16N'; + case 32217: + return 'WGS72 UTM zone 17N'; + case 32218: + return 'WGS72 UTM zone 18N'; + case 32219: + return 'WGS72 UTM zone 19N'; + case 32220: + return 'WGS72 UTM zone 20N'; + case 32221: + return 'WGS72 UTM zone 21N'; + case 32222: + return 'WGS72 UTM zone 22N'; + case 32223: + return 'WGS72 UTM zone 23N'; + case 32224: + return 'WGS72 UTM zone 24N'; + case 32225: + return 'WGS72 UTM zone 25N'; + case 32226: + return 'WGS72 UTM zone 26N'; + case 32227: + return 'WGS72 UTM zone 27N'; + case 32228: + return 'WGS72 UTM zone 28N'; + case 32229: + return 'WGS72 UTM zone 29N'; + case 32230: + return 'WGS72 UTM zone 30N'; + case 32231: + return 'WGS72 UTM zone 31N'; + case 32232: + return 'WGS72 UTM zone 32N'; + case 32233: + return 'WGS72 UTM zone 33N'; + case 32234: + return 'WGS72 UTM zone 34N'; + case 32235: + return 'WGS72 UTM zone 35N'; + case 32236: + return 'WGS72 UTM zone 36N'; + case 32237: + return 'WGS72 UTM zone 37N'; + case 32238: + return 'WGS72 UTM zone 38N'; + case 32239: + return 'WGS72 UTM zone 39N'; + case 32240: + return 'WGS72 UTM zone 40N'; + case 32241: + return 'WGS72 UTM zone 41N'; + case 32242: + return 'WGS72 UTM zone 42N'; + case 32243: + return 'WGS72 UTM zone 43N'; + case 32244: + return 'WGS72 UTM zone 44N'; + case 32245: + return 'WGS72 UTM zone 45N'; + case 32246: + return 'WGS72 UTM zone 46N'; + case 32247: + return 'WGS72 UTM zone 47N'; + case 32248: + return 'WGS72 UTM zone 48N'; + case 32249: + return 'WGS72 UTM zone 49N'; + case 32250: + return 'WGS72 UTM zone 50N'; + case 32251: + return 'WGS72 UTM zone 51N'; + case 32252: + return 'WGS72 UTM zone 52N'; + case 32253: + return 'WGS72 UTM zone 53N'; + case 32254: + return 'WGS72 UTM zone 54N'; + case 32255: + return 'WGS72 UTM zone 55N'; + case 32256: + return 'WGS72 UTM zone 56N'; + case 32257: + return 'WGS72 UTM zone 57N'; + case 32258: + return 'WGS72 UTM zone 58N'; + case 32259: + return 'WGS72 UTM zone 59N'; + case 32260: + return 'WGS72 UTM zone 60N'; + case 32301: + return 'WGS72 UTM zone 1S'; + case 32302: + return 'WGS72 UTM zone 2S'; + case 32303: + return 'WGS72 UTM zone 3S'; + case 32304: + return 'WGS72 UTM zone 4S'; + case 32305: + return 'WGS72 UTM zone 5S'; + case 32306: + return 'WGS72 UTM zone 6S'; + case 32307: + return 'WGS72 UTM zone 7S'; + case 32308: + return 'WGS72 UTM zone 8S'; + case 32309: + return 'WGS72 UTM zone 9S'; + case 32310: + return 'WGS72 UTM zone 10S'; + case 32311: + return 'WGS72 UTM zone 11S'; + case 32312: + return 'WGS72 UTM zone 12S'; + case 32313: + return 'WGS72 UTM zone 13S'; + case 32314: + return 'WGS72 UTM zone 14S'; + case 32315: + return 'WGS72 UTM zone 15S'; + case 32316: + return 'WGS72 UTM zone 16S'; + case 32317: + return 'WGS72 UTM zone 17S'; + case 32318: + return 'WGS72 UTM zone 18S'; + case 32319: + return 'WGS72 UTM zone 19S'; + case 32320: + return 'WGS72 UTM zone 20S'; + case 32321: + return 'WGS72 UTM zone 21S'; + case 32322: + return 'WGS72 UTM zone 22S'; + case 32323: + return 'WGS72 UTM zone 23S'; + case 32324: + return 'WGS72 UTM zone 24S'; + case 32325: + return 'WGS72 UTM zone 25S'; + case 32326: + return 'WGS72 UTM zone 26S'; + case 32327: + return 'WGS72 UTM zone 27S'; + case 32328: + return 'WGS72 UTM zone 28S'; + case 32329: + return 'WGS72 UTM zone 29S'; + case 32330: + return 'WGS72 UTM zone 30S'; + case 32331: + return 'WGS72 UTM zone 31S'; + case 32332: + return 'WGS72 UTM zone 32S'; + case 32333: + return 'WGS72 UTM zone 33S'; + case 32334: + return 'WGS72 UTM zone 34S'; + case 32335: + return 'WGS72 UTM zone 35S'; + case 32336: + return 'WGS72 UTM zone 36S'; + case 32337: + return 'WGS72 UTM zone 37S'; + case 32338: + return 'WGS72 UTM zone 38S'; + case 32339: + return 'WGS72 UTM zone 39S'; + case 32340: + return 'WGS72 UTM zone 40S'; + case 32341: + return 'WGS72 UTM zone 41S'; + case 32342: + return 'WGS72 UTM zone 42S'; + case 32343: + return 'WGS72 UTM zone 43S'; + case 32344: + return 'WGS72 UTM zone 44S'; + case 32345: + return 'WGS72 UTM zone 45S'; + case 32346: + return 'WGS72 UTM zone 46S'; + case 32347: + return 'WGS72 UTM zone 47S'; + case 32348: + return 'WGS72 UTM zone 48S'; + case 32349: + return 'WGS72 UTM zone 49S'; + case 32350: + return 'WGS72 UTM zone 50S'; + case 32351: + return 'WGS72 UTM zone 51S'; + case 32352: + return 'WGS72 UTM zone 52S'; + case 32353: + return 'WGS72 UTM zone 53S'; + case 32354: + return 'WGS72 UTM zone 54S'; + case 32355: + return 'WGS72 UTM zone 55S'; + case 32356: + return 'WGS72 UTM zone 56S'; + case 32357: + return 'WGS72 UTM zone 57S'; + case 32358: + return 'WGS72 UTM zone 58S'; + case 32359: + return 'WGS72 UTM zone 59S'; + case 32360: + return 'WGS72 UTM zone 60S'; + case 32401: + return 'WGS72BE UTM zone 1N'; + case 32402: + return 'WGS72BE UTM zone 2N'; + case 32403: + return 'WGS72BE UTM zone 3N'; + case 32404: + return 'WGS72BE UTM zone 4N'; + case 32405: + return 'WGS72BE UTM zone 5N'; + case 32406: + return 'WGS72BE UTM zone 6N'; + case 32407: + return 'WGS72BE UTM zone 7N'; + case 32408: + return 'WGS72BE UTM zone 8N'; + case 32409: + return 'WGS72BE UTM zone 9N'; + case 32410: + return 'WGS72BE UTM zone 10N'; + case 32411: + return 'WGS72BE UTM zone 11N'; + case 32412: + return 'WGS72BE UTM zone 12N'; + case 32413: + return 'WGS72BE UTM zone 13N'; + case 32414: + return 'WGS72BE UTM zone 14N'; + case 32415: + return 'WGS72BE UTM zone 15N'; + case 32416: + return 'WGS72BE UTM zone 16N'; + case 32417: + return 'WGS72BE UTM zone 17N'; + case 32418: + return 'WGS72BE UTM zone 18N'; + case 32419: + return 'WGS72BE UTM zone 19N'; + case 32420: + return 'WGS72BE UTM zone 20N'; + case 32421: + return 'WGS72BE UTM zone 21N'; + case 32422: + return 'WGS72BE UTM zone 22N'; + case 32423: + return 'WGS72BE UTM zone 23N'; + case 32424: + return 'WGS72BE UTM zone 24N'; + case 32425: + return 'WGS72BE UTM zone 25N'; + case 32426: + return 'WGS72BE UTM zone 26N'; + case 32427: + return 'WGS72BE UTM zone 27N'; + case 32428: + return 'WGS72BE UTM zone 28N'; + case 32429: + return 'WGS72BE UTM zone 29N'; + case 32430: + return 'WGS72BE UTM zone 30N'; + case 32431: + return 'WGS72BE UTM zone 31N'; + case 32432: + return 'WGS72BE UTM zone 32N'; + case 32433: + return 'WGS72BE UTM zone 33N'; + case 32434: + return 'WGS72BE UTM zone 34N'; + case 32435: + return 'WGS72BE UTM zone 35N'; + case 32436: + return 'WGS72BE UTM zone 36N'; + case 32437: + return 'WGS72BE UTM zone 37N'; + case 32438: + return 'WGS72BE UTM zone 38N'; + case 32439: + return 'WGS72BE UTM zone 39N'; + case 32440: + return 'WGS72BE UTM zone 40N'; + case 32441: + return 'WGS72BE UTM zone 41N'; + case 32442: + return 'WGS72BE UTM zone 42N'; + case 32443: + return 'WGS72BE UTM zone 43N'; + case 32444: + return 'WGS72BE UTM zone 44N'; + case 32445: + return 'WGS72BE UTM zone 45N'; + case 32446: + return 'WGS72BE UTM zone 46N'; + case 32447: + return 'WGS72BE UTM zone 47N'; + case 32448: + return 'WGS72BE UTM zone 48N'; + case 32449: + return 'WGS72BE UTM zone 49N'; + case 32450: + return 'WGS72BE UTM zone 50N'; + case 32451: + return 'WGS72BE UTM zone 51N'; + case 32452: + return 'WGS72BE UTM zone 52N'; + case 32453: + return 'WGS72BE UTM zone 53N'; + case 32454: + return 'WGS72BE UTM zone 54N'; + case 32455: + return 'WGS72BE UTM zone 55N'; + case 32456: + return 'WGS72BE UTM zone 56N'; + case 32457: + return 'WGS72BE UTM zone 57N'; + case 32458: + return 'WGS72BE UTM zone 58N'; + case 32459: + return 'WGS72BE UTM zone 59N'; + case 32460: + return 'WGS72BE UTM zone 60N'; + case 32501: + return 'WGS72BE UTM zone 1S'; + case 32502: + return 'WGS72BE UTM zone 2S'; + case 32503: + return 'WGS72BE UTM zone 3S'; + case 32504: + return 'WGS72BE UTM zone 4S'; + case 32505: + return 'WGS72BE UTM zone 5S'; + case 32506: + return 'WGS72BE UTM zone 6S'; + case 32507: + return 'WGS72BE UTM zone 7S'; + case 32508: + return 'WGS72BE UTM zone 8S'; + case 32509: + return 'WGS72BE UTM zone 9S'; + case 32510: + return 'WGS72BE UTM zone 10S'; + case 32511: + return 'WGS72BE UTM zone 11S'; + case 32512: + return 'WGS72BE UTM zone 12S'; + case 32513: + return 'WGS72BE UTM zone 13S'; + case 32514: + return 'WGS72BE UTM zone 14S'; + case 32515: + return 'WGS72BE UTM zone 15S'; + case 32516: + return 'WGS72BE UTM zone 16S'; + case 32517: + return 'WGS72BE UTM zone 17S'; + case 32518: + return 'WGS72BE UTM zone 18S'; + case 32519: + return 'WGS72BE UTM zone 19S'; + case 32520: + return 'WGS72BE UTM zone 20S'; + case 32521: + return 'WGS72BE UTM zone 21S'; + case 32522: + return 'WGS72BE UTM zone 22S'; + case 32523: + return 'WGS72BE UTM zone 23S'; + case 32524: + return 'WGS72BE UTM zone 24S'; + case 32525: + return 'WGS72BE UTM zone 25S'; + case 32526: + return 'WGS72BE UTM zone 26S'; + case 32527: + return 'WGS72BE UTM zone 27S'; + case 32528: + return 'WGS72BE UTM zone 28S'; + case 32529: + return 'WGS72BE UTM zone 29S'; + case 32530: + return 'WGS72BE UTM zone 30S'; + case 32531: + return 'WGS72BE UTM zone 31S'; + case 32532: + return 'WGS72BE UTM zone 32S'; + case 32533: + return 'WGS72BE UTM zone 33S'; + case 32534: + return 'WGS72BE UTM zone 34S'; + case 32535: + return 'WGS72BE UTM zone 35S'; + case 32536: + return 'WGS72BE UTM zone 36S'; + case 32537: + return 'WGS72BE UTM zone 37S'; + case 32538: + return 'WGS72BE UTM zone 38S'; + case 32539: + return 'WGS72BE UTM zone 39S'; + case 32540: + return 'WGS72BE UTM zone 40S'; + case 32541: + return 'WGS72BE UTM zone 41S'; + case 32542: + return 'WGS72BE UTM zone 42S'; + case 32543: + return 'WGS72BE UTM zone 43S'; + case 32544: + return 'WGS72BE UTM zone 44S'; + case 32545: + return 'WGS72BE UTM zone 45S'; + case 32546: + return 'WGS72BE UTM zone 46S'; + case 32547: + return 'WGS72BE UTM zone 47S'; + case 32548: + return 'WGS72BE UTM zone 48S'; + case 32549: + return 'WGS72BE UTM zone 49S'; + case 32550: + return 'WGS72BE UTM zone 50S'; + case 32551: + return 'WGS72BE UTM zone 51S'; + case 32552: + return 'WGS72BE UTM zone 52S'; + case 32553: + return 'WGS72BE UTM zone 53S'; + case 32554: + return 'WGS72BE UTM zone 54S'; + case 32555: + return 'WGS72BE UTM zone 55S'; + case 32556: + return 'WGS72BE UTM zone 56S'; + case 32557: + return 'WGS72BE UTM zone 57S'; + case 32558: + return 'WGS72BE UTM zone 58S'; + case 32559: + return 'WGS72BE UTM zone 59S'; + case 32560: + return 'WGS72BE UTM zone 60S'; + case 32601: + return 'WGS84 UTM zone 1N'; + case 32602: + return 'WGS84 UTM zone 2N'; + case 32603: + return 'WGS84 UTM zone 3N'; + case 32604: + return 'WGS84 UTM zone 4N'; + case 32605: + return 'WGS84 UTM zone 5N'; + case 32606: + return 'WGS84 UTM zone 6N'; + case 32607: + return 'WGS84 UTM zone 7N'; + case 32608: + return 'WGS84 UTM zone 8N'; + case 32609: + return 'WGS84 UTM zone 9N'; + case 32610: + return 'WGS84 UTM zone 10N'; + case 32611: + return 'WGS84 UTM zone 11N'; + case 32612: + return 'WGS84 UTM zone 12N'; + case 32613: + return 'WGS84 UTM zone 13N'; + case 32614: + return 'WGS84 UTM zone 14N'; + case 32615: + return 'WGS84 UTM zone 15N'; + case 32616: + return 'WGS84 UTM zone 16N'; + case 32617: + return 'WGS84 UTM zone 17N'; + case 32618: + return 'WGS84 UTM zone 18N'; + case 32619: + return 'WGS84 UTM zone 19N'; + case 32620: + return 'WGS84 UTM zone 20N'; + case 32621: + return 'WGS84 UTM zone 21N'; + case 32622: + return 'WGS84 UTM zone 22N'; + case 32623: + return 'WGS84 UTM zone 23N'; + case 32624: + return 'WGS84 UTM zone 24N'; + case 32625: + return 'WGS84 UTM zone 25N'; + case 32626: + return 'WGS84 UTM zone 26N'; + case 32627: + return 'WGS84 UTM zone 27N'; + case 32628: + return 'WGS84 UTM zone 28N'; + case 32629: + return 'WGS84 UTM zone 29N'; + case 32630: + return 'WGS84 UTM zone 30N'; + case 32631: + return 'WGS84 UTM zone 31N'; + case 32632: + return 'WGS84 UTM zone 32N'; + case 32633: + return 'WGS84 UTM zone 33N'; + case 32634: + return 'WGS84 UTM zone 34N'; + case 32635: + return 'WGS84 UTM zone 35N'; + case 32636: + return 'WGS84 UTM zone 36N'; + case 32637: + return 'WGS84 UTM zone 37N'; + case 32638: + return 'WGS84 UTM zone 38N'; + case 32639: + return 'WGS84 UTM zone 39N'; + case 32640: + return 'WGS84 UTM zone 40N'; + case 32641: + return 'WGS84 UTM zone 41N'; + case 32642: + return 'WGS84 UTM zone 42N'; + case 32643: + return 'WGS84 UTM zone 43N'; + case 32644: + return 'WGS84 UTM zone 44N'; + case 32645: + return 'WGS84 UTM zone 45N'; + case 32646: + return 'WGS84 UTM zone 46N'; + case 32647: + return 'WGS84 UTM zone 47N'; + case 32648: + return 'WGS84 UTM zone 48N'; + case 32649: + return 'WGS84 UTM zone 49N'; + case 32650: + return 'WGS84 UTM zone 50N'; + case 32651: + return 'WGS84 UTM zone 51N'; + case 32652: + return 'WGS84 UTM zone 52N'; + case 32653: + return 'WGS84 UTM zone 53N'; + case 32654: + return 'WGS84 UTM zone 54N'; + case 32655: + return 'WGS84 UTM zone 55N'; + case 32656: + return 'WGS84 UTM zone 56N'; + case 32657: + return 'WGS84 UTM zone 57N'; + case 32658: + return 'WGS84 UTM zone 58N'; + case 32659: + return 'WGS84 UTM zone 59N'; + case 32660: + return 'WGS84 UTM zone 60N'; + case 32701: + return 'WGS84 UTM zone 1S'; + case 32702: + return 'WGS84 UTM zone 2S'; + case 32703: + return 'WGS84 UTM zone 3S'; + case 32704: + return 'WGS84 UTM zone 4S'; + case 32705: + return 'WGS84 UTM zone 5S'; + case 32706: + return 'WGS84 UTM zone 6S'; + case 32707: + return 'WGS84 UTM zone 7S'; + case 32708: + return 'WGS84 UTM zone 8S'; + case 32709: + return 'WGS84 UTM zone 9S'; + case 32710: + return 'WGS84 UTM zone 10S'; + case 32711: + return 'WGS84 UTM zone 11S'; + case 32712: + return 'WGS84 UTM zone 12S'; + case 32713: + return 'WGS84 UTM zone 13S'; + case 32714: + return 'WGS84 UTM zone 14S'; + case 32715: + return 'WGS84 UTM zone 15S'; + case 32716: + return 'WGS84 UTM zone 16S'; + case 32717: + return 'WGS84 UTM zone 17S'; + case 32718: + return 'WGS84 UTM zone 18S'; + case 32719: + return 'WGS84 UTM zone 19S'; + case 32720: + return 'WGS84 UTM zone 20S'; + case 32721: + return 'WGS84 UTM zone 21S'; + case 32722: + return 'WGS84 UTM zone 22S'; + case 32723: + return 'WGS84 UTM zone 23S'; + case 32724: + return 'WGS84 UTM zone 24S'; + case 32725: + return 'WGS84 UTM zone 25S'; + case 32726: + return 'WGS84 UTM zone 26S'; + case 32727: + return 'WGS84 UTM zone 27S'; + case 32728: + return 'WGS84 UTM zone 28S'; + case 32729: + return 'WGS84 UTM zone 29S'; + case 32730: + return 'WGS84 UTM zone 30S'; + case 32731: + return 'WGS84 UTM zone 31S'; + case 32732: + return 'WGS84 UTM zone 32S'; + case 32733: + return 'WGS84 UTM zone 33S'; + case 32734: + return 'WGS84 UTM zone 34S'; + case 32735: + return 'WGS84 UTM zone 35S'; + case 32736: + return 'WGS84 UTM zone 36S'; + case 32737: + return 'WGS84 UTM zone 37S'; + case 32738: + return 'WGS84 UTM zone 38S'; + case 32739: + return 'WGS84 UTM zone 39S'; + case 32740: + return 'WGS84 UTM zone 40S'; + case 32741: + return 'WGS84 UTM zone 41S'; + case 32742: + return 'WGS84 UTM zone 42S'; + case 32743: + return 'WGS84 UTM zone 43S'; + case 32744: + return 'WGS84 UTM zone 44S'; + case 32745: + return 'WGS84 UTM zone 45S'; + case 32746: + return 'WGS84 UTM zone 46S'; + case 32747: + return 'WGS84 UTM zone 47S'; + case 32748: + return 'WGS84 UTM zone 48S'; + case 32749: + return 'WGS84 UTM zone 49S'; + case 32750: + return 'WGS84 UTM zone 50S'; + case 32751: + return 'WGS84 UTM zone 51S'; + case 32752: + return 'WGS84 UTM zone 52S'; + case 32753: + return 'WGS84 UTM zone 53S'; + case 32754: + return 'WGS84 UTM zone 54S'; + case 32755: + return 'WGS84 UTM zone 55S'; + case 32756: + return 'WGS84 UTM zone 56S'; + case 32757: + return 'WGS84 UTM zone 57S'; + case 32758: + return 'WGS84 UTM zone 58S'; + case 32759: + return 'WGS84 UTM zone 59S'; + case 32760: + return 'WGS84 UTM zone 60S'; + case 32767: + return 'User Defined'; + default: + return 'Unknown ($value)'; + } + } + + static String getProjectionDescription(String valueString) { + final value = int.tryParse(valueString); + if (value == null) return valueString; + switch (value) { + case 10101: + return 'Alabama CS27 East'; + case 10102: + return 'Alabama CS27 West'; + case 10131: + return 'Alabama CS83 East'; + case 10132: + return 'Alabama CS83 West'; + case 10201: + return 'Arizona Coordinate System east'; + case 10202: + return 'Arizona Coordinate System Central'; + case 10203: + return 'Arizona Coordinate System west'; + case 10231: + return 'Arizona CS83 east'; + case 10232: + return 'Arizona CS83 Central'; + case 10233: + return 'Arizona CS83 west'; + case 10301: + return 'Arkansas CS27 North'; + case 10302: + return 'Arkansas CS27 South'; + case 10331: + return 'Arkansas CS83 North'; + case 10332: + return 'Arkansas CS83 South'; + case 10401: + return 'California CS27 I'; + case 10402: + return 'California CS27 II'; + case 10403: + return 'California CS27 III'; + case 10404: + return 'California CS27 IV'; + case 10405: + return 'California CS27 V'; + case 10406: + return 'California CS27 VI'; + case 10407: + return 'California CS27 VII'; + case 10431: + return 'California CS83 1'; + case 10432: + return 'California CS83 2'; + case 10433: + return 'California CS83 3'; + case 10434: + return 'California CS83 4'; + case 10435: + return 'California CS83 5'; + case 10436: + return 'California CS83 6'; + case 10501: + return 'Colorado CS27 North'; + case 10502: + return 'Colorado CS27 Central'; + case 10503: + return 'Colorado CS27 South'; + case 10531: + return 'Colorado CS83 North'; + case 10532: + return 'Colorado CS83 Central'; + case 10533: + return 'Colorado CS83 South'; + case 10600: + return 'Connecticut CS27'; + case 10630: + return 'Connecticut CS83'; + case 10700: + return 'Delaware CS27'; + case 10730: + return 'Delaware CS83'; + case 10901: + return 'Florida CS27 East'; + case 10902: + return 'Florida CS27 West'; + case 10903: + return 'Florida CS27 North'; + case 10931: + return 'Florida CS83 East'; + case 10932: + return 'Florida CS83 West'; + case 10933: + return 'Florida CS83 North'; + case 11001: + return 'Georgia CS27 East'; + case 11002: + return 'Georgia CS27 West'; + case 11031: + return 'Georgia CS83 East'; + case 11032: + return 'Georgia CS83 West'; + case 11101: + return 'Idaho CS27 East'; + case 11102: + return 'Idaho CS27 Central'; + case 11103: + return 'Idaho CS27 West'; + case 11131: + return 'Idaho CS83 East'; + case 11132: + return 'Idaho CS83 Central'; + case 11133: + return 'Idaho CS83 West'; + case 11201: + return 'Illinois CS27 East'; + case 11202: + return 'Illinois CS27 West'; + case 11231: + return 'Illinois CS83 East'; + case 11232: + return 'Illinois CS83 West'; + case 11301: + return 'Indiana CS27 East'; + case 11302: + return 'Indiana CS27 West'; + case 11331: + return 'Indiana CS83 East'; + case 11332: + return 'Indiana CS83 West'; + case 11401: + return 'Iowa CS27 North'; + case 11402: + return 'Iowa CS27 South'; + case 11431: + return 'Iowa CS83 North'; + case 11432: + return 'Iowa CS83 South'; + case 11501: + return 'Kansas CS27 North'; + case 11502: + return 'Kansas CS27 South'; + case 11531: + return 'Kansas CS83 North'; + case 11532: + return 'Kansas CS83 South'; + case 11601: + return 'Kentucky CS27 North'; + case 11602: + return 'Kentucky CS27 South'; + case 11631: + return 'Kentucky CS83 North'; + case 11632: + return 'Kentucky CS83 South'; + case 11701: + return 'Louisiana CS27 North'; + case 11702: + return 'Louisiana CS27 South'; + case 11731: + return 'Louisiana CS83 North'; + case 11732: + return 'Louisiana CS83 South'; + case 11801: + return 'Maine CS27 East'; + case 11802: + return 'Maine CS27 West'; + case 11831: + return 'Maine CS83 East'; + case 11832: + return 'Maine CS83 West'; + case 11900: + return 'Maryland CS27'; + case 11930: + return 'Maryland CS83'; + case 12001: + return 'Massachusetts CS27 Mainland'; + case 12002: + return 'Massachusetts CS27 Island'; + case 12031: + return 'Massachusetts CS83 Mainland'; + case 12032: + return 'Massachusetts CS83 Island'; + case 12101: + return 'Michigan State Plane East'; + case 12102: + return 'Michigan State Plane Old Central'; + case 12103: + return 'Michigan State Plane West'; + case 12111: + return 'Michigan CS27 North'; + case 12112: + return 'Michigan CS27 Central'; + case 12113: + return 'Michigan CS27 South'; + case 12141: + return 'Michigan CS83 North'; + case 12142: + return 'Michigan CS83 Central'; + case 12143: + return 'Michigan CS83 South'; + case 12201: + return 'Minnesota CS27 North'; + case 12202: + return 'Minnesota CS27 Central'; + case 12203: + return 'Minnesota CS27 South'; + case 12231: + return 'Minnesota CS83 North'; + case 12232: + return 'Minnesota CS83 Central'; + case 12233: + return 'Minnesota CS83 South'; + case 12301: + return 'Mississippi CS27 East'; + case 12302: + return 'Mississippi CS27 West'; + case 12331: + return 'Mississippi CS83 East'; + case 12332: + return 'Mississippi CS83 West'; + case 12401: + return 'Missouri CS27 East'; + case 12402: + return 'Missouri CS27 Central'; + case 12403: + return 'Missouri CS27 West'; + case 12431: + return 'Missouri CS83 East'; + case 12432: + return 'Missouri CS83 Central'; + case 12433: + return 'Missouri CS83 West'; + case 12501: + return 'Montana CS27 North'; + case 12502: + return 'Montana CS27 Central'; + case 12503: + return 'Montana CS27 South'; + case 12530: + return 'Montana CS83'; + case 12601: + return 'Nebraska CS27 North'; + case 12602: + return 'Nebraska CS27 South'; + case 12630: + return 'Nebraska CS83'; + case 12701: + return 'Nevada CS27 East'; + case 12702: + return 'Nevada CS27 Central'; + case 12703: + return 'Nevada CS27 West'; + case 12731: + return 'Nevada CS83 East'; + case 12732: + return 'Nevada CS83 Central'; + case 12733: + return 'Nevada CS83 West'; + case 12800: + return 'New Hampshire CS27'; + case 12830: + return 'New Hampshire CS83'; + case 12900: + return 'New Jersey CS27'; + case 12930: + return 'New Jersey CS83'; + case 13001: + return 'New Mexico CS27 East'; + case 13002: + return 'New Mexico CS27 Central'; + case 13003: + return 'New Mexico CS27 West'; + case 13031: + return 'New Mexico CS83 East'; + case 13032: + return 'New Mexico CS83 Central'; + case 13033: + return 'New Mexico CS83 West'; + case 13101: + return 'New York CS27 East'; + case 13102: + return 'New York CS27 Central'; + case 13103: + return 'New York CS27 West'; + case 13104: + return 'New York CS27 Long Island'; + case 13131: + return 'New York CS83 East'; + case 13132: + return 'New York CS83 Central'; + case 13133: + return 'New York CS83 West'; + case 13134: + return 'New York CS83 Long Island'; + case 13200: + return 'North Carolina CS27'; + case 13230: + return 'North Carolina CS83'; + case 13301: + return 'North Dakota CS27 North'; + case 13302: + return 'North Dakota CS27 South'; + case 13331: + return 'North Dakota CS83 North'; + case 13332: + return 'North Dakota CS83 South'; + case 13401: + return 'Ohio CS27 North'; + case 13402: + return 'Ohio CS27 South'; + case 13431: + return 'Ohio CS83 North'; + case 13432: + return 'Ohio CS83 South'; + case 13501: + return 'Oklahoma CS27 North'; + case 13502: + return 'Oklahoma CS27 South'; + case 13531: + return 'Oklahoma CS83 North'; + case 13532: + return 'Oklahoma CS83 South'; + case 13601: + return 'Oregon CS27 North'; + case 13602: + return 'Oregon CS27 South'; + case 13631: + return 'Oregon CS83 North'; + case 13632: + return 'Oregon CS83 South'; + case 13701: + return 'Pennsylvania CS27 North'; + case 13702: + return 'Pennsylvania CS27 South'; + case 13731: + return 'Pennsylvania CS83 North'; + case 13732: + return 'Pennsylvania CS83 South'; + case 13800: + return 'Rhode Island CS27'; + case 13830: + return 'Rhode Island CS83'; + case 13901: + return 'South Carolina CS27 North'; + case 13902: + return 'South Carolina CS27 South'; + case 13930: + return 'South Carolina CS83'; + case 14001: + return 'South Dakota CS27 North'; + case 14002: + return 'South Dakota CS27 South'; + case 14031: + return 'South Dakota CS83 North'; + case 14032: + return 'South Dakota CS83 South'; + case 14100: + return 'Tennessee CS27'; + case 14130: + return 'Tennessee CS83'; + case 14201: + return 'Texas CS27 North'; + case 14202: + return 'Texas CS27 North Central'; + case 14203: + return 'Texas CS27 Central'; + case 14204: + return 'Texas CS27 South Central'; + case 14205: + return 'Texas CS27 South'; + case 14231: + return 'Texas CS83 North'; + case 14232: + return 'Texas CS83 North Central'; + case 14233: + return 'Texas CS83 Central'; + case 14234: + return 'Texas CS83 South Central'; + case 14235: + return 'Texas CS83 South'; + case 14301: + return 'Utah CS27 North'; + case 14302: + return 'Utah CS27 Central'; + case 14303: + return 'Utah CS27 South'; + case 14331: + return 'Utah CS83 North'; + case 14332: + return 'Utah CS83 Central'; + case 14333: + return 'Utah CS83 South'; + case 14400: + return 'Vermont CS27'; + case 14430: + return 'Vermont CS83'; + case 14501: + return 'Virginia CS27 North'; + case 14502: + return 'Virginia CS27 South'; + case 14531: + return 'Virginia CS83 North'; + case 14532: + return 'Virginia CS83 South'; + case 14601: + return 'Washington CS27 North'; + case 14602: + return 'Washington CS27 South'; + case 14631: + return 'Washington CS83 North'; + case 14632: + return 'Washington CS83 South'; + case 14701: + return 'West Virginia CS27 North'; + case 14702: + return 'West Virginia CS27 South'; + case 14731: + return 'West Virginia CS83 North'; + case 14732: + return 'West Virginia CS83 South'; + case 14801: + return 'Wisconsin CS27 North'; + case 14802: + return 'Wisconsin CS27 Central'; + case 14803: + return 'Wisconsin CS27 South'; + case 14831: + return 'Wisconsin CS83 North'; + case 14832: + return 'Wisconsin CS83 Central'; + case 14833: + return 'Wisconsin CS83 South'; + case 14901: + return 'Wyoming CS27 East'; + case 14902: + return 'Wyoming CS27 East Central'; + case 14903: + return 'Wyoming CS27 West Central'; + case 14904: + return 'Wyoming CS27 West'; + case 14931: + return 'Wyoming CS83 East'; + case 14932: + return 'Wyoming CS83 East Central'; + case 14933: + return 'Wyoming CS83 West Central'; + case 14934: + return 'Wyoming CS83 West'; + case 15001: + return 'Alaska CS27 1'; + case 15002: + return 'Alaska CS27 2'; + case 15003: + return 'Alaska CS27 3'; + case 15004: + return 'Alaska CS27 4'; + case 15005: + return 'Alaska CS27 5'; + case 15006: + return 'Alaska CS27 6'; + case 15007: + return 'Alaska CS27 7'; + case 15008: + return 'Alaska CS27 8'; + case 15009: + return 'Alaska CS27 9'; + case 15010: + return 'Alaska CS27 10'; + case 15031: + return 'Alaska CS83 1'; + case 15032: + return 'Alaska CS83 2'; + case 15033: + return 'Alaska CS83 3'; + case 15034: + return 'Alaska CS83 4'; + case 15035: + return 'Alaska CS83 5'; + case 15036: + return 'Alaska CS83 6'; + case 15037: + return 'Alaska CS83 7'; + case 15038: + return 'Alaska CS83 8'; + case 15039: + return 'Alaska CS83 9'; + case 15040: + return 'Alaska CS83 10'; + case 15101: + return 'Hawaii CS27 1'; + case 15102: + return 'Hawaii CS27 2'; + case 15103: + return 'Hawaii CS27 3'; + case 15104: + return 'Hawaii CS27 4'; + case 15105: + return 'Hawaii CS27 5'; + case 15131: + return 'Hawaii CS83 1'; + case 15132: + return 'Hawaii CS83 2'; + case 15133: + return 'Hawaii CS83 3'; + case 15134: + return 'Hawaii CS83 4'; + case 15135: + return 'Hawaii CS83 5'; + case 15201: + return 'Puerto Rico CS27'; + case 15202: + return 'St Croix'; + case 15230: + return 'Puerto Rico Virgin Is'; + case 15302: + return 'Kentucky CS27'; + case 15303: + return 'Kentucky CS83 North'; + case 15914: + return 'BLM 14N feet'; + case 15915: + return 'BLM 15N feet'; + case 15916: + return 'BLM 16N feet'; + case 15917: + return 'BLM 17N feet'; + case 16001: + return 'UTM zone 1N'; + case 16002: + return 'UTM zone 2N'; + case 16003: + return 'UTM zone 3N'; + case 16004: + return 'UTM zone 4N'; + case 16005: + return 'UTM zone 5N'; + case 16006: + return 'UTM zone 6N'; + case 16007: + return 'UTM zone 7N'; + case 16008: + return 'UTM zone 8N'; + case 16009: + return 'UTM zone 9N'; + case 16010: + return 'UTM zone 10N'; + case 16011: + return 'UTM zone 11N'; + case 16012: + return 'UTM zone 12N'; + case 16013: + return 'UTM zone 13N'; + case 16014: + return 'UTM zone 14N'; + case 16015: + return 'UTM zone 15N'; + case 16016: + return 'UTM zone 16N'; + case 16017: + return 'UTM zone 17N'; + case 16018: + return 'UTM zone 18N'; + case 16019: + return 'UTM zone 19N'; + case 16020: + return 'UTM zone 20N'; + case 16021: + return 'UTM zone 21N'; + case 16022: + return 'UTM zone 22N'; + case 16023: + return 'UTM zone 23N'; + case 16024: + return 'UTM zone 24N'; + case 16025: + return 'UTM zone 25N'; + case 16026: + return 'UTM zone 26N'; + case 16027: + return 'UTM zone 27N'; + case 16028: + return 'UTM zone 28N'; + case 16029: + return 'UTM zone 29N'; + case 16030: + return 'UTM zone 30N'; + case 16031: + return 'UTM zone 31N'; + case 16032: + return 'UTM zone 32N'; + case 16033: + return 'UTM zone 33N'; + case 16034: + return 'UTM zone 34N'; + case 16035: + return 'UTM zone 35N'; + case 16036: + return 'UTM zone 36N'; + case 16037: + return 'UTM zone 37N'; + case 16038: + return 'UTM zone 38N'; + case 16039: + return 'UTM zone 39N'; + case 16040: + return 'UTM zone 40N'; + case 16041: + return 'UTM zone 41N'; + case 16042: + return 'UTM zone 42N'; + case 16043: + return 'UTM zone 43N'; + case 16044: + return 'UTM zone 44N'; + case 16045: + return 'UTM zone 45N'; + case 16046: + return 'UTM zone 46N'; + case 16047: + return 'UTM zone 47N'; + case 16048: + return 'UTM zone 48N'; + case 16049: + return 'UTM zone 49N'; + case 16050: + return 'UTM zone 50N'; + case 16051: + return 'UTM zone 51N'; + case 16052: + return 'UTM zone 52N'; + case 16053: + return 'UTM zone 53N'; + case 16054: + return 'UTM zone 54N'; + case 16055: + return 'UTM zone 55N'; + case 16056: + return 'UTM zone 56N'; + case 16057: + return 'UTM zone 57N'; + case 16058: + return 'UTM zone 58N'; + case 16059: + return 'UTM zone 59N'; + case 16060: + return 'UTM zone 60N'; + case 16101: + return 'UTM zone 1S'; + case 16102: + return 'UTM zone 2S'; + case 16103: + return 'UTM zone 3S'; + case 16104: + return 'UTM zone 4S'; + case 16105: + return 'UTM zone 5S'; + case 16106: + return 'UTM zone 6S'; + case 16107: + return 'UTM zone 7S'; + case 16108: + return 'UTM zone 8S'; + case 16109: + return 'UTM zone 9S'; + case 16110: + return 'UTM zone 10S'; + case 16111: + return 'UTM zone 11S'; + case 16112: + return 'UTM zone 12S'; + case 16113: + return 'UTM zone 13S'; + case 16114: + return 'UTM zone 14S'; + case 16115: + return 'UTM zone 15S'; + case 16116: + return 'UTM zone 16S'; + case 16117: + return 'UTM zone 17S'; + case 16118: + return 'UTM zone 18S'; + case 16119: + return 'UTM zone 19S'; + case 16120: + return 'UTM zone 20S'; + case 16121: + return 'UTM zone 21S'; + case 16122: + return 'UTM zone 22S'; + case 16123: + return 'UTM zone 23S'; + case 16124: + return 'UTM zone 24S'; + case 16125: + return 'UTM zone 25S'; + case 16126: + return 'UTM zone 26S'; + case 16127: + return 'UTM zone 27S'; + case 16128: + return 'UTM zone 28S'; + case 16129: + return 'UTM zone 29S'; + case 16130: + return 'UTM zone 30S'; + case 16131: + return 'UTM zone 31S'; + case 16132: + return 'UTM zone 32S'; + case 16133: + return 'UTM zone 33S'; + case 16134: + return 'UTM zone 34S'; + case 16135: + return 'UTM zone 35S'; + case 16136: + return 'UTM zone 36S'; + case 16137: + return 'UTM zone 37S'; + case 16138: + return 'UTM zone 38S'; + case 16139: + return 'UTM zone 39S'; + case 16140: + return 'UTM zone 40S'; + case 16141: + return 'UTM zone 41S'; + case 16142: + return 'UTM zone 42S'; + case 16143: + return 'UTM zone 43S'; + case 16144: + return 'UTM zone 44S'; + case 16145: + return 'UTM zone 45S'; + case 16146: + return 'UTM zone 46S'; + case 16147: + return 'UTM zone 47S'; + case 16148: + return 'UTM zone 48S'; + case 16149: + return 'UTM zone 49S'; + case 16150: + return 'UTM zone 50S'; + case 16151: + return 'UTM zone 51S'; + case 16152: + return 'UTM zone 52S'; + case 16153: + return 'UTM zone 53S'; + case 16154: + return 'UTM zone 54S'; + case 16155: + return 'UTM zone 55S'; + case 16156: + return 'UTM zone 56S'; + case 16157: + return 'UTM zone 57S'; + case 16158: + return 'UTM zone 58S'; + case 16159: + return 'UTM zone 59S'; + case 16160: + return 'UTM zone 60S'; + case 16200: + return 'Gauss Kruger zone 0'; + case 16201: + return 'Gauss Kruger zone 1'; + case 16202: + return 'Gauss Kruger zone 2'; + case 16203: + return 'Gauss Kruger zone 3'; + case 16204: + return 'Gauss Kruger zone 4'; + case 16205: + return 'Gauss Kruger zone 5'; + case 17348: + return 'Map Grid of Australia 48'; + case 17349: + return 'Map Grid of Australia 49'; + case 17350: + return 'Map Grid of Australia 50'; + case 17351: + return 'Map Grid of Australia 51'; + case 17352: + return 'Map Grid of Australia 52'; + case 17353: + return 'Map Grid of Australia 53'; + case 17354: + return 'Map Grid of Australia 54'; + case 17355: + return 'Map Grid of Australia 55'; + case 17356: + return 'Map Grid of Australia 56'; + case 17357: + return 'Map Grid of Australia 57'; + case 17358: + return 'Map Grid of Australia 58'; + case 17448: + return 'Australian Map Grid 48'; + case 17449: + return 'Australian Map Grid 49'; + case 17450: + return 'Australian Map Grid 50'; + case 17451: + return 'Australian Map Grid 51'; + case 17452: + return 'Australian Map Grid 52'; + case 17453: + return 'Australian Map Grid 53'; + case 17454: + return 'Australian Map Grid 54'; + case 17455: + return 'Australian Map Grid 55'; + case 17456: + return 'Australian Map Grid 56'; + case 17457: + return 'Australian Map Grid 57'; + case 17458: + return 'Australian Map Grid 58'; + case 18031: + return 'Argentina 1'; + case 18032: + return 'Argentina 2'; + case 18033: + return 'Argentina 3'; + case 18034: + return 'Argentina 4'; + case 18035: + return 'Argentina 5'; + case 18036: + return 'Argentina 6'; + case 18037: + return 'Argentina 7'; + case 18051: + return 'Colombia 3W'; + case 18052: + return 'Colombia Bogota'; + case 18053: + return 'Colombia 3E'; + case 18054: + return 'Colombia 6E'; + case 18072: + return 'Egypt Red Belt'; + case 18073: + return 'Egypt Purple Belt'; + case 18074: + return 'Extended Purple Belt'; + case 18141: + return 'New Zealand North Island Nat Grid'; + case 18142: + return 'New Zealand South Island Nat Grid'; + case 19900: + return 'Bahrain Grid'; + case 19905: + return 'Netherlands E Indies Equatorial'; + case 19912: + return 'RSO Borneo'; + case 19926: + return 'Stereo 70'; + case 32767: + return 'User Defined'; + default: + return 'Unknown ($value)'; + } + } + + static String getProjCoordinateTransformDescription(String valueString) { + final value = int.tryParse(valueString); + if (value == null) return valueString; + switch (value) { + case 1: + return 'Transverse Mercator'; + case 2: + return 'Transverse Mercator Modified Alaska'; + case 3: + return 'Oblique Mercator'; + case 4: + return 'Oblique Mercator Laborde'; + case 5: + return 'Oblique Mercator Rosenmund'; + case 6: + return 'Oblique Mercator Spherical'; + case 7: + return 'Mercator'; + case 8: + return 'Lambert Conf Conic 2SP'; + case 9: + return 'Lambert Conf Conic 1SP'; + case 10: + return 'Lambert Azim Equal Area'; + case 11: + return 'Albers Equal Area'; + case 12: + return 'Azimuthal Equidistant'; + case 13: + return 'Equidistant Conic'; + case 14: + return 'Stereographic'; + case 15: + return 'Polar Stereographic'; + case 16: + return 'Oblique Stereographic'; + case 17: + return 'Equirectangular'; + case 18: + return 'Cassini Soldner'; + case 19: + return 'Gnomonic'; + case 20: + return 'Miller Cylindrical'; + case 21: + return 'Orthographic'; + case 22: + return 'Polyconic'; + case 23: + return 'Robinson'; + case 24: + return 'Sinusoidal'; + case 25: + return 'VanDerGrinten'; + case 26: + return 'New Zealand Map Grid'; + case 27: + return 'Transverse Mercator South Orientated'; + case 28: + return 'Cylindrical Equal Area'; + case 32767: + return 'User Defined'; + default: + return 'Unknown ($value)'; + } + } + + static String getGeoTiffUnitsDescription(String valueString) { + final value = int.tryParse(valueString); + if (value == null) return valueString; + switch (value) { + case 9001: + return 'Linear Meter'; + case 9002: + return 'Linear Foot'; + case 9003: + return 'Linear Foot US Survey'; + case 9004: + return 'Linear Foot Modified American'; + case 9005: + return 'Linear Foot Clarke'; + case 9006: + return 'Linear Foot Indian'; + case 9007: + return 'Linear Link'; + case 9008: + return 'Linear Link Benoit'; + case 9009: + return 'Linear Link Sears'; + case 9010: + return 'Linear Chain Benoit'; + case 9011: + return 'Linear Chain Sears'; + case 9012: + return 'Linear Yard Sears'; + case 9013: + return 'Linear Yard Indian'; + case 9014: + return 'Linear Fathom'; + case 9015: + return 'Linear Mile International Nautical'; + case 9101: + return 'Angular Radian'; + case 9102: + return 'Angular Degree'; + case 9103: + return 'Angular Arc Minute'; + case 9104: + return 'Angular Arc Second'; + case 9105: + return 'Angular Grad'; + case 9106: + return 'Angular Gon'; + case 9107: + return 'Angular DMS'; + case 9108: + return 'Angular DMS Hemisphere'; + case 32767: + return 'User Defined'; + default: + return 'Unknown ($value)'; + } + } +} diff --git a/lib/widgets/viewer/info/metadata/metadata_dir.dart b/lib/widgets/viewer/info/metadata/metadata_dir.dart new file mode 100644 index 0000000..af71770 --- /dev/null +++ b/lib/widgets/viewer/info/metadata/metadata_dir.dart @@ -0,0 +1,41 @@ +import 'dart:collection'; + +import 'package:flutter/material.dart'; + +class MetadataDirectory { + final String name; + final Color? color; + final String? parent; + final int? index; + final SplayTreeMap<String, String> allTags; + final SplayTreeMap<String, String> tags; + + // special directory names + static const exifThumbnailDirectory = 'Exif Thumbnail'; // from metadata-extractor + static const xmpDirectory = 'XMP'; // from metadata-extractor + static const coverDirectory = 'Cover'; // custom + static const geoTiffDirectory = 'GeoTIFF'; // custom + static const mediaDirectory = 'Media'; // custom + static const mpfImageDirectoryPrefix = 'MPF Image #'; // custom + + const MetadataDirectory( + this.name, + this.allTags, { + SplayTreeMap<String, String>? tags, + this.color, + this.parent, + this.index, + }) : tags = tags ?? allTags; + + MetadataDirectory filterKeys(bool Function(String key) testKey) { + final filteredTags = SplayTreeMap.of(Map.fromEntries(allTags.entries.where((kv) => testKey(kv.key)))); + return MetadataDirectory( + name, + tags, + tags: filteredTags, + color: color, + parent: parent, + index: index, + ); + } +} diff --git a/lib/widgets/viewer/info/metadata/metadata_dir_tile.dart b/lib/widgets/viewer/info/metadata/metadata_dir_tile.dart new file mode 100644 index 0000000..28b0d52 --- /dev/null +++ b/lib/widgets/viewer/info/metadata/metadata_dir_tile.dart @@ -0,0 +1,168 @@ +import 'dart:collection'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/ref/brand_colors.dart'; +import 'package:aves/services/metadata/svg_metadata_service.dart'; +import 'package:aves/theme/colors.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/aves_expansion_tile.dart'; +import 'package:aves/widgets/common/identity/buttons/outlined_button.dart'; +import 'package:aves/widgets/viewer/info/common.dart'; +import 'package:aves/widgets/viewer/info/embedded/notifications.dart'; +import 'package:aves/widgets/viewer/info/metadata/geotiff.dart'; +import 'package:aves/widgets/viewer/info/metadata/metadata_dir.dart'; +import 'package:aves/widgets/viewer/info/metadata/metadata_thumbnail.dart'; +import 'package:aves/widgets/viewer/info/metadata/xmp_tile.dart'; +import 'package:aves/widgets/viewer/source_viewer_page.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class MetadataDirTile extends StatelessWidget { + final AvesEntry entry; + final String title; + final MetadataDirectory dir; + final ValueNotifier<String?>? expandedDirectoryNotifier; + final bool initiallyExpanded, showThumbnails; + + const MetadataDirTile({ + super.key, + required this.entry, + required this.title, + required this.dir, + this.expandedDirectoryNotifier, + this.initiallyExpanded = false, + this.showThumbnails = true, + }); + + @override + Widget build(BuildContext context) { + var tags = dir.tags; + if (tags.isEmpty) return const SizedBox(); + + return AvesExpansionTile( + title: title, + highlightColor: getTitleColor(context, dir), + expandedNotifier: expandedDirectoryNotifier, + initiallyExpanded: initiallyExpanded, + children: [ + MetadataDirTileBody( + entry: entry, + dir: dir, + showThumbnails: showThumbnails, + ), + ], + ); + } + + static Color getTitleColor(BuildContext context, MetadataDirectory dir) { + final dirName = dir.name; + if (dirName == MetadataDirectory.xmpDirectory) { + return context.select<AvesColorsData, Color>((v) => v.xmp); + } else { + final colors = context.watch<AvesColorsData>(); + return dir.color ?? colors.fromBrandColor(BrandColors.get(dirName)) ?? colors.fromString(dirName); + } + } +} + +class MetadataDirTileBody extends StatelessWidget { + final AvesEntry entry; + final MetadataDirectory dir; + final bool showThumbnails; + + const MetadataDirTileBody({ + super.key, + required this.entry, + required this.dir, + this.showThumbnails = true, + }); + + @override + Widget build(BuildContext context) { + var tags = dir.tags; + + late final List<Widget> children; + final dirName = dir.name; + if (dirName == MetadataDirectory.xmpDirectory) { + children = [ + Padding( + padding: const EdgeInsets.only(left: 8, right: 8, bottom: 8), + child: XmpDirTileBody( + allTags: dir.allTags, + tags: tags, + ), + ), + ]; + } else { + Map<String, InfoValueSpanBuilder>? linkHandlers; + switch (dirName) { + case SvgMetadataService.metadataDirectory: + linkHandlers = getSvgLinkHandlers(tags); + case MetadataDirectory.coverDirectory: + linkHandlers = getVideoCoverLinkHandlers(tags); + case MetadataDirectory.geoTiffDirectory: + tags = SplayTreeMap.from(tags.map((name, value) { + final tag = GeoTiffDirectory.tagForName(name); + return MapEntry(name, GeoTiffDirectory.formatValue(tag, value)); + })); + } + + children = [ + if (showThumbnails && dirName == MetadataDirectory.exifThumbnailDirectory) MetadataThumbnails(entry: entry), + if (dirName.startsWith(MetadataDirectory.mpfImageDirectoryPrefix)) + Padding( + padding: const EdgeInsets.symmetric(horizontal: 8), + child: AvesOutlinedButton( + label: context.l10n.viewerInfoOpenLinkText, + onPressed: () { + final id = int.tryParse(dirName.substring(MetadataDirectory.mpfImageDirectoryPrefix.length)); + if (id != null) { + OpenEmbeddedDataNotification.mpf(id).dispatch(context); + } + }, + ), + ), + Padding( + padding: const EdgeInsets.only(left: 8, right: 8, bottom: 8), + child: InfoRowGroup( + info: tags, + spanBuilders: linkHandlers, + ), + ), + ]; + } + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: children, + ); + } + + static Map<String, InfoValueSpanBuilder> getSvgLinkHandlers(SplayTreeMap<String, String> tags) { + return { + 'Metadata': InfoRowGroup.linkSpanBuilder( + linkText: (context) => context.l10n.viewerInfoViewXmlLinkText, + onTap: (context) { + Navigator.maybeOf(context)?.push( + MaterialPageRoute( + settings: const RouteSettings(name: SourceViewerPage.routeName), + builder: (context) => SourceViewerPage( + loader: () => SynchronousFuture(tags['Metadata'] ?? ''), + ), + ), + ); + }, + ), + }; + } + + static Map<String, InfoValueSpanBuilder> getVideoCoverLinkHandlers(SplayTreeMap<String, String> tags) { + return { + 'Image': InfoRowGroup.linkSpanBuilder( + linkText: (context) => context.l10n.viewerInfoOpenLinkText, + onTap: (context) => OpenEmbeddedDataNotification.videoCover().dispatch(context), + ), + }; + } +} diff --git a/lib/widgets/viewer/info/metadata/metadata_section.dart b/lib/widgets/viewer/info/metadata/metadata_section.dart new file mode 100644 index 0000000..00f24d5 --- /dev/null +++ b/lib/widgets/viewer/info/metadata/metadata_section.dart @@ -0,0 +1,152 @@ +import 'dart:async'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/info.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/identity/buttons/outlined_button.dart'; +import 'package:aves/widgets/viewer/info/common.dart'; +import 'package:aves/widgets/viewer/info/metadata/metadata_dir.dart'; +import 'package:aves/widgets/viewer/info/metadata/metadata_dir_tile.dart'; +import 'package:aves/widgets/viewer/info/metadata/tv_page.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:flutter_staggered_animations/flutter_staggered_animations.dart'; +import 'package:provider/provider.dart'; + +class MetadataSectionSliver extends StatefulWidget { + final AvesEntry entry; + final ValueNotifier<Map<String, MetadataDirectory>> metadataNotifier; + + const MetadataSectionSliver({ + super.key, + required this.entry, + required this.metadataNotifier, + }); + + @override + State<StatefulWidget> createState() => _MetadataSectionSliverState(); +} + +class _MetadataSectionSliverState extends State<MetadataSectionSliver> { + final ValueNotifier<String?> _expandedDirectoryNotifier = ValueNotifier(null); + + AvesEntry get entry => widget.entry; + + ValueNotifier<Map<String, MetadataDirectory>> get metadataNotifier => widget.metadataNotifier; + + @override + void initState() { + super.initState(); + _registerWidget(widget); + metadataNotifier.value = {}; + _getMetadata(); + } + + @override + void didUpdateWidget(covariant MetadataSectionSliver oldWidget) { + super.didUpdateWidget(oldWidget); + _unregisterWidget(oldWidget); + _registerWidget(widget); + _getMetadata(); + } + + @override + void dispose() { + _unregisterWidget(widget); + _expandedDirectoryNotifier.dispose(); + super.dispose(); + } + + void _registerWidget(MetadataSectionSliver widget) { + widget.entry.metadataChangeNotifier.addListener(_onMetadataChanged); + } + + void _unregisterWidget(MetadataSectionSliver widget) { + widget.entry.metadataChangeNotifier.removeListener(_onMetadataChanged); + } + + @override + Widget build(BuildContext context) { + // use a `Column` inside a `SliverToBoxAdapter`, instead of a `SliverList`, + // so that we can have the metadata-dependent `AnimationLimiter` inside the metadata section + // warning: placing the `AnimationLimiter` as a parent to the `ScrollView` + // triggers dispose & reinitialization of other sections, including heavy widgets like maps + return SliverToBoxAdapter( + child: NotificationListener<ScrollNotification>( + // cancel notification bubbling so that the info page + // does not misinterpret content scrolling for page scrolling + onNotification: (notification) => true, + child: ValueListenableBuilder<Map<String, MetadataDirectory>>( + valueListenable: metadataNotifier, + builder: (context, metadata, child) { + Widget content; + if (metadata.isEmpty) { + content = const SizedBox(); + } else { + final durations = context.watch<DurationsData>(); + content = Column( + children: AnimationConfiguration.toStaggeredList( + duration: durations.staggeredAnimation, + delay: durations.staggeredAnimationDelay * timeDilation, + childAnimationBuilder: (child) => SlideAnimation( + verticalOffset: 50.0, + child: FadeInAnimation( + child: child, + ), + ), + children: settings.useTvLayout + ? [ + const SizedBox(height: 16), + AvesOutlinedButton( + label: MaterialLocalizations.of(context).moreButtonTooltip, + onPressed: () { + Navigator.maybeOf(context)?.push( + MaterialPageRoute( + settings: const RouteSettings(name: TvMetadataPage.routeName), + builder: (context) => TvMetadataPage( + entry: entry, + metadata: metadata, + ), + ), + ); + }, + ), + ] + : [ + const SectionRow(icon: AIcons.info), + ...metadata.entries.map((kv) => MetadataDirTile( + entry: entry, + title: kv.key, + dir: kv.value, + expandedDirectoryNotifier: _expandedDirectoryNotifier, + )), + ], + ), + ); + } + + return AnimationLimiter( + // we update the limiter key after fetching the metadata of a new entry, + // in order to restart the staggered animation of the metadata section + key: ValueKey(metadata.length), + child: content, + ); + }), + ), + ); + } + + void _onMetadataChanged() { + metadataNotifier.value = {}; + _getMetadata(); + } + + Future<void> _getMetadata() async { + final titledDirectories = await entry.getMetadataDirectories(context); + if (!mounted) return; + metadataNotifier.value = Map.fromEntries(titledDirectories); + _expandedDirectoryNotifier.value = null; + } +} diff --git a/lib/widgets/viewer/info/metadata/metadata_thumbnail.dart b/lib/widgets/viewer/info/metadata/metadata_thumbnail.dart new file mode 100644 index 0000000..5eac1f1 --- /dev/null +++ b/lib/widgets/viewer/info/metadata/metadata_thumbnail.dart @@ -0,0 +1,59 @@ +import 'dart:async'; +import 'dart:ui' as ui; + +import 'package:aves/image_providers/descriptor_provider.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:flutter/material.dart'; + +class MetadataThumbnails extends StatefulWidget { + final AvesEntry entry; + + const MetadataThumbnails({ + super.key, + required this.entry, + }); + + @override + State<MetadataThumbnails> createState() => _MetadataThumbnailsState(); +} + +class _MetadataThumbnailsState extends State<MetadataThumbnails> { + late Future<List<ui.ImageDescriptor?>> _loader; + + AvesEntry get entry => widget.entry; + + String get uri => entry.uri; + + @override + void initState() { + super.initState(); + _loader = embeddedDataService.getExifThumbnails(entry); + } + + @override + Widget build(BuildContext context) { + return FutureBuilder<List<ui.ImageDescriptor?>>( + future: _loader, + builder: (context, snapshot) { + if (!snapshot.hasError && snapshot.connectionState == ConnectionState.done && snapshot.data!.isNotEmpty) { + return Container( + alignment: AlignmentDirectional.topStart, + padding: const EdgeInsets.only(left: 8, top: 8, right: 8, bottom: 4), + child: Wrap( + children: snapshot.data!.map((descriptor) { + if (descriptor == null) return const SizedBox(); + return Image( + image: DescriptorImageProvider( + descriptor, + scale: MediaQuery.devicePixelRatioOf(context), + ), + ); + }).toList(), + ), + ); + } + return const SizedBox(); + }); + } +} diff --git a/lib/widgets/viewer/info/metadata/tv_page.dart b/lib/widgets/viewer/info/metadata/tv_page.dart new file mode 100644 index 0000000..0cfbae5 --- /dev/null +++ b/lib/widgets/viewer/info/metadata/tv_page.dart @@ -0,0 +1,122 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/behaviour/intents.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/navigation/tv_rail.dart'; +import 'package:aves/widgets/viewer/info/metadata/metadata_dir.dart'; +import 'package:aves/widgets/viewer/info/metadata/metadata_dir_tile.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +class TvMetadataPage extends StatefulWidget { + static const routeName = '/info/metadata'; + + final AvesEntry entry; + final Map<String, MetadataDirectory> metadata; + + const TvMetadataPage({ + super.key, + required this.entry, + required this.metadata, + }); + + @override + State<TvMetadataPage> createState() => _TvMetadataPageState(); +} + +class _TvMetadataPageState extends State<TvMetadataPage> { + final ValueNotifier<int> _railIndexNotifier = ValueNotifier(0); + final FocusNode _railFocusNode = FocusNode(); + final ScrollController _detailsScrollController = ScrollController(); + + Map<String, MetadataDirectory> get metadata => widget.metadata; + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addPostFrameCallback((_) { + _railFocusNode.children.firstOrNull?.requestFocus(); + }); + } + + @override + void dispose() { + _railIndexNotifier.dispose(); + _railFocusNode.dispose(); + _detailsScrollController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return AvesScaffold( + appBar: AppBar( + automaticallyImplyLeading: false, + title: Text(context.l10n.viewerInfoPageTitle), + ), + body: ValueListenableBuilder<int>( + valueListenable: _railIndexNotifier, + builder: (context, selectedIndex, child) { + final titles = metadata.keys.toList(); + final selectedDir = metadata[titles[selectedIndex]]; + if (selectedDir == null) return const SizedBox(); + + final rail = NavigationRail( + extended: true, + destinations: titles.mapIndexed((i, title) { + final dir = metadata[titles[i]]!; + final color = MetadataDirTile.getTitleColor(context, dir); + return NavigationRailDestination( + icon: Icon(AIcons.circle, fill: 1, color: color), + label: Text(title), + ); + }).toList(), + selectedIndex: selectedIndex, + onDestinationSelected: (index) => _railIndexNotifier.value = index, + minExtendedWidth: TvRail.minExtendedWidth, + ); + + return SafeArea( + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const SizedBox(width: 16), + Focus( + focusNode: _railFocusNode, + skipTraversal: true, + canRequestFocus: false, + child: SingleChildScrollView( + child: IntrinsicHeight( + child: rail, + ), + ), + ), + Expanded( + child: FocusableActionDetector( + shortcuts: const { + SingleActivator(LogicalKeyboardKey.arrowUp): ScrollIntent(direction: AxisDirection.up, type: ScrollIncrementType.page), + SingleActivator(LogicalKeyboardKey.arrowDown): ScrollIntent(direction: AxisDirection.down, type: ScrollIncrementType.page), + }, + actions: { + ScrollIntent: ScrollControllerAction(scrollController: _detailsScrollController), + }, + child: SingleChildScrollView( + controller: _detailsScrollController, + padding: const EdgeInsets.all(16), + child: MetadataDirTileBody( + entry: widget.entry, + dir: selectedDir, + ), + ), + ), + ), + ], + ), + ); + }, + ), + ); + } +} diff --git a/lib/widgets/viewer/info/metadata/xmp_card.dart b/lib/widgets/viewer/info/metadata/xmp_card.dart new file mode 100644 index 0000000..ba46bb1 --- /dev/null +++ b/lib/widgets/viewer/info/metadata/xmp_card.dart @@ -0,0 +1,158 @@ +import 'dart:math'; + +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/basic/multi_cross_fader.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/highlight_title.dart'; +import 'package:aves/widgets/viewer/info/common.dart'; +import 'package:aves/widgets/viewer/info/metadata/xmp_namespaces.dart'; +import 'package:flutter/material.dart'; + +typedef XmpExtractedCard = (Map<String, XmpProp>, List<XmpCardData>?); + +class XmpCard extends StatefulWidget { + final String title; + late final XmpExtractedCard? directStruct; + late final List<XmpExtractedCard>? indexedStructs; + final String Function(XmpProp prop) formatValue; + final Map<String, InfoValueSpanBuilder> Function(int? index)? spanBuilders; + + XmpCard({ + super.key, + required this.title, + required Map<int?, XmpExtractedCard> structByIndex, + required this.formatValue, + this.spanBuilders, + }) { + directStruct = structByIndex[null]; + + final length = structByIndex.keys.nonNulls.fold(0, max); + indexedStructs = length > 0 ? [for (var i = 0; i < length; i++) structByIndex[i + 1] ?? const ({}, null)] : null; + } + + @override + State<XmpCard> createState() => _XmpCardState(); +} + +class _XmpCardState extends State<XmpCard> { + final ValueNotifier<int> _indexNotifier = ValueNotifier(0); + + List<XmpExtractedCard>? get indexedStructs => widget.indexedStructs; + + bool get isIndexed => indexedStructs != null; + + int get indexedStructCount => indexedStructs?.length ?? 0; + + @override + void initState() { + super.initState(); + if (isIndexed) { + _indexNotifier.value = indexedStructCount - 1; + } + } + + @override + void didUpdateWidget(covariant XmpCard oldWidget) { + super.didUpdateWidget(oldWidget); + if (isIndexed && _indexNotifier.value >= indexedStructCount) { + _indexNotifier.value = indexedStructCount - 1; + } + } + + @override + void dispose() { + _indexNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final _isIndexed = isIndexed; + + return Container( + decoration: BoxDecoration( + border: Border.all( + color: Theme.of(context).dividerColor, + ), + borderRadius: const BorderRadius.all(Radius.circular(4)), + ), + child: ValueListenableBuilder<int>( + valueListenable: _indexNotifier, + builder: (context, index, child) { + final data = _isIndexed ? indexedStructs![index] : widget.directStruct!; + final props = data.$1.entries.map((kv) => XmpProp(kv.key, kv.value.value)).toList()..sort(); + final cards = data.$2; + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.only(left: 8, top: 8, right: 8), + child: Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Expanded( + child: HighlightTitle( + title: widget.title, + showHighlight: false, + ), + ), + if (_isIndexed) ...[ + IconButton( + visualDensity: VisualDensity.compact, + icon: const Icon(AIcons.previous), + onPressed: index > 0 ? () => _setIndex(index - 1) : null, + tooltip: context.l10n.previousTooltip, + ), + HighlightTitle( + title: '${index + 1}', + showHighlight: false, + ), + IconButton( + visualDensity: VisualDensity.compact, + icon: const Icon(AIcons.next), + onPressed: index < indexedStructCount - 1 ? () => _setIndex(index + 1) : null, + tooltip: context.l10n.nextTooltip, + ), + ] + ], + ), + ), + MultiCrossFader( + duration: ADurations.xmpStructArrayCardTransition, + sizeCurve: Curves.easeOutBack, + alignment: AlignmentDirectional.topStart, + child: Padding( + // add padding at this level (instead of the column level) + // so that the crossfader can animate the content size + // without clipping the text + padding: const EdgeInsets.only(left: 8, right: 8, bottom: 8), + child: InfoRowGroup( + info: Map.fromEntries(props.map((prop) => MapEntry(prop.displayKey, widget.formatValue(prop)))), + spanBuilders: widget.spanBuilders?.call(_isIndexed ? index + 1 : null), + ), + ), + ), + if (cards != null) + ...cards.where((v) => !v.isEmpty).map((card) { + final spanBuilders = card.spanBuilders; + return Padding( + padding: const EdgeInsets.symmetric(vertical: 4, horizontal: 8), + child: XmpCard( + title: card.title, + structByIndex: card.data, + formatValue: widget.formatValue, + spanBuilders: spanBuilders != null ? (index) => spanBuilders(index, card.data[index]!.$1) : null, + ), + ); + }), + ], + ); + }, + ), + ); + } + + void _setIndex(int index) => _indexNotifier.value = index.clamp(0, indexedStructCount - 1); +} diff --git a/lib/widgets/viewer/info/metadata/xmp_namespaces.dart b/lib/widgets/viewer/info/metadata/xmp_namespaces.dart new file mode 100644 index 0000000..f16f266 --- /dev/null +++ b/lib/widgets/viewer/info/metadata/xmp_namespaces.dart @@ -0,0 +1,247 @@ +import 'package:aves/ref/brand_colors.dart'; +import 'package:aves/ref/metadata/xmp.dart'; +import 'package:aves/theme/colors.dart'; +import 'package:aves/utils/string_utils.dart'; +import 'package:aves/utils/xmp_utils.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/identity/highlight_title.dart'; +import 'package:aves/widgets/viewer/info/common.dart'; +import 'package:aves/widgets/viewer/info/metadata/xmp_card.dart'; +import 'package:aves/widgets/viewer/info/metadata/xmp_ns/crs.dart'; +import 'package:aves/widgets/viewer/info/metadata/xmp_ns/exif.dart'; +import 'package:aves/widgets/viewer/info/metadata/xmp_ns/google.dart'; +import 'package:aves/widgets/viewer/info/metadata/xmp_ns/misc.dart'; +import 'package:aves/widgets/viewer/info/metadata/xmp_ns/photoshop.dart'; +import 'package:aves/widgets/viewer/info/metadata/xmp_ns/tiff.dart'; +import 'package:aves/widgets/viewer/info/metadata/xmp_ns/xmp.dart'; +import 'package:collection/collection.dart'; +import 'package:equatable/equatable.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +@immutable +class XmpNamespace extends Equatable { + final Map<String, String> schemaRegistryPrefixes; + final String nsUri, nsPrefix; + final Map<String, String> rawProps; + + @override + List<Object?> get props => [nsUri, nsPrefix]; + + XmpNamespace({ + required this.nsUri, + required this.schemaRegistryPrefixes, + required this.rawProps, + }) : nsPrefix = prefixForUri(schemaRegistryPrefixes, nsUri); + + factory XmpNamespace.create(Map<String, String> schemaRegistryPrefixes, String nsPrefix, Map<String, String> rawProps) { + final nsUri = schemaRegistryPrefixes[nsPrefix] ?? ''; + switch (nsUri) { + case XmpNamespaces.creatorAtom: + return XmpCreatorAtom(schemaRegistryPrefixes: schemaRegistryPrefixes, rawProps: rawProps); + case XmpNamespaces.crs: + return XmpCrsNamespace(schemaRegistryPrefixes: schemaRegistryPrefixes, rawProps: rawProps); + case XmpNamespaces.darktable: + return XmpDarktableNamespace(schemaRegistryPrefixes: schemaRegistryPrefixes, rawProps: rawProps); + case XmpNamespaces.dwc: + return XmpDwcNamespace(schemaRegistryPrefixes: schemaRegistryPrefixes, rawProps: rawProps); + case XmpNamespaces.exif: + return XmpExifNamespace(schemaRegistryPrefixes: schemaRegistryPrefixes, rawProps: rawProps); + case XmpNamespaces.gAudio: + return XmpGAudioNamespace(schemaRegistryPrefixes: schemaRegistryPrefixes, rawProps: rawProps); + case XmpNamespaces.gCamera: + return XmpGCameraNamespace(schemaRegistryPrefixes: schemaRegistryPrefixes, rawProps: rawProps); + case XmpNamespaces.gContainer: + return XmpGContainer(schemaRegistryPrefixes: schemaRegistryPrefixes, rawProps: rawProps); + case XmpNamespaces.gDepth: + return XmpGDepthNamespace(schemaRegistryPrefixes: schemaRegistryPrefixes, rawProps: rawProps); + case XmpNamespaces.gDevice: + return XmpGDeviceNamespace(schemaRegistryPrefixes: schemaRegistryPrefixes, rawProps: rawProps); + case XmpNamespaces.gImage: + return XmpGImageNamespace(schemaRegistryPrefixes: schemaRegistryPrefixes, rawProps: rawProps); + case XmpNamespaces.iptc4xmpCore: + return XmpIptcCoreNamespace(schemaRegistryPrefixes: schemaRegistryPrefixes, rawProps: rawProps); + case XmpNamespaces.iptc4xmpExt: + return XmpIptc4xmpExtNamespace(schemaRegistryPrefixes: schemaRegistryPrefixes, rawProps: rawProps); + case XmpNamespaces.mwgrs: + return XmpMgwRegionsNamespace(schemaRegistryPrefixes: schemaRegistryPrefixes, rawProps: rawProps); + case XmpNamespaces.mp: + return XmpMPNamespace(schemaRegistryPrefixes: schemaRegistryPrefixes, rawProps: rawProps); + case XmpNamespaces.photoshop: + return XmpPhotoshopNamespace(schemaRegistryPrefixes: schemaRegistryPrefixes, rawProps: rawProps); + case XmpNamespaces.plus: + return XmpPlusNamespace(schemaRegistryPrefixes: schemaRegistryPrefixes, rawProps: rawProps); + case XmpNamespaces.tiff: + return XmpTiffNamespace(schemaRegistryPrefixes: schemaRegistryPrefixes, rawProps: rawProps); + case XmpNamespaces.xmp: + return XmpBasicNamespace(schemaRegistryPrefixes: schemaRegistryPrefixes, rawProps: rawProps); + case XmpNamespaces.xmpMM: + return XmpMMNamespace(schemaRegistryPrefixes: schemaRegistryPrefixes, rawProps: rawProps); + case XmpNamespaces.xperiaCamera: + return XmpXperiaCameraNamespace(schemaRegistryPrefixes: schemaRegistryPrefixes, rawProps: rawProps); + default: + return XmpNamespace(nsUri: nsUri, schemaRegistryPrefixes: schemaRegistryPrefixes, rawProps: rawProps); + } + } + + String get displayTitle => XmpNamespaceView.nsTitles[nsUri] ?? (nsPrefix.isEmpty ? nsUri : '${nsPrefix.substring(0, nsPrefix.length - 1)} ($nsUri)'); + + List<Widget> buildNamespaceSection(BuildContext context) { + final props = rawProps.entries + .map((kv) { + final key = kv.key; + if (skippedProps.any((pattern) => pattern.allMatches(key).isNotEmpty)) { + return null; + } + final prop = XmpProp(key, kv.value); + var extracted = false; + cards.forEach((card) => extracted |= card.extract(prop)); + return extracted ? null : prop; + }) + .nonNulls + .toList() + ..sort(); + + final content = [ + if (props.isNotEmpty) + InfoRowGroup( + info: Map.fromEntries(props.map((v) => MapEntry(v.displayKey, formatValue(v)))), + spanBuilders: linkifyValues(props), + ), + ...cards.where((v) => !v.isEmpty).map((card) { + final spanBuilders = card.spanBuilders; + return Padding( + padding: const EdgeInsets.only(top: 8), + child: XmpCard( + title: card.title, + structByIndex: card.data, + formatValue: formatValue, + spanBuilders: spanBuilders != null ? (index) => spanBuilders(index, card.data[index]!.$1) : null, + ), + ); + }), + ]; + + return content.isNotEmpty + ? [ + if (displayTitle.isNotEmpty) + Padding( + padding: const EdgeInsets.only(top: 8, bottom: 4), + child: HighlightTitle( + title: displayTitle, + color: context.select<AvesColorsData, Color?>((v) => v.fromBrandColor(BrandColors.get(displayTitle))), + ), + ), + ...content + ] + : []; + } + + Set<RegExp> get skippedProps => {}; + + List<XmpCardData> get cards => []; + + String formatValue(XmpProp prop) => prop.value; + + Map<String, InfoValueSpanBuilder> linkifyValues(List<XmpProp> props) => {}; + + static String prefixForUri(Map<String, String> schemaRegistryPrefixes, String nsUri) => schemaRegistryPrefixes.entries.firstWhereOrNull((kv) => kv.value == nsUri)?.key ?? ''; +} + +class XmpProp implements Comparable<XmpProp> { + final String path, value; + final String displayKey; + + XmpProp(this.path, this.value) : displayKey = formatKey(path); + + static String formatKey(String propPath) { + return propPath.splitMapJoin(XMP.structFieldSeparator, + onMatch: (match) => ' ${match.group(0)} ', + onNonMatch: (s) { + // strip namespace + final key = s.split(XMP.propNamespaceSeparator).last; + // format + return key.replaceAll('_', ' ').toSentenceCase(); + }); + } + + @override + int compareTo(XmpProp other) => compareAsciiUpperCaseNatural(displayKey, other.displayKey); + + @override + String toString() => '$runtimeType#${shortHash(this)}{path=$path, value=$value}'; +} + +class XmpCardData { + final String title; + final RegExp pattern; + final bool indexed; + final Map<String, InfoValueSpanBuilder> Function(int?, Map<String, XmpProp> data)? spanBuilders; + final List<XmpCardData>? cards; + final Map<int?, XmpExtractedCard> data = {}; + + bool get isEmpty => data.isEmpty && (cards?.every((card) => card.isEmpty) ?? true); + + static final titlePattern = RegExp(r'(.*?)[\\/]'); + + XmpCardData( + this.pattern, { + String? title, + this.spanBuilders, + this.cards, + }) : indexed = pattern.pattern.contains(r'\[(\d+)\]'), + title = title ?? XmpProp.formatKey(titlePattern.firstMatch(pattern.pattern)!.group(1)!); + + XmpCardData cloneEmpty() { + return XmpCardData( + pattern, + title: title, + spanBuilders: spanBuilders, + cards: cards?.map((v) => v.cloneEmpty()).toList(), + ); + } + + bool extract(XmpProp prop) => indexed ? _extractIndexedStruct(prop) : _extractDirectStruct(prop); + + bool _extractDirectStruct(XmpProp prop) { + final matches = pattern.allMatches(prop.path); + if (matches.isEmpty) return false; + + final match = matches.first; + final field = match.group(1)!; + + final fields = data.putIfAbsent(null, () => (<String, XmpProp>{}, cards?.map((v) => v.cloneEmpty()).toList())); + final _cards = fields.$2; + if (_cards != null) { + final fieldProp = XmpProp(field, prop.value); + if (_cards.any((v) => v.extract(fieldProp))) { + return true; + } + } + + fields.$1[field] = prop; + return true; + } + + bool _extractIndexedStruct(XmpProp prop) { + final matches = pattern.allMatches(prop.path); + if (matches.isEmpty) return false; + + final match = matches.first; + final index = int.parse(match.group(1)!); + final field = match.group(2)!; + + final fields = data.putIfAbsent(index, () => (<String, XmpProp>{}, cards?.map((v) => v.cloneEmpty()).toList())); + final _cards = fields.$2; + if (_cards != null) { + final fieldProp = XmpProp(field, prop.value); + if (_cards.any((v) => v.extract(fieldProp))) { + return true; + } + } + + fields.$1[field] = prop; + return true; + } +} diff --git a/lib/widgets/viewer/info/metadata/xmp_ns/crs.dart b/lib/widgets/viewer/info/metadata/xmp_ns/crs.dart new file mode 100644 index 0000000..15e987d --- /dev/null +++ b/lib/widgets/viewer/info/metadata/xmp_ns/crs.dart @@ -0,0 +1,50 @@ +import 'package:aves/ref/metadata/xmp.dart'; +import 'package:aves/widgets/viewer/info/metadata/xmp_namespaces.dart'; + +class XmpCrsNamespace extends XmpNamespace { + XmpCrsNamespace({required super.schemaRegistryPrefixes, required super.rawProps}) : super(nsUri: XmpNamespaces.crs); + + @override + late final List<XmpCardData> cards = [ + XmpCardData(RegExp(nsPrefix + r'CircularGradientBasedCorrections\[(\d+)\]/(.*)')), + XmpCardData( + RegExp(nsPrefix + r'GradientBasedCorrections\[(\d+)\]/(.*)'), + cards: [ + XmpCardData(RegExp(nsPrefix + r'CorrectionMasks\[(\d+)\]/(.*)')), + XmpCardData(RegExp(nsPrefix + r'CorrectionRangeMask/(.*)')), + ], + ), + XmpCardData( + RegExp(nsPrefix + r'Look/(.*)'), + cards: [ + XmpCardData(RegExp(nsPrefix + r'Parameters/(.*)')), + ], + ), + XmpCardData( + RegExp(nsPrefix + r'MaskGroupBasedCorrections\[(\d+)\]/(.*)'), + cards: [ + XmpCardData( + RegExp(nsPrefix + r'CorrectionMasks\[(\d+)\]/(.*)'), + cards: [ + XmpCardData(RegExp(nsPrefix + r'CorrectionRangeMask/(.*)')), + XmpCardData(RegExp(nsPrefix + r'Masks\[(\d+)\]/(.*)')), + ], + ), + ], + ), + XmpCardData( + RegExp(nsPrefix + r'PaintBasedCorrections\[(\d+)\]/(.*)'), + cards: [ + XmpCardData(RegExp(nsPrefix + r'CorrectionMasks\[(\d+)\]/(.*)')), + XmpCardData(RegExp(nsPrefix + r'CorrectionRangeMask/(.*)')), + ], + ), + XmpCardData( + RegExp(nsPrefix + r'RetouchAreas\[(\d+)\]/(.*)'), + cards: [ + XmpCardData(RegExp(nsPrefix + r'Masks\[(\d+)\]/(.*)')), + ], + ), + XmpCardData(RegExp(nsPrefix + r'RangeMaskMapInfo/' + nsPrefix + r'RangeMaskMapInfo/(.*)')), + ]; +} diff --git a/lib/widgets/viewer/info/metadata/xmp_ns/exif.dart b/lib/widgets/viewer/info/metadata/xmp_ns/exif.dart new file mode 100644 index 0000000..bbbf677 --- /dev/null +++ b/lib/widgets/viewer/info/metadata/xmp_ns/exif.dart @@ -0,0 +1,75 @@ +import 'package:aves/ref/metadata/exif.dart'; +import 'package:aves/ref/metadata/xmp.dart'; +import 'package:aves/widgets/viewer/info/metadata/xmp_namespaces.dart'; + +// cf https://github.com/adobe/xmp-docs/blob/master/XMPNamespaces/exif.md +class XmpExifNamespace extends XmpNamespace { + XmpExifNamespace({required super.schemaRegistryPrefixes, required super.rawProps}) : super(nsUri: XmpNamespaces.exif); + + @override + String formatValue(XmpProp prop) { + final v = prop.value; + final field = prop.path.replaceAll(nsPrefix, ''); + switch (field) { + case 'ColorSpace': + return Exif.getColorSpaceDescription(v); + case 'Contrast': + return Exif.getContrastDescription(v); + case 'CustomRendered': + return Exif.getCustomRenderedDescription(v); + case 'ExifVersion': + case 'FlashpixVersion': + return Exif.getExifVersionDescription(v); + case 'ExposureMode': + return Exif.getExposureModeDescription(v); + case 'ExposureProgram': + return Exif.getExposureProgramDescription(v); + case 'FileSource': + return Exif.getFileSourceDescription(v); + case 'Flash/Mode': + return Exif.getFlashModeDescription(v); + case 'Flash/Return': + return Exif.getFlashReturnDescription(v); + case 'FocalPlaneResolutionUnit': + return Exif.getResolutionUnitDescription(v); + case 'GainControl': + return Exif.getGainControlDescription(v); + case 'LightSource': + return Exif.getLightSourceDescription(v); + case 'MeteringMode': + return Exif.getMeteringModeDescription(v); + case 'Saturation': + return Exif.getSaturationDescription(v); + case 'SceneCaptureType': + return Exif.getSceneCaptureTypeDescription(v); + case 'SceneType': + return Exif.getSceneTypeDescription(v); + case 'SensingMethod': + return Exif.getSensingMethodDescription(v); + case 'Sharpness': + return Exif.getSharpnessDescription(v); + case 'SubjectDistanceRange': + return Exif.getSubjectDistanceRangeDescription(v); + case 'WhiteBalance': + return Exif.getWhiteBalanceDescription(v); + case 'GPSAltitudeRef': + return Exif.getGPSAltitudeRefDescription(v); + case 'GPSDestBearingRef': + case 'GPSImgDirectionRef': + case 'GPSTrackRef': + return Exif.getGPSDirectionRefDescription(v); + case 'GPSDestDistanceRef': + return Exif.getGPSDestDistanceRefDescription(v); + case 'GPSDifferential': + return Exif.getGPSDifferentialDescription(v); + case 'GPSMeasureMode': + return Exif.getGPSMeasureModeDescription(v); + case 'GPSSpeedRef': + return Exif.getGPSSpeedRefDescription(v); + case 'GPSStatus': + return Exif.getGPSStatusDescription(v); + default: + return v; + } + } +} diff --git a/lib/widgets/viewer/info/metadata/xmp_ns/google.dart b/lib/widgets/viewer/info/metadata/xmp_ns/google.dart new file mode 100644 index 0000000..28e4f86 --- /dev/null +++ b/lib/widgets/viewer/info/metadata/xmp_ns/google.dart @@ -0,0 +1,175 @@ +import 'package:aves/ref/metadata/xmp.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/viewer/info/common.dart'; +import 'package:aves/widgets/viewer/info/embedded/notifications.dart'; +import 'package:aves/widgets/viewer/info/metadata/xmp_namespaces.dart'; +import 'package:collection/collection.dart'; + +abstract class XmpGoogleNamespace extends XmpNamespace { + XmpGoogleNamespace({ + required super.nsUri, + required super.schemaRegistryPrefixes, + required super.rawProps, + }); + + List<(String, String)> get dataProps; + + @override + Map<String, InfoValueSpanBuilder> linkifyValues(List<XmpProp> props) { + return Map.fromEntries(dataProps.map((t) { + final (dataPropPath, mimePropPath) = t; + final dataProp = props.firstWhereOrNull((prop) => prop.path == dataPropPath); + final mimeProp = props.firstWhereOrNull((prop) => prop.path == mimePropPath); + return (dataProp != null && mimeProp != null) + ? MapEntry( + dataProp.displayKey, + InfoRowGroup.linkSpanBuilder( + linkText: (context) => context.l10n.viewerInfoOpenLinkText, + onTap: (context) { + final pattern = RegExp(r'(.+):(.+)([(\d)])?'); + final props = dataProp.path.split('/').expand((part) { + var match = pattern.firstMatch(part); + if (match == null) return []; + + // ignore namespace prefix + final propName = match.group(2); + final prop = [nsUri, propName]; + + final indexString = match.groupCount >= 4 ? match.group(4) : null; + final index = indexString != null ? int.tryParse(indexString) : null; + if (index != null) { + return [prop, index]; + } else { + return [prop]; + } + }).toList(); + return OpenEmbeddedDataNotification.xmp( + props: props, + mimeType: mimeProp.value, + ).dispatch(context); + }, + )) + : null; + }).nonNulls); + } +} + +class XmpGAudioNamespace extends XmpGoogleNamespace { + XmpGAudioNamespace({required super.schemaRegistryPrefixes, required super.rawProps}) : super(nsUri: XmpNamespaces.gAudio); + + @override + List<(String, String)> get dataProps => [ + ('${nsPrefix}Data', '${nsPrefix}Mime'), + ]; +} + +class XmpGCameraNamespace extends XmpGoogleNamespace { + XmpGCameraNamespace({required super.schemaRegistryPrefixes, required super.rawProps}) : super(nsUri: XmpNamespaces.gCamera); + + @override + List<(String, String)> get dataProps => [ + ('${nsPrefix}RelitInputImageData', '${nsPrefix}RelitInputImageMime'), + ]; +} + +class XmpGContainer extends XmpNamespace { + late final String _gContainerItemNsPrefix; + late final String _rdfNsPrefix; + + XmpGContainer({required super.schemaRegistryPrefixes, required super.rawProps}) : super(nsUri: XmpNamespaces.gContainer) { + _gContainerItemNsPrefix = XmpNamespace.prefixForUri(schemaRegistryPrefixes, XmpNamespaces.gContainerItem); + _rdfNsPrefix = XmpNamespace.prefixForUri(schemaRegistryPrefixes, XmpNamespaces.rdf); + } + + @override + late final Set<RegExp> skippedProps = { + // variant of `Container:Item` with `<rdf:li>` + RegExp(nsPrefix + r'Directory\[(\d+)\]/' + _rdfNsPrefix + r'type'), + }; + + @override + late final List<XmpCardData> cards = [ + // variant of `Container:Item` with `<rdf:li rdf:parseType="Resource">` + XmpCardData(RegExp(nsPrefix + r'Directory\[(\d+)\]/' + nsPrefix + r'Item/(.*)'), title: 'Directory Item'), + // variant of `Container:Item` with `<rdf:li>` + XmpCardData(RegExp(nsPrefix + r'Directory\[(\d+)\]/(' + _gContainerItemNsPrefix + r'.*)'), title: 'Directory Item'), + ]; +} + +class XmpGDepthNamespace extends XmpGoogleNamespace { + XmpGDepthNamespace({required super.schemaRegistryPrefixes, required super.rawProps}) : super(nsUri: XmpNamespaces.gDepth); + + @override + List<(String, String)> get dataProps => [ + ('${nsPrefix}Data', '${nsPrefix}Mime'), + ('${nsPrefix}Confidence', '${nsPrefix}ConfidenceMime'), + ]; +} + +class XmpGDeviceNamespace extends XmpNamespace { + late final String _cameraNsPrefix; + late final String _containerNsPrefix; + late final String _itemNsPrefix; + + XmpGDeviceNamespace({required super.schemaRegistryPrefixes, required super.rawProps}) : super(nsUri: XmpNamespaces.gDevice) { + _cameraNsPrefix = XmpNamespace.prefixForUri(schemaRegistryPrefixes, XmpNamespaces.gDeviceCamera); + _containerNsPrefix = XmpNamespace.prefixForUri(schemaRegistryPrefixes, XmpNamespaces.gDeviceContainer); + _itemNsPrefix = XmpNamespace.prefixForUri(schemaRegistryPrefixes, XmpNamespaces.gDeviceItem); + + final mimePattern = RegExp(nsPrefix + r'Container/' + _containerNsPrefix + r'Directory\[(\d+)\]/' + _itemNsPrefix + r'Mime'); + final originalProps = rawProps.entries.toList(); + originalProps.forEach((kv) { + final path = kv.key; + final match = mimePattern.firstMatch(path); + if (match != null) { + final indexString = match.group(1); + if (indexString != null) { + final index = int.tryParse(indexString); + if (index != null) { + final dataPath = '${nsPrefix}Container/${_containerNsPrefix}Directory[$index]/${_itemNsPrefix}Data'; + rawProps[dataPath] = '[skipped]'; + } + } + } + }); + } + + @override + late final List<XmpCardData> cards = [ + XmpCardData( + RegExp(nsPrefix + r'Cameras\[(\d+)\]/(.*)'), + cards: [ + XmpCardData(RegExp(_cameraNsPrefix + r'DepthMap/(.*)')), + XmpCardData(RegExp(_cameraNsPrefix + r'Image/(.*)')), + XmpCardData(RegExp(_cameraNsPrefix + r'ImagingModel/(.*)')), + ], + ), + XmpCardData( + RegExp(nsPrefix + r'Container/' + _containerNsPrefix + r'Directory\[(\d+)\]/(.*)'), + spanBuilders: (index, struct) { + if (struct.containsKey('${_itemNsPrefix}Data') && struct.containsKey('${_itemNsPrefix}DataURI')) { + final dataUriProp = struct['${_itemNsPrefix}DataURI']; + if (dataUriProp != null) { + return { + 'Data': InfoRowGroup.linkSpanBuilder( + linkText: (context) => context.l10n.viewerInfoOpenLinkText, + onTap: (context) => OpenEmbeddedDataNotification.googleDevice(dataUri: dataUriProp.value).dispatch(context), + ), + }; + } + } + return {}; + }, + ), + XmpCardData(RegExp(nsPrefix + r'Profiles\[(\d+)\]/(.*)')), + ]; +} + +class XmpGImageNamespace extends XmpGoogleNamespace { + XmpGImageNamespace({required super.schemaRegistryPrefixes, required super.rawProps}) : super(nsUri: XmpNamespaces.gImage); + + @override + List<(String, String)> get dataProps => [ + ('${nsPrefix}Data', '${nsPrefix}Mime'), + ]; +} diff --git a/lib/widgets/viewer/info/metadata/xmp_ns/misc.dart b/lib/widgets/viewer/info/metadata/xmp_ns/misc.dart new file mode 100644 index 0000000..168d92d --- /dev/null +++ b/lib/widgets/viewer/info/metadata/xmp_ns/misc.dart @@ -0,0 +1,113 @@ +import 'package:aves/ref/metadata/xmp.dart'; +import 'package:aves/widgets/viewer/info/metadata/xmp_namespaces.dart'; + +class XmpCreatorAtom extends XmpNamespace { + XmpCreatorAtom({required super.schemaRegistryPrefixes, required super.rawProps}) : super(nsUri: XmpNamespaces.creatorAtom); + + @override + late final List<XmpCardData> cards = [ + XmpCardData(RegExp(nsPrefix + r'aeProjectLink/(.*)'), title: 'AE Project Link'), + ]; +} + +class XmpDarktableNamespace extends XmpNamespace { + XmpDarktableNamespace({required super.schemaRegistryPrefixes, required super.rawProps}) : super(nsUri: XmpNamespaces.darktable); + + @override + late final List<XmpCardData> cards = [ + XmpCardData(RegExp(nsPrefix + r'history\[(\d+)\]/(.*)')), + ]; +} + +class XmpDwcNamespace extends XmpNamespace { + XmpDwcNamespace({required super.schemaRegistryPrefixes, required super.rawProps}) : super(nsUri: XmpNamespaces.dwc); + + @override + late final List<XmpCardData> cards = [ + XmpCardData(RegExp(nsPrefix + r'dctermsLocation/(.*)'), title: 'DC Terms Location'), + XmpCardData(RegExp(nsPrefix + r'Event/(.*)')), + XmpCardData(RegExp(nsPrefix + r'GeologicalContext/(.*)')), + XmpCardData(RegExp(nsPrefix + r'Identification/(.*)')), + XmpCardData(RegExp(nsPrefix + r'MeasurementOrFact/(.*)')), + XmpCardData(RegExp(nsPrefix + r'Occurrence/(.*)')), + XmpCardData(RegExp(nsPrefix + r'Record/(.*)')), + XmpCardData(RegExp(nsPrefix + r'ResourceRelationship/(.*)')), + XmpCardData(RegExp(nsPrefix + r'Taxon/(.*)')), + ]; +} + +class XmpIptcCoreNamespace extends XmpNamespace { + XmpIptcCoreNamespace({required super.schemaRegistryPrefixes, required super.rawProps}) : super(nsUri: XmpNamespaces.iptc4xmpCore); + + @override + late final List<XmpCardData> cards = [ + XmpCardData(RegExp(nsPrefix + r'CreatorContactInfo/(.*)')), + ]; +} + +class XmpIptc4xmpExtNamespace extends XmpNamespace { + XmpIptc4xmpExtNamespace({required super.schemaRegistryPrefixes, required super.rawProps}) : super(nsUri: XmpNamespaces.iptc4xmpExt); + + @override + late final List<XmpCardData> cards = [ + XmpCardData(RegExp(nsPrefix + r'ArtworkOrObject\[(\d+)\]/(.*)')), + ]; +} + +class XmpMPNamespace extends XmpNamespace { + XmpMPNamespace({required super.schemaRegistryPrefixes, required super.rawProps}) : super(nsUri: XmpNamespaces.mp); + + @override + late final List<XmpCardData> cards = [ + XmpCardData(RegExp(nsPrefix + r'RegionInfo/MPRI:Regions\[(\d+)\]/(.*)'), title: 'Regions'), + ]; +} + +// cf www.metadataworkinggroup.org/pdf/mwg_guidance.pdf (down, as of 2021/02/15) +class XmpMgwRegionsNamespace extends XmpNamespace { + XmpMgwRegionsNamespace({required super.schemaRegistryPrefixes, required super.rawProps}) : super(nsUri: XmpNamespaces.mwgrs); + + @override + late final List<XmpCardData> cards = [ + XmpCardData(RegExp(nsPrefix + r'Regions/mwg-rs:AppliedToDimensions/(.*)'), title: 'Applied to Dimensions'), + XmpCardData(RegExp(nsPrefix + r'Regions/mwg-rs:RegionList\[(\d+)\]/(.*)'), title: 'Region List'), + ]; +} + +class XmpPlusNamespace extends XmpNamespace { + XmpPlusNamespace({required super.schemaRegistryPrefixes, required super.rawProps}) : super(nsUri: XmpNamespaces.plus); + + @override + late final List<XmpCardData> cards = [ + XmpCardData(RegExp(nsPrefix + r'CopyrightOwner\[(\d+)\]/(.*)')), + XmpCardData(RegExp(nsPrefix + r'ImageCreator\[(\d+)\]/(.*)')), + XmpCardData(RegExp(nsPrefix + r'Licensor\[(\d+)\]/(.*)')), + ]; +} + +class XmpMMNamespace extends XmpNamespace { + XmpMMNamespace({required super.schemaRegistryPrefixes, required super.rawProps}) : super(nsUri: XmpNamespaces.xmpMM); + + @override + late final List<XmpCardData> cards = [ + XmpCardData(RegExp(nsPrefix + r'DerivedFrom/(.*)')), + XmpCardData(RegExp(nsPrefix + r'History\[(\d+)\]/(.*)')), + XmpCardData(RegExp(nsPrefix + r'Ingredients\[(\d+)\]/(.*)')), + XmpCardData( + RegExp(nsPrefix + r'Pantry\[(\d+)\]/(.*)'), + cards: [ + XmpCardData(RegExp(nsPrefix + r'DerivedFrom/(.*)')), + XmpCardData(RegExp(nsPrefix + r'History\[(\d+)\]/(.*)')), + ], + ), + ]; +} + +class XmpXperiaCameraNamespace extends XmpNamespace { + XmpXperiaCameraNamespace({required super.schemaRegistryPrefixes, required super.rawProps}) : super(nsUri: XmpNamespaces.xperiaCamera); + + @override + late final List<XmpCardData> cards = [ + XmpCardData(RegExp(nsPrefix + r'Face\[(\d+)\]/(.*)')), + ]; +} diff --git a/lib/widgets/viewer/info/metadata/xmp_ns/photoshop.dart b/lib/widgets/viewer/info/metadata/xmp_ns/photoshop.dart new file mode 100644 index 0000000..5449a89 --- /dev/null +++ b/lib/widgets/viewer/info/metadata/xmp_ns/photoshop.dart @@ -0,0 +1,53 @@ +import 'package:aves/ref/metadata/xmp.dart'; +import 'package:aves/widgets/viewer/info/metadata/xmp_namespaces.dart'; + +// cf https://github.com/adobe/xmp-docs/blob/master/XMPNamespaces/photoshop.md +class XmpPhotoshopNamespace extends XmpNamespace { + XmpPhotoshopNamespace({required super.schemaRegistryPrefixes, required super.rawProps}) : super(nsUri: XmpNamespaces.photoshop); + + @override + late final List<XmpCardData> cards = [ + XmpCardData( + RegExp(nsPrefix + r'CameraProfiles\[(\d+)\]/(.*)'), + cards: [ + XmpCardData(RegExp(r'crlcp:PerspectiveModel/(.*)')), + ], + ), + XmpCardData(RegExp(nsPrefix + r'TextLayers\[(\d+)\]/(.*)')), + ]; + + @override + String formatValue(XmpProp prop) { + final value = prop.value; + switch (prop.path) { + case 'photoshop:ColorMode': + return getColorModeDescription(value); + } + return value; + } + + static String getColorModeDescription(String valueString) { + final value = int.tryParse(valueString); + if (value == null) return valueString; + switch (value) { + case 0: + return 'Bitmap'; + case 1: + return 'Gray scale'; + case 2: + return 'Indexed colour'; + case 3: + return 'RGB colour'; + case 4: + return 'CMYK colour'; + case 7: + return 'Multi-channel'; + case 8: + return 'Duotone'; + case 9: + return 'LAB colour'; + default: + return 'Unknown ($value)'; + } + } +} diff --git a/lib/widgets/viewer/info/metadata/xmp_ns/tiff.dart b/lib/widgets/viewer/info/metadata/xmp_ns/tiff.dart new file mode 100644 index 0000000..b67df3a --- /dev/null +++ b/lib/widgets/viewer/info/metadata/xmp_ns/tiff.dart @@ -0,0 +1,28 @@ +import 'package:aves/ref/metadata/exif.dart'; +import 'package:aves/ref/metadata/xmp.dart'; +import 'package:aves/widgets/viewer/info/metadata/xmp_namespaces.dart'; + +// cf https://github.com/adobe/xmp-docs/blob/master/XMPNamespaces/tiff.md +class XmpTiffNamespace extends XmpNamespace { + XmpTiffNamespace({required super.schemaRegistryPrefixes, required super.rawProps}) : super(nsUri: XmpNamespaces.tiff); + + @override + String formatValue(XmpProp prop) { + final value = prop.value; + switch (prop.path) { + case 'tiff:Compression': + return Exif.getCompressionDescription(value); + case 'tiff:Orientation': + return Exif.getOrientationDescription(value); + case 'tiff:PhotometricInterpretation': + return Exif.getPhotometricInterpretationDescription(value); + case 'tiff:PlanarConfiguration': + return Exif.getPlanarConfigurationDescription(value); + case 'tiff:ResolutionUnit': + return Exif.getResolutionUnitDescription(value); + case 'tiff:YCbCrPositioning': + return Exif.getYCbCrPositioningDescription(value); + } + return value; + } +} diff --git a/lib/widgets/viewer/info/metadata/xmp_ns/xmp.dart b/lib/widgets/viewer/info/metadata/xmp_ns/xmp.dart new file mode 100644 index 0000000..655a8fe --- /dev/null +++ b/lib/widgets/viewer/info/metadata/xmp_ns/xmp.dart @@ -0,0 +1,33 @@ +import 'package:aves/ref/metadata/xmp.dart'; +import 'package:aves/ref/mime_types.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/viewer/info/common.dart'; +import 'package:aves/widgets/viewer/info/embedded/notifications.dart'; +import 'package:aves/widgets/viewer/info/metadata/xmp_namespaces.dart'; + +class XmpBasicNamespace extends XmpNamespace { + XmpBasicNamespace({required super.schemaRegistryPrefixes, required super.rawProps}) : super(nsUri: XmpNamespaces.xmp); + + @override + late final List<XmpCardData> cards = [ + XmpCardData( + RegExp(nsPrefix + r'Thumbnails\[(\d+)\]/(.*)'), + spanBuilders: (index, struct) { + return { + if (struct.containsKey('xmpGImg:image')) + 'Image': InfoRowGroup.linkSpanBuilder( + linkText: (context) => context.l10n.viewerInfoOpenLinkText, + onTap: (context) => OpenEmbeddedDataNotification.xmp( + props: [ + const [XmpNamespaces.xmp, 'Thumbnails'], + index, + const [XmpNamespaces.xmpGImg, 'image'], + ], + mimeType: MimeTypes.jpeg, + ).dispatch(context), + ), + }; + }, + ), + ]; +} diff --git a/lib/widgets/viewer/info/metadata/xmp_tile.dart b/lib/widgets/viewer/info/metadata/xmp_tile.dart new file mode 100644 index 0000000..fd3ced9 --- /dev/null +++ b/lib/widgets/viewer/info/metadata/xmp_tile.dart @@ -0,0 +1,55 @@ +import 'dart:collection'; +import 'dart:convert'; + +import 'package:aves/utils/xmp_utils.dart'; +import 'package:aves/widgets/viewer/info/metadata/xmp_namespaces.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; + +class XmpDirTileBody extends StatefulWidget { + final SplayTreeMap<String, String> allTags, tags; + + const XmpDirTileBody({ + super.key, + required this.allTags, + required this.tags, + }); + + @override + State<XmpDirTileBody> createState() => _XmpDirTileBodyState(); +} + +class _XmpDirTileBodyState extends State<XmpDirTileBody> { + late final Map<String, String> _schemaRegistryPrefixes, _tags; + + static const schemaRegistryPrefixesKey = 'schemaRegistryPrefixes'; + + @override + void initState() { + super.initState(); + _tags = Map.from(widget.tags)..remove(schemaRegistryPrefixesKey); + final prefixesJson = widget.allTags[schemaRegistryPrefixesKey]; + final Map<String, dynamic> prefixesDecoded = prefixesJson != null ? jsonDecode(prefixesJson) : {}; + _schemaRegistryPrefixes = Map.fromEntries(prefixesDecoded.entries.map((kv) => MapEntry(kv.key, kv.value as String))); + } + + @override + Widget build(BuildContext context) { + final sections = groupBy<MapEntry<String, String>, String>(_tags.entries, (kv) { + final fullKey = kv.key; + final i = fullKey.indexOf(XMP.propNamespaceSeparator); + final nsPrefix = i == -1 ? '' : fullKey.substring(0, i + 1); + return nsPrefix; + }).entries.map((kv) { + final nsPrefix = kv.key; + final rawProps = Map.fromEntries(kv.value); + return XmpNamespace.create(_schemaRegistryPrefixes, nsPrefix, rawProps); + }).toList() + ..sort((a, b) => compareAsciiUpperCase(a.displayTitle, b.displayTitle)); + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: sections.expand((section) => section.buildNamespaceSection(context)).toList(), + ); + } +} diff --git a/lib/widgets/viewer/multipage/conductor.dart b/lib/widgets/viewer/multipage/conductor.dart new file mode 100644 index 0000000..8c607aa --- /dev/null +++ b/lib/widgets/viewer/multipage/conductor.dart @@ -0,0 +1,53 @@ +import 'dart:async'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/widgets/viewer/multipage/controller.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/foundation.dart'; +import 'package:leak_tracker/leak_tracker.dart'; + +class MultiPageConductor { + final List<MultiPageController> _controllers = []; + + static const maxControllerCount = 3; + + MultiPageConductor() { + if (kFlutterMemoryAllocationsEnabled) { + LeakTracking.dispatchObjectCreated( + library: 'aves', + className: '$MultiPageConductor', + object: this, + ); + } + } + + Future<void> dispose() async { + if (kFlutterMemoryAllocationsEnabled) { + LeakTracking.dispatchObjectDisposed(object: this); + } + await _disposeAll(); + _controllers.clear(); + } + + MultiPageController getOrCreateController(AvesEntry entry) { + var controller = getController(entry); + if (controller != null) { + _controllers.remove(controller); + } else { + controller = MultiPageController(entry); + } + _controllers.insert(0, controller); + while (_controllers.length > maxControllerCount) { + _controllers.removeLast().dispose(); + } + return controller; + } + + MultiPageController? getController(AvesEntry entry) { + return _controllers.firstWhereOrNull((c) => c.entry.uri == entry.uri && c.entry.pageId == entry.pageId); + } + + Future<void> _applyToAll(FutureOr Function(MultiPageController controller) action) => Future.forEach<MultiPageController>(_controllers, action); + + Future<void> _disposeAll() => _applyToAll((controller) => controller.dispose()); +} diff --git a/lib/widgets/viewer/multipage/controller.dart b/lib/widgets/viewer/multipage/controller.dart new file mode 100644 index 0000000..589cfa2 --- /dev/null +++ b/lib/widgets/viewer/multipage/controller.dart @@ -0,0 +1,61 @@ +import 'dart:async'; +import 'dart:math'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/multipage.dart'; +import 'package:aves/model/multipage.dart'; +import 'package:flutter/foundation.dart'; +import 'package:leak_tracker/leak_tracker.dart'; + +class MultiPageController { + final AvesEntry entry; + final ValueNotifier<int?> pageNotifier = ValueNotifier(null); + + bool _disposed = false; + MultiPageInfo? _info; + + final StreamController<MultiPageInfo?> _infoStreamController = StreamController.broadcast(); + + Stream<MultiPageInfo?> get infoStream => _infoStreamController.stream; + + MultiPageInfo? get info => _info; + + int? get page => pageNotifier.value; + + set page(int? page) => pageNotifier.value = page; + + MultiPageController(this.entry) { + if (kFlutterMemoryAllocationsEnabled) { + LeakTracking.dispatchObjectCreated( + library: 'aves', + className: '$MultiPageController', + object: this, + ); + } + reset(); + } + + void reset() => entry.getMultiPageInfo().then((info) { + if (info == null || _disposed) return; + final currentPage = pageNotifier.value; + if (currentPage == null) { + pageNotifier.value = info.defaultPage?.index ?? 0; + } else { + pageNotifier.value = min(currentPage, info.pageCount - 1); + } + _info = info; + _infoStreamController.add(_info); + }); + + void dispose() { + if (kFlutterMemoryAllocationsEnabled) { + LeakTracking.dispatchObjectDisposed(object: this); + } + _info?.dispose(); + _disposed = true; + pageNotifier.dispose(); + } + + @override + String toString() => '$runtimeType#${shortHash(this)}{entry=$entry, page=$page, info=$info}'; +} diff --git a/lib/widgets/viewer/overlay/bottom.dart b/lib/widgets/viewer/overlay/bottom.dart new file mode 100644 index 0000000..9252389 --- /dev/null +++ b/lib/widgets/viewer/overlay/bottom.dart @@ -0,0 +1,305 @@ +import 'dart:math'; + +import 'package:aves/app_mode.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/multipage.dart'; +import 'package:aves/model/selection.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/widgets/common/extensions/media_query.dart'; +import 'package:aves/widgets/viewer/controls/intents.dart'; +import 'package:aves/widgets/viewer/controls/notifications.dart'; +import 'package:aves/widgets/viewer/multipage/controller.dart'; +import 'package:aves/widgets/viewer/overlay/multipage.dart'; +import 'package:aves/widgets/viewer/overlay/selection_button.dart'; +import 'package:aves/widgets/viewer/overlay/thumbnail_preview.dart'; +import 'package:aves/widgets/viewer/overlay/viewer_buttons.dart'; +import 'package:aves/widgets/viewer/overlay/wallpaper_buttons.dart'; +import 'package:aves/widgets/viewer/page_entry_builder.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:provider/provider.dart'; + +class ViewerBottomOverlay extends StatelessWidget { + final List<AvesEntry> entries; + final int index; + final CollectionLens? collection; + final AnimationController animationController; + final Size availableSize; + final EdgeInsets? viewInsets, viewPadding; + final MultiPageController? multiPageController; + + // always keep action buttons in the lower right corner, even with RTL locales + static const actionsDirection = TextDirection.ltr; + + AvesEntry? get entry { + return index < entries.length ? entries[index] : null; + } + + const ViewerBottomOverlay({ + super.key, + required this.entries, + required this.index, + required this.collection, + required this.animationController, + required this.availableSize, + this.viewInsets, + this.viewPadding, + required this.multiPageController, + }); + + @override + Widget build(BuildContext context) { + final mainEntry = entry; + if (mainEntry == null) return const SizedBox(); + + Widget _buildContent({AvesEntry? pageEntry}) => _BottomOverlayContent( + entries: entries, + index: index, + mainEntry: mainEntry, + pageEntry: pageEntry ?? mainEntry, + collection: collection, + availableSize: availableSize, + viewInsets: viewInsets, + viewPadding: viewPadding, + multiPageController: multiPageController, + animationController: animationController, + ); + + Widget child = multiPageController != null + ? PageEntryBuilder( + multiPageController: multiPageController!, + builder: (pageEntry) => _buildContent(pageEntry: pageEntry), + ) + : _buildContent(); + + return Selector<MediaQueryData, double>( + selector: (context, mq) => max(mq.effectiveBottomPadding, mq.systemGestureInsets.bottom), + builder: (context, mqPaddingBottom, child) { + return Padding( + padding: EdgeInsets.only(bottom: mqPaddingBottom), + child: child, + ); + }, + child: child, + ); + } + + static double actionSafeHeight(BuildContext context) { + final mqPaddingBottom = context.select<MediaQueryData, double>((mq) => max(mq.effectiveBottomPadding, mq.systemGestureInsets.bottom)); + final buttonHeight = ViewerButtons.preferredHeight(context); + final thumbnailHeight = (settings.showOverlayThumbnailPreview ? ViewerThumbnailPreview.preferredHeight : 0); + return mqPaddingBottom + buttonHeight + thumbnailHeight; + } +} + +class _BottomOverlayContent extends StatefulWidget { + final List<AvesEntry> entries; + final int index; + final AvesEntry mainEntry, pageEntry; + final CollectionLens? collection; + final Size availableSize; + final EdgeInsets? viewInsets, viewPadding; + final MultiPageController? multiPageController; + final AnimationController animationController; + + const _BottomOverlayContent({ + required this.entries, + required this.index, + required this.mainEntry, + required this.pageEntry, + required this.collection, + required this.availableSize, + required this.viewInsets, + required this.viewPadding, + required this.multiPageController, + required this.animationController, + }); + + @override + State<_BottomOverlayContent> createState() => _BottomOverlayContentState(); +} + +class _BottomOverlayContentState extends State<_BottomOverlayContent> { + final FocusScopeNode _buttonRowFocusScopeNode = FocusScopeNode(); + late CurvedAnimation _buttonScale, _thumbnailOpacity; + + @override + void initState() { + super.initState(); + _registerWidget(widget); + WidgetsBinding.instance.addPostFrameCallback((_) => _requestFocus()); + } + + @override + void didUpdateWidget(covariant _BottomOverlayContent oldWidget) { + super.didUpdateWidget(oldWidget); + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + + @override + void dispose() { + _unregisterWidget(widget); + _buttonRowFocusScopeNode.dispose(); + super.dispose(); + } + + void _registerWidget(_BottomOverlayContent widget) { + final animationController = widget.animationController; + _buttonScale = CurvedAnimation( + parent: animationController, + // a little bounce at the top + curve: Curves.easeOutBack, + ); + _thumbnailOpacity = CurvedAnimation( + parent: animationController, + curve: Curves.easeOutQuad, + ); + } + + void _unregisterWidget(_BottomOverlayContent widget) { + _buttonScale.dispose(); + _thumbnailOpacity.dispose(); + } + + @override + Widget build(BuildContext context) { + final mainEntry = widget.mainEntry; + final pageEntry = widget.pageEntry; + final multiPageController = widget.multiPageController; + final isWallpaperMode = context.read<ValueNotifier<AppMode>>().value == AppMode.setWallpaper; + + return AnimatedBuilder( + animation: Listenable.merge([ + mainEntry.metadataChangeNotifier, + pageEntry.metadataChangeNotifier, + ]), + builder: (context, child) { + final viewInsetsPadding = (widget.viewInsets ?? EdgeInsets.zero) + (widget.viewPadding ?? EdgeInsets.zero); + final selection = context.read<Selection<AvesEntry>?>(); + final viewerButtonRow = (selection?.isSelecting ?? false) + ? SelectionButton( + mainEntry: mainEntry, + scale: _buttonScale, + ) + : FocusableActionDetector( + focusNode: _buttonRowFocusScopeNode, + shortcuts: settings.useTvLayout + ? const { + SingleActivator(LogicalKeyboardKey.arrowUp): TvShowLessInfoIntent(), + } + : null, + actions: { + TvShowLessInfoIntent: CallbackAction<Intent>(onInvoke: (intent) => TvShowLessInfoNotification().dispatch(context)), + }, + child: SafeArea( + top: false, + bottom: false, + minimum: EdgeInsets.only( + left: viewInsetsPadding.left, + right: viewInsetsPadding.right, + ), + child: isWallpaperMode + ? WallpaperButtons( + entry: pageEntry, + scale: _buttonScale, + ) + : ViewerButtons( + mainEntry: mainEntry, + pageEntry: pageEntry, + collection: widget.collection, + scale: _buttonScale, + ), + ), + ); + + final showMultiPageOverlay = mainEntry.isMultiPage && multiPageController != null; + final collapsedPageScroller = mainEntry.isMotionPhoto; + + final availableWidth = widget.availableSize.width; + return SizedBox( + width: availableWidth, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (showMultiPageOverlay && !collapsedPageScroller) + Padding( + padding: const EdgeInsets.only(bottom: 8), + child: FadeTransition( + opacity: _thumbnailOpacity, + child: MultiPageOverlay( + controller: multiPageController, + availableWidth: availableWidth, + scrollable: true, + ), + ), + ), + (showMultiPageOverlay && collapsedPageScroller) + ? Row( + crossAxisAlignment: CrossAxisAlignment.center, + textDirection: ViewerBottomOverlay.actionsDirection, + children: [ + SafeArea( + top: false, + bottom: false, + child: Padding( + padding: const EdgeInsets.only(bottom: 8), + child: MultiPageOverlay( + controller: multiPageController, + availableWidth: availableWidth, + scrollable: false, + ), + ), + ), + Expanded(child: viewerButtonRow), + ], + ) + : viewerButtonRow, + if (settings.showOverlayThumbnailPreview && !isWallpaperMode) + FadeTransition( + opacity: _thumbnailOpacity, + child: ViewerThumbnailPreview( + availableWidth: availableWidth, + displayedIndex: widget.index, + entries: widget.entries, + ), + ), + ], + ), + ); + }, + ); + } + + void _requestFocus() => _buttonRowFocusScopeNode.children.firstOrNull?.requestFocus(); +} + +class ExtraBottomOverlay extends StatelessWidget { + final EdgeInsets? viewInsets, viewPadding; + final Widget child; + + const ExtraBottomOverlay({ + super.key, + this.viewInsets, + this.viewPadding, + required this.child, + }); + + @override + Widget build(BuildContext context) { + final viewInsets = this.viewInsets ?? MediaQuery.viewInsetsOf(context); + final viewPadding = this.viewPadding ?? MediaQuery.viewPaddingOf(context); + final safePadding = (viewInsets + viewPadding).copyWith(bottom: 8) + const EdgeInsets.symmetric(horizontal: 8); + + return Padding( + padding: safePadding, + child: SizedBox( + width: MediaQuery.sizeOf(context).width - safePadding.horizontal, + child: child, + ), + ); + } +} diff --git a/lib/widgets/viewer/overlay/details/date.dart b/lib/widgets/viewer/overlay/details/date.dart new file mode 100644 index 0000000..7c762f0 --- /dev/null +++ b/lib/widgets/viewer/overlay/details/date.dart @@ -0,0 +1,44 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/props.dart'; +import 'package:aves/theme/format.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/theme/text.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/viewer/multipage/controller.dart'; +import 'package:aves/widgets/viewer/overlay/details/details.dart'; +import 'package:decorated_icon/decorated_icon.dart'; +import 'package:flutter/material.dart'; + +class OverlayDateRow extends StatelessWidget { + final AvesEntry entry; + final MultiPageController? multiPageController; + + const OverlayDateRow({ + super.key, + required this.entry, + required this.multiPageController, + }); + + @override + Widget build(BuildContext context) { + final locale = context.locale; + final use24hour = MediaQuery.alwaysUse24HourFormatOf(context); + + final date = entry.bestDate; + final dateText = date != null ? formatDateTime(date, locale, use24hour) : AText.valueNotAvailable; + final resolutionText = entry.isSvg + ? entry.aspectRatioText + : entry.isSized + ? entry.getResolutionText(locale) + : ''; + + return Row( + children: [ + DecoratedIcon(AIcons.date, size: ViewerDetailOverlayContent.iconSize, shadows: ViewerDetailOverlayContent.shadows(context)), + const SizedBox(width: ViewerDetailOverlayContent.iconPadding), + Expanded(flex: 3, child: Text(dateText)), + Expanded(flex: 2, child: Text(resolutionText)), + ], + ); + } +} diff --git a/lib/widgets/viewer/overlay/details/description.dart b/lib/widgets/viewer/overlay/details/description.dart new file mode 100644 index 0000000..18e6da3 --- /dev/null +++ b/lib/widgets/viewer/overlay/details/description.dart @@ -0,0 +1,35 @@ +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/viewer/overlay/details/details.dart'; +import 'package:decorated_icon/decorated_icon.dart'; +import 'package:flutter/material.dart'; + +class OverlayDescriptionRow extends StatelessWidget { + final String description; + + const OverlayDescriptionRow({ + super.key, + required this.description, + }); + + @override + Widget build(BuildContext context) { + return Text.rich( + TextSpan( + children: [ + WidgetSpan( + alignment: PlaceholderAlignment.middle, + child: Padding( + padding: const EdgeInsetsDirectional.only(end: ViewerDetailOverlayContent.iconPadding), + child: DecoratedIcon( + AIcons.description, + size: ViewerDetailOverlayContent.iconSize, + shadows: ViewerDetailOverlayContent.shadows(context), + ), + ), + ), + TextSpan(text: description), + ], + ), + ); + } +} diff --git a/lib/widgets/viewer/overlay/details/details.dart b/lib/widgets/viewer/overlay/details/details.dart new file mode 100644 index 0000000..792fccb --- /dev/null +++ b/lib/widgets/viewer/overlay/details/details.dart @@ -0,0 +1,339 @@ +import 'dart:math'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/metadata/overlay.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/styles.dart'; +import 'package:aves/widgets/common/extensions/theme.dart'; +import 'package:aves/widgets/viewer/multipage/controller.dart'; +import 'package:aves/widgets/viewer/overlay/details/date.dart'; +import 'package:aves/widgets/viewer/overlay/details/description.dart'; +import 'package:aves/widgets/viewer/overlay/details/expander.dart'; +import 'package:aves/widgets/viewer/overlay/details/location.dart'; +import 'package:aves/widgets/viewer/overlay/details/position_title.dart'; +import 'package:aves/widgets/viewer/overlay/details/rating_tags.dart'; +import 'package:aves/widgets/viewer/overlay/details/shooting.dart'; +import 'package:aves/widgets/viewer/page_entry_builder.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class ViewerDetailOverlay extends StatefulWidget { + final List<AvesEntry> entries; + final int index; + final bool hasCollection; + final MultiPageController? multiPageController; + final ValueNotifier<bool> expandedNotifier; + final Size availableSize; + + const ViewerDetailOverlay({ + super.key, + required this.entries, + required this.index, + required this.hasCollection, + required this.multiPageController, + required this.expandedNotifier, + required this.availableSize, + }); + + @override + State<ViewerDetailOverlay> createState() => _ViewerDetailOverlayState(); +} + +class _ViewerDetailOverlayState extends State<ViewerDetailOverlay> { + List<AvesEntry> get entries => widget.entries; + + AvesEntry? get entry => entryForIndex(widget.index); + + AvesEntry? entryForIndex(int index) => index < entries.length ? entries[index] : null; + + late Future<OverlayMetadata> _detailLoader; + AvesEntry? _lastEntry; + OverlayMetadata _lastDetails = const OverlayMetadata(); + + @override + void initState() { + super.initState(); + _initDetailLoader(); + } + + @override + void didUpdateWidget(covariant ViewerDetailOverlay oldWidget) { + super.didUpdateWidget(oldWidget); + final newEntry = entryForIndex(widget.index); + if (newEntry != entryForIndex(oldWidget.index) && newEntry != _lastEntry) { + _initDetailLoader(); + } + } + + void _initDetailLoader() { + final requestEntry = entry; + if (requestEntry == null) { + _detailLoader = SynchronousFuture(const OverlayMetadata()); + } else { + _detailLoader = metadataFetchService.getOverlayMetadata(requestEntry, { + if (settings.showOverlayShootingDetails) ...{ + MetadataSyntheticField.aperture, + MetadataSyntheticField.exposureTime, + MetadataSyntheticField.focalLength, + MetadataSyntheticField.iso, + }, + if (settings.showOverlayDescription) MetadataSyntheticField.description, + }); + } + } + + @override + Widget build(BuildContext context) { + return SafeArea( + top: false, + bottom: false, + child: FutureBuilder<OverlayMetadata>( + future: _detailLoader, + builder: (context, snapshot) { + if (snapshot.connectionState == ConnectionState.done && !snapshot.hasError) { + _lastDetails = snapshot.data!; + _lastEntry = entry; + } + if (_lastEntry == null) return const SizedBox(); + final mainEntry = _lastEntry!; + + final multiPageController = widget.multiPageController; + Widget _buildContent({AvesEntry? pageEntry}) => ViewerDetailOverlayContent( + pageEntry: pageEntry ?? mainEntry, + details: _lastDetails, + position: widget.hasCollection ? '${widget.index + 1}/${entries.length}' : null, + availableWidth: widget.availableSize.width, + multiPageController: multiPageController, + expandedNotifier: widget.expandedNotifier, + ); + + return multiPageController != null + ? PageEntryBuilder( + multiPageController: multiPageController, + builder: (pageEntry) => _buildContent(pageEntry: pageEntry), + ) + : _buildContent(); + }, + ), + ); + } +} + +class ViewerDetailOverlayContent extends StatelessWidget { + final AvesEntry pageEntry; + final OverlayMetadata details; + final String? position; + final double availableWidth; + final MultiPageController? multiPageController; + final ValueNotifier<bool> expandedNotifier; + + static const double _interRowPadding = 2.0; + static const double _subRowMinWidth = 300.0; + static const padding = EdgeInsets.symmetric(vertical: 4, horizontal: 8); + static const double iconPadding = 8.0; + static const double iconSize = 16.0; + + static List<Shadow>? shadows(BuildContext context) => Theme.of(context).isDark ? AStyles.embossShadows : null; + + const ViewerDetailOverlayContent({ + super.key, + required this.pageEntry, + required this.details, + required this.position, + required this.availableWidth, + required this.multiPageController, + required this.expandedNotifier, + }); + + @override + Widget build(BuildContext context) { + return AnimatedBuilder( + animation: pageEntry.metadataChangeNotifier, + builder: (context, child) => DefaultTextStyle( + style: Theme.of(context).textTheme.bodyMedium!.copyWith( + shadows: shadows(context), + ), + softWrap: false, + overflow: TextOverflow.fade, + maxLines: 1, + child: Padding( + padding: padding, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: _buildRows(context), + ), + ), + ), + ); + } + + List<Widget> _buildRows(BuildContext context) { + final infoMaxWidth = availableWidth - padding.horizontal; + final showRatingTags = settings.showOverlayRatingTags; + final showShootingDetails = settings.showOverlayShootingDetails; + final showDescription = settings.showOverlayDescription; + + final isLandscape = MediaQuery.orientationOf(context) == Orientation.landscape; + final twoColumns = isLandscape && infoMaxWidth / 2 > _subRowMinWidth; + final subRowWidth = twoColumns ? min(_subRowMinWidth, infoMaxWidth / 2) : infoMaxWidth; + final collapsedShooting = twoColumns && showShootingDetails; + final collapsedLocation = twoColumns && !showShootingDetails; + + final positionTitle = OverlayPositionTitleRow( + entry: pageEntry, + collectionPosition: position, + multiPageController: multiPageController, + ); + + final rows = <Widget>[]; + if (positionTitle.isNotEmpty) { + rows.add(OverlayRowExpander( + expandedNotifier: expandedNotifier, + child: positionTitle, + )); + rows.add(const SizedBox(height: _interRowPadding)); + } + if (twoColumns) { + rows.add( + Row( + children: [ + _buildDateSubRow(subRowWidth), + if (collapsedShooting) _buildShootingSubRow(context, subRowWidth), + if (collapsedLocation) _buildLocationSubRow(context, subRowWidth), + ], + ), + ); + } else { + rows.add(_buildDateSubRow(subRowWidth)); + if (showShootingDetails) { + rows.add(_buildShootingFullRow(context, subRowWidth)); + } + } + if (!collapsedLocation) { + rows.add(_buildLocationFullRow(context)); + } + if (showRatingTags) { + rows.add(_buildRatingTagsFullRow(context)); + } + if (showDescription) { + rows.add(_buildDescriptionFullRow(context, infoMaxWidth)); + } + return rows; + } + + Widget _buildDateSubRow(double subRowWidth) => SizedBox( + width: subRowWidth, + child: OverlayDateRow( + entry: pageEntry, + multiPageController: multiPageController, + ), + ); + + Widget _buildRatingTagsFullRow(BuildContext context) => _buildFullRowSwitcher( + context: context, + visible: pageEntry.rating != 0 || pageEntry.tags.isNotEmpty, + builder: (context) => OverlayRowExpander( + expandedNotifier: expandedNotifier, + child: OverlayRatingTagsRow(entry: pageEntry), + ), + ); + + Widget _buildDescriptionFullRow(BuildContext context, double infoMaxWidth) => _buildFullRowSwitcher( + context: context, + visible: details.description != null, + builder: (context) => SizedBox( + // size it so that a long description with multiple short lines + // expands to the full width and the scroll bar is at the edge + width: infoMaxWidth, + child: OverlayRowExpander( + expandedNotifier: expandedNotifier, + child: OverlayDescriptionRow(description: details.description!), + ), + ), + ); + + Widget _buildShootingFullRow(BuildContext context, double subRowWidth) => _buildFullRowSwitcher( + context: context, + visible: details.hasShootingDetails, + builder: (context) => SizedBox( + width: subRowWidth, + child: OverlayShootingRow(details: details), + ), + ); + + Widget _buildShootingSubRow(BuildContext context, double subRowWidth) => _buildSubRowSwitcher( + context: context, + subRowWidth: subRowWidth, + visible: details.hasShootingDetails, + builder: (context) => OverlayShootingRow(details: details), + ); + + Widget _buildLocationFullRow(BuildContext context) => _buildFullRowSwitcher( + context: context, + visible: pageEntry.hasGps, + builder: (context) => OverlayLocationRow(entry: pageEntry), + ); + + Widget _buildLocationSubRow(BuildContext context, double subRowWidth) => _buildSubRowSwitcher( + context: context, + subRowWidth: subRowWidth, + visible: pageEntry.hasGps, + builder: (context) => OverlayLocationRow(entry: pageEntry), + ); + + Widget _buildSubRowSwitcher({ + required BuildContext context, + required double subRowWidth, + required bool visible, + required WidgetBuilder builder, + }) { + final child = visible + ? SizedBox( + width: subRowWidth, + child: builder(context), + ) + : const SizedBox(); + return AnimatedSwitcher( + duration: context.select<DurationsData, Duration>((v) => v.viewerOverlayChangeAnimation), + switchInCurve: Curves.easeInOutCubic, + switchOutCurve: Curves.easeInOutCubic, + transitionBuilder: (child, animation) => FadeTransition( + opacity: animation, + child: child, + ), + child: child, + ); + } + + Widget _buildFullRowSwitcher({ + required BuildContext context, + required bool visible, + required WidgetBuilder builder, + }) { + final child = visible + ? Padding( + padding: const EdgeInsets.only(top: _interRowPadding), + child: builder(context), + ) + : const SizedBox(); + return AnimatedSwitcher( + duration: context.select<DurationsData, Duration>((v) => v.viewerOverlayChangeAnimation), + switchInCurve: Curves.easeInOutCubic, + switchOutCurve: Curves.easeInOutCubic, + transitionBuilder: (child, animation) => FadeTransition( + opacity: animation, + child: SizeTransition( + sizeFactor: animation, + axisAlignment: 1, + child: child, + ), + ), + child: child, + ); + } +} diff --git a/lib/widgets/viewer/overlay/details/expander.dart b/lib/widgets/viewer/overlay/details/expander.dart new file mode 100644 index 0000000..f7fd84d --- /dev/null +++ b/lib/widgets/viewer/overlay/details/expander.dart @@ -0,0 +1,79 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class OverlayRowExpander extends StatefulWidget { + final ValueNotifier<bool> expandedNotifier; + final Widget child; + + const OverlayRowExpander({ + super.key, + required this.expandedNotifier, + required this.child, + }); + + @override + State<OverlayRowExpander> createState() => _OverlayRowExpanderState(); +} + +class _OverlayRowExpanderState extends State<OverlayRowExpander> { + final ScrollController _scrollController = ScrollController(); + + @override + void didUpdateWidget(covariant OverlayRowExpander oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.child != widget.child) { + if (_scrollController.hasClients && _scrollController.positions.every((v) => v.hasContentDimensions)) { + _scrollController.jumpTo(0); + } + } + } + + @override + void dispose() { + _scrollController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return ValueListenableBuilder<bool>( + valueListenable: widget.expandedNotifier, + builder: (context, expanded, child) { + final parent = DefaultTextStyle.of(context); + child = DefaultTextStyle( + style: parent.style, + textAlign: parent.textAlign, + softWrap: expanded, + overflow: parent.overflow, + maxLines: expanded ? null : 1, + textWidthBasis: parent.textWidthBasis, + child: child!, + ); + if (expanded) { + child = ConstrainedBox( + constraints: BoxConstraints( + maxHeight: context.select<MediaQueryData, double>((mq) => mq.size.height / 5), + ), + child: MediaQuery.removePadding( + // remove padding so that scroll bar is consistent with the scroll view + context: context, + removeTop: true, + removeBottom: true, + child: Scrollbar( + controller: _scrollController, + thumbVisibility: true, + radius: const Radius.circular(16), + child: SingleChildScrollView( + controller: _scrollController, + child: child, + ), + ), + ), + ); + } + return child; + }, + child: widget.child, + ); + } +} diff --git a/lib/widgets/viewer/overlay/details/location.dart b/lib/widgets/viewer/overlay/details/location.dart new file mode 100644 index 0000000..4df7b89 --- /dev/null +++ b/lib/widgets/viewer/overlay/details/location.dart @@ -0,0 +1,39 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/location.dart'; +import 'package:aves/model/settings/enums/coordinate_format.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/theme/text.dart'; +import 'package:aves/widgets/viewer/overlay/details/details.dart'; +import 'package:decorated_icon/decorated_icon.dart'; +import 'package:flutter/material.dart'; + +class OverlayLocationRow extends AnimatedWidget { + final AvesEntry entry; + + OverlayLocationRow({ + super.key, + required this.entry, + }) : super(listenable: entry.addressChangeNotifier); + + @override + Widget build(BuildContext context) { + String? location; + if (entry.hasAddress) { + location = entry.shortAddress; + } + if (location == null || location.isEmpty) { + final latLng = entry.latLng; + if (latLng != null) { + location = settings.coordinateFormat.format(context, latLng); + } + } + return Row( + children: [ + DecoratedIcon(AIcons.location, size: ViewerDetailOverlayContent.iconSize, shadows: ViewerDetailOverlayContent.shadows(context)), + const SizedBox(width: ViewerDetailOverlayContent.iconPadding), + Expanded(child: Text(location ?? AText.valueNotAvailable)), + ], + ); + } +} diff --git a/lib/widgets/viewer/overlay/details/position_title.dart b/lib/widgets/viewer/overlay/details/position_title.dart new file mode 100644 index 0000000..346f66d --- /dev/null +++ b/lib/widgets/viewer/overlay/details/position_title.dart @@ -0,0 +1,54 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/multipage.dart'; +import 'package:aves/theme/text.dart'; +import 'package:aves/widgets/viewer/multipage/controller.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; + +class OverlayPositionTitleRow extends StatelessWidget { + final AvesEntry entry; + final String? collectionPosition; + final MultiPageController? multiPageController; + + const OverlayPositionTitleRow({ + super.key, + required this.entry, + required this.collectionPosition, + required this.multiPageController, + }); + + String? get title => entry.bestTitle; + + bool get isNotEmpty => collectionPosition != null || multiPageController != null || title != null; + + @override + Widget build(BuildContext context) { + Text toText({String? pagePosition}) => Text( + [ + if (collectionPosition != null) collectionPosition, + if (pagePosition != null) pagePosition, + if (title != null) '${Unicode.FSI}$title${Unicode.PDI}', + ].join(AText.separator), + ); + + if (multiPageController == null) return toText(); + + return StreamBuilder<MultiPageInfo?>( + stream: multiPageController!.infoStream, + builder: (context, snapshot) { + final multiPageInfo = multiPageController!.info; + String? pagePosition; + if (multiPageInfo != null) { + // page count may be 0 when we know an entry to have multiple pages + // but fail to get information about these pages + final pageCount = multiPageInfo.pageCount; + if (pageCount > 0) { + final page = multiPageInfo.getById(entry.pageId ?? entry.id) ?? multiPageInfo.defaultPage; + pagePosition = '${(page?.index ?? 0) + 1}/$pageCount'; + } + } + return toText(pagePosition: pagePosition); + }, + ); + } +} diff --git a/lib/widgets/viewer/overlay/details/rating_tags.dart b/lib/widgets/viewer/overlay/details/rating_tags.dart new file mode 100644 index 0000000..e777b98 --- /dev/null +++ b/lib/widgets/viewer/overlay/details/rating_tags.dart @@ -0,0 +1,61 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/theme/text.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/viewer/overlay/details/details.dart'; +import 'package:collection/collection.dart'; +import 'package:decorated_icon/decorated_icon.dart'; +import 'package:flutter/material.dart'; + +class OverlayRatingTagsRow extends AnimatedWidget { + final AvesEntry entry; + + OverlayRatingTagsRow({ + super.key, + required this.entry, + }) : super(listenable: entry.metadataChangeNotifier); + + @override + Widget build(BuildContext context) { + final String ratingString; + final rating = entry.rating.clamp(-1, 5); + switch (rating) { + case -1: + ratingString = context.l10n.filterRatingRejectedLabel; + case 0: + ratingString = ''; + default: + ratingString = '${'★' * rating}${'☆' * (5 - rating)}'; + } + + final textScaler = MediaQuery.textScalerOf(context); + final tags = entry.tags.toList()..sort(compareAsciiUpperCaseNatural); + final hasTags = tags.isNotEmpty; + + const iconSize = ViewerDetailOverlayContent.iconSize; + final textScaleFactor = textScaler.scale(iconSize) / iconSize; + + return Text.rich( + TextSpan( + children: [ + TextSpan(text: ratingString), + if (hasTags) ...[ + if (ratingString.isNotEmpty) const TextSpan(text: AText.separator), + WidgetSpan( + alignment: PlaceholderAlignment.middle, + child: Padding( + padding: const EdgeInsetsDirectional.only(end: ViewerDetailOverlayContent.iconPadding), + child: DecoratedIcon( + AIcons.tag, + size: iconSize / textScaleFactor, + shadows: ViewerDetailOverlayContent.shadows(context), + ), + ), + ), + TextSpan(text: tags.join(AText.separator)), + ] + ], + ), + ); + } +} diff --git a/lib/widgets/viewer/overlay/details/shooting.dart b/lib/widgets/viewer/overlay/details/shooting.dart new file mode 100644 index 0000000..770d04e --- /dev/null +++ b/lib/widgets/viewer/overlay/details/shooting.dart @@ -0,0 +1,42 @@ +import 'package:aves/model/metadata/overlay.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/theme/text.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/viewer/overlay/details/details.dart'; +import 'package:decorated_icon/decorated_icon.dart'; +import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; + +class OverlayShootingRow extends StatelessWidget { + final OverlayMetadata details; + + const OverlayShootingRow({ + super.key, + required this.details, + }); + + @override + Widget build(BuildContext context) { + final locale = context.locale; + + final aperture = details.aperture; + final apertureText = aperture != null ? 'ƒ/${NumberFormat('0.0', locale).format(aperture)}' : AText.valueNotAvailable; + + final focalLength = details.focalLength; + final focalLengthText = focalLength != null ? context.l10n.focalLength(NumberFormat('0.#', locale).format(focalLength)) : AText.valueNotAvailable; + + final iso = details.iso; + final isoText = iso != null ? 'ISO$iso' : AText.valueNotAvailable; + + return Row( + children: [ + DecoratedIcon(AIcons.shooting, size: ViewerDetailOverlayContent.iconSize, shadows: ViewerDetailOverlayContent.shadows(context)), + const SizedBox(width: ViewerDetailOverlayContent.iconPadding), + Expanded(child: Text(apertureText)), + Expanded(child: Text(details.exposureTime ?? AText.valueNotAvailable)), + Expanded(child: Text(focalLengthText)), + Expanded(child: Text(isoText)), + ], + ); + } +} diff --git a/lib/widgets/viewer/overlay/histogram.dart b/lib/widgets/viewer/overlay/histogram.dart new file mode 100644 index 0000000..157b21e --- /dev/null +++ b/lib/widgets/viewer/overlay/histogram.dart @@ -0,0 +1,157 @@ +import 'dart:ui'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/widgets/viewer/overlay/top.dart'; +import 'package:aves/widgets/viewer/view/controller.dart'; +import 'package:aves/widgets/viewer/view/histogram.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; + +class ImageHistogram extends StatefulWidget { + final ViewStateController viewStateController; + final ImageProvider image; + + const ImageHistogram({ + super.key, + required this.viewStateController, + required this.image, + }); + + @override + State<ImageHistogram> createState() => _ImageHistogramState(); +} + +class _ImageHistogramState extends State<ImageHistogram> { + HistogramLevels _levels = {}; + ImageStream? _imageStream; + late ImageStreamListener _imageListener; + + ViewStateController get viewStateController => widget.viewStateController; + + AvesEntry get entry => viewStateController.entry; + + ImageProvider get imageProvider => widget.image; + + @override + void initState() { + super.initState(); + _registerWidget(widget); + } + + @override + void didUpdateWidget(covariant ImageHistogram oldWidget) { + super.didUpdateWidget(oldWidget); + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + + @override + void dispose() { + _unregisterWidget(widget); + super.dispose(); + } + + void _registerWidget(ImageHistogram widget) { + _imageStream = imageProvider.resolve(ImageConfiguration.empty); + _imageListener = ImageStreamListener((image, synchronousCall) async { + // implementer is responsible for disposing the provided `ImageInfo` + await _updateLevels(image); + image.dispose(); + }); + _imageStream?.addListener(_imageListener); + } + + void _unregisterWidget(ImageHistogram widget) { + _imageStream?.removeListener(_imageListener); + } + + @override + Widget build(BuildContext context) { + return IgnorePointer( + child: CustomPaint( + painter: _HistogramPainter( + levels: _levels, + borderColor: ViewerTopOverlay.componentBorderColor, + ), + size: const Size(ViewerTopOverlay.componentDimension, ViewerTopOverlay.componentDimension * .6), + ), + ); + } + + Future<void> _updateLevels(ImageInfo info) async { + final targetEntry = entry; + final forceUpdate = targetEntry.isAnimated; + final newLevels = await viewStateController.getHistogramLevels(info, forceUpdate); + if (!mounted) return; + setState(() => _levels = targetEntry == entry ? newLevels : {}); + } +} + +class _HistogramPainter extends CustomPainter { + final HistogramLevels levels; + final Color borderColor; + + late final Paint fill, borderStroke; + + _HistogramPainter({ + required this.levels, + this.borderColor = Colors.white, + }) { + fill = Paint() + ..style = PaintingStyle.fill + ..color = const Color(0x33000000); + borderStroke = Paint() + ..style = PaintingStyle.stroke + ..color = borderColor; + } + + @override + void paint(Canvas canvas, Size size) { + if (levels.isEmpty) return; + + final backgroundRect = Rect.fromPoints(Offset.zero, Offset(size.width, size.height)); + canvas.drawRect(backgroundRect, fill); + levels.forEach((channel, values) { + final color = _getChannelColor(channel); + _drawLevels(canvas, size, color, values); + }); + canvas.drawRect(backgroundRect, borderStroke); + } + + void _drawLevels(Canvas canvas, Size size, Color color, List<double> values) { + if (values.length < 2) return; + + final xFactor = size.width / (values.length - 1); + final yFactor = size.height; + + final polyline = values.mapIndexed((i, v) => Offset(i * xFactor, size.height - v * yFactor)).toList(); + canvas.drawPoints( + PointMode.polygon, + polyline, + Paint() + ..style = PaintingStyle.stroke + ..color = color, + ); + + polyline.add(Offset(size.width, size.height)); + polyline.add(Offset(0, size.height)); + canvas.drawPath( + Path()..addPolygon(polyline, true), + Paint() + ..style = PaintingStyle.fill + ..color = color.withValues(alpha: .5), + ); + } + + Color _getChannelColor(HistogramChannel channel) { + return switch (channel) { + HistogramChannel.red => Colors.red, + HistogramChannel.green => Colors.green, + HistogramChannel.blue => Colors.blue, + HistogramChannel.luminance => Colors.white, + }; + } + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => true; +} diff --git a/lib/widgets/viewer/overlay/locked.dart b/lib/widgets/viewer/overlay/locked.dart new file mode 100644 index 0000000..ed4afe7 --- /dev/null +++ b/lib/widgets/viewer/overlay/locked.dart @@ -0,0 +1,90 @@ +import 'dart:math'; + +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/extensions/media_query.dart'; +import 'package:aves/widgets/common/identity/buttons/overlay_button.dart'; +import 'package:aves/widgets/viewer/controls/notifications.dart'; +import 'package:aves/widgets/viewer/overlay/viewer_buttons.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class ViewerLockedOverlay extends StatefulWidget { + final AnimationController animationController; + final EdgeInsets? viewInsets, viewPadding; + + const ViewerLockedOverlay({ + super.key, + required this.animationController, + this.viewInsets, + this.viewPadding, + }); + + @override + State<StatefulWidget> createState() => _ViewerLockedOverlayState(); +} + +class _ViewerLockedOverlayState extends State<ViewerLockedOverlay> { + late CurvedAnimation _buttonScale; + + @override + void initState() { + super.initState(); + _registerWidget(widget); + } + + @override + void didUpdateWidget(covariant ViewerLockedOverlay oldWidget) { + super.didUpdateWidget(oldWidget); + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + + @override + void dispose() { + _unregisterWidget(widget); + super.dispose(); + } + + void _registerWidget(ViewerLockedOverlay widget) { + _buttonScale = CurvedAnimation( + parent: widget.animationController, + // a little bounce at the top + curve: Curves.easeOutBack, + ); + } + + void _unregisterWidget(ViewerLockedOverlay widget) { + _buttonScale.dispose(); + } + + @override + Widget build(BuildContext context) { + return Selector<MediaQueryData, double>( + selector: (context, mq) => max(mq.effectiveBottomPadding, mq.systemGestureInsets.bottom), + builder: (context, mqPaddingBottom, child) { + final viewInsetsPadding = (widget.viewInsets ?? EdgeInsets.zero) + (widget.viewPadding ?? EdgeInsets.zero); + return Container( + alignment: Alignment.bottomRight, + padding: EdgeInsets.only(bottom: mqPaddingBottom) + const EdgeInsets.all(ViewerButtonRowContent.padding), + child: SafeArea( + top: false, + bottom: false, + minimum: EdgeInsets.only( + left: viewInsetsPadding.left, + right: viewInsetsPadding.right, + ), + child: OverlayButton( + scale: _buttonScale, + child: IconButton( + icon: const Icon(AIcons.viewerUnlock), + onPressed: () => const LockViewNotification(locked: false).dispatch(context), + tooltip: context.l10n.viewerActionUnlock, + ), + ), + ), + ); + }, + ); + } +} diff --git a/lib/widgets/viewer/overlay/minimap.dart b/lib/widgets/viewer/overlay/minimap.dart new file mode 100644 index 0000000..cba86e7 --- /dev/null +++ b/lib/widgets/viewer/overlay/minimap.dart @@ -0,0 +1,150 @@ +import 'dart:math'; +import 'dart:ui'; + +import 'package:aves/model/viewer/view_state.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/editor/transform/controller.dart'; +import 'package:aves/widgets/editor/transform/transformation.dart'; +import 'package:aves/widgets/viewer/overlay/top.dart'; +import 'package:aves_utils/aves_utils.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class Minimap extends StatelessWidget { + final ValueNotifier<ViewState> viewStateNotifier; + + const Minimap({ + super.key, + required this.viewStateNotifier, + }); + + @override + Widget build(BuildContext context) { + return IgnorePointer( + child: ValueListenableBuilder<ViewState>( + valueListenable: viewStateNotifier, + builder: (context, viewState, child) { + final viewportSize = viewState.viewportSize; + final contentSize = viewState.contentSize; + if (viewportSize == null || contentSize == null) return const SizedBox(); + return StreamBuilder<Transformation?>( + stream: context.select<TransformController?, Stream<Transformation?>>((v) => v?.transformationStream ?? Stream.value(null)), + builder: (context, snapshot) { + final transformation = snapshot.data; + return CustomPaint( + painter: _MinimapPainter( + viewportSize: viewportSize, + contentSize: contentSize, + viewCenterOffset: viewState.position, + viewScale: viewState.scale!, + alignmentX: context.isRtl ? 1 : 0, + transformation: transformation, + minimapBorderColor: ViewerTopOverlay.componentBorderColor, + ), + size: const Size.square(ViewerTopOverlay.componentDimension), + ); + }, + ); + }, + ), + ); + } +} + +class _MinimapPainter extends CustomPainter { + final Size contentSize, viewportSize; + final Offset viewCenterOffset; + final double viewScale, alignmentX; + final Transformation? transformation; + final Color minimapBorderColor; + + late final Paint fill, minimapStroke, viewportStroke; + + _MinimapPainter({ + required this.viewportSize, + required this.contentSize, + required this.viewCenterOffset, + required this.viewScale, + required this.alignmentX, + this.transformation, + this.minimapBorderColor = Colors.white, + }) { + fill = Paint() + ..style = PaintingStyle.fill + ..color = const Color(0x33000000); + minimapStroke = Paint() + ..style = PaintingStyle.stroke + ..color = minimapBorderColor; + viewportStroke = Paint() + ..style = PaintingStyle.stroke + ..color = Colors.white; + } + + @override + void paint(Canvas canvas, Size size) { + if (contentSize.width <= 0 || contentSize.height <= 0) return; + + final viewSize = contentSize * viewScale; + if (viewSize.isEmpty) return; + + // hide minimap when image is in full view + if (viewportSize + const Offset(precisionErrorTolerance, precisionErrorTolerance) >= viewSize) return; + + final canvasCenter = size.center(Offset.zero); + final canvasScale = size.longestSide / viewSize.longestSide; + final scaledContentSize = viewSize * canvasScale; + final scaledViewportSize = viewportSize * canvasScale; + + final contentRect = Rect.fromCenter( + center: canvasCenter, + width: scaledContentSize.width, + height: scaledContentSize.height, + ); + final viewportRect = Rect.fromCenter( + center: canvasCenter - viewCenterOffset * canvasScale, + width: min(scaledContentSize.width, scaledViewportSize.width), + height: min(scaledContentSize.height, scaledViewportSize.height), + ); + + canvas.translate(lerpDouble(0, size.width - contentRect.width, alignmentX)!, 0); + + Matrix4? transformMatrix; + if (transformation != null) { + final viewportCenter = viewportRect.center; + final transformOrigin = viewportCenter; + transformMatrix = Matrix4.identity() + ..translate(transformOrigin.dx, transformOrigin.dy) + ..multiply(transformation!.matrix) + ..translate(-transformOrigin.dx, -transformOrigin.dy); + final transViewportCenter = transformMatrix.transformOffset(viewportCenter); + final transContentCenter = transformMatrix.transformOffset(contentRect.center); + + final minimapTranslation = size / 2 + (transViewportCenter - transContentCenter - viewportCenter); + canvas.translate(minimapTranslation.width, minimapTranslation.height); + } else { + canvas.translate((contentRect.width - size.width) / 2, (contentRect.height - size.height) / 2); + } + + canvas.drawRect(viewportRect, fill); + + if (transformMatrix != null) { + canvas.transform(transformMatrix.storage); + _drawContentRect(canvas, contentRect); + transformMatrix.invert(); + canvas.transform(transformMatrix.storage); + } else { + _drawContentRect(canvas, contentRect); + } + + canvas.drawRect(viewportRect, viewportStroke); + } + + void _drawContentRect(Canvas canvas, Rect contentRect) { + canvas.drawRect(contentRect, fill); + canvas.drawRect(contentRect, minimapStroke); + } + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => true; +} diff --git a/lib/widgets/viewer/overlay/multipage.dart b/lib/widgets/viewer/overlay/multipage.dart new file mode 100644 index 0000000..50c775a --- /dev/null +++ b/lib/widgets/viewer/overlay/multipage.dart @@ -0,0 +1,87 @@ +import 'package:aves/model/multipage.dart'; +import 'package:aves/widgets/common/thumbnail/scroller.dart'; +import 'package:aves/widgets/viewer/multipage/controller.dart'; +import 'package:aves/widgets/viewer/view/conductor.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class MultiPageOverlay extends StatefulWidget { + final MultiPageController controller; + final double availableWidth; + final bool scrollable; + + const MultiPageOverlay({ + super.key, + required this.controller, + required this.availableWidth, + required this.scrollable, + }); + + @override + State<MultiPageOverlay> createState() => _MultiPageOverlayState(); +} + +class _MultiPageOverlayState extends State<MultiPageOverlay> { + int? _previousPage; + + MultiPageController get controller => widget.controller; + + @override + void initState() { + super.initState(); + _registerWidget(widget); + } + + @override + void didUpdateWidget(covariant MultiPageOverlay oldWidget) { + super.didUpdateWidget(oldWidget); + + if (oldWidget.controller != controller) { + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + } + + @override + void dispose() { + _unregisterWidget(widget); + super.dispose(); + } + + void _registerWidget(MultiPageOverlay widget) { + widget.controller.pageNotifier.addListener(_onPageChanged); + } + + void _unregisterWidget(MultiPageOverlay widget) { + widget.controller.pageNotifier.removeListener(_onPageChanged); + } + + @override + Widget build(BuildContext context) { + return StreamBuilder<MultiPageInfo?>( + stream: controller.infoStream, + builder: (context, snapshot) { + final multiPageInfo = controller.info; + return ThumbnailScroller( + key: ValueKey(multiPageInfo), + availableWidth: widget.availableWidth, + entryCount: multiPageInfo?.pageCount ?? 0, + entryBuilder: (page) => multiPageInfo?.getPageEntryByIndex(page), + indexNotifier: controller.pageNotifier, + scrollable: widget.scrollable, + ); + }, + ); + } + + void _onPageChanged() { + if (_previousPage != null) { + final info = controller.info; + if (info != null) { + final oldPageEntry = info.getPageEntryByIndex(_previousPage); + context.read<ViewStateConductor>().reset(oldPageEntry); + } + } + _previousPage = controller.page; + } +} diff --git a/lib/widgets/viewer/overlay/panorama.dart b/lib/widgets/viewer/overlay/panorama.dart new file mode 100644 index 0000000..7c0af50 --- /dev/null +++ b/lib/widgets/viewer/overlay/panorama.dart @@ -0,0 +1,52 @@ +import 'dart:async'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/widgets/common/action_mixins/feedback.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/buttons/overlay_button.dart'; +import 'package:aves/widgets/viewer/overlay/bottom.dart'; +import 'package:aves/widgets/viewer/panorama_page.dart'; +import 'package:flutter/material.dart'; + +class PanoramaOverlay extends StatelessWidget with FeedbackMixin { + final AvesEntry entry; + final Animation<double> scale; + + const PanoramaOverlay({ + super.key, + required this.entry, + required this.scale, + }); + + @override + Widget build(BuildContext context) { + return Row( + textDirection: ViewerBottomOverlay.actionsDirection, + children: [ + const Spacer(), + ScalingOverlayTextButton( + scale: scale, + onPressed: () async { + final info = await metadataFetchService.getPanoramaInfo(entry); + if (info == null) { + showFeedback(context, FeedbackType.warn, context.l10n.genericFailureFeedback); + } + if (info != null) { + unawaited(Navigator.maybeOf(context)?.push( + MaterialPageRoute( + settings: const RouteSettings(name: PanoramaPage.routeName), + builder: (context) => PanoramaPage( + entry: entry, + info: info, + ), + ), + )); + } + }, + child: Text(context.l10n.viewerOpenPanoramaButtonLabel), + ), + ], + ); + } +} diff --git a/lib/widgets/viewer/overlay/selection_button.dart b/lib/widgets/viewer/overlay/selection_button.dart new file mode 100644 index 0000000..d7f9f94 --- /dev/null +++ b/lib/widgets/viewer/overlay/selection_button.dart @@ -0,0 +1,86 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/selection.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/theme/text.dart'; +import 'package:aves/widgets/common/basic/text/animated_diff.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/buttons/overlay_button.dart'; +import 'package:aves/widgets/viewer/overlay/bottom.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class SelectionButton extends StatelessWidget { + final AvesEntry mainEntry; + final Animation<double> scale; + + static const double padding = 8; + + const SelectionButton({ + super.key, + required this.mainEntry, + required this.scale, + }); + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + final selection = context.read<Selection<AvesEntry>>(); + final duration = context.select<DurationsData, Duration>((v) => v.formTransition); + return SafeArea( + top: false, + bottom: false, + child: Padding( + padding: const EdgeInsets.only(left: padding, right: padding, bottom: padding), + child: Row( + mainAxisSize: MainAxisSize.min, + textDirection: ViewerBottomOverlay.actionsDirection, + children: [ + const Spacer(), + ScalingOverlayTextButton( + scale: scale, + onPressed: () => selection.toggleSelection(mainEntry), + child: Selector<Selection<AvesEntry>?, int>( + selector: (context, selection) => selection?.selectedItems.length ?? 0, + builder: (context, count, child) { + return Row( + mainAxisSize: MainAxisSize.min, + textDirection: ViewerBottomOverlay.actionsDirection, + children: [ + AnimatedDiffText( + count == 0 ? l10n.collectionSelectPageTitle : l10n.itemCount(count), + duration: duration, + ), + const Padding( + padding: EdgeInsets.symmetric(horizontal: 8), + child: Text(AText.separator), + ), + Selector<Selection<AvesEntry>, bool>( + selector: (context, selection) => selection.isSelected({mainEntry}), + builder: (context, isSelected, child) { + return AnimatedSwitcher( + duration: duration, + switchInCurve: Curves.easeOutBack, + switchOutCurve: Curves.easeOutBack, + transitionBuilder: (child, animation) => ScaleTransition( + scale: animation, + child: child, + ), + child: Icon( + isSelected ? AIcons.selected : AIcons.unselected, + key: ValueKey(isSelected), + ), + ); + }, + ), + ], + ); + }, + ), + ), + ], + ), + ), + ); + } +} diff --git a/lib/widgets/viewer/overlay/slideshow_buttons.dart b/lib/widgets/viewer/overlay/slideshow_buttons.dart new file mode 100644 index 0000000..6d4c7b1 --- /dev/null +++ b/lib/widgets/viewer/overlay/slideshow_buttons.dart @@ -0,0 +1,212 @@ +import 'dart:math'; + +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/extensions/media_query.dart'; +import 'package:aves/widgets/common/identity/buttons/captioned_button.dart'; +import 'package:aves/widgets/common/identity/buttons/overlay_button.dart'; +import 'package:aves/widgets/viewer/controls/intents.dart'; +import 'package:aves/widgets/viewer/controls/notifications.dart'; +import 'package:aves/widgets/viewer/overlay/bottom.dart'; +import 'package:aves/widgets/viewer/overlay/viewer_buttons.dart'; +import 'package:aves/widgets/viewer/slideshow_page.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:provider/provider.dart'; + +class SlideshowBottomOverlay extends StatelessWidget { + final AnimationController animationController; + final Size availableSize; + final EdgeInsets? viewInsets, viewPadding; + + const SlideshowBottomOverlay({ + super.key, + required this.animationController, + required this.availableSize, + this.viewInsets, + this.viewPadding, + }); + + @override + Widget build(BuildContext context) { + return Selector<MediaQueryData, double>( + selector: (context, mq) => max(mq.effectiveBottomPadding, mq.systemGestureInsets.bottom), + builder: (context, mqPaddingBottom, child) { + return Padding( + padding: EdgeInsets.only(bottom: mqPaddingBottom), + child: child, + ); + }, + child: SlideshowButtons( + availableSize: availableSize, + viewInsets: viewInsets, + viewPadding: viewPadding, + animationController: animationController, + ), + ); + } +} + +class SlideshowButtons extends StatefulWidget { + final Size availableSize; + final EdgeInsets? viewInsets, viewPadding; + final AnimationController animationController; + + const SlideshowButtons({ + super.key, + required this.availableSize, + required this.viewInsets, + required this.viewPadding, + required this.animationController, + }); + + @override + State<SlideshowButtons> createState() => _SlideshowButtonsState(); +} + +class _SlideshowButtonsState extends State<SlideshowButtons> { + final FocusScopeNode _buttonRowFocusScopeNode = FocusScopeNode(); + late CurvedAnimation _buttonScale; + + static const List<SlideshowAction> _actions = [ + SlideshowAction.resume, + SlideshowAction.showInCollection, + SlideshowAction.cast, + SlideshowAction.settings, + ]; + static const double _padding = ViewerButtonRowContent.padding; + + @override + void initState() { + super.initState(); + _registerWidget(widget); + WidgetsBinding.instance.addPostFrameCallback((_) => _requestFocus()); + } + + @override + void didUpdateWidget(covariant SlideshowButtons oldWidget) { + super.didUpdateWidget(oldWidget); + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + + @override + void dispose() { + _unregisterWidget(widget); + _buttonRowFocusScopeNode.dispose(); + super.dispose(); + } + + void _registerWidget(SlideshowButtons widget) { + _buttonScale = CurvedAnimation( + parent: widget.animationController, + // a little bounce at the top + curve: Curves.easeOutBack, + ); + } + + void _unregisterWidget(SlideshowButtons widget) { + _buttonScale.dispose(); + } + + @override + Widget build(BuildContext context) { + final viewInsetsPadding = (widget.viewInsets ?? EdgeInsets.zero) + (widget.viewPadding ?? EdgeInsets.zero); + final viewerButtonRow = FocusableActionDetector( + focusNode: _buttonRowFocusScopeNode, + shortcuts: settings.useTvLayout + ? const { + SingleActivator(LogicalKeyboardKey.arrowUp): TvShowLessInfoIntent(), + } + : null, + actions: { + TvShowLessInfoIntent: CallbackAction<Intent>(onInvoke: (intent) => TvShowLessInfoNotification().dispatch(context)), + }, + child: SafeArea( + top: false, + bottom: false, + minimum: EdgeInsets.only( + left: viewInsetsPadding.left, + right: viewInsetsPadding.right, + ), + child: _buildButtons(context), + ), + ); + + final availableWidth = widget.availableSize.width; + return SizedBox( + width: availableWidth, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + viewerButtonRow, + ], + ), + ); + } + + Widget _buildButtons(BuildContext context) { + if (settings.useTvLayout) { + return _buildTvButtonRowContent(context); + } + + return SafeArea( + top: false, + bottom: false, + child: Padding( + padding: const EdgeInsets.only(left: _padding / 2, right: _padding / 2, bottom: _padding), + child: Row( + textDirection: ViewerBottomOverlay.actionsDirection, + children: [ + const Spacer(), + ..._actions.map((action) => _buildOverlayButton(context, action)), + ], + ), + ), + ); + } + + Widget _buildOverlayButton(BuildContext context, SlideshowAction action) { + return Padding( + padding: const EdgeInsets.symmetric(horizontal: _padding / 2), + child: OverlayButton( + scale: _buttonScale, + child: IconButton( + icon: action.getIcon(), + onPressed: () => _onAction(context, action), + tooltip: action.getText(context), + ), + ), + ); + } + + Widget _buildTvButtonRowContent(BuildContext context) { + return Row( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.start, + textDirection: ViewerBottomOverlay.actionsDirection, + children: _actions.map((action) { + return CaptionedButton( + scale: _buttonScale, + icon: action.getIcon(), + caption: action.getText(context), + onPressed: () => _onAction(context, action), + ); + }).toList(), + ); + } + + void _onAction(BuildContext context, SlideshowAction action) { + switch (action) { + case SlideshowAction.cast: + const CastNotification(true).dispatch(context); + default: + SlideshowActionNotification(action).dispatch(context); + } + } + + void _requestFocus() => _buttonRowFocusScopeNode.children.firstOrNull?.requestFocus(); +} diff --git a/lib/widgets/viewer/overlay/thumbnail_preview.dart b/lib/widgets/viewer/overlay/thumbnail_preview.dart new file mode 100644 index 0000000..74b4502 --- /dev/null +++ b/lib/widgets/viewer/overlay/thumbnail_preview.dart @@ -0,0 +1,68 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/widgets/common/thumbnail/scroller.dart'; +import 'package:aves/widgets/viewer/controls/notifications.dart'; +import 'package:flutter/material.dart'; + +class ViewerThumbnailPreview extends StatefulWidget { + final List<AvesEntry> entries; + final int displayedIndex; + final double availableWidth; + + const ViewerThumbnailPreview({ + super.key, + required this.entries, + required this.displayedIndex, + required this.availableWidth, + }); + + @override + State<ViewerThumbnailPreview> createState() => _ViewerThumbnailPreviewState(); + + static double get preferredHeight => ThumbnailScroller.preferredHeight; +} + +class _ViewerThumbnailPreviewState extends State<ViewerThumbnailPreview> { + late final ValueNotifier<int> _entryIndexNotifier; + + List<AvesEntry> get entries => widget.entries; + + int get entryCount => entries.length; + + @override + void initState() { + super.initState(); + _entryIndexNotifier = ValueNotifier(widget.displayedIndex); + _entryIndexNotifier.addListener(_onScrollerIndexChanged); + } + + @override + void didUpdateWidget(covariant ViewerThumbnailPreview oldWidget) { + super.didUpdateWidget(oldWidget); + + if (oldWidget.displayedIndex != widget.displayedIndex) { + _entryIndexNotifier.value = widget.displayedIndex; + } + } + + @override + void dispose() { + _entryIndexNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return ThumbnailScroller( + availableWidth: widget.availableWidth, + entryCount: entryCount, + entryBuilder: (index) => 0 <= index && index < entryCount ? entries[index] : null, + indexNotifier: _entryIndexNotifier, + onTap: (index) => ShowEntryNotification(animate: false, index: index).dispatch(context), + ); + } + + void _onScrollerIndexChanged() { + if (!mounted) return; + ShowEntryNotification(animate: false, index: _entryIndexNotifier.value).dispatch(context); + } +} diff --git a/lib/widgets/viewer/overlay/top.dart b/lib/widgets/viewer/overlay/top.dart new file mode 100644 index 0000000..669ce41 --- /dev/null +++ b/lib/widgets/viewer/overlay/top.dart @@ -0,0 +1,211 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/multipage.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/viewer/view_state.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/fx/blurred.dart'; +import 'package:aves/widgets/common/fx/borders.dart'; +import 'package:aves/widgets/viewer/multipage/conductor.dart'; +import 'package:aves/widgets/viewer/overlay/details/details.dart'; +import 'package:aves/widgets/viewer/overlay/histogram.dart'; +import 'package:aves/widgets/viewer/overlay/minimap.dart'; +import 'package:aves/widgets/viewer/page_entry_builder.dart'; +import 'package:aves/widgets/viewer/view/conductor.dart'; +import 'package:aves/widgets/viewer/view/controller.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class ViewerTopOverlay extends StatelessWidget { + final List<AvesEntry> entries; + final int index; + final AvesEntry mainEntry; + final Animation<double> scale; + final bool hasCollection; + final ValueNotifier<bool> expandedNotifier; + final Size availableSize; + final EdgeInsets? viewInsets, viewPadding; + + static const Color componentBorderColor = Colors.white30; + static const double componentDimension = 96; + + const ViewerTopOverlay({ + super.key, + required this.entries, + required this.index, + required this.mainEntry, + required this.scale, + required this.hasCollection, + required this.expandedNotifier, + required this.availableSize, + required this.viewInsets, + required this.viewPadding, + }); + + @override + Widget build(BuildContext context) { + final multiPageController = mainEntry.isMultiPage ? context.read<MultiPageConductor>().getController(mainEntry) : null; + return PageEntryBuilder( + multiPageController: multiPageController, + builder: (pageEntry) { + pageEntry ??= mainEntry; + + final showInfo = settings.showOverlayInfo; + + final viewStateConductor = context.read<ViewStateConductor>(); + final viewStateNotifier = viewStateConductor.getOrCreateController(pageEntry).viewStateNotifier; + + final blurred = settings.enableBlurEffect; + final viewInsetsPadding = (viewInsets ?? EdgeInsets.zero) + (viewPadding ?? EdgeInsets.zero); + + Widget _decorateCornerChild(Widget child) => Padding( + padding: const EdgeInsets.symmetric(horizontal: 8) + const EdgeInsets.only(top: 8), + child: FadeTransition( + opacity: scale, + child: child, + ), + ); + + final startCornerChildren = [ + if (settings.showOverlayZoomLevel) + ZoomLevelIndicator( + viewStateNotifier: viewStateNotifier, + ), + if (settings.showOverlayMinimap) + Minimap( + viewStateNotifier: viewStateNotifier, + ), + ]; + + final endCornerChildren = [ + if (settings.overlayHistogramStyle != OverlayHistogramStyle.none) + Selector<ViewStateConductor, ViewStateController>( + selector: (context, vsc) => vsc.getOrCreateController(pageEntry!), + builder: (context, viewStateController, child) { + return ValueListenableBuilder<ImageProvider?>( + valueListenable: viewStateController.fullImageNotifier, + builder: (context, fullImage, child) { + if (fullImage == null || pageEntry == null) return const SizedBox(); + return ImageHistogram( + viewStateController: viewStateController, + image: fullImage, + ); + }, + ); + }, + ), + ]; + + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (showInfo) + GestureDetector( + onTap: () => expandedNotifier.value = !expandedNotifier.value, + child: BlurredRect( + enabled: blurred, + child: Container( + color: Themes.overlayBackgroundColor(brightness: Theme.of(context).brightness, blurred: blurred), + child: SafeArea( + bottom: false, + minimum: EdgeInsets.only( + left: viewInsetsPadding.left, + top: viewInsetsPadding.top, + right: viewInsetsPadding.right, + ), + child: ViewerDetailOverlay( + index: index, + entries: entries, + hasCollection: hasCollection, + multiPageController: multiPageController, + expandedNotifier: expandedNotifier, + availableSize: availableSize, + ), + ), + ), + ), + ), + SafeArea( + top: !showInfo, + minimum: EdgeInsets.only( + left: viewInsetsPadding.left, + right: viewInsetsPadding.right, + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (startCornerChildren.isNotEmpty) + Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: startCornerChildren.map(_decorateCornerChild).toList(), + ), + const Spacer(), + if (endCornerChildren.isNotEmpty) + Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: endCornerChildren.map(_decorateCornerChild).toList(), + ), + ], + ), + ), + ], + ); + }, + ); + } +} + +class ZoomLevelIndicator extends StatelessWidget { + final ValueNotifier<ViewState> viewStateNotifier; + + const ZoomLevelIndicator({ + super.key, + required this.viewStateNotifier, + }); + + @override + Widget build(BuildContext context) { + final blurred = settings.enableBlurEffect; + final border = AvesBorder.border( + context, + width: AvesBorder.curvedBorderWidth(context), + ); + final borderRadius = BorderRadius.circular(4); + final zoomScaleFactor = MediaQuery.devicePixelRatioOf(context) * 100; + + return IgnorePointer( + child: BlurredRRect( + enabled: blurred, + borderRadius: borderRadius, + child: Material( + type: MaterialType.button, + borderRadius: borderRadius, + color: Themes.overlayBackgroundColor(brightness: Theme.of(context).brightness, blurred: blurred), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + foregroundDecoration: BoxDecoration( + border: border, + borderRadius: borderRadius, + ), + child: ValueListenableBuilder<ViewState>( + valueListenable: viewStateNotifier, + builder: (context, viewState, child) { + final zoom = ((viewState.scale ?? 0) * zoomScaleFactor).round(); + return Text( + '$zoom${context.l10n.lengthUnitPercent}', + style: Theme.of(context).textTheme.bodyMedium!.copyWith( + shadows: ViewerDetailOverlayContent.shadows(context), + ), + ); + }, + ), + ), + ), + ), + ); + } +} diff --git a/lib/widgets/viewer/overlay/video/ab_repeat.dart b/lib/widgets/viewer/overlay/video/ab_repeat.dart new file mode 100644 index 0000000..4b7ee76 --- /dev/null +++ b/lib/widgets/viewer/overlay/video/ab_repeat.dart @@ -0,0 +1,80 @@ +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/buttons/overlay_button.dart'; +import 'package:aves/widgets/viewer/overlay/bottom.dart'; +import 'package:aves_video/aves_video.dart'; +import 'package:flutter/material.dart'; + +class VideoABRepeatOverlay extends StatefulWidget { + final AvesVideoController? controller; + final Animation<double> scale; + + const VideoABRepeatOverlay({ + super.key, + required this.controller, + required this.scale, + }); + + @override + State<StatefulWidget> createState() => _VideoABRepeatOverlayState(); +} + +class _VideoABRepeatOverlayState extends State<VideoABRepeatOverlay> { + Animation<double> get scale => widget.scale; + + AvesVideoController? get controller => widget.controller; + + ValueNotifier<ABRepeat?> get abRepeatNotifier => controller?.abRepeatNotifier ?? ValueNotifier(null); + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + + return ValueListenableBuilder<ABRepeat?>( + valueListenable: abRepeatNotifier, + builder: (context, abRepeat, child) { + if (abRepeat == null) return const SizedBox(); + + Widget boundButton; + if (abRepeat.start == null) { + boundButton = IconButton( + icon: Icon(AIcons.setBoundStart), + onPressed: controller?.setABRepeatStart, + tooltip: l10n.videoRepeatActionSetStart, + ); + } else if (abRepeat.end == null) { + boundButton = IconButton( + icon: Icon(AIcons.setBoundEnd), + onPressed: controller?.setABRepeatEnd, + tooltip: l10n.videoRepeatActionSetEnd, + ); + } else { + boundButton = IconButton( + icon: Icon(AIcons.resetBounds), + onPressed: controller?.resetABRepeat, + tooltip: l10n.resetTooltip, + ); + } + return Row( + textDirection: ViewerBottomOverlay.actionsDirection, + children: [ + const Spacer(), + OverlayButton( + scale: scale, + child: boundButton, + ), + const SizedBox(width: 8), + OverlayButton( + scale: scale, + child: IconButton( + icon: Icon(AIcons.repeatOff), + onPressed: () => controller?.toggleABRepeat(), + tooltip: l10n.stopTooltip, + ), + ), + ], + ); + }, + ); + } +} diff --git a/lib/widgets/viewer/overlay/video/controls.dart b/lib/widgets/viewer/overlay/video/controls.dart new file mode 100644 index 0000000..f2929db --- /dev/null +++ b/lib/widgets/viewer/overlay/video/controls.dart @@ -0,0 +1,94 @@ +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/action_controls/togglers/play.dart'; +import 'package:aves/widgets/common/identity/buttons/overlay_button.dart'; +import 'package:aves/widgets/viewer/overlay/bottom.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:aves_video/aves_video.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class VideoControlRow extends StatelessWidget { + final AvesVideoController? controller; + final Animation<double> scale; + final bool canOpenVideoPlayer; + final Function(EntryAction value) onActionSelected; + + static const double padding = 8; + static const Radius radius = Radius.circular(123); + + const VideoControlRow({ + super.key, + this.controller, + this.scale = kAlwaysCompleteAnimation, + this.canOpenVideoPlayer = true, + required this.onActionSelected, + }); + + @override + Widget build(BuildContext context) { + return Selector<Settings, List<EntryAction>>( + selector: (context, s) => s.videoControlActions, + builder: (context, actions, child) { + return Padding( + padding: EdgeInsets.only(left: actions.isEmpty ? 0 : padding), + child: Row( + mainAxisSize: MainAxisSize.min, + textDirection: ViewerBottomOverlay.actionsDirection, + children: actions.map((action) { + // null radius yields a circular button + BorderRadius? borderRadius; + if (actions.length > 1) { + // zero radius yields a square button + borderRadius = BorderRadius.zero; + if (action == actions.first) { + borderRadius = const BorderRadius.horizontal(left: radius); + } else if (action == actions.last) { + borderRadius = const BorderRadius.horizontal(right: radius); + } + } + return _buildOverlayButton(context, action, borderRadius); + }).toList(), + ), + ); + }, + ); + } + + Widget _buildOverlayButton( + BuildContext context, + EntryAction action, + BorderRadius? borderRadius, + ) { + Widget child; + if (action == EntryAction.videoTogglePlay) { + child = PlayToggler( + controller: controller, + onPressed: () => onActionSelected(action), + ); + } else { + final enabled = action == EntryAction.openVideoPlayer ? canOpenVideoPlayer : true; + child = IconButton( + icon: action.getIcon(), + onPressed: enabled ? () => onActionSelected(action) : null, + tooltip: action.getText(context), + ); + } + + if (borderRadius != null) { + child = Padding( + padding: EdgeInsets.only( + left: borderRadius.topLeft.x > 0 ? padding / 3 : 0, + right: borderRadius.topRight.x > 0 ? padding / 3 : 0, + ), + child: child, + ); + } + + return OverlayButton( + scale: scale, + borderRadius: borderRadius, + child: child, + ); + } +} diff --git a/lib/widgets/viewer/overlay/video/progress_bar.dart b/lib/widgets/viewer/overlay/video/progress_bar.dart new file mode 100644 index 0000000..4f11ca3 --- /dev/null +++ b/lib/widgets/viewer/overlay/video/progress_bar.dart @@ -0,0 +1,223 @@ +import 'dart:async'; + +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/ref/locales.dart'; +import 'package:aves/theme/format.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/theme/styles.dart'; +import 'package:aves/theme/themes.dart'; +import 'package:aves/widgets/common/extensions/theme.dart'; +import 'package:aves/widgets/common/fx/blurred.dart'; +import 'package:aves/widgets/common/fx/borders.dart'; +import 'package:aves_video/aves_video.dart'; +import 'package:decorated_icon/decorated_icon.dart'; +import 'package:flutter/material.dart'; + +class VideoProgressBar extends StatefulWidget { + final AvesVideoController? controller; + final Animation<double> scale; + + const VideoProgressBar({ + super.key, + required this.controller, + required this.scale, + }); + + @override + State<VideoProgressBar> createState() => _VideoProgressBarState(); +} + +class _VideoProgressBarState extends State<VideoProgressBar> { + final GlobalKey _progressBarKey = GlobalKey(debugLabel: 'video-progress-bar'); + bool _playingOnDragStart = false; + + static const double radius = 123; + + AvesVideoController? get controller => widget.controller; + + Stream<int> get positionStream => controller?.positionStream ?? Stream.value(0); + + bool get isPlaying => controller?.isPlaying ?? false; + + ValueNotifier<ABRepeat?> get abRepeatNotifier => controller?.abRepeatNotifier ?? ValueNotifier(null); + + @override + Widget build(BuildContext context) { + final blurred = settings.enableBlurEffect; + final theme = Theme.of(context); + return SizeTransition( + sizeFactor: widget.scale, + child: BlurredRRect.all( + enabled: blurred, + borderRadius: radius, + child: GestureDetector( + onTapDown: (details) { + _seekFromTap(details.globalPosition); + }, + onHorizontalDragStart: (details) { + _playingOnDragStart = isPlaying; + if (_playingOnDragStart) controller?.pause(); + }, + onHorizontalDragUpdate: (details) { + _seekFromTap(details.globalPosition); + }, + onHorizontalDragEnd: (details) { + if (_playingOnDragStart) controller?.play(); + }, + child: ConstrainedBox( + constraints: const BoxConstraints(minHeight: kMinInteractiveDimension), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 16), + decoration: BoxDecoration( + color: Themes.overlayBackgroundColor(brightness: theme.brightness, blurred: blurred), + border: AvesBorder.border(context), + borderRadius: const BorderRadius.all(Radius.circular(radius)), + ), + child: MediaQuery( + data: MediaQuery.of(context).copyWith( + textScaler: TextScaler.noScaling, + ), + child: ValueListenableBuilder<ABRepeat?>( + valueListenable: abRepeatNotifier, + builder: (context, abRepeat, child) { + return Stack( + fit: StackFit.passthrough, + children: [ + if (abRepeat != null) ...[ + _buildABRepeatMark(context, abRepeat.start), + _buildABRepeatMark(context, abRepeat.end), + ], + Container( + key: _progressBarKey, + alignment: Alignment.center, + padding: const EdgeInsets.symmetric(vertical: 4), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Row( + children: [ + StreamBuilder<int>( + stream: positionStream, + builder: (context, snapshot) { + // do not use stream snapshot because it is obsolete when switching between videos + final position = controller?.currentPosition.floor() ?? 0; + return _buildText(formatFriendlyDuration(Duration(milliseconds: position))); + }), + const Spacer(), + _buildText(formatFriendlyDuration(Duration(milliseconds: controller?.duration ?? 0))), + ], + ), + ClipRRect( + borderRadius: const BorderRadius.all(Radius.circular(4)), + child: Directionality( + textDirection: videoPlaybackDirection, + child: StreamBuilder<int>( + stream: positionStream, + builder: (context, snapshot) { + // do not use stream snapshot because it is obsolete when switching between videos + var progress = controller?.progress ?? 0.0; + if (!progress.isFinite) progress = 0.0; + return LinearProgressIndicator( + value: progress, + backgroundColor: theme.colorScheme.onSurface.withValues(alpha: .2), + ); + }), + ), + ), + Row( + children: [ + _buildSpeedIndicator(), + _buildMuteIndicator(), + // fake text below to match the height of the text above and center the whole thing + _buildText(''), + ], + ), + ], + ), + ), + ], + ); + }, + ), + ), + ), + ), + ), + ), + ); + } + + Widget _buildText(String text) { + return Text( + text, + style: TextStyle( + shadows: Theme.of(context).isDark ? AStyles.embossShadows : null, + ), + strutStyle: const StrutStyle( + forceStrutHeight: true, + ), + ); + } + + Widget _buildABRepeatMark(BuildContext context, int? position) { + if (controller == null || position == null) return const SizedBox(); + return Positioned( + left: _progressToDx(position / controller!.duration), + top: 0, + bottom: 0, + child: Container( + decoration: BoxDecoration( + border: Border(left: AvesBorder.straightSide(context, width: 2)), + ), + ), + ); + } + + Widget _buildSpeedIndicator() => StreamBuilder<double>( + stream: controller?.speedStream ?? Stream.value(1.0), + builder: (context, snapshot) { + final speed = controller?.speed ?? 1.0; + return speed != 1 + ? Padding( + padding: const EdgeInsetsDirectional.only(end: 8), + child: _buildText('x$speed'), + ) + : const SizedBox(); + }, + ); + + Widget _buildMuteIndicator() => StreamBuilder<double>( + stream: controller?.volumeStream ?? Stream.value(1.0), + builder: (context, snapshot) { + final textScaler = MediaQuery.textScalerOf(context); + final isMuted = controller?.isMuted ?? false; + return isMuted + ? Padding( + padding: const EdgeInsetsDirectional.only(end: 8), + child: DecoratedIcon( + AIcons.mute, + size: textScaler.scale(16), + shadows: Theme.of(context).isDark ? AStyles.embossShadows : null, + ), + ) + : const SizedBox(); + }, + ); + + RenderBox? _getProgressBarRenderBox() { + return _progressBarKey.currentContext?.findRenderObject() as RenderBox?; + } + + void _seekFromTap(Offset globalPosition) async { + final box = _getProgressBarRenderBox(); + if (controller == null || box == null) return; + + final dx = box.globalToLocal(globalPosition).dx; + await controller!.seekToProgress(dx / box.size.width); + } + + double? _progressToDx(double progress) { + final box = _getProgressBarRenderBox(); + return box != null && box.hasSize ? progress * box.size.width : null; + } +} diff --git a/lib/widgets/viewer/overlay/video/video.dart b/lib/widgets/viewer/overlay/video/video.dart new file mode 100644 index 0000000..02ad52a --- /dev/null +++ b/lib/widgets/viewer/overlay/video/video.dart @@ -0,0 +1,93 @@ +import 'dart:async'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/identity/buttons/overlay_button.dart'; +import 'package:aves/widgets/viewer/overlay/bottom.dart'; +import 'package:aves/widgets/viewer/overlay/video/ab_repeat.dart'; +import 'package:aves/widgets/viewer/overlay/video/controls.dart'; +import 'package:aves/widgets/viewer/overlay/video/progress_bar.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:aves_video/aves_video.dart'; +import 'package:flutter/material.dart'; + +class VideoControlOverlay extends StatefulWidget { + final AvesEntry entry; + final AvesVideoController? controller; + final Animation<double> scale; + final Function(EntryAction value) onActionSelected; + + const VideoControlOverlay({ + super.key, + required this.entry, + required this.controller, + required this.scale, + required this.onActionSelected, + }); + + @override + State<StatefulWidget> createState() => _VideoControlOverlayState(); +} + +class _VideoControlOverlayState extends State<VideoControlOverlay> with SingleTickerProviderStateMixin { + AvesEntry get entry => widget.entry; + + Animation<double> get scale => widget.scale; + + AvesVideoController? get controller => widget.controller; + + Stream<VideoStatus> get statusStream => controller?.statusStream ?? Stream.value(VideoStatus.idle); + + @override + Widget build(BuildContext context) { + return StreamBuilder<VideoStatus>( + stream: statusStream, + builder: (context, snapshot) { + // do not use stream snapshot because it is obsolete when switching between videos + final status = controller?.status ?? VideoStatus.idle; + + if (status == VideoStatus.error) { + const action = EntryAction.openVideoPlayer; + return Align( + alignment: Alignment.centerRight, + child: OverlayButton( + scale: scale, + child: IconButton( + icon: action.getIcon(), + onPressed: entry.trashed ? null : () => widget.onActionSelected(action), + tooltip: action.getText(context), + ), + ), + ); + } + + return Column( + children: [ + VideoABRepeatOverlay( + controller: controller, + scale: scale, + ), + const SizedBox(height: 8), + Row( + textDirection: ViewerBottomOverlay.actionsDirection, + children: [ + Expanded( + child: VideoProgressBar( + controller: controller, + scale: scale, + ), + ), + VideoControlRow( + controller: controller, + scale: scale, + canOpenVideoPlayer: !entry.trashed, + onActionSelected: widget.onActionSelected, + ), + ], + ), + ], + ); + }, + ); + } +} diff --git a/lib/widgets/viewer/overlay/viewer_buttons.dart b/lib/widgets/viewer/overlay/viewer_buttons.dart new file mode 100644 index 0000000..d15a8f4 --- /dev/null +++ b/lib/widgets/viewer/overlay/viewer_buttons.dart @@ -0,0 +1,540 @@ +import 'dart:math'; + +import 'package:aves/app_mode.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/multipage.dart'; +import 'package:aves/model/settings/enums/accessibility_animations.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/common/action_controls/quick_choosers/move_button.dart'; +import 'package:aves/widgets/common/action_controls/quick_choosers/rate_button.dart'; +import 'package:aves/widgets/common/action_controls/quick_choosers/share_button.dart'; +import 'package:aves/widgets/common/action_controls/quick_choosers/tag_button.dart'; +import 'package:aves/widgets/common/action_controls/togglers/favourite.dart'; +import 'package:aves/widgets/common/action_controls/togglers/mute.dart'; +import 'package:aves/widgets/common/action_controls/togglers/play.dart'; +import 'package:aves/widgets/common/basic/font_size_icon_theme.dart'; +import 'package:aves/widgets/common/basic/popup/container.dart'; +import 'package:aves/widgets/common/basic/popup/expansion_panel.dart'; +import 'package:aves/widgets/common/basic/popup/menu_row.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/buttons/captioned_button.dart'; +import 'package:aves/widgets/common/identity/buttons/overlay_button.dart'; +import 'package:aves/widgets/viewer/action/entry_action_delegate.dart'; +import 'package:aves/widgets/viewer/controls/notifications.dart'; +import 'package:aves/widgets/viewer/overlay/bottom.dart'; +import 'package:aves/widgets/viewer/video/conductor.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:aves_utils/aves_utils.dart'; +import 'package:aves_video/aves_video.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:provider/provider.dart'; + +class ViewerButtons extends StatelessWidget { + final AvesEntry mainEntry, pageEntry; + final CollectionLens? collection; + final Animation<double> scale; + + static const double outerPadding = 8; + static const double innerPadding = 8; + + static double preferredHeight(BuildContext context) => _buttonSize(context) + ViewerButtonRowContent.padding; + + static double _buttonSize(BuildContext context) => OverlayButton.getSize(context); + + const ViewerButtons({ + super.key, + required this.mainEntry, + required this.pageEntry, + required this.collection, + required this.scale, + }); + + @override + Widget build(BuildContext context) { + final actionDelegate = EntryActionDelegate(mainEntry, pageEntry, collection); + + if (settings.useTvLayout) { + return _TvButtonRowContent( + actionDelegate: actionDelegate, + scale: scale, + mainEntry: mainEntry, + pageEntry: pageEntry, + ); + } + + final appMode = context.watch<ValueNotifier<AppMode>>().value; + bool isVisible(EntryAction action) => actionDelegate.isVisible( + appMode: appMode, + action: action, + ); + + final trashed = mainEntry.trashed; + return SafeArea( + top: false, + bottom: false, + child: LayoutBuilder( + builder: (context, constraints) { + final buttonWidth = _buttonSize(context); + final availableCount = ((constraints.maxWidth - outerPadding * 2) / (buttonWidth + innerPadding)).floor(); + return Selector<Settings, bool>( + selector: (context, s) => s.isRotationLocked, + builder: (context, s, child) { + final quickActions = (trashed ? EntryActions.trashed : settings.viewerQuickActions).where(isVisible).where(actionDelegate.canApply).take(max(0, availableCount - 1)).toList(); + List<EntryAction> getMenuActions(List<EntryAction> categoryActions) { + return categoryActions.where((action) => !quickActions.contains(action)).where(isVisible).toList(); + } + + return ViewerButtonRowContent( + actionDelegate: actionDelegate, + quickActions: quickActions, + topLevelActions: getMenuActions(EntryActions.topLevel), + exportActions: getMenuActions(EntryActions.export), + videoActions: getMenuActions(EntryActions.video), + scale: scale, + mainEntry: mainEntry, + pageEntry: pageEntry, + ); + }, + ); + }, + ), + ); + } +} + +class _TvButtonRowContent extends StatelessWidget { + final EntryActionDelegate actionDelegate; + final Animation<double> scale; + final AvesEntry mainEntry, pageEntry; + + const _TvButtonRowContent({ + required this.actionDelegate, + required this.scale, + required this.mainEntry, + required this.pageEntry, + }); + + @override + Widget build(BuildContext context) { + final appMode = context.watch<ValueNotifier<AppMode>>().value; + return Selector<VideoConductor, AvesVideoController?>( + selector: (context, vc) => vc.getController(pageEntry), + builder: (context, videoController, child) { + return Row( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.start, + textDirection: ViewerBottomOverlay.actionsDirection, + children: [ + ...EntryActions.topLevel, + ...EntryActions.export, + ...EntryActions.videoPlayback, + ...EntryActions.video, + ] + .where((action) => actionDelegate.isVisible( + appMode: appMode, + action: action, + )) + .map((action) { + final enabled = actionDelegate.canApply(action); + return CaptionedButton( + scale: scale, + iconButtonBuilder: (context, focusNode) => _ViewerButtonRowContentState._buildButtonIcon( + context: context, + action: action, + mainEntry: mainEntry, + pageEntry: pageEntry, + videoController: videoController, + actionDelegate: actionDelegate, + focusNode: focusNode, + ), + captionText: _buildButtonCaption( + context: context, + action: action, + mainEntry: mainEntry, + pageEntry: pageEntry, + videoController: videoController, + enabled: enabled, + ), + onPressed: enabled ? () => actionDelegate.onActionSelected(context, action) : null, + ); + }).toList(), + ); + }, + ); + } + + static Widget _buildButtonCaption({ + required BuildContext context, + required EntryAction action, + required AvesEntry mainEntry, + required AvesEntry pageEntry, + required AvesVideoController? videoController, + required bool enabled, + }) { + switch (action) { + case EntryAction.toggleFavourite: + final favouriteTargetEntry = mainEntry.isStack ? pageEntry : mainEntry; + return FavouriteTogglerCaption( + entries: {favouriteTargetEntry}, + enabled: enabled, + ); + case EntryAction.videoToggleMute: + return MuteTogglerCaption( + controller: videoController, + enabled: enabled, + ); + case EntryAction.videoTogglePlay: + return PlayTogglerCaption( + controller: videoController, + enabled: enabled, + ); + default: + return CaptionedButtonText( + text: action.getText(context), + enabled: enabled, + ); + } + } +} + +class ViewerButtonRowContent extends StatefulWidget { + final EntryActionDelegate actionDelegate; + final List<EntryAction> quickActions, topLevelActions, exportActions, videoActions; + final Animation<double> scale; + final AvesEntry mainEntry, pageEntry; + + static const double padding = 8; + + const ViewerButtonRowContent({ + super.key, + required this.actionDelegate, + required this.quickActions, + required this.topLevelActions, + required this.exportActions, + required this.videoActions, + required this.scale, + required this.mainEntry, + required this.pageEntry, + }); + + @override + State<ViewerButtonRowContent> createState() => _ViewerButtonRowContentState(); +} + +class _ViewerButtonRowContentState extends State<ViewerButtonRowContent> { + final ValueNotifier<String?> _popupExpandedNotifier = ValueNotifier(null); + + EntryActionDelegate get actionDelegate => widget.actionDelegate; + + AvesEntry get mainEntry => widget.mainEntry; + + AvesEntry get pageEntry => widget.pageEntry; + + AvesEntry get favouriteTargetEntry => mainEntry.isStack ? pageEntry : mainEntry; + + static const double padding = ViewerButtonRowContent.padding; + + @override + void dispose() { + _popupExpandedNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final appMode = context.watch<ValueNotifier<AppMode>>().value; + bool isVisible(EntryAction action) => actionDelegate.isVisible( + appMode: appMode, + action: action, + ); + final showOrientationActions = EntryActions.orientationActions.any(isVisible); + final topLevelActions = widget.topLevelActions; + final exportActions = widget.exportActions; + final videoActions = widget.videoActions; + + final hasOverflowMenu = showOrientationActions || topLevelActions.isNotEmpty || exportActions.isNotEmpty || videoActions.isNotEmpty; + final animations = context.select<Settings, AccessibilityAnimations>((v) => v.accessibilityAnimations); + return Selector<VideoConductor, AvesVideoController?>( + selector: (context, vc) => vc.getController(pageEntry), + builder: (context, videoController, child) { + return Padding( + padding: const EdgeInsets.only(left: padding / 2, right: padding / 2, bottom: padding), + child: Row( + textDirection: ViewerBottomOverlay.actionsDirection, + children: [ + const Spacer(), + ...widget.quickActions.map((action) => _buildOverlayButton(context, action, videoController)), + if (hasOverflowMenu) + Padding( + padding: const EdgeInsets.symmetric(horizontal: padding / 2), + child: OverlayButton( + scale: widget.scale, + child: FontSizeIconTheme( + child: PopupMenuButton<EntryAction>( + key: const Key('entry-menu-button'), + itemBuilder: (context) { + final exportInternalActions = exportActions.whereNot(EntryActions.exportExternal.contains).toList(); + final exportExternalActions = exportActions.where(EntryActions.exportExternal.contains).toList(); + return [ + if (showOrientationActions) _buildRotateAndFlipMenuItems(context), + ...topLevelActions.map((action) => _buildPopupMenuItem(context, action, videoController)), + if (exportActions.isNotEmpty) + PopupMenuExpansionPanel<EntryAction>( + enabled: !availability.isLocked, + value: 'export', + expandedNotifier: _popupExpandedNotifier, + icon: AIcons.export, + title: context.l10n.entryActionExport, + items: [ + ...exportInternalActions.map((action) => _buildPopupMenuItem(context, action, videoController)), + if (exportInternalActions.isNotEmpty && exportExternalActions.isNotEmpty) const PopupMenuDivider(height: 0), + ...exportExternalActions.map((action) => _buildPopupMenuItem(context, action, videoController)), + ], + ), + if (videoActions.isNotEmpty) + PopupMenuExpansionPanel<EntryAction>( + value: 'video', + expandedNotifier: _popupExpandedNotifier, + icon: AIcons.video, + title: context.l10n.settingsVideoSectionTitle, + items: [ + ...videoActions.map((action) => _buildPopupMenuItem(context, action, videoController)), + ], + ), + if (isVisible(EntryAction.debug)) ...[ + const PopupMenuDivider(), + _buildPopupMenuItem(context, EntryAction.debug, videoController), + ] + ]; + }, + onOpened: () => PopupMenuOpenedNotification().dispatch(context), + onSelected: (action) async { + _popupExpandedNotifier.value = null; + // wait for the popup menu to hide before proceeding with the action + await Future.delayed(animations.popUpAnimationDelay * timeDilation); + actionDelegate.onActionSelected(context, action); + }, + onCanceled: () { + _popupExpandedNotifier.value = null; + }, + iconSize: IconTheme.of(context).size, + popUpAnimationStyle: animations.popUpAnimationStyle, + ), + ), + ), + ), + ], + ), + ); + }, + ); + } + + Widget _buildOverlayButton(BuildContext context, EntryAction action, AvesVideoController? videoController) { + return Padding( + padding: const EdgeInsets.symmetric(horizontal: padding / 2), + child: OverlayButton( + scale: widget.scale, + child: _buildButtonIcon( + context: context, + action: action, + mainEntry: mainEntry, + pageEntry: pageEntry, + videoController: videoController, + actionDelegate: actionDelegate, + ), + ), + ); + } + + PopupMenuItem<EntryAction> _buildPopupMenuItem(BuildContext context, EntryAction action, AvesVideoController? videoController) { + var enabled = actionDelegate.canApply(action); + switch (action) { + case EntryAction.videoCaptureFrame: + enabled &= videoController?.canCaptureFrameNotifier.value ?? false; + case EntryAction.videoToggleMute: + enabled &= videoController?.canMuteNotifier.value ?? false; + case EntryAction.videoSelectStreams: + enabled &= videoController?.canSelectStreamNotifier.value ?? false; + case EntryAction.videoSetSpeed: + enabled &= videoController?.canSetSpeedNotifier.value ?? false; + default: + break; + } + + Widget? child; + switch (action) { + case EntryAction.toggleFavourite: + child = FavouriteToggler( + entries: {favouriteTargetEntry}, + isMenuItem: true, + ); + case EntryAction.videoToggleMute: + child = MuteToggler( + controller: videoController, + isMenuItem: true, + ); + case EntryAction.videoTogglePlay: + child = PlayToggler( + controller: videoController, + isMenuItem: true, + ); + default: + child = MenuRow(text: action.getText(context), icon: action.getIcon()); + } + return PopupMenuItem( + value: action, + enabled: enabled, + child: child, + ); + } + + PopupMenuEntry<EntryAction> _buildRotateAndFlipMenuItems(BuildContext context) { + Widget buildDivider() => const SizedBox( + height: 16, + child: VerticalDivider( + width: 1, + thickness: 1, + ), + ); + + Widget buildItem(EntryAction action) => Expanded( + child: Material( + color: Colors.transparent, + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(8)), + ), + clipBehavior: Clip.antiAlias, + child: PopupMenuItem( + value: action, + enabled: actionDelegate.canApply(action), + child: Tooltip( + message: action.getText(context), + child: Center(child: action.getIcon()), + ), + ), + ), + ); + + return PopupMenuItemContainer( + child: Row( + children: [ + buildDivider(), + buildItem(EntryAction.rotateCCW), + buildDivider(), + buildItem(EntryAction.rotateCW), + buildDivider(), + buildItem(EntryAction.flip), + buildDivider(), + ], + ), + ); + } + + static Widget _buildButtonIcon({ + required BuildContext context, + required EntryAction action, + required AvesEntry mainEntry, + required AvesEntry pageEntry, + required AvesVideoController? videoController, + required EntryActionDelegate actionDelegate, + FocusNode? focusNode, + }) { + void onPressed() => actionDelegate.onActionSelected(context, action); + + Widget _buildFromListenable(ValueListenable<bool>? enabledNotifier) { + return NullableValueListenableBuilder<bool>( + valueListenable: enabledNotifier, + builder: (context, value, child) { + final canDo = value ?? false; + return IconButton( + icon: child!, + onPressed: canDo ? onPressed : null, + focusNode: focusNode, + tooltip: action.getText(context), + ); + }, + child: action.getIcon(), + ); + } + + final blurred = settings.enableBlurEffect; + switch (action) { + case EntryAction.copy: + return MoveButton( + copy: true, + blurred: blurred, + onChooserValue: (album) => actionDelegate.quickMove(context, album, copy: true), + onPressed: onPressed, + ); + case EntryAction.move: + return MoveButton( + copy: false, + blurred: blurred, + onChooserValue: (album) => actionDelegate.quickMove(context, album, copy: false), + onPressed: onPressed, + ); + case EntryAction.share: + return ShareButton( + blurred: blurred, + entries: {mainEntry}, + onChooserValue: (action) => actionDelegate.quickShare(context, action), + focusNode: focusNode, + onPressed: onPressed, + ); + case EntryAction.toggleFavourite: + final favouriteTargetEntry = mainEntry.isStack ? pageEntry : mainEntry; + return FavouriteToggler( + entries: {favouriteTargetEntry}, + focusNode: focusNode, + onPressed: onPressed, + ); + case EntryAction.videoToggleMute: + return MuteToggler( + controller: videoController, + focusNode: focusNode, + onPressed: onPressed, + ); + case EntryAction.videoTogglePlay: + return PlayToggler( + controller: videoController, + focusNode: focusNode, + onPressed: onPressed, + ); + case EntryAction.videoCaptureFrame: + return _buildFromListenable(videoController?.canCaptureFrameNotifier); + case EntryAction.videoSelectStreams: + return _buildFromListenable(videoController?.canSelectStreamNotifier); + case EntryAction.videoSetSpeed: + return _buildFromListenable(videoController?.canSetSpeedNotifier); + case EntryAction.editRating: + return RateButton( + blurred: blurred, + onChooserValue: (rating) => actionDelegate.quickRate(context, rating), + focusNode: focusNode, + onPressed: onPressed, + ); + case EntryAction.editTags: + return TagButton( + blurred: blurred, + onChooserValue: (filter) => actionDelegate.quickTag(context, filter), + focusNode: focusNode, + onPressed: onPressed, + ); + default: + return IconButton( + icon: action.getIcon(), + onPressed: onPressed, + focusNode: focusNode, + tooltip: action.getText(context), + ); + } + } +} diff --git a/lib/widgets/viewer/overlay/wallpaper_buttons.dart b/lib/widgets/viewer/overlay/wallpaper_buttons.dart new file mode 100644 index 0000000..2edf623 --- /dev/null +++ b/lib/widgets/viewer/overlay/wallpaper_buttons.dart @@ -0,0 +1,252 @@ +import 'dart:async'; +import 'dart:math'; +import 'dart:ui' as ui; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/images.dart'; +import 'package:aves/model/entry/extensions/props.dart'; +import 'package:aves/services/wallpaper_service.dart'; +import 'package:aves/widgets/common/action_mixins/feedback.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/buttons/overlay_button.dart'; +import 'package:aves/widgets/dialogs/wallpaper_settings_dialog.dart'; +import 'package:aves/widgets/viewer/overlay/bottom.dart'; +import 'package:aves/widgets/viewer/overlay/viewer_buttons.dart'; +import 'package:aves/widgets/viewer/video/conductor.dart'; +import 'package:aves/widgets/viewer/view/conductor.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:latlong2/latlong.dart'; +import 'package:provider/provider.dart'; + +class WallpaperButtons extends StatelessWidget with FeedbackMixin { + final AvesEntry entry; + final Animation<double> scale; + + const WallpaperButtons({ + super.key, + required this.entry, + required this.scale, + }); + + @override + Widget build(BuildContext context) { + const padding = ViewerButtonRowContent.padding; + return SafeArea( + top: false, + bottom: false, + child: Padding( + padding: const EdgeInsets.only(left: padding / 2, right: padding / 2, bottom: padding), + child: Row( + textDirection: ViewerBottomOverlay.actionsDirection, + children: [ + const Spacer(), + Padding( + padding: const EdgeInsets.symmetric(horizontal: padding / 2), + child: ScalingOverlayTextButton( + scale: scale, + onPressed: () => _setWallpaper(context), + child: Text(context.l10n.viewerSetWallpaperButtonLabel), + ), + ), + ], + ), + ), + ); + } + + Future<void> _setWallpaper(BuildContext context) async { + final l10n = context.l10n; + final value = await showDialog<(WallpaperTarget, bool)>( + context: context, + builder: (context) => const WallpaperSettingsDialog(), + routeSettings: const RouteSettings(name: WallpaperSettingsDialog.routeName), + ); + if (value == null) return; + + final reportController = StreamController.broadcast(); + unawaited(showOpReport( + context: context, + opStream: reportController.stream, + )); + + var region = _getVisibleRegion(context); + if (region == null) return; + + final (target, useScrollEffect) = value; + if (useScrollEffect) { + final deltaX = min(region.left, entry.displaySize.width - region.right); + region = Rect.fromLTRB(region.left - deltaX, region.top, region.right + deltaX, region.bottom); + } + + final bytes = await _getBytes(context, region); + + final success = bytes != null && await WallpaperService.set(bytes, target); + unawaited(reportController.close()); + + if (success) { + await SystemNavigator.pop(); + } else { + showFeedback(context, FeedbackType.warn, l10n.genericFailureFeedback); + } + } + + Rect? _getVisibleRegion(BuildContext context) { + final viewState = context.read<ViewStateConductor>().getOrCreateController(entry).viewState; + final viewportSize = viewState.viewportSize; + final contentSize = viewState.contentSize; + final scale = viewState.scale; + if (viewportSize == null || contentSize == null || contentSize.isEmpty || scale == null) return null; + + final center = (contentSize / 2 - viewState.position / scale) as Size; + final regionSize = viewportSize / scale; + final regionTopLeft = (center - regionSize / 2) as Offset; + return regionTopLeft & regionSize; + } + + Future<Uint8List?> _getBytes(BuildContext context, Rect displayRegion) async { + final viewState = context.read<ViewStateConductor>().getOrCreateController(entry).viewState; + final scale = viewState.scale; + + final displaySize = entry.displaySize; + if (displaySize.isEmpty || scale == null) return null; + + var storageRegion = Rectangle( + displayRegion.left, + displayRegion.top, + displayRegion.width, + displayRegion.height, + ); + + final rotationDegrees = entry.rotationDegrees; + final isFlipped = entry.isFlipped; + var needCrop = false, needOrientation = false; + + ImageProvider? provider; + if (entry.isSvg) { + provider = entry.getRegion( + scale: scale, + region: storageRegion, + ); + } else if (entry.isVideo) { + final videoController = context.read<VideoConductor>().getController(entry); + if (videoController != null) { + final bytes = await videoController.captureFrame(); + if (bytes != null) { + needOrientation = rotationDegrees != 0 || isFlipped; + needCrop = true; + provider = MemoryImage(bytes); + } + } + } else if (entry.isDecodingSupported) { + if (entry.useTiles) { + // provider image is already cropped, but not rotated + needOrientation = rotationDegrees != 0 || isFlipped; + if (needOrientation) { + final transform = Matrix4.identity() + ..translate(entry.width / 2.0, entry.height / 2.0) + ..scale(isFlipped ? -1.0 : 1.0, 1.0, 1.0) + ..rotateZ(-degToRadian(rotationDegrees.toDouble())) + ..translate(-displaySize.width / 2.0, -displaySize.height / 2.0); + + // apply EXIF orientation + final regionRectDouble = Rect.fromLTWH(displayRegion.left.toDouble(), displayRegion.top.toDouble(), displayRegion.width.toDouble(), displayRegion.height.toDouble()); + final tl = MatrixUtils.transformPoint(transform, regionRectDouble.topLeft); + final br = MatrixUtils.transformPoint(transform, regionRectDouble.bottomRight); + storageRegion = Rectangle<double>.fromPoints( + Point<double>(tl.dx, tl.dy), + Point<double>(br.dx, br.dy), + ); + } + + final devicePixelRatio = MediaQuery.of(context).devicePixelRatio; + final sampleSize = ExtraAvesEntryImages.sampleSizeForScale(magnifierScale: scale, devicePixelRatio: devicePixelRatio); + provider = entry.getRegion(sampleSize: sampleSize, region: storageRegion); + displayRegion = Rect.fromLTWH( + displayRegion.left / sampleSize, + displayRegion.top / sampleSize, + displayRegion.width / sampleSize, + displayRegion.height / sampleSize, + ); + } else { + // provider image is already rotated, but not cropped + needCrop = true; + provider = entry.fullImage; + } + } + if (provider == null) return null; + + final imageInfoCompleter = Completer<ImageInfo?>(); + final imageStream = provider.resolve(ImageConfiguration.empty); + final imageStreamListener = ImageStreamListener((image, synchronousCall) async { + imageInfoCompleter.complete(image); + }, onError: imageInfoCompleter.completeError); + imageStream.addListener(imageStreamListener); + ImageInfo? regionImageInfo; + try { + regionImageInfo = await imageInfoCompleter.future; + } catch (error) { + debugPrint('failed to get image for region=$displayRegion with error=$error'); + } + imageStream.removeListener(imageStreamListener); + var image = regionImageInfo?.image; + if (image == null) return null; + + if (needCrop || needOrientation) { + final recorder = ui.PictureRecorder(); + final canvas = Canvas(recorder); + + final w = image.width.toDouble(); + final h = image.height.toDouble(); + final imageDisplaySize = entry.isRotated ? Size(h, w) : Size(w, h); + var cropDx = -displayRegion.left.toDouble(); + var cropDy = -displayRegion.top.toDouble(); + + if (needOrientation) { + // apply EXIF orientation + if (isFlipped) { + canvas.scale(-1, 1); + switch (rotationDegrees) { + case 90: + canvas.translate(-imageDisplaySize.width, imageDisplaySize.height); + canvas.rotate(degToRadian(270)); + case 180: + canvas.translate(0, imageDisplaySize.height); + canvas.rotate(degToRadian(180)); + case 270: + canvas.rotate(degToRadian(90)); + } + } else { + switch (rotationDegrees) { + case 90: + canvas.translate(imageDisplaySize.width, 0); + cropDx = -displayRegion.top.toDouble(); + cropDy = displayRegion.left.toDouble(); + case 180: + canvas.translate(imageDisplaySize.width, imageDisplaySize.height); + case 270: + canvas.translate(0, imageDisplaySize.height); + } + if (rotationDegrees != 0) { + canvas.rotate(degToRadian(rotationDegrees.toDouble())); + } + } + } + + if (needCrop) { + canvas.translate(cropDx, cropDy); + } + canvas.drawImage(image, Offset.zero, Paint()); + final picture = recorder.endRecording(); + final renderSize = Size( + displayRegion.width.toDouble(), + displayRegion.height.toDouble(), + ); + image = await picture.toImage(renderSize.width.round(), renderSize.height.round()); + } + + // bytes should be compressed to be decodable on the platform side + return await image.toByteData(format: ui.ImageByteFormat.png).then((v) => v?.buffer.asUint8List()); + } +} diff --git a/lib/widgets/viewer/page_entry_builder.dart b/lib/widgets/viewer/page_entry_builder.dart new file mode 100644 index 0000000..b50c7fb --- /dev/null +++ b/lib/widgets/viewer/page_entry_builder.dart @@ -0,0 +1,34 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/multipage.dart'; +import 'package:aves/widgets/viewer/multipage/controller.dart'; +import 'package:aves_utils/aves_utils.dart'; +import 'package:flutter/widgets.dart'; + +class PageEntryBuilder extends StatelessWidget { + final MultiPageController? multiPageController; + final Widget Function(AvesEntry? pageEntry) builder; + + const PageEntryBuilder({ + super.key, + required this.multiPageController, + required this.builder, + }); + + @override + Widget build(BuildContext context) { + final controller = multiPageController; + return StreamBuilder<MultiPageInfo?>( + stream: controller != null ? controller.infoStream : Stream.value(null), + builder: (context, snapshot) { + final multiPageInfo = controller?.info; + return NullableValueListenableBuilder<int?>( + valueListenable: controller?.pageNotifier, + builder: (context, page, child) { + final pageEntry = multiPageInfo?.getPageEntryByIndex(page); + return builder(pageEntry); + }, + ); + }, + ); + } +} diff --git a/lib/widgets/viewer/panorama_page.dart b/lib/widgets/viewer/panorama_page.dart new file mode 100644 index 0000000..604f826 --- /dev/null +++ b/lib/widgets/viewer/panorama_page.dart @@ -0,0 +1,190 @@ +import 'dart:math'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/images.dart'; +import 'package:aves/model/media/panorama.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/aves_app.dart'; +import 'package:aves/widgets/common/basic/insets.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/extensions/media_query.dart'; +import 'package:aves/widgets/common/identity/buttons/overlay_button.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:panorama/panorama.dart'; +import 'package:provider/provider.dart'; + +class PanoramaPage extends StatefulWidget { + static const routeName = '/viewer/panorama'; + + final AvesEntry entry; + final PanoramaInfo info; + + const PanoramaPage({ + super.key, + required this.entry, + required this.info, + }); + + @override + State<PanoramaPage> createState() => _PanoramaPageState(); +} + +class _PanoramaPageState extends State<PanoramaPage> { + final ValueNotifier<bool> _overlayVisible = ValueNotifier(true); + final ValueNotifier<SensorControl> _sensorControl = ValueNotifier(SensorControl.None); + + AvesEntry get entry => widget.entry; + + PanoramaInfo get info => widget.info; + + static const _minZoom = .25; + + @override + void initState() { + super.initState(); + _overlayVisible.addListener(_onOverlayVisibleChanged); + WidgetsBinding.instance.addPostFrameCallback((_) => _initOverlay()); + } + + @override + void dispose() { + _overlayVisible.dispose(); + _sensorControl.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return PopScope( + onPopInvokedWithResult: (didPop, result) => _onLeave(), + child: AvesScaffold( + body: Stack( + children: [ + ValueListenableBuilder<SensorControl>( + valueListenable: _sensorControl, + builder: (context, sensorControl, child) { + void onTap(longitude, latitude, tilt) => _overlayVisible.value = !_overlayVisible.value; + final imageChild = child as Image; + + if (info.hasCroppedArea) { + final croppedArea = info.croppedAreaRect!; + final fullSize = info.fullPanoSize!; + final longitude = ((croppedArea.left + croppedArea.width / 2) / fullSize.width - 1 / 2) * 360; + return Panorama( + longitude: longitude, + minZoom: _minZoom, + sensorControl: sensorControl, + croppedArea: croppedArea, + croppedFullWidth: fullSize.width, + croppedFullHeight: fullSize.height, + onTap: onTap, + child: imageChild, + ); + } else { + return Panorama( + minZoom: _minZoom, + sensorControl: sensorControl, + onTap: onTap, + child: imageChild, + ); + } + }, + child: Image( + image: entry.fullImage, + ), + ), + Positioned( + right: 0, + bottom: 0, + child: _buildOverlay(context), + ), + const TopGestureAreaProtector(), + const SideGestureAreaProtector(), + const BottomGestureAreaProtector(), + ], + ), + resizeToAvoidBottomInset: false, + ), + ); + } + + Widget _buildOverlay(BuildContext context) { + if (settings.useTvLayout) return const SizedBox(); + + return TooltipTheme( + data: TooltipTheme.of(context).copyWith( + preferBelow: false, + ), + child: ValueListenableBuilder<bool>( + valueListenable: _overlayVisible, + builder: (context, overlayVisible, child) { + return Visibility( + visible: overlayVisible, + child: Selector<MediaQueryData, double>( + selector: (context, mq) => max(mq.effectiveBottomPadding, mq.systemGestureInsets.bottom), + builder: (context, mqPaddingBottom, child) { + return SafeArea( + bottom: false, + child: Padding( + padding: const EdgeInsets.all(8) + EdgeInsets.only(bottom: mqPaddingBottom), + child: child, + ), + ); + }, + child: OverlayButton( + child: ValueListenableBuilder<SensorControl>( + valueListenable: _sensorControl, + builder: (context, sensorControl, child) { + return IconButton( + icon: Icon(sensorControl == SensorControl.None ? AIcons.sensorControlEnabled : AIcons.sensorControlDisabled), + onPressed: _toggleSensor, + tooltip: sensorControl == SensorControl.None ? context.l10n.panoramaEnableSensorControl : context.l10n.panoramaDisableSensorControl, + ); + }, + ), + ), + ), + ); + }, + ), + ); + } + + void _toggleSensor() { + switch (_sensorControl.value) { + case SensorControl.None: + _sensorControl.value = SensorControl.AbsoluteOrientation; + case SensorControl.AbsoluteOrientation: + case SensorControl.Orientation: + _sensorControl.value = SensorControl.None; + } + } + + Future<void> _onLeave() async { + await AvesApp.showSystemUI(); + AvesApp.setSystemUIStyle(Theme.of(context)); + } + + // system UI + + // overlay + + Future<void> _initOverlay() async { + // wait for MaterialPageRoute.transitionDuration + // to show overlay after page animation is complete + await Future.delayed(ModalRoute.of(context)!.transitionDuration * timeDilation); + await _onOverlayVisibleChanged(); + } + + Future<void> _onOverlayVisibleChanged() async { + if (_overlayVisible.value) { + await AvesApp.showSystemUI(); + AvesApp.setSystemUIStyle(Theme.of(context)); + } else { + await AvesApp.hideSystemUI(); + } + } +} diff --git a/lib/widgets/viewer/providers.dart b/lib/widgets/viewer/providers.dart new file mode 100644 index 0000000..e0c04af --- /dev/null +++ b/lib/widgets/viewer/providers.dart @@ -0,0 +1,41 @@ +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/widgets/viewer/multipage/conductor.dart'; +import 'package:aves/widgets/viewer/video/conductor.dart'; +import 'package:aves/widgets/viewer/view/conductor.dart'; +import 'package:flutter/widgets.dart'; +import 'package:provider/provider.dart'; + +class ViewStateConductorProvider extends ProxyProvider<MediaQueryData, ViewStateConductor> { + ViewStateConductorProvider({ + super.key, + super.child, + }) : super( + create: (context) => ViewStateConductor(), + update: (context, mq, value) { + value!.viewportSize = mq.size; + return value; + }, + dispose: (context, value) => value.dispose(), + ); +} + +class VideoConductorProvider extends Provider<VideoConductor> { + VideoConductorProvider({ + super.key, + CollectionLens? collection, + super.child, + }) : super( + create: (context) => VideoConductor(collection: collection), + dispose: (context, value) => value.dispose(), + ); +} + +class MultiPageConductorProvider extends Provider<MultiPageConductor> { + MultiPageConductorProvider({ + super.key, + super.child, + }) : super( + create: (context) => MultiPageConductor(), + dispose: (context, value) => value.dispose(), + ); +} diff --git a/lib/widgets/viewer/screen_saver_page.dart b/lib/widgets/viewer/screen_saver_page.dart new file mode 100644 index 0000000..90bc7fc --- /dev/null +++ b/lib/widgets/viewer/screen_saver_page.dart @@ -0,0 +1,132 @@ +import 'package:aves/model/filters/mime.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/empty.dart'; +import 'package:aves/widgets/viewer/controls/controller.dart'; +import 'package:aves/widgets/viewer/entry_viewer_stack.dart'; +import 'package:aves/widgets/viewer/providers.dart'; +import 'package:aves_magnifier/aves_magnifier.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class ScreenSaverPage extends StatefulWidget { + static const routeName = '/screen_saver'; + + final CollectionSource source; + + const ScreenSaverPage({ + super.key, + required this.source, + }); + + @override + State<ScreenSaverPage> createState() => _ScreenSaverPageState(); +} + +class _ScreenSaverPageState extends State<ScreenSaverPage> with WidgetsBindingObserver { + late final ViewerController _viewerController; + CollectionLens? _slideshowCollection; + + CollectionSource get source => widget.source; + + @override + void initState() { + super.initState(); + _viewerController = ViewerController( + initialScale: ScaleLevel(ref: settings.screenSaverFillScreen ? ScaleReference.covered : ScaleReference.contained), + transition: settings.screenSaverTransition, + repeat: true, + autopilot: true, + autopilotInterval: Duration(seconds: settings.screenSaverInterval), + autopilotAnimatedZoom: settings.screenSaverAnimatedZoomEffect, + ); + source.stateNotifier.addListener(_onSourceStateChanged); + _initSlideshowCollection(); + WidgetsBinding.instance.addObserver(this); + } + + @override + void dispose() { + source.stateNotifier.removeListener(_onSourceStateChanged); + _viewerController.dispose(); + WidgetsBinding.instance.removeObserver(this); + super.dispose(); + } + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + if (state == AppLifecycleState.resumed) { + _viewerController.autopilot = true; + } + } + + @override + Widget build(BuildContext context) { + Widget child; + + final collection = _slideshowCollection; + if (collection == null) { + child = const SizedBox(); + } else { + final entries = collection.sortedEntries; + if (entries.isEmpty) { + child = EmptyContent( + icon: AIcons.image, + text: context.l10n.collectionEmptyImages, + alignment: Alignment.center, + ); + } else { + child = MultiProvider( + providers: [ + ViewStateConductorProvider(), + VideoConductorProvider(), + MultiPageConductorProvider(), + ], + child: EntryViewerStack( + collection: collection, + initialEntry: entries.first, + viewerController: _viewerController, + ), + ); + } + } + + return AvesScaffold( + body: child, + ); + } + + void _onSourceStateChanged() { + if (_slideshowCollection == null) { + _initSlideshowCollection(); + if (_slideshowCollection != null) { + setState(() {}); + } + } + } + + void _initSlideshowCollection() { + if (!source.isReady || _slideshowCollection != null) return; + + final originalCollection = CollectionLens( + source: source, + filters: settings.screenSaverCollectionFilters, + ); + var entries = originalCollection.sortedEntries; + if (settings.screenSaverVideoPlayback == SlideshowVideoPlayback.skip) { + entries = entries.where((entry) => !MimeFilter.video.test(entry)).toList(); + } + entries.shuffle(); + _slideshowCollection = CollectionLens( + source: originalCollection.source, + listenToSource: false, + fixedSort: true, + fixedSelection: entries, + ); + } +} diff --git a/lib/widgets/viewer/slideshow_page.dart b/lib/widgets/viewer/slideshow_page.dart new file mode 100644 index 0000000..67ce7e9 --- /dev/null +++ b/lib/widgets/viewer/slideshow_page.dart @@ -0,0 +1,186 @@ +import 'package:aves/app_mode.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/filters/covered/stored_album.dart'; +import 'package:aves/model/filters/mime.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/collection/collection_page.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/empty.dart'; +import 'package:aves/widgets/settings/viewer/slideshow.dart'; +import 'package:aves/widgets/viewer/controls/controller.dart'; +import 'package:aves/widgets/viewer/entry_viewer_stack.dart'; +import 'package:aves/widgets/viewer/providers.dart'; +import 'package:aves_magnifier/aves_magnifier.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class SlideshowPage extends StatefulWidget { + static const routeName = '/collection/slideshow'; + + final CollectionLens collection; + + const SlideshowPage({ + super.key, + required this.collection, + }); + + @override + State<SlideshowPage> createState() => _SlideshowPageState(); +} + +class _SlideshowPageState extends State<SlideshowPage> { + final ValueNotifier<AppMode> _appModeNotifier = ValueNotifier(AppMode.slideshow); + late ViewerController _viewerController; + late CollectionLens _slideshowCollection; + AvesEntry? _initialEntry; + + CollectionSource get source => widget.collection.source; + + @override + void initState() { + super.initState(); + _initViewerController(autopilot: true); + _initSlideshowCollection(); + _initialEntry = _slideshowCollection.sortedEntries.firstOrNull; + } + + @override + void dispose() { + _appModeNotifier.dispose(); + _disposeViewerController(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final initialEntry = _initialEntry; + return ListenableProvider<ValueNotifier<AppMode>>.value( + value: _appModeNotifier, + child: AvesScaffold( + body: initialEntry == null + ? EmptyContent( + icon: AIcons.image, + text: context.l10n.collectionEmptyImages, + alignment: Alignment.center, + ) + : MultiProvider( + providers: [ + ViewStateConductorProvider(), + VideoConductorProvider(), + MultiPageConductorProvider(), + ], + child: NotificationListener<SlideshowActionNotification>( + onNotification: (notification) { + _onActionSelected(notification.action); + return true; + }, + child: EntryViewerStack( + key: ValueKey(_viewerController), + collection: _slideshowCollection, + initialEntry: initialEntry, + viewerController: _viewerController, + ), + ), + ), + ), + ); + } + + void _initViewerController({required bool autopilot}) { + _viewerController = ViewerController( + initialScale: ScaleLevel(ref: settings.slideshowFillScreen ? ScaleReference.covered : ScaleReference.contained), + transition: settings.slideshowTransition, + repeat: settings.slideshowRepeat, + autopilot: autopilot, + autopilotInterval: Duration(seconds: settings.slideshowInterval), + autopilotAnimatedZoom: settings.slideshowAnimatedZoomEffect, + ); + } + + void _disposeViewerController() => _viewerController.dispose(); + + void _initSlideshowCollection() { + var entries = List.of(widget.collection.sortedEntries); + if (settings.slideshowVideoPlayback == SlideshowVideoPlayback.skip) { + entries = entries.where((entry) => !MimeFilter.video.test(entry)).toList(); + } + if (settings.slideshowShuffle) { + entries.shuffle(); + } + _slideshowCollection = CollectionLens( + source: source, + listenToSource: false, + fixedSort: true, + fixedSelection: entries, + ); + } + + void _onActionSelected(SlideshowAction action) { + switch (action) { + case SlideshowAction.resume: + _viewerController.autopilot = true; + case SlideshowAction.showInCollection: + _showInCollection(); + case SlideshowAction.cast: + // ignore, as it should be handled at the viewer level + break; + case SlideshowAction.settings: + _showSettings(context); + } + } + + void _showInCollection() { + final currentEntry = _viewerController.entryNotifier.value; + if (currentEntry == null) return; + + final album = currentEntry.directory; + final uri = currentEntry.uri; + + Navigator.maybeOf(context)?.pushAndRemoveUntil( + MaterialPageRoute( + settings: const RouteSettings(name: CollectionPage.routeName), + builder: (context) => CollectionPage( + source: source, + filters: album != null ? {StoredAlbumFilter(album, source.getStoredAlbumDisplayName(context, album))} : null, + highlightTest: (entry) => entry.uri == uri, + ), + ), + (route) => false, + ); + } + + (bool, bool) get collectionSettings => (settings.slideshowShuffle, settings.slideshowVideoPlayback == SlideshowVideoPlayback.skip); + + Future<void> _showSettings(BuildContext context) async { + final oldCollectionSettings = collectionSettings; + final currentEntry = _viewerController.entryNotifier.value; + + await Navigator.maybeOf(context)?.push( + MaterialPageRoute( + settings: const RouteSettings(name: ViewerSlideshowPage.routeName), + builder: (context) => const ViewerSlideshowPage(), + ), + ); + + _disposeViewerController(); + _initViewerController(autopilot: false); + if (oldCollectionSettings != collectionSettings) { + _initSlideshowCollection(); + } + final slideshowEntries = _slideshowCollection.sortedEntries; + _initialEntry = slideshowEntries.contains(currentEntry) ? currentEntry : slideshowEntries.firstOrNull; + setState(() {}); + } +} + +class SlideshowActionNotification extends Notification { + final SlideshowAction action; + + SlideshowActionNotification(this.action); +} diff --git a/lib/widgets/viewer/source_viewer_page.dart b/lib/widgets/viewer/source_viewer_page.dart new file mode 100644 index 0000000..a545eb2 --- /dev/null +++ b/lib/widgets/viewer/source_viewer_page.dart @@ -0,0 +1,70 @@ +import 'package:aves/widgets/common/aves_highlight.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_highlight/themes/darcula.dart'; + +class SourceViewerPage extends StatefulWidget { + static const routeName = '/viewer/source'; + + final Future<String> Function() loader; + + const SourceViewerPage({ + super.key, + required this.loader, + }); + + @override + State<SourceViewerPage> createState() => _SourceViewerPageState(); +} + +class _SourceViewerPageState extends State<SourceViewerPage> { + late Future<String> _loader; + + static const maxCodeSize = 2 << 16; // 128kB + + @override + void initState() { + super.initState(); + _loader = widget.loader(); + } + + @override + Widget build(BuildContext context) { + return AvesScaffold( + appBar: AppBar( + title: Text(context.l10n.sourceViewerPageTitle), + ), + body: SafeArea( + child: FutureBuilder<String>( + future: _loader, + builder: (context, snapshot) { + if (snapshot.hasError) return Text(snapshot.error.toString()); + if (!snapshot.hasData) return const SizedBox(); + + final data = snapshot.data!; + final source = data.length < maxCodeSize ? data : '${data.substring(0, maxCodeSize)}\n\n*** TRUNCATED ***'; + + return Container( + constraints: const BoxConstraints.expand(), + child: Scrollbar( + child: SingleChildScrollView( + child: AvesHighlightView( + input: source, + language: 'xml', + theme: darculaTheme, + padding: const EdgeInsets.all(8), + textStyle: const TextStyle( + fontSize: 10, + ), + tabSize: 4, + ), + ), + ), + ); + }, + ), + ), + ); + } +} diff --git a/lib/widgets/viewer/video/conductor.dart b/lib/widgets/viewer/video/conductor.dart new file mode 100644 index 0000000..519e3ec --- /dev/null +++ b/lib/widgets/viewer/video/conductor.dart @@ -0,0 +1,112 @@ +import 'dart:async'; +import 'dart:math'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/props.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/collection_lens.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/widgets/viewer/video/db_playback_state_handler.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:aves_video/aves_video.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/foundation.dart'; +import 'package:leak_tracker/leak_tracker.dart'; + +class VideoConductor { + final CollectionLens? _collection; + final List<AvesVideoController> _controllers = []; + final Map<AvesVideoController, StreamSubscription> _subscriptions = {}; + final PlaybackStateHandler _playbackStateHandler = DatabasePlaybackStateHandler(); + + final ValueNotifier<AvesVideoController?> playingVideoControllerNotifier = ValueNotifier(null); + + static const _defaultMaxControllerCount = 3; + + VideoConductor({CollectionLens? collection}) : _collection = collection { + if (kFlutterMemoryAllocationsEnabled) { + LeakTracking.dispatchObjectCreated( + library: 'aves', + className: '$VideoConductor', + object: this, + ); + } + } + + Future<void> dispose() async { + if (kFlutterMemoryAllocationsEnabled) { + LeakTracking.dispatchObjectDisposed(object: this); + } + await _disposeAll(); + playingVideoControllerNotifier.dispose(); + _controllers.clear(); + if (settings.keepScreenOn == KeepScreenOn.videoPlayback) { + await windowService.keepScreenOn(false); + } + } + + Future<AvesVideoController> getOrCreateController(AvesEntry entry, {int? maxControllerCount}) async { + var controller = getController(entry); + if (controller != null) { + _controllers.remove(controller); + } else { + maxControllerCount = max(_defaultMaxControllerCount, maxControllerCount ?? 0); + while (_controllers.length >= maxControllerCount) { + await _disposeController(_controllers.removeLast()); + } + await deviceService.requestGarbageCollection(); + controller = videoControllerFactory.buildController( + entry, + playbackStateHandler: _playbackStateHandler, + settings: settings, + ); + _subscriptions[controller] = controller.statusStream.listen((event) => _onControllerStatusChanged(entry, controller!, event)); + } + _controllers.insert(0, controller); + return controller; + } + + AvesVideoController? getPlayingController() => _controllers.firstWhereOrNull((c) => c.isPlaying); + + AvesVideoController? getController(AvesEntry entry) { + return _controllers.firstWhereOrNull((c) => c.entry.uri == entry.uri && c.entry.pageId == entry.pageId); + } + + Future<void> _onControllerStatusChanged(AvesEntry entry, AvesVideoController controller, VideoStatus status) async { + bool canSkipToNext = false, canSkipToPrevious = false; + final entries = _collection?.sortedEntries; + if (entries != null) { + final currentIndex = entries.indexOf(entry); + if (currentIndex != -1) { + bool isVideo(AvesEntry entry) => entry.isVideo; + canSkipToPrevious = entries.take(currentIndex).lastWhereOrNull(isVideo) != null; + canSkipToNext = entries.skip(currentIndex + 1).firstWhereOrNull(isVideo) != null; + } + } + + await mediaSessionService.update( + entry: entry, + controller: controller, + canSkipToNext: canSkipToNext, + canSkipToPrevious: canSkipToPrevious, + ); + if (settings.keepScreenOn == KeepScreenOn.videoPlayback) { + await windowService.keepScreenOn(status == VideoStatus.playing); + } + + playingVideoControllerNotifier.value = getPlayingController(); + } + + Future<void> _applyToAll(FutureOr Function(AvesVideoController controller) action) => Future.forEach<AvesVideoController>(_controllers, action); + + Future<void> _disposeAll() => _applyToAll(_disposeController); + + Future<void> pauseAll() => _applyToAll((controller) => controller.pause()); + + Future<void> muteAll(bool muted) => _applyToAll((controller) => controller.mute(muted)); + + Future<void> _disposeController(AvesVideoController controller) async { + await _subscriptions.remove(controller)?.cancel(); + await controller.dispose(); + } +} diff --git a/lib/widgets/viewer/video/db_playback_state_handler.dart b/lib/widgets/viewer/video/db_playback_state_handler.dart new file mode 100644 index 0000000..15be982 --- /dev/null +++ b/lib/widgets/viewer/video/db_playback_state_handler.dart @@ -0,0 +1,67 @@ +import 'dart:async'; + +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/viewer/video_playback.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/theme/format.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/dialogs/aves_dialog.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:aves_video/aves_video.dart'; +import 'package:flutter/material.dart'; + +class DatabasePlaybackStateHandler extends PlaybackStateHandler { + static const resumeTimeSaveMinProgress = .05; + static const resumeTimeSaveMaxProgress = .95; + + @override + Future<int?> getResumeTime({required int entryId, required BuildContext context}) async { + final playback = await localMediaDb.loadVideoPlayback(entryId); + final resumeTime = playback?.resumeTimeMillis ?? 0; + if (resumeTime == 0) return null; + + // clear on retrieval + await localMediaDb.removeVideoPlayback({entryId}); + + switch (settings.videoResumptionMode) { + case VideoResumptionMode.never: + return 0; + case VideoResumptionMode.ask: + final resume = await showDialog<bool>( + context: context, + builder: (context) => AvesDialog( + content: Text(context.l10n.videoResumeDialogMessage(formatFriendlyDuration(Duration(milliseconds: resumeTime)))), + actions: [ + TextButton( + onPressed: () => Navigator.maybeOf(context)?.pop(false), + child: Text(context.l10n.videoStartOverButtonLabel), + ), + TextButton( + onPressed: () => Navigator.maybeOf(context)?.pop(true), + child: Text(context.l10n.videoResumeButtonLabel), + ), + ], + ), + routeSettings: const RouteSettings(name: AvesDialog.confirmationRouteName), + ) ?? + false; + return resume ? resumeTime : 0; + case VideoResumptionMode.always: + return resumeTime; + } + } + + @override + Future<void> saveResumeTime({required int entryId, required int position, required double progress}) async { + if (resumeTimeSaveMinProgress < progress && progress < resumeTimeSaveMaxProgress) { + await localMediaDb.addVideoPlayback({ + VideoPlaybackRow( + entryId: entryId, + resumeTimeMillis: position, + ) + }); + } else { + await localMediaDb.removeVideoPlayback({entryId}); + } + } +} diff --git a/lib/widgets/viewer/view/conductor.dart b/lib/widgets/viewer/view/conductor.dart new file mode 100644 index 0000000..529238e --- /dev/null +++ b/lib/widgets/viewer/view/conductor.dart @@ -0,0 +1,83 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/viewer/view_state.dart'; +import 'package:aves/widgets/viewer/view/controller.dart'; +import 'package:aves_magnifier/aves_magnifier.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/rendering.dart'; +import 'package:leak_tracker/leak_tracker.dart'; + +class ViewStateConductor { + final List<ViewStateController> _controllers = []; + Size _viewportSize = Size.zero; + + static const maxControllerCount = 3; + + ViewStateConductor() { + if (kFlutterMemoryAllocationsEnabled) { + LeakTracking.dispatchObjectCreated( + library: 'aves', + className: '$ViewStateConductor', + object: this, + ); + } + } + + Future<void> dispose() async { + if (kFlutterMemoryAllocationsEnabled) { + LeakTracking.dispatchObjectDisposed(object: this); + } + _controllers.forEach((v) => v.dispose()); + _controllers.clear(); + } + + set viewportSize(Size size) => _viewportSize = size; + + ViewStateController getOrCreateController(AvesEntry entry) { + var controller = getController(entry); + if (controller != null) { + _controllers.remove(controller); + } else { + // try to initialize the view state to match magnifier initial state + const initialScale = ScaleLevel(ref: ScaleReference.contained); + final initialValue = ViewState( + position: Offset.zero, + scale: ScaleBoundaries( + allowOriginalScaleBeyondRange: true, + minScale: initialScale, + maxScale: initialScale, + initialScale: initialScale, + viewportSize: _viewportSize, + contentSize: entry.displaySize, + ).initialScale, + viewportSize: _viewportSize, + contentSize: entry.displaySize, + ); + controller = ViewStateController( + entry: entry, + viewStateNotifier: ValueNotifier<ViewState>(initialValue), + ); + } + _controllers.insert(0, controller); + while (_controllers.length > maxControllerCount) { + _controllers.removeLast().dispose(); + } + return controller; + } + + ViewStateController? getController(AvesEntry entry) { + return _controllers.firstWhereOrNull((c) => c.entry.uri == entry.uri && c.entry.pageId == entry.pageId); + } + + void reset(AvesEntry entry) { + final uris = <AvesEntry>{ + entry, + ...?entry.stackedEntries, + }.map((v) => v.uri).toSet(); + final entryControllers = _controllers.where((v) => uris.contains(v.entry.uri)).toSet(); + entryControllers.forEach((controller) { + _controllers.remove(controller); + controller.dispose(); + }); + } +} diff --git a/lib/widgets/viewer/view/controller.dart b/lib/widgets/viewer/view/controller.dart new file mode 100644 index 0000000..ca487ba --- /dev/null +++ b/lib/widgets/viewer/view/controller.dart @@ -0,0 +1,35 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/viewer/view_state.dart'; +import 'package:aves/widgets/viewer/view/histogram.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:leak_tracker/leak_tracker.dart'; + +class ViewStateController with HistogramMixin { + final AvesEntry entry; + final ValueNotifier<ViewState> viewStateNotifier; + final ValueNotifier<ImageProvider?> fullImageNotifier = ValueNotifier(null); + + ViewState get viewState => viewStateNotifier.value; + + ViewStateController({ + required this.entry, + required this.viewStateNotifier, + }) { + if (kFlutterMemoryAllocationsEnabled) { + LeakTracking.dispatchObjectCreated( + library: 'aves', + className: '$ViewStateController', + object: this, + ); + } + } + + void dispose() { + if (kFlutterMemoryAllocationsEnabled) { + LeakTracking.dispatchObjectDisposed(object: this); + } + viewStateNotifier.dispose(); + fullImageNotifier.dispose(); + } +} diff --git a/lib/widgets/viewer/view/histogram.dart b/lib/widgets/viewer/view/histogram.dart new file mode 100644 index 0000000..b25451b --- /dev/null +++ b/lib/widgets/viewer/view/histogram.dart @@ -0,0 +1,97 @@ +import 'dart:async'; +import 'dart:ui'; + +import 'package:aves/model/settings/settings.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:aves_utils/aves_utils.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; + +enum HistogramChannel { red, green, blue, luminance } + +typedef HistogramLevels = Map<HistogramChannel, List<double>>; + +mixin HistogramMixin { + HistogramLevels _levels = {}; + Future<void>? _loader; + + static const int bins = 256; + + Future<HistogramLevels> getHistogramLevels(ImageInfo info, bool forceUpdate) async { + if (_levels.isEmpty || forceUpdate) { + _loader ??= _getLevels(info); + await _loader; + _loader = null; + } + return _levels; + } + + Future<void> _getLevels(ImageInfo info) async { + final data = (await info.image.toByteData(format: ImageByteFormat.rawStraightRgba))!; + _levels = switch (settings.overlayHistogramStyle) { + OverlayHistogramStyle.rgb => await compute<ByteData, HistogramLevels>(_computeRgbLevels, data), + OverlayHistogramStyle.luminance => await compute<ByteData, HistogramLevels>(_computeLuminanceLevels, data), + _ => <HistogramChannel, List<double>>{}, + }; + } + + static HistogramLevels _computeRgbLevels(ByteData data) { + final redLevels = List.filled(bins, 0); + final greenLevels = List.filled(bins, 0); + final blueLevels = List.filled(bins, 0); + + final view = Uint8List.view(data.buffer); + final viewSize = view.length; + for (var i = 0; i < viewSize; i += 4) { + final a = view[i + 3]; + if (a > 0) { + redLevels[view[i + 0]]++; + greenLevels[view[i + 1]]++; + blueLevels[view[i + 2]]++; + } + } + + final max = [ + redLevels.max, + greenLevels.max, + blueLevels.max, + ].max; + if (max == 0) return {}; + + final f = 1.0 / max; + return { + HistogramChannel.red: redLevels.map((v) => v * f).toList(), + HistogramChannel.green: greenLevels.map((v) => v * f).toList(), + HistogramChannel.blue: blueLevels.map((v) => v * f).toList(), + }; + } + + static HistogramLevels _computeLuminanceLevels(ByteData data) { + final lumLevels = List.filled(bins, 0); + const normMax = bins - 1; + + final view = Uint8List.view(data.buffer); + final viewSize = view.length; + for (var i = 0; i < viewSize; i += 4) { + final a = view[i + 3]; + if (a > 0) { + final r = view[i + 0]; + final g = view[i + 1]; + final b = view[i + 2]; + // `Color.computeLuminance()` is more accurate, but slower + // and photo software typically use the simpler formula + final l = ColorUtils.luma(r, g, b); + lumLevels[(l * normMax).round()]++; + } + } + + final max = lumLevels.max; + if (max == 0) return {}; + + final f = 1.0 / max; + return { + HistogramChannel.luminance: lumLevels.map((v) => v * f).toList(), + }; + } +} diff --git a/lib/widgets/viewer/visual/controller_mixin.dart b/lib/widgets/viewer/visual/controller_mixin.dart new file mode 100644 index 0000000..f96ed8f --- /dev/null +++ b/lib/widgets/viewer/visual/controller_mixin.dart @@ -0,0 +1,274 @@ +import 'dart:async'; +import 'dart:math'; + +import 'package:aves/app_mode.dart'; +import 'package:aves/model/device.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/multipage.dart'; +import 'package:aves/model/entry/extensions/props.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/widgets/viewer/multipage/conductor.dart'; +import 'package:aves/widgets/viewer/multipage/controller.dart'; +import 'package:aves/widgets/viewer/video/conductor.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:aves_video/aves_video.dart'; +import 'package:collection/collection.dart'; +import 'package:floating/floating.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:flutter/services.dart'; +import 'package:provider/provider.dart'; + +// state controllers/monitors +mixin EntryViewControllerMixin<T extends StatefulWidget> on State<T> { + final Map<AvesEntry, VoidCallback> _metadataChangeListeners = {}; + final Map<MultiPageController, Future<void> Function()> _multiPageControllerPageListeners = {}; + + bool? videoMutedOverride; + + bool get isViewingImage; + + ValueNotifier<AvesEntry?> get entryNotifier; + + Future<void> initEntryControllers(AvesEntry? entry) async { + if (!mounted || entry == null) return; + + if (entry.isVideo) { + await _initVideoController(entry); + } + if (entry.isMultiPage) { + await _initMultiPageController(entry); + } + void listener() => _onMetadataChanged(entry); + _metadataChangeListeners[entry] = listener; + entry.metadataChangeNotifier.addListener(listener); + } + + void cleanEntryControllers(AvesEntry? entry) { + if (entry == null) return; + + final listener = _metadataChangeListeners.remove(entry); + if (listener != null) { + entry.metadataChangeNotifier.removeListener(listener); + } + if (entry.isMultiPage) { + _cleanMultiPageController(entry); + } + } + + void _onMetadataChanged(AvesEntry entry) { + debugPrint('reinitialize controllers for entry=$entry because metadata changed'); + cleanEntryControllers(entry); + initEntryControllers(entry); + } + + SlideshowVideoPlayback? get videoPlaybackOverride { + if (!mounted) return null; + final appMode = context.read<ValueNotifier<AppMode>>().value; + switch (appMode) { + case AppMode.screenSaver: + return settings.screenSaverVideoPlayback; + case AppMode.slideshow: + return settings.slideshowVideoPlayback; + default: + return null; + } + } + + bool get videoAutoPlayEnabled { + if (!isViewingImage) return false; + + switch (videoPlaybackOverride) { + case SlideshowVideoPlayback.skip: + return false; + case SlideshowVideoPlayback.playMuted: + case SlideshowVideoPlayback.playWithSound: + return true; + case null: + break; + } + + switch (settings.videoAutoPlayMode) { + case VideoAutoPlayMode.disabled: + return false; + case VideoAutoPlayMode.playMuted: + case VideoAutoPlayMode.playWithSound: + return true; + } + } + + bool get shouldAutoPlayVideoMuted { + if (videoMutedOverride != null) { + return videoMutedOverride!; + } + + switch (videoPlaybackOverride) { + case SlideshowVideoPlayback.skip: + case SlideshowVideoPlayback.playWithSound: + return false; + case SlideshowVideoPlayback.playMuted: + return true; + case null: + break; + } + + switch (settings.videoAutoPlayMode) { + case VideoAutoPlayMode.disabled: + case VideoAutoPlayMode.playWithSound: + return false; + case VideoAutoPlayMode.playMuted: + return true; + } + } + + bool get shouldAutoPlayMotionPhoto { + if (!isViewingImage) return false; + + return settings.enableMotionPhotoAutoPlay; + } + + Future<void> _initVideoController(AvesEntry entry) async { + final controller = await context.read<VideoConductor>().getOrCreateController(entry); + setState(() {}); + + if (videoAutoPlayEnabled || entry.isAnimated) { + final resumeTimeMillis = await controller.getResumeTime(context); + await _autoPlayVideo(controller, () => entry == entryNotifier.value, resumeTimeMillis: resumeTimeMillis); + } + } + + Future<void> _initMultiPageController(AvesEntry entry) async { + if (!mounted) return; + + final multiPageController = context.read<MultiPageConductor>().getOrCreateController(entry); + setState(() {}); + + final multiPageInfo = multiPageController.info ?? await multiPageController.infoStream.first; + assert(multiPageInfo != null); + if (multiPageInfo == null) return; + + if (entry.isMotionPhoto) { + await multiPageInfo.extractMotionPhotoVideo(); + } + + final videoPageEntries = multiPageInfo.videoPageEntries; + if (videoPageEntries.isNotEmpty) { + // init video controllers for all pages that could need it + final videoConductor = context.read<VideoConductor>(); + await Future.forEach(videoPageEntries, (entry) async { + await videoConductor.getOrCreateController(entry, maxControllerCount: videoPageEntries.length); + }); + + // auto play/pause when changing page + Future<void> _onPageChanged() async { + await pauseVideoControllers(); + if (videoAutoPlayEnabled || (entry.isMotionPhoto && shouldAutoPlayMotionPhoto)) { + final page = multiPageController.page; + final pageInfo = multiPageInfo.getByIndex(page)!; + if (pageInfo.isVideo) { + final pageEntry = multiPageInfo.getPageEntryByIndex(page); + final pageVideoController = videoConductor.getController(pageEntry); + assert(pageVideoController != null); + if (pageVideoController != null) { + await _autoPlayVideo(pageVideoController, () => entry == entryNotifier.value && page == multiPageController.page); + } + } + } + } + + _multiPageControllerPageListeners[multiPageController] = _onPageChanged; + multiPageController.pageNotifier.addListener(_onPageChanged); + await _onPageChanged(); + + if (entry.isMotionPhoto && shouldAutoPlayMotionPhoto) { + await Future.delayed(ADurations.motionPhotoAutoPlayDelay); + if (entry == entryNotifier.value) { + multiPageController.page = 1; + } + } + } + } + + Future<void> _cleanMultiPageController(AvesEntry entry) async { + final multiPageController = _multiPageControllerPageListeners.keys.firstWhereOrNull((v) => v.entry == entry); + if (multiPageController != null) { + final _onPageChange = _multiPageControllerPageListeners.remove(multiPageController); + if (_onPageChange != null) { + multiPageController.pageNotifier.removeListener(_onPageChange); + } + } + } + + Future<void> _autoPlayVideo(AvesVideoController videoController, bool Function() isCurrent, {int? resumeTimeMillis}) async { + // video decoding may fail or have initial artifacts when the player initializes + // during this widget initialization (because of the page transition and hero animation?) + // so we play after a delay for increased stability + await Future.delayed(const Duration(milliseconds: 300) * timeDilation); + + if (!videoController.isMuted && (videoController.entry.isAnimated || shouldAutoPlayVideoMuted)) { + await videoController.mute(true); + } + + if (resumeTimeMillis != null) { + await videoController.seekTo(resumeTimeMillis); + } + await videoController.play(); + + // playing controllers are paused when the entry changes, + // but the controller may still be preparing (not yet playing) when this happens + // so we make sure the current entry is still the same to keep playing + if (!isCurrent()) { + await videoController.pause(); + } + } + + Future<void> pauseVideoControllers() => context.read<VideoConductor>().pauseAll(); + + static const _pipRatioMax = Rational(43, 18); + static const _pipRatioMin = Rational(18, 43); + + Future<void> updatePictureInPicture(BuildContext context) async { + if (!device.supportPictureInPicture) return; + + if (context.mounted && settings.videoBackgroundMode == VideoBackgroundMode.pip) { + final playingController = context.read<VideoConductor>().getPlayingController(); + if (playingController != null) { + final entrySize = playingController.entry.displaySize; + final entryAspectRatio = entrySize.aspectRatio; + final Rational pipAspectRatio; + if (entryAspectRatio > _pipRatioMax.aspectRatio) { + pipAspectRatio = _pipRatioMax; + } else if (entryAspectRatio < _pipRatioMin.aspectRatio) { + pipAspectRatio = _pipRatioMin; + } else { + pipAspectRatio = Rational(entrySize.width.round(), entrySize.height.round()); + } + + final viewSize = MediaQuery.sizeOf(context) * MediaQuery.devicePixelRatioOf(context); + final fittedSize = applyBoxFit(BoxFit.contain, entrySize, viewSize).destination; + final sourceRectHint = Rectangle<int>( + ((viewSize.width - fittedSize.width) / 2).round(), + ((viewSize.height - fittedSize.height) / 2).round(), + fittedSize.width.round(), + fittedSize.height.round(), + ); + + try { + final status = await Floating().enable(OnLeavePiP( + aspectRatio: pipAspectRatio, + sourceRectHint: sourceRectHint, + )); + debugPrint('Enabled picture-in-picture with status=$status'); + return; + } on PlatformException catch (e, stack) { + await reportService.recordError(e, stack); + } + } + } + + debugPrint('Cancelling picture-in-picture'); + await Floating().cancelOnLeavePiP(); + } +} diff --git a/lib/widgets/viewer/visual/entry_page_view.dart b/lib/widgets/viewer/visual/entry_page_view.dart new file mode 100644 index 0000000..77f76b6 --- /dev/null +++ b/lib/widgets/viewer/visual/entry_page_view.dart @@ -0,0 +1,551 @@ +import 'dart:async'; + +import 'package:aves/app_mode.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/props.dart'; +import 'package:aves/model/settings/enums/widget_outline.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/viewer/view_state.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/services/media/media_session_service.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/view/view.dart'; +import 'package:aves/widgets/aves_app.dart'; +import 'package:aves/widgets/common/action_mixins/feedback.dart'; +import 'package:aves/widgets/common/basic/insets.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/home_widget.dart'; +import 'package:aves/widgets/viewer/controls/controller.dart'; +import 'package:aves/widgets/viewer/controls/notifications.dart'; +import 'package:aves/widgets/viewer/hero.dart'; +import 'package:aves/widgets/viewer/video/conductor.dart'; +import 'package:aves/widgets/viewer/view/conductor.dart'; +import 'package:aves/widgets/viewer/visual/error.dart'; +import 'package:aves/widgets/viewer/visual/raster.dart'; +import 'package:aves/widgets/viewer/visual/vector.dart'; +import 'package:aves/widgets/viewer/visual/video/cover.dart'; +import 'package:aves/widgets/viewer/visual/video/subtitle/subtitle.dart'; +import 'package:aves/widgets/viewer/visual/video/swipe_action.dart'; +import 'package:aves/widgets/viewer/visual/video/video_view.dart'; +import 'package:aves_magnifier/aves_magnifier.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:decorated_icon/decorated_icon.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class EntryPageView extends StatefulWidget { + final AvesEntry mainEntry, pageEntry; + final ViewerController viewerController; + final VoidCallback? onDisposed; + + static const decorationCheckSize = 20.0; + static const rasterMaxScale = ScaleLevel(factor: 5); + static const vectorMaxScale = ScaleLevel(factor: 25); + + const EntryPageView({ + super.key, + required this.mainEntry, + required this.pageEntry, + required this.viewerController, + this.onDisposed, + }); + + @override + State<EntryPageView> createState() => _EntryPageViewState(); +} + +class _EntryPageViewState extends State<EntryPageView> with TickerProviderStateMixin { + late ValueNotifier<ViewState> _viewStateNotifier; + late AvesMagnifierController _magnifierController; + final Set<StreamSubscription> _subscriptions = {}; + final ValueNotifier<Widget?> _actionFeedbackChildNotifier = ValueNotifier(null); + OverlayEntry? _actionFeedbackOverlayEntry; + + AvesEntry get mainEntry => widget.mainEntry; + + AvesEntry get entry => widget.pageEntry; + + ViewerController get viewerController => widget.viewerController; + + @override + void initState() { + super.initState(); + _registerWidget(widget); + } + + @override + void didUpdateWidget(covariant EntryPageView oldWidget) { + super.didUpdateWidget(oldWidget); + + if (oldWidget.pageEntry != widget.pageEntry) { + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + } + + @override + void dispose() { + _unregisterWidget(widget); + widget.onDisposed?.call(); + _actionFeedbackChildNotifier.dispose(); + super.dispose(); + } + + void _registerWidget(EntryPageView widget) { + final entry = widget.pageEntry; + _viewStateNotifier = context.read<ViewStateConductor>().getOrCreateController(entry).viewStateNotifier; + _magnifierController = AvesMagnifierController(); + _subscriptions.add(_magnifierController.stateStream.listen(_onViewStateChanged)); + _subscriptions.add(_magnifierController.scaleBoundariesStream.listen(_onViewScaleBoundariesChanged)); + if (entry.isVideo) { + _subscriptions.add(mediaSessionService.mediaCommands.listen(_onMediaCommand)); + } + viewerController.startAutopilotAnimation( + vsync: this, + onUpdate: ({required scaleLevel}) { + final boundaries = _magnifierController.scaleBoundaries; + if (boundaries != null) { + final scale = boundaries.scaleForLevel(scaleLevel); + _magnifierController.update(scale: scale, source: ChangeSource.animation); + } + }); + } + + void _unregisterWidget(EntryPageView oldWidget) { + viewerController.stopAutopilotAnimation(vsync: this); + _magnifierController.dispose(); + _subscriptions + ..forEach((sub) => sub.cancel()) + ..clear(); + } + + @override + Widget build(BuildContext context) { + Widget child = AnimatedBuilder( + animation: entry.visualChangeNotifier, + builder: (context, child) { + Widget? child; + if (entry.isSvg) { + child = _buildSvgView(); + } else if (!entry.displaySize.isEmpty) { + if (entry.isVideo) { + child = _buildVideoView(); + } else if (entry.isDecodingSupported) { + child = _buildRasterView(); + } + } + + child ??= ErrorView( + entry: entry, + onTap: _onTap, + ); + return child; + }, + ); + + if (!settings.viewerUseCutout) { + child = SafeCutoutArea( + child: ClipRect( + child: child, + ), + ); + } + + final animate = context.select<Settings, bool>((v) => v.animate); + if (animate) { + child = Consumer<EntryHeroInfo?>( + builder: (context, info, child) => Hero( + tag: info != null && info.entry == mainEntry ? info.tag : hashCode, + transitionOnUserGestures: true, + child: child!, + ), + child: child, + ); + } + + return child; + } + + Widget _buildRasterView() { + return _buildMagnifier( + applyScale: false, + child: RasterImageView( + entry: entry, + viewStateNotifier: _viewStateNotifier, + errorBuilder: (context, error, stackTrace) => ErrorView( + entry: entry, + onTap: _onTap, + ), + ), + ); + } + + Widget _buildSvgView() { + return _buildMagnifier( + maxScale: EntryPageView.vectorMaxScale, + scaleStateCycle: _vectorScaleStateCycle, + applyScale: false, + child: VectorImageView( + entry: entry, + viewStateNotifier: _viewStateNotifier, + errorBuilder: (context, error, stackTrace) => ErrorView( + entry: entry, + onTap: _onTap, + ), + ), + ); + } + + Widget _buildVideoView() { + final videoController = context.read<VideoConductor>().getController(entry); + if (videoController == null) return const SizedBox(); + + return ValueListenableBuilder<double?>( + valueListenable: videoController.sarNotifier, + builder: (context, sar, child) { + final videoDisplaySize = entry.videoDisplaySize(sar); + final isPureVideo = entry.isPureVideo; + + return Selector<Settings, (bool, bool, bool)>( + selector: (context, s) => ( + isPureVideo && s.videoGestureDoubleTapTogglePlay, + isPureVideo && s.videoGestureSideDoubleTapSeek, + isPureVideo && s.videoGestureVerticalDragBrightnessVolume, + ), + builder: (context, s, child) { + final (playGesture, seekGesture, useVerticalDragGesture) = s; + final useTapGesture = playGesture || seekGesture; + + MagnifierDoubleTapCallback? onDoubleTap; + MagnifierGestureScaleStartCallback? onScaleStart; + MagnifierGestureScaleUpdateCallback? onScaleUpdate; + MagnifierGestureScaleEndCallback? onScaleEnd; + + if (useTapGesture) { + void _applyAction(EntryAction action, {IconData? Function()? icon}) { + _actionFeedbackChildNotifier.value = DecoratedIcon( + icon?.call() ?? action.getIconData(), + size: 48, + color: Colors.white, + shadows: const [ + Shadow( + color: Colors.black, + blurRadius: 4, + ) + ], + ); + VideoActionNotification( + controller: videoController, + entry: entry, + action: action, + ).dispatch(context); + } + + onDoubleTap = (alignment) { + final x = alignment.x; + if (seekGesture) { + final sideRatio = _getSideRatio(); + if (sideRatio != null) { + if (x < sideRatio) { + _applyAction(EntryAction.videoReplay10); + return true; + } else if (x > 1 - sideRatio) { + _applyAction(EntryAction.videoSkip10); + return true; + } + } + } + if (playGesture) { + _applyAction( + EntryAction.videoTogglePlay, + icon: () => videoController.isPlaying ? AIcons.pause : AIcons.play, + ); + return true; + } + return false; + }; + } + + if (useVerticalDragGesture) { + SwipeAction? swipeAction; + var move = Offset.zero; + var dropped = false; + double? startValue; + ValueNotifier<double?>? valueNotifier; + + onScaleStart = (details, doubleTap, boundaries) { + dropped = details.pointerCount > 1 || doubleTap; + if (dropped) return; + + startValue = null; + valueNotifier = ValueNotifier<double?>(null); + final alignmentX = details.focalPoint.dx / boundaries.viewportSize.width; + final action = alignmentX > .5 ? SwipeAction.volume : SwipeAction.brightness; + action.get().then((v) => startValue = v); + swipeAction = action; + move = Offset.zero; + _actionFeedbackOverlayEntry = OverlayEntry( + builder: (context) => SwipeActionFeedback( + action: action, + valueNotifier: valueNotifier!, + ), + ); + Overlay.of(context).insert(_actionFeedbackOverlayEntry!); + }; + onScaleUpdate = (details) { + if (valueNotifier == null) return false; + + move += details.focalPointDelta; + dropped |= details.pointerCount > 1; + if (valueNotifier!.value == null) { + dropped |= MagnifierGestureRecognizer.isXPan(move); + } + if (dropped) return false; + + final _startValue = startValue; + if (_startValue != null) { + final double value = (_startValue - move.dy / SwipeActionFeedback.height).clamp(0, 1); + valueNotifier!.value = value; + swipeAction?.set(value); + } + return true; + }; + onScaleEnd = (details) { + valueNotifier?.dispose(); + + _actionFeedbackOverlayEntry + ?..remove() + ..dispose(); + _actionFeedbackOverlayEntry = null; + }; + } + + Widget videoChild = Stack( + children: [ + _buildMagnifier( + displaySize: videoDisplaySize, + onScaleStart: onScaleStart, + onScaleUpdate: onScaleUpdate, + onScaleEnd: onScaleEnd, + onDoubleTap: onDoubleTap, + child: VideoView( + entry: entry, + controller: videoController, + ), + ), + VideoSubtitles( + entry: entry, + controller: videoController, + viewStateNotifier: _viewStateNotifier, + ), + if (useTapGesture) + ValueListenableBuilder<Widget?>( + valueListenable: _actionFeedbackChildNotifier, + builder: (context, feedbackChild, child) => ActionFeedback( + child: feedbackChild, + ), + ), + ], + ); + if (useVerticalDragGesture) { + final scope = MagnifierGestureDetectorScope.maybeOf(context); + if (scope != null) { + videoChild = scope.copyWith( + acceptPointerEvent: MagnifierGestureRecognizer.isYPan, + child: videoChild, + ); + } + } + return Stack( + fit: StackFit.expand, + children: [ + videoChild, + VideoCover( + mainEntry: mainEntry, + pageEntry: entry, + magnifierController: _magnifierController, + videoController: videoController, + videoDisplaySize: videoDisplaySize, + onTap: _onTap, + magnifierBuilder: (coverController, coverSize, videoCoverUriImage) => _buildMagnifier( + controller: coverController, + displaySize: coverSize, + onDoubleTap: onDoubleTap, + child: Image( + image: videoCoverUriImage, + ), + ), + ), + ], + ); + }, + ); + }, + ); + } + + Widget _buildMagnifier({ + AvesMagnifierController? controller, + Size? displaySize, + ScaleLevel maxScale = EntryPageView.rasterMaxScale, + ScaleStateCycle scaleStateCycle = defaultScaleStateCycle, + bool applyScale = true, + MagnifierGestureScaleStartCallback? onScaleStart, + MagnifierGestureScaleUpdateCallback? onScaleUpdate, + MagnifierGestureScaleEndCallback? onScaleEnd, + MagnifierDoubleTapCallback? onDoubleTap, + required Widget child, + }) { + final isWallpaperMode = context.read<ValueNotifier<AppMode>>().value == AppMode.setWallpaper; + final minScale = isWallpaperMode ? const ScaleLevel(ref: ScaleReference.covered) : const ScaleLevel(ref: ScaleReference.contained); + + return ValueListenableBuilder<bool>( + valueListenable: AvesApp.canGestureToOtherApps, + builder: (context, canGestureToOtherApps, child) { + return AvesMagnifier( + // key includes modified date to refresh when the image is modified by metadata (e.g. rotated) + key: Key('${entry.uri}_${entry.pageId}_${entry.dateModifiedMillis}'), + controller: controller ?? _magnifierController, + contentSize: displaySize ?? entry.displaySize, + allowOriginalScaleBeyondRange: !isWallpaperMode, + allowDoubleTap: _allowDoubleTap, + minScale: minScale, + maxScale: maxScale, + initialScale: viewerController.initialScale, + scaleStateCycle: scaleStateCycle, + applyScale: applyScale, + onScaleStart: onScaleStart, + onScaleUpdate: onScaleUpdate, + onScaleEnd: onScaleEnd, + onFling: _onFling, + onTap: (context, _, alignment, __) { + if (context.mounted) { + _onTap(alignment: alignment); + } + }, + onLongPress: canGestureToOtherApps ? _startGlobalDrag : null, + onDoubleTap: onDoubleTap, + child: child!, + ); + }, + child: child, + ); + } + + Future<void> _startGlobalDrag() async { + const dragShadowSize = Size.square(128); + final cornerRadiusPx = await deviceService.getWidgetCornerRadiusPx(); + + final devicePixelRatio = MediaQuery.devicePixelRatioOf(context); + final brightness = Theme.of(context).brightness; + final outline = await WidgetOutline.systemBlackAndWhite.color(brightness); + + final dragShadowBytes = await HomeWidgetPainter( + entry: entry, + devicePixelRatio: devicePixelRatio, + ).drawWidget( + sizeDip: dragShadowSize, + cornerRadiusPx: cornerRadiusPx, + outline: outline, + shape: WidgetShape.rrect, + ); + + await windowService.startGlobalDrag(entry.uri, entry.bestTitle, dragShadowSize, dragShadowBytes); + } + + void _onFling(AxisDirection direction) { + const animate = true; + switch (direction) { + case AxisDirection.left: + (context.isRtl ? const ShowNextEntryNotification(animate: animate) : const ShowPreviousEntryNotification(animate: animate)).dispatch(context); + case AxisDirection.right: + (context.isRtl ? const ShowPreviousEntryNotification(animate: animate) : const ShowNextEntryNotification(animate: animate)).dispatch(context); + case AxisDirection.up: + PopVisualNotification().dispatch(context); + case AxisDirection.down: + ShowInfoPageNotification().dispatch(context); + } + } + + Notification? _handleSideSingleTap(Alignment? alignment) { + if (settings.viewerGestureSideTapNext && alignment != null) { + final x = alignment.x; + final sideRatio = _getSideRatio(); + if (sideRatio != null) { + const animate = false; + if (x < sideRatio) { + return context.isRtl ? const ShowNextEntryNotification(animate: animate) : const ShowPreviousEntryNotification(animate: animate); + } else if (x > 1 - sideRatio) { + return context.isRtl ? const ShowPreviousEntryNotification(animate: animate) : const ShowNextEntryNotification(animate: animate); + } + } + } + return null; + } + + void _onTap({Alignment? alignment}) => (_handleSideSingleTap(alignment) ?? const ToggleOverlayNotification()).dispatch(context); + + // side gesture handling by precedence: + // - seek in video by side double tap (if enabled) + // - go to previous/next entry by side single tap (if enabled) + // - zoom in/out by double tap + bool _allowDoubleTap(Alignment alignment) { + if (entry.isVideo && settings.videoGestureSideDoubleTapSeek) { + return true; + } + final actionNotification = _handleSideSingleTap(alignment); + return actionNotification == null; + } + + void _onMediaCommand(MediaCommandEvent event) { + final videoController = context.read<VideoConductor>().getController(entry); + if (videoController == null) return; + + switch (event.command) { + case MediaCommand.play: + videoController.play(); + case MediaCommand.pause: + videoController.pause(); + case MediaCommand.skipToNext: + ShowNextVideoNotification().dispatch(context); + case MediaCommand.skipToPrevious: + ShowPreviousVideoNotification().dispatch(context); + case MediaCommand.stop: + videoController.pause(); + case MediaCommand.seek: + if (event is MediaSeekCommandEvent) { + videoController.seekTo(event.position); + } + } + } + + void _onViewStateChanged(MagnifierState v) { + if (!mounted) return; + _viewStateNotifier.value = _viewStateNotifier.value.copyWith( + position: v.position, + scale: v.scale, + ); + } + + void _onViewScaleBoundariesChanged(ScaleBoundaries v) { + _viewStateNotifier.value = _viewStateNotifier.value.copyWith( + viewportSize: v.viewportSize, + contentSize: v.contentSize, + ); + } + + double? _getSideRatio() { + if (!mounted) return null; + final isPortrait = MediaQuery.orientationOf(context) == Orientation.portrait; + return isPortrait ? 1 / 6 : 1 / 8; + } + + static ScaleState _vectorScaleStateCycle(ScaleState actual) { + switch (actual) { + case ScaleState.initial: + return ScaleState.covering; + default: + return ScaleState.initial; + } + } +} diff --git a/lib/widgets/viewer/visual/error.dart b/lib/widgets/viewer/visual/error.dart new file mode 100644 index 0000000..5354d56 --- /dev/null +++ b/lib/widgets/viewer/visual/error.dart @@ -0,0 +1,60 @@ +import 'dart:io'; + +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/empty.dart'; +import 'package:aves/widgets/viewer/entry_viewer_page.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; + +class ErrorView extends StatefulWidget { + final AvesEntry entry; + final VoidCallback onTap; + + const ErrorView({ + super.key, + required this.entry, + required this.onTap, + }); + + @override + State<ErrorView> createState() => _ErrorViewState(); +} + +class _ErrorViewState extends State<ErrorView> { + late Future<bool> _exists; + + AvesEntry get entry => widget.entry; + + @override + void initState() { + super.initState(); + final path = entry.trashDetails?.path ?? entry.path; + _exists = path != null ? File(path).exists() : SynchronousFuture(true); + } + + @override + Widget build(BuildContext context) { + return GestureDetector( + onTap: () => widget.onTap(), + // use container to expand constraints, so that the user can tap anywhere + child: Container( + // opaque to cover potential lower quality layer below + color: EntryViewerPage.getBackground(context), + child: FutureBuilder<bool>( + future: _exists, + builder: (context, snapshot) { + if (snapshot.connectionState != ConnectionState.done) return const SizedBox(); + final exists = snapshot.data!; + return EmptyContent( + icon: exists ? AIcons.error : AIcons.broken, + text: exists ? context.l10n.viewerErrorUnknown : context.l10n.viewerErrorDoesNotExist, + alignment: Alignment.center, + safeBottom: false, + ); + }), + ), + ); + } +} diff --git a/lib/widgets/viewer/visual/raster.dart b/lib/widgets/viewer/visual/raster.dart new file mode 100644 index 0000000..9b77b3c --- /dev/null +++ b/lib/widgets/viewer/visual/raster.dart @@ -0,0 +1,517 @@ +import 'dart:math'; + +import 'package:aves/image_providers/region_provider.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/images.dart'; +import 'package:aves/model/entry/extensions/props.dart'; +import 'package:aves/model/settings/enums/entry_background.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/viewer/view_state.dart'; +import 'package:aves/widgets/common/fx/checkered_decoration.dart'; +import 'package:aves/widgets/viewer/controls/notifications.dart'; +import 'package:aves/widgets/viewer/visual/entry_page_view.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:latlong2/latlong.dart'; + +class RasterImageView extends StatefulWidget { + final AvesEntry entry; + final ValueNotifier<ViewState> viewStateNotifier; + final ImageErrorWidgetBuilder errorBuilder; + + const RasterImageView({ + super.key, + required this.entry, + required this.viewStateNotifier, + required this.errorBuilder, + }); + + @override + State<RasterImageView> createState() => _RasterImageViewState(); +} + +class _RasterImageViewState extends State<RasterImageView> { + late Size _displaySize; + late bool _useTiles; + bool _isTilingInitialized = false; + late int _maxSampleSize; + late double _tileSide; + Matrix4? _tileTransform; + ImageStream? _fullImageStream; + late ImageStreamListener _fullImageListener; + final ValueNotifier<bool> _fullImageLoaded = ValueNotifier(false); + ImageInfo? _fullImageInfo; + + static const int _pixelArtMaxSize = 256; // px + static const double _tilesByShortestSide = 2; + + AvesEntry get entry => widget.entry; + + ValueNotifier<ViewState> get viewStateNotifier => widget.viewStateNotifier; + + ViewState get viewState => viewStateNotifier.value; + + ImageProvider get thumbnailProvider => entry.bestCachedThumbnail; + + ImageProvider get fullImageProvider { + if (_useTiles) { + assert(_isTilingInitialized); + return entry.getRegion( + sampleSize: _maxSampleSize, + region: entry.fullImageRegion, + ); + } else { + return entry.fullImage; + } + } + + @override + void initState() { + super.initState(); + _displaySize = entry.displaySize; + _useTiles = entry.useTiles; + _fullImageListener = ImageStreamListener(_onFullImageCompleted); + if (!_useTiles) _registerFullImage(); + } + + @override + void didUpdateWidget(covariant RasterImageView oldWidget) { + super.didUpdateWidget(oldWidget); + + final oldViewState = oldWidget.viewStateNotifier.value; + final viewState = widget.viewStateNotifier.value; + if (oldWidget.entry != widget.entry || oldViewState.viewportSize != viewState.viewportSize) { + _isTilingInitialized = false; + _fullImageLoaded.value = false; + _unregisterFullImage(); + } + } + + @override + void dispose() { + _fullImageLoaded.dispose(); + _unregisterFullImage(); + super.dispose(); + } + + void _registerFullImage() { + _fullImageStream = fullImageProvider.resolve(ImageConfiguration.empty); + _fullImageStream!.addListener(_fullImageListener); + } + + void _unregisterFullImage() { + _fullImageStream?.removeListener(_fullImageListener); + _fullImageStream = null; + _fullImageInfo?.dispose(); + } + + void _onFullImageCompleted(ImageInfo image, bool synchronousCall) { + // implementer is responsible for disposing the provided `ImageInfo` + _unregisterFullImage(); + _fullImageInfo = image; + _fullImageLoaded.value = true; + FullImageLoadedNotification(entry, fullImageProvider).dispatch(context); + } + + @override + Widget build(BuildContext context) { + return ValueListenableBuilder<ViewState>( + valueListenable: viewStateNotifier, + builder: (context, viewState, child) { + final viewportSize = viewState.viewportSize; + final viewportSized = viewportSize?.isEmpty == false; + if (viewportSized && _useTiles && !_isTilingInitialized) _initTiling(viewportSize!); + + final magnifierScale = viewState.scale!; + return SizedBox.fromSize( + size: _displaySize * magnifierScale, + child: Stack( + alignment: Alignment.center, + children: [ + if (entry.canHaveAlpha && viewportSized) _buildBackground(), + _buildLoading(), + if (_useTiles) ..._buildTiles() else _buildFullImage(), + ], + ), + ); + }, + ); + } + + Widget _buildFullImage() { + final magnifierScale = viewState.scale!; + final devicePixelRatio = MediaQuery.of(context).devicePixelRatio; + final quality = _qualityForScaleAndSize( + magnifierScale: magnifierScale, + sampleSize: 1, + devicePixelRatio: devicePixelRatio, + ); + return Image( + image: fullImageProvider, + gaplessPlayback: true, + errorBuilder: widget.errorBuilder, + width: (_displaySize * magnifierScale).width, + fit: BoxFit.contain, + filterQuality: quality, + ); + } + + void _initTiling(Size viewportSize) { + final devicePixelRatio = MediaQuery.of(context).devicePixelRatio; + _tileSide = viewportSize.shortestSide * devicePixelRatio / _tilesByShortestSide; + // scale for initial state `contained` + final containedScale = min(viewportSize.width / _displaySize.width, viewportSize.height / _displaySize.height); + _maxSampleSize = ExtraAvesEntryImages.sampleSizeForScale(magnifierScale: containedScale, devicePixelRatio: devicePixelRatio); + + final rotationDegrees = entry.rotationDegrees; + final isFlipped = entry.isFlipped; + _tileTransform = null; + if (rotationDegrees != 0 || isFlipped) { + _tileTransform = Matrix4.identity() + ..translate(entry.width / 2.0, entry.height / 2.0) + ..scale(isFlipped ? -1.0 : 1.0, 1.0, 1.0) + ..rotateZ(-degToRadian(rotationDegrees.toDouble())) + ..translate(-_displaySize.width / 2.0, -_displaySize.height / 2.0); + } + _isTilingInitialized = true; + _registerFullImage(); + } + + Widget _buildLoading() { + return ValueListenableBuilder<bool>( + valueListenable: _fullImageLoaded, + builder: (context, fullImageLoaded, child) { + if (fullImageLoaded) return const SizedBox(); + + return Center( + child: AspectRatio( + // enforce original aspect ratio, as some thumbnails aspect ratios slightly differ + aspectRatio: entry.displayAspectRatio, + child: Image( + image: thumbnailProvider, + fit: BoxFit.fill, + ), + ), + ); + }, + ); + } + + Widget _buildBackground() { + final viewportSize = viewState.viewportSize!; + final viewSize = _displaySize * viewState.scale!; + final decorationOffset = ((viewSize - viewportSize) as Offset) / 2 - viewState.position; + // deflate as a quick way to prevent background bleed + final decorationSize = (applyBoxFit(BoxFit.none, viewSize, viewportSize).source - const Offset(.5, .5)) as Size; + + Widget child; + final background = settings.imageBackground; + if (background == EntryBackground.checkered) { + final side = viewportSize.shortestSide; + final checkSize = side / ((side / EntryPageView.decorationCheckSize).round()); + final offset = ((decorationSize - viewportSize) as Offset) / 2; + child = ValueListenableBuilder<bool>( + valueListenable: _fullImageLoaded, + builder: (context, fullImageLoaded, child) { + if (!fullImageLoaded) return const SizedBox(); + + return CustomPaint( + painter: CheckeredPainter( + checkSize: checkSize, + offset: offset, + ), + ); + }, + ); + } else { + child = DecoratedBox( + decoration: BoxDecoration( + color: background.color, + ), + ); + } + return Positioned( + left: decorationOffset.dx >= 0 ? decorationOffset.dx : null, + top: decorationOffset.dy >= 0 ? decorationOffset.dy : null, + width: decorationSize.width, + height: decorationSize.height, + child: child, + ); + } + + List<Widget> _buildTiles() { + if (!_isTilingInitialized) return []; + + final displayWidth = _displaySize.width.round(); + final displayHeight = _displaySize.height.round(); + final viewRect = _getViewRect(displayWidth, displayHeight); + final magnifierScale = viewState.scale!; + final devicePixelRatio = MediaQuery.of(context).devicePixelRatio; + + // for the largest sample size (matching the initial scale), the whole image is in view + // so we subsample the whole image without tiling + final fullImageRegionTile = _RegionTile( + entry: entry, + tileRect: Rect.fromLTWH(0, 0, displayWidth * magnifierScale, displayHeight * magnifierScale), + regionRect: entry.fullImageRegion, + sampleSize: _maxSampleSize, + quality: _qualityForScaleAndSize( + magnifierScale: magnifierScale, + sampleSize: _maxSampleSize, + devicePixelRatio: devicePixelRatio, + ), + ); + final tiles = [fullImageRegionTile]; + + final minSampleSize = min(ExtraAvesEntryImages.sampleSizeForScale(magnifierScale: magnifierScale, devicePixelRatio: devicePixelRatio), _maxSampleSize); + int nextSampleSize(int sampleSize) => (sampleSize / 2).floor(); + for (var sampleSize = nextSampleSize(_maxSampleSize); sampleSize >= minSampleSize; sampleSize = nextSampleSize(sampleSize)) { + final regionSide = (_tileSide * sampleSize).round(); + for (var x = 0; x < displayWidth; x += regionSide) { + for (var y = 0; y < displayHeight; y += regionSide) { + final rects = _getTileRects( + x: x, + y: y, + regionSide: regionSide, + displayWidth: displayWidth, + displayHeight: displayHeight, + scale: magnifierScale, + viewRect: viewRect, + ); + if (rects != null) { + final (tileRect, regionRect) = rects; + tiles.add(_RegionTile( + entry: entry, + tileRect: tileRect, + regionRect: regionRect, + sampleSize: sampleSize, + quality: _qualityForScaleAndSize( + magnifierScale: magnifierScale, + sampleSize: sampleSize, + devicePixelRatio: devicePixelRatio, + ), + )); + } + } + } + } + return tiles; + } + + Rect _getViewRect(int displayWidth, int displayHeight) { + final scale = viewState.scale!; + final centerOffset = viewState.position; + final viewportSize = viewState.viewportSize!; + final viewOrigin = Offset( + ((displayWidth * scale - viewportSize.width) / 2 - centerOffset.dx), + ((displayHeight * scale - viewportSize.height) / 2 - centerOffset.dy), + ); + return viewOrigin & viewportSize; + } + + (Rect tileRect, Rectangle<num> regionRect)? _getTileRects({ + required int x, + required int y, + required int regionSide, + required int displayWidth, + required int displayHeight, + required double scale, + required Rect viewRect, + }) { + final nextX = x + regionSide; + final nextY = y + regionSide; + final thisRegionWidth = regionSide - (nextX >= displayWidth ? nextX - displayWidth : 0); + final thisRegionHeight = regionSide - (nextY >= displayHeight ? nextY - displayHeight : 0); + final tileRect = Rect.fromLTWH(x * scale, y * scale, thisRegionWidth * scale, thisRegionHeight * scale); + + // only build visible tiles + if (!viewRect.overlaps(tileRect)) return null; + + Rectangle<num> regionRect; + if (_tileTransform != null) { + // apply EXIF orientation + final regionRectDouble = Rect.fromLTWH(x.toDouble(), y.toDouble(), thisRegionWidth.toDouble(), thisRegionHeight.toDouble()); + final tl = MatrixUtils.transformPoint(_tileTransform!, regionRectDouble.topLeft); + final br = MatrixUtils.transformPoint(_tileTransform!, regionRectDouble.bottomRight); + regionRect = Rectangle<double>.fromPoints( + Point<double>(tl.dx, tl.dy), + Point<double>(br.dx, br.dy), + ); + } else { + regionRect = Rectangle<num>(x, y, thisRegionWidth, thisRegionHeight); + } + return (tileRect, regionRect); + } + + // follow recommended thresholds from `FilterQuality` documentation + static FilterQuality _qualityForScale({ + required double magnifierScale, + required int sampleSize, + required double devicePixelRatio, + }) { + final entryScale = magnifierScale * devicePixelRatio; + final renderingScale = entryScale * sampleSize; + if (renderingScale > 1) { + return renderingScale > 10 ? FilterQuality.high : FilterQuality.medium; + } else { + return renderingScale < .5 ? FilterQuality.medium : FilterQuality.high; + } + } + + // usually follow recommendations, except for small images + // (like icons, pixel art, etc.) for which the "nearest neighbor" algorithm is used + FilterQuality _qualityForScaleAndSize({ + required double magnifierScale, + required int sampleSize, + required double devicePixelRatio, + }) { + if (_displaySize.longestSide < _pixelArtMaxSize) { + return FilterQuality.none; + } + + return _qualityForScale( + magnifierScale: magnifierScale, + sampleSize: sampleSize, + devicePixelRatio: devicePixelRatio, + ); + } +} + +class _RegionTile extends StatefulWidget { + final AvesEntry entry; + + // `tileRect` uses Flutter view coordinates + // `regionRect` uses the raw image pixel coordinates + final Rect tileRect; + final Rectangle<num> regionRect; + final int sampleSize; + final FilterQuality quality; + + const _RegionTile({ + required this.entry, + required this.tileRect, + required this.regionRect, + required this.sampleSize, + required this.quality, + }); + + @override + State<_RegionTile> createState() => _RegionTileState(); + + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + super.debugFillProperties(properties); + properties.add(IntProperty('id', entry.id)); + properties.add(IntProperty('contentId', entry.contentId)); + properties.add(DiagnosticsProperty<Rect>('tileRect', tileRect)); + properties.add(DiagnosticsProperty<Rectangle<num>>('regionRect', regionRect)); + properties.add(IntProperty('sampleSize', sampleSize)); + } +} + +class _RegionTileState extends State<_RegionTile> { + late RegionProvider _provider; + + AvesEntry get entry => widget.entry; + + @override + void initState() { + super.initState(); + _registerWidget(widget); + } + + @override + void didUpdateWidget(covariant _RegionTile oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.entry != widget.entry || oldWidget.tileRect != widget.tileRect || oldWidget.sampleSize != widget.sampleSize || oldWidget.sampleSize != widget.sampleSize) { + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + } + + @override + void dispose() { + _unregisterWidget(widget); + super.dispose(); + } + + void _registerWidget(_RegionTile widget) { + _initProvider(); + } + + void _unregisterWidget(_RegionTile widget) { + _pauseProvider(); + } + + void _initProvider() { + _provider = entry.getRegion( + sampleSize: widget.sampleSize, + region: widget.regionRect, + ); + } + + void _pauseProvider() => _provider.pause(); + + @override + Widget build(BuildContext context) { + final tileRect = widget.tileRect; + + Widget child = Image( + image: _provider, + width: tileRect.width, + height: tileRect.height, + fit: BoxFit.fill, + filterQuality: widget.quality, + ); + + // apply EXIF orientation + final quarterTurns = entry.rotationDegrees ~/ 90; + if (entry.isFlipped) { + final rotated = quarterTurns % 2 != 0; + final w = (rotated ? tileRect.height : tileRect.width) / 2.0; + final h = (rotated ? tileRect.width : tileRect.height) / 2.0; + final flipper = Matrix4.identity() + ..translate(w, h) + ..scale(-1.0, 1.0, 1.0) + ..translate(-w, -h); + child = Transform( + transform: flipper, + child: child, + ); + } + if (quarterTurns != 0) { + child = RotatedBox( + quarterTurns: quarterTurns, + child: child, + ); + } + + if (settings.debugShowViewerTiles) { + final regionRect = widget.regionRect; + child = Stack( + children: [ + Positioned.fill(child: child), + Text( + '\ntile=(${tileRect.left.round()}, ${tileRect.top.round()}) ${tileRect.width.round()} x ${tileRect.height.round()}' + '\nregion=(${regionRect.left.round()}, ${regionRect.top.round()}) ${regionRect.width.round()} x ${regionRect.height.round()}' + '\nsampling=${widget.sampleSize} quality=${widget.quality.name}', + style: const TextStyle(backgroundColor: Colors.black87), + ), + Positioned.fill( + child: DecoratedBox( + decoration: BoxDecoration( + border: Border.all(color: Colors.red, width: 1), + ), + ), + ), + ], + ); + } + + return Positioned.fromRect( + rect: tileRect, + child: child, + ); + } +} diff --git a/lib/widgets/viewer/visual/vector.dart b/lib/widgets/viewer/visual/vector.dart new file mode 100644 index 0000000..207d6bc --- /dev/null +++ b/lib/widgets/viewer/visual/vector.dart @@ -0,0 +1,443 @@ +import 'dart:math'; + +import 'package:aves/image_providers/region_provider.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/images.dart'; +import 'package:aves/model/settings/enums/entry_background.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/viewer/view_state.dart'; +import 'package:aves/utils/math_utils.dart'; +import 'package:aves/widgets/common/fx/checkered_decoration.dart'; +import 'package:aves/widgets/viewer/visual/entry_page_view.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; + +class VectorImageView extends StatefulWidget { + final AvesEntry entry; + final ValueNotifier<ViewState> viewStateNotifier; + final ImageErrorWidgetBuilder errorBuilder; + + const VectorImageView({ + super.key, + required this.entry, + required this.viewStateNotifier, + required this.errorBuilder, + }); + + @override + State<VectorImageView> createState() => _VectorImageViewState(); +} + +class _VectorImageViewState extends State<VectorImageView> { + late Size _displaySize; + bool _isTilingInitialized = false; + late double _minScale; + late double _tileSide; + ImageStream? _fullImageStream; + late ImageStreamListener _fullImageListener; + final ValueNotifier<bool> _fullImageLoaded = ValueNotifier(false); + ImageInfo? _fullImageInfo; + + AvesEntry get entry => widget.entry; + + ValueNotifier<ViewState> get viewStateNotifier => widget.viewStateNotifier; + + ViewState get viewState => viewStateNotifier.value; + + ImageProvider get thumbnailProvider => entry.bestCachedThumbnail; + + ImageProvider get fullImageProvider { + assert(_isTilingInitialized); + return entry.getRegion( + scale: _minScale, + region: entry.fullImageRegion, + ); + } + + @override + void initState() { + super.initState(); + _displaySize = entry.displaySize; + _fullImageListener = ImageStreamListener(_onFullImageCompleted); + } + + @override + void didUpdateWidget(covariant VectorImageView oldWidget) { + super.didUpdateWidget(oldWidget); + + final oldViewState = oldWidget.viewStateNotifier.value; + final viewState = widget.viewStateNotifier.value; + if (oldWidget.entry != widget.entry || oldViewState.viewportSize != viewState.viewportSize) { + _isTilingInitialized = false; + _fullImageLoaded.value = false; + _unregisterFullImage(); + } + } + + @override + void dispose() { + _fullImageLoaded.dispose(); + _unregisterFullImage(); + super.dispose(); + } + + void _registerFullImage() { + _fullImageStream = fullImageProvider.resolve(ImageConfiguration.empty); + _fullImageStream!.addListener(_fullImageListener); + } + + void _unregisterFullImage() { + _fullImageStream?.removeListener(_fullImageListener); + _fullImageStream = null; + _fullImageInfo?.dispose(); + } + + void _onFullImageCompleted(ImageInfo image, bool synchronousCall) { + // implementer is responsible for disposing the provided `ImageInfo` + _unregisterFullImage(); + _fullImageInfo = image; + _fullImageLoaded.value = true; + } + + @override + Widget build(BuildContext context) { + if (_displaySize == Size.zero) return widget.errorBuilder(context, 'Not sized', null); + + final devicePixelRatio = MediaQuery.devicePixelRatioOf(context); + return ValueListenableBuilder<ViewState>( + valueListenable: viewStateNotifier, + builder: (context, viewState, child) { + final viewportSize = viewState.viewportSize; + final viewportSized = viewportSize?.isEmpty == false; + if (viewportSized && !_isTilingInitialized) { + _initTiling( + viewportSize: viewportSize!, + devicePixelRatio: devicePixelRatio, + ); + } + + return SizedBox.fromSize( + size: _displaySize * viewState.scale!, + child: Stack( + alignment: Alignment.center, + children: [ + _buildLoading(), + ..._getTiles(devicePixelRatio), + ], + ), + ); + }, + ); + } + + void _initTiling({ + required Size viewportSize, + required double devicePixelRatio, + }) { + _tileSide = _displaySize.longestSide; + // scale for initial state `contained` + final containedScale = min(viewportSize.width / _displaySize.width, viewportSize.height / _displaySize.height); + _minScale = _imageScaleForViewScale(scale: containedScale, devicePixelRatio: devicePixelRatio); + + _isTilingInitialized = true; + _registerFullImage(); + } + + Widget _buildLoading() { + return ValueListenableBuilder<bool>( + valueListenable: _fullImageLoaded, + builder: (context, fullImageLoaded, child) { + if (fullImageLoaded) return const SizedBox(); + + return Center( + child: AspectRatio( + // enforce original aspect ratio, as some thumbnails aspect ratios slightly differ + aspectRatio: entry.displayAspectRatio, + child: Image( + image: thumbnailProvider, + fit: BoxFit.fill, + ), + ), + ); + }, + ); + } + + List<Widget> _getTiles(double devicePixelRatio) { + if (!_isTilingInitialized) return []; + + final displayWidth = _displaySize.width; + final displayHeight = _displaySize.height; + final viewRect = _getViewRect(displayWidth, displayHeight); + final viewScale = viewState.scale!; + final background = settings.imageBackground; + + Color? backgroundColor; + _BackgroundFrameBuilder? backgroundFrameBuilder; + if (background.isColor) { + backgroundColor = background.color; + } else if (background == EntryBackground.checkered) { + final viewportSize = viewState.viewportSize!; + final viewSize = _displaySize * viewState.scale!; + + final backgroundSize = applyBoxFit(BoxFit.none, viewSize, viewportSize).source; + var backgroundOffset = ((viewSize - viewportSize) as Offset) / 2 - viewState.position; + backgroundOffset = Offset(max(0, backgroundOffset.dx), max(0, backgroundOffset.dy)); + backgroundOffset += ((backgroundSize - viewportSize) as Offset) / 2; + + final side = viewportSize.shortestSide; + final checkSize = side / ((side / EntryPageView.decorationCheckSize).round()); + + backgroundFrameBuilder = (child, frame, tileRect) { + return frame == null + ? const SizedBox() + : DecoratedBox( + decoration: _CheckeredBackgroundDecoration( + viewportSize: viewportSize, + checkSize: checkSize, + offset: backgroundOffset - tileRect.topLeft, + ), + child: child, + ); + }; + } + + // for the largest sample size (matching the initial scale), the whole image is in view + // so we subsample the whole image without tiling + final fullImageRegionTile = _RegionTile( + entry: entry, + tileRect: Rect.fromLTWH(0, 0, displayWidth * viewScale, displayHeight * viewScale), + regionRect: entry.fullImageRegion, + scale: _minScale, + backgroundColor: backgroundColor, + backgroundFrameBuilder: backgroundFrameBuilder, + ); + final tiles = <Widget>[fullImageRegionTile]; + + final maxSvgScale = max(_imageScaleForViewScale(scale: viewScale, devicePixelRatio: devicePixelRatio), _minScale); + double nextScale(double scale) => scale * 2; + // add `alpha` to the region side so that tiles do not align across layers, + // which helps the checkered background deflation workaround + // for the tile background bleeding issue + var alpha = 0; + for (var svgScale = nextScale(_minScale); svgScale <= maxSvgScale; svgScale = nextScale(svgScale)) { + final regionSide = (_tileSide + alpha++) / (svgScale / _minScale); + for (var x = .0; x < displayWidth; x += regionSide) { + for (var y = .0; y < displayHeight; y += regionSide) { + final rects = _getTileRects( + x: x, + y: y, + regionSide: regionSide, + displayWidth: displayWidth, + displayHeight: displayHeight, + scale: viewScale, + viewRect: viewRect, + ); + if (rects != null) { + final (tileRect, regionRect) = rects; + tiles.add(_RegionTile( + entry: entry, + tileRect: tileRect, + regionRect: regionRect, + scale: svgScale, + backgroundColor: backgroundColor, + backgroundFrameBuilder: backgroundFrameBuilder, + )); + } + } + } + } + return tiles; + } + + Rect _getViewRect(double displayWidth, double displayHeight) { + final scale = viewState.scale!; + final centerOffset = viewState.position; + final viewportSize = viewState.viewportSize!; + final viewOrigin = Offset( + ((displayWidth * scale - viewportSize.width) / 2 - centerOffset.dx), + ((displayHeight * scale - viewportSize.height) / 2 - centerOffset.dy), + ); + return viewOrigin & viewportSize; + } + + (Rect tileRect, Rectangle<double> regionRect)? _getTileRects({ + required double x, + required double y, + required double regionSide, + required double displayWidth, + required double displayHeight, + required double scale, + required Rect viewRect, + }) { + final nextX = x + regionSide; + final nextY = y + regionSide; + final thisRegionWidth = regionSide - (nextX >= displayWidth ? nextX - displayWidth : 0); + final thisRegionHeight = regionSide - (nextY >= displayHeight ? nextY - displayHeight : 0); + final tileRect = Rect.fromLTWH(x * scale, y * scale, thisRegionWidth * scale, thisRegionHeight * scale); + + // only build visible tiles + if (!viewRect.overlaps(tileRect)) return null; + + final regionRect = Rectangle<double>(x, y, thisRegionWidth, thisRegionHeight); + return (tileRect, regionRect); + } + + double _imageScaleForViewScale({ + required double scale, + required double devicePixelRatio, + }) => + smallestPowerOf2(scale * devicePixelRatio, allowNegativePower: true).toDouble(); +} + +typedef _BackgroundFrameBuilder = Widget Function(Widget child, int? frame, Rect tileRect); + +class _RegionTile extends StatefulWidget { + final AvesEntry entry; + + // `tileRect` uses Flutter view coordinates + // `regionRect` uses the raw image pixel coordinates + final Rect tileRect; + final Rectangle<double> regionRect; + final double scale; + final Color? backgroundColor; + final _BackgroundFrameBuilder? backgroundFrameBuilder; + + const _RegionTile({ + required this.entry, + required this.tileRect, + required this.regionRect, + required this.scale, + required this.backgroundColor, + required this.backgroundFrameBuilder, + }); + + @override + State<_RegionTile> createState() => _RegionTileState(); + + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + super.debugFillProperties(properties); + properties.add(IntProperty('id', entry.id)); + properties.add(IntProperty('contentId', entry.contentId)); + properties.add(DiagnosticsProperty<Rect>('tileRect', tileRect)); + properties.add(DiagnosticsProperty<Rectangle<double>>('regionRect', regionRect)); + properties.add(DoubleProperty('scale', scale)); + } +} + +class _RegionTileState extends State<_RegionTile> { + late RegionProvider _provider; + + AvesEntry get entry => widget.entry; + + @override + void initState() { + super.initState(); + _registerWidget(widget); + } + + @override + void didUpdateWidget(covariant _RegionTile oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.entry != widget.entry || oldWidget.tileRect != widget.tileRect || oldWidget.scale != widget.scale || oldWidget.scale != widget.scale) { + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + } + + @override + void dispose() { + _unregisterWidget(widget); + super.dispose(); + } + + void _registerWidget(_RegionTile widget) { + _initProvider(); + } + + void _unregisterWidget(_RegionTile widget) { + _pauseProvider(); + } + + void _initProvider() { + _provider = entry.getRegion( + scale: widget.scale, + region: widget.regionRect, + ); + } + + void _pauseProvider() => _provider.pause(); + + @override + Widget build(BuildContext context) { + final tileRect = widget.tileRect; + + Widget child = Image( + image: _provider, + frameBuilder: (_, child, frame, __) => widget.backgroundFrameBuilder?.call(child, frame, tileRect) ?? child, + width: tileRect.width, + height: tileRect.height, + color: widget.backgroundColor, + colorBlendMode: BlendMode.dstOver, + fit: BoxFit.fill, + ); + + return Positioned.fromRect( + rect: tileRect, + child: child, + ); + } +} + +class _CheckeredBackgroundDecoration extends Decoration { + final Size viewportSize; + final double checkSize; + final Offset offset; + + const _CheckeredBackgroundDecoration({ + required this.viewportSize, + required this.checkSize, + required this.offset, + }); + + @override + _CheckeredBackgroundDecorationPainter createBoxPainter([VoidCallback? onChanged]) { + return _CheckeredBackgroundDecorationPainter(this, onChanged); + } +} + +class _CheckeredBackgroundDecorationPainter extends BoxPainter { + final _CheckeredBackgroundDecoration decoration; + + const _CheckeredBackgroundDecorationPainter(this.decoration, VoidCallback? onChanged) : super(onChanged); + + static const deflation = Offset(.5, .5); + + @override + void paint(Canvas canvas, Offset offset, ImageConfiguration configuration) { + final size = configuration.size; + if (size == null) return; + + var decorated = offset & size; + // deflate background as a workaround for background bleeding beyond tile image + decorated = Rect.fromLTRB( + decorated.left + deflation.dx, + decorated.top + deflation.dy, + decorated.right - deflation.dx, + decorated.bottom - deflation.dy, + ); + + final visible = decorated.intersect(Offset.zero & decoration.viewportSize); + final checkOffset = decoration.offset + decorated.topLeft - visible.topLeft - deflation; + + final translation = Offset(max(0, offset.dx + deflation.dx), max(0, offset.dy + deflation.dy)); + canvas.translate(translation.dx, translation.dy); + CheckeredPainter( + checkSize: decoration.checkSize, + offset: checkOffset, + ).paint(canvas, visible.size); + canvas.translate(-translation.dx, -translation.dy); + } +} diff --git a/lib/widgets/viewer/visual/video/cover.dart b/lib/widgets/viewer/visual/video/cover.dart new file mode 100644 index 0000000..e7df3d5 --- /dev/null +++ b/lib/widgets/viewer/visual/video/cover.dart @@ -0,0 +1,164 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/images.dart'; +import 'package:aves/model/entry/extensions/multipage.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/widgets/common/thumbnail/image.dart'; +import 'package:aves_magnifier/aves_magnifier.dart'; +import 'package:aves_video/aves_video.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; + +class VideoCover extends StatefulWidget { + final AvesEntry mainEntry, pageEntry; + final AvesMagnifierController magnifierController; + final AvesVideoController videoController; + final Size videoDisplaySize; + final void Function({Alignment? alignment}) onTap; + final Widget Function( + AvesMagnifierController coverController, + Size coverSize, + ImageProvider videoCoverUriImage, + ) magnifierBuilder; + + const VideoCover({ + super.key, + required this.mainEntry, + required this.pageEntry, + required this.magnifierController, + required this.videoController, + required this.videoDisplaySize, + required this.onTap, + required this.magnifierBuilder, + }); + + @override + State<VideoCover> createState() => _VideoCoverState(); +} + +class _VideoCoverState extends State<VideoCover> { + ImageStream? _videoCoverStream; + late ImageStreamListener _videoCoverStreamListener; + final ValueNotifier<ImageInfo?> _videoCoverInfoNotifier = ValueNotifier(null); + + AvesMagnifierController? _dismissedCoverMagnifierController; + + AvesMagnifierController get dismissedCoverMagnifierController { + _dismissedCoverMagnifierController ??= AvesMagnifierController(); + return _dismissedCoverMagnifierController!; + } + + AvesEntry get mainEntry => widget.mainEntry; + + AvesEntry get entry => widget.pageEntry; + + AvesMagnifierController get magnifierController => widget.magnifierController; + + AvesVideoController get videoController => widget.videoController; + + Size get videoDisplaySize => widget.videoDisplaySize; + + // use the high res photo as cover for the video part of a motion photo + ImageProvider get videoCoverUriImage => (mainEntry.isMotionPhoto ? mainEntry : entry).fullImage; + + @override + void initState() { + super.initState(); + _registerWidget(widget); + } + + @override + void didUpdateWidget(covariant VideoCover oldWidget) { + super.didUpdateWidget(oldWidget); + + if (oldWidget.pageEntry != widget.pageEntry) { + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + } + + @override + void dispose() { + _unregisterWidget(widget); + _dismissedCoverMagnifierController?.dispose(); + _videoCoverInfoNotifier.dispose(); + super.dispose(); + } + + void _registerWidget(VideoCover widget) { + _videoCoverStreamListener = ImageStreamListener((image, _) => _videoCoverInfoNotifier.value = image); + _videoCoverStream = videoCoverUriImage.resolve(ImageConfiguration.empty); + _videoCoverStream!.addListener(_videoCoverStreamListener); + } + + void _unregisterWidget(VideoCover oldWidget) { + _videoCoverStream?.removeListener(_videoCoverStreamListener); + _videoCoverStream = null; + _videoCoverInfoNotifier.value = null; + } + + @override + Widget build(BuildContext context) { + // fade out image to ease transition with the player + return StreamBuilder<VideoStatus>( + stream: videoController.statusStream, + builder: (context, snapshot) { + final showCover = !videoController.isReady; + return IgnorePointer( + ignoring: !showCover, + child: AnimatedOpacity( + opacity: showCover ? 1 : 0, + curve: Curves.easeInCirc, + duration: ADurations.viewerVideoPlayerTransition, + onEnd: () { + // while cover is fading out, the same controller is used for both the cover and the video, + // and both fire scale boundaries events, so we make sure that in the end + // the scale boundaries from the video are used after the cover is gone + final boundaries = magnifierController.scaleBoundaries; + if (boundaries != null) { + magnifierController.setScaleBoundaries( + boundaries.copyWith( + contentSize: videoDisplaySize, + ), + ); + } + }, + child: ValueListenableBuilder<ImageInfo?>( + valueListenable: _videoCoverInfoNotifier, + builder: (context, videoCoverInfo, child) { + if (videoCoverInfo != null) { + // full cover image may have a different size and different aspect ratio + final coverSize = Size( + videoCoverInfo.image.width.toDouble(), + videoCoverInfo.image.height.toDouble(), + ); + // when the cover is the same size as the video itself + // (which is often the case when the cover is not embedded but just a frame), + // we can reuse the same magnifier and preserve its state when switching from cover to video + final coverController = showCover || coverSize == videoDisplaySize ? magnifierController : dismissedCoverMagnifierController; + return widget.magnifierBuilder(coverController, coverSize, videoCoverUriImage); + } + + // default to cached thumbnail, if any + final extent = entry.cachedThumbnails.firstOrNull?.key.extent; + if (extent != null && extent > 0) { + return GestureDetector( + onTap: widget.onTap, + child: ThumbnailImage( + entry: entry, + extent: extent, + devicePixelRatio: MediaQuery.devicePixelRatioOf(context), + fit: BoxFit.contain, + showLoadingBackground: false, + ), + ); + } + + return const SizedBox(); + }, + ), + ), + ); + }, + ); + } +} diff --git a/lib/widgets/viewer/visual/video/subtitle/ass_parser.dart b/lib/widgets/viewer/visual/video/subtitle/ass_parser.dart new file mode 100644 index 0000000..6b2da5b --- /dev/null +++ b/lib/widgets/viewer/visual/video/subtitle/ass_parser.dart @@ -0,0 +1,559 @@ +import 'package:aves/ref/unicode.dart'; +import 'package:aves/widgets/viewer/visual/video/subtitle/line.dart'; +import 'package:aves/widgets/viewer/visual/video/subtitle/span.dart'; +import 'package:aves/widgets/viewer/visual/video/subtitle/style.dart'; +import 'package:flutter/material.dart'; + +class AssParser { + // the optional `*` before the tags seems to be used for inner overrides + // but specs for its usage are yet to be found + static final overridePattern = RegExp(r'{\*?(.*?)}'); + + static final tagPattern = RegExp(r'(' + r'1a|2a|3a|4a' + r'|1c|2c|3c|4c' + r'|alpha|an|a' + r'|be|blur|bord|b' + r'|clip|c' + r'|fade|fad|fax|fay|fe|fn' + r'|frx|fry|frz|fr|fscx|fscy|fsp|fs' + r'|iclip|i' + r'|kf|ko|k|K' + r'|move|org' + r'|pbo|pos|p' + r'|q|r' + r'|shad|s' + r'|t|u' + r'|xbord|xshad|ybord|yshad' + r')'); + + // &H<aa> + static final alphaPattern = RegExp('&H(..)'); + + // &H<bb><gg><rr>& + static final colorPattern = RegExp('&H(..)(..)(..)&'); + + // (<X>,<Y>) + static final multiParamPattern = RegExp('\\((.*)\\)'); + + // e.g. m 937.5 472.67 b 937.5 472.67 937.25 501.25 960 501.5 960 501.5 937.5 500.33 937.5 529.83 + static final pathPattern = RegExp(r'([mnlbspc])([.\s\d]+)'); + + // Parse text with ASS style overrides + // cf https://aegi.vmoe.info/docs/3.0/ASS_Tags/ + // e.g. `And I'm like, "We can't {\i1}not{\i0} see it."` + // e.g. `{\fad(200,200)\blur3}lorem ipsum"` + // e.g. `{\fnCrapFLTSB\an9\bord5\fs70\c&H403A2D&\3c&HE5E5E8&\pos(1868.286,27.429)}lorem ipsum"` + static StyledSubtitleLine parse(String text, TextStyle baseStyle, double scale) { + final spans = <StyledSubtitleSpan>[]; + var line = StyledSubtitleLine(spans: spans); + var extraStyle = const SubtitleStyle(); + var textStyle = baseStyle; + var i = 0; + final overrideMatches = overridePattern.allMatches(text); + overrideMatches.forEach((overrideMatch) { + if (i != overrideMatch.start) { + final spanText = extraStyle.drawingPaths?.isNotEmpty == true ? null : _replaceChars(text.substring(i, overrideMatch.start)); + spans.add(StyledSubtitleSpan( + textSpan: TextSpan( + text: spanText, + style: textStyle, + ), + extraStyle: extraStyle, + )); + } + i = overrideMatch.end; + final tags = overrideMatch.group(1); + tags?.split('\\').where((v) => v.isNotEmpty).forEach((tagWithParam) { + final tag = tagPattern.firstMatch(tagWithParam)?.group(1); + if (tag != null) { + final param = tagWithParam.substring(tag.length); + switch (tag) { + case 'alpha': + { + // \alpha: alpha of all components at once + final a = _parseAlpha(param); + if (a != null) { + textStyle = textStyle.copyWith( + color: textStyle.color?.withAlpha(a), + shadows: textStyle.shadows + ?.map((v) => Shadow( + color: v.color.withAlpha(a), + offset: v.offset, + blurRadius: v.blurRadius, + )) + .toList()); + extraStyle = extraStyle.copyWith( + borderColor: extraStyle.borderColor?.withAlpha(a), + ); + } + } + case '1a': + { + // \1a: fill alpha + final a = _parseAlpha(param); + if (a != null) textStyle = textStyle.copyWith(color: textStyle.color?.withAlpha(a)); + } + case '3a': + { + // \3a: border alpha + final a = _parseAlpha(param); + if (a != null) extraStyle = extraStyle.copyWith(borderColor: extraStyle.borderColor?.withAlpha(a)); + } + case '4a': + { + // \4a: shadow alpha + final a = _parseAlpha(param); + if (a != null) { + textStyle = textStyle.copyWith( + shadows: textStyle.shadows + ?.map((v) => Shadow( + color: v.color.withAlpha(a), + offset: v.offset, + blurRadius: v.blurRadius, + )) + .toList()); + } + } + case 'a': + // \a: line alignment (legacy) + extraStyle = _copyWithAlignment(_parseLegacyAlignment(param), extraStyle); + case 'an': + // \an: line alignment + extraStyle = _copyWithAlignment(_parseNewAlignment(param), extraStyle); + case 'b': + { + // \b: bold + final weight = _parseFontWeight(param); + if (weight != null) textStyle = textStyle.copyWith(fontWeight: weight); + } + case 'be': + { + // \be: blurs the edges of the text + final times = int.tryParse(param); + if (times != null) extraStyle = extraStyle.copyWith(edgeBlur: times == 0 ? 0 : 1); + } + case 'blur': + { + // \blur: blurs the edges of the text (Gaussian kernel) + final strength = double.tryParse(param); + if (strength != null) extraStyle = extraStyle.copyWith(edgeBlur: strength / 2); + } + case 'bord': + { + // \bord: border width + final size = double.tryParse(param); + if (size != null) extraStyle = extraStyle.copyWith(borderWidth: size); + } + case 'c': + case '1c': + { + // \c or \1c: fill color + final color = _parseColor(param); + if (color != null) { + textStyle = textStyle.copyWith(color: color.withValues(alpha: textStyle.color?.a ?? 1)); + } + } + case '3c': + { + // \3c: border color + final color = _parseColor(param); + if (color != null) { + extraStyle = extraStyle.copyWith( + borderColor: color.withValues(alpha: extraStyle.borderColor?.a ?? 1), + ); + } + } + case '4c': + { + // \4c: shadow color + final color = _parseColor(param); + if (color != null) { + textStyle = textStyle.copyWith( + shadows: textStyle.shadows + ?.map((v) => Shadow( + color: color.withValues(alpha: v.color.a), + offset: v.offset, + blurRadius: v.blurRadius, + )) + .toList()); + } + } + case 'clip': + // \clip: clip (within rectangle or path) + line = line.copyWith(clip: _parseClip(param)); + case 'fax': + { + final factor = double.tryParse(param); + // ignore subsequent shearing when line is positioned + if (factor != null && (line.position == null || extraStyle.shearX == null)) { + extraStyle = extraStyle.copyWith(shearX: factor); + } + } + case 'fay': + { + final factor = double.tryParse(param); + // ignore subsequent shearing when line is positioned + if (factor != null && (line.position == null || extraStyle.shearY == null)) { + extraStyle = extraStyle.copyWith(shearY: factor); + } + } + case 'fn': + { + final name = param; + // TODO TLAD [subtitles] extract fonts from attachment streams, and load these fonts in Flutter + if (name.isNotEmpty) textStyle = textStyle.copyWith(fontFamily: name); + } + case 'frx': + { + // \frx: text rotation (X axis) + final amount = double.tryParse(param); + if (amount != null) extraStyle = extraStyle.copyWith(rotationX: amount); + } + case 'fry': + { + // \fry: text rotation (Y axis) + final amount = double.tryParse(param); + if (amount != null) extraStyle = extraStyle.copyWith(rotationY: amount); + } + case 'fr': + case 'frz': + { + // \frz: text rotation (Z axis) + final amount = double.tryParse(param); + if (amount != null) extraStyle = extraStyle.copyWith(rotationZ: amount); + } + case 'fs': + { + // \fs: font size + final size = int.tryParse(param); + if (size != null) textStyle = textStyle.copyWith(fontSize: size * scale); + } + case 'fscx': + { + // \fscx: font scale (horizontal) + final scale = int.tryParse(param); + if (scale != null) extraStyle = extraStyle.copyWith(scaleX: scale.toDouble() / 100); + } + case 'fscy': + { + // \fscx: font scale (vertical) + final scale = int.tryParse(param); + if (scale != null) extraStyle = extraStyle.copyWith(scaleY: scale.toDouble() / 100); + } + case 'fsp': + { + // \fsp: letter spacing + final spacing = double.tryParse(param); + textStyle = textStyle.copyWith(letterSpacing: spacing); + } + case 'i': + // \i: italics + textStyle = textStyle.copyWith(fontStyle: param == '1' ? FontStyle.italic : FontStyle.normal); + case 'p': + { + // \p drawing paths + final scale = int.tryParse(param); + if (scale != null) { + if (scale > 0) { + final start = overrideMatch.end; + final end = text.indexOf('{', start); + final commands = text.substring(start, end == -1 ? null : end); + extraStyle = extraStyle.copyWith(drawingPaths: _parsePaths(commands, scale)); + } else { + extraStyle = extraStyle.copyWith(drawingPaths: null); + } + } + } + case 'pos': + { + // \pos: line position + final match = multiParamPattern.firstMatch(param); + if (match != null) { + final g = match.group(1); + if (g != null) { + final params = g.split(','); + if (params.length == 2) { + final x = double.tryParse(params[0]); + final y = double.tryParse(params[1]); + if (x != null && y != null) { + line = line.copyWith(position: Offset(x, y)); + } + } + } + } + } + case 'r': + // \r: reset + textStyle = baseStyle; + case 's': + // \s: strikeout + textStyle = textStyle.copyWith(decoration: param == '1' ? TextDecoration.lineThrough : TextDecoration.none); + case 'u': + // \u: underline + textStyle = textStyle.copyWith(decoration: param == '1' ? TextDecoration.underline : TextDecoration.none); + // TODO TLAD [subtitles] SHOULD support the following + case 'shad': + case 't': // \t: animated transform + case 'xshad': + case 'yshad': + // line props: \pos, \move, \clip, \iclip, \org, \fade and \fad + case 'iclip': // \iclip: clip (inverse) + case 'fad': // \fad: fade + case 'fade': // \fade: fade (complex) + case 'move': // \move: movement + case 'org': // \org: rotation origin + // TODO TLAD [subtitles] MAY support the following + case 'fe': // \fe: font encoding + case 'pbo': // \pbo: baseline offset + case 'q': // \q: wrap style + // border size + case 'xbord': + case 'ybord': + // karaoke + case '2a': + case '2c': + case 'k': + case 'K': + case 'kf': + case 'ko': + default: + debugPrint('unhandled ASS tag=$tag'); + } + } + }); + }); + if (i != text.length) { + final spanText = extraStyle.drawingPaths?.isNotEmpty == true ? null : _replaceChars(text.substring(i)); + spans.add(StyledSubtitleSpan( + textSpan: TextSpan( + text: spanText, + style: textStyle, + ), + extraStyle: extraStyle, + )); + } + return line; + } + + static SubtitleStyle _copyWithAlignment(Alignment? alignment, SubtitleStyle extraStyle) { + if (alignment == null) return extraStyle; + + var hAlign = TextAlign.center; + var vAlign = TextAlignVertical.bottom; + if (alignment.x < 0) { + hAlign = TextAlign.left; + } else if (alignment.x > 0) { + hAlign = TextAlign.right; + } + if (alignment.y < 0) { + vAlign = TextAlignVertical.top; + } else if (alignment.y == 0) { + vAlign = TextAlignVertical.center; + } + return extraStyle.copyWith( + hAlign: hAlign, + vAlign: vAlign, + ); + } + + static String _replaceChars(String text) => text.replaceAll(r'\h', UniChars.noBreakSpace).replaceAll(r'\N', '\n'); + + static int? _parseAlpha(String param) { + final match = alphaPattern.firstMatch(param); + if (match != null) { + final as = match.group(1); + final ai = as != null ? int.tryParse(as, radix: 16) : null; + if (ai != null) { + return 0xFF - ai; + } + } + return null; + } + + static Color? _parseColor(String param) { + final match = colorPattern.firstMatch(param); + if (match != null) { + final bs = match.group(1); + final gs = match.group(2); + final rs = match.group(3); + final rgb = int.tryParse('ff$rs$gs$bs', radix: 16); + if (rgb != null) { + return Color(rgb); + } + } + return null; + } + + static FontWeight? _parseFontWeight(String param) { + switch (int.tryParse(param)) { + case 0: + return FontWeight.normal; + case 1: + return FontWeight.bold; + case 100: + return FontWeight.w100; + case 200: + return FontWeight.w200; + case 300: + return FontWeight.w300; + case 400: + return FontWeight.w400; + case 500: + return FontWeight.w500; + case 600: + return FontWeight.w600; + case 700: + return FontWeight.w700; + case 800: + return FontWeight.w800; + case 900: + return FontWeight.w900; + default: + return null; + } + } + + static Alignment? _parseNewAlignment(String param) { + switch (int.tryParse(param)) { + case 1: + return Alignment.bottomLeft; + case 2: + return Alignment.bottomCenter; + case 3: + return Alignment.bottomRight; + case 4: + return Alignment.centerLeft; + case 5: + return Alignment.center; + case 6: + return Alignment.centerRight; + case 7: + return Alignment.topLeft; + case 8: + return Alignment.topCenter; + case 9: + return Alignment.topRight; + default: + return null; + } + } + + static Alignment? _parseLegacyAlignment(String param) { + switch (int.tryParse(param)) { + case 1: + return Alignment.bottomLeft; + case 2: + return Alignment.bottomCenter; + case 3: + return Alignment.bottomRight; + case 5: + return Alignment.topLeft; + case 6: + return Alignment.topCenter; + case 7: + return Alignment.topRight; + case 9: + return Alignment.centerLeft; + case 10: + return Alignment.center; + case 11: + return Alignment.centerRight; + default: + return null; + } + } + + static List<Path> _parsePaths(String commands, int scale) { + final paths = <Path>[]; + Path? path; + pathPattern.allMatches(commands).forEach((match) { + if (match.groupCount == 2) { + final command = match.group(1)!; + final params = match.group(2)!.trim().split(' ').map(double.tryParse).nonNulls.map((v) => v / scale).toList(); + switch (command) { + case 'b': + if (path != null) { + const bParamCount = 6; + final steps = (params.length / bParamCount).floor(); + for (var i = 0; i < steps; i++) { + final points = params.skip(i * bParamCount).take(bParamCount).toList(); + path!.cubicTo(points[0], points[1], points[2], points[3], points[4], points[5]); + } + } + case 'c': + if (path != null) { + path!.close(); + } + path = null; + case 'l': + if (path != null) { + const lParamCount = 2; + final steps = (params.length / lParamCount).floor(); + for (var i = 0; i < steps; i++) { + final points = params.skip(i * lParamCount).take(lParamCount).toList(); + path!.lineTo(points[0], points[1]); + } + } + case 'm': + if (params.length == 2) { + if (path != null) { + path!.close(); + } + path = Path(); + paths.add(path!); + path!.moveTo(params[0], params[1]); + } + case 'n': + if (params.length == 2 && path != null) { + path!.moveTo(params[0], params[1]); + } + case 's': + case 'p': + debugPrint('unhandled ASS drawing command=$command'); + } + } + }); + if (path != null) { + path!.close(); + } + return paths; + } + + static List<Path>? _parseClip(String param) { + List<Path>? paths; + final match = multiParamPattern.firstMatch(param); + if (match != null) { + final g = match.group(1); + if (g != null) { + final params = g.split(','); + if (params.length == 4) { + final points = params.map(double.tryParse).nonNulls.toList(); + if (points.length == 4) { + paths = [ + Path() + ..addRect(Rect.fromPoints( + Offset(points[0], points[1]), + Offset(points[2], points[3]), + )) + ]; + } + } else { + int? scale; + String? commands; + if (params.length == 1) { + scale = 1; + commands = params[0]; + } else if (params.length == 2) { + scale = int.tryParse(params[0]); + commands = params[1]; + } + if (scale != null && commands != null) { + paths = _parsePaths(commands, scale); + } + } + } + } + return paths; + } +} diff --git a/lib/widgets/viewer/visual/video/subtitle/line.dart b/lib/widgets/viewer/visual/video/subtitle/line.dart new file mode 100644 index 0000000..f7a213b --- /dev/null +++ b/lib/widgets/viewer/visual/video/subtitle/line.dart @@ -0,0 +1,40 @@ +import 'package:aves/widgets/viewer/visual/video/subtitle/span.dart'; +import 'package:equatable/equatable.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; + +@immutable +class StyledSubtitleLine extends Equatable with Diagnosticable { + final List<StyledSubtitleSpan> spans; + final List<Path>? clip; + final Offset? position; + + @override + List<Object?> get props => [spans, clip, position]; + + const StyledSubtitleLine({ + required this.spans, + this.clip, + this.position, + }); + + StyledSubtitleLine copyWith({ + List<StyledSubtitleSpan>? spans, + List<Path>? clip, + Offset? position, + }) { + return StyledSubtitleLine( + spans: spans ?? this.spans, + clip: clip ?? this.clip, + position: position ?? this.position, + ); + } + + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + super.debugFillProperties(properties); + properties.add(DiagnosticsProperty<List<StyledSubtitleSpan>>('spans', spans)); + properties.add(DiagnosticsProperty<List<Path>>('clip', clip)); + properties.add(DiagnosticsProperty<Offset>('position', position)); + } +} diff --git a/lib/widgets/viewer/visual/video/subtitle/span.dart b/lib/widgets/viewer/visual/video/subtitle/span.dart new file mode 100644 index 0000000..0f58705 --- /dev/null +++ b/lib/widgets/viewer/visual/video/subtitle/span.dart @@ -0,0 +1,35 @@ +import 'package:aves/widgets/viewer/visual/video/subtitle/style.dart'; +import 'package:equatable/equatable.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; + +@immutable +class StyledSubtitleSpan extends Equatable with Diagnosticable { + final TextSpan textSpan; + final SubtitleStyle extraStyle; + + @override + List<Object?> get props => [textSpan, extraStyle]; + + const StyledSubtitleSpan({ + required this.textSpan, + required this.extraStyle, + }); + + StyledSubtitleSpan copyWith({ + TextSpan? textSpan, + SubtitleStyle? extraStyle, + }) { + return StyledSubtitleSpan( + textSpan: textSpan ?? this.textSpan, + extraStyle: extraStyle ?? this.extraStyle, + ); + } + + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + super.debugFillProperties(properties); + properties.add(DiagnosticsProperty<TextSpan>('textSpan', textSpan)); + properties.add(DiagnosticsProperty<SubtitleStyle>('extraStyle', extraStyle)); + } +} diff --git a/lib/widgets/viewer/visual/video/subtitle/style.dart b/lib/widgets/viewer/visual/video/subtitle/style.dart new file mode 100644 index 0000000..3700eb1 --- /dev/null +++ b/lib/widgets/viewer/visual/video/subtitle/style.dart @@ -0,0 +1,101 @@ +import 'package:equatable/equatable.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; + +@immutable +class SubtitleStyle extends Equatable with Diagnosticable { + final TextAlign? hAlign; + final TextAlignVertical? vAlign; + final Color? borderColor; + final double? borderWidth, edgeBlur, rotationX, rotationY, rotationZ, scaleX, scaleY, shearX, shearY; + final List<Path>? drawingPaths; + + bool get rotating => (rotationX ?? 0) != 0 || (rotationY ?? 0) != 0 || (rotationZ ?? 0) != 0; + + bool get scaling => (scaleX ?? 1) != 1 || (scaleY ?? 1) != 1; + + bool get shearing => (shearX ?? 0) != 0 || (shearY ?? 0) != 0; + + @override + List<Object?> get props => [ + hAlign, + vAlign, + borderColor, + borderWidth, + edgeBlur, + rotationX, + rotationY, + rotationZ, + scaleX, + scaleY, + shearX, + shearY, + drawingPaths?.length, + ]; + + const SubtitleStyle({ + this.hAlign, + this.vAlign, + this.borderColor, + this.borderWidth, + this.edgeBlur, + this.rotationX, + this.rotationY, + this.rotationZ, + this.scaleX, + this.scaleY, + this.shearX, + this.shearY, + this.drawingPaths, + }); + + SubtitleStyle copyWith({ + TextAlign? hAlign, + TextAlignVertical? vAlign, + Color? borderColor, + double? borderWidth, + double? edgeBlur, + double? rotationX, + double? rotationY, + double? rotationZ, + double? scaleX, + double? scaleY, + double? shearX, + double? shearY, + List<Path>? drawingPaths, + }) { + return SubtitleStyle( + hAlign: hAlign ?? this.hAlign, + vAlign: vAlign ?? this.vAlign, + borderColor: borderColor ?? this.borderColor, + borderWidth: borderWidth ?? this.borderWidth, + edgeBlur: edgeBlur ?? this.edgeBlur, + rotationX: rotationX ?? this.rotationX, + rotationY: rotationY ?? this.rotationY, + rotationZ: rotationZ ?? this.rotationZ, + scaleX: scaleX ?? this.scaleX, + scaleY: scaleY ?? this.scaleY, + shearX: shearX ?? this.shearX, + shearY: shearY ?? this.shearY, + drawingPaths: drawingPaths ?? this.drawingPaths, + ); + } + + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + super.debugFillProperties(properties); + properties.add(EnumProperty<TextAlign>('hAlign', hAlign)); + properties.add(DiagnosticsProperty<TextAlignVertical>('vAlign', vAlign)); + properties.add(ColorProperty('borderColor', borderColor)); + properties.add(DoubleProperty('borderWidth', borderWidth)); + properties.add(DoubleProperty('edgeBlur', edgeBlur)); + properties.add(DoubleProperty('rotationX', rotationX)); + properties.add(DoubleProperty('rotationY', rotationY)); + properties.add(DoubleProperty('rotationZ', rotationZ)); + properties.add(DoubleProperty('scaleX', scaleX)); + properties.add(DoubleProperty('scaleY', scaleY)); + properties.add(DoubleProperty('shearX', shearX)); + properties.add(DoubleProperty('shearY', shearY)); + properties.add(DiagnosticsProperty<List<Path>>('drawingPaths', drawingPaths)); + } +} diff --git a/lib/widgets/viewer/visual/video/subtitle/subtitle.dart b/lib/widgets/viewer/visual/video/subtitle/subtitle.dart new file mode 100644 index 0000000..cbf10e7 --- /dev/null +++ b/lib/widgets/viewer/visual/video/subtitle/subtitle.dart @@ -0,0 +1,337 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/props.dart'; +import 'package:aves/model/settings/enums/subtitle_position.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/viewer/view_state.dart'; +import 'package:aves/widgets/common/basic/text/background_painter.dart'; +import 'package:aves/widgets/common/basic/text/outlined.dart'; +import 'package:aves/widgets/viewer/visual/video/subtitle/ass_parser.dart'; +import 'package:aves/widgets/viewer/visual/video/subtitle/span.dart'; +import 'package:aves/widgets/viewer/visual/video/subtitle/style.dart'; +import 'package:aves_video/aves_video.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:latlong2/latlong.dart' as angles; +import 'package:provider/provider.dart'; + +class VideoSubtitles extends StatelessWidget { + final AvesEntry entry; + final AvesVideoController controller; + final ValueNotifier<ViewState> viewStateNotifier; + final bool debugMode; + + static const baseShadowOffset = Offset(1, 1); + + const VideoSubtitles({ + super.key, + required this.entry, + required this.controller, + required this.viewStateNotifier, + this.debugMode = false, + }); + + @override + Widget build(BuildContext context) { + return ValueListenableBuilder<double?>( + valueListenable: controller.sarNotifier, + builder: (context, sar, child) { + final videoDisplaySize = entry.videoDisplaySize(sar); + + return IgnorePointer( + child: Consumer<Settings>( + builder: (context, settings, child) { + final baseTextAlign = settings.subtitleTextAlignment; + final baseTextAlignY = settings.subtitleTextPosition.toTextAlignVertical(); + final baseOutlineWidth = settings.subtitleShowOutline ? 1 : 0; + final baseOutlineColor = Colors.black.withValues(alpha: settings.subtitleTextColor.a); + final baseShadows = [ + Shadow( + color: baseOutlineColor, + offset: baseShadowOffset, + ), + ]; + final baseStyle = TextStyle( + color: settings.subtitleTextColor, + fontSize: settings.subtitleFontSize, + shadows: settings.subtitleShowOutline ? baseShadows : null, + ); + + final viewportSize = MediaQuery.sizeOf(context); + final isPortrait = MediaQuery.orientationOf(context) == Orientation.portrait; + final bottom = isPortrait ? .5 : .8; + return ValueListenableBuilder<ViewState>( + valueListenable: viewStateNotifier, + builder: (context, viewState, child) { + final viewPosition = viewState.position; + final viewScale = viewState.scale ?? 1; + final viewSize = videoDisplaySize * viewScale; + final viewOffset = Offset( + (viewportSize.width - viewSize.width) / 2, + (viewportSize.height - viewSize.height) / 2, + ); + + return StreamBuilder<String?>( + stream: controller.timedTextStream, + builder: (context, snapshot) { + final text = snapshot.data; + if (text == null) return const SizedBox(); + + if (debugMode) { + return Padding( + padding: const EdgeInsets.only(top: 100.0), + child: Align( + alignment: Alignment.topLeft, + child: OutlinedText( + textSpans: [ + TextSpan( + text: text, + style: const TextStyle(fontSize: 14), + ) + ], + outlineWidth: 1, + outlineColor: Colors.black, + ), + ), + ); + } + + final styledLine = AssParser.parse(text, baseStyle, viewScale); + final position = styledLine.position; + final clip = styledLine.clip; + final styledSpans = styledLine.spans; + final byExtraStyle = groupBy<StyledSubtitleSpan, SubtitleStyle>(styledSpans, (v) => v.extraStyle); + return Stack( + children: byExtraStyle.entries.map((kv) { + final extraStyle = kv.key; + final spans = kv.value.map((v) { + final span = v.textSpan; + final style = span.style; + if (position == null || style == null) return span; + + final letterSpacing = style.letterSpacing; + final shadows = style.shadows; + return TextSpan( + text: span.text, + style: style.copyWith( + letterSpacing: letterSpacing != null ? letterSpacing * viewScale : null, + shadows: shadows + ?.map((v) => Shadow( + color: v.color, + offset: v.offset * viewScale, + blurRadius: v.blurRadius * viewScale, + )) + .toList(), + ), + ); + }).toList(); + final drawingPaths = extraStyle.drawingPaths; + final textHAlign = extraStyle.hAlign ?? (position != null ? TextAlign.center : baseTextAlign); + final textVAlign = extraStyle.vAlign ?? (position != null ? TextAlignVertical.bottom : baseTextAlignY); + + Widget child; + if (drawingPaths != null) { + child = CustomPaint( + painter: SubtitlePathPainter( + paths: drawingPaths, + scale: viewScale, + fillColor: spans.firstOrNull?.style?.color ?? Colors.white, + strokeColor: extraStyle.borderColor, + ), + ); + } else { + final outlineWidth = extraStyle.borderWidth ?? (extraStyle.edgeBlur != null ? 2 : 1); + child = OutlinedText( + textSpans: spans, + outlineWidth: outlineWidth * (position != null ? viewScale : baseOutlineWidth), + outlineColor: extraStyle.borderColor ?? baseOutlineColor, + outlineBlurSigma: extraStyle.edgeBlur ?? 0, + textAlign: textHAlign, + ); + } + + var transform = Matrix4.identity(); + + if (position != null) { + final paragraph = RenderParagraph( + TextSpan(children: spans), + textDirection: TextDirection.ltr, + textScaler: MediaQuery.textScalerOf(context), + )..layout(const BoxConstraints()); + final textWidth = paragraph.getMaxIntrinsicWidth(double.infinity); + final textHeight = paragraph.getMaxIntrinsicHeight(double.infinity); + paragraph.dispose(); + + late double anchorOffsetX, anchorOffsetY; + switch (textHAlign) { + case TextAlign.left: + anchorOffsetX = 0; + case TextAlign.right: + anchorOffsetX = -textWidth; + case TextAlign.center: + default: + anchorOffsetX = -textWidth / 2; + } + switch (textVAlign) { + case TextAlignVertical.top: + anchorOffsetY = 0; + case TextAlignVertical.center: + anchorOffsetY = -textHeight / 2; + case TextAlignVertical.bottom: + anchorOffsetY = -textHeight; + } + final alignOffset = Offset(anchorOffsetX, anchorOffsetY); + final lineOffset = position * viewScale + viewPosition; + final translateOffset = viewOffset + lineOffset + alignOffset; + transform.translate(translateOffset.dx, translateOffset.dy); + } + + if (extraStyle.rotating) { + // for perspective + transform.setEntry(3, 2, 0.001); + final x = -angles.degToRadian(extraStyle.rotationX ?? 0); + final y = -angles.degToRadian(extraStyle.rotationY ?? 0); + final z = -angles.degToRadian(extraStyle.rotationZ ?? 0); + if (x != 0) transform.rotateX(x); + if (y != 0) transform.rotateY(y); + if (z != 0) transform.rotateZ(z); + } + if (extraStyle.scaling) { + final x = extraStyle.scaleX ?? 1; + final y = extraStyle.scaleY ?? 1; + transform.scale(x, y); + } + if (extraStyle.shearing) { + final x = extraStyle.shearX ?? 0; + final y = extraStyle.shearY ?? 0; + transform.multiply(Matrix4(1, y, 0, 0, x, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)); + } + + if (!transform.isIdentity()) { + child = Transform( + transform: transform, + alignment: Alignment.center, + child: child, + ); + } + + if (position == null) { + late double alignX; + switch (textHAlign) { + case TextAlign.left: + alignX = -1; + case TextAlign.right: + alignX = 1; + case TextAlign.center: + default: + alignX = 0; + } + late double alignY; + switch (textVAlign) { + case TextAlignVertical.top: + alignY = -bottom; + case TextAlignVertical.center: + alignY = 0; + case TextAlignVertical.bottom: + default: + alignY = bottom; + } + child = Padding( + padding: const EdgeInsets.symmetric(horizontal: 8), + child: Align( + alignment: Alignment(alignX, alignY), + child: TextBackgroundPainter( + spans: spans, + style: DefaultTextStyle.of(context).style.merge(spans.first.style!.copyWith( + backgroundColor: settings.subtitleBackgroundColor, + )), + textAlign: textHAlign, + child: child, + ), + ), + ); + } + + if (clip != null) { + final clipOffset = viewOffset + viewPosition; + final matrix = Matrix4.identity() + ..translate(clipOffset.dx, clipOffset.dy) + ..scale(viewScale, viewScale); + final transform = matrix.storage; + child = ClipPath( + clipper: SubtitlePathClipper( + paths: clip.map((v) => v.transform(transform)).toList(), + scale: viewScale, + ), + child: child, + ); + } + + return child; + }).toList(), + ); + }, + ); + }, + ); + }, + ), + ); + }, + ); + } +} + +class SubtitlePathPainter extends CustomPainter { + final List<Path> paths; + final double scale; + final Paint? fillPaint, strokePaint; + + SubtitlePathPainter({ + required this.paths, + required this.scale, + required Color? fillColor, + required Color? strokeColor, + }) : fillPaint = fillColor != null + ? (Paint() + ..style = PaintingStyle.fill + ..color = fillColor) + : null, + strokePaint = strokeColor != null + ? (Paint() + ..style = PaintingStyle.stroke + ..color = strokeColor) + : null; + + @override + void paint(Canvas canvas, Size size) { + canvas.scale(scale, scale); + paths.forEach((path) { + if (fillPaint != null) { + canvas.drawPath(path, fillPaint!); + } + if (strokePaint != null) { + canvas.drawPath(path, strokePaint!); + } + }); + } + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => true; +} + +class SubtitlePathClipper extends CustomClipper<Path> { + final List<Path> paths; + final double scale; + + const SubtitlePathClipper({ + required this.paths, + required this.scale, + }); + + @override + Path getClip(Size size) => paths.firstOrNull ?? Path(); + + @override + bool shouldReclip(covariant CustomClipper<Path> oldClipper) => true; +} diff --git a/lib/widgets/viewer/visual/video/swipe_action.dart b/lib/widgets/viewer/visual/video/swipe_action.dart new file mode 100644 index 0000000..da3a6b1 --- /dev/null +++ b/lib/widgets/viewer/visual/video/swipe_action.dart @@ -0,0 +1,137 @@ +import 'dart:async'; + +import 'package:aves/theme/icons.dart'; +import 'package:aves/widgets/aves_app.dart'; +import 'package:decorated_icon/decorated_icon.dart'; +import 'package:flutter/material.dart'; +import 'package:volume_controller/volume_controller.dart'; + +enum SwipeAction { brightness, volume } + +extension ExtraSwipeAction on SwipeAction { + Future<double> get() { + switch (this) { + case SwipeAction.brightness: + return AvesApp.screenBrightness?.application ?? Future.value(1); + case SwipeAction.volume: + return VolumeController.instance.getVolume(); + } + } + + Future<void> set(double value) async { + switch (this) { + case SwipeAction.brightness: + await AvesApp.screenBrightness?.setApplicationScreenBrightness(value); + case SwipeAction.volume: + VolumeController.instance.showSystemUI = false; + await VolumeController.instance.setVolume(value); + } + } +} + +class SwipeActionFeedback extends StatelessWidget { + final SwipeAction action; + final ValueNotifier<double?> valueNotifier; + + const SwipeActionFeedback({ + super.key, + required this.action, + required this.valueNotifier, + }); + + static const double width = 32; + static const double height = 160; + static const Radius radius = Radius.circular(width / 2); + static const double borderWidth = 2; + static const Color borderColor = Colors.white; + static final Color fillColor = Colors.white.withValues(alpha: .8); + static final Color backgroundColor = Colors.black.withValues(alpha: .2); + static final Color innerBorderColor = Colors.black.withValues(alpha: .5); + static const Color iconColor = Colors.white; + static const Color shadowColor = Colors.black; + + @override + Widget build(BuildContext context) { + return Center( + child: ValueListenableBuilder<double?>( + valueListenable: valueNotifier, + builder: (context, value, child) { + if (value == null) return const SizedBox(); + + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + _buildIcon(_getMaxIcon()), + Container( + decoration: BoxDecoration( + color: backgroundColor, + border: Border.all( + width: borderWidth * 2, + color: innerBorderColor, + ), + borderRadius: const BorderRadius.all(radius), + ), + foregroundDecoration: BoxDecoration( + border: Border.all( + color: borderColor, + width: borderWidth, + ), + borderRadius: const BorderRadius.all(radius), + ), + width: width, + height: height, + child: ClipRRect( + borderRadius: const BorderRadius.all(radius), + child: Align( + alignment: Alignment.bottomCenter, + child: Container( + color: fillColor, + width: width, + height: height * value, + ), + ), + ), + ), + _buildIcon(_getMinIcon()), + ], + ); + }, + ), + ); + } + + Widget _buildIcon(IconData icon) { + return Padding( + padding: const EdgeInsets.all(16), + child: DecoratedIcon( + icon, + size: width, + color: iconColor, + shadows: const [ + Shadow( + color: shadowColor, + blurRadius: 4, + ) + ], + ), + ); + } + + IconData _getMinIcon() { + switch (action) { + case SwipeAction.brightness: + return AIcons.brightnessMin; + case SwipeAction.volume: + return AIcons.volumeMin; + } + } + + IconData _getMaxIcon() { + switch (action) { + case SwipeAction.brightness: + return AIcons.brightnessMax; + case SwipeAction.volume: + return AIcons.volumeMax; + } + } +} diff --git a/lib/widgets/viewer/visual/video/video_view.dart b/lib/widgets/viewer/visual/video/video_view.dart new file mode 100644 index 0000000..c06c060 --- /dev/null +++ b/lib/widgets/viewer/visual/video/video_view.dart @@ -0,0 +1,61 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves_video/aves_video.dart'; +import 'package:flutter/material.dart'; + +class VideoView extends StatefulWidget { + final AvesEntry entry; + final AvesVideoController controller; + + const VideoView({ + super.key, + required this.entry, + required this.controller, + }); + + @override + State<StatefulWidget> createState() => _VideoViewState(); +} + +class _VideoViewState extends State<VideoView> { + AvesEntry get entry => widget.entry; + + AvesVideoController get controller => widget.controller; + + @override + void initState() { + super.initState(); + _registerWidget(widget); + } + + @override + void didUpdateWidget(covariant VideoView oldWidget) { + super.didUpdateWidget(oldWidget); + _unregisterWidget(oldWidget); + _registerWidget(widget); + } + + @override + void dispose() { + _unregisterWidget(widget); + super.dispose(); + } + + void _registerWidget(VideoView widget) { + widget.controller.playCompletedListenable.addListener(_onPlayCompleted); + } + + void _unregisterWidget(VideoView widget) { + widget.controller.playCompletedListenable.removeListener(_onPlayCompleted); + } + + @override + Widget build(BuildContext context) { + return StreamBuilder<VideoStatus>( + stream: controller.statusStream, + builder: (context, snapshot) => controller.isReady ? controller.buildPlayerWidget(context) : const SizedBox(), + ); + } + + // not called when looping + void _onPlayCompleted() => controller.seekTo(0); +} diff --git a/lib/widgets/wallpaper_page.dart b/lib/widgets/wallpaper_page.dart new file mode 100644 index 0000000..e86aa3e --- /dev/null +++ b/lib/widgets/wallpaper_page.dart @@ -0,0 +1,282 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/multipage.dart'; +import 'package:aves/model/entry/extensions/props.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/widgets/aves_app.dart'; +import 'package:aves/widgets/common/basic/insets.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/extensions/theme.dart'; +import 'package:aves/widgets/viewer/action/video_action_delegate.dart'; +import 'package:aves/widgets/viewer/controls/controller.dart'; +import 'package:aves/widgets/viewer/controls/notifications.dart'; +import 'package:aves/widgets/viewer/entry_horizontal_pager.dart'; +import 'package:aves/widgets/viewer/multipage/conductor.dart'; +import 'package:aves/widgets/viewer/overlay/bottom.dart'; +import 'package:aves/widgets/viewer/overlay/video/video.dart'; +import 'package:aves/widgets/viewer/page_entry_builder.dart'; +import 'package:aves/widgets/viewer/providers.dart'; +import 'package:aves/widgets/viewer/video/conductor.dart'; +import 'package:aves/widgets/viewer/visual/controller_mixin.dart'; +import 'package:aves_magnifier/aves_magnifier.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:aves_video/aves_video.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class WallpaperPage extends StatelessWidget { + static const routeName = '/set_wallpaper'; + + final AvesEntry? entry; + + const WallpaperPage({ + super.key, + required this.entry, + }); + + @override + Widget build(BuildContext context) { + return AvesScaffold( + body: entry != null + ? MultiProvider( + providers: [ + ViewStateConductorProvider(), + VideoConductorProvider(), + MultiPageConductorProvider(), + ], + child: EntryEditor( + entry: entry!, + ), + ) + : const SizedBox(), + backgroundColor: Theme.of(context).isDark ? Colors.black : Colors.white, + resizeToAvoidBottomInset: false, + ); + } +} + +class EntryEditor extends StatefulWidget { + final AvesEntry entry; + + const EntryEditor({ + super.key, + required this.entry, + }); + + @override + State<EntryEditor> createState() => _EntryEditorState(); +} + +class _EntryEditorState extends State<EntryEditor> with EntryViewControllerMixin, SingleTickerProviderStateMixin { + final ValueNotifier<bool> _overlayVisible = ValueNotifier(true); + late AnimationController _overlayAnimationController; + late CurvedAnimation _overlayVideoControlScale; + EdgeInsets? _frozenViewInsets, _frozenViewPadding; + late VideoActionDelegate _videoActionDelegate; + late final ViewerController _viewerController; + + @override + bool get isViewingImage => true; + + @override + final ValueNotifier<AvesEntry?> entryNotifier = ValueNotifier(null); + + AvesEntry get entry => widget.entry; + + @override + void initState() { + super.initState(); + if (settings.maxBrightness == MaxBrightness.viewerOnly) { + AvesApp.screenBrightness?.setApplicationScreenBrightness(1); + } + if (settings.keepScreenOn == KeepScreenOn.viewerOnly) { + windowService.keepScreenOn(true); + } + + entryNotifier.value = entry; + _overlayAnimationController = AnimationController( + duration: context.read<DurationsData>().viewerOverlayAnimation, + vsync: this, + ); + _overlayVideoControlScale = CurvedAnimation( + parent: _overlayAnimationController, + // no bounce at the bottom, to avoid video controller displacement + curve: Curves.easeOutQuad, + ); + _overlayVisible.addListener(_onOverlayVisibleChanged); + _videoActionDelegate = VideoActionDelegate( + collection: null, + ); + + _viewerController = ViewerController( + initialScale: const ScaleLevel(ref: ScaleReference.covered), + ); + initEntryControllers(entry); + _onOverlayVisibleChanged(); + } + + @override + void dispose() { + cleanEntryControllers(entry); + _overlayVisible.dispose(); + _overlayVideoControlScale.dispose(); + _overlayAnimationController.dispose(); + _videoActionDelegate.dispose(); + _viewerController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return NotificationListener( + onNotification: (dynamic notification) { + if (notification is ToggleOverlayNotification) { + _overlayVisible.value = notification.visible ?? !_overlayVisible.value; + } else if (notification is VideoActionNotification) { + _onVideoAction( + context: context, + entry: notification.entry, + controller: notification.controller, + action: notification.action, + ); + } + return true; + }, + child: LayoutBuilder( + builder: (context, constraints) { + final viewSize = Size(constraints.maxWidth, constraints.maxHeight); + return Stack( + children: [ + SingleEntryScroller( + entry: entry, + viewerController: _viewerController, + ), + Positioned( + bottom: 0, + child: _buildBottomOverlay(viewSize), + ), + const TopGestureAreaProtector(), + const SideGestureAreaProtector(), + const BottomGestureAreaProtector(), + ], + ); + }, + ), + ); + } + + Widget _buildBottomOverlay(Size viewSize) { + final mainEntry = entry; + final multiPageController = mainEntry.isMultiPage ? context.read<MultiPageConductor>().getController(mainEntry) : null; + + Widget? _buildExtraBottomOverlay({AvesEntry? pageEntry}) { + final targetEntry = pageEntry ?? mainEntry; + Widget? child; + // a 360 video is both a video and a panorama but only the video controls are displayed + if (targetEntry.isPureVideo) { + child = Selector<VideoConductor, AvesVideoController?>( + selector: (context, vc) => vc.getController(targetEntry), + builder: (context, videoController, child) => VideoControlOverlay( + entry: targetEntry, + controller: videoController, + scale: _overlayVideoControlScale, + onActionSelected: (action) => _onVideoAction( + context: context, + entry: targetEntry, + controller: videoController, + action: action, + ), + ), + ); + } + return child != null + ? ExtraBottomOverlay( + viewInsets: _frozenViewInsets, + viewPadding: _frozenViewPadding, + child: child, + ) + : null; + } + + final extraBottomOverlay = mainEntry.isMultiPage + ? PageEntryBuilder( + multiPageController: multiPageController, + builder: (pageEntry) => _buildExtraBottomOverlay(pageEntry: pageEntry) ?? const SizedBox(), + ) + : _buildExtraBottomOverlay(); + + final child = TooltipTheme( + data: TooltipTheme.of(context).copyWith( + preferBelow: false, + ), + child: Column( + children: [ + if (extraBottomOverlay != null) extraBottomOverlay, + ViewerBottomOverlay( + entries: [widget.entry], + index: 0, + collection: null, + animationController: _overlayAnimationController, + availableSize: viewSize, + viewInsets: _frozenViewInsets, + viewPadding: _frozenViewPadding, + multiPageController: multiPageController, + ), + ], + ), + ); + + return ValueListenableBuilder<double>( + valueListenable: _overlayAnimationController, + builder: (context, animation, child) { + return Visibility( + visible: !_overlayAnimationController.isDismissed, + child: child!, + ); + }, + child: child, + ); + } + + void _onVideoAction({ + required BuildContext context, + required AvesEntry entry, + required AvesVideoController? controller, + required EntryAction action, + }) { + if (controller != null) { + _videoActionDelegate.onActionSelected(context, entry, controller, action); + } + } + + // overlay + + Future<void> _onOverlayVisibleChanged({bool animate = true}) async { + if (_overlayVisible.value) { + await AvesApp.showSystemUI(); + AvesApp.setSystemUIStyle(Theme.of(context)); + if (animate) { + await _overlayAnimationController.forward(); + } else { + _overlayAnimationController.value = _overlayAnimationController.upperBound; + } + } else { + final mediaQuery = context.read<MediaQueryData>(); + setState(() { + _frozenViewInsets = mediaQuery.viewInsets; + _frozenViewPadding = mediaQuery.viewPadding; + }); + await AvesApp.hideSystemUI(); + if (animate) { + await _overlayAnimationController.reverse(); + } else { + _overlayAnimationController.reset(); + } + setState(() { + _frozenViewInsets = null; + _frozenViewPadding = null; + }); + } + } +} diff --git a/lib/widgets/welcome_page.dart b/lib/widgets/welcome_page.dart new file mode 100644 index 0000000..2f78dcf --- /dev/null +++ b/lib/widgets/welcome_page.dart @@ -0,0 +1,260 @@ +import 'package:aves/app_flavor.dart'; +import 'package:aves/model/settings/defaults.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/theme/durations.dart'; +import 'package:aves/theme/icons.dart'; +import 'package:aves/theme/text.dart'; +import 'package:aves/widgets/about/policy_page.dart'; +import 'package:aves/widgets/common/basic/link_chip.dart'; +import 'package:aves/widgets/common/basic/markdown_container.dart'; +import 'package:aves/widgets/common/basic/scaffold.dart'; +import 'package:aves/widgets/common/extensions/build_context.dart'; +import 'package:aves/widgets/common/identity/aves_logo.dart'; +import 'package:aves/widgets/common/identity/buttons/outlined_button.dart'; +import 'package:aves/widgets/home/home_page.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_staggered_animations/flutter_staggered_animations.dart'; +import 'package:provider/provider.dart'; + +class WelcomePage extends StatefulWidget { + const WelcomePage({super.key}); + + @override + State<WelcomePage> createState() => _WelcomePageState(); +} + +class _WelcomePageState extends State<WelcomePage> { + bool _hasAcceptedTerms = false; + late Future<String> _termsLoader; + + static const termsPath = 'assets/terms.md'; + static const termsDirection = TextDirection.ltr; + + @override + void initState() { + super.initState(); + _termsLoader = rootBundle.loadString(termsPath); + WidgetsBinding.instance.addPostFrameCallback((_) => _initWelcomeSettings()); + } + + void _initWelcomeSettings() { + // this should be done outside of `initState`/`build` + settings.setContextualDefaults(context.read<AppFlavor>()); + // explicitly set consent values to current defaults + // so they are not subject to future default changes + settings.isInstalledAppAccessAllowed = SettingsDefaults.isInstalledAppAccessAllowed; + settings.isErrorReportingAllowed = SettingsDefaults.isErrorReportingAllowed; + } + + @override + Widget build(BuildContext context) { + return AvesScaffold( + body: SafeArea( + child: Center( + child: FutureBuilder<String>( + future: _termsLoader, + builder: (context, snapshot) { + if (snapshot.hasError || snapshot.connectionState != ConnectionState.done) return const SizedBox(); + final terms = snapshot.data!; + final durations = context.watch<DurationsData>(); + final isPortrait = MediaQuery.orientationOf(context) == Orientation.portrait; + return Column( + mainAxisSize: MainAxisSize.min, + children: _toStaggeredList( + duration: durations.staggeredAnimation, + delay: durations.staggeredAnimationDelay * timeDilation, + childAnimationBuilder: (child) => SlideAnimation( + verticalOffset: 50.0, + child: FadeInAnimation( + child: child, + ), + ), + children: settings.useTvLayout + ? [ + ..._buildHeader(context, isPortrait: isPortrait), + Padding( + padding: const EdgeInsets.all(16), + child: LinkChip( + leading: const Icon( + AIcons.privacy, + size: 22, + ), + text: context.l10n.aboutLinkPolicy, + textStyle: Theme.of(context).textTheme.titleLarge, + onTap: _goToPolicyPage, + ), + ), + ..._buildControls(context), + ] + : [ + ..._buildHeader(context, isPortrait: isPortrait), + if (isPortrait) ...[ + Flexible( + child: MarkdownContainer( + data: terms, + textDirection: termsDirection, + ), + ), + const SizedBox(height: 16), + ..._buildControls(context), + ] else + Flexible( + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Flexible( + child: Padding( + padding: const EdgeInsets.only(bottom: 8), + child: MarkdownContainer( + data: terms, + textDirection: termsDirection, + ), + ), + ), + Flexible( + child: ListView( + shrinkWrap: true, + children: _buildControls(context), + ), + ), + ], + ), + ), + ], + ), + ); + }, + ), + ), + ), + ); + } + + List<Widget> _buildHeader(BuildContext context, {required bool isPortrait}) { + final message = Text( + context.l10n.welcomeMessage, + style: Theme.of(context).textTheme.headlineSmall, + ); + final double padding = isPortrait ? 16.0 : 8.0; + return [ + SizedBox(height: padding), + ...(isPortrait + ? [ + const AvesLogo(size: 64), + const SizedBox(height: 16), + message, + ] + : [ + Row( + mainAxisSize: MainAxisSize.min, + children: [ + const AvesLogo(size: 48), + const SizedBox(width: 16), + message, + ], + ) + ]), + SizedBox(height: padding), + ]; + } + + List<Widget> _buildControls(BuildContext context) { + final l10n = context.l10n; + final canEnableErrorReporting = context.select<AppFlavor, bool>((v) => v.canEnableErrorReporting); + const contentPadding = EdgeInsets.symmetric(horizontal: 8); + final switches = ConstrainedBox( + constraints: const BoxConstraints(maxWidth: MarkdownContainer.mobileMaxWidth), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SwitchListTile( + key: const Key('apps-checkbox'), + value: settings.isInstalledAppAccessAllowed, + onChanged: (v) => setState(() => settings.isInstalledAppAccessAllowed = v), + title: Text(l10n.settingsAllowInstalledAppAccess), + subtitle: Text([l10n.welcomeOptional, l10n.settingsAllowInstalledAppAccessSubtitle].join(AText.separator)), + contentPadding: contentPadding, + ), + if (canEnableErrorReporting) + SwitchListTile( + value: settings.isErrorReportingAllowed, + onChanged: (v) => setState(() => settings.isErrorReportingAllowed = v), + title: Text(l10n.settingsAllowErrorReporting), + subtitle: Text(l10n.welcomeOptional), + contentPadding: contentPadding, + ), + SwitchListTile( + // key is expected by test driver + key: const Key('terms-checkbox'), + value: _hasAcceptedTerms, + onChanged: (v) => setState(() => _hasAcceptedTerms = v), + title: Text(l10n.welcomeTermsToggle), + contentPadding: contentPadding, + ), + ], + ), + ); + + final button = AvesOutlinedButton( + // key is expected by test driver + key: const Key('continue-button'), + label: context.l10n.continueButtonLabel, + onPressed: _hasAcceptedTerms + ? () { + settings.hasAcceptedTerms = true; + Navigator.pushReplacement( + context, + MaterialPageRoute( + settings: const RouteSettings(name: HomePage.routeName), + builder: (context) => const HomePage(), + ), + ); + } + : null, + ); + + return [ + switches, + Center(child: button), + const SizedBox(height: 8), + ]; + } + + void _goToPolicyPage() { + Navigator.maybeOf(context)?.push( + MaterialPageRoute( + settings: const RouteSettings(name: PolicyPage.routeName), + builder: (context) => const PolicyPage(), + ), + ); + } + + // as of flutter_staggered_animations v0.1.2, `AnimationConfiguration.toStaggeredList` does not handle `Flexible` widgets + // so we use this workaround instead + static List<Widget> _toStaggeredList({ + required Duration duration, + required Duration delay, + required Widget Function(Widget) childAnimationBuilder, + required List<Widget> children, + }) => + children + .asMap() + .map((index, widget) { + var child = widget is Flexible ? widget.child : widget; + child = AnimationConfiguration.staggeredList( + position: index, + duration: duration, + delay: delay, + child: childAnimationBuilder(child), + ); + child = widget is Flexible ? Flexible(child: child) : child; + return MapEntry( + index, + child, + ); + }) + .values + .toList(); +} |
