From f19d8cd3872a49969e2f4bdb9dda65a8d7667442 Mon Sep 17 00:00:00 2001 From: Armand <4831c0@proton.me> Date: Mon, 14 Sep 2026 22:14:25 +0200 Subject: [PATCH] feat(theming): share and import themes with qr codes --- .../android/app/src/main/AndroidManifest.xml | 1 + .../screens/themes/sheets/theme_sheets.dart | 790 ++++++++++++++++++ .../ui/phone/screens/themes/theme_screen.dart | 6 +- .../phone/screens/themes/themes_screen.dart | 29 +- .../ui/phone/screens/themes/user_theme.dart | 48 ++ .../screens/themes/widgets/theme_qr_card.dart | 156 ++++ firka/pubspec.yaml | 2 + firka/test/ui/theme_sharing_test.dart | 55 ++ .../lib/ui/theme/theme_binary_format.dart | 264 ++++++ .../test/theme_binary_format_test.dart | 132 +++ 10 files changed, 1478 insertions(+), 5 deletions(-) create mode 100644 firka/lib/ui/phone/screens/themes/widgets/theme_qr_card.dart create mode 100644 firka/test/ui/theme_sharing_test.dart create mode 100644 firka_common/lib/ui/theme/theme_binary_format.dart create mode 100644 firka_common/test/theme_binary_format_test.dart diff --git a/firka/android/app/src/main/AndroidManifest.xml b/firka/android/app/src/main/AndroidManifest.xml index eabc2407..3917118a 100644 --- a/firka/android/app/src/main/AndroidManifest.xml +++ b/firka/android/app/src/main/AndroidManifest.xml @@ -12,6 +12,7 @@ + showThemeNameSheet( BuildContext context, @@ -49,6 +62,783 @@ Future showThemeDeleteSheet( return result ?? false; } +String buildThemeShareUrl(UserTheme theme) => theme.shareUrl; + +Future showThemeShareSheet( + BuildContext context, { + required UserTheme theme, + required AppInitialization data, +}) { + return showModalBottomSheet( + context: context, + elevation: 100, + isScrollControlled: true, + enableDrag: true, + backgroundColor: Colors.transparent, + barrierColor: appStyle.colors.a15p, + builder: (context) { + return _ThemeShareSheet( + theme: theme, + shareUrl: theme.shareUrl, + l10n: data.l10n, + ); + }, + ); +} + +Future showThemeImportSheet( + BuildContext context, { + required AppInitialization data, + required Future Function(UserTheme theme) onImport, +}) { + return showModalBottomSheet( + context: context, + elevation: 100, + isScrollControlled: true, + enableDrag: true, + backgroundColor: Colors.transparent, + barrierColor: appStyle.colors.a15p, + builder: (context) { + return Padding( + padding: EdgeInsets.only( + bottom: MediaQuery.viewInsetsOf(context).bottom, + ), + child: _ThemeImportSheet( + l10n: data.l10n, + onImport: onImport, + ), + ); + }, + ); +} + +class _ThemeShareSheet extends StatefulWidget { + final UserTheme theme; + final String shareUrl; + final AppLocalizations l10n; + + const _ThemeShareSheet({ + required this.theme, + required this.shareUrl, + required this.l10n, + }); + + @override + State<_ThemeShareSheet> createState() => _ThemeShareSheetState(); +} + +class _ThemeShareSheetState extends State<_ThemeShareSheet> { + final GlobalKey _cardKey = GlobalKey(); + bool _copied = false; + bool _isSharing = false; + + Future _copy() async { + await Clipboard.setData(ClipboardData(text: widget.shareUrl)); + if (!mounted) return; + setState(() => _copied = true); + await Future.delayed(const Duration(seconds: 2)); + if (mounted) setState(() => _copied = false); + } + + Future _share() async { + if (_isSharing) return; + setState(() => _isSharing = true); + + try { + final boundary = _cardKey.currentContext?.findRenderObject() as RenderRepaintBoundary?; + if (boundary == null) { + throw Exception("RenderRepaintBoundary not found"); + } + + final image = await boundary.toImage(pixelRatio: 3.0); + final byteData = await image.toByteData(format: ui.ImageByteFormat.png); + if (byteData == null) { + throw Exception("Could not encode image to PNG"); + } + + final pngBytes = byteData.buffer.asUint8List(); + final tempDir = await getTemporaryDirectory(); + final sanitizedName = widget.theme.name.replaceAll(RegExp(r'[^\w\s-]'), '').trim(); + final safeName = sanitizedName.isEmpty ? 'firka' : sanitizedName; + final file = File('${tempDir.path}/firka_theme_$safeName.png'); + await file.writeAsBytes(pngBytes); + + await SharePlus.instance.share( + ShareParams( + files: [XFile(file.path)], + subject: widget.theme.name, + ), + ); + } catch (e) { + await SharePlus.instance.share( + ShareParams( + text: widget.shareUrl, + subject: widget.theme.name, + ), + ); + } finally { + if (mounted) { + setState(() => _isSharing = false); + } + } + } + + @override + Widget build(BuildContext context) { + return _ThemeSheetShell( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + RepaintBoundary( + key: _cardKey, + child: ThemeQrCard( + theme: widget.theme, + shareData: widget.shareUrl, + ), + ), + const SizedBox(height: 20), + _sheetButton( + label: _copied ? widget.l10n.copied : "Kód másolása", + color: appStyle.colors.accent, + onTap: _copy, + ), + const SizedBox(height: 8), + _sheetButton( + label: _isSharing ? "Kép generálása..." : "Megosztás", + color: appStyle.colors.buttonSecondaryFill, + onTap: _isSharing ? () {} : _share, + ), + const SizedBox(height: 8), + ], + ), + ); + } +} + +enum _ImportMode { camera, image, text } + +class _ThemeImportSheet extends StatefulWidget { + final AppLocalizations l10n; + final Future Function(UserTheme theme) onImport; + + const _ThemeImportSheet({ + required this.l10n, + required this.onImport, + }); + + @override + State<_ThemeImportSheet> createState() => _ThemeImportSheetState(); +} + +class _ThemeImportSheetState extends State<_ThemeImportSheet> { + _ImportMode _mode = _ImportMode.camera; + final _controller = TextEditingController(); + ThemeBinaryData? _previewData; + String? _extractedName; + String? _error; + bool _isAnalyzingImage = false; + + @override + void initState() { + super.initState(); + _controller.addListener(_onTextChanged); + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + bool _processImportString(String raw, {bool silent = false}) { + final trimmed = raw.trim(); + if (trimmed.isEmpty) return false; + + final payload = trimmed.parseThemeSharePayload(); + final decoded = payload.code.tryDecodeThemeData(); + + if (decoded != null) { + setState(() { + _controller.text = trimmed; + _previewData = decoded; + _extractedName = payload.name; + _error = null; + }); + return true; + } else { + if (!silent) { + setState(() { + _error = "Érvénytelen témakód"; + }); + } + return false; + } + } + + void _onTextChanged() { + final raw = _controller.text.trim(); + if (raw.isEmpty) { + setState(() { + _previewData = null; + _extractedName = null; + _error = null; + }); + return; + } + _processImportString(raw, silent: true); + } + + Future _paste() async { + final data = await Clipboard.getData(Clipboard.kTextPlain); + if (data?.text != null && data!.text!.isNotEmpty) { + _controller.text = data.text!; + _processImportString(data.text!); + } + } + + Future _pickImageAndScan() async { + setState(() { + _isAnalyzingImage = true; + _error = null; + }); + + try { + final picker = ImagePicker(); + final picked = await picker.pickImage(source: ImageSource.gallery); + if (picked == null) { + return; + } + + final capture = await MobileScannerPlatform.instance.analyzeImage(picked.path); + if (capture != null && capture.barcodes.isNotEmpty) { + bool found = false; + for (final barcode in capture.barcodes) { + final raw = barcode.rawValue; + if (raw != null && raw.isNotEmpty) { + if (_processImportString(raw)) { + found = true; + HapticFeedback.mediumImpact(); + break; + } + } + } + if (!found) { + setState(() { + _error = "A képen nem található érvényes téma QR kód."; + }); + } + } else { + setState(() { + _error = "Nem található QR kód a kiválasztott képen."; + }); + } + } catch (e) { + setState(() { + _error = "Hiba a kép beolvasásakor: $e"; + }); + } finally { + if (mounted) { + setState(() => _isAnalyzingImage = false); + } + } + } + + Future _import() async { + final preview = _previewData; + if (preview == null) return; + + final themeName = _extractedName != null && _extractedName!.isNotEmpty + ? _extractedName! + : widget.l10n.s_c_themes_imported_label; + + final List swatch; + if (preview.isFullTheme) { + swatch = [ + preview.lightSlot(ThemeColorSlot.accent) ?? appStyle.colors.accent, + preview.lightSlot(ThemeColorSlot.textPrimary) ?? appStyle.colors.textPrimary, + preview.lightSlot(ThemeColorSlot.background) ?? appStyle.colors.background, + ]; + } else { + swatch = preview.colors.length >= 3 + ? preview.colors.take(3).toList() + : (preview.colors.isNotEmpty + ? preview.colors + : [appStyle.colors.accent, appStyle.colors.textPrimary, appStyle.colors.background]); + } + + final theme = UserTheme( + id: Snowflake.nextId(), + name: themeName, + origin: ThemeOrigin.downloaded, + swatch: swatch, + ); + + await widget.onImport(theme); + if (!mounted) return; + context.pop(); + } + + Widget _modeTab({ + required String label, + required Object icon, + required bool selected, + required VoidCallback onTap, + }) { + return Expanded( + child: GestureDetector( + onTap: onTap, + behavior: HitTestBehavior.opaque, + child: AnimatedContainer( + duration: const Duration(milliseconds: 150), + padding: const EdgeInsets.symmetric(vertical: 10), + decoration: BoxDecoration( + color: selected + ? appStyle.colors.accent.withValues(alpha: 0.15) + : appStyle.colors.card, + borderRadius: BorderRadius.circular(16), + border: Border.all( + color: selected + ? appStyle.colors.accent + : Colors.transparent, + width: 1.5, + ), + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Majesticon( + icon as Uint8List, + color: selected + ? appStyle.colors.accent + : appStyle.colors.textSecondary, + size: 18, + ), + const SizedBox(width: 6), + Text( + label, + style: appStyle.fonts.B_12R.copyWith( + fontFamily: 'Figtree', + color: selected + ? appStyle.colors.accent + : appStyle.colors.textSecondary, + fontWeight: selected ? FontWeight.bold : FontWeight.w500, + ), + ), + ], + ), + ), + ), + ); + } + + @override + Widget build(BuildContext context) { + return _ThemeSheetShell( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + _sheetIcon(Majesticon.arrowDownCircleLine), + const SizedBox(height: 16), + Text( + widget.l10n.s_c_themes_import, + textAlign: TextAlign.center, + style: appStyle.fonts.H_H2.apply( + color: appStyle.colors.textPrimary, + ), + ), + const SizedBox(height: 16), + + if (_previewData != null) ...[ + Container( + width: double.infinity, + padding: const EdgeInsets.all(20), + decoration: BoxDecoration( + color: appStyle.colors.card, + borderRadius: BorderRadius.circular(20), + border: Border.all( + color: appStyle.colors.accent.withValues(alpha: 0.4), + width: 1.5, + ), + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + _extractedName != null && _extractedName!.isNotEmpty + ? _extractedName! + : widget.l10n.s_c_themes_imported_label, + textAlign: TextAlign.center, + style: TextStyle( + fontFamily: 'Figtree', + color: appStyle.colors.textPrimary, + fontSize: 18, + fontWeight: FontWeight.bold, + ), + ), + const SizedBox(height: 12), + Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + for (final color in (_previewData!.isFullTheme + ? [ + _previewData!.lightSlot(ThemeColorSlot.accent) ?? appStyle.colors.accent, + _previewData!.lightSlot(ThemeColorSlot.textPrimary) ?? appStyle.colors.textPrimary, + _previewData!.lightSlot(ThemeColorSlot.background) ?? appStyle.colors.background, + ] + : _previewData!.colors.take(4))) + Container( + margin: const EdgeInsets.symmetric(horizontal: 4), + width: 20, + height: 20, + decoration: BoxDecoration( + color: color, + shape: BoxShape.circle, + border: Border.all( + color: appStyle.colors.textPrimary.withValues(alpha: 0.25), + width: 1.5, + ), + ), + ), + ], + ), + const SizedBox(height: 8), + Text( + _previewData!.isFullTheme + ? "Teljes téma (32 szín)" + : "${_previewData!.colors.length} szín", + style: appStyle.fonts.B_12R.apply( + color: appStyle.colors.textSecondary, + ), + ), + ], + ), + ), + const SizedBox(height: 16), + _sheetButton( + label: widget.l10n.s_c_themes_import, + color: appStyle.colors.accent, + onTap: _import, + ), + const SizedBox(height: 8), + _sheetButton( + label: "Másik beolvasása", + color: appStyle.colors.buttonSecondaryFill, + onTap: () { + setState(() { + _previewData = null; + _extractedName = null; + _controller.clear(); + _error = null; + }); + }, + ), + const SizedBox(height: 8), + ] else ...[ + Row( + children: [ + _modeTab( + label: "Kamera", + icon: Majesticon.cameraLine, + selected: _mode == _ImportMode.camera, + onTap: () { + setState(() { + _mode = _ImportMode.camera; + _error = null; + }); + }, + ), + const SizedBox(width: 8), + _modeTab( + label: "Kép", + icon: Majesticon.imageLine, + selected: _mode == _ImportMode.image, + onTap: () { + setState(() { + _mode = _ImportMode.image; + _error = null; + }); + _pickImageAndScan(); + }, + ), + const SizedBox(width: 8), + _modeTab( + label: "Szöveg", + icon: Majesticon.textboxLine, + selected: _mode == _ImportMode.text, + onTap: () { + setState(() { + _mode = _ImportMode.text; + _error = null; + }); + }, + ), + ], + ), + const SizedBox(height: 16), + + if (_mode == _ImportMode.camera) ...[ + _CameraScannerView( + onScanned: (raw) { + if (_previewData != null) return; + if (_processImportString(raw)) { + HapticFeedback.mediumImpact(); + } + }, + ), + const SizedBox(height: 10), + Text( + "Irányítsd a kamerát egy téma QR kódra", + textAlign: TextAlign.center, + style: appStyle.fonts.B_12R.apply( + color: appStyle.colors.textSecondary, + ), + ), + ] else if (_mode == _ImportMode.image) ...[ + GestureDetector( + onTap: _isAnalyzingImage ? null : _pickImageAndScan, + child: Container( + width: double.infinity, + height: 180, + decoration: BoxDecoration( + color: appStyle.colors.card, + borderRadius: BorderRadius.circular(20), + border: Border.all( + color: appStyle.colors.accent.withValues(alpha: 0.3), + width: 1.5, + ), + ), + child: Center( + child: _isAnalyzingImage + ? Column( + mainAxisSize: MainAxisSize.min, + children: [ + CircularProgressIndicator( + color: appStyle.colors.accent, + ), + const SizedBox(height: 12), + Text( + "Kép elemzése...", + style: appStyle.fonts.B_14SB.apply( + color: appStyle.colors.textSecondary, + ), + ), + ], + ) + : Column( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: appStyle.colors.accent.withValues(alpha: 0.15), + shape: BoxShape.circle, + ), + child: Majesticon( + Majesticon.imageLine, + color: appStyle.colors.accent, + size: 32, + ), + ), + const SizedBox(height: 12), + Text( + "Koppints a kép kiválasztásához", + style: appStyle.fonts.B_14SB.apply( + color: appStyle.colors.textPrimary, + ), + ), + const SizedBox(height: 4), + Text( + "Válassz QR kódot tartalmazó képet a galériából", + style: appStyle.fonts.B_12R.apply( + color: appStyle.colors.textSecondary, + ), + ), + ], + ), + ), + ), + ), + ] else if (_mode == _ImportMode.text) ...[ + Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4), + decoration: BoxDecoration( + color: appStyle.colors.card, + borderRadius: BorderRadius.circular(24), + ), + child: Row( + children: [ + Expanded( + child: TextField( + controller: _controller, + textAlign: TextAlign.start, + textInputAction: TextInputAction.done, + cursorColor: appStyle.colors.accent, + style: appStyle.fonts.B_16R.apply( + color: appStyle.colors.textPrimary, + ), + decoration: InputDecoration( + hintText: "Témakód vagy link...", + hintStyle: appStyle.fonts.B_16R.apply( + color: appStyle.colors.textTertiary, + ), + border: InputBorder.none, + enabledBorder: InputBorder.none, + focusedBorder: InputBorder.none, + ), + ), + ), + IconButton( + icon: const Icon(Icons.paste, size: 18), + color: appStyle.colors.accent, + onPressed: _paste, + ), + ], + ), + ), + const SizedBox(height: 10), + _sheetButton( + label: "Beillesztés a vágólapról", + color: appStyle.colors.buttonSecondaryFill, + onTap: _paste, + ), + ], + + if (_error != null) ...[ + const SizedBox(height: 12), + Text( + _error!, + textAlign: TextAlign.center, + style: appStyle.fonts.B_14R.apply( + color: appStyle.colors.errorAccent, + ), + ), + ], + + const SizedBox(height: 12), + _sheetButton( + label: widget.l10n.cancel, + color: appStyle.colors.buttonSecondaryFill, + onTap: () => context.pop(), + ), + const SizedBox(height: 8), + ], + ], + ), + ); + } +} + +class _CameraScannerView extends StatefulWidget { + final ValueChanged onScanned; + + const _CameraScannerView({required this.onScanned}); + + @override + State<_CameraScannerView> createState() => _CameraScannerViewState(); +} + +class _CameraScannerViewState extends State<_CameraScannerView> { + final MobileScannerController _controller = MobileScannerController( + detectionSpeed: DetectionSpeed.normal, + facing: CameraFacing.back, + ); + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return ClipRRect( + borderRadius: BorderRadius.circular(20), + child: SizedBox( + height: 220, + width: double.infinity, + child: Stack( + alignment: Alignment.center, + children: [ + MobileScanner( + controller: _controller, + onDetect: (capture) { + for (final barcode in capture.barcodes) { + final raw = barcode.rawValue; + if (raw != null && raw.isNotEmpty) { + widget.onScanned(raw); + break; + } + } + }, + errorBuilder: (context, error) { + return Container( + color: appStyle.colors.card, + padding: const EdgeInsets.all(16), + child: Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Majesticon( + Majesticon.cameraOffLine, + color: appStyle.colors.textSecondary, + size: 32, + ), + const SizedBox(height: 8), + Text( + "Kamera nem elérhető", + textAlign: TextAlign.center, + style: appStyle.fonts.B_14SB.apply( + color: appStyle.colors.textPrimary, + ), + ), + const SizedBox(height: 4), + Text( + "Használd a Kép vagy Szöveg opciót.", + textAlign: TextAlign.center, + style: appStyle.fonts.B_12R.apply( + color: appStyle.colors.textSecondary, + ), + ), + ], + ), + ), + ); + }, + ), + Container( + width: 150, + height: 150, + decoration: BoxDecoration( + border: Border.all( + color: appStyle.colors.accent.withValues(alpha: 0.8), + width: 2, + ), + borderRadius: BorderRadius.circular(16), + ), + ), + Positioned( + top: 8, + right: 8, + child: IconButton( + icon: Majesticon( + Majesticon.lightningBoltSolid, + color: Colors.white, + size: 18, + ), + style: IconButton.styleFrom( + backgroundColor: Colors.black.withValues(alpha: 0.45), + ), + onPressed: () => _controller.toggleTorch(), + ), + ), + ], + ), + ), + ); + } +} + Future _showCenteredInputSheet({ required BuildContext context, required AppLocalizations l10n, diff --git a/firka/lib/ui/phone/screens/themes/theme_screen.dart b/firka/lib/ui/phone/screens/themes/theme_screen.dart index 704ca5d4..28702939 100644 --- a/firka/lib/ui/phone/screens/themes/theme_screen.dart +++ b/firka/lib/ui/phone/screens/themes/theme_screen.dart @@ -172,7 +172,11 @@ class _ThemeScreenState extends State { ), ), FirkaIconButton( - onTap: () {}, + onTap: () => showThemeShareSheet( + context, + theme: _theme, + data: widget.data, + ), child: FirkaIconWidget( FirkaIconType.majesticons, Majesticon.shareLine, diff --git a/firka/lib/ui/phone/screens/themes/themes_screen.dart b/firka/lib/ui/phone/screens/themes/themes_screen.dart index 22925aef..780e9494 100644 --- a/firka/lib/ui/phone/screens/themes/themes_screen.dart +++ b/firka/lib/ui/phone/screens/themes/themes_screen.dart @@ -143,6 +143,19 @@ class _ThemesScreenState extends State { await _openTheme(theme); } + Future _importTheme() async { + await showThemeImportSheet( + context, + data: widget.data, + onImport: (theme) async { + await _persistTheme(theme); + if (!mounted) return; + setState(() => _storedThemes.add(theme)); + await _openTheme(theme); + }, + ); + } + Future _renameTheme(UserTheme theme, String name) async { setState(() => theme.name = name); await _persistTheme(theme); @@ -303,7 +316,11 @@ class _ThemesScreenState extends State { ), ), FirkaIconButton( - onTap: () {}, + onTap: () => showThemeShareSheet( + context, + theme: _selected, + data: widget.data, + ), child: FirkaIconWidget( FirkaIconType.majesticons, Majesticon.shareLine, @@ -312,7 +329,7 @@ class _ThemesScreenState extends State { ), ), FirkaIconButton( - onTap: () {}, + onTap: _importTheme, child: FirkaIconWidget( FirkaIconType.majesticons, Majesticon.arrowDownCircleLine, @@ -335,7 +352,11 @@ class _ThemesScreenState extends State { _actionRow( icon: Majesticon.shareLine, label: l10n.s_c_themes_share_current, - onTap: () {}, + onTap: () => showThemeShareSheet( + context, + theme: _selected, + data: widget.data, + ), ), _sectionLabel(l10n.s_c_themes_own), _themeRow( @@ -361,7 +382,7 @@ class _ThemesScreenState extends State { _actionRow( icon: Majesticon.arrowDownCircleLine, label: l10n.s_c_themes_import, - onTap: () {}, + onTap: _importTheme, ), const SizedBox(height: 24), ], diff --git a/firka/lib/ui/phone/screens/themes/user_theme.dart b/firka/lib/ui/phone/screens/themes/user_theme.dart index 10a9bcf9..74cd5f03 100644 --- a/firka/lib/ui/phone/screens/themes/user_theme.dart +++ b/firka/lib/ui/phone/screens/themes/user_theme.dart @@ -3,6 +3,7 @@ import "package:flutter/material.dart"; import "package:firka_common/data/models/user_theme_model.dart"; import "package:firka_common/ui/theme/core_theme.dart"; import "package:firka_common/ui/theme/grade_theme.dart"; +import "package:firka_common/ui/theme/theme_binary_format.dart"; import "package:firka/ui/phone/screens/themes/builtin_theme_id.dart"; import "package:firka/ui/theme/style.dart"; @@ -95,3 +96,50 @@ class ThemeScreenArgs { required this.onChanged, }); } + +extension UserThemeShareExtension on UserTheme { + String get shareCode { + if (isBuiltin) { + final core = resolveCore(id); + return ThemeBinaryFormat.encodeToBase64( + ThemeBinaryFormat.decode(ThemeBinaryFormat.encodeCoreTheme(core)).colors, + ); + } else if (swatch.isNotEmpty) { + return ThemeBinaryFormat.encodeToBase64(swatch); + } else { + return ThemeBinaryFormat.encodeToBase64([ + appStyle.colors.accent, + appStyle.colors.textPrimary, + appStyle.colors.background, + ]); + } + } + + String get shareUrl => + "https://firka.app/?d=$shareCode&n=${Uri.encodeComponent(name)}"; +} + +extension ThemeShareCodeStringExtension on String { + ({String code, String? name}) parseThemeSharePayload() { + final trimmed = trim(); + if (trimmed.startsWith('firka://') || trimmed.startsWith('http')) { + final uri = Uri.tryParse(trimmed); + if (uri != null) { + return ( + code: uri.queryParameters['d'] ?? trimmed, + name: uri.queryParameters['n'], + ); + } + } + return (code: trimmed, name: null); + } + + ThemeBinaryData? tryDecodeThemeData() { + try { + final payload = parseThemeSharePayload(); + return ThemeBinaryFormat.decodeFromBase64(payload.code); + } catch (_) { + return null; + } + } +} diff --git a/firka/lib/ui/phone/screens/themes/widgets/theme_qr_card.dart b/firka/lib/ui/phone/screens/themes/widgets/theme_qr_card.dart new file mode 100644 index 00000000..314ea86b --- /dev/null +++ b/firka/lib/ui/phone/screens/themes/widgets/theme_qr_card.dart @@ -0,0 +1,156 @@ +import 'package:flutter/material.dart'; +import 'package:qr_flutter/qr_flutter.dart'; + +import 'package:firka/ui/phone/screens/themes/user_theme.dart'; +import 'package:firka/ui/shared/dave_mascot.dart'; +import 'package:firka/ui/theme/style.dart'; + +class ThemeQrCard extends StatelessWidget { + final UserTheme theme; + final String shareData; + final double qrSize; + + const ThemeQrCard({ + super.key, + required this.theme, + required this.shareData, + this.qrSize = 180, + }); + + @override + Widget build(BuildContext context) { + // Theme colors extracted from swatch or current active theme + final accentColor = theme.swatch.isNotEmpty + ? theme.swatch[0] + : appStyle.colors.accent; + final textColor = theme.swatch.length > 1 + ? theme.swatch[1] + : appStyle.colors.textPrimary; + final cardBgColor = theme.swatch.length > 2 + ? theme.swatch[2] + : appStyle.colors.card; + + // Determine contrast: if cardBgColor is dark, use light for QR dots; if light, use dark + final brightness = ThemeData.estimateBrightnessForColor(cardBgColor); + final qrDotColor = brightness == Brightness.dark + ? (textColor.computeLuminance() > 0.4 ? textColor : Colors.white) + : (textColor.computeLuminance() < 0.6 ? textColor : Colors.black87); + + return Container( + width: 270, + padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 16), + decoration: BoxDecoration( + color: cardBgColor, + borderRadius: BorderRadius.circular(24), + border: Border.all( + color: accentColor.withValues(alpha: 0.3), + width: 1.5, + ), + boxShadow: [ + BoxShadow( + color: Colors.black.withValues(alpha: 0.2), + blurRadius: 16, + offset: const Offset(0, 6), + ), + ], + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + // QR Code with Dave Mascot in the Center + Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: cardBgColor, + borderRadius: BorderRadius.circular(16), + border: Border.all( + color: accentColor.withValues(alpha: 0.2), + width: 1, + ), + ), + child: SizedBox( + width: qrSize, + height: qrSize, + child: Stack( + alignment: Alignment.center, + children: [ + QrImageView( + data: shareData, + version: QrVersions.auto, + errorCorrectionLevel: QrErrorCorrectLevel.H, + size: qrSize, + padding: EdgeInsets.zero, + eyeStyle: QrEyeStyle( + eyeShape: QrEyeShape.circle, + color: accentColor, + ), + dataModuleStyle: QrDataModuleStyle( + dataModuleShape: QrDataModuleShape.circle, + color: qrDotColor, + ), + backgroundColor: Colors.transparent, + ), + // Dave Mascot Badge in center of QR + Container( + width: 44, + height: 44, + decoration: BoxDecoration( + color: cardBgColor, + shape: BoxShape.circle, + border: Border.all( + color: accentColor.withValues(alpha: 0.5), + width: 2, + ), + boxShadow: [ + BoxShadow( + color: Colors.black.withValues(alpha: 0.25), + blurRadius: 6, + ), + ], + ), + child: Center( + child: DaveMascot( + width: 28, + height: 28, + color: accentColor, + ), + ), + ), + ], + ), + ), + ), + const SizedBox(height: 16), + + // Theme Name Label + Text( + theme.name, + textAlign: TextAlign.center, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontFamily: 'Figtree', + color: textColor, + fontSize: 20, + fontWeight: FontWeight.bold, + ), + ), + const SizedBox(height: 4), + + // https://firka.app below theme name + Text( + "https://firka.app", + textAlign: TextAlign.center, + style: TextStyle( + fontFamily: 'Figtree', + color: accentColor, + fontSize: 13, + fontWeight: FontWeight.w600, + letterSpacing: 0.5, + ), + ), + ], + ), + ); + } +} diff --git a/firka/pubspec.yaml b/firka/pubspec.yaml index 008cde33..03010b1f 100644 --- a/firka/pubspec.yaml +++ b/firka/pubspec.yaml @@ -63,6 +63,8 @@ dependencies: flutter_bloc: ^9.0.0 vibration: ^3.1.8 dynamic_color: ^2.1.0 + qr_flutter: ^4.1.0 + mobile_scanner: ^7.4.1 dev_dependencies: flutter_test: diff --git a/firka/test/ui/theme_sharing_test.dart b/firka/test/ui/theme_sharing_test.dart new file mode 100644 index 00000000..96fcc4b6 --- /dev/null +++ b/firka/test/ui/theme_sharing_test.dart @@ -0,0 +1,55 @@ +import 'package:firka/ui/phone/screens/themes/user_theme.dart'; +import 'package:firka/ui/phone/screens/themes/widgets/theme_qr_card.dart'; +import 'package:firka_common/ui/theme/core_theme.dart'; +import 'package:firka_common/ui/theme/theme_binary_format.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('Theme sharing binary format in firka', () { + test('encode and decode URL-safe base64 string for firkaCore', () { + final bytes = ThemeBinaryFormat.encodeCoreTheme(firkaCore); + final b64 = ThemeBinaryFormat.toBase64(bytes); + expect(b64.isNotEmpty, isTrue); + + final decodedBytes = ThemeBinaryFormat.fromBase64(b64); + final decoded = ThemeBinaryFormat.decode(decodedBytes); + final slots = decoded.toThemeSlots(); + expect(slots.light[ThemeColorSlot.background], firkaCore.light.background); + expect(slots.dark[ThemeColorSlot.background], firkaCore.dark.background); + expect(slots.light[ThemeColorSlot.accent], firkaCore.light.accent); + expect(slots.dark[ThemeColorSlot.accent], firkaCore.dark.accent); + }); + + testWidgets('ThemeQrCard renders theme name and QR code', (tester) async { + final bytes = ThemeBinaryFormat.encodeCoreTheme(firkaCore); + final b64 = ThemeBinaryFormat.toBase64(bytes); + final userTheme = UserTheme( + id: 'test_theme', + name: 'Firka Green', + origin: ThemeOrigin.own, + swatch: const [ + Color(0xFFA7DC22), + Colors.white, + Color(0xFF1E1E1E), + ], + ); + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Center( + child: ThemeQrCard( + theme: userTheme, + shareData: b64, + ), + ), + ), + ), + ); + + expect(find.text('Firka Green'), findsOneWidget); + expect(find.text('https://firka.app'), findsOneWidget); + }); + }); +} diff --git a/firka_common/lib/ui/theme/theme_binary_format.dart b/firka_common/lib/ui/theme/theme_binary_format.dart new file mode 100644 index 00000000..b6e6fc1d --- /dev/null +++ b/firka_common/lib/ui/theme/theme_binary_format.dart @@ -0,0 +1,264 @@ +import 'dart:convert'; +import 'dart:typed_data'; +import 'package:flutter/material.dart'; +import 'package:firka_common/ui/theme/core_theme.dart'; + +/// The 16 customizable color slots of a Firka theme. +enum ThemeColorSlot { + accent, + background, + card, + button, + secondary, + textPrimary, + textSecondary, + textTertiary, + shadowColor, + success, + warningAccent, + warningText, + warningCard, + errorAccent, + errorText, + errorCard, +} + +/// Decoded theme binary data. +class ThemeBinaryData { + /// Format version (e.g. 0). + final int version; + + /// Ordered list of colors stored as raw bytes. + final List colors; + + const ThemeBinaryData({ + required this.version, + required this.colors, + }); + + /// True if the payload contains both light (0..15) and dark (16..31) slots. + bool get isFullTheme => colors.length >= 32; + + /// Retrieves the color for [slot] in light mode, or null if out of range. + Color? lightSlot(ThemeColorSlot slot) { + final idx = slot.index; + return idx < colors.length ? colors[idx] : null; + } + + /// Retrieves the color for [slot] in dark mode, or null if out of range. + Color? darkSlot(ThemeColorSlot slot) { + final idx = 16 + slot.index; + return idx < colors.length ? colors[idx] : null; + } + + /// Extracts the full theme mapping for light and dark modes. + ({Map light, Map dark}) toThemeSlots() { + final lightMap = {}; + final darkMap = {}; + + for (final slot in ThemeColorSlot.values) { + final lColor = lightSlot(slot); + if (lColor != null) lightMap[slot] = lColor; + + final dColor = darkSlot(slot) ?? lColor; + if (dColor != null) darkMap[slot] = dColor; + } + + return (light: lightMap, dark: darkMap); + } + + @override + String toString() => + 'ThemeBinaryData(version: $version, colors: ${colors.length})'; +} + +/// Binary encoder and decoder for Firka themes. +/// +/// Format specification: +/// 1. Header: Varint storing the format version (e.g. `0x00` for version 0). +/// 2. Colors: Raw 32-bit ARGB bytes (4 bytes per color: Alpha, Red, Green, Blue). +class ThemeBinaryFormat { + /// Current binary format version. + static const int currentVersion = 0; + + /// Encodes [value] into a standard unsigned LEB128 varint. + static void writeVarint(BytesBuilder builder, int value) { + if (value < 0) { + throw ArgumentError.value(value, 'value', 'Varint must be non-negative'); + } + var v = value; + while (v >= 0x80) { + builder.addByte((v & 0x7F) | 0x80); + v >>= 7; + } + builder.addByte(v & 0x7F); + } + + /// Reads a standard unsigned LEB128 varint from [bytes] starting at [offset]. + /// Returns a record of `(value, bytesRead)`. + static (int value, int bytesRead) readVarint(Uint8List bytes, [int offset = 0]) { + var result = 0; + var shift = 0; + var index = offset; + + while (index < bytes.length) { + final byte = bytes[index++]; + result |= (byte & 0x7F) << shift; + if ((byte & 0x80) == 0) { + return (result, index - offset); + } + shift += 7; + if (shift >= 64) { + throw const FormatException('Varint overflow'); + } + } + throw const FormatException('Unexpected end of buffer while reading varint'); + } + + /// Encodes a list of [colors] into the binary theme format. + /// + /// Prepends [version] as a varint (default 0), followed by 4 raw bytes per + /// color in 32-bit ARGB order (Alpha, Red, Green, Blue). + static Uint8List encode({ + required List colors, + int version = currentVersion, + }) { + final builder = BytesBuilder(copy: false); + + // 1. Version as varint + writeVarint(builder, version); + + // 2. Colors as raw bytes (4 bytes each: A, R, G, B) + for (final color in colors) { + final argb = color.toARGB32(); + builder.addByte((argb >> 24) & 0xFF); + builder.addByte((argb >> 16) & 0xFF); + builder.addByte((argb >> 8) & 0xFF); + builder.addByte(argb & 0xFF); + } + + return builder.takeBytes(); + } + + /// Decodes raw binary theme [bytes]. + /// + /// Reads the leading varint version and parses the subsequent raw bytes as + /// 32-bit ARGB colors (4 bytes per color). + static ThemeBinaryData decode(Uint8List bytes) { + if (bytes.isEmpty) { + throw const FormatException('Cannot decode empty theme bytes'); + } + + // 1. Read version varint + final (version, headerLength) = readVarint(bytes, 0); + + final colorByteLength = bytes.length - headerLength; + if (colorByteLength % 4 != 0) { + throw FormatException( + 'Invalid color byte length ($colorByteLength). ' + 'Color bytes must be a multiple of 4.', + ); + } + + final colorCount = colorByteLength ~/ 4; + final colors = []; + + for (var i = 0; i < colorCount; i++) { + final offset = headerLength + (i * 4); + final a = bytes[offset]; + final r = bytes[offset + 1]; + final g = bytes[offset + 2]; + final b = bytes[offset + 3]; + colors.add(Color.fromARGB(a, r, g, b)); + } + + return ThemeBinaryData(version: version, colors: colors); + } + + /// Encodes a complete 32-color Firka theme (16 light slots + 16 dark slots). + static Uint8List encodeFullTheme({ + required Map light, + required Map dark, + int version = currentVersion, + }) { + final colors = []; + + // Light slots (0..15) + for (final slot in ThemeColorSlot.values) { + colors.add(light[slot] ?? Colors.transparent); + } + + // Dark slots (16..31) + for (final slot in ThemeColorSlot.values) { + colors.add(dark[slot] ?? light[slot] ?? Colors.transparent); + } + + return encode(colors: colors, version: version); + } + + /// Encodes a [CoreTheme] (both light and dark colors) into binary. + static Uint8List encodeCoreTheme( + CoreTheme theme, { + int version = currentVersion, + }) { + Color getSlot(CoreThemeColors c, ThemeColorSlot slot) => switch (slot) { + ThemeColorSlot.accent => c.accent, + ThemeColorSlot.background => c.background, + ThemeColorSlot.card => c.card, + ThemeColorSlot.button => c.buttonSecondaryFill, + ThemeColorSlot.secondary => c.secondary, + ThemeColorSlot.textPrimary => c.textPrimary, + ThemeColorSlot.textSecondary => c.textSecondary, + ThemeColorSlot.textTertiary => c.textTertiary, + ThemeColorSlot.shadowColor => c.shadowColor, + ThemeColorSlot.success => c.success, + ThemeColorSlot.warningAccent => c.warningAccent, + ThemeColorSlot.warningText => c.warningText, + ThemeColorSlot.warningCard => c.warningCard, + ThemeColorSlot.errorAccent => c.errorAccent, + ThemeColorSlot.errorText => c.errorText, + ThemeColorSlot.errorCard => c.errorCard, + }; + + final lightMap = { + for (final slot in ThemeColorSlot.values) slot: getSlot(theme.light, slot), + }; + final darkMap = { + for (final slot in ThemeColorSlot.values) slot: getSlot(theme.dark, slot), + }; + + return encodeFullTheme(light: lightMap, dark: darkMap, version: version); + } + + /// Encodes [bytes] to Base64 (URL-safe without padding by default). + static String toBase64(Uint8List bytes, {bool urlSafe = true}) { + final b64 = urlSafe ? base64UrlEncode(bytes) : base64Encode(bytes); + return urlSafe ? b64.replaceAll('=', '') : b64; + } + + /// Decodes a Base64 or URL-safe Base64 string into binary theme bytes. + static Uint8List fromBase64(String encoded) { + var normalized = encoded.trim(); + final mod = normalized.length % 4; + if (mod != 0) { + normalized += '=' * (4 - mod); + } + return base64Url.decode(normalized); + } + + /// Convenience method: Encodes [colors] directly into a URL-safe Base64 string. + static String encodeToBase64( + List colors, { + int version = currentVersion, + bool urlSafe = true, + }) { + final bytes = encode(colors: colors, version: version); + return toBase64(bytes, urlSafe: urlSafe); + } + + /// Convenience method: Decodes a URL-safe Base64 string into [ThemeBinaryData]. + static ThemeBinaryData decodeFromBase64(String encoded) { + final bytes = fromBase64(encoded); + return decode(bytes); + } +} diff --git a/firka_common/test/theme_binary_format_test.dart b/firka_common/test/theme_binary_format_test.dart new file mode 100644 index 00000000..2bfe4f9a --- /dev/null +++ b/firka_common/test/theme_binary_format_test.dart @@ -0,0 +1,132 @@ +import 'dart:typed_data'; +import 'package:firka_common/ui/theme/core_theme.dart'; +import 'package:firka_common/ui/theme/theme_binary_format.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('ThemeBinaryFormat varint tests', () { + test('encodes and decodes 0 (version 0) as a single byte 0x00', () { + final builder = BytesBuilder(); + ThemeBinaryFormat.writeVarint(builder, 0); + final bytes = builder.takeBytes(); + + expect(bytes.length, 1); + expect(bytes[0], 0x00); + + final (value, bytesRead) = ThemeBinaryFormat.readVarint(bytes, 0); + expect(value, 0); + expect(bytesRead, 1); + }); + + test('encodes and decodes multi-byte varints', () { + for (final testVal in [1, 63, 127, 128, 255, 300, 16384, 2097151]) { + final builder = BytesBuilder(); + ThemeBinaryFormat.writeVarint(builder, testVal); + final bytes = builder.takeBytes(); + + final (decoded, bytesRead) = ThemeBinaryFormat.readVarint(bytes, 0); + expect(decoded, testVal); + expect(bytesRead, bytes.length); + } + }); + + test('throws on negative varint', () { + final builder = BytesBuilder(); + expect(() => ThemeBinaryFormat.writeVarint(builder, -1), throwsArgumentError); + }); + }); + + group('ThemeBinaryFormat color encoding', () { + test('encodes empty list as only version varint', () { + final bytes = ThemeBinaryFormat.encode(colors: []); + expect(bytes, equals([0x00])); + + final decoded = ThemeBinaryFormat.decode(bytes); + expect(decoded.version, 0); + expect(decoded.colors, isEmpty); + }); + + test('stores colors as 4 raw ARGB bytes following version 0', () { + const red = Color(0xFFFF0000); + const semiGreen = Color(0x8000FF00); + + final bytes = ThemeBinaryFormat.encode(colors: [red, semiGreen]); + + expect(bytes[0], 0x00); + expect(bytes.sublist(1, 5), equals([0xFF, 0xFF, 0x00, 0x00])); + expect(bytes.sublist(5, 9), equals([0x80, 0x00, 0xFF, 0x00])); + expect(bytes.length, 9); + + final decoded = ThemeBinaryFormat.decode(bytes); + expect(decoded.version, 0); + expect(decoded.colors.length, 2); + expect(decoded.colors[0], red); + expect(decoded.colors[1], semiGreen); + }); + + test('round-trips full theme (32 colors)', () { + final lightMap = { + for (final slot in ThemeColorSlot.values) + slot: Color((0xFF000000 + slot.index * 0x0F0F0F) & 0xFFFFFFFF), + }; + final darkMap = { + for (final slot in ThemeColorSlot.values) + slot: Color((0xFF111111 + slot.index * 0x0E0E0E) & 0xFFFFFFFF), + }; + + final bytes = ThemeBinaryFormat.encodeFullTheme( + light: lightMap, + dark: darkMap, + ); + + expect(bytes.length, 129); + expect(bytes[0], 0x00); + + final decoded = ThemeBinaryFormat.decode(bytes); + expect(decoded.version, 0); + expect(decoded.isFullTheme, isTrue); + + final slots = decoded.toThemeSlots(); + for (final slot in ThemeColorSlot.values) { + expect(slots.light[slot], lightMap[slot]); + expect(slots.dark[slot], darkMap[slot]); + } + }); + + test('round-trips CoreTheme (firkaCore)', () { + final bytes = ThemeBinaryFormat.encodeCoreTheme(firkaCore); + expect(bytes.length, 129); + + final decoded = ThemeBinaryFormat.decode(bytes); + expect(decoded.version, 0); + + final slots = decoded.toThemeSlots(); + expect(slots.light[ThemeColorSlot.accent], firkaCore.light.accent); + expect(slots.light[ThemeColorSlot.background], firkaCore.light.background); + expect(slots.dark[ThemeColorSlot.accent], firkaCore.dark.accent); + expect(slots.dark[ThemeColorSlot.background], firkaCore.dark.background); + }); + + test('throws on malformed binary data', () { + expect(() => ThemeBinaryFormat.decode(Uint8List(0)), throwsFormatException); + expect( + () => ThemeBinaryFormat.decode(Uint8List.fromList([0x00, 0xFF, 0x00, 0x00])), + throwsFormatException, + ); + }); + + test('Base64 and URL-safe serialization', () { + final colors = [const Color(0xFFA7DC22), const Color(0xFFFAFFF0)]; + final b64 = ThemeBinaryFormat.encodeToBase64(colors); + + expect(b64.contains('/'), isFalse); + expect(b64.contains('+'), isFalse); + expect(b64.contains('='), isFalse); + + final decoded = ThemeBinaryFormat.decodeFromBase64(b64); + expect(decoded.version, 0); + expect(decoded.colors, equals(colors)); + }); + }); +}