1
0
forked from firka/firka

1 Commits

Author SHA1 Message Date
zypherift
25f303e1e9 feat(themes): keep themes per account and keep shared ones live
A theme now follows the account rather than the install: it is pulled
on login and when the theme list opens, and every edit is pushed back,
so signing in elsewhere brings the theme along.

Sharing no longer hands over a dead snapshot. The link carries the
whole theme so it still imports with no network, plus a share id the
copy refetches by, which is how an edit by the owner reaches everyone
who scanned the code. Imported themes catch up on app open.

The editor's per-slot settings lookup moved to theme_palette, where
the share format already needed the same mapping.
2026-11-29 01:10:12 +01:00
19 changed files with 1358 additions and 623 deletions

View File

@@ -1,5 +1,6 @@
import "package:firka/app/app_state.dart"; import "package:firka/app/app_state.dart";
import "package:firka/app/initialization.dart"; import "package:firka/app/initialization.dart";
import "package:firka/core/theme_sync.dart";
import "package:firka/services/notification_delivery_service.dart"; import "package:firka/services/notification_delivery_service.dart";
import "package:firka_common/data/models/token_model.dart"; import "package:firka_common/data/models/token_model.dart";
import "package:kreta_api/kreta_api.dart"; import "package:kreta_api/kreta_api.dart";
@@ -17,9 +18,10 @@ Future<void> completeLogin(
await data.settings.setSelectedAccountKey(tokenModel.key); await data.settings.setSelectedAccountKey(tokenModel.key);
await initializeApp(); await initializeApp();
// this account may already have a theme stored server side
await syncThemeFromServer(data.settings);
if (data.client != null) { if (data.client != null) {
await NotificationDeliveryService.onUserLogin( await NotificationDeliveryService.onUserLogin(client: data.client!);
client: data.client!,
);
} }
} }

View File

@@ -0,0 +1,75 @@
import 'package:dio/dio.dart';
import 'package:firka/app/app_state.dart';
const _base = 'https://api.firka.app/v1';
Options _options(String? writeKey) => Options(
contentType: Headers.jsonContentType,
receiveTimeout: const Duration(seconds: 10),
sendTimeout: const Duration(seconds: 10),
headers: writeKey == null ? null : {'X-Theme-Key': writeKey},
);
/// the owner's own copy, by vault. null when nothing is stored yet.
Future<({String code, String name, String shareId})?> fetchTheme(
String vault,
) async {
try {
final res = await dio.get(
'$_base/theme-sync/$vault',
options: _options(null),
);
final data = res.data as Map<String, dynamic>;
return (
code: data['code'] as String,
name: (data['name'] as String?) ?? '',
shareId: (data['share_id'] as String?) ?? '',
);
} on DioException catch (e) {
if (e.response?.statusCode == 404) return null;
rethrow;
}
}
/// what a share link points at right now. null when the link is dead.
Future<({String code, String name})?> fetchSharedTheme(String shareId) async {
try {
final res = await dio.get(
'$_base/theme-share/$shareId',
options: _options(null),
);
final data = res.data as Map<String, dynamic>;
return (
code: data['code'] as String,
name: (data['name'] as String?) ?? '',
);
} on DioException catch (e) {
if (e.response?.statusCode == 404) return null;
rethrow;
}
}
/// stores the theme under the vault. the write key claims the vault on the
/// first push and proves ownership on every later one.
Future<void> pushTheme(
String vault, {
required String writeKey,
required String code,
required String name,
}) async {
await dio.put(
'$_base/theme-sync/$vault',
data: {'code': code, 'name': name},
options: _options(writeKey),
);
}
/// publishes the theme and returns its public, read-only share id
Future<String> shareTheme(String vault, {required String writeKey}) async {
final res = await dio.post(
'$_base/theme-sync/$vault/share',
options: _options(writeKey),
);
return (res.data as Map<String, dynamic>)['share_id'] as String;
}

View File

