feat: refactor settings ui system

This commit is contained in:
2026-08-15 22:15:47 +02:00
parent 5a79c48e6d
commit 0b1313d0be
9 changed files with 941 additions and 784 deletions

View File

@@ -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<AppIconPickerState> {
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<void> save(List<String> 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(","),
}),
);
}
}

View File

@@ -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,
),

View File

@@ -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<TokenModel> 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<void>(
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, dynamic>;
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<Color>((
Set<WidgetState> states,
) {
return appStyle.colors.secondary;
}),
onChanged: (_) async {
setStateOuter(() {});
logger.finest('Settings saved');
},
),
],
),
),
onTap: () => _switchAccount(context, token),
);
}
Future<void> _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<void> _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');
}
}
}

View File

@@ -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<AppIconPickerCubit>().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<AppIconPickerCubit>();
final activeIcon = cubit.state.activeIcon;
final saving = cubit.state.saving;
List<Widget> 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<Widget> 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(),
);
},
),
],
),
],
);
}
}

View File

@@ -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(() {});
},
),
],
);
}

View File

@@ -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<List<LicenseEntry>>(
future: LicenseRegistry.licenses.toList(),
builder:
(BuildContext context, AsyncSnapshot<List<LicenseEntry>> snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(color: appStyle.colors.accent),
);
}
final licenses = snapshot.data!;
final shownPackages = <String>{};
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(),
);
},
);
}
}

View File

@@ -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<File>()
.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<void> _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);
}
}
}

View File

@@ -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<SettingsScreen> {
_SettingsScreenState();
bool settingAppIcon = false;
late String activeIcon;
late List<TokenModel> 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<SettingsScreen> {
: 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<Widget> createWidgetTree(
Iterable<SettingsUiNode> items,
SettingsRepository settings, {
@@ -327,7 +272,7 @@ class _SettingsScreenState extends FirkaState<SettingsScreen> {
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<SettingsScreen> {
continue;
}
if (item is SettingsUiLicensePage) {
widgets.add(
FutureBuilder<List<LicenseEntry>>(
future: LicenseRegistry.licenses.toList(),
builder:
(
BuildContext context,
AsyncSnapshot<List<LicenseEntry>> snapshot,
) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(
color: appStyle.colors.accent,
),
);
}
final licenses = snapshot.data!;
final shownPackages = <String>{};
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<Widget> 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<Widget> 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, dynamic>;
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<Color>((
Set<WidgetState> 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<void>(
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<SettingsScreen> {
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<SettingsScreen> {
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,
),
),
),
),
],
],
),
),
),
),