added support for overriding locales

This commit is contained in:
Fabian Freund
2025-10-20 16:21:10 +02:00
parent aca0767d9a
commit 1c7e9ec741
66 changed files with 1679 additions and 7 deletions
+1
View File
@@ -45,6 +45,7 @@ import 'package:weblibre/features/settings/presentation/screens/developer_settin
import 'package:weblibre/features/settings/presentation/screens/doh_settings.dart';
import 'package:weblibre/features/settings/presentation/screens/fingerprint_settings.dart';
import 'package:weblibre/features/settings/presentation/screens/general_settings.dart';
import 'package:weblibre/features/settings/presentation/screens/locale_settings.dart';
import 'package:weblibre/features/settings/presentation/screens/settings.dart';
import 'package:weblibre/features/settings/presentation/screens/web_engine_hardening.dart';
import 'package:weblibre/features/settings/presentation/screens/web_engine_hardening_group.dart';
+26
View File
@@ -116,6 +116,11 @@ RouteBase get $settingsRoute => GoRouteData.$route(
name: 'FingerprintSettingsRoute',
factory: $FingerprintSettingsRoute._fromState,
),
GoRouteData.$route(
path: 'locales',
name: 'LocaleSettingsRoute',
factory: $LocaleSettingsRoute._fromState,
),
],
),
GoRouteData.$route(
@@ -306,6 +311,27 @@ mixin $FingerprintSettingsRoute on GoRouteData {
void replace(BuildContext context) => context.replace(location);
}
mixin $LocaleSettingsRoute on GoRouteData {
static LocaleSettingsRoute _fromState(GoRouterState state) =>
LocaleSettingsRoute();
@override
String get location => GoRouteData.$location('/settings/web_engine/locales');
@override
void go(BuildContext context) => context.go(location);
@override
Future<T?> push<T>(BuildContext context) => context.push<T>(location);
@override
void pushReplacement(BuildContext context) =>
context.pushReplacement(location);
@override
void replace(BuildContext context) => context.replace(location);
}
mixin $DeveloperSettingsRoute on GoRouteData {
static DeveloperSettingsRoute _fromState(GoRouterState state) =>
DeveloperSettingsRoute();
+11
View File
@@ -47,6 +47,10 @@ part of 'routes.dart';
name: 'FingerprintSettingsRoute',
path: 'fingerprint',
),
TypedGoRoute<LocaleSettingsRoute>(
name: 'LocaleSettingsRoute',
path: 'locales',
),
],
),
TypedGoRoute<DeveloperSettingsRoute>(
@@ -97,6 +101,13 @@ class FingerprintSettingsRoute extends GoRouteData
}
}
class LocaleSettingsRoute extends GoRouteData with $LocaleSettingsRoute {
@override
Widget build(BuildContext context, GoRouterState state) {
return const LocaleSettingsScreen();
}
}
class WebEngineSettingsRoute extends GoRouteData with $WebEngineSettingsRoute {
@override
Widget build(BuildContext context, GoRouterState state) {
@@ -0,0 +1,39 @@
import 'package:flutter/widgets.dart' hide Locale;
import 'package:intl/locale.dart' as intl;
import 'package:locale_resolver/locale_resolver.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:weblibre/extensions/locale.dart';
part 'locale_resolver.g.dart';
@Riverpod(keepAlive: true)
class LocaleResolverRepository extends _$LocaleResolverRepository {
final _service = LocaleResolver();
final _cache = <intl.Locale, LocalizedResult>{};
Future<LocalizedResult> resolve(intl.Locale locale) async {
final cached = _cache[locale];
if (cached != null) {
return cached;
}
return _cache[locale] = await _service.resolve(
locale.toLanguageTag(),
targetLocale.toLanguageTag(),
);
}
@override
void build(intl.Locale targetLocale) {}
}
@Riverpod()
Future<LocalizedResult> resolveLocale(Ref ref, intl.Locale locale) {
return ref
.read(
localeResolverRepositoryProvider(
WidgetsBinding.instance.platformDispatcher.locale.toIntlLocale(),
).notifier,
)
.resolve(locale);
}
@@ -0,0 +1,185 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'locale_resolver.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(LocaleResolverRepository)
const localeResolverRepositoryProvider = LocaleResolverRepositoryFamily._();
final class LocaleResolverRepositoryProvider
extends $NotifierProvider<LocaleResolverRepository, void> {
const LocaleResolverRepositoryProvider._({
required LocaleResolverRepositoryFamily super.from,
required intl.Locale super.argument,
}) : super(
retry: null,
name: r'localeResolverRepositoryProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$localeResolverRepositoryHash();
@override
String toString() {
return r'localeResolverRepositoryProvider'
''
'($argument)';
}
@$internal
@override
LocaleResolverRepository create() => LocaleResolverRepository();
/// {@macro riverpod.override_with_value}
Override overrideWithValue(void value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<void>(value),
);
}
@override
bool operator ==(Object other) {
return other is LocaleResolverRepositoryProvider &&
other.argument == argument;
}
@override
int get hashCode {
return argument.hashCode;
}
}
String _$localeResolverRepositoryHash() =>
r'dc74908d6ac1f5cc851e2a10dcf33b0dc68b5b15';
final class LocaleResolverRepositoryFamily extends $Family
with
$ClassFamilyOverride<
LocaleResolverRepository,
void,
void,
void,
intl.Locale
> {
const LocaleResolverRepositoryFamily._()
: super(
retry: null,
name: r'localeResolverRepositoryProvider',
dependencies: null,
$allTransitiveDependencies: null,
isAutoDispose: false,
);
LocaleResolverRepositoryProvider call(intl.Locale targetLocale) =>
LocaleResolverRepositoryProvider._(argument: targetLocale, from: this);
@override
String toString() => r'localeResolverRepositoryProvider';
}
abstract class _$LocaleResolverRepository extends $Notifier<void> {
late final _$args = ref.$arg as intl.Locale;
intl.Locale get targetLocale => _$args;
void build(intl.Locale targetLocale);
@$mustCallSuper
@override
void runBuild() {
build(_$args);
final ref = this.ref as $Ref<void, void>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<void, void>,
void,
Object?,
Object?
>;
element.handleValue(ref, null);
}
}
@ProviderFor(resolveLocale)
const resolveLocaleProvider = ResolveLocaleFamily._();
final class ResolveLocaleProvider
extends
$FunctionalProvider<
AsyncValue<LocalizedResult>,
LocalizedResult,
FutureOr<LocalizedResult>
>
with $FutureModifier<LocalizedResult>, $FutureProvider<LocalizedResult> {
const ResolveLocaleProvider._({
required ResolveLocaleFamily super.from,
required intl.Locale super.argument,
}) : super(
retry: null,
name: r'resolveLocaleProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$resolveLocaleHash();
@override
String toString() {
return r'resolveLocaleProvider'
''
'($argument)';
}
@$internal
@override
$FutureProviderElement<LocalizedResult> $createElement(
$ProviderPointer pointer,
) => $FutureProviderElement(pointer);
@override
FutureOr<LocalizedResult> create(Ref ref) {
final argument = this.argument as intl.Locale;
return resolveLocale(ref, argument);
}
@override
bool operator ==(Object other) {
return other is ResolveLocaleProvider && other.argument == argument;
}
@override
int get hashCode {
return argument.hashCode;
}
}
String _$resolveLocaleHash() => r'94d7a9b307a81de372b8b40b06f046acc76e01c8';
final class ResolveLocaleFamily extends $Family
with $FunctionalFamilyOverride<FutureOr<LocalizedResult>, intl.Locale> {
const ResolveLocaleFamily._()
: super(
retry: null,
name: r'resolveLocaleProvider',
dependencies: null,
$allTransitiveDependencies: null,
isAutoDispose: true,
);
ResolveLocaleProvider call(intl.Locale locale) =>
ResolveLocaleProvider._(argument: locale, from: this);
@override
String toString() => r'resolveLocaleProvider';
}
+27
View File
@@ -0,0 +1,27 @@
import 'dart:ui' as ui;
import 'package:intl/locale.dart' as intl;
extension LocaleFormat on intl.Locale {
String rawToString(String separator) {
final StringBuffer out = StringBuffer(languageCode);
if (scriptCode != null && scriptCode!.isNotEmpty) {
out.write('$separator$scriptCode');
}
final String? countryCode = this.countryCode;
if (countryCode != null && countryCode.isNotEmpty) {
out.write('$separator${this.countryCode}');
}
return out.toString();
}
}
extension LocaleConverter on ui.Locale {
intl.Locale toIntlLocale() {
return intl.Locale.fromSubtags(
languageCode: languageCode,
countryCode: countryCode,
scriptCode: scriptCode,
);
}
}
@@ -17,6 +17,7 @@
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'package:collection/collection.dart';
import 'package:flutter/material.dart' show ThemeMode;
import 'package:flutter_mozilla_components/flutter_mozilla_components.dart';
import 'package:riverpod/riverpod.dart';
@@ -141,6 +142,18 @@ class EngineSettingsReplicationService
.read(preferenceFixatorProvider.notifier)
.register('pdfjs.disabled', !settings.enablePdfJs);
}
if (!const DeepCollectionEquality.unordered().equals(
previous.value?.locales,
settings.locales,
)) {
// ignore: only_use_keep_alive_inside_keep_alive
await ref
.read(preferenceFixatorProvider.notifier)
.register(
'intl.accept_languages',
settings.locales.join(','),
);
}
} else {
await _service.setDefaultSettings(settings);
@@ -149,6 +162,11 @@ class EngineSettingsReplicationService
.read(preferenceFixatorProvider.notifier)
.register('pdfjs.disabled', !settings.enablePdfJs);
// ignore: only_use_keep_alive_inside_keep_alive
await ref
.read(preferenceFixatorProvider.notifier)
.register('intl.accept_languages', settings.locales.join(','));
initialSettingsSent = true;
}
}
@@ -44,7 +44,7 @@ final class EngineSettingsReplicationServiceProvider
}
String _$engineSettingsReplicationServiceHash() =>
r'd28cc58a94f45008a478bf52a9c40d61811b591d';
r'7583ebc8ca9c11377486ff5a3e763493dcdc903a';
abstract class _$EngineSettingsReplicationService extends $Notifier<void> {
void build();
@@ -25,8 +25,6 @@ class PreferenceChangeListener extends _$PreferenceChangeListener {
@Riverpod()
class PreferenceFixator extends _$PreferenceFixator {
Future<void> register(String name, Object value) async {
await GeckoPrefService().applyPrefs({name: value});
state = {...state}
..update(
name,
@@ -36,6 +34,8 @@ class PreferenceFixator extends _$PreferenceFixator {
return value;
},
);
await GeckoPrefService().applyPrefs({name: value});
}
Future<void> unregister(String name) async {
@@ -87,7 +87,7 @@ final class PreferenceFixatorProvider
}
}
String _$preferenceFixatorHash() => r'dfa323859c660d3db74dba7297e2a33b758ed78a';
String _$preferenceFixatorHash() => r'c76245d5c420e2e3f6c026f23c017c939b69ef59';
abstract class _$PreferenceFixator extends $Notifier<Map<String, Object>> {
Map<String, Object> build();
@@ -0,0 +1,148 @@
import 'package:country_flags/country_flags.dart';
import 'package:fast_equatable/fast_equatable.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:intl/locale.dart';
import 'package:nullability/nullability.dart';
import 'package:weblibre/domain/repositories/locale_resolver.dart';
import 'package:weblibre/extensions/locale.dart';
import 'package:weblibre/features/settings/presentation/controllers/save_settings.dart';
import 'package:weblibre/features/user/data/models/engine_settings.dart';
import 'package:weblibre/features/user/domain/repositories/engine_settings.dart';
class LocaleSettingsScreen extends HookConsumerWidget {
const LocaleSettingsScreen();
@override
Widget build(BuildContext context, WidgetRef ref) {
final formKey = useMemoized(() => GlobalKey<FormState>());
final systemLocales = useMemoized(
() => WidgetsBinding.instance.platformDispatcher.locales
.map((locale) => locale.toIntlLocale())
.toList(),
);
final userLocales = ref.watch(
engineSettingsWithDefaultsProvider.select(
(settings) => EquatableValue(
settings.locales.map(Locale.tryParse).nonNulls.toSet(),
),
),
);
final availableLocales = {
...systemLocales,
...userLocales.value,
Locale.fromSubtags(languageCode: 'en', countryCode: 'US'),
};
final customLocaleController = useTextEditingController();
return Scaffold(
appBar: AppBar(title: const Text('Browser Languages')),
body: SafeArea(
child: ListView(
children: [
...availableLocales.map((locale) {
return CheckboxListTile.adaptive(
value: userLocales.value.contains(locale),
onChanged: (value) async {
if (value != null) {
await ref
.read(saveEngineSettingsControllerProvider.notifier)
.save(
(currentSettings) => currentSettings.copyWith.locales(
value
? {
...currentSettings.locales,
locale.toLanguageTag(),
}.toList()
: ([
...currentSettings.locales,
]..remove(locale.toLanguageTag())).toList(),
),
);
}
},
title: Consumer(
builder: (context, ref, child) {
final resolvedAsync = ref.watch(
resolveLocaleProvider(locale),
);
return Text(
resolvedAsync.maybeWhen(
data: (data) =>
data.mapNotNull(
(data) =>
'${data.languageName} ${data.countryName.mapNotNull((country) => '($country)') ?? ''}'
.trim(),
) ??
locale.toLanguageTag(),
orElse: () => locale.toLanguageTag(),
),
);
},
),
subtitle: Text(locale.toLanguageTag()),
secondary: CountryFlag.fromLanguageCode(
locale.languageCode,
theme: const ImageTheme(shape: RoundedRectangle(8.0)),
),
);
}),
const Divider(),
Padding(
padding: const EdgeInsets.only(left: 16.0, right: 20),
child: Form(
key: formKey,
child: TextFormField(
controller: customLocaleController,
decoration: InputDecoration(
label: const Text('Custom Locale'),
hint: const Text('en-US'),
floatingLabelBehavior: FloatingLabelBehavior.always,
suffixIcon: IconButton(
onPressed: () {
if (formKey.currentState?.validate() == true) {
formKey.currentState?.save();
}
},
icon: const Icon(Icons.add),
),
),
validator: (value) {
if (value != null && Locale.tryParse(value) == null) {
return 'Invalid locale identifier';
}
return null;
},
onSaved: (newValue) async {
if (newValue != null) {
await ref
.read(saveEngineSettingsControllerProvider.notifier)
.save(
(currentSettings) =>
currentSettings.copyWith.locales(
{
...currentSettings.locales,
Locale.parse(newValue).toLanguageTag(),
}.toList(),
),
);
customLocaleController.clear();
}
},
),
),
),
],
),
),
);
}
}
@@ -203,6 +203,18 @@ class WebEngineSettingsScreen extends HookConsumerWidget {
],
),
),
ListTile(
title: const Text('Browser Languages'),
contentPadding: const EdgeInsets.symmetric(
vertical: 8.0,
horizontal: 16.0,
),
leading: const Icon(MdiIcons.translate),
trailing: const Icon(Icons.chevron_right),
onTap: () async {
await LocaleSettingsRoute().push(context);
},
),
SwitchListTile.adaptive(
title: const Text('Global Privacy Control (GPC)'),
secondary: const Icon(MdiIcons.incognitoCircleOff),
@@ -21,6 +21,7 @@ import 'dart:convert';
import 'package:copy_with_extension/copy_with_extension.dart';
import 'package:fast_equatable/fast_equatable.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_mozilla_components/flutter_mozilla_components.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:nullability/nullability.dart';
@@ -75,6 +76,9 @@ class EngineSettings extends GeckoEngineSettings with FastEquatable {
@override
bool get enterpriseRootsEnabled => super.enterpriseRootsEnabled!;
@override
List<String> get locales => super.locales!;
final QueryParameterStripping queryParameterStripping;
final BounceTrackingProtectionMode bounceTrackingProtectionMode;
@@ -130,6 +134,7 @@ class EngineSettings extends GeckoEngineSettings with FastEquatable {
required this.dohExceptionsList,
required super.fingerprintingProtectionOverrides,
required this.enablePdfJs,
required super.locales,
});
EngineSettings.withDefaults({
@@ -154,6 +159,7 @@ class EngineSettings extends GeckoEngineSettings with FastEquatable {
List<String>? dohExceptionsList,
String? fingerprintingProtectionOverrides,
bool? enablePdfJs,
List<String>? locales,
}) : queryParameterStripping =
queryParameterStripping ?? QueryParameterStripping.disabled,
bounceTrackingProtectionMode =
@@ -188,6 +194,11 @@ class EngineSettings extends GeckoEngineSettings with FastEquatable {
fingerprintingProtectionOverrides:
fingerprintingProtectionOverrides ??
FingerprintOverrides.defaults().toString(),
locales:
locales ??
WidgetsBinding.instance.platformDispatcher.locales
.map((x) => x.toLanguageTag())
.toList(),
);
static AddonCollection? _addonCollectionFromJson(String? json) =>
@@ -226,5 +237,6 @@ class EngineSettings extends GeckoEngineSettings with FastEquatable {
dohExceptionsList,
fingerprintingProtectionOverrides,
enablePdfJs,
locales,
];
}
@@ -67,6 +67,8 @@ abstract class _$EngineSettingsCWProxy {
EngineSettings enablePdfJs(bool enablePdfJs);
EngineSettings locales(List<String>? locales);
/// Creates a new instance with the provided field values.
/// Passing `null` to a nullable field nullifies it, while `null` for a non-nullable field is ignored. To update a single field use `EngineSettings(...).copyWith.fieldName(value)`.
///
@@ -96,6 +98,7 @@ abstract class _$EngineSettingsCWProxy {
List<String> dohExceptionsList,
String? fingerprintingProtectionOverrides,
bool enablePdfJs,
List<String>? locales,
});
}
@@ -207,6 +210,9 @@ class _$EngineSettingsCWProxyImpl implements _$EngineSettingsCWProxy {
EngineSettings enablePdfJs(bool enablePdfJs) =>
call(enablePdfJs: enablePdfJs);
@override
EngineSettings locales(List<String>? locales) => call(locales: locales);
@override
/// Creates a new instance with the provided field values.
/// Passing `null` to a nullable field nullifies it, while `null` for a non-nullable field is ignored. To update a single field use `EngineSettings(...).copyWith.fieldName(value)`.
@@ -239,6 +245,7 @@ class _$EngineSettingsCWProxyImpl implements _$EngineSettingsCWProxy {
Object? dohExceptionsList = const $CopyWithPlaceholder(),
Object? fingerprintingProtectionOverrides = const $CopyWithPlaceholder(),
Object? enablePdfJs = const $CopyWithPlaceholder(),
Object? locales = const $CopyWithPlaceholder(),
}) {
return EngineSettings(
javascriptEnabled: javascriptEnabled == const $CopyWithPlaceholder()
@@ -350,6 +357,10 @@ class _$EngineSettingsCWProxyImpl implements _$EngineSettingsCWProxy {
? _value.enablePdfJs
// ignore: cast_nullable_to_non_nullable
: enablePdfJs as bool,
locales: locales == const $CopyWithPlaceholder()
? _value.locales
// ignore: cast_nullable_to_non_nullable
: locales as List<String>?,
);
}
}
@@ -422,6 +433,9 @@ EngineSettings _$EngineSettingsFromJson(Map<String, dynamic> json) =>
fingerprintingProtectionOverrides:
json['fingerprintingProtectionOverrides'] as String?,
enablePdfJs: json['enablePdfJs'] as bool?,
locales: (json['locales'] as List<dynamic>?)
?.map((e) => e as String)
.toList(),
);
Map<String, dynamic> _$EngineSettingsToJson(
@@ -448,6 +462,7 @@ Map<String, dynamic> _$EngineSettingsToJson(
_$WebContentIsolationStrategyEnumMap[instance
.webContentIsolationStrategy]!,
'enterpriseRootsEnabled': instance.enterpriseRootsEnabled,
'locales': instance.locales,
'queryParameterStripping':
_$QueryParameterStrippingEnumMap[instance.queryParameterStripping]!,
'bounceTrackingProtectionMode':
@@ -124,6 +124,9 @@ class EngineSettingsRepository extends _$EngineSettingsRepository {
DriftSqlType.bool,
db.typeMapping,
),
'locales': settings['locales']
?.readAs(DriftSqlType.string, db.typeMapping)
.mapNotNull(jsonDecode),
});
}
@@ -34,7 +34,7 @@ final class EngineSettingsRepositoryProvider
}
String _$engineSettingsRepositoryHash() =>
r'cd087c5631faaddf1fced31569b0fd577d6030a7';
r'916abcd932fc3b3b1e060bc93a46c1a3a38bb984';
abstract class _$EngineSettingsRepository
extends $StreamNotifier<EngineSettings> {
+3
View File
@@ -11,6 +11,7 @@ dependencies:
background_fetch: ^1.4.0
collection: ^1.19.1
copy_with_extension: ^9.1.1
country_flags: ^4.1.0
drift: ^2.29.0
dynamic_color: ^1.8.1
exceptions: ^0.6.1
@@ -42,6 +43,8 @@ dependencies:
lexo_rank:
git:
url: https://github.com/FaFre/lexo_rank.git
locale_resolver:
path: ../packages/locale_resolver
local_auth: ^3.0.0
logger: ^2.6.2
markdown: ^7.3.0