import 'dart:async'; import 'dart:math' as math; import 'package:fl_clash/common/common.dart'; import 'package:fl_clash/enum/enum.dart'; import 'package:fl_clash/models/models.dart'; import 'package:fl_clash/providers/providers.dart'; import 'package:fl_clash/state.dart'; import 'package:fl_clash/ui/icons/icons.dart'; import 'package:fl_clash/views/profiles/custom/custom.dart'; import 'package:fl_clash/views/profiles/extend/extend.dart'; import 'package:fl_clash/widgets/widgets.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'add.dart'; import 'edit.dart'; import 'preview.dart'; double get _profileItemHeight { final measure = globalState.measure; return listRowExtent( titleHeight: measure.textHeight(AppTextStyle.headline), subtitleHeight: measure.textHeight(AppTextStyle.footnote), ); } class ProfilesView extends ConsumerStatefulWidget { const ProfilesView({super.key, this.picker = false}); /// Clears the bar and opens at the top, for switching profiles from a sheet. final bool picker; @override ConsumerState createState() => _ProfilesViewState(); } class _ProfilesViewState extends ConsumerState { bool _isUpdating = false; Future _updateProfiles(List profiles) async { if (_isUpdating == true) { return; } _isUpdating = true; final appLocalizations = context.appLocalizations; final profilesAction = ref.read(profilesActionProvider.notifier); final List messages = []; final updateProfiles = profiles.map((profile) async { if (profile.type != ProfileType.url) return; try { await profilesAction.updateProfile(profile, showLoading: true); } catch (e) { messages.add( UpdatingMessage( label: profile.realLabel, message: userFacingErrorMessage(e, appLocalizations), ), ); } }); await Future.wait(updateProfiles); dialogs.showFailures(messages); _isUpdating = false; } List _buildActions(List profiles) { return profiles.isNotEmpty ? [ IconButtonData( glyph: AppGlyphs.sync, onPressed: () { _updateProfiles(profiles); }, tooltip: context.appLocalizations.update, ), IconButtonData( glyph: AppGlyphs.sort, onPressed: () { showNestedSheet( context, builder: (_) { return ReorderableProfilesSheet(profiles: profiles); }, ); }, tooltip: context.appLocalizations.profilesSort, ), ] : []; } @override Widget build(BuildContext context) { return Consumer( builder: (_, ref, _) { final appLocalizations = context.appLocalizations; final isLoading = ref.watch(loadingProvider(LoadingTag.profiles)); final state = ref.watch(profilesStateProvider); final spacing = cardSpacingOf(context, ref.watch(viewModeProvider)); final picker = widget.picker; return Scaffold( isLoading: isLoading, title: appLocalizations.profiles, iconActions: picker ? const [] : _buildActions(state.profiles), actions: state.profiles.isEmpty || picker ? null : [ AddProfileMenu( builder: (open) => IconButton( tooltip: appLocalizations.addProfile, onPressed: open, icon: const GlyphIcon(AppGlyphs.addCircle), ), ), ], body: NullStatusSwitcher( isEmpty: state.profiles.isEmpty, nullStatus: NullStatus( label: appLocalizations.nullTip(appLocalizations.profiles), description: appLocalizations.nullProfileDesc, illustration: NullStatusIllustration.profile, action: AddProfileMenu( builder: (open) => TonalButton( size: TonalButtonSize.bar, glyph: AppGlyphs.addCircle, label: appLocalizations.addProfile, onPressed: open, ), ), ), child: _ProfilesGrid( profiles: state.profiles, currentProfileId: state.currentProfileId, spacing: spacing, revealsSelected: !picker, ), ), ); }, ); } } class _ProfilesGrid extends ConsumerStatefulWidget { const _ProfilesGrid({ required this.profiles, required this.currentProfileId, required this.spacing, required this.revealsSelected, }); final List profiles; final int? currentProfileId; final double spacing; final bool revealsSelected; @override ConsumerState<_ProfilesGrid> createState() => _ProfilesGridState(); } class _ProfilesGridState extends ConsumerState<_ProfilesGrid> { ScrollController? _controller; var _revealed = false; @override void didChangeDependencies() { super.didChangeDependencies(); if (_revealed || !widget.revealsSelected || !PageActivityScope.isActiveOf(context)) { return; } _revealed = true; WidgetsBinding.instance.addPostFrameCallback((_) => _revealSelected()); } @override void dispose() { _controller?.dispose(); super.dispose(); } double get _horizontalPadding => context.listInsets.margin; EdgeInsets get _padding => EdgeInsets.only( left: _horizontalPadding, right: _horizontalPadding, top: context.contentTopPadding, bottom: 16 + context.bottomInset, ); int _columnsFor(double width) => getProfilesColumns( width - _horizontalPadding * 2, spacing: widget.spacing, minItemWidth: profileItemMinWidth.ap(context), ); double? _revealOffset({ required double width, required double viewport, required double pixels, required double maxScrollExtent, }) { final index = widget.profiles.indexWhere( (profile) => profile.id == widget.currentProfileId, ); if (index == -1) { return null; } final height = _profileItemHeight; final row = index ~/ _columnsFor(width); final atTop = row * (height + widget.spacing); final atBottom = atTop + _padding.vertical + height - viewport; if (pixels >= atBottom && pixels <= atTop) { return null; } return ((atTop + atBottom) / 2).clamp(0.0, maxScrollExtent); } /// A tab switch draws the page it brings in from a snapshot of its first /// frame, so a reveal after that frame would only show once the switch ends. double _initialOffset(Size size) { if (!_revealed) { return 0; } final rows = (widget.profiles.length / _columnsFor(size.width)).ceil(); final extent = _padding.vertical + rows * _profileItemHeight + math.max(0, rows - 1) * widget.spacing; return _revealOffset( width: size.width, viewport: size.height, pixels: 0, maxScrollExtent: math.max(0, extent - size.height), ) ?? 0; } void _revealSelected() { final controller = _controller; if (!mounted || controller == null || !controller.hasClients) { return; } final position = controller.position; final offset = _revealOffset( width: context.size!.width, viewport: position.viewportDimension, pixels: position.pixels, maxScrollExtent: position.maxScrollExtent, ); if (offset != null) { controller.jumpTo(offset); } } @override Widget build(BuildContext context) { final profiles = widget.profiles; final grid = WidthBuilder( builder: (_, width) { return GridView.builder( key: profilesStoreKey, controller: _controller, padding: _padding, gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: _columnsFor(width), mainAxisSpacing: widget.spacing, crossAxisSpacing: widget.spacing, mainAxisExtent: _profileItemHeight, ), itemCount: profiles.length, itemBuilder: (context, index) { final profile = profiles[index]; return ProfileItem( key: ValueKey(profile.id), profile: profile, groupValue: widget.currentProfileId, onChanged: (profileId) { ref.read(currentProfileIdProvider.notifier).value = profileId; }, ); }, ); }, ); return LayoutBuilder( builder: (context, constraints) { _controller ??= sheetScrollController( context, initialScrollOffset: _initialOffset(constraints.biggest), ); return grid; }, ); } } class ProfileItem extends ConsumerWidget { final Profile profile; final int? groupValue; final void Function(int? value) onChanged; const ProfileItem({ super.key, required this.profile, required this.groupValue, required this.onChanged, }); Future _handleDeleteProfile(BuildContext context, WidgetRef ref) async { final profilesAction = ref.read(profilesActionProvider.notifier); final appLocalizations = context.appLocalizations; final users = await profilesAction.providerUsers(profile); final res = await dialogs.showMessage( title: appLocalizations.tip, message: TextSpan( text: users.isEmpty ? appLocalizations.deleteTip(appLocalizations.profile) : appLocalizations.providerInUse( profile.realLabel, users.map((item) => item.realLabel).join(', '), ), ), destructive: true, confirmText: appLocalizations.delete, ); if (res != true) { return; } await profilesAction.deleteProfile(profile.id); } Future _handlePreview(BuildContext context) async { unawaited( pushNestedPage(context, PreviewProfileView(profile: profile)), ); } Future updateProfile(WidgetRef ref) async { if (profile.type != ProfileType.url) return; await globalState.loadingRun(() async { await ref .read(profilesActionProvider.notifier) .updateProfile(profile, showLoading: true); }, tag: LoadingTag.profiles); } void _handleShowEditExtendPage(BuildContext context) { showNestedExtend( context, builder: (context) => EditProfileView(profile: profile), ); } SubscriptionInfo? get _subscriptionInfo => profile.type == ProfileType.url ? profile.subscriptionInfo : null; String _subtitle(BuildContext context) { final info = _subscriptionInfo; if (info != null && info.usage != null) { final used = info.upload + info.download; return '${used.traffic.show} / ${info.total.traffic.show}'; } final appLocalizations = context.appLocalizations; return switch (profile.type) { ProfileType.url => appLocalizations.remote, ProfileType.file => appLocalizations.local, ProfileType.custom => appLocalizations.custom, }; } Widget _buildTrailing(BuildContext context, {required bool isUpdating}) { return AnimatedSwitcher( duration: context.motionDuration(commonDuration), layoutBuilder: (currentChild, previousChildren) => Stack( alignment: AlignmentDirectional.centerEnd, children: [...previousChildren, ?currentChild], ), child: isUpdating ? const ActivityIndicator(key: ValueKey('updating'), size: 24) : LastUpdateTimeText( key: const ValueKey('lastUpdate'), lastUpdateDate: profile.lastUpdateDate, style: AppTextStyle.footnote.of(context).toLighter, compact: true, ), ); } Future _handleCopyLink(BuildContext context) async { await Clipboard.setData(ClipboardData(text: profile.url)); if (context.mounted) { dialogs.showBanner( context.appLocalizations.copySuccess, level: BannerLevel.success, ); } } Future _handleExportFile(BuildContext context) async { final appLocalizations = context.appLocalizations; final res = await globalState.safeRun(() async { final mFile = await profile.file; final value = await picker.saveFile( profile.exportFileName, mFile.readAsBytesSync(), ); if (value == null) return false; return true; }, title: appLocalizations.tip); if (res == true && context.mounted) { dialogs.showBanner( appLocalizations.exportSuccess, level: BannerLevel.success, ); } } void _handlePushGenProfilePage(BuildContext context, int id) { BaseNavigator.push(context, ExtendView(profileId: id)); } void _handlePushCustomProfilePage(BuildContext context, int id) { BaseNavigator.push(context, CustomProfileView(profileId: id)); } void _handleEdit(BuildContext context) { if (profile.type == ProfileType.custom) { _handlePushCustomProfilePage(context, profile.id); } else { _handleShowEditExtendPage(context); } } List _menuItems(BuildContext context, WidgetRef ref) { final appLocalizations = context.appLocalizations; final isUrl = profile.type == ProfileType.url; final isCustom = profile.type == ProfileType.custom; return [ PopupMenuItem( glyph: AppGlyphs.edit, label: appLocalizations.edit, onPressed: () => _handleEdit(context), ), if (isCustom) ...[ PopupMenuItem( glyph: AppGlyphs.textShort, label: appLocalizations.rename, onPressed: () { renameProfile(context, ref, profile); }, ), PopupMenuItem( glyph: AppGlyphs.eye, label: appLocalizations.runtimeConfig, onPressed: () { _handlePreview(context); }, ), ] else PopupMenuItem( glyph: AppGlyphs.puzzle, label: appLocalizations.extend, onPressed: () { _handlePushGenProfilePage(context, profile.id); }, ), if (isUrl) PopupMenuItem( glyph: AppGlyphs.sync, label: appLocalizations.sync, onPressed: () { updateProfile(ref); }, ), if (!isCustom) PopupMenuItem( glyph: AppGlyphs.moreCircle, label: appLocalizations.more, subItems: [ PopupMenuItem( glyph: AppGlyphs.eye, label: appLocalizations.runtimeConfig, onPressed: () { _handlePreview(context); }, ), if (isUrl) PopupMenuItem( glyph: AppGlyphs.copy, label: appLocalizations.copyLink, onPressed: () { _handleCopyLink(context); }, ), if (isUrl) PopupMenuItem( glyph: AppGlyphs.qrCode, label: appLocalizations.qrcode, onPressed: () { dialogs.showQrCode( title: profile.realLabel, data: profile.url, message: appLocalizations.shareQrcodeTip, ); }, ), PopupMenuItem( glyph: AppGlyphs.export, label: appLocalizations.exportFile, onPressed: () { _handleExportFile(context); }, ), ], ), PopupMenuItem( danger: true, glyph: AppGlyphs.delete, label: appLocalizations.delete, onPressed: () { _handleDeleteProfile(context, ref); }, ), ]; } @override Widget build(BuildContext context, WidgetRef ref) { final isUpdating = ref.watch(isUpdatingProvider(profile.updatingKey)); final subscriptionInfo = _subscriptionInfo; final isSelected = profile.id == groupValue; return ContextMenuRegion( menuItems: isUpdating ? null : _menuItems(context, ref), child: Card( enterActionsOnRight: true, radius: AppCorner.xl, isSelected: isSelected, onPressed: () { onChanged(profile.id); }, child: ListItem( key: Key(profile.id.toString()), minTileHeight: _profileItemHeight, trailing: Row( mainAxisSize: MainAxisSize.min, spacing: 8, children: [ if (profile.type == ProfileType.custom) _GroupsCountChip(profileId: profile.id) else _buildTrailing(context, isUpdating: isUpdating), if (isSelected) const SelectionBadge(size: 24), ], ), title: ChipTitle( title: profile.realLabel, expire: subscriptionInfo?.expireDate, style: AppTextStyle.headline.of(context), ), subtitle: Text( _subtitle(context), style: AppTextStyle.footnote.of(context).toLighter, maxLines: 1, overflow: TextOverflow.ellipsis, ), ), ), ); } } /// Square-cornered so a lone digit never reads as a second [SelectionBadge]. class _GroupsCountChip extends ConsumerWidget { const _GroupsCountChip({required this.profileId}); final int profileId; @override Widget build(BuildContext context, WidgetRef ref) { final count = ref.watch(profileGroupsCountProvider(profileId)).value; if (count == null) { return const SizedBox.shrink(); } final colorScheme = context.colorScheme; return Tooltip( message: context.appLocalizations.proxyGroupsCount(count, count.compact), child: TonalChip( label: count.compact, color: colorScheme.primary.opacity15, foregroundColor: colorScheme.primary, ), ); } } class ReorderableProfilesSheet extends ConsumerStatefulWidget { final List profiles; const ReorderableProfilesSheet({super.key, required this.profiles}); @override ConsumerState createState() => _ReorderableProfilesSheetState(); } class _ReorderableProfilesSheetState extends ConsumerState { late List profiles; @override void initState() { super.initState(); profiles = List.from(widget.profiles); } Widget _buildItem(int index) { final position = ItemPosition.get(index, profiles.length); final profile = profiles[index]; return ReorderDragStartListener( key: Key(profile.id.toString()), index: index, child: ItemPositionProvider( position: position, child: DecorationListItem( contentPadding: EdgeInsetsDirectional.only( start: context.listInsets.leading, ), trailing: SortHandle(index: index), title: Text(profile.realLabel), ), ), ); } void _handleSave() { Navigator.of(context).pop(); final latest = ref.read(profilesProvider); final ids = {for (final profile in profiles) profile.id}; ref.read(profilesProvider.notifier).reorder([ for (final profile in profiles) ?latest.getProfile(profile.id), for (final profile in latest) if (!ids.contains(profile.id)) profile, ]); } @override Widget build(BuildContext context) { final appLocalizations = context.appLocalizations; return Scaffold( confirmationAction: IconButtonData( glyph: AppGlyphs.check, onPressed: _handleSave, tooltip: context.appLocalizations.save, ), body: PrismReorderableListView( padding: context.listInsets.page( top: context.contentTopPadding, bottom: 32 + context.bottomInset, ), proxyDecorator: (child, index, animation) { return commonProxyDecorator(_buildItem(index), index, animation); }, onReorderItem: (oldIndex, newIndex) { setState(() { profiles = profiles.copyAndReorder(oldIndex, newIndex); }); }, itemBuilder: (_, index) { return _buildItem(index); }, itemCount: profiles.length, ), title: appLocalizations.profilesSort, ); } }