@@ -25,13 +25,13 @@ import 'package:firka/ui/phone/screens/themes/builtin_theme_id.dart';
import 'package:firka/ui/theme/style.dart'; import 'package:firka/ui/theme/style.dart';
import 'package:firka_common/ui/theme/core_theme.dart'; import 'package:firka_common/ui/theme/core_theme.dart';
import 'package:intl/intl.dart'; import 'package:intl/intl.dart';
import 'package:firka/core/theme_sync.dart';
import 'package:logging/logging.dart'; import 'package:logging/logging.dart';
import 'package:path/path.dart' as p; import 'package:path/path.dart' as p;
import 'package:isar_community/isar.dart'; import 'package:isar_community/isar.dart';
import 'package:package_info_plus/package_info_plus.dart'; import 'package:package_info_plus/package_info_plus.dart';
import 'package:path_provider/path_provider.dart'; import 'package:path_provider/path_provider.dart';
Future<void> initLang(AppInitialization data) async { Future<void> initLang(AppInitialization data) async {
switch (Settings.language.value) { switch (Settings.language.value) {
case AppLanguage.hu: case AppLanguage.hu:
@@ -143,7 +143,8 @@ void _applyCustomColors(
colors.a10p = colors.accent.withAlpha(0x1a); colors.a10p = colors.accent.withAlpha(0x1a);
colors.a15p = colors.accent.withAlpha(0x26); colors.a15p = colors.accent.withAlpha(0x26);
final bgGrad = (isLight final bgGrad =
(isLight
? Settings.customBackgroundGradientLight ? Settings.customBackgroundGradientLight
: Settings.customBackgroundGradientDark) : Settings.customBackgroundGradientDark)
.value .value
@@ -164,9 +165,7 @@ void _applyCustomColors(
colors.background0p = colors.background.withAlpha(0); colors.background0p = colors.background.withAlpha(0);
colors.card = colors.card =
(isLight (isLight ? Settings.customCardColorLight : Settings.customCardColorDark)
? Settings.customCardColorLight
: Settings.customCardColorDark)
.value .value
.toColorFromHexSetting(); .toColorFromHexSetting();
colors.cardTranslucent = colors.card.withAlpha(0x80); colors.cardTranslucent = colors.card.withAlpha(0x80);
@@ -199,9 +198,11 @@ void _applyCustomColors(
final customSecLight = Settings.customTextSecondaryColorLight.value; final customSecLight = Settings.customTextSecondaryColorLight.value;
final customSecDark = Settings.customTextSecondaryColorDark.value; final customSecDark = Settings.customTextSecondaryColorDark.value;
final isCustomSecLight = customSecLight != final isCustomSecLight =
customSecLight !=
SettingsRegistry.customTextSecondaryColorLight.defaultValue; SettingsRegistry.customTextSecondaryColorLight.defaultValue;
final isCustomSecDark = customSecDark != final isCustomSecDark =
customSecDark !=
SettingsRegistry.customTextSecondaryColorDark.defaultValue; SettingsRegistry.customTextSecondaryColorDark.defaultValue;
colors.textSecondary = isLight colors.textSecondary = isLight
@@ -218,9 +219,11 @@ void _applyCustomColors(
final customTertLight = Settings.customTextTertiaryColorLight.value; final customTertLight = Settings.customTextTertiaryColorLight.value;
final customTertDark = Settings.customTextTertiaryColorDark.value; final customTertDark = Settings.customTextTertiaryColorDark.value;
final isCustomTertLight = customTertLight != final isCustomTertLight =
customTertLight !=
SettingsRegistry.customTextTertiaryColorLight.defaultValue; SettingsRegistry.customTextTertiaryColorLight.defaultValue;
final isCustomTertDark = customTertDark != final isCustomTertDark =
customTertDark !=
SettingsRegistry.customTextTertiaryColorDark.defaultValue; SettingsRegistry.customTextTertiaryColorDark.defaultValue;
colors.textTertiary = isLight colors.textTertiary = isLight
@@ -369,6 +372,9 @@ Future<void> _initData(AppInitialization init) async {
return; return;
} }
// the owner of a shared theme keeps editing it, so catch up on app open
unawaited(refreshSharedThemes(init.settings));
// _initData reruns on ordinary resumes too (Android can recreate the // _initData reruns on ordinary resumes too (Android can recreate the
// Activity/engine without a real config change), and used to always // Activity/engine without a real config change), and used to always
// build a fresh KretaClient — discarding its in-flight guards and // build a fresh KretaClient — discarding its in-flight guards and

View File

@@ -8,6 +8,7 @@ import "package:firka/services/fcm_service.dart";
import "package:firka/services/notification_delivery_service.dart"; import "package:firka/services/notification_delivery_service.dart";
import "package:firka/services/progress_notification_service.dart"; import "package:firka/services/progress_notification_service.dart";
import "package:firka/services/wear_sync_helper.dart"; import "package:firka/services/wear_sync_helper.dart";
import "package:firka/core/theme_palette.dart";
import "package:firka/ui/phone/screens/themes/builtin_theme_id.dart"; import "package:firka/ui/phone/screens/themes/builtin_theme_id.dart";
import "package:firka_common/ui/theme/core_theme.dart"; import "package:firka_common/ui/theme/core_theme.dart";
@@ -73,6 +74,8 @@ void registerSettingsEffects(
initTheme(initData); initTheme(initData);
initData.themeCubit.refresh(); initData.themeCubit.refresh();
initData.homeRefreshCubit.requestRefresh(); initData.homeRefreshCubit.requestRefresh();
// persist the new colors into the selected user theme
scheduleActiveThemeSave(repo);
} }
for (final setting in [ for (final setting in [

View File

@@ -0,0 +1,191 @@
import 'dart:async';
import 'package:firka/core/extensions.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/theme_sync.dart';
import 'package:firka/ui/phone/screens/themes/builtin_theme_id.dart';
import 'package:firka/ui/phone/screens/themes/user_theme.dart';
import 'package:firka_common/data/database.dart';
import 'package:firka_common/data/models/user_theme_model.dart';
import 'package:firka_common/ui/theme/theme_binary_format.dart';
import 'package:flutter/painting.dart';
/// the settings that hold a slot's light and dark color
(StringSetting, StringSetting) themeSlotSettings(ThemeColorSlot slot) {
switch (slot) {
case ThemeColorSlot.accent:
return (
SettingsRegistry.customAccentColorLight,
SettingsRegistry.customAccentColorDark,
);
case ThemeColorSlot.background:
return (
SettingsRegistry.customBackgroundColorLight,
SettingsRegistry.customBackgroundColorDark,
);
case ThemeColorSlot.card:
return (
SettingsRegistry.customCardColorLight,
SettingsRegistry.customCardColorDark,
);
case ThemeColorSlot.button:
return (
SettingsRegistry.customButtonColorLight,
SettingsRegistry.customButtonColorDark,
);
case ThemeColorSlot.secondary:
return (
SettingsRegistry.customSecondaryColorLight,
SettingsRegistry.customSecondaryColorDark,
);
case ThemeColorSlot.textPrimary:
return (
SettingsRegistry.customTextColorLight,
SettingsRegistry.customTextColorDark,
);
case ThemeColorSlot.textSecondary:
return (
SettingsRegistry.customTextSecondaryColorLight,
SettingsRegistry.customTextSecondaryColorDark,
);
case ThemeColorSlot.textTertiary:
return (
SettingsRegistry.customTextTertiaryColorLight,
SettingsRegistry.customTextTertiaryColorDark,
);
case ThemeColorSlot.shadowColor:
return (
SettingsRegistry.customShadowColorLight,
SettingsRegistry.customShadowColorDark,
);
case ThemeColorSlot.success:
return (
SettingsRegistry.customSuccessColorLight,
SettingsRegistry.customSuccessColorDark,
);
case ThemeColorSlot.warningAccent:
return (
SettingsRegistry.customWarningAccentColorLight,
SettingsRegistry.customWarningAccentColorDark,
);
case ThemeColorSlot.warningText:
return (
SettingsRegistry.customWarningTextColorLight,
SettingsRegistry.customWarningTextColorDark,
);
case ThemeColorSlot.warningCard:
return (
SettingsRegistry.customWarningCardColorLight,
SettingsRegistry.customWarningCardColorDark,
);
case ThemeColorSlot.errorAccent:
return (
SettingsRegistry.customErrorAccentColorLight,
SettingsRegistry.customErrorAccentColorDark,
);
case ThemeColorSlot.errorText:
return (
SettingsRegistry.customErrorTextColorLight,
SettingsRegistry.customErrorTextColorDark,
);
case ThemeColorSlot.errorCard:
return (
SettingsRegistry.customErrorCardColorLight,
SettingsRegistry.customErrorCardColorDark,
);
}
}
/// the grade color settings, grade 1 first, the order of the share format
final _gradeSettings = [
SettingsRegistry.customGradeColor1,
SettingsRegistry.customGradeColor2,
SettingsRegistry.customGradeColor3,
SettingsRegistry.customGradeColor4,
SettingsRegistry.customGradeColor5,
];
/// the colors the app has right now as a share code: every slot, the grade
/// colors and both background gradients
String captureThemeCode(SettingsRepository settings) {
Color read(StringSetting setting) =>
settings.get(setting).toColorFromHexSetting();
final bytes = ThemeBinaryFormat.encodeFullTheme(
light: {
for (final slot in ThemeColorSlot.values)
slot: read(themeSlotSettings(slot).$1),
},
dark: {
for (final slot in ThemeColorSlot.values)
slot: read(themeSlotSettings(slot).$2),
},
gradeColors: [for (final setting in _gradeSettings) read(setting)],
gradientLight: settings
.get(SettingsRegistry.customBackgroundGradientLight)
.toColorListFromHexSetting(),
gradientDark: settings
.get(SettingsRegistry.customBackgroundGradientDark)
.toColorListFromHexSetting(),
);
return ThemeBinaryFormat.toBase64(bytes);
}
/// puts the colors of a share code into the settings. everything is written
/// quietly except the last one, so the app refreshes once and not forty times.
/// throws a [FormatException] when the code is not a theme.
Future<void> applyThemeCode(SettingsRepository settings, String code) async {
final data = ThemeBinaryFormat.decodeFromBase64(code);
final slots = data.toThemeSlots();
for (final slot in ThemeColorSlot.values) {
final (light, dark) = themeSlotSettings(slot);
await settings.setSilently(light, slots.light[slot]!.toHexSetting());
await settings.setSilently(dark, slots.dark[slot]!.toHexSetting());
}
for (var i = 0; i < _gradeSettings.length; i++) {
await settings.setSilently(
_gradeSettings[i],
data.gradeColors[i].toHexSetting(),
);
}
await settings.setSilently(
SettingsRegistry.customBackgroundGradientLight,
data.gradientLight.toHexSettingJson(),
);
await settings.set(
SettingsRegistry.customBackgroundGradientDark,
data.gradientDark.toHexSettingJson(),
);
}
/// writes the colors being edited back into the selected theme, so each theme
/// keeps its own. nothing to do while a built-in theme is selected.
Future<void> saveActiveThemeCode(SettingsRepository settings) async {
final id = settings.get(SettingsRegistry.selectedThemeId);
if (isBuiltinThemeId(id)) return;
final stored = await isarInit.userThemeModels.getByThemeId(id);
if (stored == null) return;
stored.code = captureThemeCode(settings);
stored.swatchArgb = [
for (final color in UserTheme.swatchFromAppStyle()) color.toARGB32(),
];
await isarInit.writeTxn(() => isarInit.userThemeModels.putByThemeId(stored));
await pushThemeToServer(settings);
}
Timer? _saveTimer;
/// saves the selected theme a moment after the last change, dragging a slider
/// changes a color many times a second
void scheduleActiveThemeSave(SettingsRepository settings) {
_saveTimer?.cancel();
_saveTimer = Timer(
const Duration(milliseconds: 300),
() => saveActiveThemeCode(settings),
);
}

View File

@@ -0,0 +1,213 @@
import 'dart:convert';
import 'package:crypto/crypto.dart';
import 'package:isar_community/isar.dart';
import 'package:firka/api/theme_sync_api.dart' as api;
import 'package:firka/app/app_state.dart';
import 'package:firka/core/settings/settings_repository.dart';
import 'package:firka/core/settings/settings_schema.dart';
import 'package:firka/core/theme_palette.dart';
import 'package:firka/ui/phone/screens/themes/builtin_theme_id.dart';
import 'package:firka/ui/phone/screens/themes/user_theme.dart';
import 'package:firka_common/data/database.dart';
import 'package:firka_common/data/models/token_model.dart';
import 'package:firka_common/data/models/user_theme_model.dart';
import 'package:firka_common/ui/theme/theme_binary_format.dart';
/// identifies the account's row. baked into the app so the vault can't be
/// worked out from a student's institute code and id alone.
const _vaultSalt = 'firka-theme-sync-2026';
/// a different secret for the write key, so seeing a vault never tells
/// anyone what it takes to change what is in it
const _writeSalt = 'firka-theme-write-2026';
/// the account's row id. the only thing that leaves the device is this hash,
/// never the institute code or the student id behind it. both survive a token
/// refresh, so the vault stays the same for the life of the account.
String computeVault(TokenModel token) => sha256
.convert(utf8.encode('$_vaultSalt:${token.iss}:${token.studentId}'))
.toString();
/// proves to the server that this client owns the vault. the server only
/// ever stores a hash of it, and it never goes into a share link.
String computeWriteKey(TokenModel token) => Hmac(
sha256,
utf8.encode(_writeSalt),
).convert(utf8.encode('${token.iss}:${token.studentId}')).toString();
/// the local id of the theme mirroring the account's vault
String syncedThemeId(String vault) => 'sync-${vault.substring(0, 24)}';
/// pulls this account's own theme down, so signing in on another device
/// brings the theme along. quietly does nothing while nobody is logged in
/// or the network is down.
Future<void> syncThemeFromServer(SettingsRepository settings) async {
try {
final token = settings.getSelectedToken();
if (token == null) return;
final vault = computeVault(token);
final remote = await api.fetchTheme(vault);
if (remote == null) return;
final local = await isarInit.userThemeModels.where().findAll();
// the server's copy is usually a theme of ours pushed from another
// device, so match on the colors before making a second one
final stored =
local.where((t) => t.code == remote.code).firstOrNull ??
local.where((t) => t.themeId == syncedThemeId(vault)).firstOrNull;
if (stored != null &&
stored.code == remote.code &&
stored.shareId == remote.shareId) {
return;
}
final id = stored?.themeId ?? syncedThemeId(vault);
final model = (stored ?? UserThemeModel())
..themeId = id
..name = remote.name.isNotEmpty ? remote.name : (stored?.name ?? 'Firka')
..origin = stored?.origin ?? 'own'
..code = remote.code
..shareId = remote.shareId
..swatchArgb = _swatchOf(remote.code) ?? stored?.swatchArgb ?? const [];
await isarInit.writeTxn(() => isarInit.userThemeModels.putByThemeId(model));
// applying the code makes the app save the theme, which would otherwise
// push this very theme straight back up
_lastPushed = '${remote.code}:${model.name}';
// only take the colors over while the user is still on a built-in theme
final selected = settings.get(SettingsRegistry.selectedThemeId);
if (isBuiltinThemeId(selected) || selected == id) {
await settings.setSilently(SettingsRegistry.selectedThemeId, id);
await applyThemeCode(settings, remote.code);
}
} catch (e) {
logger.warning('[ThemeSync] fetch failed: $e');
}
}
/// re-reads every theme imported from a share link. the owner of a shared
/// theme keeps editing it, so these follow along on their own.
Future<void> refreshSharedThemes(SettingsRepository settings) async {
try {
final local = await isarInit.userThemeModels.where().findAll();
final followed = local.where(
(t) => t.origin == 'downloaded' && t.shareId.isNotEmpty,
);
final selected = settings.get(SettingsRegistry.selectedThemeId);
var changedSelected = false;
for (final theme in followed) {
final remote = await api.fetchSharedTheme(theme.shareId);
// a dead link keeps the copy that was imported, rather than losing it
if (remote == null || remote.code == theme.code) continue;
theme.code = remote.code;
theme.swatchArgb = _swatchOf(remote.code) ?? theme.swatchArgb;
await isarInit.writeTxn(
() => isarInit.userThemeModels.putByThemeId(theme),
);
if (theme.themeId == selected) changedSelected = true;
}
// repaint right away when the theme being worn is the one that moved
if (changedSelected) {
final theme = await isarInit.userThemeModels.getByThemeId(selected);
if (theme != null) await applyThemeCode(settings, theme.code);
}
} catch (e) {
logger.warning('[ThemeSync] shared refresh failed: $e');
}
}
/// what the server was last told, so dragging a colour slider and pulling a
/// theme back down don't each cost a request that changes nothing
String? _lastPushed;
/// pushes the selected theme up. a shared theme is pushed like any other —
/// that is how everyone following the link sees the edit.
Future<void> pushThemeToServer(SettingsRepository settings) async {
final id = settings.get(SettingsRegistry.selectedThemeId);
if (isBuiltinThemeId(id)) return;
final stored = await isarInit.userThemeModels.getByThemeId(id);
// someone else's theme is theirs to change, we only follow it
if (stored == null || stored.origin == 'downloaded') return;
await _push(settings, stored, captureThemeCode(settings));
}
/// publishes [theme] and returns the share id to put in the link, or an
/// empty string when it couldn't be published. the theme stays editable:
/// later edits reach everyone holding the link on their own.
Future<String> publishTheme(
SettingsRepository settings,
UserTheme theme,
) async {
try {
final token = settings.getSelectedToken();
if (token == null || theme.isBuiltin) return '';
final stored = await isarInit.userThemeModels.getByThemeId(theme.id);
if (stored == null) return '';
// the link has to point at the colours it was made from
await _push(settings, stored, theme.code, force: true);
final shareId = await api.shareTheme(
computeVault(token),
writeKey: computeWriteKey(token),
);
stored.shareId = shareId;
await isarInit.writeTxn(
() => isarInit.userThemeModels.putByThemeId(stored),
);
return shareId;
} catch (e) {
logger.warning('[ThemeSync] publish failed: $e');
return '';
}
}
Future<void> _push(
SettingsRepository settings,
UserThemeModel stored,
String code, {
bool force = false,
}) async {
try {
final token = settings.getSelectedToken();
if (token == null) return;
final sent = '$code:${stored.name}';
if (!force && sent == _lastPushed) return;
await api.pushTheme(
computeVault(token),
writeKey: computeWriteKey(token),
code: code,
name: stored.name,
);
_lastPushed = sent;
} catch (e) {
logger.warning('[ThemeSync] push failed: $e');
}
}
List<int>? _swatchOf(String code) {
final data = code.tryDecodeThemeData();
if (data == null) return null;
return [
data.lightSlot(ThemeColorSlot.accent).toARGB32(),
data.lightSlot(ThemeColorSlot.textPrimary).toARGB32(),
data.lightSlot(ThemeColorSlot.background).toARGB32(),
];
}

View File

@@ -10,6 +10,7 @@ import "package:firka/core/settings/settings_repository.dart";
import "package:firka/core/settings/settings_schema.dart"; import "package:firka/core/settings/settings_schema.dart";
import "package:firka/core/snowflake.dart"; import "package:firka/core/snowflake.dart";
import "package:firka/ui/components/color_slider.dart"; import "package:firka/ui/components/color_slider.dart";
import "package:firka/core/theme_palette.dart";
import "package:firka/ui/phone/screens/themes/builtin_theme_id.dart"; import "package:firka/ui/phone/screens/themes/builtin_theme_id.dart";
import "package:firka/ui/phone/screens/themes/preview/theme_preview_data.dart"; import "package:firka/ui/phone/screens/themes/preview/theme_preview_data.dart";
import "package:firka/ui/phone/screens/themes/preview/theme_preview_pages.dart"; import "package:firka/ui/phone/screens/themes/preview/theme_preview_pages.dart";
@@ -19,6 +20,7 @@ import "package:firka/ui/theme/style.dart";
import "package:firka_common/data/database.dart"; import "package:firka_common/data/database.dart";
import "package:firka_common/data/models/user_theme_model.dart"; import "package:firka_common/data/models/user_theme_model.dart";
import "package:firka_common/ui/components/firka_card.dart"; import "package:firka_common/ui/components/firka_card.dart";
import "package:firka_common/ui/theme/theme_binary_format.dart";
import "package:firka_common/ui/theme/style.dart"; import "package:firka_common/ui/theme/style.dart";
import "package:flutter/material.dart"; import "package:flutter/material.dart";
import "package:flutter/services.dart"; import "package:flutter/services.dart";
@@ -80,90 +82,9 @@ const _defaultGradients = (
dark: [Color(0xFF0D1202), Color(0xFF1A2405)], dark: [Color(0xFF0D1202), Color(0xFF1A2405)],
); );
(StringSetting, StringSetting) _settingsFor(_ThemeSlot slot) { /// delegates to [themeSlotSettings] via the matching [ThemeColorSlot]
switch (slot) { (StringSetting, StringSetting) _settingsFor(_ThemeSlot slot) =>
case _ThemeSlot.accent: themeSlotSettings(ThemeColorSlot.values[slot.index]);
return (
SettingsRegistry.customAccentColorLight,
SettingsRegistry.customAccentColorDark,
);
case _ThemeSlot.background:
return (
SettingsRegistry.customBackgroundColorLight,
SettingsRegistry.customBackgroundColorDark,
);
case _ThemeSlot.card:
return (
SettingsRegistry.customCardColorLight,
SettingsRegistry.customCardColorDark,
);
case _ThemeSlot.button:
return (
SettingsRegistry.customButtonColorLight,
SettingsRegistry.customButtonColorDark,
);
case _ThemeSlot.secondary:
return (
SettingsRegistry.customSecondaryColorLight,
SettingsRegistry.customSecondaryColorDark,
);
case _ThemeSlot.text:
return (
SettingsRegistry.customTextColorLight,
SettingsRegistry.customTextColorDark,
);
case _ThemeSlot.textSecondary:
return (
SettingsRegistry.customTextSecondaryColorLight,
SettingsRegistry.customTextSecondaryColorDark,
);
case _ThemeSlot.textTertiary:
return (
SettingsRegistry.customTextTertiaryColorLight,
SettingsRegistry.customTextTertiaryColorDark,
);
case _ThemeSlot.shadow:
return (
SettingsRegistry.customShadowColorLight,
SettingsRegistry.customShadowColorDark,
);
case _ThemeSlot.success:
return (
SettingsRegistry.customSuccessColorLight,
SettingsRegistry.customSuccessColorDark,
);
case _ThemeSlot.warningAccent:
return (
SettingsRegistry.customWarningAccentColorLight,
SettingsRegistry.customWarningAccentColorDark,
);
case _ThemeSlot.warningText:
return (
SettingsRegistry.customWarningTextColorLight,
SettingsRegistry.customWarningTextColorDark,
);
case _ThemeSlot.warningCard:
return (
SettingsRegistry.customWarningCardColorLight,
SettingsRegistry.customWarningCardColorDark,
);
case _ThemeSlot.errorAccent:
return (
SettingsRegistry.customErrorAccentColorLight,
SettingsRegistry.customErrorAccentColorDark,
);
case _ThemeSlot.errorText:
return (
SettingsRegistry.customErrorTextColorLight,
SettingsRegistry.customErrorTextColorDark,
);
case _ThemeSlot.errorCard:
return (
SettingsRegistry.customErrorCardColorLight,
SettingsRegistry.customErrorCardColorDark,
);
}
}
void _applySlotColor(FirkaColors colors, _ThemeSlot slot, Color color) { void _applySlotColor(FirkaColors colors, _ThemeSlot slot, Color color) {
switch (slot) { switch (slot) {
@@ -232,9 +153,7 @@ class _ThemeEditorScreenState extends State<ThemeEditorScreen> {
super.initState(); super.initState();
_originalIsLight = appStyle.isLight; _originalIsLight = appStyle.isLight;
_preview = ThemePreviewData.build(); _preview = ThemePreviewData.build();
_hsv = HSVColor.fromColor( _hsv = HSVColor.fromColor(_colorForSlotAndMode(_slot!, _mode));
_colorForSlotAndMode(_slot!, _mode),
);
_syncHexField(); _syncHexField();
_refreshPreviewStyle(); _refreshPreviewStyle();
} }
@@ -288,8 +207,9 @@ class _ThemeEditorScreenState extends State<ThemeEditorScreen> {
final editingLight = _mode != _BrightnessMode.dark; final editingLight = _mode != _BrightnessMode.dark;
if (_mode == _BrightnessMode.both || editingLight == isLight) { if (_mode == _BrightnessMode.both || editingLight == isLight) {
if (slot == _ThemeSlot.background) { if (slot == _ThemeSlot.background) {
final stops = final stops = List<Color>.from(
List<Color>.from(_currentGradient(isLightSource: isLight)); _currentGradient(isLightSource: isLight),
);
if (_bgStopIndex < stops.length) { if (_bgStopIndex < stops.length) {
stops[_bgStopIndex] = _hsv.toColor(); stops[_bgStopIndex] = _hsv.toColor();
} else { } else {
@@ -346,8 +266,7 @@ class _ThemeEditorScreenState extends State<ThemeEditorScreen> {
final color = _hsv.toColor(); final color = _hsv.toColor();
final hex = color.toHexSetting(); final hex = color.toHexSetting();
_hexController.text = _hexController.text =
(color.a >= 1.0 ? hex.substring(4) : hex.substring(2)) (color.a >= 1.0 ? hex.substring(4) : hex.substring(2)).toUpperCase();
.toUpperCase();
} }
} }
@@ -370,10 +289,12 @@ class _ThemeEditorScreenState extends State<ThemeEditorScreen> {
final setting = isLightSource final setting = isLightSource
? SettingsRegistry.customBackgroundGradientLight ? SettingsRegistry.customBackgroundGradientLight
: SettingsRegistry.customBackgroundGradientDark; : SettingsRegistry.customBackgroundGradientDark;
final stops = final stops = List<Color>.from(
List<Color>.from(_currentGradient(isLightSource: isLightSource)); _currentGradient(isLightSource: isLightSource),
final idx = );
_bgStopIndex.clamp(0, math.max(0, stops.length - 1)).toInt(); final idx = _bgStopIndex
.clamp(0, math.max(0, stops.length - 1))
.toInt();
if (stops.isNotEmpty) { if (stops.isNotEmpty) {
stops[idx] = color; stops[idx] = color;
} else { } else {
@@ -417,6 +338,7 @@ class _ThemeEditorScreenState extends State<ThemeEditorScreen> {
name: widget.data.l10n.s_c_themes_own_label, name: widget.data.l10n.s_c_themes_own_label,
origin: ThemeOrigin.own, origin: ThemeOrigin.own,
swatch: UserTheme.swatchFromAppStyle(), swatch: UserTheme.swatchFromAppStyle(),
code: captureThemeCode(_settings),
); );
await isarInit.writeTxn(() async { await isarInit.writeTxn(() async {
await isarInit.userThemeModels.putByThemeId(theme.toModel()); await isarInit.userThemeModels.putByThemeId(theme.toModel());
@@ -442,8 +364,9 @@ class _ThemeEditorScreenState extends State<ThemeEditorScreen> {
_slot = slot; _slot = slot;
if (slot == _ThemeSlot.background) { if (slot == _ThemeSlot.background) {
final stops = _gradientForMode(_mode); final stops = _gradientForMode(_mode);
_bgStopIndex = _bgStopIndex = _bgStopIndex
_bgStopIndex.clamp(0, math.max(0, stops.length - 1)).toInt(); .clamp(0, math.max(0, stops.length - 1))
.toInt();
} }
_hsv = HSVColor.fromColor(_colorForSlotAndMode(slot, _mode)); _hsv = HSVColor.fromColor(_colorForSlotAndMode(slot, _mode));
_refreshPreviewStyle(); _refreshPreviewStyle();
@@ -458,8 +381,9 @@ class _ThemeEditorScreenState extends State<ThemeEditorScreen> {
if (slot != null) { if (slot != null) {
if (slot == _ThemeSlot.background) { if (slot == _ThemeSlot.background) {
final stops = _gradientForMode(mode); final stops = _gradientForMode(mode);
_bgStopIndex = _bgStopIndex = _bgStopIndex
_bgStopIndex.clamp(0, math.max(0, stops.length - 1)).toInt(); .clamp(0, math.max(0, stops.length - 1))
.toInt();
} }
_hsv = HSVColor.fromColor(_colorForSlotAndMode(slot, mode)); _hsv = HSVColor.fromColor(_colorForSlotAndMode(slot, mode));
} }
@@ -473,8 +397,9 @@ class _ThemeEditorScreenState extends State<ThemeEditorScreen> {
final setting = isLightSource final setting = isLightSource
? SettingsRegistry.customBackgroundGradientLight ? SettingsRegistry.customBackgroundGradientLight
: SettingsRegistry.customBackgroundGradientDark; : SettingsRegistry.customBackgroundGradientDark;
final stops = final stops = List<Color>.from(
List<Color>.from(_currentGradient(isLightSource: isLightSource)); _currentGradient(isLightSource: isLightSource),
);
final lastColor = stops.isNotEmpty final lastColor = stops.isNotEmpty
? stops.last ? stops.last
: (isLightSource : (isLightSource
@@ -513,8 +438,9 @@ class _ThemeEditorScreenState extends State<ThemeEditorScreen> {
final setting = isLightSource final setting = isLightSource
? SettingsRegistry.customBackgroundGradientLight ? SettingsRegistry.customBackgroundGradientLight
: SettingsRegistry.customBackgroundGradientDark; : SettingsRegistry.customBackgroundGradientDark;
final stops = final stops = List<Color>.from(
List<Color>.from(_currentGradient(isLightSource: isLightSource)); _currentGradient(isLightSource: isLightSource),
);
if (stops.length > 1 && index < stops.length) { if (stops.length > 1 && index < stops.length) {
stops.removeAt(index); stops.removeAt(index);
await _settings.set(setting, stops.toHexSettingJson()); await _settings.set(setting, stops.toHexSettingJson());
@@ -629,15 +555,14 @@ class _ThemeEditorScreenState extends State<ThemeEditorScreen> {
if (!mounted) return; if (!mounted) return;
setState(() { setState(() {
_hsv = HSVColor.fromColor( _hsv = HSVColor.fromColor(switch (_mode) {
switch (_mode) {
_BrightnessMode.light => lightDefault, _BrightnessMode.light => lightDefault,
_BrightnessMode.dark => darkDefault, _BrightnessMode.dark => darkDefault,
_BrightnessMode.both => lightDefault == darkDefault _BrightnessMode.both =>
lightDefault == darkDefault
? lightDefault ? lightDefault
: (_originalIsLight ? lightDefault : darkDefault), : (_originalIsLight ? lightDefault : darkDefault),
}, });
);
_refreshPreviewStyle(); _refreshPreviewStyle();
}); });
_syncHexField(); _syncHexField();
@@ -838,12 +763,7 @@ class _ThemeEditorScreenState extends State<ThemeEditorScreen> {
final solid = _hsv.toColor().withAlpha(255); final solid = _hsv.toColor().withAlpha(255);
return ColorSlider( return ColorSlider(
value: _hsv.alpha, value: _hsv.alpha,
trackGradient: LinearGradient( trackGradient: LinearGradient(colors: [solid.withAlpha(0), solid]),
colors: [
solid.withAlpha(0),
solid,
],
),
thumbColor: _hsv.toColor(), thumbColor: _hsv.toColor(),
onChanged: (t) => _applyHsv(_hsv.withAlpha(t.clamp(0.0, 1.0))), onChanged: (t) => _applyHsv(_hsv.withAlpha(t.clamp(0.0, 1.0))),
); );

View File

@@ -73,10 +73,7 @@ class ThemePagePreview extends StatelessWidget {
children: [ children: [
_PreviewStatusBar(), _PreviewStatusBar(),
Expanded(child: body), Expanded(child: body),
_PreviewBottomNav( _PreviewBottomNav(data: data, activeTab: activeTab),
data: data,
activeTab: activeTab,
),
], ],
), ),
), ),
@@ -114,11 +111,7 @@ class _PreviewStatusBar extends StatelessWidget {
color: appStyle.colors.textPrimary, color: appStyle.colors.textPrimary,
), ),
const SizedBox(width: 4), const SizedBox(width: 4),
Icon( Icon(Icons.wifi, size: 12, color: appStyle.colors.textPrimary),
Icons.wifi,
size: 12,
color: appStyle.colors.textPrimary,
),
const SizedBox(width: 4), const SizedBox(width: 4),
Icon( Icon(
Icons.battery_full, Icons.battery_full,
@@ -136,10 +129,7 @@ class _PreviewBottomNav extends StatelessWidget {
final AppInitialization data; final AppInitialization data;
final ThemePreviewNavTab activeTab; final ThemePreviewNavTab activeTab;
const _PreviewBottomNav({ const _PreviewBottomNav({required this.data, required this.activeTab});
required this.data,
required this.activeTab,
});
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {

View File

@@ -217,11 +217,56 @@ class ThemePreviewData {
); );
final chartSpanDays = day.difference(sept).inDays.clamp(1, 365); final chartSpanDays = day.difference(sept).inDays.clamp(1, 365);
const chartValues = [ const chartValues = [
1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 1,
3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 1,
4, 4, 3, 3, 4, 4, 4, 4, 5, 5, 1,
5, 4, 4, 5, 5, 5, 5, 5, 5, 5, 1,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 2,
2,
2,
2,
2,
2,
3,
3,
3,
3,
3,
3,
3,
4,
4,
4,
4,
4,
3,
3,
4,
4,
4,
4,
5,
5,
5,
4,
4,
5,
5,
5,
5,
5,
5,
5,
5,
5,
5,
5,
5,
5,
5,
5,
5,
5,
]; ];
final chartGrades = [ final chartGrades = [
for (var i = 0; i < chartValues.length; i++) for (var i = 0; i < chartValues.length; i++)
@@ -230,7 +275,9 @@ class ThemePreviewData {
matematika, matematika,
chartValues[i], chartValues[i],
sept.add( sept.add(
Duration(days: (i * chartSpanDays / (chartValues.length - 1)).round()), Duration(
days: (i * chartSpanDays / (chartValues.length - 1)).round(),
),
), ),
), ),
]; ];

View File

@@ -82,9 +82,7 @@ class ThemePreviewHomeMain extends StatelessWidget {
for (final test in preview.tests) { for (final test in preview.tests) {
noticeBoardWidgets.add((InfoCard.test(test), test.createdAt)); noticeBoardWidgets.add((InfoCard.test(test), test.createdAt));
} }
noticeBoardWidgets.sort( noticeBoardWidgets.sort((a, b) => b.$2.difference(a.$2).inMilliseconds);
(a, b) => b.$2.difference(a.$2).inMilliseconds,
);
return Padding( return Padding(
padding: const EdgeInsets.symmetric(horizontal: 20), padding: const EdgeInsets.symmetric(horizontal: 20),
@@ -147,11 +145,7 @@ class ThemePreviewHomeGrades extends StatelessWidget {
in preview.subjects.toList() in preview.subjects.toList()
..sort((a, b) => a.name.compareTo(b.name))) { ..sort((a, b) => a.name.compareTo(b.name))) {
gradeCards.add( gradeCards.add(
GradeSmallCard( GradeSmallCard(allGrades.getAverageBySubject(subject), null, subject),
allGrades.getAverageBySubject(subject),
null,
subject,
),
); );
} }
@@ -237,9 +231,7 @@ class ThemePreviewHomeGrades extends StatelessWidget {
height: 26, height: 26,
decoration: ShapeDecoration( decoration: ShapeDecoration(
color: filled ? getGradeColor(value).withAlpha(38) : Colors.transparent, color: filled ? getGradeColor(value).withAlpha(38) : Colors.transparent,
shape: RoundedRectangleBorder( shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
borderRadius: BorderRadius.circular(12),
),
), ),
child: Center( child: Center(
child: Text( child: Text(
@@ -263,15 +255,9 @@ class ThemePreviewHomeTimetable extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final day = DateTime( final day = DateTime(preview.now.year, preview.now.month, preview.now.day);
preview.now.year,
preview.now.month,
preview.now.day,
);
final monday = day.getMonday(); final monday = day.getMonday();
final tabDays = [ final tabDays = [for (var i = 0; i < 5; i++) monday.add(Duration(days: i))];
for (var i = 0; i < 5; i++) monday.add(Duration(days: i)),
];
return Stack( return Stack(
children: [ children: [
@@ -392,17 +378,15 @@ class ThemePreviewHomeTimetableMonthly extends StatelessWidget {
var omissionCountMonth = 0; var omissionCountMonth = 0;
for (var i = 0; i < 49; i++) { for (var i = 0; i < 49; i++) {
final d = DateTime( final d = DateTime(gridStart.year, gridStart.month, gridStart.day + i);
gridStart.year,
gridStart.month,
gridStart.day + i,
);
final key = DateTime(d.year, d.month, d.day); final key = DateTime(d.year, d.month, d.day);
final meta = preview.monthDayMeta[key] ?? final meta =
preview.monthDayMeta[key] ??
const ThemePreviewMonthDay(lessonCount: 0, hasTest: false); const ThemePreviewMonthDay(lessonCount: 0, hasTest: false);
final outOfRange = final outOfRange =
d.isBefore(currentMonthStart) || d.isAfter(currentMonthEnd); d.isBefore(currentMonthStart) || d.isAfter(currentMonthEnd);
final isToday = !outOfRange && final isToday =
!outOfRange &&
now.year == d.year && now.year == d.year &&
now.day == d.day && now.day == d.day &&
now.month == d.month; now.month == d.month;
@@ -422,7 +406,8 @@ class ThemePreviewHomeTimetableMonthly extends StatelessWidget {
child: Text( child: Text(
meta.lessonCount.toString(), meta.lessonCount.toString(),
style: appStyle.fonts.H_16px.apply( style: appStyle.fonts.H_16px.apply(
color: (todayAccent ?? color:
(todayAccent ??
(meta.omission != null (meta.omission != null
? appStyle.colors.errorText ? appStyle.colors.errorText
: appStyle.colors.secondary)) : appStyle.colors.secondary))
@@ -528,9 +513,7 @@ class ThemePreviewHomeTimetableMonthly extends StatelessWidget {
color: appStyle.colors.accent, color: appStyle.colors.accent,
), ),
Text( Text(
now now.format(data.l10n, FormatMode.yyyymmmm).toLowerCase(),
.format(data.l10n, FormatMode.yyyymmmm)
.toLowerCase(),
style: appStyle.fonts.B_16R.apply( style: appStyle.fonts.B_16R.apply(
color: appStyle.colors.textPrimary, color: appStyle.colors.textPrimary,
), ),
@@ -548,7 +531,11 @@ class ThemePreviewHomeTimetableMonthly extends StatelessWidget {
), ),
), ),
Padding( Padding(
padding: const EdgeInsets.only(top: 74 + 16 + 12, left: 20, right: 20), padding: const EdgeInsets.only(
top: 74 + 16 + 12,
left: 20,
right: 20,
),
child: GridView.count( child: GridView.count(
physics: const NeverScrollableScrollPhysics(), physics: const NeverScrollableScrollPhysics(),
crossAxisCount: 7, crossAxisCount: 7,
@@ -620,9 +607,7 @@ class _PreviewStatusToast extends StatelessWidget {
color: active color: active
? appStyle.colors.buttonSecondaryFill ? appStyle.colors.buttonSecondaryFill
: appStyle.colors.cardTranslucent, : appStyle.colors.cardTranslucent,
shape: RoundedRectangleBorder( shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
borderRadius: BorderRadius.circular(16),
),
), ),
child: Row( child: Row(
spacing: 6, spacing: 6,

View File

@@ -68,7 +68,15 @@ Future<void> showThemeShareSheet(
BuildContext context, { BuildContext context, {
required UserTheme theme, required UserTheme theme,
required AppInitialization data, required AppInitialization data,
}) { Future<void> Function()? onPublish,
}) async {
// publish first so the link carries a share id and the people who scan it
// keep seeing this theme as it is edited
if (!theme.isBuiltin && theme.shareId.isEmpty) {
await onPublish?.call();
if (!context.mounted) return;
}
return showModalBottomSheet<void>( return showModalBottomSheet<void>(
context: context, context: context,
elevation: 100, elevation: 100,
@@ -103,10 +111,7 @@ Future<void> showThemeImportSheet(
padding: EdgeInsets.only( padding: EdgeInsets.only(
bottom: MediaQuery.viewInsetsOf(context).bottom, bottom: MediaQuery.viewInsetsOf(context).bottom,
), ),
child: _ThemeImportSheet( child: _ThemeImportSheet(l10n: data.l10n, onImport: onImport),
l10n: data.l10n,
onImport: onImport,
),
); );
}, },
); );
@@ -145,7 +150,8 @@ class _ThemeShareSheetState extends State<_ThemeShareSheet> {
setState(() => _isSharing = true); setState(() => _isSharing = true);
try { try {
final boundary = _cardKey.currentContext?.findRenderObject() as RenderRepaintBoundary?; final boundary =
_cardKey.currentContext?.findRenderObject() as RenderRepaintBoundary?;
if (boundary == null) { if (boundary == null) {
throw Exception("RenderRepaintBoundary not found"); throw Exception("RenderRepaintBoundary not found");
} }
@@ -158,23 +164,19 @@ class _ThemeShareSheetState extends State<_ThemeShareSheet> {
final pngBytes = byteData.buffer.asUint8List(); final pngBytes = byteData.buffer.asUint8List();
final tempDir = await getTemporaryDirectory(); final tempDir = await getTemporaryDirectory();
final sanitizedName = widget.theme.name.replaceAll(RegExp(r'[^\w\s-]'), '').trim(); final sanitizedName = widget.theme.name
.replaceAll(RegExp(r'[^\w\s-]'), '')
.trim();
final safeName = sanitizedName.isEmpty ? 'firka' : sanitizedName; final safeName = sanitizedName.isEmpty ? 'firka' : sanitizedName;
final file = File('${tempDir.path}/firka_theme_$safeName.png'); final file = File('${tempDir.path}/firka_theme_$safeName.png');
await file.writeAsBytes(pngBytes); await file.writeAsBytes(pngBytes);
await SharePlus.instance.share( await SharePlus.instance.share(
ShareParams( ShareParams(files: [XFile(file.path)], subject: widget.theme.name),
files: [XFile(file.path)],
subject: widget.theme.name,
),
); );
} catch (e) { } catch (e) {
await SharePlus.instance.share( await SharePlus.instance.share(
ShareParams( ShareParams(text: widget.shareUrl, subject: widget.theme.name),
text: widget.shareUrl,
subject: widget.theme.name,
),
); );
} finally { } finally {
if (mounted) { if (mounted) {
@@ -191,10 +193,7 @@ class _ThemeShareSheetState extends State<_ThemeShareSheet> {
children: [ children: [
RepaintBoundary( RepaintBoundary(
key: _cardKey, key: _cardKey,
child: ThemeQrCard( child: ThemeQrCard(theme: widget.theme, shareData: widget.shareUrl),
theme: widget.theme,
shareData: widget.shareUrl,
),
), ),
const SizedBox(height: 20), const SizedBox(height: 20),
_sheetButton( _sheetButton(
@@ -221,10 +220,7 @@ class _ThemeImportSheet extends StatefulWidget {
final AppLocalizations l10n; final AppLocalizations l10n;
final Future<void> Function(UserTheme theme) onImport; final Future<void> Function(UserTheme theme) onImport;
const _ThemeImportSheet({ const _ThemeImportSheet({required this.l10n, required this.onImport});
required this.l10n,
required this.onImport,
});
@override @override
State<_ThemeImportSheet> createState() => _ThemeImportSheetState(); State<_ThemeImportSheet> createState() => _ThemeImportSheetState();
@@ -234,6 +230,8 @@ class _ThemeImportSheetState extends State<_ThemeImportSheet> {
_ImportMode _mode = _ImportMode.camera; _ImportMode _mode = _ImportMode.camera;
final _controller = TextEditingController(); final _controller = TextEditingController();
ThemeBinaryData? _previewData; ThemeBinaryData? _previewData;
String? _code;
String _shareId = '';
String? _extractedName; String? _extractedName;
String? _error; String? _error;
bool _isAnalyzingImage = false; bool _isAnalyzingImage = false;
@@ -261,6 +259,8 @@ class _ThemeImportSheetState extends State<_ThemeImportSheet> {
setState(() { setState(() {
_controller.text = trimmed; _controller.text = trimmed;
_previewData = decoded; _previewData = decoded;
_code = payload.code;
_shareId = payload.shareId;
_extractedName = payload.name; _extractedName = payload.name;
_error = null; _error = null;
}); });
@@ -280,6 +280,8 @@ class _ThemeImportSheetState extends State<_ThemeImportSheet> {
if (raw.isEmpty) { if (raw.isEmpty) {
setState(() { setState(() {
_previewData = null; _previewData = null;
_code = null;
_shareId = '';
_extractedName = null; _extractedName = null;
_error = null; _error = null;
}); });
@@ -309,7 +311,9 @@ class _ThemeImportSheetState extends State<_ThemeImportSheet> {
return; return;
} }
final capture = await MobileScannerPlatform.instance.analyzeImage(picked.path); final capture = await MobileScannerPlatform.instance.analyzeImage(
picked.path,
);
if (capture != null && capture.barcodes.isNotEmpty) { if (capture != null && capture.barcodes.isNotEmpty) {
bool found = false; bool found = false;
for (final barcode in capture.barcodes) { for (final barcode in capture.barcodes) {
@@ -345,32 +349,24 @@ class _ThemeImportSheetState extends State<_ThemeImportSheet> {
Future<void> _import() async { Future<void> _import() async {
final preview = _previewData; final preview = _previewData;
if (preview == null) return; final code = _code;
if (preview == null || code == null) return;
final themeName = _extractedName != null && _extractedName!.isNotEmpty final themeName = _extractedName != null && _extractedName!.isNotEmpty
? _extractedName! ? _extractedName!
: widget.l10n.s_c_themes_imported_label; : widget.l10n.s_c_themes_imported_label;
final List<Color> 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( final theme = UserTheme(
id: Snowflake.nextId(), id: Snowflake.nextId(),
name: themeName, name: themeName,
origin: ThemeOrigin.downloaded, origin: ThemeOrigin.downloaded,
swatch: swatch, swatch: [
preview.lightSlot(ThemeColorSlot.accent),
preview.lightSlot(ThemeColorSlot.textPrimary),
preview.lightSlot(ThemeColorSlot.background),
],
code: code,
shareId: _shareId,
); );
await widget.onImport(theme); await widget.onImport(theme);
@@ -397,9 +393,7 @@ class _ThemeImportSheetState extends State<_ThemeImportSheet> {
: appStyle.colors.card, : appStyle.colors.card,
borderRadius: BorderRadius.circular(16), borderRadius: BorderRadius.circular(16),
border: Border.all( border: Border.all(
color: selected color: selected ? appStyle.colors.accent : Colors.transparent,
? appStyle.colors.accent
: Colors.transparent,
width: 1.5, width: 1.5,
), ),
), ),
@@ -479,13 +473,11 @@ class _ThemeImportSheetState extends State<_ThemeImportSheet> {
Row( Row(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
children: [ children: [
for (final color in (_previewData!.isFullTheme for (final color in [
? [ _previewData!.lightSlot(ThemeColorSlot.accent),
_previewData!.lightSlot(ThemeColorSlot.accent) ?? appStyle.colors.accent, _previewData!.lightSlot(ThemeColorSlot.textPrimary),
_previewData!.lightSlot(ThemeColorSlot.textPrimary) ?? appStyle.colors.textPrimary, _previewData!.lightSlot(ThemeColorSlot.background),
_previewData!.lightSlot(ThemeColorSlot.background) ?? appStyle.colors.background, ])
]
: _previewData!.colors.take(4)))
Container( Container(
margin: const EdgeInsets.symmetric(horizontal: 4), margin: const EdgeInsets.symmetric(horizontal: 4),
width: 20, width: 20,
@@ -494,7 +486,9 @@ class _ThemeImportSheetState extends State<_ThemeImportSheet> {
color: color, color: color,
shape: BoxShape.circle, shape: BoxShape.circle,
border: Border.all( border: Border.all(
color: appStyle.colors.textPrimary.withValues(alpha: 0.25), color: appStyle.colors.textPrimary.withValues(
alpha: 0.25,
),
width: 1.5, width: 1.5,
), ),
), ),
@@ -503,9 +497,7 @@ class _ThemeImportSheetState extends State<_ThemeImportSheet> {
), ),
const SizedBox(height: 8), const SizedBox(height: 8),
Text( Text(
_previewData!.isFullTheme "Teljes téma (32 szín)",
? "Teljes téma (32 szín)"
: "${_previewData!.colors.length} szín",
style: appStyle.fonts.B_12R.apply( style: appStyle.fonts.B_12R.apply(
color: appStyle.colors.textSecondary, color: appStyle.colors.textSecondary,
), ),
@@ -630,7 +622,9 @@ class _ThemeImportSheetState extends State<_ThemeImportSheet> {
Container( Container(
padding: const EdgeInsets.all(16), padding: const EdgeInsets.all(16),
decoration: BoxDecoration( decoration: BoxDecoration(
color: appStyle.colors.accent.withValues(alpha: 0.15), color: appStyle.colors.accent.withValues(
alpha: 0.15,
),
shape: BoxShape.circle, shape: BoxShape.circle,
), ),
child: Majesticon( child: Majesticon(
@@ -661,7 +655,10 @@ class _ThemeImportSheetState extends State<_ThemeImportSheet> {
] else if (_mode == _ImportMode.text) ...[ ] else if (_mode == _ImportMode.text) ...[
Container( Container(
width: double.infinity, width: double.infinity,
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4), padding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 4,
),
decoration: BoxDecoration( decoration: BoxDecoration(
color: appStyle.colors.card, color: appStyle.colors.card,
borderRadius: BorderRadius.circular(24), borderRadius: BorderRadius.circular(24),

View File

@@ -10,6 +10,8 @@ import "package:firka/core/bloc/theme_cubit.dart";
import "package:firka/ui/components/firka_icon_button.dart"; import "package:firka/ui/components/firka_icon_button.dart";
import "package:firka/ui/phone/screens/themes/preview/theme_preview_data.dart"; import "package:firka/ui/phone/screens/themes/preview/theme_preview_data.dart";
import "package:firka/ui/phone/screens/themes/preview/theme_preview_pages.dart"; import "package:firka/ui/phone/screens/themes/preview/theme_preview_pages.dart";
import "package:firka/core/theme_palette.dart";
import "package:firka/core/theme_sync.dart";
import "package:firka/ui/phone/screens/themes/sheets/theme_sheets.dart"; import "package:firka/ui/phone/screens/themes/sheets/theme_sheets.dart";
import "package:firka/ui/phone/screens/themes/user_theme.dart"; import "package:firka/ui/phone/screens/themes/user_theme.dart";
import "package:firka/ui/phone/screens/themes/widgets/theme_name_label.dart"; import "package:firka/ui/phone/screens/themes/widgets/theme_name_label.dart";
@@ -149,14 +151,21 @@ class _ThemeScreenState extends State<ThemeScreen> {
Row( Row(
spacing: 8, spacing: 8,
children: [ children: [
if (_theme.isOwn) ...[ if (_theme.canEdit)
FirkaIconButton( FirkaIconButton(
onTap: () async { onTap: () async {
// apply this theme before editing so the
// editor sees the right colors
await widget.args.onUse(_theme.id);
if (!mounted) return;
await context.push("/theme-editor"); await context.push("/theme-editor");
if (!mounted) return; if (!mounted) return;
setState(() { setState(() {
_theme.swatch = _theme.swatch =
UserTheme.swatchFromAppStyle(); UserTheme.swatchFromAppStyle();
_theme.code = captureThemeCode(
widget.data.settings,
);
appStyle = buildStyleForBrightness( appStyle = buildStyleForBrightness(
appStyle.isLight, appStyle.isLight,
isCustomTheme: true, isCustomTheme: true,
@@ -171,11 +180,20 @@ class _ThemeScreenState extends State<ThemeScreen> {
color: appStyle.colors.textPrimary, color: appStyle.colors.textPrimary,
), ),
), ),
if (_theme.canShare)
FirkaIconButton( FirkaIconButton(
onTap: () => showThemeShareSheet( onTap: () => showThemeShareSheet(
context, context,
theme: _theme, theme: _theme,
data: widget.data, data: widget.data,
onPublish: () async {
_theme.shareId = await publishTheme(
widget.data.settings,
_theme,
);
widget.args.onChanged();
if (mounted) setState(() {});
},
), ),
child: FirkaIconWidget( child: FirkaIconWidget(
FirkaIconType.majesticons, FirkaIconType.majesticons,
@@ -184,7 +202,6 @@ class _ThemeScreenState extends State<ThemeScreen> {
color: appStyle.colors.textPrimary, color: appStyle.colors.textPrimary,
), ),
), ),
],
if (_theme.canDelete) if (_theme.canDelete)
FirkaIconButton( FirkaIconButton(
onTap: _delete, onTap: _delete,

View File

@@ -8,6 +8,8 @@ import "package:firka/core/settings/settings_repository.dart";
import "package:firka/core/settings/settings_schema.dart"; import "package:firka/core/settings/settings_schema.dart";
import "package:firka/core/snowflake.dart"; import "package:firka/core/snowflake.dart";
import "package:firka/ui/components/firka_icon_button.dart"; import "package:firka/ui/components/firka_icon_button.dart";
import "package:firka/core/theme_palette.dart";
import "package:firka/core/theme_sync.dart";
import "package:firka/ui/phone/screens/themes/builtin_theme_id.dart"; import "package:firka/ui/phone/screens/themes/builtin_theme_id.dart";
import "package:firka/ui/phone/screens/themes/sheets/theme_sheets.dart"; import "package:firka/ui/phone/screens/themes/sheets/theme_sheets.dart";
import "package:firka/ui/phone/screens/themes/user_theme.dart"; import "package:firka/ui/phone/screens/themes/user_theme.dart";
@@ -49,6 +51,12 @@ class _ThemesScreenState extends State<ThemesScreen> {
} }
Future<void> _loadThemes() async { Future<void> _loadThemes() async {
// pull this account's own theme, and catch up on any edits the owners of
// the imported ones have made since
await syncThemeFromServer(widget.data.settings);
await refreshSharedThemes(widget.data.settings);
if (!mounted) return;
final stored = await isarInit.userThemeModels.where().findAll(); final stored = await isarInit.userThemeModels.where().findAll();
if (!mounted) return; if (!mounted) return;
@@ -60,10 +68,7 @@ class _ThemesScreenState extends State<ThemesScreen> {
setState(() { setState(() {
_storedThemes = stored.map(UserTheme.fromModel).toList(); _storedThemes = stored.map(UserTheme.fromModel).toList();
_selectedId = normalized; _selectedId = normalized;
final knownIds = { final knownIds = {_builtin.id, ..._storedThemes.map((t) => t.id)};
_builtin.id,
..._storedThemes.map((t) => t.id),
};
if (isBuiltinThemeId(_selectedId)) { if (isBuiltinThemeId(_selectedId)) {
// Always use the composed builtin id for the current core/grade. // Always use the composed builtin id for the current core/grade.
_selectedId = _builtin.id; _selectedId = _builtin.id;
@@ -114,6 +119,13 @@ class _ThemesScreenState extends State<ThemesScreen> {
final (coreId, gradeId) = parseBuiltinThemeId(next); final (coreId, gradeId) = parseBuiltinThemeId(next);
await Settings.selectedCoreThemeId.set(coreId); await Settings.selectedCoreThemeId.set(coreId);
await Settings.selectedGradeThemeId.set(gradeId); await Settings.selectedGradeThemeId.set(gradeId);
} else {
// select it first, the colors written next are then saved to this theme
await Settings.selectedThemeId.setSilently(next);
final code = _storedThemes.where((t) => t.id == next).firstOrNull?.code;
if (code != null && code.isNotEmpty) {
await applyThemeCode(widget.data.settings, code);
}
} }
setState(() => _selectedId = next); setState(() => _selectedId = next);
await Settings.selectedThemeId.set(next); await Settings.selectedThemeId.set(next);
@@ -136,6 +148,7 @@ class _ThemesScreenState extends State<ThemesScreen> {
name: name, name: name,
origin: ThemeOrigin.own, origin: ThemeOrigin.own,
swatch: UserTheme.swatchFromAppStyle(), swatch: UserTheme.swatchFromAppStyle(),
code: captureThemeCode(widget.data.settings),
); );
await _persistTheme(theme); await _persistTheme(theme);
if (!mounted) return; if (!mounted) return;
@@ -195,9 +208,7 @@ class _ThemesScreenState extends State<ThemesScreen> {
padding: const EdgeInsets.only(left: 4, bottom: 8, top: 16), padding: const EdgeInsets.only(left: 4, bottom: 8, top: 16),
child: Text( child: Text(
text, text,
style: appStyle.fonts.B_16R.apply( style: appStyle.fonts.B_16R.apply(color: appStyle.colors.textPrimary),
color: appStyle.colors.textPrimary,
),
), ),
); );
} }
@@ -221,7 +232,7 @@ class _ThemesScreenState extends State<ThemesScreen> {
onTap: () => _openTheme(theme), onTap: () => _openTheme(theme),
child: FirkaCard( child: FirkaCard(
left: [ left: [
ThemeSwatchIcon(swatch: theme.swatch, size: 36), ThemeSwatchIcon(swatch: theme.swatch, size: 26),
const SizedBox(width: 10), const SizedBox(width: 10),
ThemeNameLabel( ThemeNameLabel(
name: theme.name, name: theme.name,
@@ -248,8 +259,8 @@ class _ThemesScreenState extends State<ThemesScreen> {
FirkaIconWidget( FirkaIconWidget(
FirkaIconType.majesticons, FirkaIconType.majesticons,
icon, icon,
size: 20, size: 24,
color: appStyle.colors.textPrimary, color: appStyle.colors.accent,
), ),
const SizedBox(width: 8), const SizedBox(width: 8),
Text( Text(
@@ -348,7 +359,7 @@ class _ThemesScreenState extends State<ThemesScreen> {
children: [ children: [
_sectionLabel(l10n.s_c_themes_current), _sectionLabel(l10n.s_c_themes_current),
_themeRow(_selected, selected: true), _themeRow(_selected, selected: true),
if (!_selected.isBuiltin) if (_selected.canShare)
_actionRow( _actionRow(
icon: Majesticon.shareLine, icon: Majesticon.shareLine,
label: l10n.s_c_themes_share_current, label: l10n.s_c_themes_share_current,
@@ -364,10 +375,7 @@ class _ThemesScreenState extends State<ThemesScreen> {
selected: isBuiltinThemeId(_selectedId), selected: isBuiltinThemeId(_selectedId),
), ),
for (final theme in _ownThemes) for (final theme in _ownThemes)
_themeRow( _themeRow(theme, selected: theme.id == _selectedId),
theme,
selected: theme.id == _selectedId,
),
_actionRow( _actionRow(
icon: Majesticon.plusLine, icon: Majesticon.plusLine,
label: l10n.s_c_themes_create_new, label: l10n.s_c_themes_create_new,
@@ -375,10 +383,7 @@ class _ThemesScreenState extends State<ThemesScreen> {
), ),
_sectionLabel(l10n.s_c_themes_downloaded), _sectionLabel(l10n.s_c_themes_downloaded),
for (final theme in _downloadedThemes) for (final theme in _downloadedThemes)
_themeRow( _themeRow(theme, selected: theme.id == _selectedId),
theme,
selected: theme.id == _selectedId,
),
_actionRow( _actionRow(
icon: Majesticon.arrowDownCircleLine, icon: Majesticon.arrowDownCircleLine,
label: l10n.s_c_themes_import, label: l10n.s_c_themes_import,

View File

@@ -16,20 +16,36 @@ class UserTheme {
final ThemeOrigin origin; final ThemeOrigin origin;
List<Color> swatch; List<Color> swatch;
/// the whole theme as a share code, see [UserThemeModel.code]
String code;
/// the server handle this theme is tied to, empty until it is shared or
/// imported, see [UserThemeModel.shareId]
String shareId;
UserTheme({ UserTheme({
required this.id, required this.id,
required this.name, required this.name,
required this.origin, required this.origin,
required this.swatch, required this.swatch,
this.code = '',
this.shareId = '',
}); });
bool get isBuiltin => bool get isBuiltin => origin == ThemeOrigin.builtin || isBuiltinThemeId(id);
origin == ThemeOrigin.builtin || isBuiltinThemeId(id);
bool get isOwn => origin == ThemeOrigin.own && !isBuiltinThemeId(id); bool get isOwn => origin == ThemeOrigin.own && !isBuiltinThemeId(id);
bool get isDownloaded => origin == ThemeOrigin.downloaded; bool get isDownloaded => origin == ThemeOrigin.downloaded;
bool get canRename => isOwn; bool get canRename => isOwn;
bool get canEdit => isOwn;
bool get canDelete => !isBuiltin; bool get canDelete => !isBuiltin;
/// a copy of someone else's shared theme, so it follows their edits
bool get followsShare => isDownloaded && shareId.isNotEmpty;
/// builtins can always be shared (the code is computed on the fly),
/// custom themes can be shared once their code has been captured
bool get canShare => isBuiltin || code.isNotEmpty;
static List<Color> swatchFromCore(CoreTheme core, {bool isLight = true}) { static List<Color> swatchFromCore(CoreTheme core, {bool isLight = true}) {
final colors = core.forBrightness(isLight); final colors = core.forBrightness(isLight);
return [colors.accent, colors.textPrimary, colors.background]; return [colors.accent, colors.textPrimary, colors.background];
@@ -68,6 +84,8 @@ class UserTheme {
_ => ThemeOrigin.own, _ => ThemeOrigin.own,
}, },
swatch: model.swatchArgb.map(Color.new).toList(), swatch: model.swatchArgb.map(Color.new).toList(),
code: model.code,
shareId: model.shareId,
); );
} }
@@ -79,7 +97,9 @@ class UserTheme {
ThemeOrigin.downloaded => "downloaded", ThemeOrigin.downloaded => "downloaded",
ThemeOrigin.own || ThemeOrigin.builtin => "own", ThemeOrigin.own || ThemeOrigin.builtin => "own",
} }
..swatchArgb = swatch.map((c) => c.toARGB32()).toList(); ..swatchArgb = swatch.map((c) => c.toARGB32()).toList()
..code = code
..shareId = shareId;
} }
} }
@@ -98,29 +118,39 @@ class ThemeScreenArgs {
} }
extension UserThemeShareExtension on UserTheme { extension UserThemeShareExtension on UserTheme {
/// for builtins the code is computed from the core+grade themes,
/// for custom themes it comes from the stored code field
String get shareCode { String get shareCode {
if (isBuiltin) { if (isBuiltin) {
final core = resolveCore(id); final (coreId, gradeId) = parseBuiltinThemeId(id);
return ThemeBinaryFormat.encodeToBase64( final core = resolveCore(coreId);
ThemeBinaryFormat.decode(ThemeBinaryFormat.encodeCoreTheme(core)).colors, final grade = resolveGrade(gradeId);
final bytes = ThemeBinaryFormat.encodeCoreTheme(
core,
gradeColors: [
grade.light.grade1,
grade.light.grade2,
grade.light.grade3,
grade.light.grade4,
grade.light.grade5,
],
); );
} else if (swatch.isNotEmpty) { return ThemeBinaryFormat.toBase64(bytes);
return ThemeBinaryFormat.encodeToBase64(swatch);
} else {
return ThemeBinaryFormat.encodeToBase64([
appStyle.colors.accent,
appStyle.colors.textPrimary,
appStyle.colors.background,
]);
} }
return code;
} }
String get shareUrl => /// carries the whole theme so it imports with no network at all, plus the
/// share id so the copy can follow the owner's later edits
String get shareUrl {
final url =
"https://firka.app/?d=$shareCode&n=${Uri.encodeComponent(name)}"; "https://firka.app/?d=$shareCode&n=${Uri.encodeComponent(name)}";
return shareId.isEmpty ? url : "$url&s=$shareId";
}
} }
extension ThemeShareCodeStringExtension on String { extension ThemeShareCodeStringExtension on String {
({String code, String? name}) parseThemeSharePayload() { ({String code, String? name, String shareId}) parseThemeSharePayload() {
final trimmed = trim(); final trimmed = trim();
if (trimmed.startsWith('firka://') || trimmed.startsWith('http')) { if (trimmed.startsWith('firka://') || trimmed.startsWith('http')) {
final uri = Uri.tryParse(trimmed); final uri = Uri.tryParse(trimmed);
@@ -128,10 +158,11 @@ extension ThemeShareCodeStringExtension on String {
return ( return (
code: uri.queryParameters['d'] ?? trimmed, code: uri.queryParameters['d'] ?? trimmed,
name: uri.queryParameters['n'], name: uri.queryParameters['n'],
shareId: uri.queryParameters['s'] ?? '',
); );
} }
} }
return (code: trimmed, name: null); return (code: trimmed, name: null, shareId: '');
} }
ThemeBinaryData? tryDecodeThemeData() { ThemeBinaryData? tryDecodeThemeData() {

View File

@@ -4,27 +4,18 @@ class ThemeSwatchIcon extends StatelessWidget {
final List<Color> swatch; final List<Color> swatch;
final double size; final double size;
const ThemeSwatchIcon({ const ThemeSwatchIcon({required this.swatch, this.size = 40, super.key});
required this.swatch,
this.size = 40,
super.key,
});
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final colors = swatch.length >= 3 final colors = swatch.length >= 3
? swatch.take(3).toList() ? swatch.take(3).toList()
: [ : [...swatch, ...List.filled(3 - swatch.length, Colors.grey)];
...swatch,
...List.filled(3 - swatch.length, Colors.grey),
];
return SizedBox( return SizedBox(
width: size, width: size,
height: size, height: size,
child: CustomPaint( child: CustomPaint(painter: _SwatchPainter(colors: colors)),
painter: _SwatchPainter(colors: colors),
),
); );
} }
} }

View File

@@ -1,48 +1,201 @@
import 'package:firka/ui/phone/screens/themes/builtin_theme_id.dart';
import 'package:firka/ui/phone/screens/themes/user_theme.dart'; 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/ui/phone/screens/themes/widgets/theme_qr_card.dart';
import 'package:firka_common/ui/theme/core_theme.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_common/ui/theme/theme_binary_format.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
final _testGradeColors = [
resolveGrade(defaultGradeThemeId).light.grade1,
resolveGrade(defaultGradeThemeId).light.grade2,
resolveGrade(defaultGradeThemeId).light.grade3,
resolveGrade(defaultGradeThemeId).light.grade4,
resolveGrade(defaultGradeThemeId).light.grade5,
];
void main() { void main() {
group('Theme sharing binary format in firka', () { group('theme sharing binary format in firka', () {
test('encode and decode URL-safe base64 string for firkaCore', () { test('encode and decode url-safe base64 string for firkacore', () {
final bytes = ThemeBinaryFormat.encodeCoreTheme(firkaCore); final bytes = ThemeBinaryFormat.encodeCoreTheme(
firkaCore,
gradeColors: _testGradeColors,
);
final b64 = ThemeBinaryFormat.toBase64(bytes); final b64 = ThemeBinaryFormat.toBase64(bytes);
expect(b64.isNotEmpty, isTrue); expect(b64.isNotEmpty, isTrue);
final decodedBytes = ThemeBinaryFormat.fromBase64(b64); final decodedBytes = ThemeBinaryFormat.fromBase64(b64);
final decoded = ThemeBinaryFormat.decode(decodedBytes); final decoded = ThemeBinaryFormat.decode(decodedBytes);
final slots = decoded.toThemeSlots(); final slots = decoded.toThemeSlots();
expect(slots.light[ThemeColorSlot.background], firkaCore.light.background); expect(
slots.light[ThemeColorSlot.background],
firkaCore.light.background,
);
expect(slots.dark[ThemeColorSlot.background], firkaCore.dark.background); expect(slots.dark[ThemeColorSlot.background], firkaCore.dark.background);
expect(slots.light[ThemeColorSlot.accent], firkaCore.light.accent); expect(slots.light[ThemeColorSlot.accent], firkaCore.light.accent);
expect(slots.dark[ThemeColorSlot.accent], firkaCore.dark.accent); expect(slots.dark[ThemeColorSlot.accent], firkaCore.dark.accent);
}); });
test('builtin theme produces a share code', () {
final builtin = UserTheme.builtin(
'firka',
coreId: defaultCoreThemeId,
gradeId: defaultGradeThemeId,
);
expect(builtin.canShare, isTrue);
final code = builtin.shareCode;
expect(code.isNotEmpty, isTrue);
// the code round-trips back to valid binary data
final decoded = ThemeBinaryFormat.decodeFromBase64(code);
expect(decoded.gradeColors.length, 5);
final slots = decoded.toThemeSlots();
expect(slots.light[ThemeColorSlot.accent], firkaCore.light.accent);
});
test('custom theme without code cannot share', () {
final custom = UserTheme(
id: 'custom_1',
name: 'empty',
origin: ThemeOrigin.own,
swatch: const [Colors.red, Colors.white, Colors.black],
);
expect(custom.canShare, isFalse);
});
test('custom theme with code can share', () {
final bytes = ThemeBinaryFormat.encodeCoreTheme(
firkaCore,
gradeColors: _testGradeColors,
);
final code = ThemeBinaryFormat.toBase64(bytes);
final custom = UserTheme(
id: 'custom_2',
name: 'with code',
origin: ThemeOrigin.own,
swatch: const [Colors.red, Colors.white, Colors.black],
code: code,
);
expect(custom.canShare, isTrue);
expect(custom.shareCode, code);
});
test('share url includes name and code', () {
final bytes = ThemeBinaryFormat.encodeCoreTheme(
firkaCore,
gradeColors: _testGradeColors,
);
final code = ThemeBinaryFormat.toBase64(bytes);
final theme = UserTheme(
id: 'url_test',
name: 'Teszt Téma',
origin: ThemeOrigin.own,
swatch: const [Colors.red, Colors.white, Colors.black],
code: code,
);
final url = theme.shareUrl;
expect(url, contains('firka.app'));
expect(url, contains('d=$code'));
expect(url, contains('n='));
});
test('parse theme share payload from url', () {
final code = 'abc123';
final url = 'https://firka.app/?d=$code&n=My%20Theme';
final payload = url.parseThemeSharePayload();
expect(payload.code, code);
expect(payload.name, 'My Theme');
expect(payload.shareId, isEmpty);
});
test('an unpublished theme shares without a share id', () {
final theme = UserTheme(
id: 'unpublished',
name: 'Teszt',
origin: ThemeOrigin.own,
swatch: const [Colors.red, Colors.white, Colors.black],
code: 'abc123',
);
expect(theme.shareUrl, isNot(contains('&s=')));
});
test('a published theme carries both the code and the share id', () {
final theme = UserTheme(
id: 'published',
name: 'Teszt',
origin: ThemeOrigin.own,
swatch: const [Colors.red, Colors.white, Colors.black],
code: 'abc123',
shareId: 'f' * 32,
);
// the code imports with no network, the share id keeps it up to date
final payload = theme.shareUrl.parseThemeSharePayload();
expect(payload.code, 'abc123');
expect(payload.shareId, 'f' * 32);
expect(payload.name, 'Teszt');
});
test('an imported theme follows the share it came from', () {
final followed = UserTheme(
id: 'imported',
name: 'Teszt',
origin: ThemeOrigin.downloaded,
swatch: const [Colors.red, Colors.white, Colors.black],
code: 'abc123',
shareId: 'f' * 32,
);
expect(followed.followsShare, isTrue);
final pasted = UserTheme(
id: 'pasted',
name: 'Teszt',
origin: ThemeOrigin.downloaded,
swatch: const [Colors.red, Colors.white, Colors.black],
code: 'abc123',
);
expect(pasted.followsShare, isFalse);
});
test('sharing no longer freezes a theme', () {
final shared = UserTheme(
id: 'still_editable',
name: 'Teszt',
origin: ThemeOrigin.own,
swatch: const [Colors.red, Colors.white, Colors.black],
code: 'abc123',
shareId: 'f' * 32,
);
expect(shared.canEdit, isTrue);
expect(shared.canRename, isTrue);
});
test('parse theme share payload from plain code', () {
final code = 'abc123';
final payload = code.parseThemeSharePayload();
expect(payload.code, code);
expect(payload.name, isNull);
});
testWidgets('ThemeQrCard renders theme name and QR code', (tester) async { testWidgets('ThemeQrCard renders theme name and QR code', (tester) async {
final bytes = ThemeBinaryFormat.encodeCoreTheme(firkaCore); final bytes = ThemeBinaryFormat.encodeCoreTheme(
firkaCore,
gradeColors: _testGradeColors,
);
final b64 = ThemeBinaryFormat.toBase64(bytes); final b64 = ThemeBinaryFormat.toBase64(bytes);
final userTheme = UserTheme( final userTheme = UserTheme(
id: 'test_theme', id: 'test_theme',
name: 'Firka Green', name: 'Firka Green',
origin: ThemeOrigin.own, origin: ThemeOrigin.own,
swatch: const [ swatch: const [Color(0xFFA7DC22), Colors.white, Color(0xFF1E1E1E)],
Color(0xFFA7DC22),
Colors.white,
Color(0xFF1E1E1E),
],
); );
await tester.pumpWidget( await tester.pumpWidget(
MaterialApp( MaterialApp(
home: Scaffold( home: Scaffold(
body: Center( body: Center(
child: ThemeQrCard( child: ThemeQrCard(theme: userTheme, shareData: b64),
theme: userTheme,
shareData: b64,
),
), ),
), ),
), ),

View File

@@ -16,5 +16,14 @@ class UserThemeModel {
late List<int> swatchArgb; late List<int> swatchArgb;
/// the whole theme as a share code: the slots, the grade colors and the
/// gradients. empty for themes made before codes were stored.
String code = "";
/// the server handle this theme is tied to, empty until it is shared or
/// imported. the owner keeps editing a shared theme and everyone holding
/// the link follows along, so this is also what a copy refetches by.
String shareId = "";
UserThemeModel(); UserThemeModel();
} }

View File

@@ -25,46 +25,41 @@ enum ThemeColorSlot {
/// Decoded theme binary data. /// Decoded theme binary data.
class ThemeBinaryData { class ThemeBinaryData {
/// Format version (e.g. 0). /// format version, always [ThemeBinaryFormat.currentVersion].
final int version; final int version;
/// Ordered list of colors stored as raw bytes. /// the 32 slot colors: the 16 light slots, then the 16 dark slots.
final List<Color> colors; final List<Color> colors;
/// the five grade colors, grade 1 first.
final List<Color> gradeColors;
/// background gradient stops, empty when the theme has none.
final List<Color> gradientLight;
final List<Color> gradientDark;
const ThemeBinaryData({ const ThemeBinaryData({
required this.version, required this.version,
required this.colors, required this.colors,
required this.gradeColors,
required this.gradientLight,
required this.gradientDark,
}); });
/// True if the payload contains both light (0..15) and dark (16..31) slots. /// retrieves the color for [slot] in light mode.
bool get isFullTheme => colors.length >= 32; Color lightSlot(ThemeColorSlot slot) => colors[slot.index];
/// Retrieves the color for [slot] in light mode, or null if out of range. /// retrieves the color for [slot] in dark mode.
Color? lightSlot(ThemeColorSlot slot) { Color darkSlot(ThemeColorSlot slot) =>
final idx = slot.index; colors[ThemeColorSlot.values.length + 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. /// Extracts the full theme mapping for light and dark modes.
({Map<ThemeColorSlot, Color> light, Map<ThemeColorSlot, Color> dark}) toThemeSlots() { ({Map<ThemeColorSlot, Color> light, Map<ThemeColorSlot, Color> dark})
final lightMap = <ThemeColorSlot, Color>{}; toThemeSlots() {
final darkMap = <ThemeColorSlot, Color>{}; return (
light: {for (final slot in ThemeColorSlot.values) slot: lightSlot(slot)},
for (final slot in ThemeColorSlot.values) { dark: {for (final slot in ThemeColorSlot.values) slot: darkSlot(slot)},
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 @override
@@ -74,12 +69,22 @@ class ThemeBinaryData {
/// Binary encoder and decoder for Firka themes. /// Binary encoder and decoder for Firka themes.
/// ///
/// Format specification: /// format specification, one version only:
/// 1. Header: Varint storing the format version (e.g. `0x00` for version 0). /// 1. header: varint storing the format version, [currentVersion].
/// 2. Colors: Raw 32-bit ARGB bytes (4 bytes per color: Alpha, Red, Green, Blue). /// 2. the 32 slot colors: 16 light, then 16 dark.
/// 3. the 5 grade colors, grade 1 first.
/// 4. the light background gradient: a varint stop count, then the stops.
/// 5. the dark background gradient, the same way.
///
/// a color is 32-bit argb, 4 bytes: alpha, red, green, blue.
class ThemeBinaryFormat { class ThemeBinaryFormat {
/// Current binary format version. /// the only binary format version, anything else is refused.
static const int currentVersion = 0; static const int currentVersion = 1;
static const int gradeColorCount = 5;
/// more stops than the editor allows is not a theme.
static const int maxGradientStops = 16;
/// Encodes [value] into a standard unsigned LEB128 varint. /// Encodes [value] into a standard unsigned LEB128 varint.
static void writeVarint(BytesBuilder builder, int value) { static void writeVarint(BytesBuilder builder, int value) {
@@ -96,7 +101,10 @@ class ThemeBinaryFormat {
/// Reads a standard unsigned LEB128 varint from [bytes] starting at [offset]. /// Reads a standard unsigned LEB128 varint from [bytes] starting at [offset].
/// Returns a record of `(value, bytesRead)`. /// Returns a record of `(value, bytesRead)`.
static (int value, int bytesRead) readVarint(Uint8List bytes, [int offset = 0]) { static (int value, int bytesRead) readVarint(
Uint8List bytes, [
int offset = 0,
]) {
var result = 0; var result = 0;
var shift = 0; var shift = 0;
var index = offset; var index = offset;
@@ -112,24 +120,12 @@ class ThemeBinaryFormat {
throw const FormatException('Varint overflow'); throw const FormatException('Varint overflow');
} }
} }
throw const FormatException('Unexpected end of buffer while reading varint'); throw const FormatException(
'Unexpected end of buffer while reading varint',
);
} }
/// Encodes a list of [colors] into the binary theme format. static void _writeColor(BytesBuilder builder, Color color) {
///
/// 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<Color> 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(); final argb = color.toARGB32();
builder.addByte((argb >> 24) & 0xFF); builder.addByte((argb >> 24) & 0xFF);
builder.addByte((argb >> 16) & 0xFF); builder.addByte((argb >> 16) & 0xFF);
@@ -137,69 +133,112 @@ class ThemeBinaryFormat {
builder.addByte(argb & 0xFF); builder.addByte(argb & 0xFF);
} }
return builder.takeBytes(); /// decodes raw binary theme [bytes], throws a [FormatException] for anything
} /// that is not a complete theme of the current version.
/// 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) { static ThemeBinaryData decode(Uint8List bytes) {
if (bytes.isEmpty) { if (bytes.isEmpty) {
throw const FormatException('Cannot decode empty theme bytes'); throw const FormatException('Cannot decode empty theme bytes');
} }
// 1. Read version varint
final (version, headerLength) = readVarint(bytes, 0); final (version, headerLength) = readVarint(bytes, 0);
if (version != currentVersion) {
throw FormatException('Unsupported theme version $version');
}
final colorByteLength = bytes.length - headerLength; var offset = headerLength;
if (colorByteLength % 4 != 0) {
throw FormatException( List<Color> readColors(int count) {
'Invalid color byte length ($colorByteLength). ' if (offset + count * 4 > bytes.length) {
'Color bytes must be a multiple of 4.', throw const FormatException('Theme data ends too early');
}
final colors = <Color>[];
for (var i = 0; i < count; i++) {
colors.add(
Color.fromARGB(
bytes[offset],
bytes[offset + 1],
bytes[offset + 2],
bytes[offset + 3],
),
);
offset += 4;
}
return colors;
}
List<Color> readGradient() {
final (count, read) = readVarint(bytes, offset);
offset += read;
if (count > maxGradientStops) {
throw FormatException('Too many gradient stops ($count)');
}
return readColors(count);
}
final colors = readColors(ThemeColorSlot.values.length * 2);
final gradeColors = readColors(gradeColorCount);
final gradientLight = readGradient();
final gradientDark = readGradient();
if (offset != bytes.length) {
throw const FormatException('Unexpected data after the theme');
}
return ThemeBinaryData(
version: version,
colors: colors,
gradeColors: gradeColors,
gradientLight: gradientLight,
gradientDark: gradientDark,
); );
} }
final colorCount = colorByteLength ~/ 4; /// encodes a complete theme: the 16 light and 16 dark slots, the grade
final colors = <Color>[]; /// colors (grade 1 first) and the two background gradients.
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({ static Uint8List encodeFullTheme({
required Map<ThemeColorSlot, Color> light, required Map<ThemeColorSlot, Color> light,
required Map<ThemeColorSlot, Color> dark, required Map<ThemeColorSlot, Color> dark,
int version = currentVersion, required List<Color> gradeColors,
List<Color> gradientLight = const [],
List<Color> gradientDark = const [],
}) { }) {
final colors = <Color>[]; if (gradeColors.length != gradeColorCount) {
throw ArgumentError.value(
// Light slots (0..15) gradeColors.length,
for (final slot in ThemeColorSlot.values) { 'gradeColors',
colors.add(light[slot] ?? Colors.transparent); 'A theme has $gradeColorCount grade colors',
);
}
if (gradientLight.length > maxGradientStops ||
gradientDark.length > maxGradientStops) {
throw ArgumentError('A gradient has at most $maxGradientStops stops');
} }
// Dark slots (16..31) final builder = BytesBuilder(copy: false);
writeVarint(builder, currentVersion);
for (final slot in ThemeColorSlot.values) { for (final slot in ThemeColorSlot.values) {
colors.add(dark[slot] ?? light[slot] ?? Colors.transparent); _writeColor(builder, light[slot] ?? Colors.transparent);
} }
for (final slot in ThemeColorSlot.values) {
return encode(colors: colors, version: version); _writeColor(builder, dark[slot] ?? light[slot] ?? Colors.transparent);
}
for (final color in gradeColors) {
_writeColor(builder, color);
}
for (final stops in [gradientLight, gradientDark]) {
writeVarint(builder, stops.length);
for (final color in stops) {
_writeColor(builder, color);
}
}
return builder.takeBytes();
} }
/// Encodes a [CoreTheme] (both light and dark colors) into binary. /// Encodes a [CoreTheme] (both light and dark colors) into binary.
static Uint8List encodeCoreTheme( static Uint8List encodeCoreTheme(
CoreTheme theme, { CoreTheme theme, {
int version = currentVersion, required List<Color> gradeColors,
List<Color> gradientLight = const [],
List<Color> gradientDark = const [],
}) { }) {
Color getSlot(CoreThemeColors c, ThemeColorSlot slot) => switch (slot) { Color getSlot(CoreThemeColors c, ThemeColorSlot slot) => switch (slot) {
ThemeColorSlot.accent => c.accent, ThemeColorSlot.accent => c.accent,
@@ -221,13 +260,20 @@ class ThemeBinaryFormat {
}; };
final lightMap = { final lightMap = {
for (final slot in ThemeColorSlot.values) slot: getSlot(theme.light, slot), for (final slot in ThemeColorSlot.values)
slot: getSlot(theme.light, slot),
}; };
final darkMap = { final darkMap = {
for (final slot in ThemeColorSlot.values) slot: getSlot(theme.dark, slot), for (final slot in ThemeColorSlot.values) slot: getSlot(theme.dark, slot),
}; };
return encodeFullTheme(light: lightMap, dark: darkMap, version: version); return encodeFullTheme(
light: lightMap,
dark: darkMap,
gradeColors: gradeColors,
gradientLight: gradientLight,
gradientDark: gradientDark,
);
} }
/// Encodes [bytes] to Base64 (URL-safe without padding by default). /// Encodes [bytes] to Base64 (URL-safe without padding by default).
@@ -246,16 +292,6 @@ class ThemeBinaryFormat {
return base64Url.decode(normalized); return base64Url.decode(normalized);
} }
/// Convenience method: Encodes [colors] directly into a URL-safe Base64 string.
static String encodeToBase64(
List<Color> 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]. /// Convenience method: Decodes a URL-safe Base64 string into [ThemeBinaryData].
static ThemeBinaryData decodeFromBase64(String encoded) { static ThemeBinaryData decodeFromBase64(String encoded) {
final bytes = fromBase64(encoded); final bytes = fromBase64(encoded);

View File

@@ -33,39 +33,14 @@ void main() {
test('throws on negative varint', () { test('throws on negative varint', () {
final builder = BytesBuilder(); final builder = BytesBuilder();
expect(() => ThemeBinaryFormat.writeVarint(builder, -1), throwsArgumentError); expect(
() => ThemeBinaryFormat.writeVarint(builder, -1),
throwsArgumentError,
);
}); });
}); });
group('ThemeBinaryFormat color encoding', () { 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 = { final lightMap = {
for (final slot in ThemeColorSlot.values) for (final slot in ThemeColorSlot.values)
slot: Color((0xFF000000 + slot.index * 0x0F0F0F) & 0xFFFFFFFF), slot: Color((0xFF000000 + slot.index * 0x0F0F0F) & 0xFFFFFFFF),
@@ -74,18 +49,50 @@ void main() {
for (final slot in ThemeColorSlot.values) for (final slot in ThemeColorSlot.values)
slot: Color((0xFF111111 + slot.index * 0x0E0E0E) & 0xFFFFFFFF), slot: Color((0xFF111111 + slot.index * 0x0E0E0E) & 0xFFFFFFFF),
}; };
const grades = [
Color(0xFFFF54A1),
Color(0xFFFFA046),
Color(0xFFF9CF00),
Color(0xFF92EA3B),
Color(0xFF22CCAD),
];
const gradientLight = [Color(0xFFFAFFF0), Color(0xFFE8F7C8)];
const gradientDark = [
Color(0xFF0D1202),
Color(0xFF1A2405),
Color(0x80000000),
];
test('stores colors as 4 raw ARGB bytes after the version', () {
final bytes = ThemeBinaryFormat.encodeFullTheme(
light: {ThemeColorSlot.accent: const Color(0xFFFF0000)},
dark: {ThemeColorSlot.accent: const Color(0x8000FF00)},
gradeColors: grades,
);
expect(bytes[0], ThemeBinaryFormat.currentVersion);
// the first light slot, then (after the other 15) the first dark slot
expect(bytes.sublist(1, 5), equals([0xFF, 0xFF, 0x00, 0x00]));
expect(bytes.sublist(65, 69), equals([0x80, 0x00, 0xFF, 0x00]));
});
test('round-trips a complete theme', () {
final bytes = ThemeBinaryFormat.encodeFullTheme( final bytes = ThemeBinaryFormat.encodeFullTheme(
light: lightMap, light: lightMap,
dark: darkMap, dark: darkMap,
gradeColors: grades,
gradientLight: gradientLight,
gradientDark: gradientDark,
); );
expect(bytes.length, 129); // version, 32 slots, 5 grades, two counts and 2 + 3 stops
expect(bytes[0], 0x00); expect(bytes.length, 1 + 32 * 4 + 5 * 4 + 1 + 2 * 4 + 1 + 3 * 4);
final decoded = ThemeBinaryFormat.decode(bytes); final decoded = ThemeBinaryFormat.decode(bytes);
expect(decoded.version, 0); expect(decoded.version, ThemeBinaryFormat.currentVersion);
expect(decoded.isFullTheme, isTrue); expect(decoded.gradeColors, equals(grades));
expect(decoded.gradientLight, equals(gradientLight));
expect(decoded.gradientDark, equals(gradientDark));
final slots = decoded.toThemeSlots(); final slots = decoded.toThemeSlots();
for (final slot in ThemeColorSlot.values) { for (final slot in ThemeColorSlot.values) {
@@ -94,39 +101,96 @@ void main() {
} }
}); });
test('round-trips CoreTheme (firkaCore)', () { test('a theme without gradients round-trips with empty gradients', () {
final bytes = ThemeBinaryFormat.encodeCoreTheme(firkaCore); final decoded = ThemeBinaryFormat.decode(
expect(bytes.length, 129); ThemeBinaryFormat.encodeFullTheme(
light: lightMap,
dark: darkMap,
gradeColors: grades,
),
);
expect(decoded.gradientLight, isEmpty);
expect(decoded.gradientDark, isEmpty);
});
final decoded = ThemeBinaryFormat.decode(bytes); test('round-trips CoreTheme (firkaCore)', () {
expect(decoded.version, 0); final decoded = ThemeBinaryFormat.decode(
ThemeBinaryFormat.encodeCoreTheme(firkaCore, gradeColors: grades),
);
final slots = decoded.toThemeSlots(); final slots = decoded.toThemeSlots();
expect(slots.light[ThemeColorSlot.accent], firkaCore.light.accent); expect(slots.light[ThemeColorSlot.accent], firkaCore.light.accent);
expect(slots.light[ThemeColorSlot.background], firkaCore.light.background); expect(
slots.light[ThemeColorSlot.background],
firkaCore.light.background,
);
expect(slots.dark[ThemeColorSlot.accent], firkaCore.dark.accent); expect(slots.dark[ThemeColorSlot.accent], firkaCore.dark.accent);
expect(slots.dark[ThemeColorSlot.background], firkaCore.dark.background); expect(slots.dark[ThemeColorSlot.background], firkaCore.dark.background);
}); });
test('throws on malformed binary data', () { test('refuses a theme with the wrong number of grade colors', () {
expect(() => ThemeBinaryFormat.decode(Uint8List(0)), throwsFormatException);
expect( expect(
() => ThemeBinaryFormat.decode(Uint8List.fromList([0x00, 0xFF, 0x00, 0x00])), () => ThemeBinaryFormat.encodeFullTheme(
light: lightMap,
dark: darkMap,
gradeColors: grades.take(3).toList(),
),
throwsArgumentError,
);
});
test('refuses everything that is not a complete theme of this version', () {
final good = ThemeBinaryFormat.encodeFullTheme(
light: lightMap,
dark: darkMap,
gradeColors: grades,
gradientLight: gradientLight,
);
expect(
() => ThemeBinaryFormat.decode(Uint8List(0)),
throwsFormatException,
);
// an old three color code
expect(
() => ThemeBinaryFormat.decode(
Uint8List.fromList([0x00, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF]),
),
throwsFormatException,
);
// another version
expect(
() =>
ThemeBinaryFormat.decode(Uint8List.fromList([2, ...good.skip(1)])),
throwsFormatException,
);
// cut short and with extra bytes
expect(
() => ThemeBinaryFormat.decode(good.sublist(0, good.length - 2)),
throwsFormatException,
);
expect(
() => ThemeBinaryFormat.decode(Uint8List.fromList([...good, 0])),
throwsFormatException, throwsFormatException,
); );
}); });
test('Base64 and URL-safe serialization', () { test('Base64 and URL-safe serialization', () {
final colors = [const Color(0xFFA7DC22), const Color(0xFFFAFFF0)]; final bytes = ThemeBinaryFormat.encodeFullTheme(
final b64 = ThemeBinaryFormat.encodeToBase64(colors); light: lightMap,
dark: darkMap,
gradeColors: grades,
gradientLight: gradientLight,
);
final b64 = ThemeBinaryFormat.toBase64(bytes);
expect(b64.contains('/'), isFalse); expect(b64.contains('/'), isFalse);
expect(b64.contains('+'), isFalse); expect(b64.contains('+'), isFalse);
expect(b64.contains('='), isFalse); expect(b64.contains('='), isFalse);
final decoded = ThemeBinaryFormat.decodeFromBase64(b64); final decoded = ThemeBinaryFormat.decodeFromBase64(b64);
expect(decoded.version, 0); expect(decoded.version, ThemeBinaryFormat.currentVersion);
expect(decoded.colors, equals(colors)); expect(decoded.gradientLight, equals(gradientLight));
}); });
}); });
} }