prepare for multiple apps

This commit is contained in:
Fabian Freund committed 2026-04-06 12:23:11 +02:00
1 parent bd1600e8dc
commit 5afc323f04
904 files changed
+29 -29

No files matched your search

@@ -0,0 +1,34 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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:flutter_mozilla_components/flutter_mozilla_components.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'providers.g.dart';
@Riverpod(keepAlive: true)
Future<PackageInfo> packageInfo(Ref ref) async {
return await PackageInfo.fromPlatform();
}
@Riverpod(keepAlive: true)
Future<String> geckoVersion(Ref ref) async {
return await GeckoBrowserService().getGeckoVersion();
}
@@ -0,0 +1,82 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'providers.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(packageInfo)
final packageInfoProvider = PackageInfoProvider._();
final class PackageInfoProvider
extends
$FunctionalProvider<
AsyncValue<PackageInfo>,
PackageInfo,
FutureOr<PackageInfo>
>
with $FutureModifier<PackageInfo>, $FutureProvider<PackageInfo> {
PackageInfoProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'packageInfoProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$packageInfoHash();
@$internal
@override
$FutureProviderElement<PackageInfo> $createElement(
$ProviderPointer pointer,
) => $FutureProviderElement(pointer);
@override
FutureOr<PackageInfo> create(Ref ref) {
return packageInfo(ref);
}
}
String _$packageInfoHash() => r'44d37547139567a5f03c1942c1d62ff1abb07248';
@ProviderFor(geckoVersion)
final geckoVersionProvider = GeckoVersionProvider._();
final class GeckoVersionProvider
extends $FunctionalProvider<AsyncValue<String>, String, FutureOr<String>>
with $FutureModifier<String>, $FutureProvider<String> {
GeckoVersionProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'geckoVersionProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$geckoVersionHash();
@$internal
@override
$FutureProviderElement<String> $createElement($ProviderPointer pointer) =>
$FutureProviderElement(pointer);
@override
FutureOr<String> create(Ref ref) {
return geckoVersion(ref);
}
}
String _$geckoVersionHash() => r'1cdaaebc674da967a2765c5bf85a7442425c47ce';
@@ -0,0 +1,140 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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:flutter/material.dart';
import 'package:flutter_material_design_icons/flutter_material_design_icons.dart';
import 'package:flutter_svg/svg.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:weblibre/core/providers/defaults.dart';
import 'package:weblibre/core/routing/routes.dart';
import 'package:weblibre/features/about/domain/providers.dart';
import 'package:weblibre/features/geckoview/domain/repositories/tab.dart';
import 'package:weblibre/features/geckoview/features/tabs/data/entities/tab_mode.dart';
class AboutDialogScreen extends HookConsumerWidget {
const AboutDialogScreen({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final packageInfo = ref.watch(
packageInfoProvider.select(
//During startup we make sure
(value) => value.value!,
),
);
return AboutDialog(
applicationIcon: SizedBox.square(
dimension: IconTheme.of(context).size,
child: SvgPicture.asset('assets/icon/icon.svg'),
),
applicationName: packageInfo.appName,
applicationVersion: packageInfo.version,
applicationLegalese: 'Copyright © Fabian Freund, 2024-2026',
children: [
ListTile(
contentPadding: EdgeInsets.zero,
title: const Text('Gecko Version'),
subtitle: Consumer(
builder: (context, ref, child) {
final geckoVersion = ref.watch(geckoVersionProvider);
return Text(geckoVersion.value ?? 'N/A');
},
),
),
const Divider(),
ListTile(
contentPadding: EdgeInsets.zero,
leading: const Icon(MdiIcons.charity),
title: const Text('Feedback'),
onTap: () async {
await ref
.read(tabRepositoryProvider.notifier)
.addTab(
url: Uri.https('feedback.weblibre.eu'),
tabMode: TabMode.regular,
selectTab: true,
);
if (context.mounted) {
const BrowserRoute().go(context);
}
},
),
ListTile(
contentPadding: EdgeInsets.zero,
leading: const Icon(MdiIcons.handHeart),
title: const Text('Donate'),
onTap: () async {
await ref
.read(tabRepositoryProvider.notifier)
.addTab(
url: Uri.https('github.com').replace(path: 'FaFre/WebLibre'),
tabMode: TabMode.regular,
selectTab: true,
);
if (context.mounted) {
const BrowserRoute().go(context);
}
},
),
ListTile(
contentPadding: EdgeInsets.zero,
// ignore: deprecated_member_use
leading: const Icon(Icons.book),
title: const Text('Documentation'),
onTap: () async {
await ref
.read(tabRepositoryProvider.notifier)
.addTab(
url: ref.read(docsUriProvider),
tabMode: TabMode.regular,
selectTab: true,
);
if (context.mounted) {
const BrowserRoute().go(context);
}
},
),
ListTile(
contentPadding: EdgeInsets.zero,
// ignore: deprecated_member_use
leading: const Icon(MdiIcons.github),
title: const Text('Github'),
onTap: () async {
await ref
.read(tabRepositoryProvider.notifier)
.addTab(
url: Uri.https('github.com').replace(path: 'FaFre/WebLibre'),
tabMode: TabMode.regular,
selectTab: true,
);
if (context.mounted) {
const BrowserRoute().go(context);
}
},
),
],
);
}
}
@@ -0,0 +1,40 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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:home_widget/home_widget.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:rxdart/rxdart.dart';
import 'package:weblibre/data/models/received_intent_parameter.dart';
part 'home_widget.g.dart';
@Riverpod(keepAlive: true)
Future<bool> widgetPinnable(Ref ref) async {
return await HomeWidget.isRequestPinWidgetSupported() ?? false;
}
@Riverpod()
Raw<Stream<ReceivedIntentParameter>> appWidgetLaunchStream(Ref ref) {
final initialStream = HomeWidget.initiallyLaunchedFromHomeWidget().asStream();
return ConcatStream([
initialStream,
HomeWidget.widgetClicked,
]).whereNotNull().map((uri) => ReceivedIntentParameter(null, uri.host));
}
@@ -0,0 +1,92 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'home_widget.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(widgetPinnable)
final widgetPinnableProvider = WidgetPinnableProvider._();
final class WidgetPinnableProvider
extends $FunctionalProvider<AsyncValue<bool>, bool, FutureOr<bool>>
with $FutureModifier<bool>, $FutureProvider<bool> {
WidgetPinnableProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'widgetPinnableProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$widgetPinnableHash();
@$internal
@override
$FutureProviderElement<bool> $createElement($ProviderPointer pointer) =>
$FutureProviderElement(pointer);
@override
FutureOr<bool> create(Ref ref) {
return widgetPinnable(ref);
}
}
String _$widgetPinnableHash() => r'3181e5e3e69e7e796e6429ca7507bbbc239f6c21';
@ProviderFor(appWidgetLaunchStream)
final appWidgetLaunchStreamProvider = AppWidgetLaunchStreamProvider._();
final class AppWidgetLaunchStreamProvider
extends
$FunctionalProvider<
Raw<Stream<ReceivedIntentParameter>>,
Raw<Stream<ReceivedIntentParameter>>,
Raw<Stream<ReceivedIntentParameter>>
>
with $Provider<Raw<Stream<ReceivedIntentParameter>>> {
AppWidgetLaunchStreamProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'appWidgetLaunchStreamProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$appWidgetLaunchStreamHash();
@$internal
@override
$ProviderElement<Raw<Stream<ReceivedIntentParameter>>> $createElement(
$ProviderPointer pointer,
) => $ProviderElement(pointer);
@override
Raw<Stream<ReceivedIntentParameter>> create(Ref ref) {
return appWidgetLaunchStream(ref);
}
/// {@macro riverpod.override_with_value}
Override overrideWithValue(Raw<Stream<ReceivedIntentParameter>> value) {
return $ProviderOverride(
origin: this,
providerOverride:
$SyncValueProvider<Raw<Stream<ReceivedIntentParameter>>>(value),
);
}
}
String _$appWidgetLaunchStreamHash() =>
r'ed042d1391ae3dbc26f806d6fa2e9a4a2464ae44';
@@ -0,0 +1,169 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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:drift/drift.dart';
import 'package:nullability/nullability.dart';
import 'package:weblibre/features/bangs/data/database/daos/bang.drift.dart';
import 'package:weblibre/features/bangs/data/database/database.dart';
import 'package:weblibre/features/bangs/data/database/definitions.drift.dart';
import 'package:weblibre/features/bangs/data/models/bang.dart';
import 'package:weblibre/features/bangs/data/models/bang_data.dart';
import 'package:weblibre/features/bangs/data/models/bang_group.dart';
import 'package:weblibre/features/bangs/data/models/bang_key.dart';
@DriftAccessor()
class BangDao extends DatabaseAccessor<BangDatabase> with $BangDaoMixin {
BangDao(super.db);
Selectable<Bang> getBangList({Iterable<BangGroup>? groups}) {
final selectable = select(db.bang);
if (groups != null) {
selectable.where((t) => t.group.isInValues(groups));
}
return selectable;
}
SingleSelectable<int> getBangCount({Iterable<BangGroup>? groups}) {
return db.bang.count(
where: groups.mapNotNull(
(groups) =>
(t) => t.group.isInValues(groups),
),
);
}
Future<int> upsertBang(Bang bang) {
return db.bang.insertOne(bang, mode: InsertMode.insertOrReplace);
}
SingleOrNullSelectable<BangData> getBangData(
BangGroup group,
String trigger,
) {
return select(db.bangDataView)
..where((t) => t.group.equalsValue(group) & t.trigger.equals(trigger));
}
Selectable<BangData> getBangDataList({
Iterable<String>? triggers,
Iterable<BangGroup>? groups,
String? domain,
String? category,
String? subCategory,
bool? orderMostFrequentFirst,
}) {
final selectable = select(db.bangDataView);
if (triggers != null) {
selectable.where((t) => t.trigger.isIn(triggers));
}
if (groups != null) {
selectable.where((t) => t.group.isInValues(groups));
}
if (domain != null) {
selectable.where((t) => t.domain.equals(domain));
}
if (category != null) {
selectable.where((t) => t.category.equals(category));
if (subCategory != null) {
selectable.where((t) => t.subCategory.equals(subCategory));
}
}
selectable.orderBy([
if (orderMostFrequentFirst == true) (t) => OrderingTerm.desc(t.frequency),
(t) => OrderingTerm.asc(t.websiteName),
]);
return selectable;
}
Selectable<BangData> getFrequentBangDataList({Iterable<BangGroup>? groups}) {
final selectable = select(db.bangDataView)
..where((t) => t.frequency.isBiggerThanValue(0));
if (groups != null) {
selectable.where((t) => t.group.isInValues(groups));
}
selectable.orderBy([
(t) => OrderingTerm.desc(t.frequency),
(t) => OrderingTerm.desc(t.lastUsed),
]);
return selectable;
}
Future<int> increaseBangFrequency(BangKey key) {
return db.bangFrequency.insertOne(
BangFrequencyCompanion.insert(
trigger: key.trigger,
group: key.group,
frequency: 1,
lastUsed: DateTime.now(),
),
onConflict: DoUpdate(
(old) => BangFrequencyCompanion.custom(
frequency: old.frequency + const Constant(1),
lastUsed: Variable(DateTime.now()),
),
),
);
}
Selectable<BangData> queryBangs(String searchString) {
final ftsQuery = db.buildFtsQuery(searchString);
if (ftsQuery.isNotEmpty) {
return db.definitionsDrift.queryBangs(query: ftsQuery);
} else {
return db.definitionsDrift.queryBangsBasic(
query: db.buildLikeQuery(searchString),
);
}
}
Future<int> addSearchEntry(
BangGroup group,
String trigger,
String searchQuery,
) {
return db.bangHistory.insertOne(
BangHistoryCompanion.insert(
searchQuery: searchQuery,
trigger: trigger,
group: group,
searchDate: DateTime.now(),
),
onConflict: DoUpdate(
target: [db.bangHistory.searchQuery],
(old) => BangHistoryCompanion(
trigger: Value(trigger),
group: Value(group),
searchDate: Value(DateTime.now()),
),
),
);
}
Future<int> removeSearchEntry(String searchQuery) {
return db.bangHistory.deleteWhere((t) => t.searchQuery.equals(searchQuery));
}
}
@@ -0,0 +1,13 @@
// dart format width=80
// ignore_for_file: type=lint
import 'package:drift/drift.dart' as i0;
import 'package:weblibre/features/bangs/data/database/database.dart' as i1;
mixin $BangDaoMixin on i0.DatabaseAccessor<i1.BangDatabase> {
BangDaoManager get managers => BangDaoManager(this);
}
class BangDaoManager {
final $BangDaoMixin _db;
BangDaoManager(this._db);
}
@@ -0,0 +1,99 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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:drift/drift.dart';
import 'package:weblibre/features/bangs/data/database/daos/sync.drift.dart';
import 'package:weblibre/features/bangs/data/database/database.dart';
import 'package:weblibre/features/bangs/data/database/definitions.drift.dart';
import 'package:weblibre/features/bangs/data/models/bang.dart';
import 'package:weblibre/features/bangs/data/models/bang_group.dart';
@DriftAccessor()
class SyncDao extends DatabaseAccessor<BangDatabase> with $SyncDaoMixin {
SyncDao(super.db);
SingleOrNullSelectable<DateTime?> getLastSyncOfGroup(BangGroup group) {
final query = selectOnly(db.bangSync)
..addColumns([db.bangSync.lastSync])
..where(db.bangSync.group.equalsValue(group));
return query.map((row) => row.read(db.bangSync.lastSync));
}
Future<void> upsertLastSyncOfGroup(BangGroup group, DateTime lastSync) {
return db.bangSync.insertOne(
BangSyncCompanion.insert(group: Value(group), lastSync: lastSync),
onConflict: DoUpdate(
(old) => BangSyncCompanion(lastSync: Value(lastSync)),
),
);
}
Future<void> insertBangs(Iterable<Bang> bangs) {
return db.bang.insertAll(bangs);
}
Future<void> replaceBangs(Iterable<Bang> bangs) {
return batch((batch) {
batch.replaceAll(db.bang, bangs);
});
}
Future<int> deleteBangs(BangGroup group, Iterable<String> triggers) {
final statement = delete(db.bang)
..where((t) => t.group.equalsValue(group) & t.trigger.isIn(triggers));
return statement.go();
}
Future<void> syncBangs({
required BangGroup group,
required Iterable<Bang> remoteBangs,
required DateTime syncTime,
}) async {
final remoteBangMap = Map.fromEntries(
remoteBangs.map((e) => MapEntry(e.trigger, e)),
);
final localBangMap = await db.bangDao
.getBangList(groups: [group])
.get()
.then(
(bangs) => Map.fromEntries(bangs.map((e) => MapEntry(e.trigger, e))),
);
final remoteBangTriggers = remoteBangMap.keys.toSet();
final localBangTriggers = localBangMap.keys.toSet();
final removedBangs = localBangTriggers.difference(remoteBangTriggers);
final addedBangs = remoteBangTriggers
.difference(localBangTriggers)
.map((e) => remoteBangMap[e]!);
final changedBangs = remoteBangTriggers
.intersection(localBangTriggers)
.where((e) => remoteBangMap[e] != localBangMap[e])
.map((e) => remoteBangMap[e]!);
await db.transaction(() async {
await deleteBangs(group, removedBangs);
await insertBangs(addedBangs);
await replaceBangs(changedBangs);
await upsertLastSyncOfGroup(group, syncTime);
});
}
}
@@ -0,0 +1,13 @@
// dart format width=80
// ignore_for_file: type=lint
import 'package:drift/drift.dart' as i0;
import 'package:weblibre/features/bangs/data/database/database.dart' as i1;
mixin $SyncDaoMixin on i0.DatabaseAccessor<i1.BangDatabase> {
SyncDaoManager get managers => SyncDaoManager(this);
}
class SyncDaoManager {
final $SyncDaoMixin _db;
SyncDaoManager(this._db);
}
@@ -0,0 +1,145 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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:drift/drift.dart';
import 'package:drift/internal/versioned_schema.dart';
import 'package:drift_dev/api/migrations_native.dart';
import 'package:flutter/foundation.dart';
import 'package:weblibre/features/bangs/data/database/daos/bang.dart';
import 'package:weblibre/features/bangs/data/database/daos/sync.dart';
import 'package:weblibre/features/bangs/data/database/database.drift.dart';
import 'package:weblibre/features/bangs/data/database/database.steps.dart';
import 'package:weblibre/features/bangs/data/database/definitions.drift.dart';
import 'package:weblibre/features/search/domain/fts_tokenizer.dart';
@DriftDatabase(include: {'definitions.drift'}, daos: [BangDao, SyncDao])
class BangDatabase extends $BangDatabase with PrefixQueryBuilderMixin {
@override
final int schemaVersion = 5;
@override
final int ftsTokenLimit = 6;
@override
final int ftsMinTokenLength = 2;
@override
MigrationStrategy get migration => MigrationStrategy(
onUpgrade: (m, from, to) async {
// Following the advice from https://drift.simonbinder.eu/Migrations/api/#general-tips
await customStatement('PRAGMA foreign_keys = OFF');
await transaction(
() => VersionedSchema.runMigrationSteps(
migrator: m,
from: from,
to: to,
steps: _upgrade,
),
);
if (kDebugMode) {
final wrongForeignKeys = await customSelect(
'PRAGMA foreign_key_check',
).get();
assert(
wrongForeignKeys.isEmpty,
'${wrongForeignKeys.map((e) => e.data)}',
);
}
await customStatement('PRAGMA foreign_keys = ON');
},
beforeOpen: (details) async {
if (kDebugMode) {
// This check pulls in a fair amount of code that's not needed
// anywhere else, so we recommend only doing it in debug builds.
await validateDatabaseSchema();
}
if (details.hadUpgrade && details.versionBefore != null) {
await customStatement('PRAGMA foreign_keys = OFF');
if (details.versionBefore! < 3) {
await bang.deleteWhere((t) => t.group.equals(3));
await bangTriggers.deleteWhere((t) => t.group.equals(3));
await bangSync.deleteWhere((t) => t.group.equals(3));
await bangFrequency.deleteWhere((t) => t.group.equals(3));
await bangHistory.deleteWhere((t) => t.group.equals(3));
} else if (details.versionBefore! < 5) {
await bang.deleteWhere((t) => t.group.equals(1));
await bangTriggers.deleteWhere((t) => t.group.equals(1));
await bangSync.deleteWhere((t) => t.group.equals(1));
await bangFrequency.deleteWhere((t) => t.group.equals(1));
await bangHistory.deleteWhere((t) => t.group.equals(1));
await (bang.update()..where((t) => t.group.isBiggerThanValue(0)))
.write(
BangCompanion.custom(group: bang.group - const Constant(1)),
);
await (bangTriggers.update()
..where((t) => t.group.isBiggerThanValue(0)))
.write(
BangTriggersCompanion.custom(
group: bangTriggers.group - const Constant(1),
),
);
await (bangSync.update()..where((t) => t.group.isBiggerThanValue(0)))
.write(
BangSyncCompanion.custom(
group: bangSync.group - const Constant(1),
),
);
await (bangFrequency.update()
..where((t) => t.group.isBiggerThanValue(0)))
.write(
BangFrequencyCompanion.custom(
group: bangFrequency.group - const Constant(1),
),
);
await (bangHistory.update()
..where((t) => t.group.isBiggerThanValue(0)))
.write(
BangHistoryCompanion.custom(
group: bangHistory.group - const Constant(1),
),
);
}
}
await customStatement('PRAGMA foreign_keys = ON');
},
);
BangDatabase(super.e);
static final _upgrade = migrationSteps(
from1To2: (m, schema) async {
//Too many changes, we switch to a new database
},
from2To3: (m, schema) async {
await m.addColumn(schema.bang, schema.bang.searxngApi);
},
from3To4: (m, schema) async {
await m.alterTable(TableMigration(schema.bangHistory));
},
from4To5: (m, schema) async {
await m.addColumn(schema.bang, schema.bang.snapDomain);
},
);
}
@@ -0,0 +1,200 @@
// dart format width=80
// ignore_for_file: type=lint
import 'package:drift/drift.dart' as i0;
import 'package:weblibre/features/bangs/data/database/definitions.drift.dart'
as i1;
import 'package:weblibre/features/bangs/data/database/daos/bang.dart' as i2;
import 'package:weblibre/features/bangs/data/database/database.dart' as i3;
import 'package:weblibre/features/bangs/data/database/daos/sync.dart' as i4;
import 'package:drift/internal/modular.dart' as i5;
import 'package:sqlite3/common.dart' as i6;
abstract class $BangDatabase extends i0.GeneratedDatabase {
$BangDatabase(i0.QueryExecutor e) : super(e);
$BangDatabaseManager get managers => $BangDatabaseManager(this);
late final i1.BangTable bang = i1.BangTable(this);
late final i1.BangTriggers bangTriggers = i1.BangTriggers(this);
late final i1.BangSync bangSync = i1.BangSync(this);
late final i1.BangFrequency bangFrequency = i1.BangFrequency(this);
late final i1.BangHistory bangHistory = i1.BangHistory(this);
late final i1.BangFts bangFts = i1.BangFts(this);
late final i1.BangTriggersFts bangTriggersFts = i1.BangTriggersFts(this);
late final i1.BangDataView bangDataView = i1.BangDataView(this);
late final i2.BangDao bangDao = i2.BangDao(this as i3.BangDatabase);
late final i4.SyncDao syncDao = i4.SyncDao(this as i3.BangDatabase);
i1.DefinitionsDrift get definitionsDrift => i5.ReadDatabaseContainer(
this,
).accessor<i1.DefinitionsDrift>(i1.DefinitionsDrift.new);
@override
Iterable<i0.TableInfo<i0.Table, Object?>> get allTables =>
allSchemaEntities.whereType<i0.TableInfo<i0.Table, Object?>>();
@override
List<i0.DatabaseSchemaEntity> get allSchemaEntities => [
bang,
bangTriggers,
i1.idxBangTriggersLookup,
i1.bangTriggersAfterInsert,
i1.bangTriggersAfterUpdate,
bangSync,
bangFrequency,
bangHistory,
bangFts,
bangTriggersFts,
bangDataView,
i1.bangAfterInsert,
i1.bangAfterDelete,
i1.bangAfterUpdate,
i1.bangTriggersAfterInsertFts,
i1.bangTriggersAfterDeleteFts,
i1.bangTriggersAfterUpdateFts,
];
@override
i0.StreamQueryUpdateRules
get streamUpdateRules => const i0.StreamQueryUpdateRules([
i0.WritePropagation(
on: i0.TableUpdateQuery.onTableName(
'bang',
limitUpdateKind: i0.UpdateKind.delete,
),
result: [i0.TableUpdate('bang_triggers', kind: i0.UpdateKind.delete)],
),
i0.WritePropagation(
on: i0.TableUpdateQuery.onTableName(
'bang',
limitUpdateKind: i0.UpdateKind.insert,
),
result: [i0.TableUpdate('bang_triggers', kind: i0.UpdateKind.insert)],
),
i0.WritePropagation(
on: i0.TableUpdateQuery.onTableName(
'bang',
limitUpdateKind: i0.UpdateKind.update,
),
result: [
i0.TableUpdate('bang_triggers', kind: i0.UpdateKind.delete),
i0.TableUpdate('bang_triggers', kind: i0.UpdateKind.insert),
],
),
i0.WritePropagation(
on: i0.TableUpdateQuery.onTableName(
'bang',
limitUpdateKind: i0.UpdateKind.delete,
),
result: [i0.TableUpdate('bang_frequency', kind: i0.UpdateKind.delete)],
),
i0.WritePropagation(
on: i0.TableUpdateQuery.onTableName(
'bang',
limitUpdateKind: i0.UpdateKind.delete,
),
result: [i0.TableUpdate('bang_history', kind: i0.UpdateKind.delete)],
),
i0.WritePropagation(
on: i0.TableUpdateQuery.onTableName(
'bang',
limitUpdateKind: i0.UpdateKind.insert,
),
result: [i0.TableUpdate('bang_fts', kind: i0.UpdateKind.insert)],
),
i0.WritePropagation(
on: i0.TableUpdateQuery.onTableName(
'bang',
limitUpdateKind: i0.UpdateKind.delete,
),
result: [i0.TableUpdate('bang_fts', kind: i0.UpdateKind.insert)],
),
i0.WritePropagation(
on: i0.TableUpdateQuery.onTableName(
'bang',
limitUpdateKind: i0.UpdateKind.update,
),
result: [i0.TableUpdate('bang_fts', kind: i0.UpdateKind.insert)],
),
i0.WritePropagation(
on: i0.TableUpdateQuery.onTableName(
'bang_triggers',
limitUpdateKind: i0.UpdateKind.insert,
),
result: [i0.TableUpdate('bang_triggers_fts', kind: i0.UpdateKind.insert)],
),
i0.WritePropagation(
on: i0.TableUpdateQuery.onTableName(
'bang_triggers',
limitUpdateKind: i0.UpdateKind.delete,
),
result: [i0.TableUpdate('bang_triggers_fts', kind: i0.UpdateKind.insert)],
),
i0.WritePropagation(
on: i0.TableUpdateQuery.onTableName(
'bang_triggers',
limitUpdateKind: i0.UpdateKind.update,
),
result: [i0.TableUpdate('bang_triggers_fts', kind: i0.UpdateKind.insert)],
),
]);
}
class $BangDatabaseManager {
final $BangDatabase _db;
$BangDatabaseManager(this._db);
i1.$BangTableTableManager get bang =>
i1.$BangTableTableManager(_db, _db.bang);
i1.$BangTriggersTableManager get bangTriggers =>
i1.$BangTriggersTableManager(_db, _db.bangTriggers);
i1.$BangSyncTableManager get bangSync =>
i1.$BangSyncTableManager(_db, _db.bangSync);
i1.$BangFrequencyTableManager get bangFrequency =>
i1.$BangFrequencyTableManager(_db, _db.bangFrequency);
i1.$BangHistoryTableManager get bangHistory =>
i1.$BangHistoryTableManager(_db, _db.bangHistory);
i1.$BangFtsTableManager get bangFts =>
i1.$BangFtsTableManager(_db, _db.bangFts);
i1.$BangTriggersFtsTableManager get bangTriggersFts =>
i1.$BangTriggersFtsTableManager(_db, _db.bangTriggersFts);
}
extension DefineFunctions on i6.CommonDatabase {
void defineFunctions({
required String Function(int, String?) lexoRankNext,
required String Function(int, String?) lexoRankPrevious,
required String Function(String?, String?) lexoRankReorderAfter,
required String Function(String?, String?) lexoRankReorderBefore,
}) {
createFunction(
functionName: 'lexo_rank_next',
argumentCount: const i6.AllowedArgumentCount(2),
function: (args) {
final arg0 = args[0] as int;
final arg1 = args[1] as String?;
return lexoRankNext(arg0, arg1);
},
);
createFunction(
functionName: 'lexo_rank_previous',
argumentCount: const i6.AllowedArgumentCount(2),
function: (args) {
final arg0 = args[0] as int;
final arg1 = args[1] as String?;
return lexoRankPrevious(arg0, arg1);
},
);
createFunction(
functionName: 'lexo_rank_reorder_after',
argumentCount: const i6.AllowedArgumentCount(2),
function: (args) {
final arg0 = args[0] as String?;
final arg1 = args[1] as String?;
return lexoRankReorderAfter(arg0, arg1);
},
);
createFunction(
functionName: 'lexo_rank_reorder_before',
argumentCount: const i6.AllowedArgumentCount(2),
function: (args) {
final arg0 = args[0] as String?;
final arg1 = args[1] as String?;
return lexoRankReorderBefore(arg0, arg1);
},
);
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,295 @@
import 'package:weblibre/features/bangs/data/database/drift/converters/bang_format.dart';
import 'package:weblibre/features/bangs/data/database/drift/converters/trigger_list.dart';
import 'package:weblibre/features/bangs/data/models/bang_data.dart';
import 'package:weblibre/features/bangs/data/models/bang_group.dart';
import 'package:weblibre/features/bangs/data/models/bang.dart';
import 'package:weblibre/features/bangs/data/models/search_history_entry.dart';
CREATE TABLE bang (
"trigger" TEXT NOT NULL,
"group" ENUM(BangGroup) NOT NULL,
website_name TEXT NOT NULL,
domain TEXT NOT NULL,
url_template TEXT NOT NULL,
category TEXT,
sub_category TEXT,
format TEXT MAPPED BY `const BangFormatConverter()`,
additional_triggers TEXT MAPPED BY `const TriggerListConverter()`,
searxng_api BOOL NOT NULL DEFAULT FALSE,
snap_domain TEXT,
PRIMARY KEY ("trigger", "group")
) WITH Bang;
CREATE TABLE bang_triggers (
"trigger" TEXT NOT NULL,
"group" ENUM(BangGroup) NOT NULL,
additional_trigger TEXT NOT NULL,
PRIMARY KEY ("trigger", "group", additional_trigger),
FOREIGN KEY ("trigger", "group") REFERENCES bang ("trigger", "group") ON DELETE CASCADE
);
CREATE INDEX idx_bang_triggers_lookup ON bang_triggers (additional_trigger, "group");
-- Trigger to populate bang_triggers when inserting a new bang
CREATE TRIGGER bang_triggers_after_insert AFTER INSERT ON bang
WHEN new.additional_triggers IS NOT NULL
BEGIN
INSERT INTO bang_triggers("trigger", "group", additional_trigger)
SELECT
new."trigger",
new."group",
json_each.value
FROM json_each(new.additional_triggers);
END;
-- Trigger to update bang_triggers when updating a bang
CREATE TRIGGER bang_triggers_after_update AFTER UPDATE ON bang BEGIN
-- Delete old additional triggers
DELETE FROM bang_triggers
WHERE "trigger" = old."trigger" AND "group" = old."group";
-- Insert new additional triggers if they exist
INSERT INTO bang_triggers("trigger", "group", additional_trigger)
SELECT
new."trigger",
new."group",
json_each.value
FROM json_each(new.additional_triggers)
WHERE new.additional_triggers IS NOT NULL;
END;
CREATE TABLE bang_sync (
"group" ENUM(BangGroup) PRIMARY KEY NOT NULL,
last_sync DATETIME NOT NULL
);
CREATE TABLE bang_frequency (
"trigger" TEXT NOT NULL,
"group" ENUM(BangGroup) NOT NULL,
frequency INTEGER NOT NULL,
last_used DATETIME NOT NULL,
PRIMARY KEY ("trigger", "group"),
FOREIGN KEY ("trigger", "group") REFERENCES bang ("trigger", "group") ON DELETE CASCADE
);
CREATE TABLE bang_history (
search_query TEXT UNIQUE NOT NULL,
"trigger" TEXT NOT NULL,
"group" ENUM(BangGroup) NOT NULL,
search_date DATETIME NOT NULL,
FOREIGN KEY ("trigger", "group") REFERENCES bang ("trigger", "group") ON DELETE CASCADE
);
CREATE VIRTUAL TABLE bang_fts
USING fts5(
trigger,
website_name,
content=bang,
prefix='2 3'
);
CREATE VIRTUAL TABLE bang_triggers_fts
USING fts5(
additional_trigger,
content=bang_triggers,
prefix='2 3'
);
CREATE VIEW bang_data_view WITH BangData AS
SELECT
b.*,
bf.frequency,
bf.last_used
FROM
bang b
LEFT JOIN
bang_frequency bf ON b."trigger" = bf."trigger" AND b."group" = bf."group";
-- Triggers to keep the FTS index up to date.
CREATE TRIGGER bang_after_insert AFTER INSERT ON bang BEGIN
INSERT INTO
bang_fts(rowid, "trigger", website_name)
VALUES (new.rowid, new."trigger", new.website_name);
END;
CREATE TRIGGER bang_after_delete AFTER DELETE ON bang BEGIN
INSERT INTO
bang_fts(bang_fts, rowid, "trigger", website_name)
VALUES('delete', old.rowid, old."trigger", old.website_name);
END;
CREATE TRIGGER bang_after_update AFTER UPDATE ON bang BEGIN
INSERT INTO
bang_fts(bang_fts, rowid, "trigger", website_name)
VALUES('delete', old.rowid, old."trigger", old.website_name);
INSERT INTO
bang_fts(rowid, "trigger", website_name)
VALUES (new.rowid, new."trigger", new.website_name);
END;
CREATE TRIGGER bang_triggers_after_insert_fts AFTER INSERT ON bang_triggers BEGIN
INSERT INTO
bang_triggers_fts(rowid, additional_trigger)
VALUES (new.rowid, new.additional_trigger);
END;
CREATE TRIGGER bang_triggers_after_delete_fts AFTER DELETE ON bang_triggers BEGIN
INSERT INTO
bang_triggers_fts(bang_triggers_fts, rowid, additional_trigger)
VALUES('delete', old.rowid, old.additional_trigger);
END;
CREATE TRIGGER bang_triggers_after_update_fts AFTER UPDATE ON bang_triggers BEGIN
INSERT INTO
bang_triggers_fts(bang_triggers_fts, rowid, additional_trigger)
VALUES('delete', old.rowid, old.additional_trigger);
INSERT INTO
bang_triggers_fts(rowid, additional_trigger)
VALUES (new.rowid, new.additional_trigger);
END;
optimizeBangFtsIndex:
INSERT INTO bang_fts(bang_fts) VALUES ('optimize');
optimizeTriggerFtsIndex:
INSERT INTO bang_triggers_fts(bang_triggers_fts) VALUES ('optimize');
queryBangs WITH BangData:
WITH weights AS (
SELECT
10.0 AS "trigger",
8.0 AS additional_trigger,
5.0 AS website_name
),
bang_results AS (
SELECT
b.*,
bf.frequency,
bf.last_used,
bm25(bang_fts, weights."trigger", weights.website_name) AS weighted_rank
FROM
bang_fts(:query) fts
INNER JOIN
bang b ON b.rowid = fts.rowid
LEFT JOIN
bang_frequency bf ON b."trigger" = bf."trigger" AND b."group" = bf."group"
CROSS JOIN weights
),
trigger_results AS (
SELECT
b.*,
bf.frequency,
bf.last_used,
bm25(bang_triggers_fts, weights.additional_trigger) AS weighted_rank
FROM
bang_triggers_fts(:query) tfts
INNER JOIN
bang_triggers bt ON bt.rowid = tfts.rowid
INNER JOIN
bang b ON b."trigger" = bt."trigger" AND b."group" = bt."group"
LEFT JOIN
bang_frequency bf ON b."trigger" = bf."trigger" AND b."group" = bf."group"
CROSS JOIN weights
),
combined_results AS (
SELECT * FROM bang_results
UNION ALL
SELECT * FROM trigger_results
)
SELECT
*,
MIN(weighted_rank) AS weighted_rank
FROM combined_results
GROUP BY "trigger", "group"
ORDER BY
weighted_rank ASC,
frequency NULLS LAST;
queryBangsBasic WITH BangData:
WITH weights AS (
SELECT
10.0 AS "trigger",
8.0 AS additional_trigger,
5.0 AS website_name
),
bang_results AS (
SELECT
b.*,
bf.frequency,
bf.last_used,
bm25(bang_fts, weights."trigger", weights.website_name) AS weighted_rank
FROM
bang_fts fts
INNER JOIN
bang b ON b.rowid = fts.rowid
LEFT JOIN
bang_frequency bf ON b."trigger" = bf."trigger" AND b."group" = bf."group"
CROSS JOIN weights
WHERE
fts."trigger" LIKE :query OR
fts.website_name LIKE :query
),
trigger_results AS (
SELECT
b.*,
bf.frequency,
bf.last_used,
bm25(bang_triggers_fts, weights.additional_trigger) AS weighted_rank
FROM
bang_triggers_fts tfts
INNER JOIN
bang_triggers bt ON bt.rowid = tfts.rowid
INNER JOIN
bang b ON b."trigger" = bt."trigger" AND b."group" = bt."group"
LEFT JOIN
bang_frequency bf ON b."trigger" = bf."trigger" AND b."group" = bf."group"
CROSS JOIN weights
WHERE
tfts.additional_trigger LIKE :query
),
combined_results AS (
SELECT * FROM bang_results
UNION ALL
SELECT * FROM trigger_results
)
SELECT
*,
MIN(weighted_rank) AS weighted_rank
FROM combined_results
GROUP BY "trigger", "group"
ORDER BY
weighted_rank ASC,
frequency NULLS LAST;
categoriesJson:
WITH categories AS (
SELECT
b.category,
json_group_array(
DISTINCT b.sub_category
ORDER BY b.sub_category
) AS sub_categories
FROM
bang b
WHERE
b.category IS NOT NULL AND
b.sub_category IS NOT NULL
GROUP BY b.category
ORDER BY b.category
)
SELECT
json_group_object(
c.category,
json(c.sub_categories)
) AS categories_json
FROM categories c;
searchHistoryEntries WITH SearchHistoryEntry:
SELECT *
FROM bang_history
ORDER BY search_date DESC
LIMIT :limit;
evictHistoryEntries:
DELETE FROM bang_history
WHERE rowid IN (
SELECT rowid
FROM bang_history
ORDER BY search_date DESC
LIMIT -1 OFFSET :limit
);
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,45 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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 'dart:convert';
import 'package:drift/drift.dart';
import 'package:weblibre/features/bangs/data/models/bang.dart';
class BangFormatConverter extends TypeConverter<Set<BangFormat>?, String?> {
const BangFormatConverter();
@override
Set<BangFormat>? fromSql(String? fromDb) {
if (fromDb == null) {
return null;
}
return Bang.decodeFormat(jsonDecode(fromDb) as List);
}
@override
String? toSql(Set<BangFormat>? value) {
if (value == null) {
return null;
}
return jsonEncode(Bang.encodeFormat(value));
}
}
@@ -0,0 +1,39 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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 'dart:convert';
import 'package:drift/drift.dart';
import 'package:nullability/nullability.dart';
class TriggerListConverter extends TypeConverter<Set<String>?, String?> {
const TriggerListConverter();
@override
Set<String>? fromSql(String? fromDb) {
return fromDb.mapNotNull(
(value) => (jsonDecode(value) as List).cast<String>().toSet(),
);
}
@override
String? toSql(Set<String>? value) {
return value.mapNotNull((value) => jsonEncode(value.toList()));
}
}
@@ -0,0 +1,196 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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:copy_with_extension/copy_with_extension.dart';
import 'package:drift/drift.dart' show Expression, Insertable, Value;
import 'package:fast_equatable/fast_equatable.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:nullability/nullability.dart';
import 'package:weblibre/extensions/uri.dart';
import 'package:weblibre/features/bangs/data/database/definitions.drift.dart';
import 'package:weblibre/features/bangs/data/models/bang_group.dart';
part 'bang.g.dart';
enum BangFormat {
///When the bang is invoked with no query, opens the base path of the URL (/)
///instead of any path given in the template (g., /search)
@JsonValue('open_base_path')
openBasePath,
///URL encode the search terms. Some sites do not work with this, so it can
///be disabled by omitting this.
@JsonValue('url_encode_placeholder')
urlEncodePlaceholder,
///URL encodes spaces as +, instead of %20. Some sites only work correctly
///with one or the other.
@JsonValue('url_encode_space_to_plus')
urlEncodeSpaceToPlus,
///When the bang is invoked with no query, open the snap domain (ad) instead of any path given in the template
@JsonValue('open_snap_domain')
openSnapDomain,
}
@JsonSerializable()
@CopyWith()
class Bang with FastEquatable implements Insertable<Bang> {
static const _templateQueryPlaceholder = '{{{s}}}';
@JsonKey(includeFromJson: false, includeToJson: false)
final BangGroup? group;
///The name of the website associated with the bang.
@JsonKey(name: 's')
final String websiteName;
///The domain name of the websit
@JsonKey(name: 'd')
final String domain;
///The specific trigger word or phrase used to invoke the bang.
@JsonKey(name: 't')
final String trigger;
///The URL template to use when the bang is invoked, where `{{{s}}}` is replaced by the user's query.
@JsonKey(name: 'u')
final String urlTemplate;
///The category of the website, if applicable
@JsonKey(name: 'c')
final String? category;
///The subcategory of the website, if applicable
@JsonKey(name: 'sc')
final String? subCategory;
///The format flags indicating how the query should be processed.
@JsonKey(name: 'fmt')
final Set<BangFormat>? format;
///Additional triggers that invoke this bang
@JsonKey(name: 'ts')
final Set<String>? additionalTriggers;
///Additional triggers that invoke this bang
@JsonKey(name: 'ad')
final String? snapDomain;
@JsonKey(defaultValue: false)
final bool searxngApi;
String formatQuery(String input) {
return (format == null ||
format!.contains(BangFormat.urlEncodePlaceholder) == true)
? (format == null ||
format?.contains(BangFormat.urlEncodeSpaceToPlus) == true)
? Uri.encodeQueryComponent(input)
: Uri.encodeComponent(input)
: input;
}
Uri getDefaultUrl() {
return getTemplateUrl('');
}
Uri getTemplateUrl(String? query) {
final queryEmpty = query.isEmpty;
if (queryEmpty && format?.contains(BangFormat.openSnapDomain) == true) {
if (snapDomain.isNotEmpty) {
return Uri.parse(snapDomain!);
}
}
final url = (!queryEmpty)
? urlTemplate.replaceAll(_templateQueryPlaceholder, formatQuery(query!))
: urlTemplate;
var template = Uri.parse(url);
if (!template.hasScheme || template.origin.isEmpty) {
template = Uri.https(
domain,
).replace(path: template.path, query: template.query);
}
if (queryEmpty && format?.contains(BangFormat.openBasePath) == true) {
template = template.base;
}
return template;
}
static Set<BangFormat> decodeFormat(Iterable input) {
return input.map((e) => $enumDecode(_$BangFormatEnumMap, e)).toSet();
}
static List<String> encodeFormat(Iterable<BangFormat> format) {
return format.map((e) => _$BangFormatEnumMap[e]!).toList();
}
Bang({
required this.websiteName,
required this.domain,
required this.trigger,
required this.urlTemplate,
required this.searxngApi,
this.group,
this.category,
this.subCategory,
this.format,
this.additionalTriggers,
this.snapDomain,
});
factory Bang.fromJson(Map<String, dynamic> json) => _$BangFromJson(json);
Map<String, dynamic> toJson() => _$BangToJson(this);
@override
List<Object?> get hashParameters => [
group,
websiteName,
domain,
trigger,
urlTemplate,
category,
subCategory,
format,
additionalTriggers,
snapDomain,
searxngApi,
];
@override
Map<String, Expression<Object>> toColumns(bool nullToAbsent) {
return BangCompanion(
trigger: Value(trigger),
websiteName: Value(websiteName),
domain: Value(domain),
urlTemplate: Value(urlTemplate),
group: Value.absentIfNull(group),
category: Value.absentIfNull(category),
subCategory: Value.absentIfNull(subCategory),
format: Value.absentIfNull(format),
additionalTriggers: Value.absentIfNull(additionalTriggers),
snapDomain: Value.absentIfNull(snapDomain),
).toColumns(nullToAbsent);
}
}
@@ -0,0 +1,214 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'bang.dart';
// **************************************************************************
// CopyWithGenerator
// **************************************************************************
abstract class _$BangCWProxy {
Bang websiteName(String websiteName);
Bang domain(String domain);
Bang trigger(String trigger);
Bang urlTemplate(String urlTemplate);
Bang searxngApi(bool searxngApi);
Bang group(BangGroup? group);
Bang category(String? category);
Bang subCategory(String? subCategory);
Bang format(Set<BangFormat>? format);
Bang additionalTriggers(Set<String>? additionalTriggers);
Bang snapDomain(String? snapDomain);
/// 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 `Bang(...).copyWith.fieldName(value)`.
///
/// Example:
/// ```dart
/// Bang(...).copyWith(id: 12, name: "My name")
/// ```
Bang call({
String websiteName,
String domain,
String trigger,
String urlTemplate,
bool searxngApi,
BangGroup? group,
String? category,
String? subCategory,
Set<BangFormat>? format,
Set<String>? additionalTriggers,
String? snapDomain,
});
}
/// Callable proxy for `copyWith` functionality.
/// Use as `instanceOfBang.copyWith(...)` or call `instanceOfBang.copyWith.fieldName(value)` for a single field.
class _$BangCWProxyImpl implements _$BangCWProxy {
const _$BangCWProxyImpl(this._value);
final Bang _value;
@override
Bang websiteName(String websiteName) => call(websiteName: websiteName);
@override
Bang domain(String domain) => call(domain: domain);
@override
Bang trigger(String trigger) => call(trigger: trigger);
@override
Bang urlTemplate(String urlTemplate) => call(urlTemplate: urlTemplate);
@override
Bang searxngApi(bool searxngApi) => call(searxngApi: searxngApi);
@override
Bang group(BangGroup? group) => call(group: group);
@override
Bang category(String? category) => call(category: category);
@override
Bang subCategory(String? subCategory) => call(subCategory: subCategory);
@override
Bang format(Set<BangFormat>? format) => call(format: format);
@override
Bang additionalTriggers(Set<String>? additionalTriggers) =>
call(additionalTriggers: additionalTriggers);
@override
Bang snapDomain(String? snapDomain) => call(snapDomain: snapDomain);
@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 `Bang(...).copyWith.fieldName(value)`.
///
/// Example:
/// ```dart
/// Bang(...).copyWith(id: 12, name: "My name")
/// ```
Bang call({
Object? websiteName = const $CopyWithPlaceholder(),
Object? domain = const $CopyWithPlaceholder(),
Object? trigger = const $CopyWithPlaceholder(),
Object? urlTemplate = const $CopyWithPlaceholder(),
Object? searxngApi = const $CopyWithPlaceholder(),
Object? group = const $CopyWithPlaceholder(),
Object? category = const $CopyWithPlaceholder(),
Object? subCategory = const $CopyWithPlaceholder(),
Object? format = const $CopyWithPlaceholder(),
Object? additionalTriggers = const $CopyWithPlaceholder(),
Object? snapDomain = const $CopyWithPlaceholder(),
}) {
return Bang(
websiteName:
websiteName == const $CopyWithPlaceholder() || websiteName == null
? _value.websiteName
// ignore: cast_nullable_to_non_nullable
: websiteName as String,
domain: domain == const $CopyWithPlaceholder() || domain == null
? _value.domain
// ignore: cast_nullable_to_non_nullable
: domain as String,
trigger: trigger == const $CopyWithPlaceholder() || trigger == null
? _value.trigger
// ignore: cast_nullable_to_non_nullable
: trigger as String,
urlTemplate:
urlTemplate == const $CopyWithPlaceholder() || urlTemplate == null
? _value.urlTemplate
// ignore: cast_nullable_to_non_nullable
: urlTemplate as String,
searxngApi:
searxngApi == const $CopyWithPlaceholder() || searxngApi == null
? _value.searxngApi
// ignore: cast_nullable_to_non_nullable
: searxngApi as bool,
group: group == const $CopyWithPlaceholder()
? _value.group
// ignore: cast_nullable_to_non_nullable
: group as BangGroup?,
category: category == const $CopyWithPlaceholder()
? _value.category
// ignore: cast_nullable_to_non_nullable
: category as String?,
subCategory: subCategory == const $CopyWithPlaceholder()
? _value.subCategory
// ignore: cast_nullable_to_non_nullable
: subCategory as String?,
format: format == const $CopyWithPlaceholder()
? _value.format
// ignore: cast_nullable_to_non_nullable
: format as Set<BangFormat>?,
additionalTriggers: additionalTriggers == const $CopyWithPlaceholder()
? _value.additionalTriggers
// ignore: cast_nullable_to_non_nullable
: additionalTriggers as Set<String>?,
snapDomain: snapDomain == const $CopyWithPlaceholder()
? _value.snapDomain
// ignore: cast_nullable_to_non_nullable
: snapDomain as String?,
);
}
}
extension $BangCopyWith on Bang {
/// Returns a callable class used to build a new instance with modified fields.
/// Example: `instanceOfBang.copyWith(...)` or `instanceOfBang.copyWith.fieldName(...)`.
// ignore: library_private_types_in_public_api
_$BangCWProxy get copyWith => _$BangCWProxyImpl(this);
}
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
Bang _$BangFromJson(Map<String, dynamic> json) => Bang(
websiteName: json['s'] as String,
domain: json['d'] as String,
trigger: json['t'] as String,
urlTemplate: json['u'] as String,
searxngApi: json['searxngApi'] as bool? ?? false,
category: json['c'] as String?,
subCategory: json['sc'] as String?,
format: (json['fmt'] as List<dynamic>?)
?.map((e) => $enumDecode(_$BangFormatEnumMap, e))
.toSet(),
additionalTriggers: (json['ts'] as List<dynamic>?)
?.map((e) => e as String)
.toSet(),
snapDomain: json['ad'] as String?,
);
Map<String, dynamic> _$BangToJson(Bang instance) => <String, dynamic>{
's': instance.websiteName,
'd': instance.domain,
't': instance.trigger,
'u': instance.urlTemplate,
'c': instance.category,
'sc': instance.subCategory,
'fmt': instance.format?.map((e) => _$BangFormatEnumMap[e]!).toList(),
'ts': instance.additionalTriggers?.toList(),
'ad': instance.snapDomain,
'searxngApi': instance.searxngApi,
};
const _$BangFormatEnumMap = {
BangFormat.openBasePath: 'open_base_path',
BangFormat.urlEncodePlaceholder: 'url_encode_placeholder',
BangFormat.urlEncodeSpaceToPlus: 'url_encode_space_to_plus',
BangFormat.openSnapDomain: 'open_snap_domain',
};
@@ -0,0 +1,81 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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:copy_with_extension/copy_with_extension.dart';
import 'package:weblibre/features/bangs/data/models/bang.dart';
import 'package:weblibre/features/bangs/data/models/bang_group.dart';
import 'package:weblibre/features/bangs/data/models/bang_key.dart';
import 'package:weblibre/features/geckoview/domain/entities/browser_icon.dart';
part 'bang_data.g.dart';
@CopyWith(constructor: '_copyWith')
class BangData extends Bang {
final int frequency;
final DateTime? lastUsed;
final BrowserIcon? icon;
@override
BangGroup get group => super.group!;
BangData({
required super.websiteName,
required super.domain,
required super.trigger,
required super.urlTemplate,
required super.group,
required super.searxngApi,
super.category,
super.subCategory,
super.format,
super.additionalTriggers,
super.snapDomain,
int? frequency,
this.lastUsed,
this.icon,
}) : frequency = frequency ?? 0;
//For some reasons including super.group breaks generation of copywith, so we have this one for now
BangData._copyWith({
required super.websiteName,
required super.domain,
required super.trigger,
required super.urlTemplate,
required super.searxngApi,
super.category,
super.subCategory,
super.format,
super.additionalTriggers,
super.snapDomain,
int? frequency,
this.lastUsed,
this.icon,
}) : frequency = frequency ?? 0;
BangKey toKey() => BangKey(group: group, trigger: trigger);
@override
List<Object?> get hashParameters => [
...super.hashParameters,
frequency,
lastUsed,
icon,
];
}
@@ -0,0 +1,195 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'bang_data.dart';
// **************************************************************************
// CopyWithGenerator
// **************************************************************************
abstract class _$BangDataCWProxy {
BangData websiteName(String websiteName);
BangData domain(String domain);
BangData trigger(String trigger);
BangData urlTemplate(String urlTemplate);
BangData searxngApi(bool searxngApi);
BangData category(String? category);
BangData subCategory(String? subCategory);
BangData format(Set<BangFormat>? format);
BangData additionalTriggers(Set<String>? additionalTriggers);
BangData snapDomain(String? snapDomain);
BangData frequency(int? frequency);
BangData lastUsed(DateTime? lastUsed);
BangData icon(BrowserIcon? icon);
/// 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 `BangData(...).copyWith.fieldName(value)`.
///
/// Example:
/// ```dart
/// BangData(...).copyWith(id: 12, name: "My name")
/// ```
BangData call({
String websiteName,
String domain,
String trigger,
String urlTemplate,
bool searxngApi,
String? category,
String? subCategory,
Set<BangFormat>? format,
Set<String>? additionalTriggers,
String? snapDomain,
int? frequency,
DateTime? lastUsed,
BrowserIcon? icon,
});
}
/// Callable proxy for `copyWith` functionality.
/// Use as `instanceOfBangData.copyWith(...)` or call `instanceOfBangData.copyWith.fieldName(value)` for a single field.
class _$BangDataCWProxyImpl implements _$BangDataCWProxy {
const _$BangDataCWProxyImpl(this._value);
final BangData _value;
@override
BangData websiteName(String websiteName) => call(websiteName: websiteName);
@override
BangData domain(String domain) => call(domain: domain);
@override
BangData trigger(String trigger) => call(trigger: trigger);
@override
BangData urlTemplate(String urlTemplate) => call(urlTemplate: urlTemplate);
@override
BangData searxngApi(bool searxngApi) => call(searxngApi: searxngApi);
@override
BangData category(String? category) => call(category: category);
@override
BangData subCategory(String? subCategory) => call(subCategory: subCategory);
@override
BangData format(Set<BangFormat>? format) => call(format: format);
@override
BangData additionalTriggers(Set<String>? additionalTriggers) =>
call(additionalTriggers: additionalTriggers);
@override
BangData snapDomain(String? snapDomain) => call(snapDomain: snapDomain);
@override
BangData frequency(int? frequency) => call(frequency: frequency);
@override
BangData lastUsed(DateTime? lastUsed) => call(lastUsed: lastUsed);
@override
BangData icon(BrowserIcon? icon) => call(icon: icon);
@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 `BangData(...).copyWith.fieldName(value)`.
///
/// Example:
/// ```dart
/// BangData(...).copyWith(id: 12, name: "My name")
/// ```
BangData call({
Object? websiteName = const $CopyWithPlaceholder(),
Object? domain = const $CopyWithPlaceholder(),
Object? trigger = const $CopyWithPlaceholder(),
Object? urlTemplate = const $CopyWithPlaceholder(),
Object? searxngApi = const $CopyWithPlaceholder(),
Object? category = const $CopyWithPlaceholder(),
Object? subCategory = const $CopyWithPlaceholder(),
Object? format = const $CopyWithPlaceholder(),
Object? additionalTriggers = const $CopyWithPlaceholder(),
Object? snapDomain = const $CopyWithPlaceholder(),
Object? frequency = const $CopyWithPlaceholder(),
Object? lastUsed = const $CopyWithPlaceholder(),
Object? icon = const $CopyWithPlaceholder(),
}) {
return BangData._copyWith(
websiteName:
websiteName == const $CopyWithPlaceholder() || websiteName == null
? _value.websiteName
// ignore: cast_nullable_to_non_nullable
: websiteName as String,
domain: domain == const $CopyWithPlaceholder() || domain == null
? _value.domain
// ignore: cast_nullable_to_non_nullable
: domain as String,
trigger: trigger == const $CopyWithPlaceholder() || trigger == null
? _value.trigger
// ignore: cast_nullable_to_non_nullable
: trigger as String,
urlTemplate:
urlTemplate == const $CopyWithPlaceholder() || urlTemplate == null
? _value.urlTemplate
// ignore: cast_nullable_to_non_nullable
: urlTemplate as String,
searxngApi:
searxngApi == const $CopyWithPlaceholder() || searxngApi == null
? _value.searxngApi
// ignore: cast_nullable_to_non_nullable
: searxngApi as bool,
category: category == const $CopyWithPlaceholder()
? _value.category
// ignore: cast_nullable_to_non_nullable
: category as String?,
subCategory: subCategory == const $CopyWithPlaceholder()
? _value.subCategory
// ignore: cast_nullable_to_non_nullable
: subCategory as String?,
format: format == const $CopyWithPlaceholder()
? _value.format
// ignore: cast_nullable_to_non_nullable
: format as Set<BangFormat>?,
additionalTriggers: additionalTriggers == const $CopyWithPlaceholder()
? _value.additionalTriggers
// ignore: cast_nullable_to_non_nullable
: additionalTriggers as Set<String>?,
snapDomain: snapDomain == const $CopyWithPlaceholder()
? _value.snapDomain
// ignore: cast_nullable_to_non_nullable
: snapDomain as String?,
frequency: frequency == const $CopyWithPlaceholder()
? _value.frequency
// ignore: cast_nullable_to_non_nullable
: frequency as int?,
lastUsed: lastUsed == const $CopyWithPlaceholder()
? _value.lastUsed
// ignore: cast_nullable_to_non_nullable
: lastUsed as DateTime?,
icon: icon == const $CopyWithPlaceholder()
? _value.icon
// ignore: cast_nullable_to_non_nullable
: icon as BrowserIcon?,
);
}
}
extension $BangDataCopyWith on BangData {
/// Returns a callable class used to build a new instance with modified fields.
/// Example: `instanceOfBangData.copyWith(...)` or `instanceOfBangData.copyWith.fieldName(...)`.
// ignore: library_private_types_in_public_api
_$BangDataCWProxy get copyWith => _$BangDataCWProxyImpl(this);
}
@@ -0,0 +1,37 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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/>.
*/
enum BangGroup {
general(
remote:
'https://raw.githubusercontent.com/FaFre/bangs/main/data/bangs.json',
bundled: 'assets/bangs/bangs.json',
),
kagi(
remote:
'https://raw.githubusercontent.com/FaFre/bangs/main/data/kagi_bangs.json',
bundled: 'assets/bangs/kagi_bangs.json',
),
user(remote: null, bundled: null);
final String? bundled;
final String? remote;
const BangGroup({required this.bundled, required this.remote});
}
@@ -0,0 +1,83 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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:json_annotation/json_annotation.dart';
import 'package:nullability/nullability.dart';
import 'package:weblibre/core/logger.dart';
import 'package:weblibre/features/bangs/data/models/bang_group.dart';
class BangKey {
final String trigger;
final BangGroup group;
const BangKey({required this.group, required this.trigger});
@override
String toString() {
return '${group.name}::$trigger';
}
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is BangKey &&
runtimeType == other.runtimeType &&
trigger == other.trigger &&
group == other.group;
@override
int get hashCode => Object.hash(trigger, group);
static BangKey? tryFromString(String key) {
try {
var [group, trigger] = key.split('::');
//Migrate to schema v5
if (group == 'assistant') {
group = BangGroup.kagi.name;
}
return BangKey(
group: BangGroup.values.firstWhere((g) => g.name == group),
trigger: trigger,
);
} catch (e, s) {
logger.w(
'Failed to parse BangKey from string: "$key"',
error: e,
stackTrace: s,
);
return null;
}
}
}
class BangKeyConverter implements JsonConverter<BangKey?, String?> {
const BangKeyConverter();
@override
BangKey? fromJson(String? json) {
return json.mapNotNull((json) => BangKey.tryFromString(json));
}
@override
String? toJson(BangKey? object) {
return object?.toString();
}
}
@@ -0,0 +1,35 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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:fast_equatable/fast_equatable.dart';
class SearchHistoryEntry with FastEquatable {
final String searchQuery;
final String trigger;
final DateTime searchDate;
SearchHistoryEntry({
required this.searchQuery,
required this.trigger,
required this.searchDate,
});
@override
List<Object?> get hashParameters => [searchQuery, trigger, searchDate];
}
@@ -0,0 +1,55 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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 'dart:io';
import 'package:drift/drift.dart';
import 'package:drift/native.dart';
import 'package:path/path.dart' as p;
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:sqlite3_flutter_libs/sqlite3_flutter_libs.dart';
import 'package:weblibre/core/database_registry.dart';
import 'package:weblibre/core/filesystem.dart';
import 'package:weblibre/features/bangs/data/database/database.dart';
part 'providers.g.dart';
@Riverpod(keepAlive: true)
BangDatabase bangDatabase(Ref ref) {
final db = BangDatabase(
LazyDatabase(() async {
final file = File(p.join(filesystem.profileDatabasesDir.path, 'bang.db'));
// Also work around limitations on old Android versions
if (Platform.isAndroid) {
await applyWorkaroundToOpenSqlite3OnOldAndroidVersions();
}
return NativeDatabase.createInBackground(file);
}),
);
DatabaseRegistry.instance.register('bang', db);
ref.onDispose(() async {
await db.close();
});
return db;
}
@@ -0,0 +1,51 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'providers.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(bangDatabase)
final bangDatabaseProvider = BangDatabaseProvider._();
final class BangDatabaseProvider
extends $FunctionalProvider<BangDatabase, BangDatabase, BangDatabase>
with $Provider<BangDatabase> {
BangDatabaseProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'bangDatabaseProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$bangDatabaseHash();
@$internal
@override
$ProviderElement<BangDatabase> $createElement($ProviderPointer pointer) =>
$ProviderElement(pointer);
@override
BangDatabase create(Ref ref) {
return bangDatabase(ref);
}
/// {@macro riverpod.override_with_value}
Override overrideWithValue(BangDatabase value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<BangDatabase>(value),
);
}
}
String _$bangDatabaseHash() => r'0369d508def140a32c08c0551cefed57b1ca4b26';
@@ -0,0 +1,82 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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 'dart:convert';
import 'package:exceptions/exceptions.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart' show rootBundle;
import 'package:http/http.dart' as http;
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:weblibre/core/http_error_handler.dart';
import 'package:weblibre/features/bangs/data/models/bang.dart';
import 'package:weblibre/features/bangs/data/models/bang_group.dart';
part 'data_source.g.dart';
@Riverpod(keepAlive: true)
class BangDataSourceService extends _$BangDataSourceService {
@override
void build() {}
Future<Result<List<Bang>>> fetchRemoteBangs(Uri url, BangGroup group) {
return Result.fromAsync(() async {
return await compute((args) async {
final client = http.Client();
try {
final url = Uri.parse(args[0]);
final response = await client
.get(url)
.timeout(const Duration(seconds: 30));
return jsonDecode(utf8.decode(response.bodyBytes)) as List;
} finally {
client.close();
}
}, [url.toString()]).then(
(json) => json.map((e) {
final bang = Bang.fromJson(e as Map<String, dynamic>);
return bang.copyWith.group(group);
}).toList(),
);
}, exceptionHandler: handleHttpError);
}
Future<DateTime> getBundledBangDate(String path) async {
final content = await rootBundle.loadString(path);
return DateTime.parse(content.trim()).toLocal();
}
Future<Result<List<Bang>>> getBundledBangs(String path, BangGroup? group) {
return Result.fromAsync(() async {
final content = await rootBundle.loadString(path);
final json = jsonDecode(content) as List;
return json.map((e) {
var bang = Bang.fromJson(e as Map<String, dynamic>);
if (group != null) {
bang = bang.copyWith.group(group);
}
return bang;
}).toList();
});
}
}
@@ -0,0 +1,63 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'data_source.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(BangDataSourceService)
final bangDataSourceServiceProvider = BangDataSourceServiceProvider._();
final class BangDataSourceServiceProvider
extends $NotifierProvider<BangDataSourceService, void> {
BangDataSourceServiceProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'bangDataSourceServiceProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$bangDataSourceServiceHash();
@$internal
@override
BangDataSourceService create() => BangDataSourceService();
/// {@macro riverpod.override_with_value}
Override overrideWithValue(void value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<void>(value),
);
}
}
String _$bangDataSourceServiceHash() =>
r'b1bd96bbd834de0f71af86d7f791d367d0a837be';
abstract class _$BangDataSourceService extends $Notifier<void> {
void build();
@$mustCallSuper
@override
void runBuild() {
final ref = this.ref as $Ref<void, void>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<void, void>,
void,
Object?,
Object?
>;
element.handleCreate(ref, build);
}
}
@@ -0,0 +1,102 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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:riverpod/riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:weblibre/features/bangs/data/models/bang_data.dart';
import 'package:weblibre/features/bangs/data/models/bang_group.dart';
import 'package:weblibre/features/bangs/data/models/bang_key.dart';
import 'package:weblibre/features/bangs/data/models/search_history_entry.dart';
import 'package:weblibre/features/bangs/domain/repositories/data.dart';
import 'package:weblibre/features/bangs/domain/repositories/sync.dart';
import 'package:weblibre/features/user/domain/repositories/general_settings.dart';
part 'bangs.g.dart';
@Riverpod(keepAlive: true)
Stream<BangData?> defaultSearchBangData(Ref ref) {
final key = ref.watch(
generalSettingsWithDefaultsProvider.select(
(value) => value.defaultSearchProvider,
),
);
final repository = ref.watch(bangDataRepositoryProvider.notifier);
return repository.watchBang(key);
}
@Riverpod()
Stream<BangData?> bangData(Ref ref, BangKey key) {
final repository = ref.watch(bangDataRepositoryProvider.notifier);
return repository.watchBang(key);
}
@Riverpod()
Stream<Map<String, List<String>>> bangCategories(Ref ref) {
final repository = ref.watch(bangDataRepositoryProvider.notifier);
return repository.watchCategories();
}
@Riverpod()
Stream<List<BangData>> bangList(
Ref ref, {
List<String>? triggers,
List<BangGroup>? groups,
String? domain,
({String category, String? subCategory})? categoryFilter,
bool? orderMostFrequentFirst,
}) {
final repository = ref.watch(bangDataRepositoryProvider.notifier);
return repository.watchBangs(
triggers: triggers,
groups: groups,
domain: domain,
categoryFilter: categoryFilter,
orderMostFrequentFirst: orderMostFrequentFirst,
);
}
@Riverpod()
Stream<List<BangData>> frequentBangList(Ref ref) {
final repository = ref.watch(bangDataRepositoryProvider.notifier);
return repository.watchFrequentBangs();
}
@Riverpod()
Stream<List<SearchHistoryEntry>> searchHistory(Ref ref) {
final repository = ref.watch(bangDataRepositoryProvider.notifier);
final maxSearchHistoryEntries = ref.watch(
generalSettingsWithDefaultsProvider.select(
(s) => s.maxSearchHistoryEntries,
),
);
return repository.watchSearchHistory(limit: maxSearchHistoryEntries);
}
@Riverpod()
Stream<DateTime?> lastSyncOfGroup(Ref ref, BangGroup group) {
final repository = ref.watch(bangSyncRepositoryProvider.notifier);
return repository.watchLastSyncOfGroup(group);
}
@Riverpod()
Stream<int> bangCountOfGroup(Ref ref, BangGroup group) {
final repository = ref.watch(bangDataRepositoryProvider.notifier);
return repository.watchBangCount(group);
}
@@ -0,0 +1,496 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'bangs.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(defaultSearchBangData)
final defaultSearchBangDataProvider = DefaultSearchBangDataProvider._();
final class DefaultSearchBangDataProvider
extends
$FunctionalProvider<AsyncValue<BangData?>, BangData?, Stream<BangData?>>
with $FutureModifier<BangData?>, $StreamProvider<BangData?> {
DefaultSearchBangDataProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'defaultSearchBangDataProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$defaultSearchBangDataHash();
@$internal
@override
$StreamProviderElement<BangData?> $createElement($ProviderPointer pointer) =>
$StreamProviderElement(pointer);
@override
Stream<BangData?> create(Ref ref) {
return defaultSearchBangData(ref);
}
}
String _$defaultSearchBangDataHash() =>
r'5f43b8989219cf3cb2f5ca65df351b6cb100427f';
@ProviderFor(bangData)
final bangDataProvider = BangDataFamily._();
final class BangDataProvider
extends
$FunctionalProvider<AsyncValue<BangData?>, BangData?, Stream<BangData?>>
with $FutureModifier<BangData?>, $StreamProvider<BangData?> {
BangDataProvider._({
required BangDataFamily super.from,
required BangKey super.argument,
}) : super(
retry: null,
name: r'bangDataProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$bangDataHash();
@override
String toString() {
return r'bangDataProvider'
''
'($argument)';
}
@$internal
@override
$StreamProviderElement<BangData?> $createElement($ProviderPointer pointer) =>
$StreamProviderElement(pointer);
@override
Stream<BangData?> create(Ref ref) {
final argument = this.argument as BangKey;
return bangData(ref, argument);
}
@override
bool operator ==(Object other) {
return other is BangDataProvider && other.argument == argument;
}
@override
int get hashCode {
return argument.hashCode;
}
}
String _$bangDataHash() => r'bd9f5ec8b29aab74620a9b5a4246cb7e3b2fd377';
final class BangDataFamily extends $Family
with $FunctionalFamilyOverride<Stream<BangData?>, BangKey> {
BangDataFamily._()
: super(
retry: null,
name: r'bangDataProvider',
dependencies: null,
$allTransitiveDependencies: null,
isAutoDispose: true,
);
BangDataProvider call(BangKey key) =>
BangDataProvider._(argument: key, from: this);
@override
String toString() => r'bangDataProvider';
}
@ProviderFor(bangCategories)
final bangCategoriesProvider = BangCategoriesProvider._();
final class BangCategoriesProvider
extends
$FunctionalProvider<
AsyncValue<Map<String, List<String>>>,
Map<String, List<String>>,
Stream<Map<String, List<String>>>
>
with
$FutureModifier<Map<String, List<String>>>,
$StreamProvider<Map<String, List<String>>> {
BangCategoriesProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'bangCategoriesProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$bangCategoriesHash();
@$internal
@override
$StreamProviderElement<Map<String, List<String>>> $createElement(
$ProviderPointer pointer,
) => $StreamProviderElement(pointer);
@override
Stream<Map<String, List<String>>> create(Ref ref) {
return bangCategories(ref);
}
}
String _$bangCategoriesHash() => r'947fcfd2dffcc7f585c6ed7379d319f4fe72293a';
@ProviderFor(bangList)
final bangListProvider = BangListFamily._();
final class BangListProvider
extends
$FunctionalProvider<
AsyncValue<List<BangData>>,
List<BangData>,
Stream<List<BangData>>
>
with $FutureModifier<List<BangData>>, $StreamProvider<List<BangData>> {
BangListProvider._({
required BangListFamily super.from,
required ({
List<String>? triggers,
List<BangGroup>? groups,
String? domain,
({String category, String? subCategory})? categoryFilter,
bool? orderMostFrequentFirst,
})
super.argument,
}) : super(
retry: null,
name: r'bangListProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$bangListHash();
@override
String toString() {
return r'bangListProvider'
''
'$argument';
}
@$internal
@override
$StreamProviderElement<List<BangData>> $createElement(
$ProviderPointer pointer,
) => $StreamProviderElement(pointer);
@override
Stream<List<BangData>> create(Ref ref) {
final argument =
this.argument
as ({
List<String>? triggers,
List<BangGroup>? groups,
String? domain,
({String category, String? subCategory})? categoryFilter,
bool? orderMostFrequentFirst,
});
return bangList(
ref,
triggers: argument.triggers,
groups: argument.groups,
domain: argument.domain,
categoryFilter: argument.categoryFilter,
orderMostFrequentFirst: argument.orderMostFrequentFirst,
);
}
@override
bool operator ==(Object other) {
return other is BangListProvider && other.argument == argument;
}
@override
int get hashCode {
return argument.hashCode;
}
}
String _$bangListHash() => r'd1e0bb9fa4f523ce516e075c0d149bf7803ebb2b';
final class BangListFamily extends $Family
with
$FunctionalFamilyOverride<
Stream<List<BangData>>,
({
List<String>? triggers,
List<BangGroup>? groups,
String? domain,
({String category, String? subCategory})? categoryFilter,
bool? orderMostFrequentFirst,
})
> {
BangListFamily._()
: super(
retry: null,
name: r'bangListProvider',
dependencies: null,
$allTransitiveDependencies: null,
isAutoDispose: true,
);
BangListProvider call({
List<String>? triggers,
List<BangGroup>? groups,
String? domain,
({String category, String? subCategory})? categoryFilter,
bool? orderMostFrequentFirst,
}) => BangListProvider._(
argument: (
triggers: triggers,
groups: groups,
domain: domain,
categoryFilter: categoryFilter,
orderMostFrequentFirst: orderMostFrequentFirst,
),
from: this,
);
@override
String toString() => r'bangListProvider';
}
@ProviderFor(frequentBangList)
final frequentBangListProvider = FrequentBangListProvider._();
final class FrequentBangListProvider
extends
$FunctionalProvider<
AsyncValue<List<BangData>>,
List<BangData>,
Stream<List<BangData>>
>
with $FutureModifier<List<BangData>>, $StreamProvider<List<BangData>> {
FrequentBangListProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'frequentBangListProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$frequentBangListHash();
@$internal
@override
$StreamProviderElement<List<BangData>> $createElement(
$ProviderPointer pointer,
) => $StreamProviderElement(pointer);
@override
Stream<List<BangData>> create(Ref ref) {
return frequentBangList(ref);
}
}
String _$frequentBangListHash() => r'2c1ecb7e9416772fc1c32d01d767e1eb4f865975';
@ProviderFor(searchHistory)
final searchHistoryProvider = SearchHistoryProvider._();
final class SearchHistoryProvider
extends
$FunctionalProvider<
AsyncValue<List<SearchHistoryEntry>>,
List<SearchHistoryEntry>,
Stream<List<SearchHistoryEntry>>
>
with
$FutureModifier<List<SearchHistoryEntry>>,
$StreamProvider<List<SearchHistoryEntry>> {
SearchHistoryProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'searchHistoryProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$searchHistoryHash();
@$internal
@override
$StreamProviderElement<List<SearchHistoryEntry>> $createElement(
$ProviderPointer pointer,
) => $StreamProviderElement(pointer);
@override
Stream<List<SearchHistoryEntry>> create(Ref ref) {
return searchHistory(ref);
}
}
String _$searchHistoryHash() => r'5f9508a6b286bfcd1b641bd429de46ad052a3dfe';
@ProviderFor(lastSyncOfGroup)
final lastSyncOfGroupProvider = LastSyncOfGroupFamily._();
final class LastSyncOfGroupProvider
extends
$FunctionalProvider<AsyncValue<DateTime?>, DateTime?, Stream<DateTime?>>
with $FutureModifier<DateTime?>, $StreamProvider<DateTime?> {
LastSyncOfGroupProvider._({
required LastSyncOfGroupFamily super.from,
required BangGroup super.argument,
}) : super(
retry: null,
name: r'lastSyncOfGroupProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$lastSyncOfGroupHash();
@override
String toString() {
return r'lastSyncOfGroupProvider'
''
'($argument)';
}
@$internal
@override
$StreamProviderElement<DateTime?> $createElement($ProviderPointer pointer) =>
$StreamProviderElement(pointer);
@override
Stream<DateTime?> create(Ref ref) {
final argument = this.argument as BangGroup;
return lastSyncOfGroup(ref, argument);
}
@override
bool operator ==(Object other) {
return other is LastSyncOfGroupProvider && other.argument == argument;
}
@override
int get hashCode {
return argument.hashCode;
}
}
String _$lastSyncOfGroupHash() => r'23d07f3132ba9bb35a31f74e3a69698d31d4c569';
final class LastSyncOfGroupFamily extends $Family
with $FunctionalFamilyOverride<Stream<DateTime?>, BangGroup> {
LastSyncOfGroupFamily._()
: super(
retry: null,
name: r'lastSyncOfGroupProvider',
dependencies: null,
$allTransitiveDependencies: null,
isAutoDispose: true,
);
LastSyncOfGroupProvider call(BangGroup group) =>
LastSyncOfGroupProvider._(argument: group, from: this);
@override
String toString() => r'lastSyncOfGroupProvider';
}
@ProviderFor(bangCountOfGroup)
final bangCountOfGroupProvider = BangCountOfGroupFamily._();
final class BangCountOfGroupProvider
extends $FunctionalProvider<AsyncValue<int>, int, Stream<int>>
with $FutureModifier<int>, $StreamProvider<int> {
BangCountOfGroupProvider._({
required BangCountOfGroupFamily super.from,
required BangGroup super.argument,
}) : super(
retry: null,
name: r'bangCountOfGroupProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$bangCountOfGroupHash();
@override
String toString() {
return r'bangCountOfGroupProvider'
''
'($argument)';
}
@$internal
@override
$StreamProviderElement<int> $createElement($ProviderPointer pointer) =>
$StreamProviderElement(pointer);
@override
Stream<int> create(Ref ref) {
final argument = this.argument as BangGroup;
return bangCountOfGroup(ref, argument);
}
@override
bool operator ==(Object other) {
return other is BangCountOfGroupProvider && other.argument == argument;
}
@override
int get hashCode {
return argument.hashCode;
}
}
String _$bangCountOfGroupHash() => r'211ffcd7f49b637a7953f913dc5eafda344423f3';
final class BangCountOfGroupFamily extends $Family
with $FunctionalFamilyOverride<Stream<int>, BangGroup> {
BangCountOfGroupFamily._()
: super(
retry: null,
name: r'bangCountOfGroupProvider',
dependencies: null,
$allTransitiveDependencies: null,
isAutoDispose: true,
);
BangCountOfGroupProvider call(BangGroup group) =>
BangCountOfGroupProvider._(argument: group, from: this);
@override
String toString() => r'bangCountOfGroupProvider';
}
@@ -0,0 +1,102 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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 'dart:async';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:weblibre/features/bangs/data/models/bang_data.dart';
import 'package:weblibre/features/bangs/data/providers.dart';
import 'package:weblibre/features/bangs/domain/providers/bangs.dart';
import 'package:weblibre/features/bangs/domain/repositories/data.dart';
import 'package:weblibre/features/user/domain/repositories/general_settings.dart';
part 'search.g.dart';
@Riverpod()
class BangSearch extends _$BangSearch {
late StreamController<List<BangData>> _streamController;
Future<Uri> triggerBangSearch(BangData bang, String searchQuery) async {
final bangDataNotifier = ref.read(bangDataRepositoryProvider.notifier);
final settings = ref.read(generalSettingsWithDefaultsProvider);
await bangDataNotifier.increaseFrequency(bang.toKey());
await bangDataNotifier.addSearchEntry(
bang.group,
bang.trigger,
searchQuery,
maxEntryCount: settings.maxSearchHistoryEntries,
);
return bang.getTemplateUrl(searchQuery);
}
Future<void> search(String input) async {
if (input.isNotEmpty) {
await ref.read(bangDatabaseProvider).bangDao.queryBangs(input).get().then(
(value) {
if (!_streamController.isClosed) {
_streamController.add(value);
}
},
);
}
}
@override
Stream<List<BangData>> build() {
_streamController = StreamController();
// Emit initial empty list so UI doesn't show loading state
_streamController.add([]);
ref.onDispose(() async {
await _streamController.close();
});
return _streamController.stream;
}
}
@Riverpod()
class SeamlessBang extends _$SeamlessBang {
bool _hasSearch = false;
void search(String input) {
if (input.isNotEmpty) {
if (!_hasSearch) {
_hasSearch = true;
ref.invalidateSelf();
}
//Don't block
unawaited(ref.read(bangSearchProvider.notifier).search(input));
} else if (_hasSearch) {
_hasSearch = false;
ref.invalidateSelf();
}
}
@override
AsyncValue<List<BangData>> build() {
return _hasSearch
? ref.watch(bangSearchProvider)
: ref.watch(frequentBangListProvider);
}
}
@@ -0,0 +1,111 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'search.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(BangSearch)
final bangSearchProvider = BangSearchProvider._();
final class BangSearchProvider
extends $StreamNotifierProvider<BangSearch, List<BangData>> {
BangSearchProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'bangSearchProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$bangSearchHash();
@$internal
@override
BangSearch create() => BangSearch();
}
String _$bangSearchHash() => r'feed24edfe703b0697f4a855be9c7359c456b0f2';
abstract class _$BangSearch extends $StreamNotifier<List<BangData>> {
Stream<List<BangData>> build();
@$mustCallSuper
@override
void runBuild() {
final ref = this.ref as $Ref<AsyncValue<List<BangData>>, List<BangData>>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<AsyncValue<List<BangData>>, List<BangData>>,
AsyncValue<List<BangData>>,
Object?,
Object?
>;
element.handleCreate(ref, build);
}
}
@ProviderFor(SeamlessBang)
final seamlessBangProvider = SeamlessBangProvider._();
final class SeamlessBangProvider
extends $NotifierProvider<SeamlessBang, AsyncValue<List<BangData>>> {
SeamlessBangProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'seamlessBangProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$seamlessBangHash();
@$internal
@override
SeamlessBang create() => SeamlessBang();
/// {@macro riverpod.override_with_value}
Override overrideWithValue(AsyncValue<List<BangData>> value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<AsyncValue<List<BangData>>>(value),
);
}
}
String _$seamlessBangHash() => r'8bd7a2cbe4c302ae08f85167290666a7437f8b9b';
abstract class _$SeamlessBang extends $Notifier<AsyncValue<List<BangData>>> {
AsyncValue<List<BangData>> build();
@$mustCallSuper
@override
void runBuild() {
final ref =
this.ref
as $Ref<AsyncValue<List<BangData>>, AsyncValue<List<BangData>>>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<
AsyncValue<List<BangData>>,
AsyncValue<List<BangData>>
>,
AsyncValue<List<BangData>>,
Object?,
Object?
>;
element.handleCreate(ref, build);
}
}
@@ -0,0 +1,167 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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 'dart:convert';
import 'package:drift/drift.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:weblibre/features/bangs/data/models/bang.dart';
import 'package:weblibre/features/bangs/data/models/bang_data.dart';
import 'package:weblibre/features/bangs/data/models/bang_group.dart';
import 'package:weblibre/features/bangs/data/models/bang_key.dart';
import 'package:weblibre/features/bangs/data/models/search_history_entry.dart';
import 'package:weblibre/features/bangs/data/providers.dart';
part 'data.g.dart';
@Riverpod(keepAlive: true)
class BangDataRepository extends _$BangDataRepository {
@override
void build() {}
Stream<BangData?> watchBang(BangKey? key) {
if (key != null) {
return ref
.read(bangDatabaseProvider)
.bangDao
.getBangData(key.group, key.trigger)
.watchSingleOrNull();
} else {
return Stream.value(null);
}
}
Stream<Map<String, List<String>>> watchCategories() {
return ref
.read(bangDatabaseProvider)
.definitionsDrift
.categoriesJson()
.watchSingle()
.map((json) {
final decoded = jsonDecode(json) as Map<String, dynamic>;
return decoded.map(
(key, value) => MapEntry(key, (value as List<dynamic>).cast()),
);
});
}
Stream<int> watchBangCount(BangGroup group) {
return ref
.read(bangDatabaseProvider)
.bangDao
.getBangCount(groups: [group])
.watchSingle();
}
Stream<List<BangData>> watchBangs({
Iterable<String>? triggers,
Iterable<BangGroup>? groups,
String? domain,
({String category, String? subCategory})? categoryFilter,
bool? orderMostFrequentFirst,
}) {
return ref
.read(bangDatabaseProvider)
.bangDao
.getBangDataList(
triggers: triggers,
groups: groups,
domain: domain,
category: categoryFilter?.category,
subCategory: categoryFilter?.subCategory,
orderMostFrequentFirst: orderMostFrequentFirst,
)
.watch();
}
Stream<List<BangData>> watchFrequentBangs({Iterable<BangGroup>? groups}) {
return ref
.read(bangDatabaseProvider)
.bangDao
.getFrequentBangDataList(groups: groups)
.watch();
}
Stream<List<SearchHistoryEntry>> watchSearchHistory({required int limit}) {
return ref
.read(bangDatabaseProvider)
.definitionsDrift
.searchHistoryEntries(limit: limit)
.watch();
}
Future<void> increaseFrequency(BangKey key) {
return ref.read(bangDatabaseProvider).bangDao.increaseBangFrequency(key);
}
Future<void> addSearchEntry(
BangGroup group,
String trigger,
String searchQuery, {
required int maxEntryCount,
}) async {
// Skip capturing history if maxEntryCount is 0
if (maxEntryCount <= 0) {
return;
}
final db = ref.read(bangDatabaseProvider);
//Pack in a transaction to bundle rebuilds of watch() queries
return db.transaction(() async {
await db.bangDao.addSearchEntry(group, trigger, searchQuery);
await db.definitionsDrift.evictHistoryEntries(limit: maxEntryCount);
});
}
Future<void> removeSearchEntry(String searchQuery) {
return ref
.read(bangDatabaseProvider)
.bangDao
.removeSearchEntry(searchQuery);
}
Future<int> resetFrequencies() {
return ref.read(bangDatabaseProvider).bangFrequency.deleteAll();
}
Future<int> resetFrequency(String trigger) {
return ref
.read(bangDatabaseProvider)
.bangFrequency
.deleteWhere((t) => t.trigger.equals(trigger));
}
Future<BangData?> getBang(BangKey key) {
return ref
.read(bangDatabaseProvider)
.bangDao
.getBangData(key.group, key.trigger)
.getSingleOrNull();
}
Future<void> upsertBang(Bang bang) {
return ref.read(bangDatabaseProvider).bangDao.upsertBang(bang);
}
Future<void> deleteBang(BangKey key) {
return ref.read(bangDatabaseProvider).syncDao.deleteBangs(key.group, [
key.trigger,
]);
}
}
@@ -0,0 +1,63 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'data.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(BangDataRepository)
final bangDataRepositoryProvider = BangDataRepositoryProvider._();
final class BangDataRepositoryProvider
extends $NotifierProvider<BangDataRepository, void> {
BangDataRepositoryProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'bangDataRepositoryProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$bangDataRepositoryHash();
@$internal
@override
BangDataRepository create() => BangDataRepository();
/// {@macro riverpod.override_with_value}
Override overrideWithValue(void value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<void>(value),
);
}
}
String _$bangDataRepositoryHash() =>
r'c562ef10d75ca6dee13805f84d2491cf2a89aaac';
abstract class _$BangDataRepository extends $Notifier<void> {
void build();
@$mustCallSuper
@override
void runBuild() {
final ref = this.ref as $Ref<void, void>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<void, void>,
void,
Object?,
Object?
>;
element.handleCreate(ref, build);
}
}
@@ -0,0 +1,191 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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:exceptions/exceptions.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:weblibre/features/bangs/data/database/database.dart';
import 'package:weblibre/features/bangs/data/models/bang_group.dart';
import 'package:weblibre/features/bangs/data/providers.dart';
import 'package:weblibre/features/bangs/data/services/data_source.dart';
part 'sync.g.dart';
@Riverpod(keepAlive: true)
class BangSyncRepository extends _$BangSyncRepository {
static Future<Result<void>> _fetchAndSyncRemote({
required BangDataSourceService sourceService,
required BangDatabase db,
required Uri url,
required BangGroup group,
required Duration? syncInterval,
}) async {
if (syncInterval != null) {
final lastSync = await db.syncDao
.getLastSyncOfGroup(group)
.getSingleOrNull();
if (lastSync != null &&
DateTime.now().difference(lastSync) < syncInterval) {
return Result.success(null);
}
}
final result = await sourceService.fetchRemoteBangs(url, group);
return result.flatMapAsync((remoteBangs) async {
await db.syncDao.syncBangs(
group: group,
remoteBangs: remoteBangs,
syncTime: DateTime.now(),
);
await db.definitionsDrift.optimizeBangFtsIndex();
await db.definitionsDrift.optimizeTriggerFtsIndex();
});
}
static Future<Result<void>> _fetchAndSyncBundled({
required BangDataSourceService sourceService,
required BangDatabase db,
required BangGroup group,
}) async {
if (group.bundled == null) {
return Result.failure(
const ErrorMessage(source: 'BangSync', message: 'Not bundled'),
);
}
if (group.remote == null) {
return Result.failure(
const ErrorMessage(source: 'BangSync', message: 'No remote source'),
);
}
final lastSync = await db.syncDao
.getLastSyncOfGroup(group)
.getSingleOrNull();
final sourceDate = await sourceService.getBundledBangDate(
'assets/bangs/last_sync.txt',
);
if (lastSync != null &&
(sourceDate == lastSync ||
sourceDate.difference(lastSync).isNegative)) {
return Result.success(null);
}
final result = await sourceService.getBundledBangs(group.bundled!, group);
return result.flatMapAsync((remoteBangs) async {
await db.syncDao.syncBangs(
group: group,
remoteBangs: remoteBangs,
syncTime: sourceDate,
);
await db.definitionsDrift.optimizeBangFtsIndex();
await db.definitionsDrift.optimizeTriggerFtsIndex();
});
}
Future<Result<void>> syncRemoteBangGroup(
BangGroup group,
Duration? syncInterval,
) async {
try {
return Result.success(
await ref
.read(bangDatabaseProvider)
.computeWithDatabase(
connect: BangDatabase.new,
computation: (db) async {
final ref = ProviderContainer();
final result = await _fetchAndSyncRemote(
sourceService: ref.read(
bangDataSourceServiceProvider.notifier,
),
db: db,
url: Uri.parse(group.remote!),
group: group,
syncInterval: syncInterval,
);
//Throw if necessary
return result.value;
},
),
);
} catch (e) {
return Result.failure(
ErrorMessage(
message: "Failed to sync Bangs (${group.name})",
source: 'BangSync',
details: e,
),
);
}
}
Future<Result<void>> syncBundledBangGroup(BangGroup group) async {
try {
final db = ref.read(bangDatabaseProvider);
final result = await _fetchAndSyncBundled(
sourceService: ref.read(bangDataSourceServiceProvider.notifier),
db: db,
group: group,
);
//Throw if necessary
return result;
} catch (e) {
return Result.failure(
ErrorMessage(
message: "Failed to sync Bangs (${group.name})",
source: 'BangSync',
details: e,
),
);
}
}
Stream<DateTime?> watchLastSyncOfGroup(BangGroup group) {
return ref
.read(bangDatabaseProvider)
.syncDao
.getLastSyncOfGroup(group)
.watchSingleOrNull();
}
Future<Map<BangGroup, Result<void>>> syncBundledBangGroups({
Set<BangGroup>? groups,
}) async {
//Default to all sources
groups ??= BangGroup.values.where((e) => e.bundled != null).toSet();
//Run isolated operations
final futures = groups.map(
(source) => syncBundledBangGroup(
source,
).then((result) => MapEntry(source, result)),
);
return Map.fromEntries(await Future.wait(futures));
}
@override
void build() {}
}
@@ -0,0 +1,63 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'sync.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(BangSyncRepository)
final bangSyncRepositoryProvider = BangSyncRepositoryProvider._();
final class BangSyncRepositoryProvider
extends $NotifierProvider<BangSyncRepository, void> {
BangSyncRepositoryProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'bangSyncRepositoryProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$bangSyncRepositoryHash();
@$internal
@override
BangSyncRepository create() => BangSyncRepository();
/// {@macro riverpod.override_with_value}
Override overrideWithValue(void value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<void>(value),
);
}
}
String _$bangSyncRepositoryHash() =>
r'1347dcbd03f6a1a4fa3bbbae5d9302098d260c50';
abstract class _$BangSyncRepository extends $Notifier<void> {
void build();
@$mustCallSuper
@override
void runBuild() {
final ref = this.ref as $Ref<void, void>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<void, void>,
void,
Object?,
Object?
>;
element.handleCreate(ref, build);
}
}
@@ -0,0 +1,46 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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:riverpod/riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:weblibre/features/bangs/data/providers.dart';
import 'package:weblibre/features/user/domain/repositories/general_settings.dart';
part 'search_history_cleanup.g.dart';
/// Service that listens to maxSearchHistoryEntries setting changes
/// and cleans up search history when the limit is reduced.
@Riverpod(keepAlive: true)
class SearchHistoryCleanupService extends _$SearchHistoryCleanupService {
@override
void build() {
ref.listen(
generalSettingsWithDefaultsProvider.select(
(settings) => settings.maxSearchHistoryEntries,
),
(previous, next) async {
// Only cleanup when limit is reduced (including to 0)
if (previous != null && next < previous) {
final db = ref.read(bangDatabaseProvider);
await db.definitionsDrift.evictHistoryEntries(limit: next);
}
},
);
}
}
@@ -0,0 +1,73 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'search_history_cleanup.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
/// Service that listens to maxSearchHistoryEntries setting changes
/// and cleans up search history when the limit is reduced.
@ProviderFor(SearchHistoryCleanupService)
final searchHistoryCleanupServiceProvider =
SearchHistoryCleanupServiceProvider._();
/// Service that listens to maxSearchHistoryEntries setting changes
/// and cleans up search history when the limit is reduced.
final class SearchHistoryCleanupServiceProvider
extends $NotifierProvider<SearchHistoryCleanupService, void> {
/// Service that listens to maxSearchHistoryEntries setting changes
/// and cleans up search history when the limit is reduced.
SearchHistoryCleanupServiceProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'searchHistoryCleanupServiceProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$searchHistoryCleanupServiceHash();
@$internal
@override
SearchHistoryCleanupService create() => SearchHistoryCleanupService();
/// {@macro riverpod.override_with_value}
Override overrideWithValue(void value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<void>(value),
);
}
}
String _$searchHistoryCleanupServiceHash() =>
r'4e84ab50fa2ad55c615bb63a667c95383715570b';
/// Service that listens to maxSearchHistoryEntries setting changes
/// and cleans up search history when the limit is reduced.
abstract class _$SearchHistoryCleanupService extends $Notifier<void> {
void build();
@$mustCallSuper
@override
void runBuild() {
final ref = this.ref as $Ref<void, void>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<void, void>,
void,
Object?,
Object?
>;
element.handleCreate(ref, build);
}
}
@@ -0,0 +1,50 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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:flutter/material.dart';
/// Dialog to confirm bang deletion.
/// Returns true if user confirms deletion, false if cancelled, null if dismissed.
Future<bool?> showDeleteBangDialog(BuildContext context) {
return showDialog<bool?>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
icon: const Icon(Icons.warning),
title: const Text('Delete Bang'),
content: const Text('Are you sure you want to delete this Bang?'),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.pop(context, false);
},
child: const Text('Cancel'),
),
TextButton(
onPressed: () {
Navigator.pop(context, true);
},
child: const Text('Delete'),
),
],
);
},
);
}
@@ -0,0 +1,127 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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:fading_scroll/fading_scroll.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:weblibre/core/routing/routes.dart';
import 'package:weblibre/features/bangs/data/models/bang_key.dart';
import 'package:weblibre/features/bangs/domain/providers/bangs.dart';
import 'package:weblibre/features/geckoview/features/browser/domain/providers.dart';
import 'package:weblibre/presentation/widgets/failure_widget.dart';
class BangCategoriesScreen extends HookConsumerWidget {
const BangCategoriesScreen({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final categoriesAsync = ref.watch(bangCategoriesProvider);
return Scaffold(
appBar: AppBar(
title: const Text('Bang Categories'),
actions: [
IconButton(
onPressed: () async {
final trigger = await const BangSearchRoute().push<BangKey?>(
context,
);
if (trigger != null) {
ref
.read(selectedBangTriggerProvider().notifier)
.setTrigger(trigger);
}
},
icon: const Icon(Icons.search),
),
],
),
body: SafeArea(
child: categoriesAsync.when(
skipLoadingOnReload: true,
data: (categories) {
return FadingScroll(
fadingSize: 25,
builder: (context, controller) {
return SingleChildScrollView(
controller: controller,
child: HookBuilder(
builder: (context) {
final expanded = useState(<String>{});
return ExpansionPanelList(
expansionCallback: (index, expand) {
final key = categories.keys.elementAt(index);
if (!expanded.value.contains(key)) {
expanded.value = {...expanded.value, key};
} else {
expanded.value = {...expanded.value}..remove(key);
}
},
children: categories.entries
.map(
(category) => ExpansionPanel(
canTapOnHeader: true,
isExpanded: expanded.value.contains(
category.key,
),
headerBuilder: (context, isExpanded) =>
ListTile(title: Text(category.key)),
body: Padding(
padding: const EdgeInsets.only(left: 16.0),
child: Column(
mainAxisSize: MainAxisSize.min,
children: category.value
.map(
(subCategory) => ListTile(
title: Text(subCategory),
onTap: () async {
await BangSubCategoryRoute(
category: category.key,
subCategory: subCategory,
).push(context);
},
),
)
.toList(),
),
),
),
)
.toList(),
);
},
),
);
},
);
},
error: (error, stackTrace) => Center(
child: FailureWidget(
title: 'Failed to load Bang Categories',
exception: error,
),
),
loading: () => const Center(child: CircularProgressIndicator()),
),
),
);
}
}
@@ -0,0 +1,95 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:nullability/nullability.dart';
import 'package:weblibre/core/routing/routes.dart';
import 'package:weblibre/features/bangs/domain/providers/bangs.dart';
import 'package:weblibre/features/bangs/presentation/widgets/bang_details.dart';
import 'package:weblibre/features/geckoview/domain/providers/tab_state.dart';
import 'package:weblibre/features/geckoview/features/browser/domain/providers.dart';
import 'package:weblibre/features/user/domain/repositories/general_settings.dart';
import 'package:weblibre/presentation/widgets/failure_widget.dart';
class BangCategoryScreen extends HookConsumerWidget {
final String? category;
final String? subCategory;
const BangCategoryScreen({this.category, this.subCategory, super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final bangsAsync = ref.watch(
bangListProvider(
categoryFilter: category.mapNotNull(
(category) => (category: category, subCategory: subCategory),
),
),
);
return Scaffold(
body: CustomScrollView(
slivers: [
SliverAppBar.medium(title: Text('$category: $subCategory')),
bangsAsync.when(
skipLoadingOnReload: true,
data: (bangs) {
return SliverList.builder(
itemCount: bangs.length,
itemBuilder: (context, index) {
final bang = bangs[index];
return BangDetails(
bang,
onTap: () {
ref
.read(selectedBangTriggerProvider().notifier)
.setTrigger(bang.toKey());
final settings = ref.read(
generalSettingsWithDefaultsProvider,
);
SearchRoute(
tabType:
ref.read(selectedTabTypeProvider) ??
settings.effectiveDefaultCreateTabType,
).go(context);
},
);
},
);
},
error: (error, stackTrace) => SliverToBoxAdapter(
child: Center(
child: FailureWidget(
title: 'Failed to load Bangs',
exception: error,
),
),
),
loading: () => const SliverToBoxAdapter(
child: Center(child: CircularProgressIndicator()),
),
),
],
),
);
}
}
@@ -0,0 +1,346 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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:fast_equatable/fast_equatable.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:go_router/go_router.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:nullability/nullability.dart';
import 'package:weblibre/features/bangs/data/models/bang.dart';
import 'package:weblibre/features/bangs/data/models/bang_group.dart';
import 'package:weblibre/features/bangs/data/models/bang_key.dart';
import 'package:weblibre/features/bangs/domain/providers/bangs.dart';
import 'package:weblibre/features/bangs/domain/repositories/data.dart';
import 'package:weblibre/features/bangs/presentation/dialogs/delete_bang_dialog.dart';
import 'package:weblibre/utils/form_validators.dart';
import 'package:weblibre/utils/ui_helper.dart' as ui_helper;
class EditBangScreen extends HookConsumerWidget {
final Bang? initialBang;
const EditBangScreen({super.key, required this.initialBang});
@override
Widget build(BuildContext context, WidgetRef ref) {
final formKey = useMemoized(() => GlobalKey<FormState>());
final categories = ref.watch(
bangCategoriesProvider.select((value) => value.value),
);
final nameTextController = useTextEditingController(
text: initialBang?.websiteName,
);
final triggerTextController = useTextEditingController(
text: initialBang?.trigger,
);
final urlTextController = useTextEditingController(
text: initialBang?.urlTemplate,
);
final category = useState(initialBang?.category);
final subCategory = useState(initialBang?.subCategory);
final formatFlags = useState(initialBang?.format);
return Scaffold(
appBar: AppBar(
title: Text(initialBang == null ? 'New Bang' : 'Edit Bang'),
actions: [
IconButton(
onPressed: () async {
if (formKey.currentState?.validate() ?? false) {
final existingBang = await ref
.read(bangDataRepositoryProvider.notifier)
.getBang(
BangKey(
group: BangGroup.user,
trigger: triggerTextController.text,
),
);
if ((initialBang == null && existingBang != null) ||
(initialBang != null &&
existingBang != null &&
existingBang.trigger != initialBang!.trigger)) {
if (context.mounted) {
ui_helper.showErrorMessage(
context,
'A Bang with Trigger "${triggerTextController.text}" does already exist',
);
}
return;
}
final uri = parseValidatedUrl(
urlTextController.text,
eagerParsing: false,
onlyHttpProtocol: true,
);
if (uri == null) {
return;
}
final bang = Bang(
group: BangGroup.user,
trigger: triggerTextController.text,
websiteName: nameTextController.text,
domain: uri.host,
urlTemplate: urlTextController.text,
searxngApi: false,
category: category.value,
subCategory: subCategory.value,
additionalTriggers: initialBang?.additionalTriggers,
snapDomain: initialBang?.snapDomain,
format: formatFlags.value.isNotEmpty
? formatFlags.value
: null,
);
if (initialBang != null &&
initialBang!.trigger != bang.trigger) {
await ref
.read(bangDataRepositoryProvider.notifier)
.deleteBang(
BangKey(
group: BangGroup.user,
trigger: initialBang!.trigger,
),
);
}
await ref
.read(bangDataRepositoryProvider.notifier)
.upsertBang(bang);
if (context.mounted) {
context.pop();
}
}
},
icon: const Icon(Icons.check),
),
],
),
body: SafeArea(
child: Form(
key: formKey,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12.0),
child: ListView(
children: [
TextFormField(
controller: nameTextController,
decoration: const InputDecoration(
label: Text('Name'),
helper: Text(
'The name of the website associated with the bang',
),
floatingLabelBehavior: FloatingLabelBehavior.always,
),
validator: validateRequired,
),
const SizedBox(height: 16),
TextFormField(
controller: triggerTextController,
decoration: const InputDecoration(
label: Text('Trigger'),
helper: Text(
'The specific trigger word or phrase used to invoke the bang.',
),
floatingLabelBehavior: FloatingLabelBehavior.always,
),
validator: validateRequired,
),
const SizedBox(height: 16),
TextFormField(
controller: urlTextController,
keyboardType: TextInputType.url,
decoration: const InputDecoration(
label: Text('URL'),
helper: Text(
"The URL template to use when the bang is invoked, where `{{{s}}}` is replaced by the user's query.",
),
floatingLabelBehavior: FloatingLabelBehavior.always,
),
validator: (value) {
if (value?.contains('{{{s}}}') != true) {
return 'Must contain the query placeholder {{{s}}}';
}
return validateUrl(
value,
eagerParsing: false,
onlyHttpProtocol: true,
);
},
),
const SizedBox(height: 24),
DropdownMenuFormField(
key: ValueKey(EquatableValue([category.value, categories])),
enableFilter: true,
requestFocusOnTap: true,
label: const Text('Category'),
expandedInsets: EdgeInsets.zero,
initialSelection: category.value,
dropdownMenuEntries: [
...?categories?.keys.map(
(e) => DropdownMenuEntry(value: e, label: e),
),
],
onSelected: (value) {
if (category.value != value) {
category.value = value;
subCategory.value = null;
}
},
),
const SizedBox(height: 16),
DropdownMenuFormField(
key: ValueKey(
EquatableValue([subCategory.value, categories]),
),
enableFilter: true,
requestFocusOnTap: true,
label: const Text('Sub Category'),
expandedInsets: EdgeInsets.zero,
initialSelection: subCategory.value,
dropdownMenuEntries: [
...?categories?[category.value]?.map(
(e) => DropdownMenuEntry(value: e, label: e),
),
],
onSelected: (value) {
if (subCategory.value != value) {
subCategory.value = value;
}
},
),
const SizedBox(height: 16),
Text('Flags', style: Theme.of(context).textTheme.labelMedium),
const SizedBox(height: 4),
CheckboxListTile(
value:
formatFlags.value?.contains(BangFormat.openBasePath) ??
false,
title: const Text('Open Base Path'),
subtitle: const Text(
'When the bang is invoked with no query, opens the base path of the URL (/) instead of any path given in the template (g., /search)',
),
onChanged: (value) {
if (value != null) {
formatFlags.value =
value
? {
...?formatFlags.value,
BangFormat.openBasePath,
}
: {...?formatFlags.value}
..remove(BangFormat.openBasePath);
}
},
),
CheckboxListTile(
value:
formatFlags.value?.contains(
BangFormat.urlEncodePlaceholder,
) ??
false,
title: const Text('URL Encode Placeholder'),
subtitle: const Text(
'URL encode the search terms. Some sites do not work with this, so it can be disabled by omitting this.',
),
onChanged: (value) {
if (value != null) {
formatFlags.value =
value
? {
...?formatFlags.value,
BangFormat.urlEncodePlaceholder,
}
: {...?formatFlags.value}
..remove(BangFormat.urlEncodePlaceholder);
}
},
),
CheckboxListTile(
value:
formatFlags.value?.contains(
BangFormat.urlEncodeSpaceToPlus,
) ??
false,
title: const Text('URL Encode Space to Plus'),
subtitle: const Text(
'URL encodes spaces as +, instead of %20. Some sites only work correctly with one or the other.',
),
onChanged: (value) {
if (value != null) {
formatFlags.value =
value
? {
...?formatFlags.value,
BangFormat.urlEncodeSpaceToPlus,
}
: {...?formatFlags.value}
..remove(BangFormat.urlEncodeSpaceToPlus);
}
},
),
if (initialBang != null)
SizedBox(
width: double.infinity,
child: OutlinedButton.icon(
style: OutlinedButton.styleFrom(
side: BorderSide(
color: Theme.of(context).colorScheme.error,
),
foregroundColor: Theme.of(context).colorScheme.error,
iconColor: Theme.of(context).colorScheme.error,
),
label: const Text('Delete'),
icon: const Icon(Icons.delete),
onPressed: () async {
final result = await showDeleteBangDialog(context);
if (result == true) {
await ref
.read(bangDataRepositoryProvider.notifier)
.deleteBang(
BangKey(
group: BangGroup.user,
trigger: initialBang!.trigger,
),
);
if (context.mounted) {
context.pop();
}
}
},
),
),
],
),
),
),
),
);
}
}
@@ -0,0 +1,64 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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:flutter/material.dart';
import 'package:flutter_material_design_icons/flutter_material_design_icons.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:weblibre/core/routing/routes.dart';
class BangMenuScreen extends HookConsumerWidget {
const BangMenuScreen({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
return Scaffold(
appBar: AppBar(title: const Text('Bangs')),
body: SafeArea(
child: ListView(
children: [
ListTile(
leading: const Icon(MdiIcons.accountAlert),
title: const Text('Manage User Bangs'),
trailing: const Icon(Icons.chevron_right),
onTap: () async {
await const UserBangsRoute().push(context);
},
),
ListTile(
leading: const Icon(Icons.search),
title: const Text('Search Bangs'),
trailing: const Icon(Icons.chevron_right),
onTap: () async {
await const BangSearchRoute().push(context);
},
),
ListTile(
leading: const Icon(MdiIcons.fileTree),
title: const Text('Browse Categories'),
trailing: const Icon(Icons.chevron_right),
onTap: () async {
await const BangCategoriesRoute().push(context);
},
),
],
),
),
);
}
}
@@ -0,0 +1,108 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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 'dart:async';
import 'package:fading_scroll/fading_scroll.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:go_router/go_router.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:weblibre/features/bangs/domain/providers/search.dart';
import 'package:weblibre/features/bangs/presentation/widgets/bang_details.dart';
import 'package:weblibre/features/user/domain/providers.dart';
import 'package:weblibre/presentation/widgets/failure_widget.dart';
class BangSearchScreen extends HookConsumerWidget {
final String? initialSearchText;
const BangSearchScreen({super.key, this.initialSearchText});
@override
Widget build(BuildContext context, WidgetRef ref) {
final resultsAsync = ref.watch(bangSearchProvider);
final incognitoEnabled = ref.watch(incognitoModeEnabledProvider);
final focusNode = useFocusNode();
final textEditingController = useTextEditingController(
text: initialSearchText,
);
useOnListenableChange(textEditingController, () {
unawaited(
ref
.read(bangSearchProvider.notifier)
.search(textEditingController.text),
);
});
return Scaffold(
appBar: AppBar(
title: TextField(
enableIMEPersonalizedLearning: !incognitoEnabled,
focusNode: focusNode,
controller: textEditingController,
autofocus: true,
autocorrect: false,
decoration: const InputDecoration.collapsed(hintText: 'Search'),
),
actions: [
IconButton(
onPressed: () {
if (textEditingController.text.isEmpty) {
context.pop();
} else {
textEditingController.clear();
focusNode.requestFocus();
}
},
icon: const Icon(Icons.clear),
),
],
),
body: SafeArea(
child: resultsAsync.when(
skipLoadingOnReload: true,
data: (bangs) => FadingScroll(
fadingSize: 25,
builder: (context, controller) {
return ListView.builder(
controller: controller,
itemCount: bangs.length,
itemBuilder: (context, index) {
final bang = bangs[index];
return BangDetails(
bang,
onTap: () {
context.pop(bang.toKey());
},
);
},
);
},
),
error: (error, stackTrace) => Center(
child: FailureWidget(title: 'Bang Search failed', exception: error),
),
loading: () => const Center(child: CircularProgressIndicator()),
),
),
);
}
}
@@ -0,0 +1,102 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:weblibre/core/routing/routes.dart';
import 'package:weblibre/features/bangs/data/models/bang_group.dart';
import 'package:weblibre/features/bangs/data/models/bang_key.dart';
import 'package:weblibre/features/bangs/domain/providers/bangs.dart';
import 'package:weblibre/features/bangs/domain/repositories/data.dart';
import 'package:weblibre/features/bangs/presentation/widgets/bang_details.dart';
import 'package:weblibre/presentation/widgets/failure_widget.dart';
class UserBangs extends HookConsumerWidget {
static const _userGroupFilter = [BangGroup.user];
const UserBangs({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final bangsAsync = ref.watch(bangListProvider(groups: _userGroupFilter));
return Scaffold(
appBar: AppBar(title: const Text('User Bangs')),
body: bangsAsync.when(
skipLoadingOnReload: true,
data: (bangs) {
return ListView.builder(
itemCount: bangs.length,
itemBuilder: (context, index) {
final bang = bangs[index];
return Slidable(
endActionPane: ActionPane(
motion: const ScrollMotion(),
children: [
SlidableAction(
onPressed: (context) async {
await ref
.read(bangDataRepositoryProvider.notifier)
.deleteBang(
BangKey(
group: BangGroup.user,
trigger: bang.trigger,
),
);
},
backgroundColor: Theme.of(
context,
).colorScheme.errorContainer,
foregroundColor: Theme.of(
context,
).colorScheme.onErrorContainer,
icon: Icons.delete,
label: 'Delete',
),
],
),
child: BangDetails(
bang,
onTap: () async {
await EditUserBangRoute(
initialBang: jsonEncode(bang.toJson()),
).push(context);
},
),
);
},
);
},
error: (error, stackTrace) => Center(
child: FailureWidget(title: 'Failed to load Bangs', exception: error),
),
loading: () => const Center(child: CircularProgressIndicator()),
),
floatingActionButton: FloatingActionButton(
child: const Icon(Icons.add),
onPressed: () async {
await const NewUserBangRoute().push(context);
},
),
);
}
}
@@ -0,0 +1,131 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:nullability/nullability.dart';
import 'package:weblibre/core/routing/routes.dart';
import 'package:weblibre/features/bangs/data/models/bang_data.dart';
import 'package:weblibre/features/geckoview/domain/repositories/tab.dart';
import 'package:weblibre/features/geckoview/features/tabs/data/entities/tab_mode.dart';
import 'package:weblibre/features/user/domain/repositories/general_settings.dart';
import 'package:weblibre/presentation/widgets/url_icon.dart';
class BangDetails extends HookConsumerWidget {
final BangData bangData;
final void Function()? onTap;
const BangDetails(this.bangData, {this.onTap, super.key});
String? _categoryString(BangData bang) {
if (bang.category == null) {
return null;
} else if (bang.subCategory == null) {
return bang.category;
} else {
return '${bang.category} / ${bang.subCategory}';
}
}
@override
Widget build(BuildContext context, WidgetRef ref) {
final theme = Theme.of(context);
return Card(
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: onTap,
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
UrlIcon([bangData.getDefaultUrl()], iconSize: 34.0),
const SizedBox(width: 12.0),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
bangData.websiteName.trim(),
style: theme.textTheme.titleMedium,
),
if (bangData.category != null)
Text(
_categoryString(bangData)!,
style: theme.textTheme.titleSmall,
),
],
),
),
],
),
const SizedBox(height: 8.0),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
FilledButton.tonalIcon(
style: const ButtonStyle(
visualDensity: VisualDensity.compact,
),
onPressed: () async {
final url = Uri.parse(bangData.getDefaultUrl().origin);
final tabMode = TabMode.fromTabType(
ref
.read(generalSettingsWithDefaultsProvider)
.effectiveDefaultCreateTabType,
);
await ref
.read(tabRepositoryProvider.notifier)
.addTab(url: url, tabMode: tabMode, selectTab: true);
if (context.mounted) {
const BrowserRoute().go(context);
}
},
label: Text(bangData.domain),
icon: const Icon(Icons.open_in_new),
),
const SizedBox(width: 8),
Expanded(
child: Tooltip(
message:
'Triggers: ${bangData.trigger}${bangData.additionalTriggers.mapNotNull((triggers) => ', ${triggers.map((trigger) => '!$trigger').join(', ')}') ?? ''}',
child: Text(
'!${bangData.trigger}',
style: theme.textTheme.titleSmall,
textAlign: TextAlign.right,
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
),
),
],
),
],
),
),
),
);
}
}
@@ -0,0 +1,50 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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:riverpod_annotation/riverpod_annotation.dart';
import 'package:weblibre/features/geckoview/features/browser/domain/entities/sheet.dart';
part 'bottom_sheet.g.dart';
@Riverpod(keepAlive: true)
class BottomSheetController extends _$BottomSheetController {
@override
Sheet? build() {
return null;
}
///We depend on a listener that updates/syncs UI to open the sheet
// ignore: use_setters_to_change_properties api decision
void show(Sheet sheet) {
state = sheet;
}
///We depend on a listener that updates/syncs UI to close the sheet
void requestDismiss() {
state = null;
}
///This is called by UI when the sheet gets closed
void closed(Sheet sheet) {
if (sheet == stateOrNull) {
state = null;
}
}
}
@@ -0,0 +1,63 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'bottom_sheet.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(BottomSheetController)
final bottomSheetControllerProvider = BottomSheetControllerProvider._();
final class BottomSheetControllerProvider
extends $NotifierProvider<BottomSheetController, Sheet?> {
BottomSheetControllerProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'bottomSheetControllerProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$bottomSheetControllerHash();
@$internal
@override
BottomSheetController create() => BottomSheetController();
/// {@macro riverpod.override_with_value}
Override overrideWithValue(Sheet? value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<Sheet?>(value),
);
}
}
String _$bottomSheetControllerHash() =>
r'54112ccef72ad7777c746b9f2dc02da1e383c127';
abstract class _$BottomSheetController extends $Notifier<Sheet?> {
Sheet? build();
@$mustCallSuper
@override
void runBuild() {
final ref = this.ref as $Ref<Sheet?, Sheet?>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<Sheet?, Sheet?>,
Sheet?,
Object?,
Object?
>;
element.handleCreate(ref, build);
}
}
@@ -0,0 +1,40 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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:flutter/widgets.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'overlay.g.dart';
@Riverpod(keepAlive: true)
class OverlayController extends _$OverlayController {
@override
WidgetBuilder? build() {
return null;
}
// ignore: use_setters_to_change_properties api decision
void show(WidgetBuilder builder) {
state = builder;
}
void dismiss() {
state = null;
}
}
@@ -0,0 +1,62 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'overlay.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(OverlayController)
final overlayControllerProvider = OverlayControllerProvider._();
final class OverlayControllerProvider
extends $NotifierProvider<OverlayController, WidgetBuilder?> {
OverlayControllerProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'overlayControllerProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$overlayControllerHash();
@$internal
@override
OverlayController create() => OverlayController();
/// {@macro riverpod.override_with_value}
Override overrideWithValue(WidgetBuilder? value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<WidgetBuilder?>(value),
);
}
}
String _$overlayControllerHash() => r'd0cd7c4cf867397f10f801ec2f7733be56520fb3';
abstract class _$OverlayController extends $Notifier<WidgetBuilder?> {
WidgetBuilder? build();
@$mustCallSuper
@override
void runBuild() {
final ref = this.ref as $Ref<WidgetBuilder?, WidgetBuilder?>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<WidgetBuilder?, WidgetBuilder?>,
WidgetBuilder?,
Object?,
Object?
>;
element.handleCreate(ref, build);
}
}
@@ -0,0 +1,56 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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 'dart:typed_data';
import 'dart:ui';
import 'package:fast_equatable/fast_equatable.dart';
import 'package:flutter_mozilla_components/flutter_mozilla_components.dart';
import 'package:weblibre/domain/entities/equatable_image.dart';
import 'package:weblibre/features/geckoview/utils/image_helper.dart';
class BrowserIcon with FastEquatable {
final EquatableImage image;
final Color? dominantColor;
final IconSource source;
static Future<BrowserIcon> fromBytes(
Uint8List bytes, {
required Color? dominantColor,
required IconSource source,
}) async {
final image = await tryDecodeImage(bytes);
return BrowserIcon(
image: image!,
dominantColor: dominantColor,
source: source,
);
}
BrowserIcon({
required this.image,
required this.dominantColor,
required this.source,
});
@override
List<Object?> get hashParameters => [image, dominantColor, source];
}
@@ -0,0 +1,52 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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:fast_equatable/fast_equatable.dart';
class FindResultState with FastEquatable {
final String? lastSearchText;
final int activeMatchOrdinal;
final int numberOfMatches;
final bool isDoneCounting;
bool get hasMatches => numberOfMatches > 0;
FindResultState({
required this.lastSearchText,
required this.activeMatchOrdinal,
required this.numberOfMatches,
required this.isDoneCounting,
});
factory FindResultState.$default() => FindResultState(
lastSearchText: null,
activeMatchOrdinal: -1,
numberOfMatches: 0,
isDoneCounting: false,
);
@override
List<Object?> get hashParameters => [
lastSearchText,
activeMatchOrdinal,
numberOfMatches,
isDoneCounting,
];
}
@@ -0,0 +1,60 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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:fast_equatable/fast_equatable.dart';
class HistoryItem with FastEquatable {
final Uri url;
final String title;
HistoryItem({required this.url, required this.title});
@override
List<Object?> get hashParameters => [url, title];
}
class HistoryState with FastEquatable {
final List<HistoryItem> items;
final int currentIndex;
final bool canGoBack;
final bool canGoForward;
HistoryState({
required this.items,
required this.currentIndex,
required this.canGoBack,
required this.canGoForward,
});
factory HistoryState.$default() => HistoryState(
items: const [],
currentIndex: 0,
canGoBack: false,
canGoForward: false,
);
@override
List<Object?> get hashParameters => [
items,
currentIndex,
canGoBack,
canGoForward,
];
}
@@ -0,0 +1,34 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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:fast_equatable/fast_equatable.dart';
class ReaderableState with FastEquatable {
final bool readerable;
final bool active;
ReaderableState({required this.readerable, required this.active});
factory ReaderableState.$default() =>
ReaderableState(readerable: false, active: false);
@override
List<Object?> get hashParameters => [readerable, active];
}
@@ -0,0 +1,38 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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:fast_equatable/fast_equatable.dart';
class SecurityState with FastEquatable {
final bool secure;
final String host;
final String issuer;
SecurityState({
required this.secure,
required this.host,
required this.issuer,
});
factory SecurityState.$default() =>
SecurityState(secure: false, host: "", issuer: "");
@override
List<Object?> get hashParameters => [secure, host, issuer];
}
@@ -0,0 +1,139 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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:copy_with_extension/copy_with_extension.dart';
import 'package:flutter_mozilla_components/flutter_mozilla_components.dart';
import 'package:nullability/nullability.dart';
import 'package:weblibre/data/models/web_page_info.dart';
import 'package:weblibre/domain/entities/equatable_image.dart';
import 'package:weblibre/features/geckoview/domain/entities/browser_icon.dart';
import 'package:weblibre/features/geckoview/domain/entities/states/find_result.dart';
import 'package:weblibre/features/geckoview/domain/entities/states/history.dart';
import 'package:weblibre/features/geckoview/domain/entities/states/readerable.dart';
import 'package:weblibre/features/geckoview/domain/entities/states/security.dart';
import 'package:weblibre/features/geckoview/domain/entities/states/translation.dart';
import 'package:weblibre/features/geckoview/features/tabs/data/entities/tab_mode.dart';
part 'tab.g.dart';
@CopyWith()
class TabState extends WebPageInfo {
static final defaultUrl = Uri.parse('about:blank');
@CopyWithField(immutable: true)
final String id;
final String? parentId;
final String? contextId;
@override
String get title => super.title!;
String get titleOrAuthority => (title.isNotEmpty) ? title : url.authority;
final EquatableImage? icon;
@override
BrowserIcon? get favicon => icon.mapNotNull(
(icon) => BrowserIcon(
image: icon,
dominantColor: null,
source: IconSource.memory,
),
);
final EquatableImage? thumbnail;
final int progress;
final TabMode tabMode;
String? get isolationContextId => tabMode.isolationContextId;
final bool isFullScreen;
final bool isLoading;
final bool showToolbarAsExpanded;
bool get isFinishedLoading => !isLoading && progress == 100;
final SecurityState securityInfoState;
final HistoryState historyState;
final ReaderableState readerableState;
final FindResultState findResultState;
final TranslationState translationState;
TabState({
required this.id,
required this.parentId,
required this.contextId,
required super.url,
required String title,
required this.icon,
required this.thumbnail,
required this.progress,
this.tabMode = TabMode.regular,
required this.isFullScreen,
required this.isLoading,
required this.showToolbarAsExpanded,
required this.securityInfoState,
required this.historyState,
required this.readerableState,
required this.findResultState,
required this.translationState,
}) : super(title: title.trim());
factory TabState.$default(String tabId) => TabState(
id: tabId,
parentId: null,
contextId: null,
url: defaultUrl,
title: "",
icon: null,
thumbnail: null,
progress: 0,
isFullScreen: false,
isLoading: false,
showToolbarAsExpanded: false,
securityInfoState: SecurityState.$default(),
historyState: HistoryState.$default(),
readerableState: ReaderableState.$default(),
findResultState: FindResultState.$default(),
translationState: TranslationState.$default(),
);
@override
List<Object?> get hashParameters => [
...super.hashParameters,
id,
parentId,
contextId,
icon,
thumbnail,
progress,
tabMode,
isFullScreen,
isLoading,
showToolbarAsExpanded,
securityInfoState,
historyState,
readerableState,
findResultState,
translationState,
];
}
@@ -0,0 +1,243 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'tab.dart';
// **************************************************************************
// CopyWithGenerator
// **************************************************************************
abstract class _$TabStateCWProxy {
TabState parentId(String? parentId);
TabState contextId(String? contextId);
TabState url(Uri url);
TabState title(String title);
TabState icon(EquatableImage? icon);
TabState thumbnail(EquatableImage? thumbnail);
TabState progress(int progress);
TabState tabMode(TabMode tabMode);
TabState isFullScreen(bool isFullScreen);
TabState isLoading(bool isLoading);
TabState showToolbarAsExpanded(bool showToolbarAsExpanded);
TabState securityInfoState(SecurityState securityInfoState);
TabState historyState(HistoryState historyState);
TabState readerableState(ReaderableState readerableState);
TabState findResultState(FindResultState findResultState);
TabState translationState(TranslationState translationState);
/// 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 `TabState(...).copyWith.fieldName(value)`.
///
/// Example:
/// ```dart
/// TabState(...).copyWith(id: 12, name: "My name")
/// ```
TabState call({
String? parentId,
String? contextId,
Uri url,
String title,
EquatableImage? icon,
EquatableImage? thumbnail,
int progress,
TabMode tabMode,
bool isFullScreen,
bool isLoading,
bool showToolbarAsExpanded,
SecurityState securityInfoState,
HistoryState historyState,
ReaderableState readerableState,
FindResultState findResultState,
TranslationState translationState,
});
}
/// Callable proxy for `copyWith` functionality.
/// Use as `instanceOfTabState.copyWith(...)` or call `instanceOfTabState.copyWith.fieldName(value)` for a single field.
class _$TabStateCWProxyImpl implements _$TabStateCWProxy {
const _$TabStateCWProxyImpl(this._value);
final TabState _value;
@override
TabState parentId(String? parentId) => call(parentId: parentId);
@override
TabState contextId(String? contextId) => call(contextId: contextId);
@override
TabState url(Uri url) => call(url: url);
@override
TabState title(String title) => call(title: title);
@override
TabState icon(EquatableImage? icon) => call(icon: icon);
@override
TabState thumbnail(EquatableImage? thumbnail) => call(thumbnail: thumbnail);
@override
TabState progress(int progress) => call(progress: progress);
@override
TabState tabMode(TabMode tabMode) => call(tabMode: tabMode);
@override
TabState isFullScreen(bool isFullScreen) => call(isFullScreen: isFullScreen);
@override
TabState isLoading(bool isLoading) => call(isLoading: isLoading);
@override
TabState showToolbarAsExpanded(bool showToolbarAsExpanded) =>
call(showToolbarAsExpanded: showToolbarAsExpanded);
@override
TabState securityInfoState(SecurityState securityInfoState) =>
call(securityInfoState: securityInfoState);
@override
TabState historyState(HistoryState historyState) =>
call(historyState: historyState);
@override
TabState readerableState(ReaderableState readerableState) =>
call(readerableState: readerableState);
@override
TabState findResultState(FindResultState findResultState) =>
call(findResultState: findResultState);
@override
TabState translationState(TranslationState translationState) =>
call(translationState: translationState);
@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 `TabState(...).copyWith.fieldName(value)`.
///
/// Example:
/// ```dart
/// TabState(...).copyWith(id: 12, name: "My name")
/// ```
TabState call({
Object? parentId = const $CopyWithPlaceholder(),
Object? contextId = const $CopyWithPlaceholder(),
Object? url = const $CopyWithPlaceholder(),
Object? title = const $CopyWithPlaceholder(),
Object? icon = const $CopyWithPlaceholder(),
Object? thumbnail = const $CopyWithPlaceholder(),
Object? progress = const $CopyWithPlaceholder(),
Object? tabMode = const $CopyWithPlaceholder(),
Object? isFullScreen = const $CopyWithPlaceholder(),
Object? isLoading = const $CopyWithPlaceholder(),
Object? showToolbarAsExpanded = const $CopyWithPlaceholder(),
Object? securityInfoState = const $CopyWithPlaceholder(),
Object? historyState = const $CopyWithPlaceholder(),
Object? readerableState = const $CopyWithPlaceholder(),
Object? findResultState = const $CopyWithPlaceholder(),
Object? translationState = const $CopyWithPlaceholder(),
}) {
return TabState(
id: _value.id,
parentId: parentId == const $CopyWithPlaceholder()
? _value.parentId
// ignore: cast_nullable_to_non_nullable
: parentId as String?,
contextId: contextId == const $CopyWithPlaceholder()
? _value.contextId
// ignore: cast_nullable_to_non_nullable
: contextId as String?,
url: url == const $CopyWithPlaceholder() || url == null
? _value.url
// ignore: cast_nullable_to_non_nullable
: url as Uri,
title: title == const $CopyWithPlaceholder() || title == null
? _value.title
// ignore: cast_nullable_to_non_nullable
: title as String,
icon: icon == const $CopyWithPlaceholder()
? _value.icon
// ignore: cast_nullable_to_non_nullable
: icon as EquatableImage?,
thumbnail: thumbnail == const $CopyWithPlaceholder()
? _value.thumbnail
// ignore: cast_nullable_to_non_nullable
: thumbnail as EquatableImage?,
progress: progress == const $CopyWithPlaceholder() || progress == null
? _value.progress
// ignore: cast_nullable_to_non_nullable
: progress as int,
tabMode: tabMode == const $CopyWithPlaceholder() || tabMode == null
? _value.tabMode
// ignore: cast_nullable_to_non_nullable
: tabMode as TabMode,
isFullScreen:
isFullScreen == const $CopyWithPlaceholder() || isFullScreen == null
? _value.isFullScreen
// ignore: cast_nullable_to_non_nullable
: isFullScreen as bool,
isLoading: isLoading == const $CopyWithPlaceholder() || isLoading == null
? _value.isLoading
// ignore: cast_nullable_to_non_nullable
: isLoading as bool,
showToolbarAsExpanded:
showToolbarAsExpanded == const $CopyWithPlaceholder() ||
showToolbarAsExpanded == null
? _value.showToolbarAsExpanded
// ignore: cast_nullable_to_non_nullable
: showToolbarAsExpanded as bool,
securityInfoState:
securityInfoState == const $CopyWithPlaceholder() ||
securityInfoState == null
? _value.securityInfoState
// ignore: cast_nullable_to_non_nullable
: securityInfoState as SecurityState,
historyState:
historyState == const $CopyWithPlaceholder() || historyState == null
? _value.historyState
// ignore: cast_nullable_to_non_nullable
: historyState as HistoryState,
readerableState:
readerableState == const $CopyWithPlaceholder() ||
readerableState == null
? _value.readerableState
// ignore: cast_nullable_to_non_nullable
: readerableState as ReaderableState,
findResultState:
findResultState == const $CopyWithPlaceholder() ||
findResultState == null
? _value.findResultState
// ignore: cast_nullable_to_non_nullable
: findResultState as FindResultState,
translationState:
translationState == const $CopyWithPlaceholder() ||
translationState == null
? _value.translationState
// ignore: cast_nullable_to_non_nullable
: translationState as TranslationState,
);
}
}
extension $TabStateCopyWith on TabState {
/// Returns a callable class used to build a new instance with modified fields.
/// Example: `instanceOfTabState.copyWith(...)` or `instanceOfTabState.copyWith.fieldName(...)`.
// ignore: library_private_types_in_public_api
_$TabStateCWProxy get copyWith => _$TabStateCWProxyImpl(this);
}
@@ -0,0 +1,84 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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:fast_equatable/fast_equatable.dart';
import 'package:flutter_mozilla_components/flutter_mozilla_components.dart';
class TranslationState with FastEquatable {
final bool isTranslated;
final bool isTranslateProcessing;
final bool isOfferTranslate;
final bool isExpectedTranslate;
final String? detectedLanguageCode;
final String? userPreferredLanguageCode;
final String? requestedFromLanguage;
final String? requestedToLanguage;
final String? translationErrorName;
final bool? displayError;
TranslationState({
required this.isTranslated,
required this.isTranslateProcessing,
required this.isOfferTranslate,
required this.isExpectedTranslate,
this.detectedLanguageCode,
this.userPreferredLanguageCode,
this.requestedFromLanguage,
this.requestedToLanguage,
this.translationErrorName,
this.displayError,
});
factory TranslationState.$default() => TranslationState(
isTranslated: false,
isTranslateProcessing: false,
isOfferTranslate: false,
isExpectedTranslate: false,
);
factory TranslationState.fromData(TabTranslationStateData data) =>
TranslationState(
isTranslated: data.isTranslated,
isTranslateProcessing: data.isTranslateProcessing,
isOfferTranslate: data.isOfferTranslate,
isExpectedTranslate: data.isExpectedTranslate,
detectedLanguageCode: data.detectedLanguageCode,
userPreferredLanguageCode: data.userPreferredLanguageCode,
requestedFromLanguage: data.requestedFromLanguage,
requestedToLanguage: data.requestedToLanguage,
translationErrorName: data.translationErrorName,
displayError: data.displayError,
);
bool get hasError => translationErrorName != null && (displayError ?? true);
@override
List<Object?> get hashParameters => [
isTranslated,
isTranslateProcessing,
isOfferTranslate,
isExpectedTranslate,
detectedLanguageCode,
userPreferredLanguageCode,
requestedFromLanguage,
requestedToLanguage,
translationErrorName,
displayError,
];
}
@@ -0,0 +1,60 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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 'dart:ui';
import 'package:copy_with_extension/copy_with_extension.dart';
import 'package:fast_equatable/fast_equatable.dart';
import 'package:weblibre/domain/entities/equatable_image.dart';
part 'web_extension.g.dart';
@CopyWith()
class WebExtensionState with FastEquatable {
String extensionId;
String? title;
bool enabled;
String? badgeText;
Color? badgeTextColor;
Color? badgeBackgroundColor;
final EquatableImage? icon;
WebExtensionState({
required this.extensionId,
required this.enabled,
this.title,
this.badgeText,
this.badgeTextColor,
this.badgeBackgroundColor,
this.icon,
});
@override
List<Object?> get hashParameters => [
extensionId,
title,
enabled,
badgeText,
badgeTextColor,
badgeBackgroundColor,
icon,
];
}
@@ -0,0 +1,130 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'web_extension.dart';
// **************************************************************************
// CopyWithGenerator
// **************************************************************************
abstract class _$WebExtensionStateCWProxy {
WebExtensionState extensionId(String extensionId);
WebExtensionState enabled(bool enabled);
WebExtensionState title(String? title);
WebExtensionState badgeText(String? badgeText);
WebExtensionState badgeTextColor(Color? badgeTextColor);
WebExtensionState badgeBackgroundColor(Color? badgeBackgroundColor);
WebExtensionState icon(EquatableImage? icon);
/// 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 `WebExtensionState(...).copyWith.fieldName(value)`.
///
/// Example:
/// ```dart
/// WebExtensionState(...).copyWith(id: 12, name: "My name")
/// ```
WebExtensionState call({
String extensionId,
bool enabled,
String? title,
String? badgeText,
Color? badgeTextColor,
Color? badgeBackgroundColor,
EquatableImage? icon,
});
}
/// Callable proxy for `copyWith` functionality.
/// Use as `instanceOfWebExtensionState.copyWith(...)` or call `instanceOfWebExtensionState.copyWith.fieldName(value)` for a single field.
class _$WebExtensionStateCWProxyImpl implements _$WebExtensionStateCWProxy {
const _$WebExtensionStateCWProxyImpl(this._value);
final WebExtensionState _value;
@override
WebExtensionState extensionId(String extensionId) =>
call(extensionId: extensionId);
@override
WebExtensionState enabled(bool enabled) => call(enabled: enabled);
@override
WebExtensionState title(String? title) => call(title: title);
@override
WebExtensionState badgeText(String? badgeText) => call(badgeText: badgeText);
@override
WebExtensionState badgeTextColor(Color? badgeTextColor) =>
call(badgeTextColor: badgeTextColor);
@override
WebExtensionState badgeBackgroundColor(Color? badgeBackgroundColor) =>
call(badgeBackgroundColor: badgeBackgroundColor);
@override
WebExtensionState icon(EquatableImage? icon) => call(icon: icon);
@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 `WebExtensionState(...).copyWith.fieldName(value)`.
///
/// Example:
/// ```dart
/// WebExtensionState(...).copyWith(id: 12, name: "My name")
/// ```
WebExtensionState call({
Object? extensionId = const $CopyWithPlaceholder(),
Object? enabled = const $CopyWithPlaceholder(),
Object? title = const $CopyWithPlaceholder(),
Object? badgeText = const $CopyWithPlaceholder(),
Object? badgeTextColor = const $CopyWithPlaceholder(),
Object? badgeBackgroundColor = const $CopyWithPlaceholder(),
Object? icon = const $CopyWithPlaceholder(),
}) {
return WebExtensionState(
extensionId:
extensionId == const $CopyWithPlaceholder() || extensionId == null
? _value.extensionId
// ignore: cast_nullable_to_non_nullable
: extensionId as String,
enabled: enabled == const $CopyWithPlaceholder() || enabled == null
? _value.enabled
// ignore: cast_nullable_to_non_nullable
: enabled as bool,
title: title == const $CopyWithPlaceholder()
? _value.title
// ignore: cast_nullable_to_non_nullable
: title as String?,
badgeText: badgeText == const $CopyWithPlaceholder()
? _value.badgeText
// ignore: cast_nullable_to_non_nullable
: badgeText as String?,
badgeTextColor: badgeTextColor == const $CopyWithPlaceholder()
? _value.badgeTextColor
// ignore: cast_nullable_to_non_nullable
: badgeTextColor as Color?,
badgeBackgroundColor: badgeBackgroundColor == const $CopyWithPlaceholder()
? _value.badgeBackgroundColor
// ignore: cast_nullable_to_non_nullable
: badgeBackgroundColor as Color?,
icon: icon == const $CopyWithPlaceholder()
? _value.icon
// ignore: cast_nullable_to_non_nullable
: icon as EquatableImage?,
);
}
}
extension $WebExtensionStateCopyWith on WebExtensionState {
/// Returns a callable class used to build a new instance with modified fields.
/// Example: `instanceOfWebExtensionState.copyWith(...)` or `instanceOfWebExtensionState.copyWith.fieldName(...)`.
// ignore: library_private_types_in_public_api
_$WebExtensionStateCWProxy get copyWith =>
_$WebExtensionStateCWProxyImpl(this);
}
@@ -0,0 +1,48 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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:weblibre/features/geckoview/features/tabs/data/models/container_data.dart';
sealed class TabContainerSelection {
const TabContainerSelection();
const factory TabContainerSelection.useSelected() =
UseSelectedContainerTabSelection;
const factory TabContainerSelection.unassigned() =
UnassignedContainerTabSelection;
const factory TabContainerSelection.specific(ContainerData container) =
SpecificContainerTabSelection;
}
final class UseSelectedContainerTabSelection extends TabContainerSelection {
const UseSelectedContainerTabSelection();
}
final class UnassignedContainerTabSelection extends TabContainerSelection {
const UnassignedContainerTabSelection();
}
final class SpecificContainerTabSelection extends TabContainerSelection {
final ContainerData container;
const SpecificContainerTabSelection(this.container);
}
@@ -0,0 +1,303 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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 'dart:async';
import 'package:flutter_mozilla_components/flutter_mozilla_components.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:share_plus/share_plus.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:weblibre/core/logger.dart';
import 'package:weblibre/core/providers/router.dart';
import 'package:weblibre/core/routing/routes.dart';
import 'package:weblibre/features/bangs/domain/providers/bangs.dart';
import 'package:weblibre/features/geckoview/domain/providers/selected_tab.dart';
import 'package:weblibre/features/geckoview/domain/providers/tab_state.dart';
import 'package:weblibre/features/geckoview/domain/repositories/tab.dart';
import 'package:weblibre/features/geckoview/features/find_in_page/domain/repositories/find_in_page.dart';
import 'package:weblibre/features/geckoview/features/tabs/data/entities/tab_mode.dart';
import 'package:weblibre/features/user/domain/repositories/general_settings.dart';
part 'providers.g.dart';
@Riverpod(keepAlive: true)
GeckoSelectionActionService selectionActionService(Ref ref) {
final service = GeckoSelectionActionService.setUp();
unawaited(
service.setActions([
NewTabAction((text) async {
if (ref.mounted) {
final router = await ref.read(routerProvider.future);
if (ref.mounted) {
final settings = ref.read(generalSettingsWithDefaultsProvider);
final selectedTabState = ref.read(
tabStatesProvider,
)[ref.read(selectedTabProvider)];
final selectedTabType = selectedTabState?.tabMode.toTabType();
final route = SearchRoute(
tabType:
selectedTabType ?? settings.effectiveDefaultCreateTabType,
searchText: text,
);
await router.push(route.location);
}
}
}),
DefaultSearchAction((text) async {
if (ref.mounted) {
final defaultSearchBang = await ref.read(
defaultSearchBangDataProvider.future,
);
if (ref.mounted && defaultSearchBang != null) {
final currentTab = ref.read(
tabStatesProvider,
)[ref.read(selectedTabProvider)];
final tabMode =
currentTab?.tabMode ??
TabMode.fromTabType(
ref
.read(generalSettingsWithDefaultsProvider)
.effectiveDefaultCreateTabType,
);
await ref
.read(tabRepositoryProvider.notifier)
.addTab(
url: defaultSearchBang.getTemplateUrl(text),
parentId: currentTab?.id,
tabMode: tabMode,
selectTab: true,
);
} else {
logger.e('No default search bang found');
}
}
}),
FindInPageAction((text) async {
if (ref.mounted) {
final tabId = ref.read(selectedTabProvider);
if (tabId != null) {
await ref
.read(findInPageRepositoryProvider(tabId).notifier)
.findAll(text);
}
}
}),
ShareAction((text) async {
await SharePlus.instance.share(ShareParams(text: text));
}),
CallAction((text) async {
final uri = Uri.tryParse('tel:${text.replaceAll(' ', '')}');
if (uri != null) {
final canLaunch = await canLaunchUrl(uri);
if (canLaunch) {
await launchUrl(uri);
}
}
}),
EmailAction((text) async {
final uri = Uri.tryParse('mailto:$text');
if (uri != null) {
final canLaunch = await canLaunchUrl(uri);
if (canLaunch) {
await launchUrl(uri);
}
}
}),
]),
);
return service;
}
@Riverpod(keepAlive: true)
GeckoEventService eventService(Ref ref) {
final service = GeckoEventService.setUp();
ref.onDispose(() async {
await service.dispose();
});
return service;
}
@Riverpod(keepAlive: true)
GeckoAddonService addonService(Ref ref) {
final service = GeckoAddonService.setUp();
ref.onDispose(() async {
await service.dispose();
});
return service;
}
@Riverpod(keepAlive: true)
GeckoTabContentService tabContentService(Ref ref) {
final service = GeckoTabContentService.setUp();
ref.onDispose(() async {
await service.dispose();
});
return service;
}
@Riverpod(keepAlive: true)
GeckoSuggestionsService engineSuggestionsService(Ref ref) {
final service = GeckoSuggestionsService.setUp();
ref.onDispose(() async {
await service.dispose();
});
return service;
}
@Riverpod(keepAlive: true)
GeckoViewportService viewportService(Ref ref) {
final service = GeckoViewportService();
service.setUp();
ref.onDispose(() async {
await service.dispose();
});
return service;
}
@Riverpod(keepAlive: true)
class EngineReadyState extends _$EngineReadyState {
@override
bool build() {
final eventService = ref.watch(eventServiceProvider);
final currentState =
eventService.engineReadyStateEvents.valueOrNull ?? false;
if (!currentState) {
unawaited(
eventService.engineReadyStateEvents
.firstWhere((value) => value == true)
.timeout(
const Duration(seconds: 3),
onTimeout: () {
logger.w('Waiting for engine ready state timed out');
return true;
},
)
.whenComplete(() {
if (ref.mounted) {
state = true;
}
}),
);
}
final sub = eventService.engineReadyStateEvents.listen((value) {
if (ref.mounted) {
state = value;
}
});
ref.onDispose(() async {
await sub.cancel();
});
return currentState;
}
}
/// Stream of ML model progress events
@Riverpod(keepAlive: true)
Stream<MlProgressData> mlProgressEvents(Ref ref) {
final service = ref.watch(eventServiceProvider);
return service.mlProgressEvents;
}
/// Translation engine state (browser-level: supported languages, engine availability)
@Riverpod(keepAlive: true)
class TranslationEngineState extends _$TranslationEngineState {
@override
TranslationEngineStateData? build() {
final eventService = ref.watch(eventServiceProvider);
final sub = eventService.translationEngineEvents.listen((value) {
if (ref.mounted) {
state = value;
}
});
ref.onDispose(() async {
await sub.cancel();
});
return eventService.translationEngineEvents.valueOrNull;
}
}
/// Tracks active ML model downloads
@Riverpod()
class MlDownloadState extends _$MlDownloadState {
Timer? _clearTimer;
@override
MlProgressData? build() {
ref.listen(mlProgressEventsProvider, (previous, next) {
next.whenData((progress) {
if (!ref.mounted) return;
if (progress.type == MlProgressType.downloading) {
if (progress.status == MlProgressStatus.done) {
// Keep showing for 2 seconds after completion
_clearTimer?.cancel();
_clearTimer = Timer(const Duration(seconds: 2), () {
if (ref.mounted && state != null && state!.id == progress.id) {
state = null;
}
});
} else {
state = progress;
}
}
});
});
ref.onDispose(() {
_clearTimer?.cancel();
_clearTimer = null;
});
return null;
}
void clear() {
_clearTimer?.cancel();
_clearTimer = null;
state = null;
}
}
@@ -0,0 +1,514 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'providers.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(selectionActionService)
final selectionActionServiceProvider = SelectionActionServiceProvider._();
final class SelectionActionServiceProvider
extends
$FunctionalProvider<
GeckoSelectionActionService,
GeckoSelectionActionService,
GeckoSelectionActionService
>
with $Provider<GeckoSelectionActionService> {
SelectionActionServiceProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'selectionActionServiceProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$selectionActionServiceHash();
@$internal
@override
$ProviderElement<GeckoSelectionActionService> $createElement(
$ProviderPointer pointer,
) => $ProviderElement(pointer);
@override
GeckoSelectionActionService create(Ref ref) {
return selectionActionService(ref);
}
/// {@macro riverpod.override_with_value}
Override overrideWithValue(GeckoSelectionActionService value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<GeckoSelectionActionService>(value),
);
}
}
String _$selectionActionServiceHash() =>
r'5faf8c13c414406dfc2eb55fdd372677dbccdf8c';
@ProviderFor(eventService)
final eventServiceProvider = EventServiceProvider._();
final class EventServiceProvider
extends
$FunctionalProvider<
GeckoEventService,
GeckoEventService,
GeckoEventService
>
with $Provider<GeckoEventService> {
EventServiceProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'eventServiceProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$eventServiceHash();
@$internal
@override
$ProviderElement<GeckoEventService> $createElement(
$ProviderPointer pointer,
) => $ProviderElement(pointer);
@override
GeckoEventService create(Ref ref) {
return eventService(ref);
}
/// {@macro riverpod.override_with_value}
Override overrideWithValue(GeckoEventService value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<GeckoEventService>(value),
);
}
}
String _$eventServiceHash() => r'3a297348fadda05dc60433d7ce8f662b2ff62c26';
@ProviderFor(addonService)
final addonServiceProvider = AddonServiceProvider._();
final class AddonServiceProvider
extends
$FunctionalProvider<
GeckoAddonService,
GeckoAddonService,
GeckoAddonService
>
with $Provider<GeckoAddonService> {
AddonServiceProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'addonServiceProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$addonServiceHash();
@$internal
@override
$ProviderElement<GeckoAddonService> $createElement(
$ProviderPointer pointer,
) => $ProviderElement(pointer);
@override
GeckoAddonService create(Ref ref) {
return addonService(ref);
}
/// {@macro riverpod.override_with_value}
Override overrideWithValue(GeckoAddonService value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<GeckoAddonService>(value),
);
}
}
String _$addonServiceHash() => r'30fedb35c68943159246df79b5f1b62a25767fa0';
@ProviderFor(tabContentService)
final tabContentServiceProvider = TabContentServiceProvider._();
final class TabContentServiceProvider
extends
$FunctionalProvider<
GeckoTabContentService,
GeckoTabContentService,
GeckoTabContentService
>
with $Provider<GeckoTabContentService> {
TabContentServiceProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'tabContentServiceProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$tabContentServiceHash();
@$internal
@override
$ProviderElement<GeckoTabContentService> $createElement(
$ProviderPointer pointer,
) => $ProviderElement(pointer);
@override
GeckoTabContentService create(Ref ref) {
return tabContentService(ref);
}
/// {@macro riverpod.override_with_value}
Override overrideWithValue(GeckoTabContentService value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<GeckoTabContentService>(value),
);
}
}
String _$tabContentServiceHash() => r'12d8322c37ded4ad3344af327d884bbf7f089594';
@ProviderFor(engineSuggestionsService)
final engineSuggestionsServiceProvider = EngineSuggestionsServiceProvider._();
final class EngineSuggestionsServiceProvider
extends
$FunctionalProvider<
GeckoSuggestionsService,
GeckoSuggestionsService,
GeckoSuggestionsService
>
with $Provider<GeckoSuggestionsService> {
EngineSuggestionsServiceProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'engineSuggestionsServiceProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$engineSuggestionsServiceHash();
@$internal
@override
$ProviderElement<GeckoSuggestionsService> $createElement(
$ProviderPointer pointer,
) => $ProviderElement(pointer);
@override
GeckoSuggestionsService create(Ref ref) {
return engineSuggestionsService(ref);
}
/// {@macro riverpod.override_with_value}
Override overrideWithValue(GeckoSuggestionsService value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<GeckoSuggestionsService>(value),
);
}
}
String _$engineSuggestionsServiceHash() =>
r'1ec1192f0c5c86cecc7ad448ee2b039f7a48e32b';
@ProviderFor(viewportService)
final viewportServiceProvider = ViewportServiceProvider._();
final class ViewportServiceProvider
extends
$FunctionalProvider<
GeckoViewportService,
GeckoViewportService,
GeckoViewportService
>
with $Provider<GeckoViewportService> {
ViewportServiceProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'viewportServiceProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$viewportServiceHash();
@$internal
@override
$ProviderElement<GeckoViewportService> $createElement(
$ProviderPointer pointer,
) => $ProviderElement(pointer);
@override
GeckoViewportService create(Ref ref) {
return viewportService(ref);
}
/// {@macro riverpod.override_with_value}
Override overrideWithValue(GeckoViewportService value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<GeckoViewportService>(value),
);
}
}
String _$viewportServiceHash() => r'bab39db3180bb6a1cf8c055966b7f5910b41b424';
@ProviderFor(EngineReadyState)
final engineReadyStateProvider = EngineReadyStateProvider._();
final class EngineReadyStateProvider
extends $NotifierProvider<EngineReadyState, bool> {
EngineReadyStateProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'engineReadyStateProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$engineReadyStateHash();
@$internal
@override
EngineReadyState create() => EngineReadyState();
/// {@macro riverpod.override_with_value}
Override overrideWithValue(bool value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<bool>(value),
);
}
}
String _$engineReadyStateHash() => r'ab3fe385fbda4d7d8acaf8f5428b3b48b75f3f46';
abstract class _$EngineReadyState extends $Notifier<bool> {
bool build();
@$mustCallSuper
@override
void runBuild() {
final ref = this.ref as $Ref<bool, bool>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<bool, bool>,
bool,
Object?,
Object?
>;
element.handleCreate(ref, build);
}
}
/// Stream of ML model progress events
@ProviderFor(mlProgressEvents)
final mlProgressEventsProvider = MlProgressEventsProvider._();
/// Stream of ML model progress events
final class MlProgressEventsProvider
extends
$FunctionalProvider<
AsyncValue<MlProgressData>,
MlProgressData,
Stream<MlProgressData>
>
with $FutureModifier<MlProgressData>, $StreamProvider<MlProgressData> {
/// Stream of ML model progress events
MlProgressEventsProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'mlProgressEventsProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$mlProgressEventsHash();
@$internal
@override
$StreamProviderElement<MlProgressData> $createElement(
$ProviderPointer pointer,
) => $StreamProviderElement(pointer);
@override
Stream<MlProgressData> create(Ref ref) {
return mlProgressEvents(ref);
}
}
String _$mlProgressEventsHash() => r'41c1e6aece7f9ee2bebe5d189c6bec753c2fefc8';
/// Translation engine state (browser-level: supported languages, engine availability)
@ProviderFor(TranslationEngineState)
final translationEngineStateProvider = TranslationEngineStateProvider._();
/// Translation engine state (browser-level: supported languages, engine availability)
final class TranslationEngineStateProvider
extends
$NotifierProvider<TranslationEngineState, TranslationEngineStateData?> {
/// Translation engine state (browser-level: supported languages, engine availability)
TranslationEngineStateProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'translationEngineStateProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$translationEngineStateHash();
@$internal
@override
TranslationEngineState create() => TranslationEngineState();
/// {@macro riverpod.override_with_value}
Override overrideWithValue(TranslationEngineStateData? value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<TranslationEngineStateData?>(value),
);
}
}
String _$translationEngineStateHash() =>
r'04592e18715b0e237e9bc027287a880a4bb023da';
/// Translation engine state (browser-level: supported languages, engine availability)
abstract class _$TranslationEngineState
extends $Notifier<TranslationEngineStateData?> {
TranslationEngineStateData? build();
@$mustCallSuper
@override
void runBuild() {
final ref =
this.ref
as $Ref<TranslationEngineStateData?, TranslationEngineStateData?>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<
TranslationEngineStateData?,
TranslationEngineStateData?
>,
TranslationEngineStateData?,
Object?,
Object?
>;
element.handleCreate(ref, build);
}
}
/// Tracks active ML model downloads
@ProviderFor(MlDownloadState)
final mlDownloadStateProvider = MlDownloadStateProvider._();
/// Tracks active ML model downloads
final class MlDownloadStateProvider
extends $NotifierProvider<MlDownloadState, MlProgressData?> {
/// Tracks active ML model downloads
MlDownloadStateProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'mlDownloadStateProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$mlDownloadStateHash();
@$internal
@override
MlDownloadState create() => MlDownloadState();
/// {@macro riverpod.override_with_value}
Override overrideWithValue(MlProgressData? value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<MlProgressData?>(value),
);
}
}
String _$mlDownloadStateHash() => r'4b943f0a950bf63c9a1b628d4104fdd6fa0d8d07';
/// Tracks active ML model downloads
abstract class _$MlDownloadState extends $Notifier<MlProgressData?> {
MlProgressData? build();
@$mustCallSuper
@override
void runBuild() {
final ref = this.ref as $Ref<MlProgressData?, MlProgressData?>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<MlProgressData?, MlProgressData?>,
MlProgressData?,
Object?,
Object?
>;
element.handleCreate(ref, build);
}
}
@@ -0,0 +1,40 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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:flutter_mozilla_components/flutter_mozilla_components.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'browser_extension.g.dart';
@Riverpod(keepAlive: true)
GeckoBrowserExtensionService browserExtensionService(Ref ref) {
final service = GeckoBrowserExtensionService.setUp();
ref.onDispose(() {
service.dispose();
});
return service;
}
@Riverpod()
Stream<String> feedRequested(Ref ref) {
final service = ref.watch(browserExtensionServiceProvider);
return service.feedRequested;
}
@@ -0,0 +1,91 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'browser_extension.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(browserExtensionService)
final browserExtensionServiceProvider = BrowserExtensionServiceProvider._();
final class BrowserExtensionServiceProvider
extends
$FunctionalProvider<
GeckoBrowserExtensionService,
GeckoBrowserExtensionService,
GeckoBrowserExtensionService
>
with $Provider<GeckoBrowserExtensionService> {
BrowserExtensionServiceProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'browserExtensionServiceProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$browserExtensionServiceHash();
@$internal
@override
$ProviderElement<GeckoBrowserExtensionService> $createElement(
$ProviderPointer pointer,
) => $ProviderElement(pointer);
@override
GeckoBrowserExtensionService create(Ref ref) {
return browserExtensionService(ref);
}
/// {@macro riverpod.override_with_value}
Override overrideWithValue(GeckoBrowserExtensionService value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<GeckoBrowserExtensionService>(value),
);
}
}
String _$browserExtensionServiceHash() =>
r'c3f67763e0abb10039b407fced6e175e5ec7c6c3';
@ProviderFor(feedRequested)
final feedRequestedProvider = FeedRequestedProvider._();
final class FeedRequestedProvider
extends $FunctionalProvider<AsyncValue<String>, String, Stream<String>>
with $FutureModifier<String>, $StreamProvider<String> {
FeedRequestedProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'feedRequestedProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$feedRequestedHash();
@$internal
@override
$StreamProviderElement<String> $createElement($ProviderPointer pointer) =>
$StreamProviderElement(pointer);
@override
Stream<String> create(Ref ref) {
return feedRequested(ref);
}
}
String _$feedRequestedHash() => r'4f179d0878072a77a87422ff6afdac53a3d57c04';
@@ -0,0 +1,48 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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:riverpod_annotation/riverpod_annotation.dart';
import 'package:weblibre/features/geckoview/domain/providers/tab_session.dart';
part 'desktop_mode.g.dart';
@Riverpod(keepAlive: true)
class DesktopMode extends _$DesktopMode {
// ignore: use_setters_to_change_properties
void enabled(bool value) {
state = value;
}
void toggle() {
state = !state;
}
@override
bool build(String tabId) {
listenSelf((previous, next) async {
if (previous != null) {
await ref
.read(tabSessionProvider(tabId: tabId).notifier)
.requestDesktopSite(next);
}
});
return false;
}
}
@@ -0,0 +1,99 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'desktop_mode.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(DesktopMode)
final desktopModeProvider = DesktopModeFamily._();
final class DesktopModeProvider extends $NotifierProvider<DesktopMode, bool> {
DesktopModeProvider._({
required DesktopModeFamily super.from,
required String super.argument,
}) : super(
retry: null,
name: r'desktopModeProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$desktopModeHash();
@override
String toString() {
return r'desktopModeProvider'
''
'($argument)';
}
@$internal
@override
DesktopMode create() => DesktopMode();
/// {@macro riverpod.override_with_value}
Override overrideWithValue(bool value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<bool>(value),
);
}
@override
bool operator ==(Object other) {
return other is DesktopModeProvider && other.argument == argument;
}
@override
int get hashCode {
return argument.hashCode;
}
}
String _$desktopModeHash() => r'18550009e95a23ff82d30206ce81daa859c57c26';
final class DesktopModeFamily extends $Family
with $ClassFamilyOverride<DesktopMode, bool, bool, bool, String> {
DesktopModeFamily._()
: super(
retry: null,
name: r'desktopModeProvider',
dependencies: null,
$allTransitiveDependencies: null,
isAutoDispose: false,
);
DesktopModeProvider call(String tabId) =>
DesktopModeProvider._(argument: tabId, from: this);
@override
String toString() => r'desktopModeProvider';
}
abstract class _$DesktopMode extends $Notifier<bool> {
late final _$args = ref.$arg as String;
String get tabId => _$args;
bool build(String tabId);
@$mustCallSuper
@override
void runBuild() {
final ref = this.ref as $Ref<bool, bool>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<bool, bool>,
bool,
Object?,
Object?
>;
element.handleCreate(ref, () => build(_$args));
}
}
@@ -0,0 +1,69 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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:flutter_mozilla_components/flutter_mozilla_components.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:weblibre/core/logger.dart';
import 'package:weblibre/features/geckoview/domain/providers.dart';
part 'selected_tab.g.dart';
@Riverpod(keepAlive: true)
class SelectedTab extends _$SelectedTab {
@override
String? build() {
final eventSerivce = ref.watch(eventServiceProvider);
ref.listen(
fireImmediately: true,
engineReadyStateProvider,
(previous, next) async {
if (next) {
await GeckoTabService().syncEvents(onSelectedTabChange: true);
}
},
onError: (error, stackTrace) {
logger.e(
'Error listening to engineReadyStateProvider',
error: error,
stackTrace: stackTrace,
);
},
);
final selectedTabSub = eventSerivce.selectedTabEvents.listen(
(tabId) {
state = tabId;
},
onError: (Object error, StackTrace stackTrace) {
logger.e(
'Error in selected tab events',
error: error,
stackTrace: stackTrace,
);
},
);
ref.onDispose(() async {
await selectedTabSub.cancel();
});
return null;
}
}
@@ -0,0 +1,62 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'selected_tab.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(SelectedTab)
final selectedTabProvider = SelectedTabProvider._();
final class SelectedTabProvider
extends $NotifierProvider<SelectedTab, String?> {
SelectedTabProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'selectedTabProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$selectedTabHash();
@$internal
@override
SelectedTab create() => SelectedTab();
/// {@macro riverpod.override_with_value}
Override overrideWithValue(String? value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<String?>(value),
);
}
}
String _$selectedTabHash() => r'5caa359376e9103767e2d2e94c548d53cba79d0f';
abstract class _$SelectedTab extends $Notifier<String?> {
String? build();
@$mustCallSuper
@override
void runBuild() {
final ref = this.ref as $Ref<String?, String?>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<String?, String?>,
String?,
Object?,
Object?
>;
element.handleCreate(ref, build);
}
}
@@ -0,0 +1,74 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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:fast_equatable/fast_equatable.dart';
import 'package:flutter_mozilla_components/flutter_mozilla_components.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:weblibre/core/logger.dart';
import 'package:weblibre/features/geckoview/domain/providers.dart';
part 'tab_list.g.dart';
@Riverpod(keepAlive: true)
class TabList extends _$TabList {
@override
EquatableValue<List<String>> build() {
final eventService = ref.watch(eventServiceProvider);
ref.listen(
fireImmediately: true,
engineReadyStateProvider,
(previous, next) async {
if (next) {
await GeckoTabService().syncEvents(onTabListChange: true);
}
},
onError: (error, stackTrace) {
logger.e(
'Error listening to eventServiceProvider',
error: error,
stackTrace: stackTrace,
);
},
);
final tabListSub = eventService.tabListEvents.listen(
(tabs) {
final equatableTabs = EquatableValue(tabs);
if (equatableTabs != state) {
state = equatableTabs;
}
},
onError: (Object error, StackTrace stackTrace) {
logger.e(
'Error in tab list events',
error: error,
stackTrace: stackTrace,
);
},
);
ref.onDispose(() async {
await tabListSub.cancel();
});
return EquatableValue([]);
}
}
@@ -0,0 +1,67 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'tab_list.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(TabList)
final tabListProvider = TabListProvider._();
final class TabListProvider
extends $NotifierProvider<TabList, EquatableValue<List<String>>> {
TabListProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'tabListProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$tabListHash();
@$internal
@override
TabList create() => TabList();
/// {@macro riverpod.override_with_value}
Override overrideWithValue(EquatableValue<List<String>> value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<EquatableValue<List<String>>>(value),
);
}
}
String _$tabListHash() => r'88c2598a4d586fee9e3d0f1b418cf88ea5c7da75';
abstract class _$TabList extends $Notifier<EquatableValue<List<String>>> {
EquatableValue<List<String>> build();
@$mustCallSuper
@override
void runBuild() {
final ref =
this.ref
as $Ref<EquatableValue<List<String>>, EquatableValue<List<String>>>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<
EquatableValue<List<String>>,
EquatableValue<List<String>>
>,
EquatableValue<List<String>>,
Object?,
Object?
>;
element.handleCreate(ref, build);
}
}
@@ -0,0 +1,130 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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 'dart:typed_data';
import 'package:flutter_mozilla_components/flutter_mozilla_components.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'tab_session.g.dart';
@Riverpod(keepAlive: true)
class TabSession extends _$TabSession {
late GeckoSessionService _sessionService;
Future<void> loadUrl({
required Uri url,
LoadUrlFlags flags = LoadUrlFlags.NONE,
Map<String, String>? additionalHeaders,
}) {
return _sessionService.loadUrl(
url: url,
flags: flags,
additionalHeaders: additionalHeaders,
);
}
Future<void> stopLoading() {
return _sessionService.stopLoading();
}
Future<void> reload({LoadUrlFlags flags = LoadUrlFlags.NONE}) {
return _sessionService.reload(flags: flags);
}
Future<void> goBack() {
return _sessionService.goBack();
}
Future<void> goForward() {
return _sessionService.goForward();
}
Future<void> goToHistoryIndex({required int index}) {
return _sessionService.goToHistoryIndex(index: index);
}
Future<void> exitFullscreen() {
return _sessionService.exitFullscreen();
}
Future<Uint8List?> requestScreenshot({bool requireImageResult = true}) {
return _sessionService.requestScreenshot(requireImageResult);
}
Future<void> requestDesktopSite(bool enable) {
return _sessionService.requestDesktopSite(enable: enable);
}
Future<void> saveToPdf() {
return _sessionService.saveToPdf();
}
Future<void> printContent() {
return _sessionService.printContent();
}
Future<void> translate({
required String fromLanguage,
required String toLanguage,
bool? downloadModel,
}) {
return _sessionService.translate(
fromLanguage: fromLanguage,
toLanguage: toLanguage,
options: TranslationOptions(downloadModel: downloadModel ?? true),
);
}
Future<void> translateRestore() {
return _sessionService.translateRestore();
}
Future<void> pageUp() {
// Android KeyEvent.KEYCODE_PAGE_UP = 92
return _sessionService.dispatchKeyEvent(keyCode: 92);
}
Future<void> pageDown() {
// Android KeyEvent.KEYCODE_PAGE_DOWN = 93
return _sessionService.dispatchKeyEvent(keyCode: 93);
}
Future<void> scrollToTop() {
// Android KeyEvent.KEYCODE_MOVE_HOME = 122
return _sessionService.dispatchKeyEvent(keyCode: 122);
}
Future<void> scrollToBottom() {
// Android KeyEvent.KEYCODE_MOVE_END = 123
return _sessionService.dispatchKeyEvent(keyCode: 123);
}
@override
void build({required String? tabId}) {
_sessionService = (tabId != null)
? GeckoSessionService(tabId: tabId)
: GeckoSessionService.forActiveTab();
}
}
@Riverpod(keepAlive: true)
Raw<TabSession> selectedTabSessionNotifier(Ref ref) {
return ref.watch(tabSessionProvider(tabId: null).notifier);
}
@@ -0,0 +1,142 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'tab_session.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(TabSession)
final tabSessionProvider = TabSessionFamily._();
final class TabSessionProvider extends $NotifierProvider<TabSession, void> {
TabSessionProvider._({
required TabSessionFamily super.from,
required String? super.argument,
}) : super(
retry: null,
name: r'tabSessionProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$tabSessionHash();
@override
String toString() {
return r'tabSessionProvider'
''
'($argument)';
}
@$internal
@override
TabSession create() => TabSession();
/// {@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 TabSessionProvider && other.argument == argument;
}
@override
int get hashCode {
return argument.hashCode;
}
}
String _$tabSessionHash() => r'636f0940425d689ff98fabfc61687de828a8eeb9';
final class TabSessionFamily extends $Family
with $ClassFamilyOverride<TabSession, void, void, void, String?> {
TabSessionFamily._()
: super(
retry: null,
name: r'tabSessionProvider',
dependencies: null,
$allTransitiveDependencies: null,
isAutoDispose: false,
);
TabSessionProvider call({required String? tabId}) =>
TabSessionProvider._(argument: tabId, from: this);
@override
String toString() => r'tabSessionProvider';
}
abstract class _$TabSession extends $Notifier<void> {
late final _$args = ref.$arg as String?;
String? get tabId => _$args;
void build({required String? tabId});
@$mustCallSuper
@override
void runBuild() {
final ref = this.ref as $Ref<void, void>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<void, void>,
void,
Object?,
Object?
>;
element.handleCreate(ref, () => build(tabId: _$args));
}
}
@ProviderFor(selectedTabSessionNotifier)
final selectedTabSessionProvider = SelectedTabSessionNotifierProvider._();
final class SelectedTabSessionNotifierProvider
extends
$FunctionalProvider<Raw<TabSession>, Raw<TabSession>, Raw<TabSession>>
with $Provider<Raw<TabSession>> {
SelectedTabSessionNotifierProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'selectedTabSessionProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$selectedTabSessionNotifierHash();
@$internal
@override
$ProviderElement<Raw<TabSession>> $createElement($ProviderPointer pointer) =>
$ProviderElement(pointer);
@override
Raw<TabSession> create(Ref ref) {
return selectedTabSessionNotifier(ref);
}
/// {@macro riverpod.override_with_value}
Override overrideWithValue(Raw<TabSession> value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<Raw<TabSession>>(value),
);
}
}
String _$selectedTabSessionNotifierHash() =>
r'3945a3a3faf615e1c95819abda276f3e251d5b4c';
@@ -0,0 +1,467 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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 'dart:async';
import 'package:flutter_mozilla_components/flutter_mozilla_components.dart';
import 'package:nullability/nullability.dart';
import 'package:riverpod/riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:rxdart/rxdart.dart';
import 'package:weblibre/core/logger.dart';
import 'package:weblibre/core/routing/routes.dart';
import 'package:weblibre/features/geckoview/domain/entities/states/find_result.dart';
import 'package:weblibre/features/geckoview/domain/entities/states/history.dart';
import 'package:weblibre/features/geckoview/domain/entities/states/readerable.dart';
import 'package:weblibre/features/geckoview/domain/entities/states/security.dart';
import 'package:weblibre/features/geckoview/domain/entities/states/tab.dart';
import 'package:weblibre/features/geckoview/domain/entities/states/translation.dart';
import 'package:weblibre/features/geckoview/domain/providers.dart';
import 'package:weblibre/features/geckoview/domain/providers/selected_tab.dart';
import 'package:weblibre/features/geckoview/features/find_in_page/domain/repositories/find_in_page.dart';
import 'package:weblibre/features/geckoview/features/tabs/data/entities/isolation_context.dart';
import 'package:weblibre/features/geckoview/features/tabs/data/entities/tab_mode.dart';
import 'package:weblibre/features/geckoview/features/tabs/domain/providers.dart';
import 'package:weblibre/features/geckoview/features/tabs/domain/repositories/gecko_inference.dart';
import 'package:weblibre/features/geckoview/features/tabs/domain/repositories/tab.dart';
import 'package:weblibre/features/geckoview/utils/image_helper.dart';
import 'package:weblibre/features/user/data/models/tor_settings.dart';
import 'package:weblibre/features/user/domain/repositories/tor_settings.dart';
part 'tab_state.g.dart';
@Riverpod(keepAlive: true)
class TabStates extends _$TabStates {
/// Disposes images from a TabState to free GPU memory.
void _disposeTabImages(TabState tab) {
tab.icon?.dispose();
tab.thumbnail?.dispose();
}
/// Updates state while disposing images from removed tabs.
void _updateState(Map<String, TabState> newState) {
// Find and dispose images from tabs that are being removed
for (final tabId in state.keys) {
if (!newState.containsKey(tabId)) {
_disposeTabImages(state[tabId]!);
}
}
state = newState;
}
Future<void> _onTabContentStateChange(TabContentState contentState) async {
final current = await patchedState(contentState.id);
final url = Uri.parse(contentState.url);
// Determine title based on priority: new non-empty title > existing title if URL authority unchanged > new title
final String resolvedTitle;
if (contentState.title.isNotEmpty) {
resolvedTitle = contentState.title;
} else if (current.url.authority == url.authority) {
resolvedTitle = current.title;
} else {
resolvedTitle = contentState.title;
}
// Infer tabMode from context ID if not already set and context is isolated
final inferredTabMode = switch (current.tabMode) {
IsolatedTabMode() => current.tabMode,
_ when isIsolatedContextId(contentState.contextId) => TabMode.isolated(
contentState.contextId!,
),
_ when contentState.isPrivate => TabMode.private,
_ => TabMode.regular,
};
final newState = current.copyWith(
parentId: contentState.parentId,
contextId: contentState.contextId,
url: url,
title: resolvedTitle,
progress: contentState.progress,
tabMode: inferredTabMode,
isFullScreen: contentState.isFullScreen,
isLoading: contentState.isLoading,
showToolbarAsExpanded: contentState.showToolbarAsExpanded,
);
_updateState({...state}..[contentState.id] = newState);
if (newState.isFinishedLoading) {
ref
.read(geckoInferenceRepositoryProvider.notifier)
.markInitialLoadComplete();
}
}
Future<TabState> patchedState(String id) async {
var current = stateOrNull?[id];
if (current == null || current.url == TabState.defaultUrl) {
current ??= TabState.$default(id);
final tabData = await ref
.read(tabDataRepositoryProvider.notifier)
.getTabDataById(id);
if (tabData?.url != null) {
current = current.copyWith(
title: tabData!.title ?? current.title,
url: tabData.url ?? current.url,
);
}
}
return current;
}
Future<void> _onIconChange(IconChangeEvent event) async {
final IconChangeEvent(:tabId, :bytes) = event;
final image = await bytes.mapNotNull((bytes) => tryDecodeImage(bytes));
final current = state[tabId] ?? TabState.$default(tabId);
// Dispose old icon only after successfully creating new one
current.icon?.dispose();
state = {...state}..[tabId] = current.copyWith.icon(image);
}
Future<void> _onThumbnailChange(ThumbnailEvent event) async {
final ThumbnailEvent(:tabId, :bytes) = event;
final image = await bytes.mapNotNull((bytes) => tryDecodeImage(bytes));
final current = state[tabId] ?? TabState.$default(tabId);
// Dispose old thumbnail only after successfully creating new one
current.thumbnail?.dispose();
state = {...state}..[tabId] = current.copyWith.thumbnail(image);
}
void _onSecurityInfoStateChange(SecurityInfoEvent event) {
final SecurityInfoEvent(:tabId, :securityInfo) = event;
final current = state[tabId] ?? TabState.$default(tabId);
state = {...state}
..[tabId] = current.copyWith.securityInfoState(
SecurityState(
secure: securityInfo.secure,
host: securityInfo.host,
issuer: securityInfo.issuer,
),
);
}
void _onHistoryStateChange(HistoryEvent event) {
final HistoryEvent(:tabId, :history) = event;
final current = state[tabId] ?? TabState.$default(tabId);
state = {...state}
..[tabId] = current.copyWith.historyState(
HistoryState(
items: history.items.nonNulls
.map(
(item) =>
HistoryItem(url: Uri.parse(item.url), title: item.title),
)
.toList(),
currentIndex: history.currentIndex,
canGoBack: history.canGoBack,
canGoForward: history.canGoForward,
),
);
}
void _onReaderableStateChange(ReaderableEvent event) {
final ReaderableEvent(:tabId, :readerable) = event;
final current = state[tabId] ?? TabState.$default(tabId);
state = {...state}
..[tabId] = current.copyWith.readerableState(
ReaderableState(
readerable: readerable.readerable,
active: readerable.active,
),
);
}
void _onTabTranslationStateChange(TabTranslationEvent event) {
final TabTranslationEvent(:tabId, :state) = event;
final current = this.state[tabId] ?? TabState.$default(tabId);
this.state = {...this.state}
..[tabId] = current.copyWith.translationState(
TranslationState.fromData(state),
);
}
void _onFindResultsChange(FindResultsEvent event) {
final FindResultsEvent(:tabId, :results) = event;
final current = state[tabId] ?? TabState.$default(tabId);
if (results.isNotEmpty) {
final result = results.last;
state = {...state}
..[tabId] = current.copyWith.findResultState(
FindResultState(
lastSearchText: ref.read(findInPageRepositoryProvider(tabId)),
activeMatchOrdinal: result.activeMatchOrdinal,
numberOfMatches: result.numberOfMatches,
isDoneCounting: result.isDoneCounting,
),
);
} else if (current.findResultState.hasMatches) {
state = {
...state,
}..[tabId] = current.copyWith.findResultState(FindResultState.$default());
}
}
@override
Map<String, TabState> build() {
final eventService = ref.watch(eventServiceProvider);
final subscriptions = [
eventService.tabContentEvents.listen(
(event) async {
await _onTabContentStateChange(event);
},
onError: (Object error, StackTrace stackTrace) {
logger.e(
'Error in tab content events',
error: error,
stackTrace: stackTrace,
);
},
),
eventService.iconChangeEvents.listen(
(event) async {
await _onIconChange(event);
},
onError: (Object error, StackTrace stackTrace) {
logger.e(
'Error in icon change events',
error: error,
stackTrace: stackTrace,
);
},
),
eventService.thumbnailEvents.listen(
(event) async {
await _onThumbnailChange(event);
},
onError: (Object error, StackTrace stackTrace) {
logger.e(
'Error in thumbnail events',
error: error,
stackTrace: stackTrace,
);
},
),
eventService.securityInfoEvents.listen(
(event) {
_onSecurityInfoStateChange(event);
},
onError: (Object error, StackTrace stackTrace) {
logger.e(
'Error in security info events',
error: error,
stackTrace: stackTrace,
);
},
),
eventService.historyEvents.listen(
(event) {
_onHistoryStateChange(event);
},
onError: (Object error, StackTrace stackTrace) {
logger.e(
'Error in history events',
error: error,
stackTrace: stackTrace,
);
},
),
eventService.readerableEvents.listen(
(event) {
_onReaderableStateChange(event);
},
onError: (Object error, StackTrace stackTrace) {
logger.e(
'Error in readerable events',
error: error,
stackTrace: stackTrace,
);
},
),
eventService.findResultsEvent
.debounceTime(const Duration(milliseconds: 25))
.listen(
(event) {
_onFindResultsChange(event);
},
onError: (Object error, StackTrace stackTrace) {
logger.e(
'Error in find results events',
error: error,
stackTrace: stackTrace,
);
},
),
eventService.tabTranslationEvents.listen(
(event) {
_onTabTranslationStateChange(event);
},
onError: (Object error, StackTrace stackTrace) {
logger.e(
'Error in tab translation events',
error: error,
stackTrace: stackTrace,
);
},
),
];
ref.listen(
fireImmediately: true,
engineReadyStateProvider,
(previous, next) async {
if (next) {
await GeckoTabService().syncEvents(
onTabContentStateChange: true,
onIconChange: true,
onThumbnailChange: true,
onSecurityInfoStateChange: true,
onHistoryStateChange: true,
onFindResults: true,
onTranslationStateChange: true,
);
}
},
onError: (error, stackTrace) {
logger.e(
'Error listening to engineReadyStateProvider',
error: error,
stackTrace: stackTrace,
);
},
);
ref.onDispose(() async {
// Dispose all remaining tab images
for (final tab in state.values) {
_disposeTabImages(tab);
}
// Cancel all stream subscriptions
for (final sub in subscriptions) {
await sub.cancel();
}
});
return {};
}
}
@Riverpod()
TabState? tabState(Ref ref, String? tabId) {
if (tabId == null) {
return null;
}
return ref.watch(tabStatesProvider.select((tabs) => tabs[tabId]));
}
@Riverpod()
Future<TabState> tabStateWithFallback(Ref ref, String tabId) async {
final state = ref.watch(tabStateProvider(tabId));
if (state != null) {
return state;
}
return await ref.read(tabStatesProvider.notifier).patchedState(tabId);
}
@Riverpod()
Future<bool> isTabTunneled(Ref ref, String? tabId) async {
final tabState = ref.watch(tabStateProvider(tabId));
final torSettings = ref.watch(torSettingsWithDefaultsProvider);
if (tabState != null) {
// Isolated tabs follow the same proxy rules as regular tabs
// (container-based routing via proxy aliasing)
if (tabState.tabMode is PrivateTabMode) {
return torSettings.proxyPrivateTabsTor;
} else {
switch (torSettings.proxyRegularTabsMode) {
case TorRegularTabProxyMode.container:
final containerData = await ref
.read(tabDataRepositoryProvider.notifier)
.getTabContainerData(tabState.id);
if (!ref.mounted) return false;
return containerData?.metadata.useProxy ?? false;
case TorRegularTabProxyMode.all:
return true;
}
}
}
return false;
}
@Riverpod()
TabState? selectedTabState(Ref ref) {
final tabId = ref.watch(selectedTabProvider);
return ref.watch(tabStateProvider(tabId));
}
@Riverpod()
TabType? selectedTabType(Ref ref) {
final selectedState = ref.watch(selectedTabStateProvider);
return selectedState?.tabMode.toTabType();
}
@Riverpod()
AsyncValue<String?> selectedTabContainerId(Ref ref) {
final tabId = ref.watch(selectedTabProvider);
if (tabId != null) {
return ref.watch(watchContainerTabIdProvider(tabId));
}
return const AsyncData(null);
}
// @Riverpod()
// Stream<int> tabScrollY(Ref ref, String? tabId, Duration sampleTime) {
// final eventService = ref.watch(eventServiceProvider);
// return eventService.scrollEvent
// .where((event) => event.tabId == tabId)
// .sampleTime(sampleTime)
// .map((event) => event.scrollY)
// .asBroadcastStream();
// }
@@ -0,0 +1,409 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'tab_state.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(TabStates)
final tabStatesProvider = TabStatesProvider._();
final class TabStatesProvider
extends $NotifierProvider<TabStates, Map<String, TabState>> {
TabStatesProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'tabStatesProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$tabStatesHash();
@$internal
@override
TabStates create() => TabStates();
/// {@macro riverpod.override_with_value}
Override overrideWithValue(Map<String, TabState> value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<Map<String, TabState>>(value),
);
}
}
String _$tabStatesHash() => r'6fc9a91b1343f9ae0b442100bed20e42448afa37';
abstract class _$TabStates extends $Notifier<Map<String, TabState>> {
Map<String, TabState> build();
@$mustCallSuper
@override
void runBuild() {
final ref = this.ref as $Ref<Map<String, TabState>, Map<String, TabState>>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<Map<String, TabState>, Map<String, TabState>>,
Map<String, TabState>,
Object?,
Object?
>;
element.handleCreate(ref, build);
}
}
@ProviderFor(tabState)
final tabStateProvider = TabStateFamily._();
final class TabStateProvider
extends $FunctionalProvider<TabState?, TabState?, TabState?>
with $Provider<TabState?> {
TabStateProvider._({
required TabStateFamily super.from,
required String? super.argument,
}) : super(
retry: null,
name: r'tabStateProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$tabStateHash();
@override
String toString() {
return r'tabStateProvider'
''
'($argument)';
}
@$internal
@override
$ProviderElement<TabState?> $createElement($ProviderPointer pointer) =>
$ProviderElement(pointer);
@override
TabState? create(Ref ref) {
final argument = this.argument as String?;
return tabState(ref, argument);
}
/// {@macro riverpod.override_with_value}
Override overrideWithValue(TabState? value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<TabState?>(value),
);
}
@override
bool operator ==(Object other) {
return other is TabStateProvider && other.argument == argument;
}
@override
int get hashCode {
return argument.hashCode;
}
}
String _$tabStateHash() => r'f57b2353acc99ca73670d504b45ea5ff19df38c7';
final class TabStateFamily extends $Family
with $FunctionalFamilyOverride<TabState?, String?> {
TabStateFamily._()
: super(
retry: null,
name: r'tabStateProvider',
dependencies: null,
$allTransitiveDependencies: null,
isAutoDispose: true,
);
TabStateProvider call(String? tabId) =>
TabStateProvider._(argument: tabId, from: this);
@override
String toString() => r'tabStateProvider';
}
@ProviderFor(tabStateWithFallback)
final tabStateWithFallbackProvider = TabStateWithFallbackFamily._();
final class TabStateWithFallbackProvider
extends
$FunctionalProvider<AsyncValue<TabState>, TabState, FutureOr<TabState>>
with $FutureModifier<TabState>, $FutureProvider<TabState> {
TabStateWithFallbackProvider._({
required TabStateWithFallbackFamily super.from,
required String super.argument,
}) : super(
retry: null,
name: r'tabStateWithFallbackProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$tabStateWithFallbackHash();
@override
String toString() {
return r'tabStateWithFallbackProvider'
''
'($argument)';
}
@$internal
@override
$FutureProviderElement<TabState> $createElement($ProviderPointer pointer) =>
$FutureProviderElement(pointer);
@override
FutureOr<TabState> create(Ref ref) {
final argument = this.argument as String;
return tabStateWithFallback(ref, argument);
}
@override
bool operator ==(Object other) {
return other is TabStateWithFallbackProvider && other.argument == argument;
}
@override
int get hashCode {
return argument.hashCode;
}
}
String _$tabStateWithFallbackHash() =>
r'061011ac79738dbe4e662a76fccbc8592cba21cf';
final class TabStateWithFallbackFamily extends $Family
with $FunctionalFamilyOverride<FutureOr<TabState>, String> {
TabStateWithFallbackFamily._()
: super(
retry: null,
name: r'tabStateWithFallbackProvider',
dependencies: null,
$allTransitiveDependencies: null,
isAutoDispose: true,
);
TabStateWithFallbackProvider call(String tabId) =>
TabStateWithFallbackProvider._(argument: tabId, from: this);
@override
String toString() => r'tabStateWithFallbackProvider';
}
@ProviderFor(isTabTunneled)
final isTabTunneledProvider = IsTabTunneledFamily._();
final class IsTabTunneledProvider
extends $FunctionalProvider<AsyncValue<bool>, bool, FutureOr<bool>>
with $FutureModifier<bool>, $FutureProvider<bool> {
IsTabTunneledProvider._({
required IsTabTunneledFamily super.from,
required String? super.argument,
}) : super(
retry: null,
name: r'isTabTunneledProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$isTabTunneledHash();
@override
String toString() {
return r'isTabTunneledProvider'
''
'($argument)';
}
@$internal
@override
$FutureProviderElement<bool> $createElement($ProviderPointer pointer) =>
$FutureProviderElement(pointer);
@override
FutureOr<bool> create(Ref ref) {
final argument = this.argument as String?;
return isTabTunneled(ref, argument);
}
@override
bool operator ==(Object other) {
return other is IsTabTunneledProvider && other.argument == argument;
}
@override
int get hashCode {
return argument.hashCode;
}
}
String _$isTabTunneledHash() => r'b11134b33ad0c98ffddd14afc2c790fb65735e93';
final class IsTabTunneledFamily extends $Family
with $FunctionalFamilyOverride<FutureOr<bool>, String?> {
IsTabTunneledFamily._()
: super(
retry: null,
name: r'isTabTunneledProvider',
dependencies: null,
$allTransitiveDependencies: null,
isAutoDispose: true,
);
IsTabTunneledProvider call(String? tabId) =>
IsTabTunneledProvider._(argument: tabId, from: this);
@override
String toString() => r'isTabTunneledProvider';
}
@ProviderFor(selectedTabState)
final selectedTabStateProvider = SelectedTabStateProvider._();
final class SelectedTabStateProvider
extends $FunctionalProvider<TabState?, TabState?, TabState?>
with $Provider<TabState?> {
SelectedTabStateProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'selectedTabStateProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$selectedTabStateHash();
@$internal
@override
$ProviderElement<TabState?> $createElement($ProviderPointer pointer) =>
$ProviderElement(pointer);
@override
TabState? create(Ref ref) {
return selectedTabState(ref);
}
/// {@macro riverpod.override_with_value}
Override overrideWithValue(TabState? value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<TabState?>(value),
);
}
}
String _$selectedTabStateHash() => r'dbd36af7af286bd9d079f30e8e11bbda23bf7728';
@ProviderFor(selectedTabType)
final selectedTabTypeProvider = SelectedTabTypeProvider._();
final class SelectedTabTypeProvider
extends $FunctionalProvider<TabType?, TabType?, TabType?>
with $Provider<TabType?> {
SelectedTabTypeProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'selectedTabTypeProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$selectedTabTypeHash();
@$internal
@override
$ProviderElement<TabType?> $createElement($ProviderPointer pointer) =>
$ProviderElement(pointer);
@override
TabType? create(Ref ref) {
return selectedTabType(ref);
}
/// {@macro riverpod.override_with_value}
Override overrideWithValue(TabType? value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<TabType?>(value),
);
}
}
String _$selectedTabTypeHash() => r'4cf99c9175357a7835fc3c4eff29a9f328931e4f';
@ProviderFor(selectedTabContainerId)
final selectedTabContainerIdProvider = SelectedTabContainerIdProvider._();
final class SelectedTabContainerIdProvider
extends
$FunctionalProvider<
AsyncValue<String?>,
AsyncValue<String?>,
AsyncValue<String?>
>
with $Provider<AsyncValue<String?>> {
SelectedTabContainerIdProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'selectedTabContainerIdProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$selectedTabContainerIdHash();
@$internal
@override
$ProviderElement<AsyncValue<String?>> $createElement(
$ProviderPointer pointer,
) => $ProviderElement(pointer);
@override
AsyncValue<String?> create(Ref ref) {
return selectedTabContainerId(ref);
}
/// {@macro riverpod.override_with_value}
Override overrideWithValue(AsyncValue<String?> value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<AsyncValue<String?>>(value),
);
}
}
String _$selectedTabContainerIdHash() =>
r'07899d29f69654d3b314d0da945ad402b1003b41';
@@ -0,0 +1,200 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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 'dart:async';
import 'dart:ui';
import 'package:flutter_mozilla_components/flutter_mozilla_components.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:weblibre/core/logger.dart';
import 'package:weblibre/domain/entities/equatable_image.dart';
import 'package:weblibre/features/geckoview/domain/entities/states/web_extension.dart';
import 'package:weblibre/features/geckoview/domain/providers.dart';
import 'package:weblibre/features/geckoview/utils/image_helper.dart';
import 'package:weblibre/utils/lru_cache.dart';
part 'web_extensions_state.g.dart';
@Riverpod(keepAlive: true)
class WebExtensionsState extends _$WebExtensionsState {
late final LRUCache<String, EquatableImage> _imageCache;
WebExtensionsState()
: _imageCache = LRUCache(50, onEvict: (image) => image.dispose());
void _onExtensionUpdate(ExtensionDataEvent event) {
final ExtensionDataEvent(:extensionId, :data) = event;
if (data != null) {
final cachedIcon = _imageCache.get(extensionId);
if (cachedIcon != null && cachedIcon.value == null) {
_imageCache.remove(extensionId);
}
final current =
state[extensionId] ??
WebExtensionState(
extensionId: extensionId,
icon: _imageCache.get(extensionId),
enabled: false,
);
state = {...state}
..[extensionId] = current.copyWith(
title: data.title,
enabled: data.enabled ?? current.enabled,
badgeText: data.badgeText,
badgeTextColor: data.badgeTextColor != null
? Color(data.badgeTextColor!)
: null,
badgeBackgroundColor: data.badgeBackgroundColor != null
? Color(data.badgeBackgroundColor!)
: null,
);
} else {
if (state.containsKey(extensionId)) {
state = {...state}..remove(extensionId);
// remove() triggers onEvict which handles disposal
_imageCache.remove(extensionId);
}
}
}
Future<void> _onIconChange(ExtensionIconEvent event) async {
final ExtensionIconEvent(:extensionId, :bytes) = event;
final image = await tryDecodeImage(bytes);
if (image != null) {
// set() will evict the old entry via onEvict callback, which handles disposal
_imageCache.set(extensionId, image);
if (state.containsKey(extensionId)) {
state = {...state}
..[extensionId] = state[extensionId]!.copyWith.icon(image);
}
}
}
@override
Map<String, WebExtensionState> build(WebExtensionActionType actionType) {
final addonService = ref.watch(addonServiceProvider);
final subscriptions = switch (actionType) {
WebExtensionActionType.browser => [
addonService.browserExtensionStream.listen(
(event) {
_onExtensionUpdate(event);
},
onError: (Object error, StackTrace stackTrace) {
logger.e(
'Error in browser extension stream',
error: error,
stackTrace: stackTrace,
);
},
),
addonService.browserIconStream.listen(
(event) async {
await _onIconChange(event);
},
onError: (Object error, StackTrace stackTrace) {
logger.e(
'Error in browser icon stream',
error: error,
stackTrace: stackTrace,
);
},
),
],
WebExtensionActionType.page => [
addonService.pageExtensionStream.listen(
(event) {
_onExtensionUpdate(event);
},
onError: (Object error, StackTrace stackTrace) {
logger.e(
'Error in page extension stream',
error: error,
stackTrace: stackTrace,
);
},
),
addonService.pageIconStream.listen(
(event) async {
await _onIconChange(event);
},
onError: (Object error, StackTrace stackTrace) {
logger.e(
'Error in page icon stream',
error: error,
stackTrace: stackTrace,
);
},
),
],
};
// Sync extension events after engine is ready and listeners are set up
// This ensures we get the current state even if we missed initial events
ref.listen(
fireImmediately: true,
engineReadyStateProvider,
(previous, next) async {
if (next) {
try {
await GeckoTabService().syncEvents(
onBrowserExtensionsChange:
actionType == WebExtensionActionType.browser,
onPageExtensionsChange: actionType == WebExtensionActionType.page,
onBrowserExtensionIcons:
actionType == WebExtensionActionType.browser,
onPageExtensionIcons: actionType == WebExtensionActionType.page,
);
} catch (e, s) {
logger.w(
'Failed to sync extension events for $actionType',
error: e,
stackTrace: s,
);
}
}
},
onError: (error, stackTrace) {
logger.e(
'Error listening to engineReadyStateProvider',
error: error,
stackTrace: stackTrace,
);
},
);
ref.onDispose(() async {
// Dispose all cached images
_imageCache.clear();
// Cancel all stream subscriptions
for (final sub in subscriptions) {
await sub.cancel();
}
});
return {};
}
}
@@ -0,0 +1,120 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'web_extensions_state.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(WebExtensionsState)
final webExtensionsStateProvider = WebExtensionsStateFamily._();
final class WebExtensionsStateProvider
extends
$NotifierProvider<WebExtensionsState, Map<String, WebExtensionState>> {
WebExtensionsStateProvider._({
required WebExtensionsStateFamily super.from,
required WebExtensionActionType super.argument,
}) : super(
retry: null,
name: r'webExtensionsStateProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$webExtensionsStateHash();
@override
String toString() {
return r'webExtensionsStateProvider'
''
'($argument)';
}
@$internal
@override
WebExtensionsState create() => WebExtensionsState();
/// {@macro riverpod.override_with_value}
Override overrideWithValue(Map<String, WebExtensionState> value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<Map<String, WebExtensionState>>(
value,
),
);
}
@override
bool operator ==(Object other) {
return other is WebExtensionsStateProvider && other.argument == argument;
}
@override
int get hashCode {
return argument.hashCode;
}
}
String _$webExtensionsStateHash() =>
r'13cbbea409b5b643eb6766689f6b23a4d1701204';
final class WebExtensionsStateFamily extends $Family
with
$ClassFamilyOverride<
WebExtensionsState,
Map<String, WebExtensionState>,
Map<String, WebExtensionState>,
Map<String, WebExtensionState>,
WebExtensionActionType
> {
WebExtensionsStateFamily._()
: super(
retry: null,
name: r'webExtensionsStateProvider',
dependencies: null,
$allTransitiveDependencies: null,
isAutoDispose: false,
);
WebExtensionsStateProvider call(WebExtensionActionType actionType) =>
WebExtensionsStateProvider._(argument: actionType, from: this);
@override
String toString() => r'webExtensionsStateProvider';
}
abstract class _$WebExtensionsState
extends $Notifier<Map<String, WebExtensionState>> {
late final _$args = ref.$arg as WebExtensionActionType;
WebExtensionActionType get actionType => _$args;
Map<String, WebExtensionState> build(WebExtensionActionType actionType);
@$mustCallSuper
@override
void runBuild() {
final ref =
this.ref
as $Ref<
Map<String, WebExtensionState>,
Map<String, WebExtensionState>
>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<
Map<String, WebExtensionState>,
Map<String, WebExtensionState>
>,
Map<String, WebExtensionState>,
Object?,
Object?
>;
element.handleCreate(ref, () => build(_$args));
}
}
@@ -0,0 +1,850 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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 'dart:async';
import 'package:collection/collection.dart';
import 'package:drift/drift.dart';
import 'package:flutter_mozilla_components/flutter_mozilla_components.dart';
import 'package:nullability/nullability.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:synchronized/synchronized.dart';
import 'package:weblibre/core/logger.dart';
import 'package:weblibre/features/geckoview/domain/entities/states/tab.dart';
import 'package:weblibre/features/geckoview/domain/entities/tab_container_selection.dart';
import 'package:weblibre/features/geckoview/domain/providers.dart';
import 'package:weblibre/features/geckoview/domain/providers/selected_tab.dart';
import 'package:weblibre/features/geckoview/domain/providers/tab_list.dart';
import 'package:weblibre/features/geckoview/domain/providers/tab_state.dart';
import 'package:weblibre/features/geckoview/features/browser/domain/services/browser_data.dart';
import 'package:weblibre/features/geckoview/features/tabs/data/entities/isolation_context.dart';
import 'package:weblibre/features/geckoview/features/tabs/data/entities/tab_mode.dart';
import 'package:weblibre/features/geckoview/features/tabs/data/entities/tab_source.dart';
import 'package:weblibre/features/geckoview/features/tabs/data/models/container_data.dart';
import 'package:weblibre/features/geckoview/features/tabs/data/providers.dart';
import 'package:weblibre/features/geckoview/features/tabs/domain/providers/selected_container.dart';
import 'package:weblibre/features/geckoview/features/tabs/domain/repositories/container.dart';
import 'package:weblibre/features/geckoview/features/tabs/domain/repositories/tab.dart';
import 'package:weblibre/features/tor/domain/repositories/tor_proxy.dart';
import 'package:weblibre/features/user/data/models/general_settings.dart';
import 'package:weblibre/features/user/domain/repositories/general_settings.dart';
import 'package:weblibre/utils/debouncer.dart';
part 'tab.g.dart';
@Riverpod(keepAlive: true)
class TabRepository extends _$TabRepository {
final _tabsService = GeckoTabService();
final _tabFromIntent = <String>{};
final _closeLock = Lock();
final _pendingIsolationCleanup = <String>{};
bool hasLaunchedFromIntent(String? tabId) {
if (tabId == null) {
return false;
}
return _tabFromIntent.contains(tabId);
}
void clearLaunchedFromIntent(String tabId) {
_tabFromIntent.remove(tabId);
}
NewTabPosition _newTabPositionForParent(String? parentId) {
if (parentId != null) {
return NewTabPosition.first;
}
return ref.read(generalSettingsWithDefaultsProvider).newTabPosition;
}
Future<String?> _resolveParentIdForContext({
required String? parentId,
required String? targetContextId,
}) async {
if (parentId == null) {
return null;
}
final parentContainerData = await ref
.read(tabDatabaseProvider)
.tabDao
.getTabContainerData(parentId)
.getSingleOrNull();
final parentContextId = parentContainerData?.metadata.contextualIdentity;
return (parentContextId == targetContextId) ? parentId : null;
}
Future<String> addTab({
required TabMode tabMode,
Uri? url,
required bool selectTab,
bool startLoading = true,
String? parentId,
LoadUrlFlags flags = LoadUrlFlags.NONE,
Source source = Internal.newTab,
HistoryMetadataKey? historyMetadata,
Map<String, String>? additionalHeaders,
TabContainerSelection containerSelection =
const TabContainerSelection.useSelected(),
bool launchedFromIntent = false,
}) async {
final tabDao = ref.read(tabDatabaseProvider).tabDao;
final assignedContainer = switch (containerSelection) {
UseSelectedContainerTabSelection() =>
await ref.read(selectedContainerProvider.notifier).fetchData(),
UnassignedContainerTabSelection() => null,
SpecificContainerTabSelection(:final container) => container,
};
// For isolated tabs, skip parent context validation since
// isolated tabs use their own immutable context ID.
final validatedParentId = tabMode is IsolatedTabMode
? parentId
: await _resolveParentIdForContext(
parentId: parentId,
targetContextId: assignedContainer?.metadata.contextualIdentity,
);
final effectiveIsolationContextId = tabMode.isolationContextId;
final effectiveContextId = tabMode is IsolatedTabMode
? effectiveIsolationContextId
: assignedContainer?.metadata.contextualIdentity;
final newTabPosition = _newTabPositionForParent(validatedParentId);
final newTabId = await tabDao.upsertTabTransactional(
() {
return _tabsService.addTab(
url: url,
selectTab: selectTab,
startLoading: startLoading,
parentId: validatedParentId,
flags: flags,
contextId: effectiveContextId,
source: source,
private: tabMode is PrivateTabMode,
historyMetadata: historyMetadata,
additionalHeaders: additionalHeaders,
);
},
parentId: Value(validatedParentId),
newTabPosition: newTabPosition,
containerId: Value(assignedContainer?.id),
url: Value(url),
tabMode: Value(tabMode),
);
if (launchedFromIntent) {
_tabFromIntent.add(newTabId);
}
return newTabId;
}
Future<List<String>> addMultipleTabs({
required List<AddTabParams> tabs,
String? selectTabId,
TabContainerSelection containerSelection =
const TabContainerSelection.unassigned(),
}) async {
final tabDao = ref.read(tabDatabaseProvider).tabDao;
final db = ref.read(tabDatabaseProvider);
final assignedContainer = switch (containerSelection) {
UseSelectedContainerTabSelection() =>
await ref.read(selectedContainerProvider.notifier).fetchData(),
UnassignedContainerTabSelection() => null,
SpecificContainerTabSelection(:final container) => container,
};
return await db.transaction(() async {
final createdTabIds = await _tabsService.addMultipleTabs(
tabs: tabs,
selectTabId: selectTabId,
);
// Build sets for validation
final creatingTabIds = createdTabIds.toSet();
final parentIdsToValidate = tabs
.map((tab) => tab.parentId)
.whereType<String>()
.where((id) => !creatingTabIds.contains(id))
.toSet();
// Batch validate parent IDs that aren't in the current creation batch
final existingParentIds = await tabDao
.getExistingTabIds(parentIdsToValidate)
.get()
.then((ids) => ids.toSet());
// Upsert all tabs in the database
for (var i = 0; i < createdTabIds.length; i++) {
final tabId = createdTabIds[i];
final tab = tabs[i];
// Validate parent exists in either the batch being created or database
String? validatedParentId;
if (tab.parentId != null) {
if (creatingTabIds.contains(tab.parentId) ||
existingParentIds.contains(tab.parentId)) {
validatedParentId = tab.parentId;
}
}
await tabDao.insertTab(
tabId,
parentId: Value(validatedParentId),
source: TabSource.manual,
newTabPosition: _newTabPositionForParent(validatedParentId),
containerId: Value(assignedContainer?.id),
url: Value(Uri.tryParse(tab.url)),
tabMode: Value(
isIsolatedContextId(tab.contextId)
? TabMode.isolated(tab.contextId!)
: tab.private
? TabMode.private
: TabMode.regular,
),
);
}
return createdTabIds;
});
}
Future<String> duplicateTab({
required String selectTabId,
required ContainerData? containerData,
required bool selectTab,
}) async {
final tabDao = ref.read(tabDatabaseProvider).tabDao;
final sourceTabMode =
await tabDao.getTabMode(selectTabId).getSingleOrNull() ??
TabMode.regular;
// Duplicating an isolated tab creates a new isolation group
final duplicateIsolationContextId = sourceTabMode is IsolatedTabMode
? newIsolatedContextId()
: null;
final duplicateTabMode = sourceTabMode is IsolatedTabMode
? TabMode.isolated(duplicateIsolationContextId!)
: sourceTabMode;
// Isolated tabs always use their isolation context ID
final effectiveContextId = sourceTabMode is IsolatedTabMode
? duplicateIsolationContextId
: containerData?.metadata.contextualIdentity;
return await tabDao.upsertTabTransactional(
() {
return _tabsService.duplicateTab(
selectTabId: selectTabId,
newContextId: effectiveContextId,
selectNewTab: selectTab,
);
},
parentId: const Value.absent(),
newTabPosition: _newTabPositionForParent(null),
containerId: Value(containerData?.id),
tabMode: Value(duplicateTabMode),
);
}
Future<bool> selectPreviouslyOpenedTab(String tabId) async {
final previousTabId = await ref
.read(tabDatabaseProvider)
.definitionsDrift
.previousTabByTimestamp(tabId: tabId)
.getSingleOrNull();
if (ref.mounted && previousTabId != null) {
return selectTab(previousTabId);
}
return false;
}
Future<bool> resumeLatestTab() async {
final latestTab = await ref
.read(tabDatabaseProvider)
.tabDao
.getTabsFifo(limit: 1)
.getSingleOrNull();
if (!ref.mounted || latestTab == null) {
return false;
}
return selectTab(latestTab.id);
}
Future<bool> resumeLatestContainerTab(String? containerId) async {
final latestTab = await ref
.read(tabDatabaseProvider)
.tabDao
.getContainerTabsFifo(containerId, limit: 1)
.getSingleOrNull();
if (!ref.mounted || latestTab == null) {
return false;
}
return selectTab(latestTab.id);
}
Future<bool> selectPreviousTab(
String tabId, {
String? containerId,
bool skipContainerCheck = true,
}) async {
final previousTabId = await ref
.read(tabDatabaseProvider)
.definitionsDrift
.previousTabByOrderKey(
tabId: tabId,
containerId: containerId,
skipContainerCheck: skipContainerCheck,
)
.getSingleOrNull();
if (ref.mounted && previousTabId != null) {
return selectTab(previousTabId);
}
return false;
}
Future<bool> selectNextTab(
String tabId, {
String? containerId,
bool skipContainerCheck = true,
}) async {
final previousTabId = await ref
.read(tabDatabaseProvider)
.definitionsDrift
.nextTabByOrderKey(
tabId: tabId,
containerId: containerId,
skipContainerCheck: skipContainerCheck,
)
.getSingleOrNull();
if (ref.mounted && previousTabId != null) {
return selectTab(previousTabId);
}
return false;
}
Future<bool> selectTab(String tabId) async {
final containerData = await ref
.read(tabDataRepositoryProvider.notifier)
.getTabContainerData(tabId);
if (!ref.mounted) return false;
if (containerData != null) {
if (containerData.metadata.useProxy) {
final proxyPluginHealthy = await GeckoContainerProxyService()
.healthcheck();
if (!proxyPluginHealthy) {
logger.w(
'Tried to open proxied tab $tabId but proxy plugin not responding',
);
return false;
}
}
}
await _tabsService.selectTab(tabId: tabId);
return true;
}
Future<void> _selectNextTab(String tabId) async {
final tabState = ref.read(tabStatesProvider)[tabId];
final currentContainerId = await ref
.read(tabDataRepositoryProvider.notifier)
.getTabContainerId(tabId);
if (!ref.mounted) return;
final sameContainerTabs = await ref
.read(containerRepositoryProvider.notifier)
.getContainerTabIds(currentContainerId)
.then((tabs) => tabs.where((tab) => tab != tabId).toList());
if (!ref.mounted) return;
// Priority 1: Check for parent tab first
if (tabState?.parentId != null) {
return _tabsService.selectTab(tabId: tabState!.parentId!);
}
// Priority 2: Check for previous tab by timestamp
final previousTabId = await ref
.read(tabDatabaseProvider)
.definitionsDrift
.previousTabByTimestamp(tabId: tabId)
.getSingleOrNull();
if (previousTabId != null) {
if (sameContainerTabs.any((tab) => tab == previousTabId)) {
return _tabsService.selectTab(tabId: previousTabId);
}
}
if (!ref.mounted) return;
final previousOrderedTabId = await ref
.read(tabDatabaseProvider)
.definitionsDrift
.previousTabByOrderKey(
tabId: tabId,
containerId: currentContainerId,
skipContainerCheck: false,
)
.getSingleOrNull();
if (previousOrderedTabId != null) {
return _tabsService.selectTab(tabId: previousOrderedTabId);
}
if (!ref.mounted) return;
final nextOrderedTabId = await ref
.read(tabDatabaseProvider)
.definitionsDrift
.nextTabByOrderKey(
tabId: tabId,
containerId: currentContainerId,
skipContainerCheck: false,
)
.getSingleOrNull();
if (nextOrderedTabId != null) {
return _tabsService.selectTab(tabId: nextOrderedTabId);
}
if (!ref.mounted) return;
final unassignedTabs = await ref
.read(containerRepositoryProvider.notifier)
.getContainerTabIds(null)
.then((tabs) => tabs.where((tab) => tab != tabId).toList());
if (unassignedTabs.isNotEmpty) {
return _tabsService.selectTab(tabId: unassignedTabs.first);
}
if (!ref.mounted) return;
final availableContainers = await ref
.read(containerRepositoryProvider.notifier)
.getAllContainersWithCount();
final nextAvailableContainer = availableContainers.firstOrNull;
if (!ref.mounted) return;
final nextContainerTabs = await nextAvailableContainer.mapNotNull(
(container) => ref
.read(containerRepositoryProvider.notifier)
.getContainerTabIds(container.id)
.then((tabs) => tabs.where((tab) => tab != tabId).toList()),
);
if (nextContainerTabs.isNotEmpty) {
return _tabsService.selectTab(tabId: nextContainerTabs!.first);
}
}
Future<void> closeTab(String tabId) {
return _closeLock.synchronized(() async {
// Collect isolation context before close
final isolationContextId = ref
.read(tabStatesProvider)[tabId]
?.isolationContextId;
if (ref.read(selectedTabProvider) == tabId) {
await _selectNextTab(tabId);
}
await _tabsService.removeTab(tabId: tabId);
// Queue isolation cleanup — actual cleanup runs after syncTabs
// deletes the DB row, so the count check is accurate.
if (isolationContextId != null) {
_pendingIsolationCleanup.add(isolationContextId);
}
});
}
Future<void> closeTabs(List<String> tabIds) {
return _closeLock.synchronized(() async {
// Collect isolation contexts from tabs being closed
for (final tabId in tabIds) {
final contextId = ref
.read(tabStatesProvider)[tabId]
?.isolationContextId;
if (contextId != null) {
_pendingIsolationCleanup.add(contextId);
}
}
final selectedTab = ref.read(selectedTabProvider);
if (selectedTab.mapNotNull(tabIds.contains) ?? false) {
await _selectNextTab(selectedTab!);
}
await _tabsService.removeTabs(ids: tabIds);
});
}
/// Clears Gecko browsing data and removes proxy alias for an isolation
/// context if no more tabs share it.
Future<void> _cleanupIsolationContextIfEmpty(String contextId) async {
final tabDao = ref.read(tabDatabaseProvider).tabDao;
// Re-verify count after close (handles concurrent close races)
final remaining = await tabDao.tabsInIsolationGroup(contextId).getSingle();
if (remaining > 0) return;
// Guard against debounced DB persistence: a sibling tab can already be
// active in-memory for this context before isolation_context_id is written.
final activeTabs = ref.read(tabListProvider).value;
final activeStates = ref.read(tabStatesProvider);
final hasActiveSibling = activeTabs.any((tabId) {
final state = activeStates[tabId];
if (state == null) return false;
return state.isolationContextId == contextId ||
state.contextId == contextId;
});
if (hasActiveSibling) {
logger.i(
'Skipping isolation cleanup for active context still in memory: $contextId',
);
return;
}
logger.i('Cleaning up isolation context: $contextId');
// Clear Gecko browsing data for this context
try {
await ref
.read(browserDataServiceProvider.notifier)
.clearDataForContext(contextId);
} catch (e, st) {
logger.e(
'Failed to clear data for isolation context $contextId',
error: e,
stackTrace: st,
);
}
// Best-effort: remove proxy alias (no-op if never set)
try {
await ref
.read(torProxyRepositoryProvider.notifier)
.removeContainerProxy(contextId);
} catch (e, st) {
logger.e(
'Failed to remove proxy for isolation context $contextId',
error: e,
stackTrace: st,
);
}
}
Future<void> undoClose() {
return _tabsService.undo();
}
/// Cleans up isolation contexts from previous crashed sessions.
/// Called once after tab list stabilizes on startup.
// Future<void> _cleanupOrphanedIsolationContexts() async {
// final tabDao = ref.read(tabDatabaseProvider).tabDao;
// try {
// await _closeLock.synchronized(() async {
// if (!ref.mounted) return;
// // Reconcile DB rows against the current engine tab snapshot, including
// // valid empty-tab sessions (retainTabIds can be empty here).
// final syncTabsResult = await tabDao.syncTabs(
// retainTabIds: ref.read(tabListProvider).value,
// );
// _pendingIsolationCleanup.addAll(
// syncTabsResult.deletedIsolationContextIds,
// );
// if (_pendingIsolationCleanup.isNotEmpty) {
// final pending = Set<String>.of(_pendingIsolationCleanup);
// _pendingIsolationCleanup.clear();
// for (final contextId in pending) {
// if (!ref.mounted) return;
// logger.i('Cleaning orphaned isolation context: $contextId');
// await _cleanupIsolationContextIfEmpty(contextId);
// }
// }
// });
// } catch (e, st) {
// logger.e(
// 'Error during orphan isolation context cleanup',
// error: e,
// stackTrace: st,
// );
// }
// }
@override
void build() {
final eventSerivce = ref.watch(eventServiceProvider);
final tabContentService = ref.watch(tabContentServiceProvider);
final db = ref.watch(tabDatabaseProvider);
final tabAddedSub = eventSerivce.tabAddedStream.listen(
(tabId) async {
final containerId = ref.read(selectedContainerProvider);
await db.tabDao.insertTab(
tabId,
parentId: const Value.absent(),
source: TabSource.addedEvent,
newTabPosition: _newTabPositionForParent(null),
containerId: Value(containerId),
);
},
onError: (Object error, StackTrace stackTrace) {
logger.e(
'Error in tab added stream',
error: error,
stackTrace: stackTrace,
);
},
);
final containerSiteAssignementSub = eventSerivce.siteAssignementEvent.listen(
(event) async {
if (event.tabId != null) {
final tabState = ref.read(tabStatesProvider)[event.tabId];
if (tabState != null) {
final uri = Uri.parse(event.url);
final originUri = event.originUrl.mapNotNull(Uri.parse);
final targetContainerId = await ref
.read(containerRepositoryProvider.notifier)
.siteAssignedContainerId(Uri.parse(uri.origin));
final containerData = await targetContainerId.mapNotNull(
(id) => ref
.read(containerRepositoryProvider.notifier)
.getContainerData(id),
);
if (containerData != null) {
final tabIsEmpty =
tabState.url == TabState.defaultUrl &&
tabState.historyState.items.isEmpty;
if (event.blocked || tabIsEmpty) {
await addTab(
url: uri,
tabMode: tabState.tabMode,
containerSelection: TabContainerSelection.specific(
containerData,
),
parentId: tabState.id,
selectTab: true,
);
if (tabState.historyState.items.isEmpty) {
await closeTab(tabState.id);
}
} else {
final tabContainerId = await ref
.read(tabDataRepositoryProvider.notifier)
.getTabContainerId(tabState.id);
if (targetContainerId != tabContainerId) {
if (originUri == null) {
await ref
.read(tabDataRepositoryProvider.notifier)
.assignContainer(tabState.id, containerData);
} else if (tabState.url == originUri) {
await ref
.read(tabDataRepositoryProvider.notifier)
.assignContainer(
tabState.id,
containerData,
closeOldTab: false,
);
} else {
logger.w(
'Could not match origin url for assignment ${tabState.url} to request ${event.originUrl}',
);
}
}
}
}
} else {
logger.w('Could not get tab for assignement ${tabState?.url}');
}
}
},
onError: (Object error, StackTrace stackTrace) {
logger.e(
'Error in container site assignment stream',
error: error,
stackTrace: stackTrace,
);
},
);
final tabContentSub = tabContentService.tabContentStream.listen(
(content) async {
await db.tabDao.updateTabContent(
content.tabId,
isProbablyReaderable: content.isProbablyReaderable,
extractedContentMarkdown: content.extractedContentMarkdown,
extractedContentPlain: content.extractedContentPlain,
fullContentMarkdown: content.fullContentMarkdown,
fullContentPlain: content.fullContentPlain,
);
},
onError: (Object error, StackTrace stackTrace) {
logger.e(
'Error in tab content stream',
error: error,
stackTrace: stackTrace,
);
},
);
ref.listen(
fireImmediately: true,
selectedTabProvider,
(previous, tabId) async {
if (tabId != null) {
await db.tabDao.touchTab(tabId, timestamp: DateTime.now());
}
},
onError: (Object error, StackTrace stackTrace) {
logger.e(
'Error listening to selectedTabProvider',
error: error,
stackTrace: stackTrace,
);
},
);
ref.listen(
tabListProvider,
(previous, next) async {
//Only sync tabs if there has been a previous value or is not empty
final shouldSyncTabs =
next.value.isNotEmpty || (previous?.value.isNotEmpty ?? false);
if (shouldSyncTabs) {
final syncTabsResult = await db.tabDao.syncTabs(
retainTabIds: next.value,
);
// Capture isolation contexts from rows deleted by syncTabs
// (orphaned tabs from crashes, or tabs the engine dropped).
_pendingIsolationCleanup.addAll(
syncTabsResult.deletedIsolationContextIds,
);
}
// Process pending isolation context cleanups after syncTabs
// has deleted the rows, so the count check is accurate.
if (_pendingIsolationCleanup.isNotEmpty) {
final pending = Set<String>.of(_pendingIsolationCleanup);
_pendingIsolationCleanup.clear();
for (final contextId in pending) {
if (!ref.mounted) break;
await _cleanupIsolationContextIfEmpty(contextId);
}
}
// One-shot orphan cleanup after tab list stabilizes (5s debounce).
// Also runs for DB-only contexts whose rows were already deleted
// by syncTabs above (those are handled via _pendingIsolationCleanup).
// if (!orphanCleanupDone) {
// orphanCleanupTimer?.cancel();
// orphanCleanupTimer = Timer(const Duration(seconds: 5), () async {
// if (orphanCleanupDone || !ref.mounted) return;
// orphanCleanupDone = true;
// await _cleanupOrphanedIsolationContexts();
// });
// }
},
onError: (Object error, StackTrace stackTrace) {
logger.e(
'Error listening to tabListProvider',
error: error,
stackTrace: stackTrace,
);
},
);
final tabStateDebouncer = Debouncer(const Duration(seconds: 1));
Map<String, TabState>? debounceStartValue;
ref.listen(
tabStatesProvider,
(previous, next) {
//Since state changes occure pretty often and our map always contains
//the latest state, we cache the value before starting debouncing and
//later diff to that, to avoid frequent database writes
if (!tabStateDebouncer.isDebouncing) {
debounceStartValue = previous;
}
tabStateDebouncer.eventOccured(() async {
await db.tabDao.updateTabs(debounceStartValue, next);
});
},
onError: (Object error, StackTrace stackTrace) {
logger.e(
'Error listening to tabStatesProvider',
error: error,
stackTrace: stackTrace,
);
},
);
ref.onDispose(() async {
tabStateDebouncer.dispose();
await tabAddedSub.cancel();
await tabContentSub.cancel();
await containerSiteAssignementSub.cancel();
});
}
}
@@ -0,0 +1,62 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'tab.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(TabRepository)
final tabRepositoryProvider = TabRepositoryProvider._();
final class TabRepositoryProvider
extends $NotifierProvider<TabRepository, void> {
TabRepositoryProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'tabRepositoryProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$tabRepositoryHash();
@$internal
@override
TabRepository create() => TabRepository();
/// {@macro riverpod.override_with_value}
Override overrideWithValue(void value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<void>(value),
);
}
}
String _$tabRepositoryHash() => r'ce4ac2f2efbb859ba66e98c6e6d21f8205d9b4ed';
abstract class _$TabRepository extends $Notifier<void> {
void build();
@$mustCallSuper
@override
void runBuild() {
final ref = this.ref as $Ref<void, void>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<void, void>,
void,
Object?,
Object?
>;
element.handleCreate(ref, build);
}
}
@@ -0,0 +1,164 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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:copy_with_extension/copy_with_extension.dart';
import 'package:fast_equatable/fast_equatable.dart';
import 'package:flutter_mozilla_components/flutter_mozilla_components.dart';
import 'package:json_annotation/json_annotation.dart';
part 'bookmark_item.g.dart';
sealed class BookmarkItem {
abstract final String guid;
abstract final String? parentGuid;
abstract final String title;
abstract final int dateAdded;
abstract final int? position;
const BookmarkItem();
static BookmarkItem? parseRecursive(BookmarkNode node) {
return switch (node.type) {
BookmarkNodeType.item => BookmarkEntry(
guid: node.guid,
parentGuid: node.parentGuid,
url: Uri.parse(node.url!),
title: node.title ?? node.url!,
previewImageUrl: Uri.parse(node.url!),
position: node.position,
dateAdded: node.dateAdded,
),
BookmarkNodeType.folder => BookmarkFolder(
guid: node.guid,
parentGuid: node.parentGuid,
title: node.title ?? "Unnamed Folder",
position: node.position,
dateAdded: node.dateAdded,
children: node.children?.map(parseRecursive).nonNulls.toList(),
),
BookmarkNodeType.separator => null,
};
}
factory BookmarkItem.fromJson(Map<String, dynamic> json) {
return (json.containsKey('url'))
? BookmarkEntry.fromJson(json)
: BookmarkFolder.fromJson(json);
}
Map<String, dynamic> toJson();
BookmarkItem clone();
}
@CopyWith()
@JsonSerializable()
class BookmarkEntry extends BookmarkItem with FastEquatable {
@override
final String guid;
@override
final String? parentGuid;
final Uri url;
@override
final String title;
final Uri previewImageUrl;
@override
final int? position;
@override
final int dateAdded;
BookmarkEntry({
required this.guid,
required this.parentGuid,
required this.url,
required this.title,
required this.previewImageUrl,
required this.position,
required this.dateAdded,
});
factory BookmarkEntry.fromJson(Map<String, dynamic> json) =>
_$BookmarkEntryFromJson(json);
@override
Map<String, dynamic> toJson() => _$BookmarkEntryToJson(this);
@override
BookmarkItem clone() {
return copyWith();
}
@override
List<Object?> get hashParameters => [
guid,
parentGuid,
url,
title,
previewImageUrl,
position,
dateAdded,
];
}
@CopyWith()
@JsonSerializable()
class BookmarkFolder extends BookmarkItem with FastEquatable {
@override
final String guid;
@override
final String? parentGuid;
@override
final String title;
@override
final int? position;
@override
final int dateAdded;
final List<BookmarkItem>? children;
BookmarkFolder({
required this.guid,
required this.parentGuid,
required String title,
required this.position,
required this.dateAdded,
required this.children,
}) : title = bookmarkRootDisplayNames[guid] ?? title;
factory BookmarkFolder.fromJson(Map<String, dynamic> json) =>
_$BookmarkFolderFromJson(json);
@override
Map<String, dynamic> toJson() => _$BookmarkFolderToJson(this);
@override
BookmarkItem clone() {
return copyWith();
}
@override
List<Object?> get hashParameters => [
guid,
parentGuid,
title,
position,
dateAdded,
children,
];
}
@@ -0,0 +1,284 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'bookmark_item.dart';
// **************************************************************************
// CopyWithGenerator
// **************************************************************************
abstract class _$BookmarkEntryCWProxy {
BookmarkEntry guid(String guid);
BookmarkEntry parentGuid(String? parentGuid);
BookmarkEntry url(Uri url);
BookmarkEntry title(String title);
BookmarkEntry previewImageUrl(Uri previewImageUrl);
BookmarkEntry position(int? position);
BookmarkEntry dateAdded(int dateAdded);
/// 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 `BookmarkEntry(...).copyWith.fieldName(value)`.
///
/// Example:
/// ```dart
/// BookmarkEntry(...).copyWith(id: 12, name: "My name")
/// ```
BookmarkEntry call({
String guid,
String? parentGuid,
Uri url,
String title,
Uri previewImageUrl,
int? position,
int dateAdded,
});
}
/// Callable proxy for `copyWith` functionality.
/// Use as `instanceOfBookmarkEntry.copyWith(...)` or call `instanceOfBookmarkEntry.copyWith.fieldName(value)` for a single field.
class _$BookmarkEntryCWProxyImpl implements _$BookmarkEntryCWProxy {
const _$BookmarkEntryCWProxyImpl(this._value);
final BookmarkEntry _value;
@override
BookmarkEntry guid(String guid) => call(guid: guid);
@override
BookmarkEntry parentGuid(String? parentGuid) => call(parentGuid: parentGuid);
@override
BookmarkEntry url(Uri url) => call(url: url);
@override
BookmarkEntry title(String title) => call(title: title);
@override
BookmarkEntry previewImageUrl(Uri previewImageUrl) =>
call(previewImageUrl: previewImageUrl);
@override
BookmarkEntry position(int? position) => call(position: position);
@override
BookmarkEntry dateAdded(int dateAdded) => call(dateAdded: dateAdded);
@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 `BookmarkEntry(...).copyWith.fieldName(value)`.
///
/// Example:
/// ```dart
/// BookmarkEntry(...).copyWith(id: 12, name: "My name")
/// ```
BookmarkEntry call({
Object? guid = const $CopyWithPlaceholder(),
Object? parentGuid = const $CopyWithPlaceholder(),
Object? url = const $CopyWithPlaceholder(),
Object? title = const $CopyWithPlaceholder(),
Object? previewImageUrl = const $CopyWithPlaceholder(),
Object? position = const $CopyWithPlaceholder(),
Object? dateAdded = const $CopyWithPlaceholder(),
}) {
return BookmarkEntry(
guid: guid == const $CopyWithPlaceholder() || guid == null
? _value.guid
// ignore: cast_nullable_to_non_nullable
: guid as String,
parentGuid: parentGuid == const $CopyWithPlaceholder()
? _value.parentGuid
// ignore: cast_nullable_to_non_nullable
: parentGuid as String?,
url: url == const $CopyWithPlaceholder() || url == null
? _value.url
// ignore: cast_nullable_to_non_nullable
: url as Uri,
title: title == const $CopyWithPlaceholder() || title == null
? _value.title
// ignore: cast_nullable_to_non_nullable
: title as String,
previewImageUrl:
previewImageUrl == const $CopyWithPlaceholder() ||
previewImageUrl == null
? _value.previewImageUrl
// ignore: cast_nullable_to_non_nullable
: previewImageUrl as Uri,
position: position == const $CopyWithPlaceholder()
? _value.position
// ignore: cast_nullable_to_non_nullable
: position as int?,
dateAdded: dateAdded == const $CopyWithPlaceholder() || dateAdded == null
? _value.dateAdded
// ignore: cast_nullable_to_non_nullable
: dateAdded as int,
);
}
}
extension $BookmarkEntryCopyWith on BookmarkEntry {
/// Returns a callable class used to build a new instance with modified fields.
/// Example: `instanceOfBookmarkEntry.copyWith(...)` or `instanceOfBookmarkEntry.copyWith.fieldName(...)`.
// ignore: library_private_types_in_public_api
_$BookmarkEntryCWProxy get copyWith => _$BookmarkEntryCWProxyImpl(this);
}
abstract class _$BookmarkFolderCWProxy {
BookmarkFolder guid(String guid);
BookmarkFolder parentGuid(String? parentGuid);
BookmarkFolder title(String title);
BookmarkFolder position(int? position);
BookmarkFolder dateAdded(int dateAdded);
BookmarkFolder children(List<BookmarkItem>? children);
/// 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 `BookmarkFolder(...).copyWith.fieldName(value)`.
///
/// Example:
/// ```dart
/// BookmarkFolder(...).copyWith(id: 12, name: "My name")
/// ```
BookmarkFolder call({
String guid,
String? parentGuid,
String title,
int? position,
int dateAdded,
List<BookmarkItem>? children,
});
}
/// Callable proxy for `copyWith` functionality.
/// Use as `instanceOfBookmarkFolder.copyWith(...)` or call `instanceOfBookmarkFolder.copyWith.fieldName(value)` for a single field.
class _$BookmarkFolderCWProxyImpl implements _$BookmarkFolderCWProxy {
const _$BookmarkFolderCWProxyImpl(this._value);
final BookmarkFolder _value;
@override
BookmarkFolder guid(String guid) => call(guid: guid);
@override
BookmarkFolder parentGuid(String? parentGuid) => call(parentGuid: parentGuid);
@override
BookmarkFolder title(String title) => call(title: title);
@override
BookmarkFolder position(int? position) => call(position: position);
@override
BookmarkFolder dateAdded(int dateAdded) => call(dateAdded: dateAdded);
@override
BookmarkFolder children(List<BookmarkItem>? children) =>
call(children: children);
@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 `BookmarkFolder(...).copyWith.fieldName(value)`.
///
/// Example:
/// ```dart
/// BookmarkFolder(...).copyWith(id: 12, name: "My name")
/// ```
BookmarkFolder call({
Object? guid = const $CopyWithPlaceholder(),
Object? parentGuid = const $CopyWithPlaceholder(),
Object? title = const $CopyWithPlaceholder(),
Object? position = const $CopyWithPlaceholder(),
Object? dateAdded = const $CopyWithPlaceholder(),
Object? children = const $CopyWithPlaceholder(),
}) {
return BookmarkFolder(
guid: guid == const $CopyWithPlaceholder() || guid == null
? _value.guid
// ignore: cast_nullable_to_non_nullable
: guid as String,
parentGuid: parentGuid == const $CopyWithPlaceholder()
? _value.parentGuid
// ignore: cast_nullable_to_non_nullable
: parentGuid as String?,
title: title == const $CopyWithPlaceholder() || title == null
? _value.title
// ignore: cast_nullable_to_non_nullable
: title as String,
position: position == const $CopyWithPlaceholder()
? _value.position
// ignore: cast_nullable_to_non_nullable
: position as int?,
dateAdded: dateAdded == const $CopyWithPlaceholder() || dateAdded == null
? _value.dateAdded
// ignore: cast_nullable_to_non_nullable
: dateAdded as int,
children: children == const $CopyWithPlaceholder()
? _value.children
// ignore: cast_nullable_to_non_nullable
: children as List<BookmarkItem>?,
);
}
}
extension $BookmarkFolderCopyWith on BookmarkFolder {
/// Returns a callable class used to build a new instance with modified fields.
/// Example: `instanceOfBookmarkFolder.copyWith(...)` or `instanceOfBookmarkFolder.copyWith.fieldName(...)`.
// ignore: library_private_types_in_public_api
_$BookmarkFolderCWProxy get copyWith => _$BookmarkFolderCWProxyImpl(this);
}
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
BookmarkEntry _$BookmarkEntryFromJson(Map<String, dynamic> json) =>
BookmarkEntry(
guid: json['guid'] as String,
parentGuid: json['parentGuid'] as String?,
url: Uri.parse(json['url'] as String),
title: json['title'] as String,
previewImageUrl: Uri.parse(json['previewImageUrl'] as String),
position: (json['position'] as num?)?.toInt(),
dateAdded: (json['dateAdded'] as num).toInt(),
);
Map<String, dynamic> _$BookmarkEntryToJson(BookmarkEntry instance) =>
<String, dynamic>{
'guid': instance.guid,
'parentGuid': instance.parentGuid,
'url': instance.url.toString(),
'title': instance.title,
'previewImageUrl': instance.previewImageUrl.toString(),
'position': instance.position,
'dateAdded': instance.dateAdded,
};
BookmarkFolder _$BookmarkFolderFromJson(Map<String, dynamic> json) =>
BookmarkFolder(
guid: json['guid'] as String,
parentGuid: json['parentGuid'] as String?,
title: json['title'] as String,
position: (json['position'] as num?)?.toInt(),
dateAdded: (json['dateAdded'] as num).toInt(),
children: (json['children'] as List<dynamic>?)
?.map((e) => BookmarkItem.fromJson(e as Map<String, dynamic>))
.toList(),
);
Map<String, dynamic> _$BookmarkFolderToJson(BookmarkFolder instance) =>
<String, dynamic>{
'guid': instance.guid,
'parentGuid': instance.parentGuid,
'title': instance.title,
'position': instance.position,
'dateAdded': instance.dateAdded,
'children': instance.children?.map((e) => e.toJson()).toList(),
};
@@ -0,0 +1,47 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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:copy_with_extension/copy_with_extension.dart';
import 'package:fast_equatable/fast_equatable.dart';
import 'package:weblibre/features/geckoview/features/bookmarks/domain/entities/bookmark_sort_type.dart';
part 'bookmark_list_ui_state.g.dart';
@CopyWith()
class BookmarkListUiState with FastEquatable {
final bool selectionMode;
final Set<String> selectedGuids;
final BookmarkSortType sortType;
final bool foldersOnly;
BookmarkListUiState({
this.selectionMode = false,
this.selectedGuids = const {},
this.sortType = BookmarkSortType.manual,
this.foldersOnly = false,
});
@override
List<Object?> get hashParameters => [
selectionMode,
selectedGuids,
sortType,
foldersOnly,
];
}
@@ -0,0 +1,100 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'bookmark_list_ui_state.dart';
// **************************************************************************
// CopyWithGenerator
// **************************************************************************
abstract class _$BookmarkListUiStateCWProxy {
BookmarkListUiState selectionMode(bool selectionMode);
BookmarkListUiState selectedGuids(Set<String> selectedGuids);
BookmarkListUiState sortType(BookmarkSortType sortType);
BookmarkListUiState foldersOnly(bool foldersOnly);
/// 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 `BookmarkListUiState(...).copyWith.fieldName(value)`.
///
/// Example:
/// ```dart
/// BookmarkListUiState(...).copyWith(id: 12, name: "My name")
/// ```
BookmarkListUiState call({
bool selectionMode,
Set<String> selectedGuids,
BookmarkSortType sortType,
bool foldersOnly,
});
}
/// Callable proxy for `copyWith` functionality.
/// Use as `instanceOfBookmarkListUiState.copyWith(...)` or call `instanceOfBookmarkListUiState.copyWith.fieldName(value)` for a single field.
class _$BookmarkListUiStateCWProxyImpl implements _$BookmarkListUiStateCWProxy {
const _$BookmarkListUiStateCWProxyImpl(this._value);
final BookmarkListUiState _value;
@override
BookmarkListUiState selectionMode(bool selectionMode) =>
call(selectionMode: selectionMode);
@override
BookmarkListUiState selectedGuids(Set<String> selectedGuids) =>
call(selectedGuids: selectedGuids);
@override
BookmarkListUiState sortType(BookmarkSortType sortType) =>
call(sortType: sortType);
@override
BookmarkListUiState foldersOnly(bool foldersOnly) =>
call(foldersOnly: foldersOnly);
@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 `BookmarkListUiState(...).copyWith.fieldName(value)`.
///
/// Example:
/// ```dart
/// BookmarkListUiState(...).copyWith(id: 12, name: "My name")
/// ```
BookmarkListUiState call({
Object? selectionMode = const $CopyWithPlaceholder(),
Object? selectedGuids = const $CopyWithPlaceholder(),
Object? sortType = const $CopyWithPlaceholder(),
Object? foldersOnly = const $CopyWithPlaceholder(),
}) {
return BookmarkListUiState(
selectionMode:
selectionMode == const $CopyWithPlaceholder() || selectionMode == null
? _value.selectionMode
// ignore: cast_nullable_to_non_nullable
: selectionMode as bool,
selectedGuids:
selectedGuids == const $CopyWithPlaceholder() || selectedGuids == null
? _value.selectedGuids
// ignore: cast_nullable_to_non_nullable
: selectedGuids as Set<String>,
sortType: sortType == const $CopyWithPlaceholder() || sortType == null
? _value.sortType
// ignore: cast_nullable_to_non_nullable
: sortType as BookmarkSortType,
foldersOnly:
foldersOnly == const $CopyWithPlaceholder() || foldersOnly == null
? _value.foldersOnly
// ignore: cast_nullable_to_non_nullable
: foldersOnly as bool,
);
}
}
extension $BookmarkListUiStateCopyWith on BookmarkListUiState {
/// Returns a callable class used to build a new instance with modified fields.
/// Example: `instanceOfBookmarkListUiState.copyWith(...)` or `instanceOfBookmarkListUiState.copyWith.fieldName(...)`.
// ignore: library_private_types_in_public_api
_$BookmarkListUiStateCWProxy get copyWith =>
_$BookmarkListUiStateCWProxyImpl(this);
}
@@ -0,0 +1,63 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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:weblibre/core/sort_field.dart';
import 'package:weblibre/features/geckoview/features/bookmarks/domain/entities/bookmark_item.dart';
enum BookmarkSortType {
manual('Default', null),
titleAsc('Title A-Z', SortField.titleAsc),
titleDesc('Title Z-A', SortField.titleDesc),
urlAsc('URL A-Z', SortField.urlAsc),
urlDesc('URL Z-A', SortField.urlDesc),
dateAddedDesc('Newest First', SortField.dateDesc),
dateAddedAsc('Oldest First', SortField.dateAsc);
final String label;
final SortField? sortField;
const BookmarkSortType(this.label, this.sortField);
}
int compareBookmarkItems(
BookmarkItem a,
BookmarkItem b,
BookmarkSortType sort,
) {
final sortField = sort.sortField;
if (sortField == null) {
return 0;
}
return switch (sortField) {
SortField.titleAsc => a.title.toLowerCase().compareTo(
b.title.toLowerCase(),
),
SortField.titleDesc => b.title.toLowerCase().compareTo(
a.title.toLowerCase(),
),
SortField.urlAsc => _urlKey(a).compareTo(_urlKey(b)),
SortField.urlDesc => _urlKey(b).compareTo(_urlKey(a)),
SortField.dateAsc => a.dateAdded.compareTo(b.dateAdded),
SortField.dateDesc => b.dateAdded.compareTo(a.dateAdded),
};
}
String _urlKey(BookmarkItem item) =>
item is BookmarkEntry ? item.url.toString() : item.title.toLowerCase();
@@ -0,0 +1,74 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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:riverpod_annotation/riverpod_annotation.dart';
import 'package:weblibre/features/geckoview/features/bookmarks/domain/entities/bookmark_list_ui_state.dart';
import 'package:weblibre/features/geckoview/features/bookmarks/domain/entities/bookmark_sort_type.dart';
part 'bookmark_list_ui_state.g.dart';
@Riverpod()
class BookmarkListUiStateNotifier extends _$BookmarkListUiStateNotifier {
@override
BookmarkListUiState build() => BookmarkListUiState();
void enterSelectionMode({String? initialGuid}) {
state = state.copyWith(
selectionMode: true,
selectedGuids: initialGuid != null ? {initialGuid} : {},
);
}
void exitSelectionMode() {
state = state.copyWith(selectionMode: false, selectedGuids: {});
}
void toggleSelection(String guid) {
final updated = Set<String>.from(state.selectedGuids);
if (updated.contains(guid)) {
updated.remove(guid);
} else {
updated.add(guid);
}
if (updated.isEmpty) {
exitSelectionMode();
} else {
state = state.copyWith(selectedGuids: updated);
}
}
void selectAll(Iterable<String> guids) {
state = state.copyWith(
selectionMode: true,
selectedGuids: Set<String>.from(guids),
);
}
void clearSelection() {
exitSelectionMode();
}
void setSortType(BookmarkSortType sortType) {
state = state.copyWith(sortType: sortType);
}
void toggleFoldersOnly() {
state = state.copyWith(foldersOnly: !state.foldersOnly);
}
}
@@ -0,0 +1,65 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'bookmark_list_ui_state.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(BookmarkListUiStateNotifier)
final bookmarkListUiStateProvider = BookmarkListUiStateNotifierProvider._();
final class BookmarkListUiStateNotifierProvider
extends
$NotifierProvider<BookmarkListUiStateNotifier, BookmarkListUiState> {
BookmarkListUiStateNotifierProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'bookmarkListUiStateProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$bookmarkListUiStateNotifierHash();
@$internal
@override
BookmarkListUiStateNotifier create() => BookmarkListUiStateNotifier();
/// {@macro riverpod.override_with_value}
Override overrideWithValue(BookmarkListUiState value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<BookmarkListUiState>(value),
);
}
}
String _$bookmarkListUiStateNotifierHash() =>
r'7c764fc2f1deb178063ca95764775ca237471f9f';
abstract class _$BookmarkListUiStateNotifier
extends $Notifier<BookmarkListUiState> {
BookmarkListUiState build();
@$mustCallSuper
@override
void runBuild() {
final ref = this.ref as $Ref<BookmarkListUiState, BookmarkListUiState>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<BookmarkListUiState, BookmarkListUiState>,
BookmarkListUiState,
Object?,
Object?
>;
element.handleCreate(ref, build);
}
}
@@ -0,0 +1,257 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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 'dart:async';
import 'package:flutter/services.dart';
import 'package:flutter_mozilla_components/flutter_mozilla_components.dart';
import 'package:nullability/nullability.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:weblibre/features/geckoview/features/bookmarks/domain/entities/bookmark_item.dart';
import 'package:weblibre/features/geckoview/features/bookmarks/domain/repositories/bookmarks.dart';
part 'bookmarks.g.dart';
/// Check if a root folder is effectively empty (has no non-root children)
bool _isEmptyRootFolder(BookmarkFolder folder) {
if (folder.children == null) return true;
// A root folder is empty if it has no children, or only contains other root folders
return folder.children!.every(
(child) => bookmarkRootIds.contains(child.guid),
);
}
T? _selectChildRecursive<T extends BookmarkItem>(
List<BookmarkItem> children,
String guid,
) {
for (final child in children) {
if (child.guid == guid && child is T) {
return child;
}
if (child case final BookmarkFolder folder) {
if (folder.children != null) {
final result = _selectChildRecursive<T>(folder.children!, guid);
if (result != null) {
return result;
}
}
}
}
return null;
}
T _cloneAndFilterChildrenType<T extends BookmarkItem>(T node) {
if (node is BookmarkFolder) {
if (node.children != null) {
return node.copyWith.children(
node.children
?.whereType<T>()
.map((e) => _cloneAndFilterChildrenType<T>(e))
.toList(),
)
as T;
}
}
return node.clone() as T;
}
BookmarkItem? _cloneAndFilterOnGuids(BookmarkItem node, Set<String> guids) {
if (node is BookmarkFolder) {
if (node.children != null) {
final filtered = node.children
?.where((e) => e is BookmarkFolder || guids.contains(e.guid))
.map((e) => _cloneAndFilterOnGuids(e, guids))
.nonNulls
.toList();
if (filtered.isNotEmpty) {
return node.copyWith.children(filtered);
} else {
return null;
}
}
}
if (guids.contains(node.guid)) {
return node.clone();
}
return null;
}
@Riverpod()
class BookmarksSearch extends _$BookmarksSearch {
final _service = GeckoBookmarksService();
late StreamController<Set<String>> _streamController;
Future<void> search(String query, {int limit = 10}) async {
if (query.isNotEmpty) {
try {
await _service.searchBookmarks(query, limit: limit).then((value) {
if (!_streamController.isClosed) {
_streamController.add(value.map((e) => e.guid).toSet());
}
});
} on PlatformException catch (e) {
if (e.code == 'OperationInterrupted') return;
rethrow;
}
}
}
@override
Stream<Set<String>> build() {
_streamController = StreamController();
ref.onDispose(() async {
await _streamController.close();
});
return _streamController.stream;
}
}
@Riverpod()
class BookmarkSearchResults extends _$BookmarkSearchResults {
final _service = GeckoBookmarksService();
Future<void> search(String query, {int limit = 10}) async {
if (query.isEmpty) {
state = [];
return;
}
try {
final results = await _service.searchBookmarks(query, limit: limit);
if (!ref.mounted) return;
state = results
.map(BookmarkItem.parseRecursive)
.whereType<BookmarkEntry>()
.toList();
} on PlatformException catch (e) {
if (e.code == 'OperationInterrupted') return;
rethrow;
}
}
@override
List<BookmarkEntry> build() {
return [];
}
}
@Riverpod()
AsyncValue<T?> bookmarks<T extends BookmarkItem>(
Ref ref,
String entryGuid, {
bool hideEmptyRoots = false,
}) {
final bookmarksAsync = ref.watch(bookmarksRepositoryProvider);
return bookmarksAsync.whenData((bookmarkNode) {
T? selectedNode;
if (bookmarkNode != null && bookmarkNode is T) {
if (bookmarkNode.guid == entryGuid) {
selectedNode = bookmarkNode;
} else if (bookmarkNode case final BookmarkFolder folder) {
if (folder.children != null) {
selectedNode = _selectChildRecursive<T>(folder.children!, entryGuid);
}
}
}
if (selectedNode != null) {
var result = _cloneAndFilterChildrenType<T>(selectedNode);
// Filter empty root folders when viewing root level (excluding WebLibre root)
if (hideEmptyRoots &&
entryGuid == BookmarkRoot.root.id &&
result is BookmarkFolder) {
final filteredChildren = result.children
?.where(
(child) =>
child is! BookmarkFolder ||
child.guid == BookmarkRoot.mobile.id ||
!_isEmptyRootFolder(child),
)
.toList();
result = result.copyWith.children(filteredChildren) as T;
}
return result;
}
return null;
});
}
@Riverpod()
class SeamlessBookmarks extends _$SeamlessBookmarks {
bool _hasSearch = false;
void search(String input) {
if (input.isNotEmpty) {
if (!_hasSearch) {
_hasSearch = true;
ref.invalidateSelf();
}
//Don't block
unawaited(ref.read(bookmarksSearchProvider.notifier).search(input));
} else if (_hasSearch) {
_hasSearch = false;
ref.invalidateSelf();
}
}
@override
AsyncValue<BookmarkItem?> build(
String entryGuid, {
bool hideEmptyRoots = false,
}) {
final bookmarks = ref.watch(
bookmarksProvider<BookmarkItem>(
entryGuid,
hideEmptyRoots: hideEmptyRoots,
),
);
if (_hasSearch) {
final filterGuids = ref.watch(bookmarksSearchProvider);
return bookmarks.map(
data: (node) =>
node.value.mapNotNull(
(node) => filterGuids.whenData(
(results) => _cloneAndFilterOnGuids(node, results),
),
) ??
const AsyncValue.data(null),
error: (e) => e,
loading: (s) => s,
);
} else {
return bookmarks;
}
}
}
@@ -0,0 +1,330 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'bookmarks.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(BookmarksSearch)
final bookmarksSearchProvider = BookmarksSearchProvider._();
final class BookmarksSearchProvider
extends $StreamNotifierProvider<BookmarksSearch, Set<String>> {
BookmarksSearchProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'bookmarksSearchProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$bookmarksSearchHash();
@$internal
@override
BookmarksSearch create() => BookmarksSearch();
}
String _$bookmarksSearchHash() => r'41053cbc1014e0fdd04d9510bf15c9896a9f752d';
abstract class _$BookmarksSearch extends $StreamNotifier<Set<String>> {
Stream<Set<String>> build();
@$mustCallSuper
@override
void runBuild() {
final ref = this.ref as $Ref<AsyncValue<Set<String>>, Set<String>>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<AsyncValue<Set<String>>, Set<String>>,
AsyncValue<Set<String>>,
Object?,
Object?
>;
element.handleCreate(ref, build);
}
}
@ProviderFor(BookmarkSearchResults)
final bookmarkSearchResultsProvider = BookmarkSearchResultsProvider._();
final class BookmarkSearchResultsProvider
extends $NotifierProvider<BookmarkSearchResults, List<BookmarkEntry>> {
BookmarkSearchResultsProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'bookmarkSearchResultsProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$bookmarkSearchResultsHash();
@$internal
@override
BookmarkSearchResults create() => BookmarkSearchResults();
/// {@macro riverpod.override_with_value}
Override overrideWithValue(List<BookmarkEntry> value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<List<BookmarkEntry>>(value),
);
}
}
String _$bookmarkSearchResultsHash() =>
r'49ebd21a137bc09bbd67b692aacb2554b8364564';
abstract class _$BookmarkSearchResults extends $Notifier<List<BookmarkEntry>> {
List<BookmarkEntry> build();
@$mustCallSuper
@override
void runBuild() {
final ref = this.ref as $Ref<List<BookmarkEntry>, List<BookmarkEntry>>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<List<BookmarkEntry>, List<BookmarkEntry>>,
List<BookmarkEntry>,
Object?,
Object?
>;
element.handleCreate(ref, build);
}
}
@ProviderFor(bookmarks)
final bookmarksProvider = BookmarksFamily._();
final class BookmarksProvider<T extends BookmarkItem>
extends $FunctionalProvider<AsyncValue<T?>, AsyncValue<T?>, AsyncValue<T?>>
with $Provider<AsyncValue<T?>> {
BookmarksProvider._({
required BookmarksFamily super.from,
required (String, {bool hideEmptyRoots}) super.argument,
}) : super(
retry: null,
name: r'bookmarksProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$bookmarksHash();
@override
String toString() {
return r'bookmarksProvider'
'<${T}>'
'$argument';
}
@$internal
@override
$ProviderElement<AsyncValue<T?>> $createElement($ProviderPointer pointer) =>
$ProviderElement(pointer);
@override
AsyncValue<T?> create(Ref ref) {
final argument = this.argument as (String, {bool hideEmptyRoots});
return bookmarks<T>(
ref,
argument.$1,
hideEmptyRoots: argument.hideEmptyRoots,
);
}
$R _captureGenerics<$R>($R Function<T extends BookmarkItem>() cb) {
return cb<T>();
}
/// {@macro riverpod.override_with_value}
Override overrideWithValue(AsyncValue<T?> value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<AsyncValue<T?>>(value),
);
}
@override
bool operator ==(Object other) {
return other is BookmarksProvider &&
other.runtimeType == runtimeType &&
other.argument == argument;
}
@override
int get hashCode {
return Object.hash(runtimeType, argument);
}
}
String _$bookmarksHash() => r'72b54c4ff18cfdb60824a57607628be6b61d25d4';
final class BookmarksFamily extends $Family {
BookmarksFamily._()
: super(
retry: null,
name: r'bookmarksProvider',
dependencies: null,
$allTransitiveDependencies: null,
isAutoDispose: true,
);
BookmarksProvider<T> call<T extends BookmarkItem>(
String entryGuid, {
bool hideEmptyRoots = false,
}) => BookmarksProvider<T>._(
argument: (entryGuid, hideEmptyRoots: hideEmptyRoots),
from: this,
);
@override
String toString() => r'bookmarksProvider';
/// {@macro riverpod.override_with}
Override overrideWith(
AsyncValue<T?> Function<T extends BookmarkItem>(
Ref ref,
(String, {bool hideEmptyRoots}) args,
)
create,
) => $FamilyOverride(
from: this,
createElement: (pointer) {
final provider = pointer.origin as BookmarksProvider;
return provider._captureGenerics(<T extends BookmarkItem>() {
provider as BookmarksProvider<T>;
final argument = provider.argument as (String, {bool hideEmptyRoots});
return provider
.$view(create: (ref) => create(ref, argument))
.$createElement(pointer);
});
},
);
}
@ProviderFor(SeamlessBookmarks)
final seamlessBookmarksProvider = SeamlessBookmarksFamily._();
final class SeamlessBookmarksProvider
extends $NotifierProvider<SeamlessBookmarks, AsyncValue<BookmarkItem?>> {
SeamlessBookmarksProvider._({
required SeamlessBookmarksFamily super.from,
required (String, {bool hideEmptyRoots}) super.argument,
}) : super(
retry: null,
name: r'seamlessBookmarksProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$seamlessBookmarksHash();
@override
String toString() {
return r'seamlessBookmarksProvider'
''
'$argument';
}
@$internal
@override
SeamlessBookmarks create() => SeamlessBookmarks();
/// {@macro riverpod.override_with_value}
Override overrideWithValue(AsyncValue<BookmarkItem?> value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<AsyncValue<BookmarkItem?>>(value),
);
}
@override
bool operator ==(Object other) {
return other is SeamlessBookmarksProvider && other.argument == argument;
}
@override
int get hashCode {
return argument.hashCode;
}
}
String _$seamlessBookmarksHash() => r'240b213fa8fe595781ccc608c5d551be54c31992';
final class SeamlessBookmarksFamily extends $Family
with
$ClassFamilyOverride<
SeamlessBookmarks,
AsyncValue<BookmarkItem?>,
AsyncValue<BookmarkItem?>,
AsyncValue<BookmarkItem?>,
(String, {bool hideEmptyRoots})
> {
SeamlessBookmarksFamily._()
: super(
retry: null,
name: r'seamlessBookmarksProvider',
dependencies: null,
$allTransitiveDependencies: null,
isAutoDispose: true,
);
SeamlessBookmarksProvider call(
String entryGuid, {
bool hideEmptyRoots = false,
}) => SeamlessBookmarksProvider._(
argument: (entryGuid, hideEmptyRoots: hideEmptyRoots),
from: this,
);
@override
String toString() => r'seamlessBookmarksProvider';
}
abstract class _$SeamlessBookmarks
extends $Notifier<AsyncValue<BookmarkItem?>> {
late final _$args = ref.$arg as (String, {bool hideEmptyRoots});
String get entryGuid => _$args.$1;
bool get hideEmptyRoots => _$args.hideEmptyRoots;
AsyncValue<BookmarkItem?> build(
String entryGuid, {
bool hideEmptyRoots = false,
});
@$mustCallSuper
@override
void runBuild() {
final ref =
this.ref as $Ref<AsyncValue<BookmarkItem?>, AsyncValue<BookmarkItem?>>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<AsyncValue<BookmarkItem?>, AsyncValue<BookmarkItem?>>,
AsyncValue<BookmarkItem?>,
Object?,
Object?
>;
element.handleCreate(
ref,
() => build(_$args.$1, hideEmptyRoots: _$args.hideEmptyRoots),
);
}
}
@@ -0,0 +1,196 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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:flutter_mozilla_components/flutter_mozilla_components.dart';
import 'package:nullability/nullability.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:weblibre/core/logger.dart';
import 'package:weblibre/features/geckoview/features/bookmarks/domain/entities/bookmark_item.dart';
import 'package:weblibre/features/geckoview/features/bookmarks/utils/bookmark_html_utils.dart';
import 'package:weblibre/features/geckoview/features/bookmarks/utils/bookmark_json_utils.dart';
part 'bookmarks.g.dart';
@Riverpod(keepAlive: true)
class BookmarksRepository extends _$BookmarksRepository {
final _service = GeckoBookmarksService();
late final _jsonUtils = BookmarkJSONUtils(_service);
late final _htmlUtils = BookmarkHTMLUtils(_service);
Future<void> addBookmark({
required String parentGuid,
required Uri url,
required String title,
int? position,
}) async {
await _service.addItem(parentGuid, url, title, position);
ref.invalidateSelf();
}
Future<void> addFolder({
required String parentGuid,
required String title,
int? position,
}) async {
await _service.addFolder(parentGuid, title, position);
ref.invalidateSelf();
}
Future<void> editBookmark({
required String guid,
String? title,
Uri? url,
String? parentGuid,
int? position,
}) async {
await _service.updateNode(
guid,
BookmarkInfo(
title: title,
url: url?.toString(),
parentGuid: parentGuid,
position: position,
),
);
ref.invalidateSelf();
}
Future<void> editFolder({
required String guid,
String? title,
String? parentGuid,
int? position,
}) async {
await _service.updateNode(
guid,
BookmarkInfo(title: title, parentGuid: parentGuid, position: position),
);
ref.invalidateSelf();
}
Future<void> delete(String guid) async {
await _service.deleteNode(guid);
ref.invalidateSelf();
}
Future<void> moveMany({
required Iterable<BookmarkItem> items,
required String targetParentGuid,
}) async {
for (final item in items) {
if (bookmarkRootIds.contains(item.guid)) {
logger.w('Skipping move of root folder: ${item.guid}');
continue;
}
if (item.parentGuid == targetParentGuid) continue;
await _service.updateNode(
item.guid,
BookmarkInfo(parentGuid: targetParentGuid),
);
}
ref.invalidateSelf();
}
Future<void> deleteMany(Iterable<String> guids) async {
for (final guid in guids) {
if (bookmarkRootIds.contains(guid)) {
logger.w('Skipping delete of root folder: $guid');
continue;
}
await _service.deleteNode(guid);
}
ref.invalidateSelf();
}
Future<void> flattenFolder({required BookmarkFolder folder}) async {
if (folder.parentGuid == null || bookmarkRootIds.contains(folder.guid)) {
logger.w('Cannot flatten root or parentless folder: ${folder.guid}');
return;
}
// Fetch the full folder tree from storage to avoid operating on a
// filtered subset (e.g. when search is active), which would silently
// delete children that were not moved.
final fullNode = await _service.getTree(folder.guid);
final children = fullNode?.children;
if (children != null) {
for (final child in children) {
await _service.updateNode(
child.guid,
BookmarkInfo(parentGuid: folder.parentGuid),
);
}
}
await _service.deleteNode(folder.guid);
ref.invalidateSelf();
}
/// Returns the GUIDs of all descendant folders of [guid] by fetching the
/// full subtree from storage. This is safe to call even when the UI tree is
/// filtered (e.g. during search), unlike the pure-utility
/// [collectDescendantFolderGuids] which only walks the in-memory tree.
Future<Set<String>> getDescendantFolderGuids(String guid) async {
final node = await _service.getTree(guid, recursive: true);
if (node == null) return const {};
final result = <String>{};
void collect(BookmarkNode n) {
for (final child in n.children ?? const <BookmarkNode>[]) {
if (child.type == BookmarkNodeType.folder) {
result.add(child.guid);
collect(child);
}
}
}
collect(node);
return result;
}
Future<void> eraseEverything(BookmarkRoot root) async {
await _service.eraseEverything(root);
ref.invalidateSelf();
}
Future<int> importFromJSON(String jsonString, {bool replace = false}) async {
final count = await _jsonUtils.importFromJSON(jsonString, replace: replace);
ref.invalidateSelf();
return count;
}
Future<int> importFromHTML(String htmlString, {bool replace = false}) async {
final count = await _htmlUtils.importFromHTML(htmlString, replace: replace);
ref.invalidateSelf();
return count;
}
Future<Map<String, dynamic>?> exportToJson({
required BookmarkRoot root,
}) async {
return await _jsonUtils.exportToJson(root: root);
}
Future<String> exportToHTML({required BookmarkRoot root}) async {
return await _htmlUtils.exportToHTML(root: root);
}
@override
Future<BookmarkItem?> build() async {
final node = await _service.getTree(BookmarkRoot.root.id, recursive: true);
return node.mapNotNull(BookmarkItem.parseRecursive);
}
}
@@ -0,0 +1,55 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'bookmarks.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(BookmarksRepository)
final bookmarksRepositoryProvider = BookmarksRepositoryProvider._();
final class BookmarksRepositoryProvider
extends $AsyncNotifierProvider<BookmarksRepository, BookmarkItem?> {
BookmarksRepositoryProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'bookmarksRepositoryProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$bookmarksRepositoryHash();
@$internal
@override
BookmarksRepository create() => BookmarksRepository();
}
String _$bookmarksRepositoryHash() =>
r'2169d5b354c4a22192096451c96ab1490cf55ab4';
abstract class _$BookmarksRepository extends $AsyncNotifier<BookmarkItem?> {
FutureOr<BookmarkItem?> build();
@$mustCallSuper
@override
void runBuild() {
final ref = this.ref as $Ref<AsyncValue<BookmarkItem?>, BookmarkItem?>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<AsyncValue<BookmarkItem?>, BookmarkItem?>,
AsyncValue<BookmarkItem?>,
Object?,
Object?
>;
element.handleCreate(ref, build);
}
}
@@ -0,0 +1,162 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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:flutter_mozilla_components/flutter_mozilla_components.dart';
import 'package:weblibre/features/geckoview/features/bookmarks/domain/entities/bookmark_item.dart';
import 'package:weblibre/features/geckoview/features/bookmarks/domain/entities/bookmark_sort_type.dart';
/// Recursively sorts a bookmark tree by the given sort type.
/// Root-level built-in folders are kept in their canonical order.
BookmarkItem sortBookmarkTree(
BookmarkItem item,
BookmarkSortType sortType, {
bool isRoot = false,
}) {
if (sortType == BookmarkSortType.manual) return item;
if (item is BookmarkFolder && item.children != null) {
final sortedChildren = item.children!.map((child) {
return sortBookmarkTree(child, sortType);
}).toList();
// At root level, keep built-in root folders pinned in original order
if (isRoot) {
final rootFolders = <BookmarkItem>[];
final nonRootItems = <BookmarkItem>[];
for (final child in sortedChildren) {
if (bookmarkRootIds.contains(child.guid)) {
rootFolders.add(child);
} else {
nonRootItems.add(child);
}
}
nonRootItems.sort((a, b) => compareBookmarkItems(a, b, sortType));
return BookmarkFolder(
guid: item.guid,
parentGuid: item.parentGuid,
title: item.title,
position: item.position,
dateAdded: item.dateAdded,
children: [...rootFolders, ...nonRootItems],
);
}
sortedChildren.sort((a, b) => compareBookmarkItems(a, b, sortType));
return BookmarkFolder(
guid: item.guid,
parentGuid: item.parentGuid,
title: item.title,
position: item.position,
dateAdded: item.dateAdded,
children: sortedChildren,
);
}
return item;
}
/// Collects all descendant folder GUIDs from a folder (not including the folder itself).
Set<String> collectDescendantFolderGuids(BookmarkFolder folder) {
final result = <String>{};
if (folder.children != null) {
for (final child in folder.children!) {
if (child is BookmarkFolder) {
result.add(child.guid);
result.addAll(collectDescendantFolderGuids(child));
}
}
}
return result;
}
/// Resolves BookmarkItems from a tree by their GUIDs.
List<BookmarkItem> resolveSelectedItems(BookmarkItem root, Set<String> guids) {
final result = <BookmarkItem>[];
_collectByGuids(root, guids, result);
return result;
}
void _collectByGuids(
BookmarkItem item,
Set<String> guids,
List<BookmarkItem> result,
) {
if (guids.contains(item.guid)) {
result.add(item);
}
if (item is BookmarkFolder && item.children != null) {
for (final child in item.children!) {
_collectByGuids(child, guids, result);
}
}
}
/// Whether a folder can be flattened (non-root, has a parent, has children).
bool canFlattenFolder(BookmarkFolder folder) {
return folder.parentGuid != null &&
!bookmarkRootIds.contains(folder.guid) &&
folder.children != null &&
folder.children!.isNotEmpty;
}
/// Normalizes a selection set: removes items that are descendants of selected folders.
/// This prevents double-applying moves when both a folder and its children are selected.
Set<String> normalizeSelection(BookmarkItem root, Set<String> selectedGuids) {
final items = resolveSelectedItems(root, selectedGuids);
final folderGuidsToRemove = <String>{};
for (final item in items) {
if (item is BookmarkFolder) {
_collectAllDescendantGuids(item, folderGuidsToRemove);
}
}
return selectedGuids.difference(folderGuidsToRemove);
}
void _collectAllDescendantGuids(BookmarkFolder folder, Set<String> result) {
if (folder.children != null) {
for (final child in folder.children!) {
result.add(child.guid);
if (child is BookmarkFolder) {
_collectAllDescendantGuids(child, result);
}
}
}
}
/// Returns GUIDs of all bookmark entries matching [url] in the tree.
List<String> bookmarkGuidsForUrl(BookmarkItem? root, Uri? url) {
final result = <String>[];
if (root == null || url == null) return result;
void collect(BookmarkItem item) {
if (item is BookmarkEntry && item.url == url) {
result.add(item.guid);
}
if (item is BookmarkFolder) {
for (final child in item.children ?? const <BookmarkItem>[]) {
collect(child);
}
}
}
collect(root);
return result;
}
@@ -0,0 +1,47 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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:flutter/material.dart';
Future<bool?> showDeleteBookmarkDialog(BuildContext context) {
return showDialog<bool?>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
icon: const Icon(Icons.warning),
title: const Text('Delete Bookmark'),
content: const Text('Are you sure you want to delete this Bookmark?'),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.pop(context, false);
},
child: const Text('Cancel'),
),
TextButton(
onPressed: () {
Navigator.pop(context, true);
},
child: const Text('Delete'),
),
],
);
},
);
}
@@ -0,0 +1,49 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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:flutter/material.dart';
Future<bool?> showDeleteFolderDialog(BuildContext context) {
return showDialog<bool?>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
icon: const Icon(Icons.warning),
title: const Text('Delete Folder'),
content: const Text(
'Are you sure you want to delete this Folder including all bookmarks?',
),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.pop(context, false);
},
child: const Text('Cancel'),
),
TextButton(
onPressed: () {
Navigator.pop(context, true);
},
child: const Text('Delete'),
),
],
);
},
);
}
@@ -0,0 +1,49 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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:flutter/material.dart';
Future<bool?> showImportBookmarksDialog(BuildContext context) {
return showDialog<bool?>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Import Bookmarks'),
content: const Text(
'Do you want to erase all existing bookmarks before importing?\n\n'
'Choose "Replace" to delete existing bookmarks, or "Merge" to keep them.',
),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.pop(context, false);
},
child: const Text('Merge'),
),
TextButton(
onPressed: () {
Navigator.pop(context, true);
},
child: const Text('Replace'),
),
],
);
},
);
}
@@ -0,0 +1,102 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:flutter_mozilla_components/flutter_mozilla_components.dart';
import 'package:go_router/go_router.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:weblibre/features/geckoview/features/bookmarks/presentation/widgets/folder_tree_picker.dart';
/// Shows a bottom sheet for selecting a bookmark folder destination (for move operations).
///
/// Returns the selected folder GUID, or null if cancelled.
Future<String?> showSelectBookmarkFolderDialog(
BuildContext context, {
Set<String> excludeFolderGuids = const {},
String? initialFolderGuid,
}) {
return showModalBottomSheet<String>(
context: context,
isScrollControlled: true,
builder: (context) => _SelectBookmarkFolderSheet(
excludeFolderGuids: excludeFolderGuids,
initialFolderGuid: initialFolderGuid,
),
);
}
class _SelectBookmarkFolderSheet extends HookConsumerWidget {
final Set<String> excludeFolderGuids;
final String? initialFolderGuid;
const _SelectBookmarkFolderSheet({
required this.excludeFolderGuids,
this.initialFolderGuid,
});
@override
Widget build(BuildContext context, WidgetRef ref) {
final selectedGuid = useState(initialFolderGuid ?? BookmarkRoot.mobile.id);
return SafeArea(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
'Move to Folder',
style: Theme.of(context).textTheme.titleLarge,
),
const SizedBox(height: 16),
ConstrainedBox(
constraints: BoxConstraints(
maxHeight: MediaQuery.of(context).size.height * 0.5,
),
child: SingleChildScrollView(
child: FolderTreePicker(
selectedFolderGuid: selectedGuid,
excludeFolderGuids: excludeFolderGuids,
entryGuid: BookmarkRoot.root.id,
),
),
),
const SizedBox(height: 16),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
TextButton(
onPressed: () => context.pop(),
child: const Text('Cancel'),
),
const SizedBox(width: 8),
FilledButton(
onPressed: () => context.pop(selectedGuid.value),
child: const Text('Move'),
),
],
),
],
),
),
);
}
}
@@ -0,0 +1,208 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:flutter_material_design_icons/flutter_material_design_icons.dart';
import 'package:flutter_mozilla_components/flutter_mozilla_components.dart';
import 'package:go_router/go_router.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:weblibre/features/geckoview/features/bookmarks/domain/entities/bookmark_item.dart';
import 'package:weblibre/features/geckoview/features/bookmarks/domain/repositories/bookmarks.dart';
import 'package:weblibre/features/geckoview/features/bookmarks/presentation/dialogs/delete_bookmark_dialog.dart';
import 'package:weblibre/features/geckoview/features/bookmarks/presentation/widgets/folder_tree_picker.dart';
import 'package:weblibre/utils/form_validators.dart';
import 'package:weblibre/utils/uri_input_parser.dart';
class BookmarkEntryEditScreen extends HookConsumerWidget {
final BookmarkInfo? initialInfo;
final BookmarkEntry? exisitingEntry;
const BookmarkEntryEditScreen({
super.key,
required this.exisitingEntry,
required this.initialInfo,
});
@override
Widget build(BuildContext context, WidgetRef ref) {
final formKey = useMemoized(() => GlobalKey<FormState>());
final nameTextController = useTextEditingController(
text: initialInfo?.title ?? exisitingEntry?.title,
);
final urlTextController = useTextEditingController(
text: initialInfo?.url ?? exisitingEntry?.url.toString(),
);
final parentGuid = useState(
initialInfo?.parentGuid ??
exisitingEntry?.parentGuid ??
BookmarkRoot.mobile.id,
);
final addToTop = useState(false);
return Scaffold(
appBar: AppBar(
title: (exisitingEntry != null)
? const Text('Edit Bookmark')
: const Text('Create Bookmark'),
actions: [
IconButton(
onPressed: () async {
if (formKey.currentState?.validate() ?? false) {
var newUrl = parseValidatedUrl(
urlTextController.text,
eagerParsing: true,
onlyHttpProtocol: true,
);
if (newUrl == null) {
return;
}
newUrl = redactUriCredentials(newUrl);
if (exisitingEntry != null) {
await ref
.read(bookmarksRepositoryProvider.notifier)
.editBookmark(
guid: exisitingEntry!.guid,
title:
(nameTextController.text != exisitingEntry!.title)
? nameTextController.text
: null,
parentGuid:
(parentGuid.value != exisitingEntry!.parentGuid)
? parentGuid.value
: null,
url: (newUrl != exisitingEntry!.url) ? newUrl : null,
);
if (context.mounted) {
context.pop();
}
} else {
await ref
.read(bookmarksRepositoryProvider.notifier)
.addBookmark(
parentGuid: parentGuid.value,
title: nameTextController.text,
url: newUrl,
position: addToTop.value ? 0 : null,
);
if (context.mounted) {
context.pop();
}
}
}
},
icon: const Icon(Icons.check),
),
],
),
body: SafeArea(
child: Form(
key: formKey,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12.0),
child: ListView(
children: [
TextFormField(
controller: nameTextController,
decoration: const InputDecoration(
label: Text('Name'),
floatingLabelBehavior: FloatingLabelBehavior.always,
),
minLines: 1,
maxLines: 3,
validator: validateRequired,
),
const SizedBox(height: 8),
TextFormField(
controller: urlTextController,
keyboardType: TextInputType.url,
minLines: 1,
maxLines: 10,
decoration: const InputDecoration(
label: Text('URL'),
hintText: 'https://example.com/',
floatingLabelBehavior: FloatingLabelBehavior.always,
),
validator: (value) {
return validateUrl(
value,
onlyHttpProtocol: true,
eagerParsing: true,
);
},
),
const SizedBox(height: 16),
FolderTreePicker(
selectedFolderGuid: parentGuid,
entryGuid: BookmarkRoot.root.id,
),
if (exisitingEntry == null) ...[
const SizedBox(height: 8),
SwitchListTile(
contentPadding: EdgeInsets.zero,
title: const Text('Add to top'),
value: addToTop.value,
onChanged: (value) => addToTop.value = value,
),
],
const SizedBox(height: 16),
if (exisitingEntry != null)
SizedBox(
width: double.infinity,
child: OutlinedButton.icon(
style: OutlinedButton.styleFrom(
side: BorderSide(
color: Theme.of(context).colorScheme.error,
),
foregroundColor: Theme.of(context).colorScheme.error,
iconColor: Theme.of(context).colorScheme.error,
),
label: const Text('Delete'),
icon: const Icon(MdiIcons.bookmarkRemove),
onPressed: () async {
final result = await showDeleteBookmarkDialog(context);
if (result == true) {
await ref
.read(bookmarksRepositoryProvider.notifier)
.delete(exisitingEntry!.guid);
if (context.mounted) {
context.pop();
}
}
},
),
),
],
),
),
),
),
);
}
}
@@ -0,0 +1,172 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:flutter_mozilla_components/flutter_mozilla_components.dart';
import 'package:go_router/go_router.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:weblibre/features/geckoview/features/bookmarks/domain/entities/bookmark_item.dart';
import 'package:weblibre/features/geckoview/features/bookmarks/domain/repositories/bookmarks.dart';
import 'package:weblibre/features/geckoview/features/bookmarks/presentation/dialogs/delete_folder_dialog.dart';
import 'package:weblibre/features/geckoview/features/bookmarks/presentation/widgets/folder_tree_picker.dart';
import 'package:weblibre/utils/form_validators.dart';
class BookmarkFolderEditScreen extends HookConsumerWidget {
final String? parentGuid;
final BookmarkFolder? folder;
const BookmarkFolderEditScreen({
super.key,
required this.folder,
this.parentGuid,
});
@override
Widget build(BuildContext context, WidgetRef ref) {
final formKey = useMemoized(() => GlobalKey<FormState>());
final nameTextController = useTextEditingController(text: folder?.title);
final currentParentGuid = useState(
parentGuid ?? folder?.parentGuid ?? BookmarkRoot.mobile.id,
);
final addToTop = useState(false);
// Check if this is a bookmark root folder (these cannot be moved)
final isBookmarkRoot =
folder != null && bookmarkRootIds.contains(folder!.guid);
return Scaffold(
appBar: AppBar(
title: (folder != null)
? const Text('Edit Folder')
: const Text('Create Folder'),
actions: [
IconButton(
onPressed: () async {
if (formKey.currentState?.validate() ?? false) {
if (folder != null) {
await ref
.read(bookmarksRepositoryProvider.notifier)
.editFolder(
guid: folder!.guid,
title: (nameTextController.text != folder!.title)
? nameTextController.text
: null,
parentGuid:
(!isBookmarkRoot &&
currentParentGuid.value != folder!.parentGuid)
? currentParentGuid.value
: null,
);
if (context.mounted) {
context.pop();
}
} else {
await ref
.read(bookmarksRepositoryProvider.notifier)
.addFolder(
parentGuid: currentParentGuid.value,
title: nameTextController.text,
position: addToTop.value ? 0 : null,
);
if (context.mounted) {
context.pop();
}
}
}
},
icon: const Icon(Icons.check),
),
],
),
body: SafeArea(
child: Form(
key: formKey,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12.0),
child: ListView(
children: [
TextFormField(
controller: nameTextController,
decoration: const InputDecoration(
label: Text('Name'),
floatingLabelBehavior: FloatingLabelBehavior.always,
),
validator: validateRequired,
),
const SizedBox(height: 16),
if (!isBookmarkRoot) ...[
FolderTreePicker(
selectedFolderGuid: currentParentGuid,
excludeFolderGuids: folder != null
? {folder!.guid}
: const {},
entryGuid: BookmarkRoot.root.id,
),
if (folder == null) ...[
const SizedBox(height: 8),
SwitchListTile(
contentPadding: EdgeInsets.zero,
title: const Text('Add to top'),
value: addToTop.value,
onChanged: (value) => addToTop.value = value,
),
],
const SizedBox(height: 16),
],
if (folder != null)
SizedBox(
width: double.infinity,
child: OutlinedButton.icon(
style: OutlinedButton.styleFrom(
side: BorderSide(
color: Theme.of(context).colorScheme.error,
),
foregroundColor: Theme.of(context).colorScheme.error,
iconColor: Theme.of(context).colorScheme.error,
),
label: const Text('Delete'),
icon: const Icon(Icons.delete),
onPressed: () async {
final result = await showDeleteFolderDialog(context);
if (result == true) {
await ref
.read(bookmarksRepositoryProvider.notifier)
.delete(folder!.guid);
if (context.mounted) {
context.pop();
}
}
},
),
),
],
),
),
),
),
);
}
}
@@ -0,0 +1,164 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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:animated_tree_view/animated_tree_view.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:flutter_material_design_icons/flutter_material_design_icons.dart';
import 'package:flutter_mozilla_components/flutter_mozilla_components.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:weblibre/core/routing/routes.dart';
import 'package:weblibre/features/geckoview/features/bookmarks/domain/entities/bookmark_item.dart';
import 'package:weblibre/features/geckoview/features/bookmarks/domain/providers/bookmarks.dart';
import 'package:weblibre/presentation/widgets/failure_widget.dart';
/// A widget that displays a tree view of bookmark folders and allows the user
/// to select a parent folder.
///
/// When editing a folder, pass [excludeFolderGuids] to prevent selecting the
/// folders or their descendants as the parent (which would create a circular reference).
class FolderTreePicker extends HookConsumerWidget {
/// The currently selected folder GUID
final ValueNotifier<String> selectedFolderGuid;
/// Optional folder GUIDs to exclude from the tree (along with their descendants).
/// Used when editing/moving folders to prevent circular parent relationships.
final Set<String> excludeFolderGuids;
final String entryGuid;
const FolderTreePicker({
required this.selectedFolderGuid,
required this.entryGuid,
this.excludeFolderGuids = const {},
super.key,
});
@override
Widget build(BuildContext context, WidgetRef ref) {
final treeKey = useMemoized(() => GlobalKey<TreeViewState>());
final folderList = ref.watch(bookmarksProvider<BookmarkFolder>(entryGuid));
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Folder', style: Theme.of(context).textTheme.labelMedium),
folderList.when(
skipLoadingOnReload: true,
data: (list) {
TreeNode<BookmarkFolder> addChildren(
TreeNode<BookmarkFolder>? parent,
BookmarkFolder item,
) {
final node = TreeNode(key: item.guid, data: item, parent: parent);
final targetNode = (parent?..add(node)) ?? node;
if (item.children != null) {
for (final child in item.children!) {
// Skip excluded folders and their descendants
if (child is BookmarkFolder &&
!excludeFolderGuids.contains(child.guid)) {
addChildren(node, child);
}
}
}
return targetNode;
}
final root = (list != null)
? addChildren(null, list)
: TreeNode<BookmarkFolder>.root();
return TreeView.simple(
key: treeKey,
tree: root,
shrinkWrap: true,
showRootNode: entryGuid != BookmarkRoot.root.id,
onTreeReady: (controller) {
controller.expandAllChildren(root, recursive: true);
},
expansionIndicatorBuilder: (context, tree) =>
ChevronIndicator.upDown(
tree: tree,
padding: const EdgeInsets.symmetric(
vertical: 16.0,
horizontal: 12.0,
),
),
builder: (context, item) {
final isSelected = item.data?.guid == selectedFolderGuid.value;
// BookmarkRoot.root cannot be selected as a parent
final isRootFolder = item.data?.guid == BookmarkRoot.root.id;
return Padding(
padding: const EdgeInsets.only(right: 42.0),
child: switch (item.data) {
final BookmarkFolder folder => ListTile(
key: ValueKey(folder.guid),
contentPadding: EdgeInsets.zero,
selected: isSelected,
enabled: !isRootFolder,
leading: (item.isExpanded)
? const Icon(MdiIcons.folderOpen)
: const Icon(MdiIcons.folder),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (isSelected) const Icon(Icons.check),
IconButton(
onPressed: () async {
await BookmarkFolderAddRoute(
parentGuid: folder.guid,
).push(context);
},
icon: const Icon(MdiIcons.folderPlus),
),
],
),
title: Text(folder.title),
onTap: !isRootFolder
? () {
selectedFolderGuid.value = folder.guid;
}
: null,
),
null => const SizedBox.shrink(),
},
);
},
);
},
error: (error, stackTrace) => Center(
child: FailureWidget(
title: 'Failed to load Bookmark Folders',
exception: error,
onRetry: () {
ref.invalidate(bookmarksProvider<BookmarkFolder>(entryGuid));
},
),
),
loading: () => const Center(child: CircularProgressIndicator()),
),
],
);
}
}
@@ -0,0 +1,594 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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:flutter_mozilla_components/flutter_mozilla_components.dart';
import 'package:html/dom.dart' as dom;
import 'package:html/parser.dart' as html_parser;
import 'package:weblibre/core/logger.dart';
const _containerNormal = 0;
const _containerToolbar = 1;
const _containerMenu = 2;
const _containerUnfiled = 3;
const _containerPlaces = 4;
const _exportIndent = ' ';
class _Frame {
final Map<String, dynamic> folder;
int containerNesting = 0;
int lastContainerType = _containerNormal;
String previousText = '';
bool inDescription = false;
String? previousLink;
Map<String, dynamic>? previousItem;
DateTime? previousDateAdded;
DateTime? previousLastModifiedDate;
_Frame(this.folder);
}
class BookmarkHTMLUtils {
final GeckoBookmarksService _service;
BookmarkHTMLUtils(this._service);
/// Import bookmarks from HTML string
Future<int> importFromHTML(String htmlString, {bool replace = false}) async {
final importer = _BookmarkImporter(_service, replace);
return await importer.importFromHTML(htmlString);
}
/// Export bookmarks to HTML string
Future<String> exportToHTML({required BookmarkRoot root}) async {
final tree = await _service.getTree(root.id, recursive: true);
if (tree == null) {
throw Exception('Failed to get bookmarks tree');
}
final exporter = _BookmarkExporter(tree);
return exporter.exportToHTML();
}
}
class _BookmarkImporter {
final GeckoBookmarksService _service;
final bool _isImportDefaults;
final Map<String, dynamic> _bookmarkTree;
final List<_Frame> _frames = [];
_BookmarkImporter(this._service, this._isImportDefaults)
: _bookmarkTree = {
'type': BookmarkNodeType.folder.index,
'guid': BookmarkRoot.menu.id,
'children': <Map<String, dynamic>>[],
} {
_frames.add(_Frame(_bookmarkTree));
}
_Frame get _curFrame => _frames.last;
Future<int> importFromHTML(String htmlString) async {
final document = html_parser.parse(htmlString);
_walkTreeForImport(document.body);
return await _importBookmarks();
}
dom.Node? _nextSibling(dom.Node node) {
final parent = node.parent;
if (parent == null) return null;
final siblings = parent.nodes;
final index = siblings.indexOf(node);
if (index != -1 && index + 1 < siblings.length) {
return siblings[index + 1];
}
return null;
}
void _walkTreeForImport(dom.Node? node) {
if (node == null) return;
dom.Node? current = node;
dom.Node? next;
for (;;) {
if (current?.nodeType == dom.Node.ELEMENT_NODE) {
_openContainer(current! as dom.Element);
} else if (current?.nodeType == dom.Node.TEXT_NODE) {
_appendText(current!.text ?? '');
}
if ((next = current?.firstChild) != null) {
current = next;
continue;
}
for (;;) {
if (current?.nodeType == dom.Node.ELEMENT_NODE) {
_closeContainer(current! as dom.Element);
}
if (current == node) return;
if ((next = _nextSibling(current!)) != null) {
current = next;
break;
}
current = current.parentNode;
}
}
}
void _openContainer(dom.Element element) {
switch (element.localName) {
case 'h2':
case 'h3':
case 'h4':
case 'h5':
case 'h6':
_handleHeadBegin(element);
case 'a':
_handleLinkBegin(element);
case 'dl':
case 'ul':
case 'menu':
_handleContainerBegin();
case 'dd':
_curFrame.inDescription = true;
case 'hr':
_handleSeparator();
}
}
void _closeContainer(dom.Element element) {
final frame = _curFrame;
if (frame.inDescription) {
frame.previousText = '';
frame.inDescription = false;
}
switch (element.localName) {
case 'dl':
case 'ul':
case 'menu':
_handleContainerEnd();
case 'h2':
case 'h3':
case 'h4':
case 'h5':
case 'h6':
_handleHeadEnd();
case 'a':
_handleLinkEnd();
}
}
void _appendText(String str) {
_curFrame.previousText += str;
}
void _handleHeadBegin(dom.Element element) {
final frame = _curFrame;
frame.previousLink = null;
frame.lastContainerType = _containerNormal;
if (frame.containerNesting == 0 && _frames.length > 1) {
_frames.removeLast();
}
if (element.attributes.containsKey('personal_toolbar_folder')) {
if (_isImportDefaults) {
frame.lastContainerType = _containerToolbar;
}
} else if (element.attributes.containsKey('bookmarks_menu')) {
if (_isImportDefaults) {
frame.lastContainerType = _containerMenu;
}
} else if (element.attributes.containsKey('unfiled_bookmarks_folder')) {
if (_isImportDefaults) {
frame.lastContainerType = _containerUnfiled;
}
} else if (element.attributes.containsKey('places_root')) {
if (_isImportDefaults) {
frame.lastContainerType = _containerPlaces;
}
} else {
final addDate = element.attributes['add_date'];
if (addDate != null) {
frame.previousDateAdded = _convertImportedDateToInternalDate(addDate);
}
final modDate = element.attributes['last_modified'];
if (modDate != null) {
frame.previousLastModifiedDate = _convertImportedDateToInternalDate(
modDate,
);
}
}
_curFrame.previousText = '';
}
void _handleLinkBegin(dom.Element element) {
final frame = _curFrame;
frame.previousItem = null;
frame.previousText = '';
final href = element.attributes['href']?.trim();
final dateAdded = element.attributes['add_date']?.trim();
final lastModified = element.attributes['last_modified']?.trim();
final tags = element.attributes['tags']?.trim();
final keyword = element.attributes['shortcuturl']?.trim();
final postData = element.attributes['post_data']?.trim();
final lastCharset = element.attributes['last_charset']?.trim();
if (href == null || href.isEmpty) {
frame.previousLink = null;
return;
}
try {
final uri = Uri.parse(href);
if (!uri.hasScheme) {
frame.previousLink = null;
return;
}
frame.previousLink = uri.toString();
} catch (e) {
frame.previousLink = null;
return;
}
final bookmark = <String, dynamic>{'url': frame.previousLink};
if (dateAdded != null) {
bookmark['dateAdded'] = _convertImportedDateToInternalDate(
dateAdded,
).millisecondsSinceEpoch;
}
if (lastModified != null) {
bookmark['lastModified'] = _convertImportedDateToInternalDate(
lastModified,
).millisecondsSinceEpoch;
}
if (dateAdded == null && lastModified != null) {
bookmark['dateAdded'] = bookmark['lastModified'];
}
if (tags != null && tags.isNotEmpty) {
bookmark['tags'] = tags;
}
if (keyword != null && keyword.isNotEmpty) {
bookmark['keyword'] = keyword;
}
if (postData != null && postData.isNotEmpty) {
bookmark['postData'] = postData;
}
if (lastCharset != null && lastCharset.isNotEmpty) {
bookmark['charset'] = lastCharset;
}
(frame.folder['children'] as List).add(bookmark);
frame.previousItem = bookmark;
}
void _handleContainerBegin() {
_curFrame.containerNesting++;
}
void _handleContainerEnd() {
final frame = _curFrame;
if (frame.containerNesting > 0) {
frame.containerNesting--;
}
if (_frames.length > 1 && frame.containerNesting == 0) {
_frames.removeLast();
}
}
void _handleHeadEnd() {
_newFrame();
}
void _handleLinkEnd() {
final frame = _curFrame;
frame.previousText = frame.previousText.trim();
if (frame.previousItem != null) {
frame.previousItem!['title'] = frame.previousText;
}
frame.previousText = '';
}
void _handleSeparator() {
final frame = _curFrame;
final separator = <String, dynamic>{
'type': BookmarkNodeType.separator.index,
};
(frame.folder['children'] as List).add(separator);
frame.previousItem = separator;
}
void _newFrame() {
final frame = _curFrame;
final containerTitle = frame.previousText;
frame.previousText = '';
final containerType = frame.lastContainerType;
final folder = <String, dynamic>{
'children': <Map<String, dynamic>>[],
'type': BookmarkNodeType.folder.index,
};
switch (containerType) {
case _containerNormal:
folder['title'] = containerTitle;
case _containerPlaces:
folder['guid'] = BookmarkRoot.root.id;
case _containerMenu:
folder['guid'] = BookmarkRoot.menu.id;
case _containerUnfiled:
folder['guid'] = BookmarkRoot.unfiled.id;
case _containerToolbar:
folder['guid'] = BookmarkRoot.toolbar.id;
}
(frame.folder['children'] as List).add(folder);
if (frame.previousDateAdded != null) {
folder['dateAdded'] = frame.previousDateAdded!.millisecondsSinceEpoch;
frame.previousDateAdded = null;
}
if (frame.previousLastModifiedDate != null) {
folder['lastModified'] =
frame.previousLastModifiedDate!.millisecondsSinceEpoch;
frame.previousLastModifiedDate = null;
}
if (!folder.containsKey('dateAdded') &&
folder.containsKey('lastModified')) {
folder['dateAdded'] = folder['lastModified'];
}
frame.previousItem = folder;
_frames.add(_Frame(folder));
}
DateTime _convertImportedDateToInternalDate(String seconds) {
try {
final parsed = int.tryParse(seconds);
if (parsed != null) {
return DateTime.fromMillisecondsSinceEpoch(parsed * 1000);
}
} catch (e) {
// Fall through
}
return DateTime.now();
}
List<Map<String, dynamic>> _getBookmarkTrees() {
if (!_isImportDefaults) {
return [_bookmarkTree];
}
final bookmarkTrees = <Map<String, dynamic>>[_bookmarkTree];
final children = _bookmarkTree['children'] as List<Map<String, dynamic>>;
_bookmarkTree['children'] = children.where((child) {
final guid = child['guid'] as String?;
if (guid != null && bookmarkRootIds.contains(guid)) {
bookmarkTrees.add(child);
return false;
}
return true;
}).toList();
return bookmarkTrees;
}
Future<int> _importBookmarks() async {
if (_isImportDefaults) {
// Delete bookmarks from each root folder (except root itself to avoid errors)
for (final root in BookmarkRoot.values) {
if (root != BookmarkRoot.root) {
await _service.eraseEverything(root);
}
}
}
final bookmarkTrees = _getBookmarkTrees();
int bookmarkCount = 0;
for (final tree in bookmarkTrees) {
final children = tree['children'] as List?;
if (children == null || children.isEmpty) continue;
bookmarkCount += await _insertTree(tree);
}
return bookmarkCount;
}
Future<int> _insertTree(Map<String, dynamic> node) async {
int count = 0;
final children = node['children'] as List?;
if (children == null || children.isEmpty) return 0;
final parentGuid = node['guid'] as String;
for (int i = 0; i < children.length; i++) {
final child = children[i] as Map<String, dynamic>;
final type = child['type'] as int? ?? BookmarkNodeType.item.index;
if (type == BookmarkNodeType.item.index) {
final url = child['url'] as String?;
final title = child['title'] as String? ?? '';
if (url != null && url.isNotEmpty) {
try {
final uri = Uri.parse(url);
if (uri.hasScheme) {
await _service.addItem(parentGuid, uri, title, i);
count++;
}
} catch (e) {
logger.e('Failed to import bookmark "$title": $e');
}
}
} else if (type == BookmarkNodeType.folder.index) {
final title = child['title'] as String? ?? '';
try {
final newGuid = await _service.addFolder(parentGuid, title, i);
child['guid'] = newGuid;
count += await _insertTree(child);
} catch (e) {
logger.e('Failed to import folder "$title": $e');
}
}
}
return count;
}
}
class _BookmarkExporter {
final BookmarkNode _root;
final StringBuffer _buffer = StringBuffer();
_BookmarkExporter(this._root);
String exportToHTML() {
_writeHeader();
_writeContainer(_root);
return _buffer.toString();
}
void _write(String text) {
_buffer.write(text);
}
void _writeLine(String text) {
_buffer.writeln(text);
}
void _writeHeader() {
_writeLine('<!DOCTYPE NETSCAPE-Bookmark-file-1>');
_writeLine('<!-- This is an automatically generated file.');
_writeLine(' It will be read and overwritten.');
_writeLine(' DO NOT EDIT! -->');
_writeLine(
'<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">',
);
_writeLine('<meta http-equiv="Content-Security-Policy"');
_writeLine(
' content="default-src \'self\'; script-src \'none\'; img-src data: *; object-src \'none\'"></meta>',
);
_writeLine('<TITLE>Bookmarks</TITLE>');
}
void _writeContainer(BookmarkNode item, [String indent = '']) {
if (item.guid == _root.guid) {
_writeLine('<H1>${_escapeHtml(item.title ?? 'Bookmarks')}</H1>');
_writeLine('');
} else {
_write('$indent<DT><H3');
_writeDateAttributes(item);
if (item.guid == BookmarkRoot.toolbar.id) {
_write(' PERSONAL_TOOLBAR_FOLDER="true"');
} else if (item.guid == BookmarkRoot.unfiled.id) {
_write(' UNFILED_BOOKMARKS_FOLDER="true"');
}
_writeLine('>${_escapeHtml(item.title ?? '')}</H3>');
}
_writeLine('$indent<DL><p>');
if (item.children != null) {
_writeContainerContents(item, indent);
}
if (item.guid == _root.guid) {
_writeLine('$indent</DL>');
} else {
_writeLine('$indent</DL><p>');
}
}
void _writeContainerContents(BookmarkNode item, String indent) {
final localIndent = indent + _exportIndent;
for (final child in item.children!) {
if (child.type == BookmarkNodeType.folder) {
_writeContainer(child, localIndent);
} else if (child.type == BookmarkNodeType.separator) {
_writeSeparator(child, localIndent);
} else {
_writeItem(child, localIndent);
}
}
}
void _writeSeparator(BookmarkNode item, String indent) {
_write('$indent<HR');
if (item.title != null && item.title!.isNotEmpty) {
_write(' NAME="${_escapeHtml(item.title!)}"');
}
_writeLine('>');
}
void _writeItem(BookmarkNode item, String indent) {
if (item.url == null || item.url!.isEmpty) return;
try {
Uri.parse(item.url!);
} catch (e) {
return;
}
_write('$indent<DT><A HREF="${_escapeUrl(item.url!)}"');
_writeDateAttributes(item);
_writeLine('>${_escapeHtml(item.title ?? '')}</A>');
}
void _writeDateAttributes(BookmarkNode item) {
// Convert from microseconds to seconds (UNIX timestamp)
if (item.dateAdded > 0) {
_write(' ADD_DATE="${item.dateAdded ~/ 1000000}"');
}
if (item.lastModified > 0) {
_write(' LAST_MODIFIED="${item.lastModified ~/ 1000000}"');
}
}
String _escapeHtml(String text) {
return text
.replaceAll('&', '&amp;')
.replaceAll('<', '&lt;')
.replaceAll('>', '&gt;')
.replaceAll('"', '&quot;')
.replaceAll("'", '&#39;');
}
String _escapeUrl(String text) {
return text.replaceAll('"', '%22');
}
}
@@ -0,0 +1,376 @@
/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* 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/>.
*/
// ignore_for_file: unnecessary_raw_strings
import 'dart:convert';
import 'package:flutter_mozilla_components/flutter_mozilla_components.dart';
import 'package:weblibre/core/logger.dart';
import 'package:weblibre/utils/uri_input_parser.dart';
class BookmarkJSONUtils {
final GeckoBookmarksService _service;
BookmarkJSONUtils(this._service);
/// Import bookmarks from JSON string
Future<int> importFromJSON(String jsonString, {bool replace = false}) async {
try {
final data = jsonDecode(jsonString);
if (data is! Map<String, dynamic>) {
throw Exception('Invalid JSON format');
}
final children = data['children'] as List?;
if (children == null || children.isEmpty) {
return 0;
}
return await _import(data, replace: replace);
} catch (ex) {
logger.e('Failed to import bookmarks: $ex');
rethrow;
}
}
/// Export bookmarks to JSON
Future<Map<String, dynamic>?> exportToJson({
required BookmarkRoot root,
}) async {
final tree = await _service.getTree(root.id, recursive: true);
if (tree == null) {
throw Exception('Failed to get bookmarks tree');
}
return _nodeToJson(tree, isRoot: true);
}
/// Import implementation
Future<int> _import(
Map<String, dynamic> rootNode, {
required bool replace,
}) async {
final nodes =
(rootNode['children'] as List?)
?.whereType<Map<String, dynamic>>()
.where(
(node) =>
node['root'] != 'tagsFolder' &&
node['guid'] != 'tags________',
)
.toList() ??
[];
if (nodes.isEmpty) {
return 0;
}
// If replacing, erase existing bookmarks first
if (replace) {
// Delete bookmarks from each root folder (except root itself to avoid errors)
for (final root in BookmarkRoot.values) {
if (root != BookmarkRoot.root) {
await _service.eraseEverything(root);
}
}
}
final folderIdToGuidMap = <String, String>{};
// Translate tree types and build folder map
for (final node in nodes) {
if (node['children'] == null || (node['children'] as List).isEmpty) {
continue;
}
final folders = _translateTreeTypes(node);
folderIdToGuidMap.addAll(folders);
}
int bookmarkCount = 0;
// Insert nodes
for (final node in nodes) {
if (node['children'] == null || (node['children'] as List).isEmpty) {
continue;
}
final guid = node['guid'] as String?;
if (guid == null || !bookmarkRootIds.contains(guid)) {
continue;
}
_fixupSearchQueries(node, folderIdToGuidMap);
// Insert the tree recursively
bookmarkCount += await _insertTree(node, folderIdToGuidMap);
}
return bookmarkCount;
}
/// Recursively insert bookmark tree
Future<int> _insertTree(
Map<String, dynamic> node,
Map<String, String> folderIdToGuidMap,
) async {
int count = 0;
final children = node['children'] as List?;
if (children == null || children.isEmpty) {
return 0;
}
final parentGuid = node['guid'] as String;
for (int i = 0; i < children.length; i++) {
final child = children[i] as Map<String, dynamic>;
final type = _getNodeType(child);
if (type == BookmarkNodeType.item) {
final url = _getNodeUrl(child);
final title = child['title'] as String? ?? '';
if (url != null && url.isNotEmpty) {
try {
// Validate URL before inserting
final uri = Uri.tryParse(url);
if (uri != null && uri.hasScheme) {
await _service.addItem(parentGuid, uri, title, i);
count++;
} else {
final parsed = Uri.tryParse(url);
final redacted = parsed != null
? redactUriCredentials(parsed)
: url;
logger.w('Skipping invalid URL: $redacted');
}
} catch (e) {
logger.e('Failed to import bookmark "$title": $e');
}
}
} else if (type == BookmarkNodeType.folder) {
final title = child['title'] as String? ?? '';
try {
final newGuid = await _service.addFolder(parentGuid, title, i);
child['guid'] = newGuid;
// Recursively insert children
count += await _insertTree(child, folderIdToGuidMap);
} catch (e) {
logger.e('Failed to import folder "$title": $e');
}
}
// Note: Separators are not supported by the Android API
}
return count;
}
/// Translate tree types from JSON format to internal format
Map<String, String> _translateTreeTypes(Map<String, dynamic> node) {
final folderIdToGuidMap = <String, String>{};
_normalizeNodeUrl(node);
final type = node['type'];
if (type == 'text/x-moz-place-container') {
node['type'] = BookmarkNodeType.folder.index;
final id = node['id']?.toString();
final guid = node['guid'] as String?;
if (id != null && guid != null) {
folderIdToGuidMap[id] = guid;
}
} else if (type == 'text/x-moz-place') {
node['type'] = BookmarkNodeType.item.index;
} else if (type == 'text/x-moz-place-separator') {
node['type'] = BookmarkNodeType.separator.index;
node.remove('title');
}
final children = node['children'] as List?;
if (children != null) {
for (final child in children) {
if (child is Map<String, dynamic>) {
folderIdToGuidMap.addAll(_translateTreeTypes(child));
}
}
}
return folderIdToGuidMap;
}
/// Fix up search queries with folder mappings
void _fixupSearchQueries(
Map<String, dynamic> node,
Map<String, String> folderIdToGuidMap,
) {
final url = _getNodeUrl(node);
if (url != null && url.startsWith('place:')) {
node['url'] = _fixupQuery(url, folderIdToGuidMap);
}
final children = node['children'] as List?;
if (children != null) {
for (final child in children) {
if (child is Map<String, dynamic>) {
_fixupSearchQueries(child, folderIdToGuidMap);
}
}
}
}
/// Replace folder IDs with GUIDs in place: URIs
String _fixupQuery(String queryURL, Map<String, String> folderIdToGuidMap) {
final regex = RegExp(r'folder=([A-Za-z0-9_]+)');
bool invalid = false;
final result = queryURL.replaceAllMapped(regex, (match) {
final folderId = match.group(1)!;
final guid = folderIdToGuidMap[folderId];
if (guid == null) {
invalid = true;
return 'invalidOldParentId=$folderId';
}
return 'parent=$guid';
});
if (invalid) {
return '$result&excludeItems=1';
}
return result;
}
/// Convert BookmarkNode to JSON (for export)
Map<String, dynamic>? _nodeToJson(BookmarkNode node, {bool isRoot = false}) {
// Skip invalid bookmarks
if (node.type == BookmarkNodeType.item) {
if (node.url == null || node.url!.isEmpty) {
logger.w('Skipping bookmark with invalid URL: ${node.guid}');
return null;
}
try {
Uri.parse(node.url!);
} catch (e) {
logger.w('Skipping bookmark with malformed URL: ${node.url}');
return null;
}
}
final json = <String, dynamic>{
'guid': node.guid,
'title': node.type == BookmarkNodeType.separator
? ''
: (node.title ?? ''),
'index': 0, // Will be set by parent
'dateAdded': node.dateAdded,
'lastModified': node.lastModified,
'typeCode': node.type.index + 1,
'type': _getTypeString(node.type),
};
if (isRoot &&
node.parentGuid != null &&
node.guid != BookmarkRoot.root.id) {
json['parentGuid'] = node.parentGuid;
}
final rootName = _getRootName(node.guid);
if (rootName != null) {
json['root'] = rootName;
}
if (node.type == BookmarkNodeType.item) {
json['url'] = node.url;
}
if (node.type == BookmarkNodeType.folder && node.children != null) {
final validChildren = <Map<String, dynamic>>[];
for (var i = 0; i < node.children!.length; i++) {
final childJson = _nodeToJson(node.children![i]);
if (childJson != null) {
childJson['index'] = validChildren.length;
validChildren.add(childJson);
}
}
if (validChildren.isNotEmpty) {
json['children'] = validChildren;
}
}
return json;
}
/// Convert BookmarkNodeType to Firefox type string
String _getTypeString(BookmarkNodeType type) {
switch (type) {
case BookmarkNodeType.item:
return 'text/x-moz-place';
case BookmarkNodeType.folder:
return 'text/x-moz-place-container';
case BookmarkNodeType.separator:
return 'text/x-moz-place-separator';
}
}
/// Get root folder name for JSON
String? _getRootName(String guid) {
if (guid == BookmarkRoot.root.id) return 'placesRoot';
if (guid == BookmarkRoot.menu.id) return 'bookmarksMenuFolder';
if (guid == BookmarkRoot.toolbar.id) return 'toolbarFolder';
if (guid == BookmarkRoot.unfiled.id) return 'unfiledBookmarksFolder';
if (guid == BookmarkRoot.mobile.id) return 'mobileFolder';
return null;
}
/// Get URL from node (accepts both 'url' and 'uri')
String? _getNodeUrl(Map<String, dynamic> node) {
return node['url'] as String? ?? node['uri'] as String?;
}
/// Normalize 'uri' to 'url' during import
void _normalizeNodeUrl(Map<String, dynamic> node) {
if (node.containsKey('uri')) {
node['url'] = node['uri'];
node.remove('uri');
}
}
/// Get node type from JSON
BookmarkNodeType _getNodeType(Map<String, dynamic> node) {
final type = node['type'];
if (type is int) {
return BookmarkNodeType.values[type];
}
if (type == 'text/x-moz-place-container') {
return BookmarkNodeType.folder;
} else if (type == 'text/x-moz-place') {
return BookmarkNodeType.item;
} else {
return BookmarkNodeType.separator;
}
}
}
Loaded 100 of 904 files, more files were not shown because too many files have changed in this diff. Show more