From 0b1313d0bea62a8da28e81b85b26da3d8e0e75f7 Mon Sep 17 00:00:00 2001 From: Armand <4831c0@proton.me> Date: Sat, 15 Aug 2026 22:15:47 +0200 Subject: [PATCH] feat: refactor settings ui system --- .../lib/core/bloc/app_icon_picker_cubit.dart | 52 ++ firka/lib/core/settings.dart | 14 +- firka/lib/l10n | 2 +- .../settings/settings_account_picker.dart | 309 +++++++ .../settings/settings_app_icon_picker.dart | 255 ++++++ .../screens/settings/settings_bool_row.dart | 62 ++ .../settings/settings_license_page.dart | 108 +++ .../phone/screens/settings/settings_logs.dart | 97 ++ .../screens/settings/settings_screen.dart | 826 ++---------------- 9 files changed, 941 insertions(+), 784 deletions(-) create mode 100644 firka/lib/core/bloc/app_icon_picker_cubit.dart create mode 100644 firka/lib/ui/phone/screens/settings/settings_account_picker.dart create mode 100644 firka/lib/ui/phone/screens/settings/settings_app_icon_picker.dart create mode 100644 firka/lib/ui/phone/screens/settings/settings_bool_row.dart create mode 100644 firka/lib/ui/phone/screens/settings/settings_license_page.dart create mode 100644 firka/lib/ui/phone/screens/settings/settings_logs.dart diff --git a/firka/lib/core/bloc/app_icon_picker_cubit.dart b/firka/lib/core/bloc/app_icon_picker_cubit.dart new file mode 100644 index 00000000..f5f2ef6d --- /dev/null +++ b/firka/lib/core/bloc/app_icon_picker_cubit.dart @@ -0,0 +1,52 @@ +import "package:flutter/services.dart"; +import "package:flutter_bloc/flutter_bloc.dart"; +import "package:logging/logging.dart"; + +import "package:firka/core/settings/settings_repository.dart"; +import "package:firka/core/settings/settings_schema.dart"; + +final Logger _logger = Logger('AppIconPickerCubit'); + +class AppIconPickerState { + final String activeIcon; + final bool saving; + + const AppIconPickerState({required this.activeIcon, this.saving = false}); + + AppIconPickerState copyWith({String? activeIcon, bool? saving}) => + AppIconPickerState( + activeIcon: activeIcon ?? this.activeIcon, + saving: saving ?? this.saving, + ); +} + +class AppIconPickerCubit extends Cubit { + AppIconPickerCubit(String initialIcon) + : super(AppIconPickerState(activeIcon: initialIcon)); + + void select(String icon) { + if (state.saving) return; + emit(state.copyWith(activeIcon: icon)); + } + + /// Persists the selected icon and swaps the platform's launcher icon. + Future save(List allIconKeys) async { + if (state.saving) return; + emit(state.copyWith(saving: true)); + + await Settings.appIcon.set(state.activeIcon); + + await Future.delayed(Duration(seconds: 1)); + + _logger.info(allIconKeys.join(",")); + _logger.info(state.activeIcon); + + const channel = MethodChannel('firka.app/main'); + _logger.info( + await channel.invokeMethod('set_icon', { + "icon": state.activeIcon == "original" ? null : state.activeIcon, + "icons": allIconKeys.join(","), + }), + ); + } +} diff --git a/firka/lib/core/settings.dart b/firka/lib/core/settings.dart index b80f7921..dbe8ab23 100644 --- a/firka/lib/core/settings.dart +++ b/firka/lib/core/settings.dart @@ -205,7 +205,7 @@ SettingsUiGroup buildSettingsTree(AppLocalizations l10n) { SettingsUiBoolean( null, null, - "Privacy Ever Declined", + l10n.s_ag_privacy_ever_declined, SettingsRegistry.liveActivityPrivacyEverDeclined, never, ), @@ -360,16 +360,16 @@ SettingsUiGroup buildSettingsTree(AppLocalizations l10n) { SettingsUiSubGroup( FirkaIconType.majesticons, Majesticon.lightningBoltSolid, - "Extrák", + l10n.s_extras, [SettingsUiBackHeader(l10n.s_settings, always)], never, ), SettingsUiPadding(20, never), - SettingsUiHeaderSmall("Egyéb", never), + SettingsUiHeaderSmall(l10n.s_other, never), SettingsUiSubGroup( FirkaIconType.majesticonsLocal, "wrenchSolid", - "Developer", + l10n.s_developer, [ SettingsUiBackHeader(l10n.s_settings, always), SettingsUiBoolean( @@ -386,7 +386,7 @@ SettingsUiGroup buildSettingsTree(AppLocalizations l10n) { SettingsUiBoolean( null, null, - "Beta warning", + l10n.s_beta_warning, SettingsRegistry.betaWarning, never, ), @@ -398,7 +398,7 @@ SettingsUiGroup buildSettingsTree(AppLocalizations l10n) { never, ), SettingsUiPadding(20, always), - SettingsUiHeaderSmall("Névjegy", always), + SettingsUiHeaderSmall(l10n.s_about, always), SettingsUiSubGroup( FirkaIconType.majesticons, Majesticon.chatSolid, @@ -430,7 +430,7 @@ SettingsUiGroup buildSettingsTree(AppLocalizations l10n) { SettingsUiBoolean( null, null, - "Developer", + l10n.s_developer, SettingsRegistry.developerOptsEnabled, never, ), diff --git a/firka/lib/l10n b/firka/lib/l10n index 2dd94691..2715ee8b 160000 --- a/firka/lib/l10n +++ b/firka/lib/l10n @@ -1 +1 @@ -Subproject commit 2dd94691b70153307e3be10d9b0ec58e8cecb06f +Subproject commit 2715ee8b5ddb367bb9a19056ba2d64ebf2ebf1de diff --git a/firka/lib/ui/phone/screens/settings/settings_account_picker.dart b/firka/lib/ui/phone/screens/settings/settings_account_picker.dart new file mode 100644 index 00000000..459e3a9a --- /dev/null +++ b/firka/lib/ui/phone/screens/settings/settings_account_picker.dart @@ -0,0 +1,309 @@ +import "dart:io"; + +import "package:dart_jsonwebtoken/dart_jsonwebtoken.dart"; +import "package:firka/app/app_state.dart"; +import "package:firka/app/initialization.dart"; +import "package:firka/services/live_activity_service.dart"; +import "package:firka/services/watch_sync_helper.dart"; +import "package:firka/ui/shared/firka_icon.dart"; +import "package:firka/ui/theme/style.dart"; +import "package:firka/ui/phone/widgets/login_webview.dart"; +import "package:firka_common/data/models/token_model.dart"; +import "package:firka_common/ui/components/firka_card.dart"; +import "package:flutter/material.dart"; +import "package:isar_community/isar.dart"; + +class SettingsAccountPickerView extends StatelessWidget { + final AppInitialization data; + final List tokens; + final void Function(VoidCallback fn) setStateOuter; + + const SettingsAccountPickerView({ + required this.data, + required this.tokens, + required this.setStateOuter, + super.key, + }); + + @override + Widget build(BuildContext context) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + for (final token in tokens) ...[ + _accountRow(context, token), + SizedBox(height: 8), + ], + GestureDetector( + child: FirkaCard( + left: [ + Text( + data.l10n.s_acc_add, + style: appStyle.fonts.B_16R.apply( + color: appStyle.colors.textPrimary, + ), + ), + ], + ), + onTap: () { + showModalBottomSheet( + context: context, + isScrollControlled: true, + enableDrag: false, + builder: (BuildContext context) { + return LoginWebviewWidget(data); + }, + ); + }, + ), + SizedBox(height: 20), + GestureDetector( + child: FirkaCard( + left: [ + Row( + children: [ + FirkaIconWidget( + FirkaIconType.icons, + "group", + color: appStyle.colors.accent, + ), + SizedBox(width: 8), + Text( + data.l10n.s_acc_logout, + style: appStyle.fonts.B_16R.apply( + color: appStyle.colors.textPrimary, + ), + ), + ], + ), + ], + ), + onTap: () => _logout(context), + ), + ], + ); + } + + Widget _accountRow(BuildContext context, TokenModel token) { + final jwt = JWT.decode(token.idToken!); + final payload = jwt.payload as Map; + String studentRole = payload["role"]; + if (studentRole == "Tanulo") { + studentRole = "Tanuló"; + } else if (studentRole == "Gondviselo") { + studentRole = "Gondviselő"; + } + + return GestureDetector( + child: SizedBox( + height: 52, + child: FirkaCard( + left: [ + Text( + payload["name"], + style: appStyle.fonts.B_16R.apply( + color: appStyle.colors.textPrimary, + ), + ), + SizedBox(width: 8), + Text( + studentRole, + style: appStyle.fonts.B_16R.apply( + color: appStyle.colors.textTertiary, + ), + ), + ], + right: [ + token.key != data.settings.selectedAccountKey + ? SizedBox() + : Checkbox( + value: true, + fillColor: WidgetStateProperty.resolveWith(( + Set states, + ) { + return appStyle.colors.secondary; + }), + onChanged: (_) async { + setStateOuter(() {}); + logger.finest('Settings saved'); + }, + ), + ], + ), + ), + onTap: () => _switchAccount(context, token), + ); + } + + Future _switchAccount(BuildContext context, TokenModel token) async { + if (token.key == data.settings.selectedAccountKey) { + return; + } + + final previousAccountId = data.client!.cache.token.key; + if (Platform.isIOS) { + await LiveActivityService.onUserLogout(); + try { + await WatchSyncHelper.clearSharedLanguageState(); + } catch (e) { + logger.warning( + '[Settings] Failed to clear shared language state on account switch: $e', + ); + } + if (previousAccountId != null) { + try { + await WatchSyncHelper.clearRefreshLeaseForAccount(previousAccountId); + } catch (e) { + logger.warning( + '[Settings] Failed to clear refresh lease on account switch: $e', + ); + } + } + } + + await data.settings.setSelectedAccountKey(token.key); + await initializeApp(); + + if (Platform.isIOS) { + var watchReachable = false; + try { + watchReachable = await WatchSyncHelper.isWatchReachable( + forceRefreshInstall: true, + ); + } catch (e) { + logger.warning( + '[Settings] Failed to query Watch reachability on account switch: $e', + ); + } + + if (watchReachable) { + try { + await WatchSyncHelper.sendTokenModelToWatch( + token, + allowExpiredAccessToken: true, + ); + } catch (e) { + logger.warning( + '[Settings] Failed to send switched account token to reachable Watch: $e', + ); + } + } else { + try { + await WatchSyncHelper.saveTokenToiCloud( + token, + forceAccountSwitch: true, + ); + } catch (e) { + logger.warning( + '[Settings] Failed to sync switched account token to iCloud: $e', + ); + } + } + } + + if (!context.mounted) return; + final nav = Navigator.of(context); + if (nav.canPop()) nav.pop(); + appRouter?.go('/home'); + } + + Future _logout(BuildContext context) async { + try { + if (Platform.isIOS) { + await LiveActivityService.onUserLogout(); + } + + final active = data.client!.cache.token.key; + if (Platform.isIOS) { + try { + await WatchSyncHelper.clearRefreshLeaseForAccount(active); + } catch (e) { + logger.warning( + '[Settings] Failed to clear refresh lease for active account: $e', + ); + } + try { + await WatchSyncHelper.clearSharedLanguageState(); + } catch (e) { + logger.warning( + '[Settings] Failed to clear shared language state on logout: $e', + ); + } + } + + await data.isar.writeTxn(() async { + await data.isar.tokenModels.delete(active); + }); + await data.settings.setSelectedAccountKey(0); + + final accounts = await data.isar.tokenModels.where().findAll(); + + if (accounts.isEmpty) { + if (Platform.isIOS) { + try { + await WatchSyncHelper.clearICloudToken(notifyWatch: true); + await WatchSyncHelper.clearAllRefreshLeases(); + } catch (e) { + logger.warning('[Settings] Failed to clear iCloud token: $e'); + } + } + } else { + if (Platform.isIOS) { + final nextToken = accounts.first; + var watchReachable = false; + try { + watchReachable = await WatchSyncHelper.isWatchReachable( + forceRefreshInstall: true, + ); + } catch (e) { + logger.warning( + '[Settings] Failed to query Watch reachability after logout: $e', + ); + } + + if (watchReachable) { + try { + await WatchSyncHelper.sendTokenModelToWatch( + nextToken, + allowExpiredAccessToken: true, + ); + } catch (e) { + logger.warning( + '[Settings] Failed to send next account token to reachable Watch after logout: $e', + ); + } + } else { + try { + await WatchSyncHelper.saveTokenToiCloud( + nextToken, + forceAccountSwitch: true, + ); + } catch (e) { + logger.warning( + '[Settings] Failed to sync next account token to iCloud after logout: $e', + ); + } + } + } + } + + await initializeApp(); + + if (!context.mounted) return; + final nav = Navigator.of(context); + if (nav.canPop()) nav.pop(); + if (accounts.isEmpty) { + appRouter?.go('/login'); + } else { + appRouter?.go('/home'); + } + } catch (e, st) { + logger.shout('[Settings] Logout failed: $e', e, st); + if (context.mounted) { + final nav = Navigator.of(context); + if (nav.canPop()) nav.pop(); + } + appRouter?.go('/login'); + } + } +} diff --git a/firka/lib/ui/phone/screens/settings/settings_app_icon_picker.dart b/firka/lib/ui/phone/screens/settings/settings_app_icon_picker.dart new file mode 100644 index 00000000..f4a501fa --- /dev/null +++ b/firka/lib/ui/phone/screens/settings/settings_app_icon_picker.dart @@ -0,0 +1,255 @@ +import "package:firka/app/app_state.dart"; +import "package:firka/core/bloc/app_icon_picker_cubit.dart"; +import "package:firka/core/image_preloader.dart"; +import "package:firka/core/settings.dart"; +import "package:firka/core/settings/settings_repository.dart"; +import "package:firka/core/settings/settings_schema.dart"; +import "package:firka/core/settings/settings_ui.dart"; +import "package:firka/core/firka_bundle.dart"; +import "package:firka/ui/components/firka_button.dart"; +import "package:firka/ui/theme/style.dart"; +import "package:flutter/material.dart"; +import "package:flutter_bloc/flutter_bloc.dart"; + +import "settings_bool_row.dart"; + +class SettingsAppIconPreviewView extends StatelessWidget { + final AppInitialization data; + + const SettingsAppIconPreviewView({required this.data, super.key}); + + @override + Widget build(BuildContext context) { + final activeIcon = context.watch().state.activeIcon; + + return Container( + decoration: BoxDecoration( + image: DecorationImage( + image: PreloadedImageProvider( + FirkaBundle(), + ('assets/images/background.webp'), + ), + fit: BoxFit.cover, + ), + borderRadius: BorderRadius.all(Radius.circular(16)), + ), + width: MediaQuery.of(context).size.width, + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 16), + child: Column( + children: [ + Column( + children: [ + ClipRRect( + borderRadius: const BorderRadius.all(Radius.circular(16.0)), + child: Image( + image: PreloadedImageProvider( + FirkaBundle(), + "assets/images/icons/$activeIcon.webp", + ), + width: 74, + height: 74, + ), + ), + Text( + appIconLabels(data.l10n)[activeIcon]!, + style: appStyle.fonts.H_12px.apply( + color: appStyle.colors.card, + ), + ), + ], + ), + ], + ), + ), + ); + } +} + +class SettingsAppIconPickerView extends StatelessWidget { + final AppInitialization data; + final SettingsUiAppIconPicker item; + final SettingsRepository settings; + final void Function(VoidCallback fn) setStateOuter; + + const SettingsAppIconPickerView({ + required this.data, + required this.item, + required this.settings, + required this.setStateOuter, + super.key, + }); + + @override + Widget build(BuildContext context) { + final cubit = context.watch(); + final activeIcon = cubit.state.activeIcon; + final saving = cubit.state.saving; + + List pWidgets = []; + + for (var group in item.iconGroups.keys) { + if (Settings.childProtection.value) { + if (group == data.l10n.s_ci_icon_g7) { + continue; + } + } else { + if (group == data.l10n.s_ci_icon_g8) { + continue; + } + } + List groupIcons = []; + for (var icon in item.iconGroups[group]!) { + var active = icon == activeIcon; + + groupIcons.add( + Column( + children: [ + GestureDetector( + child: active + ? Container( + decoration: BoxDecoration( + color: appStyle.colors.accent, + borderRadius: BorderRadius.all(Radius.circular(16)), + ), + child: Padding( + padding: const EdgeInsets.all(4), + child: ClipRRect( + borderRadius: const BorderRadius.all( + Radius.circular(12.0), + ), + child: Image( + image: PreloadedImageProvider( + FirkaBundle(), + "assets/images/icons/$icon.webp", + ), + width: 48, + height: 48, + ), + ), + ), + ) + : ClipRRect( + borderRadius: const BorderRadius.all( + Radius.circular(16.0), + ), + child: Image( + image: PreloadedImageProvider( + FirkaBundle(), + "assets/images/icons/$icon.webp", + ), + width: 54, + height: 54, + ), + ), + onTap: () { + if (saving) return; + + cubit.select(icon); + }, + ), + Text( + appIconLabels(data.l10n)[icon]!, + style: appStyle.fonts.B_12R.apply( + color: active + ? appStyle.colors.textPrimary + : appStyle.colors.textSecondary, + ), + textAlign: TextAlign.center, + ), + ], + ), + ); + } + + pWidgets.add( + Text( + group, + style: appStyle.fonts.H_14px.apply( + color: appStyle.colors.textPrimary, + ), + ), + ); + + if (group == data.l10n.s_ci_icon_g6) { + pWidgets.add( + Text( + data.l10n.s_ci_icon_g6_desc, + style: appStyle.fonts.B_16R.apply( + color: appStyle.colors.textSecondary, + ), + ), + ); + } + + if (group == data.l10n.s_ci_icon_g7 || group == data.l10n.s_ci_icon_g8) { + pWidgets.add(SizedBox(height: 12)); + pWidgets.add( + buildBoolRow(item.childProtection, settings, setStateOuter), + ); + } + + pWidgets.add(SizedBox(height: 12)); + pWidgets.add( + SizedBox( + height: (groupIcons.length / 4).ceil() * 100, + child: GridView.count( + crossAxisCount: 4, + physics: NeverScrollableScrollPhysics(), + children: groupIcons, + ), + ), + ); + } + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + height: MediaQuery.of(context).size.height / 1.7, + child: SingleChildScrollView( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: pWidgets, + ), + ), + ), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + GestureDetector( + child: FirkaButton( + text: data.l10n.cancel, + bgColor: appStyle.colors.buttonSecondaryFill, + fontStyle: appStyle.fonts.B_16R.apply( + color: appStyle.colors.textSecondary, + ), + ), + onTap: () { + Navigator.pop(context); + }, + ), + GestureDetector( + child: FirkaButton( + text: data.l10n.save, + bgColor: appStyle.colors.accent, + fontStyle: appStyle.fonts.B_16R.apply( + color: appStyle.colors.textSecondaryLight, + ), + ), + onTap: () async { + if (saving) return; + + await cubit.save( + appIconLabels( + data.l10n, + ).keys.where((e) => e != "original").toList(), + ); + }, + ), + ], + ), + ], + ); + } +} diff --git a/firka/lib/ui/phone/screens/settings/settings_bool_row.dart b/firka/lib/ui/phone/screens/settings/settings_bool_row.dart new file mode 100644 index 00000000..7def2904 --- /dev/null +++ b/firka/lib/ui/phone/screens/settings/settings_bool_row.dart @@ -0,0 +1,62 @@ +import "package:firka/core/settings/settings_repository.dart"; +import "package:firka/core/settings/settings_ui.dart"; +import "package:firka/ui/shared/firka_icon.dart"; +import "package:firka/ui/theme/style.dart"; +import "package:firka_common/ui/components/firka_card.dart"; +import "package:flutter/material.dart"; + +Widget buildBoolRow( + SettingsUiBoolean item, + SettingsRepository settings, + void Function(VoidCallback fn) setStateOuter, +) { + final value = settings.get(item.setting); + + return FirkaCard( + height: 52 + 12, + left: [ + item.iconType != null + ? Row( + children: [ + FirkaIconWidget( + item.iconType!, + item.iconData!, + color: appStyle.colors.accent, + package: + item.iconType == FirkaIconType.icons || + item.iconType == FirkaIconType.majesticonsLocal + ? 'firka' + : null, + ), + SizedBox(width: 4), + ], + ) + : SizedBox(), + Text( + item.title, + style: appStyle.fonts.B_16SB.apply(color: appStyle.colors.textPrimary), + ), + ], + right: [ + Switch( + value: value, + thumbColor: WidgetStateProperty.fromMap({ + WidgetState.selected: appStyle.colors.buttonSecondaryFill, + WidgetState.any: appStyle.colors.accent, + }), + trackColor: WidgetStateProperty.fromMap({ + WidgetState.selected: appStyle.colors.accent, + WidgetState.any: appStyle.colors.a10p, + }), + trackOutlineColor: WidgetStateProperty.fromMap({ + WidgetState.selected: appStyle.colors.accent, + WidgetState.any: appStyle.colors.a15p, + }), + onChanged: (v) async { + await settings.set(item.setting, v); + setStateOuter(() {}); + }, + ), + ], + ); +} diff --git a/firka/lib/ui/phone/screens/settings/settings_license_page.dart b/firka/lib/ui/phone/screens/settings/settings_license_page.dart new file mode 100644 index 00000000..040d01ca --- /dev/null +++ b/firka/lib/ui/phone/screens/settings/settings_license_page.dart @@ -0,0 +1,108 @@ +import "package:firka/app/app_state.dart"; +import "package:firka/ui/theme/style.dart"; +import "package:firka_common/ui/components/firka_card.dart"; +import "package:flutter/foundation.dart"; +import "package:flutter/material.dart"; + +class SettingsLicensePageView extends StatelessWidget { + final AppInitialization data; + + const SettingsLicensePageView({required this.data, super.key}); + + @override + Widget build(BuildContext context) { + return FutureBuilder>( + future: LicenseRegistry.licenses.toList(), + builder: + (BuildContext context, AsyncSnapshot> snapshot) { + if (!snapshot.hasData) { + return Center( + child: CircularProgressIndicator(color: appStyle.colors.accent), + ); + } + + final licenses = snapshot.data!; + final shownPackages = {}; + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: licenses + .where( + (license) => license.packages.any( + (pkg) => !shownPackages.contains(pkg), + ), + ) + .map((license) { + final packageName = license.packages.firstWhere( + (pkg) => !shownPackages.contains(pkg), + orElse: () => license.packages.first, + ); + shownPackages.add(packageName); + final paragraphs = license.paragraphs + .map((p) => p.text) + .join('\n\n'); + + return Padding( + padding: const EdgeInsets.symmetric(vertical: 8.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + GestureDetector( + onTap: () { + showDialog( + context: context, + builder: (BuildContext context) { + return AlertDialog( + backgroundColor: appStyle.colors.card, + title: Text( + packageName, + style: const TextStyle( + fontWeight: FontWeight.bold, + ), + ), + content: SingleChildScrollView( + child: Text( + paragraphs, + style: appStyle.fonts.B_15SB.apply( + color: appStyle.colors.textPrimary, + ), + ), + ), + actions: [ + TextButton( + child: Text( + data.l10n.close, + style: appStyle.fonts.B_14R.apply( + color: + appStyle.colors.textSecondary, + ), + ), + onPressed: () { + Navigator.of(context).pop(); + }, + ), + ], + ); + }, + ); + }, + child: FirkaCard( + left: [ + Text( + packageName, + style: appStyle.fonts.B_14R.apply( + color: appStyle.colors.textPrimary, + ), + ), + ], + ), + ), + ], + ), + ); + }) + .toList(), + ); + }, + ); + } +} diff --git a/firka/lib/ui/phone/screens/settings/settings_logs.dart b/firka/lib/ui/phone/screens/settings/settings_logs.dart new file mode 100644 index 00000000..5093c225 --- /dev/null +++ b/firka/lib/ui/phone/screens/settings/settings_logs.dart @@ -0,0 +1,97 @@ +import "dart:io"; + +import "package:firka/app/app_state.dart"; +import "package:firka/ui/shared/firka_icon.dart"; +import "package:firka/ui/theme/style.dart"; +import "package:firka_common/ui/components/firka_card.dart"; +import "package:flutter/material.dart"; +import "package:majesticons_flutter/majesticons_flutter.dart"; +import "package:path/path.dart" as p; +import "package:share_plus/share_plus.dart"; + +class SettingsLogsView extends StatelessWidget { + final AppInitialization data; + + const SettingsLogsView({required this.data, super.key}); + + @override + Widget build(BuildContext context) { + final logFileRegex = RegExp(r'^(\d{4})_(\d{2})_(\d{2})\.log$'); + final entries = data.appDir + .listSync() + .whereType() + .where((entity) => logFileRegex.hasMatch(entity.uri.pathSegments.last)) + .toList(); + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + for (final entity in entries) ...[ + GestureDetector( + child: SizedBox( + height: 52, + child: FirkaCard( + left: [ + FirkaIconWidget( + FirkaIconType.majesticons, + Majesticon.noteTextSolid, + color: appStyle.colors.accent, + ), + Text( + entity.uri.pathSegments.last, + style: appStyle.fonts.B_16R.apply( + color: appStyle.colors.textPrimary, + ), + ), + ], + ), + ), + onTap: () => _shareLog(entity), + ), + SizedBox(height: 8), + ], + ], + ); + } + + Future _shareLog(File entity) async { + final name = entity.uri.pathSegments.last; + + try { + logger.info("Compressing log file: ${entity.path}"); + final originalBytes = await entity.readAsBytes(); + final gzBytes = GZipCodec().encode(originalBytes); + final tempDir = await Directory.systemTemp.createTemp('firka'); + final gzPath = p.join(tempDir.path, '${p.basename(entity.path)}.gz'); + final gzFile = await File(gzPath).writeAsBytes(gzBytes, flush: true); + + final params = ShareParams( + text: name, + files: [XFile(gzFile.path, mimeType: 'application/gzip')], + ); + + await SharePlus.instance.share(params); + + await gzFile.delete(); + await tempDir.delete(); + } catch (ex) { + if (ex is Error) { + logger.shout( + "Failed to compress log file", + ex.toString(), + ex.stackTrace, + ); + } else { + logger.shout("Failed to compress log file", ex.toString()); + } + + logger.info("Sharing regular log file instead: ${entity.path}"); + final params = ShareParams( + text: name, + files: [XFile(entity.path, mimeType: 'text/plain')], + ); + + await SharePlus.instance.share(params); + } + } +} diff --git a/firka/lib/ui/phone/screens/settings/settings_screen.dart b/firka/lib/ui/phone/screens/settings/settings_screen.dart index b4e350be..9b4f3f3e 100644 --- a/firka/lib/ui/phone/screens/settings/settings_screen.dart +++ b/firka/lib/ui/phone/screens/settings/settings_screen.dart @@ -1,34 +1,28 @@ -import 'dart:io'; - -import 'package:dart_jsonwebtoken/dart_jsonwebtoken.dart'; import 'package:firka_common/data/database.dart'; import 'package:firka_common/data/models/token_model.dart'; -import 'package:firka/core/image_preloader.dart'; -import 'package:firka/core/settings.dart'; +import 'package:firka/core/bloc/app_icon_picker_cubit.dart'; import 'package:firka/core/settings/setting.dart'; import 'package:firka/core/settings/settings_repository.dart'; import 'package:firka/core/settings/settings_schema.dart'; import 'package:firka/core/settings/settings_ui.dart'; -import 'package:firka/ui/components/firka_button.dart'; import 'package:firka_common/ui/components/firka_card.dart'; import 'package:firka/app/app_state.dart'; import 'package:firka/ui/theme/style.dart'; import 'package:firka/ui/shared/firka_icon.dart'; import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:go_router/go_router.dart'; -import 'package:flutter/services.dart'; +import 'package:isar_community/isar.dart'; import 'package:majesticons_flutter/majesticons_flutter.dart'; -import 'package:path/path.dart' as p; -import 'package:share_plus/share_plus.dart'; import 'package:url_launcher/url_launcher_string.dart'; import 'package:firka/core/firka_bundle.dart'; -import 'package:firka/app/initialization.dart'; import 'package:firka/core/state/firka_state.dart'; -import 'package:firka/services/live_activity_service.dart'; -import 'package:firka/services/watch_sync_helper.dart'; -import 'package:flutter/foundation.dart'; -import 'package:isar_community/isar.dart'; -import '../../widgets/login_webview.dart'; + +import 'settings_account_picker.dart'; +import 'settings_app_icon_picker.dart'; +import 'settings_bool_row.dart'; +import 'settings_license_page.dart'; +import 'settings_logs.dart'; class SettingsScreen extends StatefulWidget { final AppInitialization data; @@ -43,16 +37,21 @@ class SettingsScreen extends StatefulWidget { class _SettingsScreenState extends FirkaState { _SettingsScreenState(); - bool settingAppIcon = false; - late String activeIcon; late List tokens; + late final AppIconPickerCubit appIconPickerCubit; @override void initState() { super.initState(); - activeIcon = Settings.appIcon.value; tokens = isarInit.tokenModels.where().sortByUpdatedAtMsDesc().findAllSync(); + appIconPickerCubit = AppIconPickerCubit(Settings.appIcon.value); + } + + @override + void dispose() { + appIconPickerCubit.close(); + super.dispose(); } String _roundedDoubleString(double value, DoubleSetting setting) { @@ -63,60 +62,6 @@ class _SettingsScreenState extends FirkaState { : value.toStringAsPrecision(setting.precision); } - Widget _boolRow(SettingsUiBoolean item, SettingsRepository settings) { - final value = settings.get(item.setting); - - return FirkaCard( - height: 52 + 12, - left: [ - item.iconType != null - ? Row( - children: [ - FirkaIconWidget( - item.iconType!, - item.iconData!, - color: appStyle.colors.accent, - package: - item.iconType == FirkaIconType.icons || - item.iconType == FirkaIconType.majesticonsLocal - ? 'firka' - : null, - ), - SizedBox(width: 4), - ], - ) - : SizedBox(), - Text( - item.title, - style: appStyle.fonts.B_16SB.apply( - color: appStyle.colors.textPrimary, - ), - ), - ], - right: [ - Switch( - value: value, - thumbColor: WidgetStateProperty.fromMap({ - WidgetState.selected: appStyle.colors.buttonSecondaryFill, - WidgetState.any: appStyle.colors.accent, - }), - trackColor: WidgetStateProperty.fromMap({ - WidgetState.selected: appStyle.colors.accent, - WidgetState.any: appStyle.colors.a10p, - }), - trackOutlineColor: WidgetStateProperty.fromMap({ - WidgetState.selected: appStyle.colors.accent, - WidgetState.any: appStyle.colors.a15p, - }), - onChanged: (v) async { - await settings.set(item.setting, v); - setState(() {}); - }, - ), - ], - ); - } - List createWidgetTree( Iterable items, SettingsRepository settings, { @@ -327,7 +272,7 @@ class _SettingsScreenState extends FirkaState { continue; } if (item is SettingsUiBoolean) { - widgets.add(_boolRow(item, settings)); + widgets.add(buildBoolRow(item, settings, setState)); continue; } @@ -400,628 +345,33 @@ class _SettingsScreenState extends FirkaState { continue; } if (item is SettingsUiLicensePage) { - widgets.add( - FutureBuilder>( - future: LicenseRegistry.licenses.toList(), - builder: - ( - BuildContext context, - AsyncSnapshot> snapshot, - ) { - if (!snapshot.hasData) { - return Center( - child: CircularProgressIndicator( - color: appStyle.colors.accent, - ), - ); - } - - final licenses = snapshot.data!; - final shownPackages = {}; - return Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: licenses - .where( - (license) => license.packages.any( - (pkg) => !shownPackages.contains(pkg), - ), - ) - .map((license) { - final packageName = license.packages.firstWhere( - (pkg) => !shownPackages.contains(pkg), - orElse: () => license.packages.first, - ); - shownPackages.add(packageName); - final paragraphs = license.paragraphs - .map((p) => p.text) - .join('\n\n'); - - return Padding( - padding: const EdgeInsets.symmetric(vertical: 8.0), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - GestureDetector( - onTap: () { - showDialog( - context: context, - builder: (BuildContext context) { - return AlertDialog( - backgroundColor: appStyle.colors.card, - title: Text( - packageName, - style: const TextStyle( - fontWeight: FontWeight.bold, - ), - ), - content: SingleChildScrollView( - child: Text( - paragraphs, - style: appStyle.fonts.B_15SB - .apply( - color: appStyle - .colors - .textPrimary, - ), - ), - ), - actions: [ - TextButton( - child: Text( - widget.data.l10n.close, - style: appStyle.fonts.B_14R - .apply( - color: appStyle - .colors - .textSecondary, - ), - ), - onPressed: () { - Navigator.of(context).pop(); - }, - ), - ], - ); - }, - ); - }, - child: FirkaCard( - left: [ - Text( - packageName, - style: appStyle.fonts.B_14R.apply( - color: appStyle.colors.textPrimary, - ), - ), - ], - ), - ), - ], - ), - ); - }) - .toList(), - ); - }, - ), - ); + widgets.add(SettingsLicensePageView(data: widget.data)); continue; } if (item is SettingsUiAppIconPreview) { - widgets.add( - Container( - decoration: BoxDecoration( - image: DecorationImage( - image: PreloadedImageProvider( - FirkaBundle(), - ('assets/images/background.webp'), - ), - fit: BoxFit.cover, - ), - borderRadius: BorderRadius.all(Radius.circular(16)), - ), - width: MediaQuery.of(context).size.width, - child: Padding( - padding: const EdgeInsets.symmetric(vertical: 16), - child: Column( - children: [ - Column( - children: [ - ClipRRect( - borderRadius: const BorderRadius.all( - Radius.circular(16.0), - ), - child: Image( - image: PreloadedImageProvider( - FirkaBundle(), - "assets/images/icons/$activeIcon.webp", - ), - width: 74, - height: 74, - ), - ), - Text( - appIconLabels(widget.data.l10n)[activeIcon]!, - style: appStyle.fonts.H_12px.apply( - color: appStyle.colors.card, - ), - ), - ], - ), - ], - ), - ), - ), - ); + widgets.add(SettingsAppIconPreviewView(data: widget.data)); continue; } if (item is SettingsUiAppIconPicker) { - List pWidgets = []; - - for (var group in item.iconGroups.keys) { - if (Settings.childProtection.value) { - if (group == widget.data.l10n.s_ci_icon_g7) { - continue; - } - } else { - if (group == widget.data.l10n.s_ci_icon_g8) { - continue; - } - } - List groupIcons = []; - for (var icon in item.iconGroups[group]!) { - var active = icon == activeIcon; - - groupIcons.add( - Column( - children: [ - GestureDetector( - child: active - ? Container( - decoration: BoxDecoration( - color: appStyle.colors.accent, - borderRadius: BorderRadius.all( - Radius.circular(16), - ), - ), - child: Padding( - padding: const EdgeInsets.all(4), - child: ClipRRect( - borderRadius: const BorderRadius.all( - Radius.circular(12.0), - ), - child: Image( - image: PreloadedImageProvider( - FirkaBundle(), - "assets/images/icons/$icon.webp", - ), - width: 48, - height: 48, - ), - ), - ), - ) - : ClipRRect( - borderRadius: const BorderRadius.all( - Radius.circular(16.0), - ), - child: Image( - image: PreloadedImageProvider( - FirkaBundle(), - "assets/images/icons/$icon.webp", - ), - width: 54, - height: 54, - ), - ), - onTap: () { - if (settingAppIcon) return; - - setState(() { - activeIcon = icon; - }); - }, - ), - Text( - appIconLabels(widget.data.l10n)[icon]!, - style: appStyle.fonts.B_12R.apply( - color: active - ? appStyle.colors.textPrimary - : appStyle.colors.textSecondary, - ), - textAlign: TextAlign.center, - ), - ], - ), - ); - } - - pWidgets.add( - Text( - group, - style: appStyle.fonts.H_14px.apply( - color: appStyle.colors.textPrimary, - ), - ), - ); - - if (group == widget.data.l10n.s_ci_icon_g6) { - pWidgets.add( - Text( - widget.data.l10n.s_ci_icon_g6_desc, - style: appStyle.fonts.B_16R.apply( - color: appStyle.colors.textSecondary, - ), - ), - ); - } - - if (group == widget.data.l10n.s_ci_icon_g7 || - group == widget.data.l10n.s_ci_icon_g8) { - pWidgets.add(SizedBox(height: 12)); - pWidgets.add(_boolRow(item.childProtection, settings)); - } - - pWidgets.add(SizedBox(height: 12)); - pWidgets.add( - SizedBox( - height: (groupIcons.length / 4).ceil() * 100, - child: GridView.count( - crossAxisCount: 4, - physics: NeverScrollableScrollPhysics(), - children: groupIcons, - ), - ), - ); - } - widgets.add( - SizedBox( - height: MediaQuery.of(context).size.height / 1.7, - child: SingleChildScrollView( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: pWidgets, - ), - ), - ), - ); - - widgets.add( - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - GestureDetector( - child: FirkaButton( - text: widget.data.l10n.cancel, - bgColor: appStyle.colors.buttonSecondaryFill, - fontStyle: appStyle.fonts.B_16R.apply( - color: appStyle.colors.textSecondary, - ), - ), - onTap: () { - Navigator.pop(context); - }, - ), - GestureDetector( - child: FirkaButton( - text: widget.data.l10n.save, - bgColor: appStyle.colors.accent, - fontStyle: appStyle.fonts.B_16R.apply( - color: appStyle.colors.textSecondaryLight, - ), - ), - onTap: () async { - if (settingAppIcon) return; - settingAppIcon = true; - - await Settings.appIcon.set(activeIcon); - - await Future.delayed(Duration(seconds: 1)); - - logger.info( - appIconLabels( - widget.data.l10n, - ).keys.where((e) => e != "original").join(","), - ); - - logger.info(activeIcon); - - const channel = MethodChannel('firka.app/main'); - logger.info( - await channel.invokeMethod('set_icon', { - "icon": activeIcon == "original" ? null : activeIcon, - "icons": appIconLabels( - widget.data.l10n, - ).keys.where((e) => e != "original").join(","), - }), - ); - }, - ), - ], + SettingsAppIconPickerView( + data: widget.data, + item: item, + settings: settings, + setStateOuter: setState, ), ); continue; } if (item is SettingsUiKretaAccountPicker) { - for (TokenModel token in tokens) { - final jwt = JWT.decode(token.idToken!); - final payload = jwt.payload as Map; - String studentRole = payload["role"]; - if (studentRole == "Tanulo") { - studentRole = "Tanuló"; - } else if (studentRole == "Gondviselo") { - studentRole = "Gondviselő"; - } - widgets.add( - GestureDetector( - child: SizedBox( - height: 52, - child: FirkaCard( - left: [ - Text( - payload["name"], - style: appStyle.fonts.B_16R.apply( - color: appStyle.colors.textPrimary, - ), - ), - SizedBox(width: 8), - Text( - studentRole, - style: appStyle.fonts.B_16R.apply( - color: appStyle.colors.textTertiary, - ), - ), - ], - right: [ - token.key != widget.data.settings.selectedAccountKey - ? SizedBox() - : Checkbox( - value: true, - fillColor: WidgetStateProperty.resolveWith(( - Set states, - ) { - return appStyle.colors.secondary; - }), - onChanged: (_) async { - setState(() {}); - logger.finest('Settings saved'); - }, - ), - ], - ), - ), - onTap: () async { - if (token.key == widget.data.settings.selectedAccountKey) { - return; - } - - final previousAccountId = widget.data.client!.cache.token.key; - if (Platform.isIOS) { - await LiveActivityService.onUserLogout(); - try { - await WatchSyncHelper.clearSharedLanguageState(); - } catch (e) { - logger.warning( - '[Settings] Failed to clear shared language state on account switch: $e', - ); - } - if (previousAccountId != null) { - try { - await WatchSyncHelper.clearRefreshLeaseForAccount( - previousAccountId, - ); - } catch (e) { - logger.warning( - '[Settings] Failed to clear refresh lease on account switch: $e', - ); - } - } - } - - await widget.data.settings.setSelectedAccountKey(token.key); - await initializeApp(); - - if (Platform.isIOS) { - var watchReachable = false; - try { - watchReachable = await WatchSyncHelper.isWatchReachable( - forceRefreshInstall: true, - ); - } catch (e) { - logger.warning( - '[Settings] Failed to query Watch reachability on account switch: $e', - ); - } - - if (watchReachable) { - try { - await WatchSyncHelper.sendTokenModelToWatch( - token, - allowExpiredAccessToken: true, - ); - } catch (e) { - logger.warning( - '[Settings] Failed to send switched account token to reachable Watch: $e', - ); - } - } else { - try { - await WatchSyncHelper.saveTokenToiCloud( - token, - forceAccountSwitch: true, - ); - } catch (e) { - logger.warning( - '[Settings] Failed to sync switched account token to iCloud: $e', - ); - } - } - } - - if (!mounted) return; - final nav = Navigator.of(context); - if (nav.canPop()) nav.pop(); - appRouter?.go('/home'); - }, - ), - ); - widgets.add(SizedBox(height: 8)); - } - widgets.add( - GestureDetector( - child: FirkaCard( - left: [ - Text( - widget.data.l10n.s_acc_add, - style: appStyle.fonts.B_16R.apply( - color: appStyle.colors.textPrimary, - ), - ), - ], - ), - onTap: () { - showModalBottomSheet( - context: context, - isScrollControlled: true, - enableDrag: false, - builder: (BuildContext context) { - return LoginWebviewWidget(widget.data); - }, - ); - }, - ), - ); - widgets.add(SizedBox(height: 20)); - widgets.add( - GestureDetector( - child: FirkaCard( - left: [ - Row( - children: [ - FirkaIconWidget( - FirkaIconType.icons, - "group", - color: appStyle.colors.accent, - ), - SizedBox(width: 8), - Text( - widget.data.l10n.s_acc_logout, - style: appStyle.fonts.B_16R.apply( - color: appStyle.colors.textPrimary, - ), - ), - ], - ), - ], - ), - onTap: () async { - try { - if (Platform.isIOS) { - await LiveActivityService.onUserLogout(); - } - - final active = widget.data.client!.cache.token.key; - if (Platform.isIOS) { - try { - await WatchSyncHelper.clearRefreshLeaseForAccount(active); - } catch (e) { - logger.warning( - '[Settings] Failed to clear refresh lease for active account: $e', - ); - } - try { - await WatchSyncHelper.clearSharedLanguageState(); - } catch (e) { - logger.warning( - '[Settings] Failed to clear shared language state on logout: $e', - ); - } - } - - await widget.data.isar.writeTxn(() async { - await widget.data.isar.tokenModels.delete(active); - }); - await widget.data.settings.setSelectedAccountKey(0); - - final accounts = await widget.data.isar.tokenModels - .where() - .findAll(); - - if (accounts.isEmpty) { - if (Platform.isIOS) { - try { - await WatchSyncHelper.clearICloudToken(notifyWatch: true); - await WatchSyncHelper.clearAllRefreshLeases(); - } catch (e) { - logger.warning( - '[Settings] Failed to clear iCloud token: $e', - ); - } - } - } else { - if (Platform.isIOS) { - final nextToken = accounts.first; - var watchReachable = false; - try { - watchReachable = await WatchSyncHelper.isWatchReachable( - forceRefreshInstall: true, - ); - } catch (e) { - logger.warning( - '[Settings] Failed to query Watch reachability after logout: $e', - ); - } - - if (watchReachable) { - try { - await WatchSyncHelper.sendTokenModelToWatch( - nextToken, - allowExpiredAccessToken: true, - ); - } catch (e) { - logger.warning( - '[Settings] Failed to send next account token to reachable Watch after logout: $e', - ); - } - } else { - try { - await WatchSyncHelper.saveTokenToiCloud( - nextToken, - forceAccountSwitch: true, - ); - } catch (e) { - logger.warning( - '[Settings] Failed to sync next account token to iCloud after logout: $e', - ); - } - } - } - } - - await initializeApp(); - - if (!mounted) return; - final nav = Navigator.of(context); - if (nav.canPop()) nav.pop(); - if (accounts.isEmpty) { - appRouter?.go('/login'); - } else { - appRouter?.go('/home'); - } - } catch (e, st) { - logger.shout('[Settings] Logout failed: $e', e, st); - if (mounted) { - final nav = Navigator.of(context); - if (nav.canPop()) nav.pop(); - } - appRouter?.go('/login'); - } - }, + SettingsAccountPickerView( + data: widget.data, + tokens: tokens, + setStateOuter: setState, ), ); continue; @@ -1066,86 +416,7 @@ class _SettingsScreenState extends FirkaState { continue; } if (item is SettingsUiLogs) { - final logFileRegex = RegExp(r'^(\d{4})_(\d{2})_(\d{2})\.log$'); - - for (final entity in widget.data.appDir.listSync()) { - if (entity is! File) continue; - final name = entity.uri.pathSegments.last; - final m = logFileRegex.firstMatch(name); - if (m == null) continue; - - widgets.add( - GestureDetector( - child: SizedBox( - height: 52, - child: FirkaCard( - left: [ - FirkaIconWidget( - FirkaIconType.majesticons, - Majesticon.noteTextSolid, - color: appStyle.colors.accent, - ), - Text( - name, - style: appStyle.fonts.B_16R.apply( - color: appStyle.colors.textPrimary, - ), - ), - ], - ), - ), - onTap: () async { - try { - logger.info("Compressing log file: ${entity.path}"); - final original = File(entity.path); - final originalBytes = await original.readAsBytes(); - final gzBytes = GZipCodec().encode(originalBytes); - final tempDir = await Directory.systemTemp.createTemp( - 'firka', - ); - final gzPath = p.join( - tempDir.path, - '${p.basename(entity.path)}.gz', - ); - final gzFile = await File( - gzPath, - ).writeAsBytes(gzBytes, flush: true); - - final params = ShareParams( - text: name, - files: [XFile(gzFile.path, mimeType: 'application/gzip')], - ); - - await SharePlus.instance.share(params); - - await gzFile.delete(); - await tempDir.delete(); - } catch (ex) { - if (ex is Error) { - logger.shout( - "Failed to compress log file", - ex.toString(), - ex.stackTrace, - ); - } else { - logger.shout("Failed to compress log file", ex.toString()); - } - - logger.info( - "Sharing regular log file instead: ${entity.path}", - ); - final params = ShareParams( - text: name, - files: [XFile(entity.path, mimeType: 'text/plain')], - ); - - await SharePlus.instance.share(params); - } - }, - ), - ); - widgets.add(SizedBox(height: 8)); - } + widgets.add(SettingsLogsView(data: widget.data)); continue; } } @@ -1157,25 +428,28 @@ class _SettingsScreenState extends FirkaState { Widget build(BuildContext context) { var body = createWidgetTree(widget.items, widget.data.settings); - return DefaultAssetBundle( - bundle: FirkaBundle(), - child: Scaffold( - backgroundColor: appStyle.colors.background, - body: SafeArea( - child: SizedBox( - height: MediaQuery.of(context).size.height, - child: Stack( - children: [ - Padding( - padding: EdgeInsetsGeometry.all(20), - child: SingleChildScrollView( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: body, + return BlocProvider.value( + value: appIconPickerCubit, + child: DefaultAssetBundle( + bundle: FirkaBundle(), + child: Scaffold( + backgroundColor: appStyle.colors.background, + body: SafeArea( + child: SizedBox( + height: MediaQuery.of(context).size.height, + child: Stack( + children: [ + Padding( + padding: EdgeInsetsGeometry.all(20), + child: SingleChildScrollView( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: body, + ), ), ), - ), - ], + ], + ), ), ), ),