diff --git a/.codex/config.toml b/.codex/config.toml new file mode 100644 index 0000000..384ee6d --- /dev/null +++ b/.codex/config.toml @@ -0,0 +1,7 @@ +[mcp_servers.serverpod] +command = "serverpod" +args = ["mcp-server", "--server-dir", "test/serverpod_offline_sync_test_server"] + +[mcp_servers.dart_mcp] +command = "dart" +args = ["mcp-server", "--force-roots-fallback"] diff --git a/.cursor/skills/mcp.json b/.cursor/skills/mcp.json new file mode 100644 index 0000000..1e9b2d8 --- /dev/null +++ b/.cursor/skills/mcp.json @@ -0,0 +1,12 @@ +{ + "mcpServers": { + "serverpod": { + "command": "serverpod", + "args": ["mcp-server", "--server-dir", "test/serverpod_offline_sync_test_server"] + }, + "dart": { + "command": "dart", + "args": ["mcp-server"] + } + } +} diff --git a/.mcp.json b/.mcp.json new file mode 100644 index 0000000..fd65591 --- /dev/null +++ b/.mcp.json @@ -0,0 +1,18 @@ +{ + "mcpServers": { + "serverpod": { + "command": "serverpod", + "args": [ + "mcp-server", + "--server-dir", + "test/serverpod_offline_sync_test_server" + ] + }, + "dart": { + "command": "dart", + "args": [ + "mcp-server" + ] + } + } +} diff --git a/example/offline_sync_demo/.gitignore b/example/offline_sync_demo/.gitignore new file mode 100644 index 0000000..3820a95 --- /dev/null +++ b/example/offline_sync_demo/.gitignore @@ -0,0 +1,45 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ +/coverage/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/example/offline_sync_demo/.metadata b/example/offline_sync_demo/.metadata new file mode 100644 index 0000000..e836225 --- /dev/null +++ b/example/offline_sync_demo/.metadata @@ -0,0 +1,39 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "ff37bef603469fb030f2b72995ab929ccfc227f0" + channel: "stable" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: ff37bef603469fb030f2b72995ab929ccfc227f0 + base_revision: ff37bef603469fb030f2b72995ab929ccfc227f0 + - platform: linux + create_revision: ff37bef603469fb030f2b72995ab929ccfc227f0 + base_revision: ff37bef603469fb030f2b72995ab929ccfc227f0 + - platform: macos + create_revision: ff37bef603469fb030f2b72995ab929ccfc227f0 + base_revision: ff37bef603469fb030f2b72995ab929ccfc227f0 + - platform: web + create_revision: ff37bef603469fb030f2b72995ab929ccfc227f0 + base_revision: ff37bef603469fb030f2b72995ab929ccfc227f0 + - platform: windows + create_revision: ff37bef603469fb030f2b72995ab929ccfc227f0 + base_revision: ff37bef603469fb030f2b72995ab929ccfc227f0 + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/example/offline_sync_demo/README.md b/example/offline_sync_demo/README.md new file mode 100644 index 0000000..fb7ceb4 --- /dev/null +++ b/example/offline_sync_demo/README.md @@ -0,0 +1,98 @@ +# Offline Sync Demo + +Desktop Flutter demo for `serverpod_offline_sync`. It runs two independent local +replicas of one user's data side by side, plus a view of the server's merged +truth, so you can drive `A → server` and `B → server` independently and watch +them converge. + +## How the package is wired + +If you are here to learn the package, read **`lib/src/offline_replica.dart`** +first — it is the entire integration in ~60 lines, deliberately free of demo and +UI code. Every replica follows the same four steps: + +1. **Open a local database.** `client.createSession(path)` opens a Serverpod + client database (a local SQLite file) and runs the client migrations. +2. **Wrap it for CRDT sync.** `CrdtDatabaseSession.wraps(raw, syncTables: …, + persistentUserId: …)`, then `crdtSession.db.initialize()` to establish this + device's CRDT node so it can take part in sync. +3. **Read and write generated models** against that session, e.g. + `Person.db.insertRow(session, person)` or `session.db.find()`. (The + demo also routes these through a generic `TableOps` registry so its + metadata-driven UI can touch any table without a per-type switch — that part + is demo-only; the `seed*` methods in `lib/src/demo_controller.dart` show the + plain form.) +4. **Synchronize through a Serverpod client.** + `client.crdt.syncOnce(session, onMergeSuccess: …)` for a one-shot push/pull, + or `client.crdt.syncContinuously(session, …)` to stream until cancelled. + +Connectivity is just *which client you sync through*: the demo swaps +`Client.httpClientOverride` between a real transport and a failing one to +simulate going offline — the local database is untouched either way. + +The rest of `lib/src` layers a UI on top: `demo_controller.dart` (a +`ChangeNotifier` orchestrating users, replicas, and the server panel), +`snapshot.dart` / `relationships.dart` / `table_ops.dart` (the metadata-driven +view of the synced schema), `demo_view.dart` / `sheets.dart` (widgets), and +`scenarios.dart` (guided scripts). + +## What the UI shows + +Each demo user owns two replicas (`-a.db`, `-b.db`) shown side by +side. A replica is a local SQLite store with its own CRDT node id but the same +sync scope; replicas share nothing locally and only converge by syncing through +the server — like two phones on one account (see the "i" button in the toolbar). + +The layout is a **scenario rail**, **Replica A**, **Replica B**, and a **Server** +panel, with a global toolbar on top and a status line at the bottom. + +**Toolbar** + +- **Connectivity** toggles every client between a real and a failing HTTP + transport (the offline switch). +- **Show hidden rows** reveals locally hidden / soft-deleted (tombstoned) rows, + shown struck-through and muted alongside the visible "user view". +- **Refresh** reloads all three panels; **Reset all** wipes both replicas and the + server scope at once. +- The **i** button explains replica isolation. +- The app bar carries a light/dark toggle and an avatar menu for switching + between or creating demo users. + +**Per replica** + +- **Sync** runs one push/pull; **Stream** keeps syncing continuously until + toggled off — drive A and B independently and watch them (and the Server + panel) converge. +- **Add data** creates a root row or attaches a child through a foreign key; the + same menu also offers ready-made seeds (a city/person/address/town graph, a + typed row, an FK chain). Each row carries inline **attach child** and + **re-parent / detach** actions, and every edge shows its `onDelete` action + (restrict / cascade / set null / …). +- **Reset** wipes just that replica's local database (a fresh device); syncing + afterwards re-pulls whatever the server still holds. +- Click any row to open its full record, edit fields, or delete it. + +**Server panel** + +- Shows the server's merged truth for the current scope, fetched through the + `demoDebug.fetchScopeSnapshot` endpoint (reads run in the caller's scope via + `transactionForUser`). It refreshes after each sync and via its own refresh + button. +- **Reset server scope** hard-clears every row and CRDT metadata record in the + scope; the seed buttons write a graph straight into the scope via + `demoDebug.seedScope`, so you can reset a replica and sync to exercise the + fetch-from-scratch flow. + +**Scenario rail** + +- Guided scripts (restrict, set-null, cascade, unique-conflict, …) that run a + sequence of these same actions step by step. Every step is also doable by hand. + +## Running + +Simply run the serverpod server and the app will be started together: + +```sh +cd test/serverpod_offline_sync_test_server +serverpod start +``` diff --git a/example/offline_sync_demo/analysis_options.yaml b/example/offline_sync_demo/analysis_options.yaml new file mode 100644 index 0000000..0bd999b --- /dev/null +++ b/example/offline_sync_demo/analysis_options.yaml @@ -0,0 +1,4 @@ +include: package:flutter_lints/flutter.yaml + +linter: + rules: diff --git a/example/offline_sync_demo/lib/main.dart b/example/offline_sync_demo/lib/main.dart new file mode 100644 index 0000000..eac080c --- /dev/null +++ b/example/offline_sync_demo/lib/main.dart @@ -0,0 +1,104 @@ +import 'dart:async'; + +import 'package:flutter_driver/driver_extension.dart'; +import 'package:shadcn_flutter/shadcn_flutter.dart'; + +import 'src/demo_controller.dart'; +import 'src/demo_view.dart'; + +const _defaultServerUrl = String.fromEnvironment( + 'SERVERPOD_URL', + defaultValue: 'http://localhost:8080/', +); + +const _lightDemoColorScheme = ColorSchemes.lightNeutral; +const _darkDemoColorScheme = ColorSchemes.darkNeutral; + +ThemeData _demoTheme(ColorScheme colorScheme) { + return ThemeData(colorScheme: colorScheme, radius: 0.5); +} + +void main() { + enableFlutterDriverExtension(enableTextEntryEmulation: false); + runApp(const DemoRoot()); +} + +/// Hosts the [ShadcnApp] and owns the light/dark theme selection. +class DemoRoot extends StatefulWidget { + const DemoRoot({super.key}); + + @override + State createState() => _DemoRootState(); +} + +class _DemoRootState extends State { + bool _isDark = true; + + void _toggleTheme() => setState(() => _isDark = !_isDark); + + @override + Widget build(BuildContext context) { + return ShadcnApp( + title: 'Offline Sync Demo', + theme: _demoTheme(_lightDemoColorScheme), + darkTheme: _demoTheme(_darkDemoColorScheme), + themeMode: _isDark ? ThemeMode.dark : ThemeMode.light, + debugShowCheckedModeBanner: false, + home: DemoHome(isDark: _isDark, onToggleTheme: _toggleTheme), + ); + } +} + +/// The main screen: builds the controller and the dashboard scaffold. +class DemoHome extends StatefulWidget { + const DemoHome({ + super.key, + required this.isDark, + required this.onToggleTheme, + }); + + final bool isDark; + final VoidCallback onToggleTheme; + + @override + State createState() => _DemoHomeState(); +} + +class _DemoHomeState extends State { + late final DemoController controller; + + @override + void initState() { + super.initState(); + controller = DemoController(serverUrl: _defaultServerUrl); + unawaited(controller.initialize()); + } + + @override + void dispose() { + controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + headers: [ + AppBar( + title: const Text('Serverpod Offline Sync Demo'), + subtitle: const Text(_defaultServerUrl), + trailing: [ + ThemeToggleButton( + isDark: widget.isDark, + onToggle: widget.onToggleTheme, + ), + const Gap(8), + UserAvatarMenu(controller: controller), + ], + ), + const Divider(), + ], + child: DemoDashboard(controller: controller), + ); + } +} diff --git a/example/offline_sync_demo/lib/src/demo_controller.dart b/example/offline_sync_demo/lib/src/demo_controller.dart new file mode 100644 index 0000000..f0843a5 --- /dev/null +++ b/example/offline_sync_demo/lib/src/demo_controller.dart @@ -0,0 +1,1347 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:flutter/foundation.dart'; +import 'package:path/path.dart' as p; +import 'package:path_provider/path_provider.dart'; +import 'package:serverpod_database/serverpod_database.dart' + show ColumnDefinition, ColumnType, TableDefinition, TableRow; +import 'package:serverpod_offline_sync_client/serverpod_offline_sync_client.dart' + as offline; +import 'package:serverpod_offline_sync_test_client/serverpod_offline_sync_test_client.dart' + as protocol; + +import 'models.dart'; +import 'offline_replica.dart'; +import 'relationships.dart'; +import 'snapshot.dart'; +import 'table_ops.dart'; + +part 'scenarios.dart'; + +/// Lifecycle state of a replica's sync transport. +enum SyncPhase { + offline('Offline'), + idle('Idle'), + syncing('Syncing once'), + streaming('Streaming'), + failed('Failed'); + + const SyncPhase(this.label); + + final String label; +} + +/// A candidate parent row, offered by the re-parent picker. +class ParentOption { + ParentOption({required this.ref, required this.label, required this.visible}); + + final DemoRowRef ref; + final String label; + final bool visible; +} + +/// Per-replica view and sync state held side by side by [DemoController]. +class ReplicaState extends ChangeNotifier { + ReplicaState(this.slot); + + final ReplicaSlot slot; + OfflineReplica? session; + DemoSnapshot? snapshot; + DemoProjection projection = DemoProjection.empty(); + SyncPhase phase = SyncPhase.idle; + String? lastSyncedLabel; + String? error; + offline.CrdtSyncSession? stream; + bool busy = false; + bool _disposed = false; + + bool get streaming => stream != null; + + void changed() { + if (_disposed) return; + notifyListeners(); + } + + @override + void dispose() { + _disposed = true; + super.dispose(); + } +} + +/// State of the "Server" panel that mirrors the merged server truth. +class ServerPanelState extends ChangeNotifier { + DemoProjection projection = DemoProjection.empty(); + bool loading = false; + bool busy = false; + String? error; + String? lastFetchedLabel; + bool _disposed = false; + + void changed() { + if (_disposed) return; + notifyListeners(); + } + + @override + void dispose() { + _disposed = true; + super.dispose(); + } +} + +/// Drives the whole demo: users, replicas, connectivity, sync, and editing. +class DemoController extends ChangeNotifier { + DemoController({required this.serverUrl}); + + final String serverUrl; + final authKeyProvider = DemoAuthKeyProvider(); + + late final RelationshipCatalog catalog = RelationshipCatalog.build({ + for (final table in demoSyncTables) table.tableName, + }); + + final users = []; + final replicas = { + ReplicaSlot.a: ReplicaState(ReplicaSlot.a), + ReplicaSlot.b: ReplicaState(ReplicaSlot.b), + }; + final server = ServerPanelState(); + final _sessions = {}; + final _counter = ScenarioCounter(); + + protocol.Client? _client; + DemoUser? selectedUser; + + bool online = true; + bool showHidden = true; + bool busy = false; + + /// True until the first [initialize] finishes opening the local databases. + /// While set, the replica and server panels show a loading indicator. + bool initializing = true; + String status = 'Opening local demo databases...'; + bool _disposed = false; + + // Active guided scenario, if any. + Scenario? activeScenario; + List _activeSteps = const []; + int scenarioStepIndex = 0; + bool scenarioAutoPlaying = false; + Timer? _scenarioAutoPlayTimer; + + static const _scenarioAutoPlayDelay = Duration(milliseconds: 500); + + bool get anyBusy => + busy || server.busy || replicas.values.any((state) => state.busy); + + /// Static explanation shown by the replica-isolation info button. + String get replicaIsolationMessage { + final user = selectedUser?.username ?? ''; + return 'Replica A and B are independent local SQLite stores ' + '($user-a.db, $user-b.db), each with its own CRDT node id but the ' + 'same sync scope. They share nothing locally and only exchange data ' + 'by syncing through the server — exactly like two phones on one ' + 'account.'; + } + + protocol.Client get client => _client ??= _createClient(); + + ReplicaState replica(ReplicaSlot slot) => replicas[slot]!; + + bool replicaBusy(ReplicaSlot slot) => busy || replicas[slot]!.busy; + + /// Visible rows of [parentTable] on [slot], offered as re-parent targets. + List parentOptions(ReplicaSlot slot, String parentTable) { + final snapshot = replicas[slot]!.snapshot; + if (snapshot == null) return const []; + return [ + for (final row in snapshot.rows) + if (row.table == parentTable && (row.visible || showHidden)) + ParentOption( + ref: DemoRowRef(tableName: row.table, id: row.id), + label: catalog.displayLabel(row.model), + visible: row.visible, + ), + ]; + } + + // --- Lifecycle ---------------------------------------------------------- + + Future initialize() async { + await _run('Opened local demo databases.', () async { + final alice = _localUser('alice'); + final bob = _localUser('bob'); + users + ..add(alice) + ..add(bob); + selectedUser = alice; + authKeyProvider.token = alice.token; + await _openSessionsFor(alice); + _resetReplicaPhases(); + await _refreshReplicas(notify: false); + unawaited(_ensureRemoteAuth(alice)); + }); + initializing = false; + notifyListeners(); + } + + @override + void dispose() { + _disposed = true; + stopScenarioAutoPlay(); + unawaited(_stopAllStreams()); + for (final replica in _sessions.values) { + unawaited(replica.close()); + } + for (final state in replicas.values) { + state.dispose(); + } + server.dispose(); + super.dispose(); + } + + @override + void notifyListeners() { + if (_disposed) return; + super.notifyListeners(); + } + + // --- Users -------------------------------------------------------------- + + Future createOrSwitchUser(String username) async { + final normalized = normalizeUsername(username); + if (normalized.isEmpty) return; + + var user = _findUser(normalized); + user ??= _localUser(normalized); + if (!users.contains(user)) users.add(user); + + await switchUser(user); + } + + Future switchUser(DemoUser user) async { + if (identical(user, selectedUser)) return; + await _run('Switched to ${user.username}.', () async { + await _stopAllStreams(); + stopScenario(); + selectedUser = user; + authKeyProvider.token = user.token; + _rebuildClient(); + await _openSessionsFor(user); + _resetReplicaPhases(); + await _refreshReplicas(notify: false); + if (online) { + await _ensureRemoteAuth(user); + } else { + await _fetchServer(notify: false); + } + }); + } + + // --- Controls ----------------------------------------------------------- + + Future setShowHidden(bool value) async { + if (showHidden == value) return; + showHidden = value; + notifyListeners(); + _projectFromSnapshots(); + if (online) { + await _fetchServer(notify: false); + } + _notifyEverything(); + } + + Future setOnline(bool value) async { + await _run( + value ? 'Connectivity enabled.' : 'Connectivity disabled.', + () async { + if (!value) { + await _stopAllStreams(); + } + online = value; + _rebuildClient(); + _resetReplicaPhases(); + if (online && selectedUser != null) { + await _ensureRemoteAuth(selectedUser!); + } else { + await _fetchServer(notify: false); + } + }, + ); + } + + // --- Sync (per replica) ------------------------------------------------- + + Future syncReplica(ReplicaSlot slot) async { + final state = replicas[slot]!; + final session = state.session; + if (session == null || !online || state.streaming || state.busy) return; + + await _runReplica(slot, 'Synced ${slot.label} with the server.', () async { + state.phase = SyncPhase.syncing; + state.error = null; + state.changed(); + try { + await session.syncOnce( + client, + onMergeSuccess: (hlc) => _handleReplicaMerge(slot, hlc), + ); + state.phase = SyncPhase.idle; + state.lastSyncedLabel = 'synced ${_timeLabel()}'; + } catch (error) { + state.phase = SyncPhase.failed; + state.error = '$error'; + rethrow; + } finally { + await _refreshReplica(slot, notify: false); + state.changed(); + } + }); + } + + Future setReplicaStreaming(ReplicaSlot slot, bool value) async { + final state = replicas[slot]!; + if (value) { + final session = state.session; + if (session == null || !online || state.streaming || state.busy) return; + await _runReplica( + slot, + 'Streaming ${slot.label} with the server.', + () async { + final stream = session.syncContinuously( + client, + onMergeSuccess: (hlc) => unawaited(_handleReplicaMerge(slot, hlc)), + ); + state.stream = stream; + state.phase = SyncPhase.streaming; + state.error = null; + unawaited( + stream.done + .then((_) { + if (!identical(state.stream, stream)) return; + state.stream = null; + if (state.phase == SyncPhase.streaming) { + state.phase = SyncPhase.idle; + } + state.changed(); + notifyListeners(); + }) + .catchError((Object error) { + if (!identical(state.stream, stream)) return; + state.stream = null; + state.phase = SyncPhase.failed; + state.error = '$error'; + state.changed(); + notifyListeners(); + }), + ); + }, + ); + return; + } + + await _runReplica( + slot, + 'Stopped streaming ${slot.label}.', + () => _stopReplicaStream(slot), + ); + } + + // --- Refresh ------------------------------------------------------------ + + Future refreshAll() async { + await _refreshReplicas(notify: false); + await _fetchServer(notify: false); + _notifyEverything(); + } + + /// Re-fetches just the server "merged truth" panel. + Future refreshServer() => _fetchServer(); + + Future _refreshReplicas({bool notify = true}) async { + for (final slot in ReplicaSlot.values) { + await _refreshReplica(slot, notify: false); + } + if (notify) { + _notifyReplicas(); + } + } + + Future _fetchServer({bool notify = true}) async { + if (!online) { + server + ..projection = DemoProjection.empty() + ..error = null + ..lastFetchedLabel = null; + if (notify) server.changed(); + return; + } + server.loading = true; + if (notify) server.changed(); + try { + final rows = await client.demoDebug.fetchScopeSnapshot( + includeHidden: showHidden, + ); + // The server returns a flat list of row models. To flag CRDT-hidden rows + // we diff against a visible-only fetch (the same two reads the endpoint + // used to do internally); skipped entirely when hidden rows aren't shown. + final hiddenIds = {}; + if (showHidden) { + final visible = await client.demoDebug.fetchScopeSnapshot( + includeHidden: false, + ); + final visibleIds = { + for (final row in visible) '${(row as dynamic).id}', + }; + for (final row in rows) { + final id = '${(row as dynamic).id}'; + if (!visibleIds.contains(id)) hiddenIds.add(id); + } + } + server + ..projection = DemoSnapshot.fromServer( + catalog, + rows, + hiddenIds: hiddenIds, + ).project(showHidden: showHidden) + ..error = null + ..lastFetchedLabel = 'fetched ${_timeLabel()}'; + } catch (error) { + server + ..projection = DemoProjection.empty() + ..error = '$error'; + } finally { + server.loading = false; + if (notify) server.changed(); + } + } + + Future _handleReplicaMerge(ReplicaSlot slot, Object hlc) async { + replicas[slot]!.lastSyncedLabel = 'merged $hlc'; + await _refreshReplica(slot, notify: false); + await _fetchServer(notify: false); + replicas[slot]!.changed(); + server.changed(); + } + + Future _refreshReplica(ReplicaSlot slot, {bool notify = true}) async { + final state = replicas[slot]!; + final session = state.session; + if (session == null) { + state.snapshot = null; + state.projection = DemoProjection.empty(); + } else { + // Reading the view must never turn a successful sync/seed into a reported + // failure. Surface the error in the panel and keep the last projection. + try { + final snapshot = await DemoSnapshot.load(catalog, session.session); + state.snapshot = snapshot; + state.projection = snapshot.project(showHidden: showHidden); + state.error = null; + } catch (error, stackTrace) { + if (kDebugMode) { + debugPrint('Snapshot load failed for ${slot.label}: $error'); + debugPrint('$stackTrace'); + } + state.error = 'view error: $error'; + } + } + if (notify) state.changed(); + } + + // --- Reset -------------------------------------------------------------- + + /// Wipes one replica's local database (a fresh device). Syncing afterwards + /// re-pulls whatever the server still holds. + Future resetReplica(ReplicaSlot slot) async { + await _runReplica( + slot, + 'Reset ${slot.label} (wiped local database).', + () => _resetReplicaStorage(slot), + ); + } + + /// Wipes both replicas and the server scope at once, concurrently. + Future resetAll() async { + await _stopAllStreams(); + await Future.wait([ + resetReplica(ReplicaSlot.a), + resetReplica(ReplicaSlot.b), + if (online) resetServer(), + ]); + } + + /// Hard-clears the caller's server scope, including synced rows and CRDT + /// metadata. + Future resetServer() async { + if (!online) return; + await _runServer('Reset the server scope.', () async { + await _stopAllStreams(); + _notifyReplicas(); + try { + await client.demoDebug.resetScope(); + } catch (error) { + server.error = 'reset failed: $error'; + rethrow; + } + await _fetchServer(notify: false); + server.changed(); + }); + } + + // --- Free-form row construction (the primary workflow) ------------------ + + /// Creates a root row of [table] on [slot] and returns its reference. + Future createRoot( + ReplicaSlot slot, + String table, { + String? label, + }) async { + final row = catalog.buildRow( + table, + label: label ?? '${_friendly(table)} ${_counter.next(table)}', + ); + if (row == null) { + status = 'Cannot create $table without more fields.'; + notifyListeners(); + return null; + } + return _insertRow(slot, row, 'Created $table on ${slot.label}.'); + } + + /// Creates a child of [parent] on [slot] using [relation], attaching its + /// foreign key to the parent. Returns the new child's reference. + Future createChildFor( + ReplicaSlot slot, + DemoRowRef parent, + Relationship relation, + ) async { + final childLabel = + '${_friendly(relation.childTable)} ${_counter.next(relation.childTable)}'; + final row = catalog.buildRow( + relation.childTable, + fkColumn: relation.fkColumn, + fkValue: parent.id, + label: childLabel, + ); + if (row == null) { + status = 'Cannot create ${relation.childTable} here.'; + notifyListeners(); + return null; + } + return _insertRow( + slot, + row, + 'Attached ${relation.childTable} to ${parent.tableName} on ${slot.label}.', + ); + } + + /// Re-points [ref]'s [fkColumn] at [newParentId], or detaches it when null. + Future reParent( + ReplicaSlot slot, + DemoRowRef ref, + String fkColumn, + protocol.UuidValue? newParentId, + ) async { + final ops = demoTableOps[ref.tableName]; + final session = replicas[slot]!.session; + if (ops == null || session == null) return; + + final verb = newParentId == null ? 'Detached' : 'Re-parented'; + await _runReplica( + slot, + '$verb ${ref.tableName} on ${slot.label}.', + () async { + final crdt = session.session; + final row = + await ops.findById(crdt, ref.id) ?? + await _findHiddenRow(ops, crdt, ref.id); + if (row == null) return; + await ops.updateFields(crdt, row, {fkColumn: newParentId}); + await _refreshReplica(slot, notify: false); + replicas[slot]!.changed(); + }, + ); + } + + Future _insertRow( + ReplicaSlot slot, + TableRow row, + String success, + ) async { + final table = row.table.tableName; + final ops = demoTableOps[table]; + final session = replicas[slot]!.session; + if (ops == null || session == null) return null; + final id = row.id; + if (id == null) return null; + final ok = await _runReplica(slot, success, () async { + await ops.insertRow(session.session, row); + await _refreshReplica(slot, notify: false); + replicas[slot]!.changed(); + }); + return ok ? DemoRowRef(tableName: table, id: id) : null; + } + + /// Restores a soft-deleted row by inserting it again with the same id. + Future reinsertRow(DemoRowRef ref, ReplicaSlot slot) async { + final ops = demoTableOps[ref.tableName]; + final session = replicas[slot]!.session; + if (ops == null || session == null) return null; + + final ok = await _runReplica( + slot, + 'Reinserted ${ref.tableName} on ${slot.label}.', + () async { + final crdt = session.session; + final hidden = await _findHiddenRow(ops, crdt, ref.id); + if (hidden == null) return; + await ops.insertRow(crdt, hidden); + await _refreshReplica(slot, notify: false); + replicas[slot]!.changed(); + }, + ); + return ok ? ref : null; + } + + /// Applies [fields] to a visible row on [slot]. + Future updateRowFields( + DemoRowRef ref, + ReplicaSlot slot, + Map fields, + ) async { + final ops = demoTableOps[ref.tableName]; + final session = replicas[slot]!.session; + if (ops == null || session == null) return; + + await _runReplica( + slot, + 'Updated ${ref.tableName} on ${slot.label}.', + () async { + final crdt = session.session; + final row = await ops.findById(crdt, ref.id); + if (row == null) return; + await ops.updateFields(crdt, row, fields); + await _refreshReplica(slot, notify: false); + replicas[slot]!.changed(); + }, + ); + } + + // --- Seeds (quick-starts, used by menus and scenarios) ------------------ + + Future seedBasicGraph(ReplicaSlot slot) { + return _seedLocal( + slot, + 'Seeded a city/person/address/town graph on ${slot.label}.', + (session) async { + final suffix = _counter.next('basic'); + final city = await protocol.City.db.insertRow( + session.session, + protocol.City(id: newId(), name: 'City $suffix'), + ); + final person = await protocol.Person.db.insertRow( + session.session, + protocol.Person( + id: newId(), + name: 'Person $suffix', + surname: 'Local', + ), + ); + await protocol.Address.db.insertRow( + session.session, + protocol.Address( + id: newId(), + street: 'Main Street $suffix', + inhabitantId: person.id, + ), + ); + await protocol.Town.db.insertRow( + session.session, + protocol.Town(id: newId(), name: 'Town $suffix', cityId: city.id), + ); + }, + ); + } + + Future seedTypedRow(ReplicaSlot slot) { + return _seedLocal(slot, 'Seeded a typed row on ${slot.label}.', ( + session, + ) async { + final suffix = _counter.next('types'); + await protocol.Types.db.insertRow( + session.session, + protocol.Types( + id: newId(), + aBool: suffix.isOdd, + aDateTime: DateTime.utc(2026, 6, ((suffix - 1) % 28) + 1, 12), + aText: 'typed-$suffix', + anInt: suffix, + anInt64: BigInt.parse('9007199254740993') + BigInt.from(suffix), + aReal: suffix + 0.25, + aBlob: ByteData.sublistView(Uint8List.fromList([suffix, 2, 3])), + anEnum: protocol + .TypesEnum + .values[suffix % protocol.TypesEnum.values.length], + optionalText: 'optional-$suffix', + optionalUuid: newId(), + ), + ); + }); + } + + Future seedForeignKeyChain(ReplicaSlot slot) { + return _seedLocal(slot, 'Seeded a mixed FK chain on ${slot.label}.', ( + session, + ) async { + final suffix = _counter.next('chain'); + final root = await protocol.FkChainRoot.db.insertRow( + session.session, + protocol.FkChainRoot(id: newId(), name: 'Root $suffix'), + ); + final middle = await protocol.FkChainCascadeMiddle.db.insertRow( + session.session, + protocol.FkChainCascadeMiddle( + id: newId(), + name: 'Cascade middle $suffix', + rootId: root.id, + ), + ); + final blocker = await protocol.FkChainRestrictBlocker.db.insertRow( + session.session, + protocol.FkChainRestrictBlocker( + id: newId(), + name: 'Restrict blocker $suffix', + cascadeMiddleId: middle.id, + ), + ); + await protocol.FkChainMiddleSetNullChild.db.insertRow( + session.session, + protocol.FkChainMiddleSetNullChild( + id: newId(), + name: 'Set-null child $suffix', + restrictBlockerId: blocker.id, + ), + ); + await protocol.FkChainMiddleCascadeChild.db.insertRow( + session.session, + protocol.FkChainMiddleCascadeChild( + id: newId(), + name: 'Cascade child $suffix', + restrictBlockerId: blocker.id, + ), + ); + }); + } + + /// Inserts a Unique row with a fixed [name] (for concurrent-insert conflicts). + Future createUnique(ReplicaSlot slot, String name) { + return createRoot(slot, 'unique', label: name); + } + + /// Inserts a Town, optionally with a fixed [id] (used for SetDefault targets). + Future createTown( + ReplicaSlot slot, { + protocol.UuidValue? id, + String? label, + }) async { + final row = protocol.Town( + id: id ?? newId(), + name: label ?? 'Town ${_counter.next('town')}', + ); + return _insertRow(slot, row, 'Created town on ${slot.label}.'); + } + + /// Inserts a Company referencing [town]. + Future createCompanyForTown( + ReplicaSlot slot, + DemoRowRef town, { + String? label, + }) async { + final row = protocol.Company( + id: newId(), + name: label ?? 'Company ${_counter.next('company')}', + townId: town.id, + ); + return _insertRow(slot, row, 'Created company on ${slot.label}.'); + } + + Future _seedLocal( + ReplicaSlot slot, + String success, + Future Function(OfflineReplica session) local, + ) async { + final session = replicas[slot]!.session; + if (session == null) return; + await _runReplica(slot, success, () async { + await local(session); + await _refreshReplica(slot, notify: false); + replicas[slot]!.changed(); + }); + } + + /// Seeds a graph directly on the server (fetch-from-scratch scenarios). + Future seedServer(String kind, [String? text]) async { + if (!online) { + status = 'Connect to seed the server.'; + notifyListeners(); + return; + } + await _runServer('Seeded the server scope ($kind).', () async { + try { + await client.demoDebug.seedScope(kind, text); + } catch (error) { + server.error = 'seed failed: $error'; + rethrow; + } + await _fetchServer(notify: false); + server.changed(); + }); + } + + // --- Scenarios ---------------------------------------------------------- + + late final List scenarios = _buildScenarios(); + + List get activeSteps => _activeSteps; + + void startScenario(Scenario scenario) { + stopScenarioAutoPlay(); + activeScenario = scenario; + _activeSteps = scenario.build(this); + scenarioStepIndex = 0; + status = 'Scenario "${scenario.title}" ready — run the steps in order.'; + notifyListeners(); + } + + void stopScenario() { + if (activeScenario == null) return; + stopScenarioAutoPlay(); + activeScenario = null; + _activeSteps = const []; + scenarioStepIndex = 0; + notifyListeners(); + } + + bool get scenarioComplete => + activeScenario != null && scenarioStepIndex >= _activeSteps.length; + + void toggleScenarioAutoPlay() { + if (scenarioAutoPlaying) { + stopScenarioAutoPlay(); + } else { + startScenarioAutoPlay(); + } + } + + void startScenarioAutoPlay() { + if (activeScenario == null || scenarioComplete || scenarioAutoPlaying) { + return; + } + scenarioAutoPlaying = true; + notifyListeners(); + _kickScenarioAutoPlay(); + } + + void stopScenarioAutoPlay() { + if (!scenarioAutoPlaying && _scenarioAutoPlayTimer == null) return; + scenarioAutoPlaying = false; + _scenarioAutoPlayTimer?.cancel(); + _scenarioAutoPlayTimer = null; + notifyListeners(); + } + + void _kickScenarioAutoPlay() { + if (!scenarioAutoPlaying || scenarioComplete || activeScenario == null) { + return; + } + if (anyBusy) { + _scheduleScenarioAutoPlayStep(delay: const Duration(milliseconds: 100)); + return; + } + unawaited(_runScenarioAutoPlayStep()); + } + + void _scheduleScenarioAutoPlayStep({ + Duration delay = _scenarioAutoPlayDelay, + }) { + _scenarioAutoPlayTimer?.cancel(); + if (!scenarioAutoPlaying || scenarioComplete || activeScenario == null) { + return; + } + _scenarioAutoPlayTimer = Timer(delay, _kickScenarioAutoPlay); + } + + Future _runScenarioAutoPlayStep() async { + if (!scenarioAutoPlaying || scenarioComplete || activeScenario == null) { + return; + } + if (anyBusy) { + _scheduleScenarioAutoPlayStep(delay: const Duration(milliseconds: 100)); + return; + } + await runNextScenarioStep(); + } + + Future runNextScenarioStep() async { + if (activeScenario == null) return; + if (scenarioStepIndex >= _activeSteps.length) return; + final step = _activeSteps[scenarioStepIndex]; + await step.run(); + scenarioStepIndex++; + if (scenarioStepIndex >= _activeSteps.length) { + status = 'Scenario "${activeScenario!.title}" complete.'; + stopScenarioAutoPlay(); + } else if (scenarioAutoPlaying) { + _scheduleScenarioAutoPlayStep(); + } + notifyListeners(); + } + + // --- Row detail, editing & deletion ------------------------------------- + + /// Finds a row by id including CRDT-hidden rows (via `includeHidden`), + /// since a plain findById only returns visible rows. + Future?> _findHiddenRow( + TableOps ops, + offline.CrdtDatabaseSession crdt, + protocol.UuidValue id, + ) async { + final all = await ops.findAll(crdt, includeHidden: true); + for (final row in all) { + if (row.id == id) return row; + } + return null; + } + + /// Loads the full record for [ref] on [slot], reading hidden rows through the + /// includeHidden expression when needed. + Future loadDetail(DemoRowRef ref, ReplicaSlot slot) async { + final ops = demoTableOps[ref.tableName]; + final session = replicas[slot]!.session; + if (ops == null || session == null) return null; + + final visibleRow = await ops.findById(session.session, ref.id); + final row = + visibleRow ?? await _findHiddenRow(ops, session.session, ref.id); + if (row == null) return null; + + final json = row.toJson() as Map; + final fields = _modelFields(ref.tableName, json); + return RowDetail( + slot: slot, + tableName: ref.tableName, + uuid: ref.id.uuid, + visible: visibleRow != null, + fields: fields, + editable: _editableFields(ref.tableName, fields), + ); + } + + /// Applies [values] (keyed by [EditableField.key]) to the row on [slot]. + Future applyEdit( + DemoRowRef ref, + ReplicaSlot slot, + Map values, + ) async { + final ops = demoTableOps[ref.tableName]; + final session = replicas[slot]!.session; + if (ops == null || session == null) return false; + + return _runReplica( + slot, + 'Updated ${ref.tableName} on ${slot.label}.', + () async { + final crdt = session.session; + final row = await ops.findById(crdt, ref.id); + if (row == null) return; + final fields = _decodeEditedValues(ref.tableName, values); + await ops.updateFields(crdt, row, fields); + await _refreshReplica(slot, notify: false); + replicas[slot]!.changed(); + }, + ); + } + + Future deleteRow(DemoRowRef ref, ReplicaSlot slot) async { + final ops = demoTableOps[ref.tableName]; + final session = replicas[slot]!.session; + if (ops == null || session == null) return; + + await _runReplica( + slot, + 'Deleted ${ref.tableName} on ${slot.label}.', + () async { + await ops.deleteById(session.session, ref.id); + await _refreshReplica(slot, notify: false); + replicas[slot]!.changed(); + }, + ); + } + + // --- Internals ---------------------------------------------------------- + + String _friendly(String table) { + final words = tableLabel(table).split(' '); + return words + .map((w) => w.isEmpty ? w : '${w[0].toUpperCase()}${w.substring(1)}') + .join(' '); + } + + Future _openSession(DemoUser user, ReplicaSlot slot) async { + final key = _sessionKey(user, slot); + final existing = _sessions[key]; + if (existing != null) { + replicas[slot]!.session = existing; + return existing; + } + + // The demo chooses where each replica's database lives (one file per + // user+slot); opening and CRDT-wrapping it is OfflineReplica's job. + final dir = await getApplicationSupportDirectory(); + final dbDir = Directory(p.join(dir.path, 'serverpod_offline_sync_demo')); + if (!dbDir.existsSync()) { + dbDir.createSync(recursive: true); + } + final replica = await OfflineReplica.open( + client: client, + databasePath: p.join(dbDir.path, '${user.username}-${slot.name}.db'), + persistentUserId: user.authUserId, + ); + _sessions[key] = replica; + replicas[slot]!.session = replica; + return replica; + } + + Future _openSessionsFor(DemoUser user) async { + for (final slot in ReplicaSlot.values) { + await _openSession(user, slot); + } + } + + Future _ensureRemoteAuth(DemoUser user) async { + if (!online) return; + try { + final token = await client.demoAuth.loginOrCreateUser(user.username); + user.token = token; + user.authUserId = authUserIdFromToken(token); + if (identical(selectedUser, user)) { + authKeyProvider.token = token; + } + status = 'Authenticated ${user.username} on the demo server.'; + if (identical(selectedUser, user)) { + await _fetchServer(notify: false); + server.changed(); + } + notifyListeners(); + } catch (error) { + status = 'Using local ${user.username}; server auth unavailable: $error'; + notifyListeners(); + } + } + + Future _stopReplicaStream(ReplicaSlot slot) async { + final state = replicas[slot]!; + final stream = state.stream; + state.stream = null; + if (state.phase == SyncPhase.streaming) state.phase = SyncPhase.idle; + await stream?.cancel(); + } + + Future _stopAllStreams() async { + for (final slot in ReplicaSlot.values) { + await _stopReplicaStream(slot); + } + } + + /// Wipes a replica's local database (via [OfflineReplica.reset]) and resets + /// its sync phase. Syncing afterwards re-pulls whatever the server still + /// holds. + Future _resetReplicaStorage(ReplicaSlot slot) async { + await _stopReplicaStream(slot); + await replicas[slot]!.session?.reset(); + + replicas[slot]! + ..phase = online ? SyncPhase.idle : SyncPhase.offline + ..lastSyncedLabel = null + ..error = null; + await _refreshReplica(slot, notify: false); + } + + void _resetReplicaPhases() { + for (final state in replicas.values) { + if (state.streaming) continue; + state.phase = online ? SyncPhase.idle : SyncPhase.offline; + } + } + + void _rebuildClient() => _client = _createClient(); + + protocol.Client _createClient() { + return protocol.Client( + serverUrl, + httpClientOverride: online ? null : OfflineHttpClient(), + )..authKeyProvider = authKeyProvider; + } + + DemoUser _localUser(String username) { + final normalized = normalizeUsername(username); + final authUserId = demoAuthUserIdForUsername(normalized); + return DemoUser( + username: normalized, + authUserId: authUserId, + token: demoTokenForAuthUserId(authUserId), + ); + } + + DemoUser? _findUser(String username) { + for (final user in users) { + if (user.username == username) return user; + } + return null; + } + + Future _run(String success, Future Function() action) async { + busy = true; + _notifyEverything(); + try { + await action(); + status = success; + return true; + } catch (error, stackTrace) { + if (kDebugMode) { + debugPrint('$stackTrace'); + } + status = 'Failed: $error'; + return false; + } finally { + busy = false; + _notifyEverything(); + } + } + + Future _runReplica( + ReplicaSlot slot, + String success, + Future Function() action, + ) async { + final state = replicas[slot]!; + if (busy || state.busy) return false; + + state + ..busy = true + ..error = null; + state.changed(); + notifyListeners(); + + try { + await action(); + status = success; + return true; + } catch (error, stackTrace) { + if (kDebugMode) { + debugPrint('$stackTrace'); + } + state.error ??= '$error'; + status = 'Failed: $error'; + return false; + } finally { + state.busy = false; + state.changed(); + notifyListeners(); + } + } + + Future _runServer( + String success, + Future Function() action, + ) async { + if (busy || server.busy) return false; + + server + ..busy = true + ..error = null; + server.changed(); + notifyListeners(); + + try { + await action(); + status = success; + return true; + } catch (error, stackTrace) { + if (kDebugMode) { + debugPrint('$stackTrace'); + } + server.error ??= '$error'; + status = 'Failed: $error'; + return false; + } finally { + server.busy = false; + server.changed(); + notifyListeners(); + } + } + + void _projectFromSnapshots() { + for (final state in replicas.values) { + final snapshot = state.snapshot; + if (snapshot != null) { + state.projection = snapshot.project(showHidden: showHidden); + } + } + } + + void _notifyReplicas() { + for (final state in replicas.values) { + state.changed(); + } + } + + void _notifyEverything() { + _notifyReplicas(); + server.changed(); + notifyListeners(); + } + + String _sessionKey(DemoUser user, ReplicaSlot slot) { + return '${user.authUserId.uuid}:${slot.name}'; + } + + String _timeLabel() { + final now = DateTime.now(); + String two(int v) => v.toString().padLeft(2, '0'); + return '${two(now.hour)}:${two(now.minute)}:${two(now.second)}'; + } +} + +/// A single editable field of a row detail. +class EditableField { + EditableField(this.key, this.value); + + final String key; + final String value; +} + +/// The complete record behind a tree row, plus its CRDT visibility status. +class RowDetail { + RowDetail({ + required this.slot, + required this.tableName, + required this.uuid, + required this.visible, + required this.fields, + required this.editable, + }); + + final ReplicaSlot slot; + final String tableName; + final String uuid; + final bool visible; + final Map fields; + final List editable; + + /// The CRDT scope id stored on the row, if any. + String? get scopeId => fields['scopeId']?.toString(); +} + +final _tableDefinitionsByName = { + for (final table in protocol.Protocol.targetTableDefinitions) + table.name: table, +}; + +Map _modelFields(String tableName, Map json) { + final fields = {}; + final table = _tableDefinition(tableName); + + for (final column in table.columns) { + fields[column.name] = json[column.name]; + } + + for (final entry in json.entries) { + if (_isPublicField(entry.key)) { + fields.putIfAbsent(entry.key, () => entry.value); + } + } + + return fields; +} + +List _editableFields( + String tableName, + Map fields, +) { + final table = _tableDefinition(tableName); + + return [ + for (final column in table.columns) + if (_isEditableColumn(column)) + EditableField(column.name, fields[column.name]?.toString() ?? ''), + ]; +} + +Map _decodeEditedValues( + String tableName, + Map values, +) { + final edited = {}; + final table = _tableDefinition(tableName); + + for (final column in table.columns) { + final value = values[column.name]; + if (value == null || !_isEditableColumn(column)) continue; + edited[column.name] = _parseFieldText(value, column); + } + + return edited; +} + +bool _isPublicField(String key) { + return !key.startsWith('__') && !key.startsWith('_'); +} + +bool _isEditableField(String key) { + return _isPublicField(key) && key != 'id' && key != 'scopeId'; +} + +bool _isEditableColumn(ColumnDefinition column) { + return _isEditableField(column.name); +} + +TableDefinition _tableDefinition(String tableName) { + return _tableDefinitionsByName[tableName] ?? + (throw StateError('No table definition registered for $tableName.')); +} + +/// Parses editable text into the JSON shape consumed by [protocol.Protocol]. +dynamic _parseFieldText(String raw, ColumnDefinition column) { + if (raw.isEmpty && column.isNullable) return null; + + return switch (column.columnType) { + ColumnType.boolean => _parseBool(raw), + ColumnType.bigint => _parseBigIntColumn(raw, column), + ColumnType.integer => int.parse(raw), + ColumnType.doublePrecision => double.parse(raw), + ColumnType.uuid || + ColumnType.timestampWithoutTimeZone || + ColumnType.text || + ColumnType.bytea => raw, + _ => raw, + }; +} + +dynamic _parseBigIntColumn(String raw, ColumnDefinition column) { + final dartType = column.dartType; + if (dartType?.startsWith('protocol:') ?? false) return int.parse(raw); + if (dartType == 'int' || dartType == 'int?') return int.parse(raw); + return raw; +} + +bool _parseBool(String raw) { + return switch (raw.trim().toLowerCase()) { + 'true' || '1' || 'yes' => true, + 'false' || '0' || 'no' => false, + _ => throw FormatException('Expected a boolean value.'), + }; +} diff --git a/example/offline_sync_demo/lib/src/demo_view.dart b/example/offline_sync_demo/lib/src/demo_view.dart new file mode 100644 index 0000000..0e685e2 --- /dev/null +++ b/example/offline_sync_demo/lib/src/demo_view.dart @@ -0,0 +1,1388 @@ +import 'dart:async'; + +import 'package:flutter/services.dart' show Clipboard, ClipboardData; +import 'package:shadcn_flutter/shadcn_flutter.dart'; + +import 'demo_controller.dart'; +import 'models.dart'; +import 'relationships.dart'; +import 'snapshot.dart'; + +part 'sheets.dart'; + +/// The full dashboard: global toolbar, scenario rail, replica panels, server. +class DemoDashboard extends StatelessWidget { + const DemoDashboard({super.key, required this.controller}); + + final DemoController controller; + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _Toolbar(controller: controller), + const Gap(12), + Expanded( + child: Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + SizedBox( + width: 280, + child: _ScenarioRail(controller: controller), + ), + const Gap(12), + Expanded( + flex: 4, + child: _ReplicaPanel( + controller: controller, + slot: ReplicaSlot.a, + ), + ), + const Gap(12), + Expanded( + flex: 4, + child: _ReplicaPanel( + controller: controller, + slot: ReplicaSlot.b, + ), + ), + const Gap(12), + Expanded(flex: 3, child: _ServerPanel(controller: controller)), + ], + ), + ), + const Gap(12), + _StatusBar(controller: controller), + ], + ), + ); + } +} + +class _Toolbar extends StatelessWidget { + const _Toolbar({required this.controller}); + + final DemoController controller; + + @override + Widget build(BuildContext context) { + return AnimatedBuilder( + animation: controller, + builder: (context, _) => OutlinedContainer( + padding: const EdgeInsets.all(12), + child: Wrap( + spacing: 12, + runSpacing: 10, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + Checkbox( + state: controller.online + ? CheckboxState.checked + : CheckboxState.unchecked, + onChanged: controller.anyBusy + ? null + : (value) => unawaited( + controller.setOnline(value == CheckboxState.checked), + ), + trailing: const Text('Connectivity'), + ), + Checkbox( + state: controller.showHidden + ? CheckboxState.checked + : CheckboxState.unchecked, + onChanged: controller.anyBusy + ? null + : (value) => unawaited( + controller.setShowHidden(value == CheckboxState.checked), + ), + trailing: const Text('Show hidden rows'), + ), + OutlineButton( + onPressed: controller.anyBusy + ? null + : () => unawaited(controller.refreshAll()), + child: const Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.refresh, size: 16), + Gap(6), + Text('Refresh'), + ], + ), + ), + Tooltip( + tooltip: (context) => const TooltipContainer( + child: Text('Wipe both replicas and the server scope at once'), + ), + child: OutlineButton( + onPressed: controller.anyBusy + ? null + : () => unawaited(controller.resetAll()), + child: const Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.delete_sweep_outlined, size: 16), + Gap(6), + Text('Reset all'), + ], + ), + ), + ), + _ReplicaIsolationInfoButton(controller: controller), + ], + ), + ), + ); + } +} + +class _ReplicaIsolationInfoButton extends StatelessWidget { + const _ReplicaIsolationInfoButton({required this.controller}); + + final DemoController controller; + + @override + Widget build(BuildContext context) { + return IconButton.ghost( + icon: const Icon(Icons.info_outline, size: 18), + onPressed: () { + showPopover( + context: context, + alignment: Alignment.bottomCenter, + builder: (context) => OutlinedContainer( + padding: const EdgeInsets.all(12), + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 360), + child: Text(controller.replicaIsolationMessage), + ), + ), + ); + }, + ); + } +} + +// --- Scenario rail --------------------------------------------------------- + +class _ScenarioRail extends StatelessWidget { + const _ScenarioRail({required this.controller}); + + final DemoController controller; + + @override + Widget build(BuildContext context) { + return AnimatedBuilder( + animation: controller, + builder: (context, _) { + final active = controller.activeScenario; + return OutlinedContainer( + padding: const EdgeInsets.all(12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + children: [ + const Icon(Icons.list_alt, size: 16), + const Gap(6), + const Text('Scenarios').semiBold(), + const Spacer(), + if (active != null) + IconButton.ghost( + icon: const Icon(Icons.close, size: 16), + onPressed: controller.stopScenario, + ), + ], + ), + const Gap(4), + const Text( + 'Optional quick-starts. Everything here is also doable by hand ' + 'on the trees.', + ).xSmall().muted(), + const Gap(12), + Expanded( + child: SingleChildScrollView( + child: active == null + ? _ScenarioList(controller: controller) + : _ScenarioSteps( + controller: controller, + scenario: active, + ), + ), + ), + ], + ), + ); + }, + ); + } +} + +class _ScenarioList extends StatelessWidget { + const _ScenarioList({required this.controller}); + + final DemoController controller; + + @override + Widget build(BuildContext context) { + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + for (final scenario in controller.scenarios) + Padding( + padding: const EdgeInsets.only(bottom: 8), + child: OutlineButton( + onPressed: controller.anyBusy + ? null + : () => controller.startScenario(scenario), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Icon(Icons.play_circle_outline, size: 18), + const Gap(8), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(scenario.title), + const Gap(2), + Text(scenario.summary).xSmall().muted(), + ], + ), + ), + ], + ), + ), + ), + ], + ); + } +} + +class _ScenarioSteps extends StatelessWidget { + const _ScenarioSteps({required this.controller, required this.scenario}); + + final DemoController controller; + final Scenario scenario; + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + final steps = controller.activeSteps; + final current = controller.scenarioStepIndex; + + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text(scenario.title).semiBold(), + const Gap(2), + Text(scenario.summary).xSmall().muted(), + const Gap(12), + for (var i = 0; i < steps.length; i++) + Padding( + padding: const EdgeInsets.only(bottom: 8), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Icon( + i < current + ? Icons.check_circle + : i == current + ? Icons.radio_button_checked + : Icons.radio_button_unchecked, + size: 16, + color: i < current + ? scheme.primary + : i == current + ? scheme.foreground + : scheme.mutedForeground, + ), + const Gap(8), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + steps[i].label, + style: TextStyle( + fontSize: 13, + color: i == current + ? scheme.foreground + : scheme.mutedForeground, + fontWeight: i == current + ? FontWeight.w500 + : FontWeight.normal, + ), + ), + if (steps[i].replica != null) + Text(steps[i].replica!.label).xSmall().muted(), + ], + ), + ), + ], + ), + ), + const Gap(8), + if (controller.scenarioComplete) + PrimaryButton( + onPressed: controller.stopScenario, + child: const Text('Done'), + ) + else + Row( + children: [ + Expanded( + child: PrimaryButton( + onPressed: + controller.anyBusy || controller.scenarioAutoPlaying + ? null + : () => unawaited(controller.runNextScenarioStep()), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + const Icon(Icons.play_arrow, size: 16), + const Gap(4), + Text('Run step ${current + 1}'), + ], + ), + ), + ), + const Gap(8), + Tooltip( + tooltip: (context) => TooltipContainer( + child: Text( + controller.scenarioAutoPlaying + ? 'Pause auto-play' + : 'Auto-play steps (1.0s apart)', + ), + ), + child: OutlineButton( + onPressed: + controller.anyBusy && !controller.scenarioAutoPlaying + ? null + : controller.toggleScenarioAutoPlay, + child: Icon( + controller.scenarioAutoPlaying + ? Icons.pause + : Icons.play_arrow, + size: 16, + ), + ), + ), + ], + ), + ], + ); + } +} + +// --- Replica panel --------------------------------------------------------- + +class _ReplicaPanel extends StatelessWidget { + const _ReplicaPanel({required this.controller, required this.slot}); + + final DemoController controller; + final ReplicaSlot slot; + + @override + Widget build(BuildContext context) { + return AnimatedBuilder( + animation: Listenable.merge([controller, controller.replica(slot)]), + builder: (context, _) { + final scheme = Theme.of(context).colorScheme; + final state = controller.replica(slot); + final canUseReplica = !controller.busy && !state.busy; + final canSync = + controller.online && + canUseReplica && + !state.streaming && + state.session != null; + final actions = _RowActions(controller: controller, slot: slot); + + return OutlinedContainer( + padding: const EdgeInsets.all(12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + children: [ + Icon( + slot == ReplicaSlot.a ? Icons.computer : Icons.laptop, + size: 16, + ), + const Gap(6), + Text(slot.label).semiBold(), + const Gap(8), + _SyncBadge(state: state), + if (state.busy) ...[ + const Gap(6), + const SizedBox( + width: 12, + height: 12, + child: CircularProgressIndicator(), + ), + ], + const Spacer(), + Text( + '${state.projection.visibleRowCount} visible · ' + '${state.projection.hiddenRowCount} hidden', + ).xSmall().muted(), + ], + ), + const Gap(8), + Row( + children: [ + _NewRowButton( + controller: controller, + slot: slot, + enabled: canUseReplica && state.session != null, + ), + const Spacer(), + PrimaryButton( + onPressed: canSync + ? () => unawaited(controller.syncReplica(slot)) + : null, + child: const Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.sync, size: 14), + Gap(4), + Text('Sync'), + ], + ), + ), + const Gap(12), + Checkbox( + state: state.streaming + ? CheckboxState.checked + : CheckboxState.unchecked, + onChanged: (!controller.online || !canUseReplica) + ? null + : (value) => unawaited( + controller.setReplicaStreaming( + slot, + value == CheckboxState.checked, + ), + ), + trailing: const Text('Stream'), + ), + const Gap(4), + Tooltip( + tooltip: (context) => TooltipContainer( + child: Text('Reset ${slot.label}: wipe local database'), + ), + child: IconButton.ghost( + icon: const Icon(Icons.delete_outline, size: 16), + onPressed: canUseReplica + ? () => unawaited(controller.resetReplica(slot)) + : null, + ), + ), + ], + ), + if (state.error != null) ...[ + const Gap(6), + Row( + children: [ + Icon( + Icons.error_outline, + size: 12, + color: scheme.destructive, + ), + const Gap(4), + Expanded( + child: Text( + state.error!, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 11, + color: scheme.destructive, + ), + ), + ), + ], + ), + ], + const Gap(8), + const Divider(), + const Gap(8), + Expanded( + child: controller.initializing + ? const _PanelLoading(message: 'Opening local database…') + : _ProjectionTree( + key: ValueKey(controller.showHidden), + nodes: state.projection.nodes, + actions: actions, + onTapRow: (ref) => unawaited( + showRowDetailSheet(context, controller, ref, slot), + ), + ), + ), + ], + ), + ); + }, + ); + } +} + +/// Bundles the per-replica context the row action menus need. +class _RowActions { + _RowActions({required this.controller, required this.slot}); + + final DemoController controller; + final ReplicaSlot slot; +} + +class _NewRowButton extends StatelessWidget { + const _NewRowButton({ + required this.controller, + required this.slot, + required this.enabled, + }); + + final DemoController controller; + final ReplicaSlot slot; + final bool enabled; + + @override + Widget build(BuildContext context) { + return OutlineButton( + onPressed: enabled ? () => _open(context) : null, + child: const Row( + mainAxisSize: MainAxisSize.min, + children: [Icon(Icons.add, size: 14), Gap(4), Text('Add data')], + ), + ); + } + + void _open(BuildContext context) { + showDropdown( + context: context, + builder: (context) => DropdownMenu( + children: [ + MenuButton( + leading: const Icon(Icons.account_tree, size: 16), + onPressed: (_) => unawaited(controller.seedBasicGraph(slot)), + child: const Text('Seed city/person/address/town'), + ), + MenuButton( + leading: const Icon(Icons.data_object, size: 16), + onPressed: (_) => unawaited(controller.seedTypedRow(slot)), + child: const Text('Seed typed row'), + ), + MenuButton( + leading: const Icon(Icons.hub, size: 16), + onPressed: (_) => unawaited(controller.seedForeignKeyChain(slot)), + child: const Text('Seed FK chain'), + ), + for (final table in controller.catalog.creatableRootTables) + MenuButton( + leading: Icon(iconForTable(table, hidden: false), size: 16), + onPressed: (_) => unawaited(controller.createRoot(slot, table)), + child: Text(tableLabel(table)), + ), + ], + ), + ); + } +} + +// --- Server panel ---------------------------------------------------------- + +class _ServerPanel extends StatelessWidget { + const _ServerPanel({required this.controller}); + + final DemoController controller; + + @override + Widget build(BuildContext context) { + return AnimatedBuilder( + animation: Listenable.merge([controller, controller.server]), + builder: (context, _) { + final state = controller.server; + final serverBusy = controller.busy || state.busy || state.loading; + + return OutlinedContainer( + padding: const EdgeInsets.all(12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + children: [ + const Icon(Icons.dns, size: 16), + const Gap(6), + const Text('Server').semiBold(), + const Gap(8), + _ServerBadge(controller: controller), + if (state.busy) ...[ + const Gap(6), + const SizedBox( + width: 12, + height: 12, + child: CircularProgressIndicator(), + ), + ], + ], + ), + const Gap(6), + Row( + children: [ + Expanded( + child: Text( + '${state.projection.visibleRowCount} rows · merged truth', + ).xSmall().muted(), + ), + _ServerSeedButton( + controller: controller, + enabled: controller.online && !serverBusy, + ), + const Gap(4), + Tooltip( + tooltip: (context) => const TooltipContainer( + child: Text('Reset server scope: clear all rows'), + ), + child: IconButton.ghost( + icon: const Icon(Icons.delete_outline, size: 16), + onPressed: (!controller.online || serverBusy) + ? null + : () => unawaited(controller.resetServer()), + ), + ), + const Gap(4), + Tooltip( + tooltip: (context) => const TooltipContainer( + child: Text('Refresh server state'), + ), + child: IconButton.ghost( + icon: const Icon(Icons.refresh, size: 16), + onPressed: (!controller.online || serverBusy) + ? null + : () => unawaited(controller.refreshServer()), + ), + ), + ], + ), + const Gap(8), + const Divider(), + const Gap(8), + Expanded( + child: controller.initializing + ? const _PanelLoading(message: 'Loading server state…') + : !controller.online + ? const Center( + child: Text('Offline — connect to view server state.'), + ) + : state.error != null + ? Center( + child: Padding( + padding: const EdgeInsets.all(12), + child: Text(state.error!).small().muted(), + ), + ) + : _ProjectionTree( + key: ValueKey(controller.showHidden), + nodes: state.projection.nodes, + ), + ), + ], + ), + ); + }, + ); + } +} + +class _ServerSeedButton extends StatelessWidget { + const _ServerSeedButton({required this.controller, required this.enabled}); + + final DemoController controller; + final bool enabled; + + @override + Widget build(BuildContext context) { + return Tooltip( + tooltip: (context) => + const TooltipContainer(child: Text('Seed the server scope directly')), + child: IconButton.ghost( + icon: const Icon(Icons.add, size: 16), + onPressed: enabled ? () => _open(context) : null, + ), + ); + } + + void _open(BuildContext context) { + showDropdown( + context: context, + builder: (context) => DropdownMenu( + children: [ + MenuButton( + leading: const Icon(Icons.account_tree, size: 16), + onPressed: (_) => unawaited(controller.seedServer('basicGraph')), + child: const Text('Seed graph'), + ), + MenuButton( + leading: const Icon(Icons.data_object, size: 16), + onPressed: (_) => unawaited(controller.seedServer('typedRow')), + child: const Text('Seed typed row'), + ), + MenuButton( + leading: const Icon(Icons.hub, size: 16), + onPressed: (_) => unawaited(controller.seedServer('fkChain')), + child: const Text('Seed FK chain'), + ), + ], + ), + ); + } +} + +class _Badge extends StatelessWidget { + const _Badge({ + required this.text, + required this.background, + required this.foreground, + this.tooltip, + this.compact = false, + }); + + final String text; + final Color background; + final Color foreground; + final String? tooltip; + final bool compact; + + @override + Widget build(BuildContext context) { + final badge = Container( + padding: compact + ? const EdgeInsets.symmetric(horizontal: 6, vertical: 1) + : const EdgeInsets.symmetric(horizontal: 8, vertical: 2), + decoration: BoxDecoration( + color: background, + borderRadius: BorderRadius.circular(6), + ), + child: Text( + text, + style: TextStyle(color: foreground, fontSize: compact ? 10 : 11), + ), + ); + final message = tooltip; + return message == null + ? badge + : Tooltip( + tooltip: (context) => TooltipContainer(child: Text(message)), + child: badge, + ); + } +} + +class _ServerBadge extends StatelessWidget { + const _ServerBadge({required this.controller}); + + final DemoController controller; + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + final state = controller.server; + + String label; + Color bg; + Color fg; + if (!controller.online) { + label = 'offline'; + bg = scheme.muted; + fg = scheme.mutedForeground; + } else if (state.busy || state.loading) { + label = 'loading'; + bg = scheme.primary; + fg = scheme.primaryForeground; + } else if (state.error != null) { + label = 'error'; + bg = scheme.destructive; + fg = Colors.white; + } else { + label = state.lastFetchedLabel ?? 'idle'; + bg = scheme.muted; + fg = scheme.mutedForeground; + } + + return _Badge( + text: label, + background: bg, + foreground: fg, + tooltip: state.error ?? label, + ); + } +} + +class _SyncBadge extends StatelessWidget { + const _SyncBadge({required this.state}); + + final ReplicaState state; + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + final failed = state.phase == SyncPhase.failed; + final active = + state.busy || + state.phase == SyncPhase.syncing || + state.phase == SyncPhase.streaming; + final bg = failed + ? scheme.destructive + : active + ? scheme.primary + : scheme.muted; + final fg = failed + ? Colors.white + : active + ? scheme.primaryForeground + : scheme.mutedForeground; + final label = state.busy && state.phase == SyncPhase.idle + ? 'Working' + : state.lastSyncedLabel != null && state.phase == SyncPhase.idle + ? state.lastSyncedLabel! + : state.phase.label; + return _Badge( + text: label, + background: bg, + foreground: fg, + tooltip: state.error ?? label, + ); + } +} + +/// Centered loading indicator shown in a panel body while the local databases +/// are still opening (during [DemoController.initializing]). +class _PanelLoading extends StatelessWidget { + const _PanelLoading({required this.message}); + + final String message; + + @override + Widget build(BuildContext context) { + return Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const SizedBox( + width: 20, + height: 20, + child: CircularProgressIndicator(), + ), + const Gap(10), + Text(message).small().muted(), + ], + ), + ); + } +} + +// --- Tree ------------------------------------------------------------------ + +class _ProjectionTree extends StatefulWidget { + const _ProjectionTree({ + super.key, + required this.nodes, + this.onTapRow, + this.actions, + }); + + final List> nodes; + final void Function(DemoRowRef ref)? onTapRow; + final _RowActions? actions; + + @override + State<_ProjectionTree> createState() => _ProjectionTreeState(); +} + +class _ProjectionTreeState extends State<_ProjectionTree> { + late List> nodes; + + @override + void initState() { + super.initState(); + nodes = widget.nodes; + } + + @override + void didUpdateWidget(covariant _ProjectionTree oldWidget) { + super.didUpdateWidget(oldWidget); + if (!identical(oldWidget.nodes, widget.nodes)) { + nodes = widget.nodes; + } + } + + @override + Widget build(BuildContext context) { + if (nodes.isEmpty) { + return const Center(child: Text('No rows yet.')); + } + final onTapRow = widget.onTapRow; + + return TreeView( + nodes: nodes, + expandIcon: true, + branchLine: BranchLine.path, + builder: (context, node) { + return _DemoTreeItemView( + node: node, + actions: widget.actions, + onTapRow: onTapRow, + onExpand: TreeView.defaultItemExpandHandler(nodes, node, (value) { + setState(() => nodes = value); + }), + ); + }, + ); + } +} + +class _DemoTreeItemView extends StatefulWidget { + const _DemoTreeItemView({ + required this.node, + required this.onExpand, + required this.onTapRow, + required this.actions, + }); + + final TreeItem node; + final ValueChanged onExpand; + final void Function(DemoRowRef ref)? onTapRow; + final _RowActions? actions; + + @override + State<_DemoTreeItemView> createState() => _DemoTreeItemViewState(); +} + +class _DemoTreeItemViewState extends State<_DemoTreeItemView> { + late final FocusNode _focusNode; + bool _hovered = false; + + @override + void initState() { + super.initState(); + _focusNode = FocusNode(canRequestFocus: false, skipTraversal: true); + } + + @override + void dispose() { + _focusNode.dispose(); + super.dispose(); + } + + void _handlePressed() { + final ref = widget.node.data.ref; + final onTapRow = widget.onTapRow; + if (ref != null && onTapRow != null) { + onTapRow(ref); + return; + } + + if (widget.node.children.isNotEmpty) { + widget.onExpand(!widget.node.expanded); + } + } + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + final item = widget.node.data; + final ref = item.ref; + final selectable = ref != null && widget.onTapRow != null; + final expandable = widget.node.children.isNotEmpty; + final interactive = selectable || expandable; + final showActions = widget.actions != null && ref != null && !item.metadata; + + return MouseRegion( + cursor: interactive ? SystemMouseCursors.click : SystemMouseCursors.basic, + onEnter: (_) => setState(() => _hovered = true), + onExit: (_) => setState(() => _hovered = false), + child: Container( + decoration: BoxDecoration( + color: _hovered ? scheme.muted : Colors.transparent, + borderRadius: BorderRadius.circular(6), + ), + child: TreeItemView( + focusNode: _focusNode, + leading: Icon( + item.icon, + size: 14, + color: item.hidden ? scheme.mutedForeground : null, + ), + onExpand: widget.onExpand, + onPressed: interactive ? _handlePressed : null, + trailing: showActions + ? _RowActionBar(actions: widget.actions!, ref: ref) + : null, + child: Row( + children: [ + Flexible( + child: Text( + item.title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 13, + fontWeight: item.metadata + ? FontWeight.normal + : FontWeight.w500, + color: item.hidden + ? scheme.mutedForeground + : scheme.foreground, + decoration: item.hidden ? TextDecoration.lineThrough : null, + ), + ), + ), + if (item.detail != null) + Flexible( + child: Padding( + padding: const EdgeInsets.only(left: 8), + child: Text( + item.detail!, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 11, + color: scheme.mutedForeground, + ), + ), + ), + ), + if (item.relation != null) ...[ + const Gap(6), + _FkBadge(relation: item.relation!), + ], + if (item.dangling) ...[const Gap(6), _DanglingBadge()], + ], + ), + ), + ), + ); + } +} + +class _FkBadge extends StatelessWidget { + const _FkBadge({required this.relation}); + + final Relationship relation; + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + final (bg, fg) = _actionColors(scheme, relation.onDelete); + return _Badge( + text: '${relationLabel(relation.fkColumn)} · ${relation.onDelete.label}', + background: bg, + foreground: fg, + compact: true, + tooltip: + '${relationLabel(relation.fkColumn)} → ${tableLabel(relation.parentTable)} ' + '· ${relation.onDelete.label} (${relation.onDelete.summary})', + ); + } +} + +class _DanglingBadge extends StatelessWidget { + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + return _Badge( + text: 'dangling', + background: scheme.muted, + foreground: scheme.mutedForeground, + compact: true, + tooltip: 'Foreign key points at a row not present here.', + ); + } +} + +(Color, Color) _actionColors(ColorScheme scheme, FkAction action) { + return switch (action) { + FkAction.restrict => (scheme.destructive, Colors.white), + FkAction.cascade => (const Color(0xFFB45309), Colors.white), + FkAction.setNull || + FkAction.setDefault => (scheme.primary, scheme.primaryForeground), + FkAction.noAction => (scheme.muted, scheme.mutedForeground), + }; +} + +class _RowActionBar extends StatelessWidget { + const _RowActionBar({required this.actions, required this.ref}); + + final _RowActions actions; + final DemoRowRef ref; + + @override + Widget build(BuildContext context) { + final controller = actions.controller; + final children = controller.catalog.childRelationshipsOf(ref.tableName); + final parents = controller.catalog.parentRelationshipsOf(ref.tableName); + final busy = controller.replicaBusy(actions.slot); + + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (children.isNotEmpty) + _ActionIcon( + icon: Icons.add, + tooltip: 'Attach a child', + onTap: busy ? null : () => _openAddChild(context, children), + ), + if (parents.isNotEmpty) + _ActionIcon( + icon: Icons.drive_file_move_outline, + tooltip: 'Re-parent or detach', + onTap: busy ? null : () => _openMove(context, parents), + ), + ], + ); + } + + void _openAddChild(BuildContext context, List children) { + showDropdown( + context: context, + builder: (context) => DropdownMenu( + children: [ + for (final relation in children) + MenuButton( + leading: Icon( + iconForTable(relation.childTable, hidden: false), + size: 16, + ), + trailing: _MiniActionTag(action: relation.onDelete), + onPressed: (_) => unawaited( + actions.controller.createChildFor(actions.slot, ref, relation), + ), + child: Text( + '${tableLabel(relation.childTable)} · ' + '${relationLabel(relation.fkColumn)}', + ), + ), + ], + ), + ); + } + + void _openMove(BuildContext context, List parents) { + if (parents.length == 1) { + _openParentPicker(context, parents.single); + return; + } + showDropdown( + context: context, + builder: (context) => DropdownMenu( + children: [ + for (final relation in parents) + MenuButton( + trailing: _MiniActionTag(action: relation.onDelete), + onPressed: (_) => _openParentPicker(context, relation), + child: Text( + '${relationLabel(relation.fkColumn)} → ' + '${tableLabel(relation.parentTable)}', + ), + ), + ], + ), + ); + } + + void _openParentPicker(BuildContext context, Relationship relation) { + final controller = actions.controller; + final options = controller + .parentOptions(actions.slot, relation.parentTable) + .where((option) => option.ref.id.uuid != ref.id.uuid) + .toList(); + + showDropdown( + context: context, + builder: (context) => DropdownMenu( + children: [ + MenuButton( + leading: const Icon(Icons.link_off, size: 16), + onPressed: (_) => unawaited( + controller.reParent(actions.slot, ref, relation.fkColumn, null), + ), + child: const Text('Detach (null)'), + ), + for (final option in options) + MenuButton( + leading: Icon( + iconForTable(relation.parentTable, hidden: !option.visible), + size: 16, + ), + onPressed: (_) => unawaited( + controller.reParent( + actions.slot, + ref, + relation.fkColumn, + option.ref.id, + ), + ), + child: Text(option.label), + ), + ], + ), + ); + } +} + +class _ActionIcon extends StatelessWidget { + const _ActionIcon({ + required this.icon, + required this.tooltip, + required this.onTap, + }); + + final IconData icon; + final String tooltip; + final VoidCallback? onTap; + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + final color = onTap == null + ? scheme.mutedForeground.withAlpha(110) + : scheme.mutedForeground; + return Tooltip( + tooltip: (context) => TooltipContainer(child: Text(tooltip)), + child: MouseRegion( + cursor: onTap == null + ? SystemMouseCursors.basic + : SystemMouseCursors.click, + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: onTap, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 3), + child: Icon(icon, size: 15, color: color), + ), + ), + ), + ); + } +} + +class _MiniActionTag extends StatelessWidget { + const _MiniActionTag({required this.action}); + + final FkAction action; + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + final (bg, fg) = _actionColors(scheme, action); + return _Badge( + text: action.label, + background: bg, + foreground: fg, + compact: true, + ); + } +} + +class _StatusBar extends StatelessWidget { + const _StatusBar({required this.controller}); + + final DemoController controller; + + @override + Widget build(BuildContext context) { + return AnimatedBuilder( + animation: controller, + builder: (context, _) => OutlinedContainer( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), + child: Row( + children: [ + Icon(controller.online ? Icons.wifi : Icons.wifi_off, size: 18), + const Gap(8), + Expanded(child: Text(controller.status)), + if (controller.anyBusy) + const SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator(), + ), + ], + ), + ), + ); + } +} + +/// Top-bar action that flips the app between light and dark themes. +class ThemeToggleButton extends StatelessWidget { + const ThemeToggleButton({ + super.key, + required this.isDark, + required this.onToggle, + }); + + final bool isDark; + final VoidCallback onToggle; + + @override + Widget build(BuildContext context) { + return IconButton.ghost( + icon: Icon(isDark ? Icons.light_mode : Icons.dark_mode, size: 18), + onPressed: onToggle, + ); + } +} + +/// Top-bar avatar that switches between demo users and creates new ones. +class UserAvatarMenu extends StatelessWidget { + const UserAvatarMenu({super.key, required this.controller}); + + final DemoController controller; + + @override + Widget build(BuildContext context) { + return AnimatedBuilder( + animation: controller, + builder: (context, _) { + final user = controller.selectedUser; + return GhostButton( + onPressed: controller.anyBusy ? null : () => _open(context), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Avatar(initials: user?.initials ?? '?', size: 28), + const Gap(8), + Text(user?.username ?? 'no user'), + const Gap(2), + const Icon(Icons.arrow_drop_down, size: 18), + ], + ), + ); + }, + ); + } + + void _open(BuildContext context) { + showDropdown( + context: context, + builder: (context) => DropdownMenu( + children: [ + for (final user in controller.users) + MenuButton( + leading: Avatar(initials: user.initials, size: 20), + onPressed: (_) => unawaited(controller.switchUser(user)), + child: Text(user.username), + ), + MenuButton( + leading: const Icon(Icons.person_add, size: 16), + onPressed: (_) => + unawaited(showCreateUserSheet(context, controller)), + child: const Text('Create user…'), + ), + ], + ), + ); + } +} diff --git a/example/offline_sync_demo/lib/src/models.dart b/example/offline_sync_demo/lib/src/models.dart new file mode 100644 index 0000000..1e8d3ec --- /dev/null +++ b/example/offline_sync_demo/lib/src/models.dart @@ -0,0 +1,121 @@ +import 'package:http/http.dart' as http; +import 'package:serverpod_offline_sync_test_client/serverpod_offline_sync_test_client.dart' + as protocol; +import 'package:uuid/uuid.dart' as uuid; + +/// One of the two independent local replicas held side by side. +enum ReplicaSlot { + a('Replica A'), + b('Replica B'); + + const ReplicaSlot(this.label); + + /// Human readable name shown in the UI. + final String label; +} + +/// A demo user backed by a deterministic auth-user id. +class DemoUser { + DemoUser({ + required this.username, + required this.authUserId, + required this.token, + }); + + final String username; + protocol.UuidValue authUserId; + String token; + + /// Up to two uppercase initials for the avatar. + String get initials { + final trimmed = username.trim(); + if (trimmed.isEmpty) return '?'; + return trimmed.substring(0, trimmed.length >= 2 ? 2 : 1).toUpperCase(); + } +} + +/// Identifies a domain row by its demo table name and UUID. +class DemoRowRef { + const DemoRowRef({required this.tableName, required this.id}); + + final String tableName; + final protocol.UuidValue id; +} + +/// Stores the current demo bearer token for outgoing requests. +class DemoAuthKeyProvider implements protocol.ClientAuthKeyProvider { + String? token; + + @override + Future get authHeaderValue async { + final value = token; + if (value == null) return null; + return 'Bearer $value'; + } +} + +/// HTTP client that fails every request, simulating an offline device. +class OfflineHttpClient extends http.BaseClient { + @override + Future send(http.BaseRequest request) { + throw http.ClientException( + 'Connectivity is disabled by the demo httpClientOverride.', + request.url, + ); + } +} + +/// Monotonic counter used to label seeded rows per scenario. +class ScenarioCounter { + final _values = {}; + + int next(String key) { + final value = (_values[key] ?? 0) + 1; + _values[key] = value; + return value; + } +} + +/// Normalizes a demo username so the same person maps to one scope. +String normalizeUsername(String username) { + return username.trim().toLowerCase(); +} + +/// Deterministic auth-user id for [username], matching the server algorithm. +protocol.UuidValue demoAuthUserIdForUsername(String username) { + final id = const uuid.Uuid().v5( + uuid.Namespace.url.value, + 'serverpod-offline-sync/demo-user/${normalizeUsername(username)}', + ); + return protocol.UuidValue.withValidation(id); +} + +/// Bearer token accepted by the demo authentication handler. +String demoTokenForAuthUserId(protocol.UuidValue authUserId) { + return 'offline-sync-demo:${authUserId.uuid}'; +} + +/// Extracts the auth-user id from a demo bearer [token]. +protocol.UuidValue authUserIdFromToken(String token) { + const prefix = 'offline-sync-demo:'; + if (!token.startsWith(prefix)) { + throw FormatException('Unexpected demo auth token.', token); + } + return protocol.UuidValue.withValidation(token.substring(prefix.length)); +} + +/// Builds a fresh time-ordered UUID for a new row. +protocol.UuidValue newId() { + return const protocol.Uuid().v7obj(); +} + +/// Short 8-character form of a UUID for compact display. +/// +/// Uses the last 8 characters so v7 UUIDs show the random suffix rather than +/// the timestamp prefix. +String shortId(protocol.UuidValue? value) { + if (value == null) return 'null'; + final uuid = value.uuid; + if (uuid.length <= 8) return uuid; + return uuid.substring(uuid.length - 8); +} diff --git a/example/offline_sync_demo/lib/src/offline_replica.dart b/example/offline_sync_demo/lib/src/offline_replica.dart new file mode 100644 index 0000000..364af6b --- /dev/null +++ b/example/offline_sync_demo/lib/src/offline_replica.dart @@ -0,0 +1,126 @@ +import 'package:flutter/foundation.dart' show kDebugMode; +import 'package:serverpod_database/serverpod_database.dart' + show ClientDatabaseSession; +import 'package:serverpod_offline_sync_client/serverpod_offline_sync_client.dart'; +import 'package:serverpod_offline_sync_test_client/serverpod_offline_sync_test_client.dart'; + +import 'table_ops.dart' show demoSyncTables; + +/// One local replica: a Serverpod client database wrapped with the +/// `serverpod_offline_sync` CRDT layer, plus the calls that synchronize it. +/// +/// This class is the entire surface a real integration needs — read it first to +/// understand the package. The four steps are: +/// +/// 1. [open] opens a local SQLite database ([Client.createSession]) +/// and wraps it in a [CrdtDatabaseSession]. The rest of the app +/// reads and writes generated models through [session]. +/// 2. CRUD happens against [session] with the generated model APIs (see +/// the `seed*` methods in `DemoController` for the plain, recommended form, +/// e.g. `Person.db.insertRow(crdtSession, person)`). +/// 3. [syncOnce] / [syncContinuously] push local changes and merge remote +/// ones through a Serverpod [Client]. +/// 4. [reset] / [close] tear the replica down. +/// +/// It deliberately holds **no UI state**: the demo's `DemoController` layers +/// busy/error/projection bookkeeping on top of these calls so that this file +/// stays a clean reference for the package itself. +class OfflineReplica { + OfflineReplica._(this._rawSession, this.session, this.persistentUserId); + + /// Owns the underlying SQLite connection; closed by [close]. + final ClientDatabaseSession _rawSession; + + /// CRDT-aware session used for every model read and write. By default it only + /// exposes visible (non-tombstoned) rows; queries opt into hidden rows with + /// the `includeHiddenRows` where-clause. + final CrdtDatabaseSession session; + + /// The signed-in user every local write on this replica is attributed to. + final UuidValue persistentUserId; + + /// Opens [databasePath] through [client] and wraps it for CRDT sync. + /// + /// [Client.createSession] opens the local client database (running + /// client migrations); [CrdtDatabaseSession.wraps] layers CRDT + /// tracking over it; and `db.initialize()` establishes this device's CRDT + /// node so it can take part in sync. + static Future open({ + required Client client, + required String databasePath, + required UuidValue persistentUserId, + }) async { + final rawSession = await client.createSession( + databasePath, + isDebugMode: kDebugMode, + ); + final crdtSession = CrdtDatabaseSession.wraps( + rawSession, + syncTables: demoSyncTables, + persistentUserId: persistentUserId, + ); + await crdtSession.db.initialize(); + return OfflineReplica._(rawSession, crdtSession, persistentUserId); + } + + /// Pushes local pending changes through [client] and merges remote ones once. + /// + /// Connectivity is expressed entirely by [client]: pass an online client to + /// reach the server, an offline one (failing transport) to simulate no + /// network. The replica's local database is the same either way. + Future syncOnce( + Client client, { + CrdtSyncOnMergeSuccess? onMergeSuccess, + }) { + return client.crdt.syncOnce(session, onMergeSuccess: onMergeSuccess); + } + + /// Streams changes through [client] until the returned session is cancelled + /// (via [CrdtSyncSession.cancel]) or the remote stream closes. + CrdtSyncSession syncContinuously( + Client client, { + CrdtSyncOnMergeSuccess? onMergeSuccess, + }) { + return client.crdt.syncContinuously( + session, + onMergeSuccess: onMergeSuccess, + ); + } + + /// Wipes this replica back to an empty device by deleting its local CRDT + /// scope row. Every synced table cascades on `scopeId` -> `crdt_scopes`, so + /// the domain rows and CRDT metadata go with it — no need to drop and recreate + /// the database file. A fresh scope/node is established lazily on the next + /// write. + /// + /// The delete runs with `defer_foreign_keys` on: the scopeId cascade fans out + /// across the CRDT metadata diamond (`crdt_data_rows`/`crdt_data_fields`/ + /// `crdt_data_tombstone` reference `crdt_nodes` with NO ACTION while both + /// sides cascade off `crdt_scopes`), and SQLite's cascade order can + /// transiently violate those immediate checks. Deferring them to commit lets + /// the whole cascade complete first. + Future reset() async { + final scope = await CrdtScope.db.findFirstRow( + session, + where: (t) => t.uuidScopeId.equals(persistentUserId), + ); + final scopeId = scope?.id; + if (scopeId != null) { + await session.db.transaction((transaction) async { + await session.db.unsafeExecute( + 'PRAGMA defer_foreign_keys = ON', + transaction: transaction, + ); + await CrdtScope.db.deleteWhere( + session, + where: (t) => t.id.equals(scopeId), + transaction: transaction, + ); + }); + } + await session.db.initialize(); + } + + /// Closes the underlying database connection. + Future close() => _rawSession.close(); +} diff --git a/example/offline_sync_demo/lib/src/relationships.dart b/example/offline_sync_demo/lib/src/relationships.dart new file mode 100644 index 0000000..04ce491 --- /dev/null +++ b/example/offline_sync_demo/lib/src/relationships.dart @@ -0,0 +1,188 @@ +import 'package:serverpod_database/serverpod_database.dart' + show ColumnType, ForeignKeyAction, TableDefinition, TableRow; +import 'package:serverpod_offline_sync_test_client/serverpod_offline_sync_test_client.dart' + as protocol; + +import 'models.dart'; +import 'table_ops.dart'; + +/// The referential action a foreign key takes when its parent is deleted. +/// +/// This is the whole point of the FK-conflict demo, so it is surfaced directly +/// on every relationship edge. +enum FkAction { + restrict('Restrict', 'blocks the delete'), + cascade('Cascade', 'deletes children'), + setNull('SetNull', 'nulls the reference'), + setDefault('SetDefault', 'resets to default'), + noAction('NoAction', 'no enforced action'); + + const FkAction(this.label, this.summary); + + final String label; + final String summary; + + static FkAction from(ForeignKeyAction? action) => switch (action) { + ForeignKeyAction.cascade => FkAction.cascade, + ForeignKeyAction.restrict => FkAction.restrict, + ForeignKeyAction.setNull => FkAction.setNull, + ForeignKeyAction.setDefault => FkAction.setDefault, + _ => FkAction.noAction, + }; +} + +/// A single foreign-key edge: [childTable].[fkColumn] → [parentTable], with the +/// [onDelete] action that fires when the parent row is removed. +class Relationship { + Relationship({ + required this.childTable, + required this.fkColumn, + required this.parentTable, + required this.onDelete, + }); + + final String childTable; + final String fkColumn; + final String parentTable; + final FkAction onDelete; +} + +/// Metadata-driven view of the synced schema. +/// +/// Everything here is computed once from [protocol.Protocol.targetTableDefinitions] +/// (the same table definitions the client already ships), so the relationship +/// menus and edge badges stay in sync with the generated model. +class RelationshipCatalog { + RelationshipCatalog._(this._byName, this._inbound, this._outbound); + + final Map _byName; + final Map> _inbound; + final Map> _outbound; + + static RelationshipCatalog build(Set syncedTables) { + final byName = { + for (final table in protocol.Protocol.targetTableDefinitions) + if (syncedTables.contains(table.name)) table.name: table, + }; + + final outbound = >{}; + final inbound = >{}; + for (final table in byName.values) { + outbound[table.name] = []; + inbound.putIfAbsent(table.name, () => []); + } + + for (final table in byName.values) { + for (final fk in table.foreignKeys) { + // Only simple, user-visible relationships: single column, not one of + // the generated `_relationBackref` columns, and pointing at a table we + // actually render. + if (fk.columns.length != 1) continue; + final column = fk.columns.single; + if (column.startsWith('_')) continue; + if (!byName.containsKey(fk.referenceTable)) continue; + + final relationship = Relationship( + childTable: table.name, + fkColumn: column, + parentTable: fk.referenceTable, + onDelete: FkAction.from(fk.onDelete), + ); + outbound[table.name]!.add(relationship); + inbound[fk.referenceTable]!.add(relationship); + } + } + + return RelationshipCatalog._(byName, inbound, outbound); + } + + Iterable get tables => _byName.keys; + + /// Relationships whose parent is [table] — i.e. the kinds of child rows that + /// can be attached to it. Drives the "+ child" menu. + List childRelationshipsOf(String table) => + _inbound[table] ?? const []; + + /// This table's own foreign keys — the references that can be re-pointed or + /// detached. Drives the "move" picker and tree nesting. + List parentRelationshipsOf(String table) => + _outbound[table] ?? const []; + + /// Tables listed in the "Add data" menu, as declared by + /// [demoTableOps.canCreateRoot]. + List get creatableRootTables { + final result = []; + for (final table in _byName.keys) { + if (demoTableOps[table]?.canCreateRoot ?? false) result.add(table); + } + result.sort(); + return result; + } + + /// The column used as a row's human label (e.g. `name`, `street`, `value`). + String displayColumn(String table) { + final definition = _byName[table]; + if (definition == null) return 'id'; + const preferred = ['name', 'street', 'aText', 'value', 'title', 'label']; + for (final candidate in preferred) { + if (definition.columns.any((c) => c.name == candidate)) return candidate; + } + for (final column in definition.columns) { + if (_isSystemColumn(column.name)) continue; + if (column.columnType == ColumnType.text) return column.name; + } + for (final column in definition.columns) { + if (_isSystemColumn(column.name)) continue; + if (column.columnType == ColumnType.uuid) return column.name; + } + return 'id'; + } + + /// A short human label for [row]. + String displayLabel(TableRow row) { + final table = row.table.tableName; + final json = row.toJson() as Map; + final column = displayColumn(table); + final value = json[column]; + if (value == null) return '(${shortId(row.id)})'; + final definition = _byName[table]; + final isUuid = + definition?.columns + .firstWhere( + (c) => c.name == column, + orElse: () => definition.columns.first, + ) + .columnType == + ColumnType.uuid; + if (isUuid && value is protocol.UuidValue) return shortId(value); + final text = '$value'; + if (isUuid && text.length >= 8) return text.substring(text.length - 8); + return text; + } + + /// Builds a generated row for [table], optionally assigning one foreign key. + /// Required fields and defaults remain owned by the generated constructors. + TableRow? buildRow( + String table, { + String? fkColumn, + protocol.UuidValue? fkValue, + String? label, + }) { + final create = demoTableOps[table]?.create; + if (create == null) return null; + return create(newId(), label ?? _defaultLabel(table), { + if (fkColumn != null && fkValue != null) fkColumn: fkValue, + }); + } + + String _defaultLabel(String table) { + final words = table.split('_').map((w) { + if (w.isEmpty) return w; + return '${w[0].toUpperCase()}${w.substring(1)}'; + }); + return words.join(' '); + } + + static bool _isSystemColumn(String name) => + name == 'id' || name == 'scopeId' || name.startsWith('_'); +} diff --git a/example/offline_sync_demo/lib/src/scenarios.dart b/example/offline_sync_demo/lib/src/scenarios.dart new file mode 100644 index 0000000..afd6301 --- /dev/null +++ b/example/offline_sync_demo/lib/src/scenarios.dart @@ -0,0 +1,640 @@ +part of 'demo_controller.dart'; + +/// One step of a guided scenario, bound to a concrete replica and rows. +class ScenarioStep { + ScenarioStep(this.label, this.run, {this.replica}); + + final String label; + final ReplicaSlot? replica; + final Future Function() run; +} + +/// A guided, stateful recipe that scripts the free-form primitives. Optional — +/// every step it runs can also be done by hand directly on the tree. +class Scenario { + Scenario({required this.title, required this.summary, required this.build}); + + final String title; + final String summary; + final List Function(DemoController controller) build; +} + +extension on DemoController { + List _buildScenarios() { + Relationship? childRelation(String parent, String child) { + for (final relation in catalog.childRelationshipsOf(parent)) { + if (relation.childTable == child) return relation; + } + return null; + } + + return [ + Scenario( + title: 'Restrict blocks delete', + summary: + 'A Restrict child added on B blocks the parent delete made on A.', + build: (c) { + final ctx = {}; + final relation = childRelation('person', 'restrict_child'); + return [ + ScenarioStep( + 'Seed parent Person on A', + replica: ReplicaSlot.a, + () async => ctx['parent'] = await c.createRoot( + ReplicaSlot.a, + 'person', + label: 'Restricted parent', + ), + ), + ScenarioStep( + 'Sync A → server', + () => c.syncReplica(ReplicaSlot.a), + replica: ReplicaSlot.a, + ), + ScenarioStep( + 'Sync B ← server', + () => c.syncReplica(ReplicaSlot.b), + replica: ReplicaSlot.b, + ), + ScenarioStep( + 'Attach Restrict child on B', + replica: ReplicaSlot.b, + () async { + final parent = ctx['parent']; + if (parent != null && relation != null) { + await c.createChildFor(ReplicaSlot.b, parent, relation); + } + }, + ), + ScenarioStep( + 'Delete parent on A', + replica: ReplicaSlot.a, + () async { + final parent = ctx['parent']; + if (parent != null) await c.deleteRow(parent, ReplicaSlot.a); + }, + ), + ScenarioStep( + 'Sync A → server', + () => c.syncReplica(ReplicaSlot.a), + replica: ReplicaSlot.a, + ), + ScenarioStep( + 'Sync B ← server', + () => c.syncReplica(ReplicaSlot.b), + replica: ReplicaSlot.b, + ), + ScenarioStep( + 'Sync A ← server (converge)', + () => c.syncReplica(ReplicaSlot.a), + replica: ReplicaSlot.a, + ), + ]; + }, + ), + Scenario( + title: 'SetNull projection', + summary: + 'A Town mayor reference on B is nulled when the mayor is deleted on A.', + build: (c) { + final ctx = {}; + final relation = childRelation('person', 'town'); + return [ + ScenarioStep( + 'Seed mayor Person on A', + replica: ReplicaSlot.a, + () async => ctx['mayor'] = await c.createRoot( + ReplicaSlot.a, + 'person', + label: 'Mayor candidate', + ), + ), + ScenarioStep( + 'Sync A → server', + () => c.syncReplica(ReplicaSlot.a), + replica: ReplicaSlot.a, + ), + ScenarioStep( + 'Sync B ← server', + () => c.syncReplica(ReplicaSlot.b), + replica: ReplicaSlot.b, + ), + ScenarioStep( + 'Add Town with that mayor on B', + replica: ReplicaSlot.b, + () async { + final mayor = ctx['mayor']; + if (mayor != null && relation != null) { + await c.createChildFor(ReplicaSlot.b, mayor, relation); + } + }, + ), + ScenarioStep('Delete mayor on A', replica: ReplicaSlot.a, () async { + final mayor = ctx['mayor']; + if (mayor != null) await c.deleteRow(mayor, ReplicaSlot.a); + }), + ScenarioStep( + 'Sync A → server', + () => c.syncReplica(ReplicaSlot.a), + replica: ReplicaSlot.a, + ), + ScenarioStep( + 'Sync B ← server', + () => c.syncReplica(ReplicaSlot.b), + replica: ReplicaSlot.b, + ), + ScenarioStep( + 'Sync A ← server (converge)', + () => c.syncReplica(ReplicaSlot.a), + replica: ReplicaSlot.a, + ), + ]; + }, + ), + Scenario( + title: 'Cascade hides children', + summary: + 'Deleting an Organization on A cascade-hides the Person attached on B.', + build: (c) { + final ctx = {}; + final relation = childRelation('organization', 'person'); + return [ + ScenarioStep( + 'Seed Organization on A', + replica: ReplicaSlot.a, + () async => ctx['org'] = await c.createRoot( + ReplicaSlot.a, + 'organization', + label: 'Cascade org', + ), + ), + ScenarioStep( + 'Sync A → server', + () => c.syncReplica(ReplicaSlot.a), + replica: ReplicaSlot.a, + ), + ScenarioStep( + 'Sync B ← server', + () => c.syncReplica(ReplicaSlot.b), + replica: ReplicaSlot.b, + ), + ScenarioStep( + 'Attach Person to org on B', + replica: ReplicaSlot.b, + () async { + final org = ctx['org']; + if (org != null && relation != null) { + await c.createChildFor(ReplicaSlot.b, org, relation); + } + }, + ), + ScenarioStep('Delete org on A', replica: ReplicaSlot.a, () async { + final org = ctx['org']; + if (org != null) await c.deleteRow(org, ReplicaSlot.a); + }), + ScenarioStep( + 'Sync A → server', + () => c.syncReplica(ReplicaSlot.a), + replica: ReplicaSlot.a, + ), + ScenarioStep( + 'Sync B ← server', + () => c.syncReplica(ReplicaSlot.b), + replica: ReplicaSlot.b, + ), + ScenarioStep( + 'Sync A ← server (converge)', + () => c.syncReplica(ReplicaSlot.a), + replica: ReplicaSlot.a, + ), + ]; + }, + ), + Scenario( + title: 'Concurrent unique insert', + summary: + 'Both replicas insert a Unique row with the same name; one loses on merge.', + build: (c) { + final name = 'shared-${c._counter.next('unique')}'; + return [ + ScenarioStep( + 'Insert Unique "$name" on A', + replica: ReplicaSlot.a, + () => c.createUnique(ReplicaSlot.a, name), + ), + ScenarioStep( + 'Insert Unique "$name" on B', + replica: ReplicaSlot.b, + () => c.createUnique(ReplicaSlot.b, name), + ), + ScenarioStep( + 'Sync A → server', + () => c.syncReplica(ReplicaSlot.a), + replica: ReplicaSlot.a, + ), + ScenarioStep( + 'Sync B → server (conflict resolves)', + () => c.syncReplica(ReplicaSlot.b), + replica: ReplicaSlot.b, + ), + ScenarioStep( + 'Sync A ← server (converge)', + () => c.syncReplica(ReplicaSlot.a), + replica: ReplicaSlot.a, + ), + ]; + }, + ), + Scenario( + title: 'Concurrent field edits', + summary: + 'A and B edit different Person columns offline; both values survive merge.', + build: (c) { + final ctx = {}; + return [ + ScenarioStep( + 'Seed Person on A', + replica: ReplicaSlot.a, + () async => ctx['person'] = await c.createRoot( + ReplicaSlot.a, + 'person', + label: 'Conflict person', + ), + ), + ScenarioStep( + 'Sync A → server', + () => c.syncReplica(ReplicaSlot.a), + replica: ReplicaSlot.a, + ), + ScenarioStep( + 'Sync B ← server', + () => c.syncReplica(ReplicaSlot.b), + replica: ReplicaSlot.b, + ), + ScenarioStep('Edit name on A', replica: ReplicaSlot.a, () async { + final person = ctx['person']; + if (person != null) { + await c.updateRowFields(person, ReplicaSlot.a, { + 'name': 'Name from A', + }); + } + }), + ScenarioStep('Edit surname on B', replica: ReplicaSlot.b, () async { + final person = ctx['person']; + if (person != null) { + await c.updateRowFields(person, ReplicaSlot.b, { + 'surname': 'Surname from B', + }); + } + }), + ScenarioStep( + 'Sync A → server', + () => c.syncReplica(ReplicaSlot.a), + replica: ReplicaSlot.a, + ), + ScenarioStep( + 'Sync B → server', + () => c.syncReplica(ReplicaSlot.b), + replica: ReplicaSlot.b, + ), + ScenarioStep( + 'Sync A ← server (converge)', + () => c.syncReplica(ReplicaSlot.a), + replica: ReplicaSlot.a, + ), + ]; + }, + ), + Scenario( + title: 'Unique update conflict', + summary: + 'Two Unique rows are renamed to the same value; the older claim keeps it.', + build: (c) { + final ctx = {}; + final shared = 'shared-${c._counter.next('unique-update')}'; + return [ + ScenarioStep( + 'Insert Unique "first" on A', + replica: ReplicaSlot.a, + () async => ctx['first'] = await c.createUnique( + ReplicaSlot.a, + 'first-$shared', + ), + ), + ScenarioStep( + 'Insert Unique "second" on A', + replica: ReplicaSlot.a, + () async => ctx['second'] = await c.createUnique( + ReplicaSlot.a, + 'second-$shared', + ), + ), + ScenarioStep( + 'Sync A → server', + () => c.syncReplica(ReplicaSlot.a), + replica: ReplicaSlot.a, + ), + ScenarioStep( + 'Sync B ← server', + () => c.syncReplica(ReplicaSlot.b), + replica: ReplicaSlot.b, + ), + ScenarioStep( + 'Rename "first" to "$shared" on A', + replica: ReplicaSlot.a, + () async { + final first = ctx['first']; + if (first != null) { + await c.updateRowFields(first, ReplicaSlot.a, { + 'name': shared, + }); + } + }, + ), + ScenarioStep( + 'Rename "second" to "$shared" on B', + replica: ReplicaSlot.b, + () async { + final second = ctx['second']; + if (second != null) { + await c.updateRowFields(second, ReplicaSlot.b, { + 'name': shared, + }); + } + }, + ), + ScenarioStep( + 'Sync B → server (newer update first)', + () => c.syncReplica(ReplicaSlot.b), + replica: ReplicaSlot.b, + ), + ScenarioStep( + 'Sync A → server (older update loses)', + () => c.syncReplica(ReplicaSlot.a), + replica: ReplicaSlot.a, + ), + ScenarioStep( + 'Sync B ← server (converge)', + () => c.syncReplica(ReplicaSlot.b), + replica: ReplicaSlot.b, + ), + ]; + }, + ), + Scenario( + title: 'Delete and restore', + summary: + 'A deletes a Person; B reinserts it with a newer restore that wins on merge.', + build: (c) { + final ctx = {}; + return [ + ScenarioStep( + 'Seed Person on A', + replica: ReplicaSlot.a, + () async => ctx['person'] = await c.createRoot( + ReplicaSlot.a, + 'person', + label: 'Restorable person', + ), + ), + ScenarioStep( + 'Sync A → server', + () => c.syncReplica(ReplicaSlot.a), + replica: ReplicaSlot.a, + ), + ScenarioStep( + 'Sync B ← server', + () => c.syncReplica(ReplicaSlot.b), + replica: ReplicaSlot.b, + ), + ScenarioStep( + 'Delete Person on A', + replica: ReplicaSlot.a, + () async { + final person = ctx['person']; + if (person != null) await c.deleteRow(person, ReplicaSlot.a); + }, + ), + ScenarioStep( + 'Sync A → server', + () => c.syncReplica(ReplicaSlot.a), + replica: ReplicaSlot.a, + ), + ScenarioStep( + 'Sync B ← server (tombstone arrives)', + () => c.syncReplica(ReplicaSlot.b), + replica: ReplicaSlot.b, + ), + ScenarioStep( + 'Reinsert Person on B', + replica: ReplicaSlot.b, + () async { + final person = ctx['person']; + if (person != null) await c.reinsertRow(person, ReplicaSlot.b); + }, + ), + ScenarioStep( + 'Sync B → server', + () => c.syncReplica(ReplicaSlot.b), + replica: ReplicaSlot.b, + ), + ScenarioStep( + 'Sync A ← server (converge)', + () => c.syncReplica(ReplicaSlot.a), + replica: ReplicaSlot.a, + ), + ]; + }, + ), + Scenario( + title: 'SetDefault projection', + summary: + 'Deleting a Town on A resets a Company on B to the schema default town.', + build: (c) { + final ctx = {}; + const defaultTownId = protocol.UuidValue.raw( + '550e8400-e29b-41d4-a716-446655440000', + ); + final townRelation = childRelation('town', 'company'); + return [ + ScenarioStep( + 'Seed default Town on A', + replica: ReplicaSlot.a, + () async => ctx['defaultTown'] = await c.createTown( + ReplicaSlot.a, + id: defaultTownId, + label: 'Default town', + ), + ), + ScenarioStep( + 'Seed linked Town on A', + replica: ReplicaSlot.a, + () async => ctx['linkedTown'] = await c.createTown( + ReplicaSlot.a, + label: 'Linked town', + ), + ), + ScenarioStep( + 'Sync A → server', + () => c.syncReplica(ReplicaSlot.a), + replica: ReplicaSlot.a, + ), + ScenarioStep( + 'Sync B ← server', + () => c.syncReplica(ReplicaSlot.b), + replica: ReplicaSlot.b, + ), + ScenarioStep( + 'Attach Company to linked Town on B', + replica: ReplicaSlot.b, + () async { + final town = ctx['linkedTown']; + if (town != null && townRelation != null) { + ctx['company'] = await c.createChildFor( + ReplicaSlot.b, + town, + townRelation, + ); + } else if (town != null) { + ctx['company'] = await c.createCompanyForTown( + ReplicaSlot.b, + town, + ); + } + }, + ), + ScenarioStep( + 'Delete linked Town on A', + replica: ReplicaSlot.a, + () async { + final town = ctx['linkedTown']; + if (town != null) await c.deleteRow(town, ReplicaSlot.a); + }, + ), + ScenarioStep( + 'Sync A → server', + () => c.syncReplica(ReplicaSlot.a), + replica: ReplicaSlot.a, + ), + ScenarioStep( + 'Sync B ← server', + () => c.syncReplica(ReplicaSlot.b), + replica: ReplicaSlot.b, + ), + ScenarioStep( + 'Sync A ← server (converge)', + () => c.syncReplica(ReplicaSlot.a), + replica: ReplicaSlot.a, + ), + ]; + }, + ), + Scenario( + title: 'FK chain cascade', + summary: + 'Deleting the chain root on A cascade-hides grandchildren built on B.', + build: (c) { + final ctx = {}; + final middleRelation = childRelation( + 'fk_chain_root', + 'fk_chain_cascade_middle', + ); + final blockerRelation = childRelation( + 'fk_chain_cascade_middle', + 'fk_chain_restrict_blocker', + ); + final cascadeChildRelation = childRelation( + 'fk_chain_restrict_blocker', + 'fk_chain_middle_cascade_child', + ); + return [ + ScenarioStep( + 'Seed FK chain root on A', + replica: ReplicaSlot.a, + () async => ctx['root'] = await c.createRoot( + ReplicaSlot.a, + 'fk_chain_root', + label: 'Chain root', + ), + ), + ScenarioStep( + 'Sync A → server', + () => c.syncReplica(ReplicaSlot.a), + replica: ReplicaSlot.a, + ), + ScenarioStep( + 'Sync B ← server', + () => c.syncReplica(ReplicaSlot.b), + replica: ReplicaSlot.b, + ), + ScenarioStep( + 'Attach cascade middle on B', + replica: ReplicaSlot.b, + () async { + final root = ctx['root']; + if (root != null && middleRelation != null) { + ctx['middle'] = await c.createChildFor( + ReplicaSlot.b, + root, + middleRelation, + ); + } + }, + ), + ScenarioStep( + 'Attach restrict blocker on B', + replica: ReplicaSlot.b, + () async { + final middle = ctx['middle']; + if (middle != null && blockerRelation != null) { + ctx['blocker'] = await c.createChildFor( + ReplicaSlot.b, + middle, + blockerRelation, + ); + } + }, + ), + ScenarioStep( + 'Attach cascade grandchild on B', + replica: ReplicaSlot.b, + () async { + final blocker = ctx['blocker']; + if (blocker != null && cascadeChildRelation != null) { + await c.createChildFor( + ReplicaSlot.b, + blocker, + cascadeChildRelation, + ); + } + }, + ), + ScenarioStep( + 'Delete chain root on A', + replica: ReplicaSlot.a, + () async { + final root = ctx['root']; + if (root != null) await c.deleteRow(root, ReplicaSlot.a); + }, + ), + ScenarioStep( + 'Sync A → server', + () => c.syncReplica(ReplicaSlot.a), + replica: ReplicaSlot.a, + ), + ScenarioStep( + 'Sync B ← server', + () => c.syncReplica(ReplicaSlot.b), + replica: ReplicaSlot.b, + ), + ScenarioStep( + 'Sync A ← server (converge)', + () => c.syncReplica(ReplicaSlot.a), + replica: ReplicaSlot.a, + ), + ]; + }, + ), + ]; + } +} diff --git a/example/offline_sync_demo/lib/src/sheets.dart b/example/offline_sync_demo/lib/src/sheets.dart new file mode 100644 index 0000000..7da3468 --- /dev/null +++ b/example/offline_sync_demo/lib/src/sheets.dart @@ -0,0 +1,378 @@ +part of 'demo_view.dart'; + +/// Opens the right-hand sheet that creates and switches to a new demo user. +Future showCreateUserSheet( + BuildContext context, + DemoController controller, +) { + return openSheet( + context: context, + position: OverlayPosition.right, + builder: (context) => _CreateUserSheet(controller: controller), + ); +} + +class _CreateUserSheet extends StatefulWidget { + const _CreateUserSheet({required this.controller}); + + final DemoController controller; + + @override + State<_CreateUserSheet> createState() => _CreateUserSheetState(); +} + +class _CreateUserSheetState extends State<_CreateUserSheet> { + final _textController = TextEditingController(); + + @override + void dispose() { + _textController.dispose(); + super.dispose(); + } + + void _submit() { + final username = _textController.text; + closeOverlay(context); + unawaited(widget.controller.createOrSwitchUser(username)); + } + + @override + Widget build(BuildContext context) { + return SizedBox( + width: 320, + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const Text('Create demo user').large().semiBold(), + const Gap(4), + const Text( + 'Authenticates by username only and opens its replicas.', + ).small().muted(), + const Gap(12), + const Text('Username').small().muted(), + const Gap(4), + TextField( + controller: _textController, + autofocus: true, + onSubmitted: (_) => _submit(), + ), + const Gap(12), + PrimaryButton( + onPressed: _submit, + child: const Text('Create & switch'), + ), + ], + ), + ), + ); + } +} + +/// Opens the right-hand sheet showing the complete record for [ref]. +Future showRowDetailSheet( + BuildContext context, + DemoController controller, + DemoRowRef ref, + ReplicaSlot slot, +) { + return openSheet( + context: context, + position: OverlayPosition.right, + builder: (context) => + _RowDetailSheet(controller: controller, ref: ref, slot: slot), + ); +} + +class _RowDetailSheet extends StatefulWidget { + const _RowDetailSheet({ + required this.controller, + required this.ref, + required this.slot, + }); + + final DemoController controller; + final DemoRowRef ref; + final ReplicaSlot slot; + + @override + State<_RowDetailSheet> createState() => _RowDetailSheetState(); +} + +class _RowDetailSheetState extends State<_RowDetailSheet> { + final _controllers = {}; + RowDetail? _detail; + bool _loading = true; + bool _saveFailed = false; + bool _saving = false; + + @override + void initState() { + super.initState(); + unawaited(_load()); + } + + Future _load() async { + final detail = await widget.controller.loadDetail(widget.ref, widget.slot); + if (!mounted) return; + setState(() { + _detail = detail; + _loading = false; + if (detail != null) { + for (final field in detail.editable) { + _controllers[field.key] = TextEditingController(text: field.value); + } + } + }); + } + + @override + void dispose() { + for (final controller in _controllers.values) { + controller.dispose(); + } + super.dispose(); + } + + void _save() { + if (_saving) return; + unawaited(_saveAsync()); + } + + Future _saveAsync() async { + setState(() { + _saveFailed = false; + _saving = true; + }); + + final values = { + for (final entry in _controllers.entries) entry.key: entry.value.text, + }; + final saved = await widget.controller.applyEdit( + widget.ref, + widget.slot, + values, + ); + + if (!mounted) return; + if (saved) { + closeOverlay(context); + return; + } + + final detail = _detail; + if (detail != null) { + for (final field in detail.editable) { + _controllers[field.key]?.text = field.value; + } + } + + setState(() { + _saveFailed = true; + _saving = false; + }); + } + + void _delete() { + closeOverlay(context); + unawaited(widget.controller.deleteRow(widget.ref, widget.slot)); + } + + void _copyValue(String value) { + unawaited(Clipboard.setData(ClipboardData(text: value))); + } + + @override + Widget build(BuildContext context) { + return SizedBox( + width: 400, + child: _loading + ? const Center(child: CircularProgressIndicator()) + : _detail == null + ? const Center(child: Text('Row not found on this replica.')) + : _buildDetail(context, _detail!), + ); + } + + Widget _buildDetail(BuildContext context, RowDetail detail) { + return SingleChildScrollView( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + children: [ + Text(tableLabel(detail.tableName)).large().semiBold(), + const Gap(8), + _StatusPill( + text: detail.visible ? 'visible' : 'hidden', + warn: !detail.visible, + ), + const Spacer(), + Tooltip( + tooltip: (context) => + const TooltipContainer(child: Text('Close details')), + child: IconButton.ghost( + icon: const Icon(Icons.close, size: 16), + onPressed: () => closeOverlay(context), + ), + ), + ], + ), + const Gap(4), + Text(detail.slot.label).small().muted(), + const Gap(12), + _kv(context, 'Row UUID', detail.uuid), + _kv(context, 'Scope id', detail.scopeId ?? '—'), + _kv( + context, + 'Visibility', + detail.visible ? 'visible' : 'hidden on this replica', + ), + const Gap(16), + if (_controllers.isNotEmpty) ...[ + const Text('Edit fields').semiBold(), + const Gap(8), + for (final field in detail.editable) + Padding( + padding: const EdgeInsets.only(bottom: 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text(field.key).small().muted(), + const Gap(4), + TextField( + controller: _controllers[field.key], + onTap: () => _copyValue(_controllers[field.key]!.text), + onChanged: (_) { + if (_saveFailed) { + setState(() => _saveFailed = false); + } + }, + ), + ], + ), + ), + const Gap(8), + Row( + children: [ + Expanded( + child: _SaveButton( + failed: _saveFailed, + saving: _saving, + onPressed: _save, + ), + ), + const Gap(8), + _SolidDestructiveButton( + onPressed: _delete, + child: const Text('Delete'), + ), + ], + ), + ] else + _SolidDestructiveButton( + onPressed: _delete, + child: const Text('Delete'), + ), + const Gap(16), + const Text('Full record').semiBold(), + const Gap(8), + for (final entry in detail.fields.entries) + _kv(context, entry.key, '${entry.value}'), + ], + ), + ); + } + + Widget _kv(BuildContext context, String label, String value) { + return MouseRegion( + cursor: SystemMouseCursors.click, + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () => _copyValue(value), + child: Padding( + padding: const EdgeInsets.only(bottom: 6), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox(width: 96, child: Text(label).xSmall().muted()), + Expanded(child: Text(value).xSmall()), + ], + ), + ), + ), + ); + } +} + +class _SaveButton extends StatelessWidget { + const _SaveButton({ + required this.failed, + required this.saving, + required this.onPressed, + }); + + final bool failed; + final bool saving; + final VoidCallback onPressed; + + @override + Widget build(BuildContext context) { + final child = Text(saving ? 'Saving' : 'Save'); + if (failed) { + return _SolidDestructiveButton(onPressed: onPressed, child: child); + } + + return PrimaryButton(onPressed: onPressed, child: child); + } +} + +class _SolidDestructiveButton extends StatelessWidget { + const _SolidDestructiveButton({required this.onPressed, required this.child}); + + final VoidCallback onPressed; + final Widget child; + + @override + Widget build(BuildContext context) { + return ButtonStyleOverride.inherit( + decoration: (context, states, value) { + if (states.contains(WidgetState.disabled)) return value; + + final theme = Theme.of(context); + final scheme = theme.colorScheme; + final color = scheme.brightness == Brightness.dark + ? const Color(0xFFDC2626) + : scheme.destructive; + + return BoxDecoration( + color: states.contains(WidgetState.hovered) + ? const Color(0xFFB91C1C) + : color, + borderRadius: BorderRadius.circular(theme.radiusMd), + ); + }, + child: DestructiveButton(onPressed: onPressed, child: child), + ); + } +} + +class _StatusPill extends StatelessWidget { + const _StatusPill({required this.text, required this.warn}); + + final String text; + final bool warn; + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + return _Badge( + text: text, + background: warn ? scheme.destructive : scheme.primary, + foreground: warn ? Colors.white : scheme.primaryForeground, + ); + } +} diff --git a/example/offline_sync_demo/lib/src/snapshot.dart b/example/offline_sync_demo/lib/src/snapshot.dart new file mode 100644 index 0000000..4f66d3f --- /dev/null +++ b/example/offline_sync_demo/lib/src/snapshot.dart @@ -0,0 +1,329 @@ +import 'package:serverpod_database/serverpod_database.dart' as db show TableRow; +import 'package:serverpod_offline_sync_client/serverpod_offline_sync_client.dart' + as offline; +import 'package:serverpod_offline_sync_test_client/serverpod_offline_sync_test_client.dart' + as protocol; +import 'package:shadcn_flutter/shadcn_flutter.dart'; + +import 'models.dart'; +import 'relationships.dart'; +import 'table_ops.dart'; + +/// A generated domain row together with its visibility for one replica. +class RowView { + RowView({required this.model, required this.visible}); + + final db.TableRow model; + final bool visible; + + String get table => model.table.tableName; + protocol.UuidValue get id => model.id!; + Map get json => model.toJson() as Map; +} + +/// The data shown in one tree node. +class DemoTreeItem { + DemoTreeItem._({ + required this.title, + required this.icon, + this.detail, + this.ref, + this.relation, + this.hidden = false, + this.dangling = false, + this.metadata = false, + }); + + factory DemoTreeItem.group(String title, String detail) { + return DemoTreeItem._( + title: title, + detail: detail, + icon: Icons.folder_open, + ); + } + + factory DemoTreeItem.row( + String title, + String detail, + DemoRowRef ref, { + required bool hidden, + Relationship? relation, + bool dangling = false, + }) { + return DemoTreeItem._( + title: title, + detail: detail, + ref: ref, + icon: iconForTable(ref.tableName, hidden: hidden), + hidden: hidden, + relation: relation, + dangling: dangling, + ); + } + + factory DemoTreeItem.metadata(String title, String detail) { + return DemoTreeItem._( + title: title, + detail: detail, + icon: Icons.info_outline, + metadata: true, + ); + } + + final String title; + final String? detail; + final IconData icon; + final DemoRowRef? ref; + + /// The foreign-key edge that attaches this node to its parent (null for roots + /// and groups). Drives the onDelete badge. + final Relationship? relation; + final bool hidden; + + /// This row carries a non-null foreign key whose parent is not present here. + final bool dangling; + final bool metadata; +} + +/// A projected tree plus the visible/hidden row counts behind it. +class DemoProjection { + DemoProjection({ + required this.nodes, + required this.visibleRowCount, + required this.hiddenRowCount, + }); + + factory DemoProjection.empty() { + return DemoProjection( + nodes: const [], + visibleRowCount: 0, + hiddenRowCount: 0, + ); + } + + final List> nodes; + final int visibleRowCount; + final int hiddenRowCount; +} + +/// An immutable view of one replica's domain rows and CRDT metadata. +class DemoSnapshot { + DemoSnapshot({ + required this.catalog, + required this.rows, + required this.foreignKeys, + required this.tombstones, + }); + + final RelationshipCatalog catalog; + final List rows; + final List foreignKeys; + final List tombstones; + + /// Loads the visible rows and the full set (visible + CRDT-hidden, via + /// `includeHidden`) for every synced table through the one CRDT session, and + /// classifies each row's visibility. + static Future load( + RelationshipCatalog catalog, + offline.CrdtDatabaseSession crdt, + ) async { + final rows = []; + for (final table in catalog.tables) { + final ops = demoTableOps[table]; + if (ops == null) continue; + final visible = await ops.findAll(crdt); + final full = await ops.findAll(crdt, includeHidden: true); + final visibleIds = { + for (final row in visible) + if (row.id != null) row.id!.uuid, + }; + for (final model in full) { + final id = model.id; + if (id == null) continue; + rows.add(RowView(model: model, visible: visibleIds.contains(id.uuid))); + } + } + + return DemoSnapshot( + catalog: catalog, + rows: rows, + foreignKeys: await offline.CrdtDataForeignKey.db.find(crdt), + tombstones: await offline.CrdtDataDeleted.db.find(crdt), + ); + } + + /// Builds a snapshot from the server's merged truth. [serverRows] is the flat + /// `List` returned by `fetchScopeSnapshot`: each element is a typed + /// domain model, deserialized by Serverpod from its `__className__` tag, so + /// the table name and JSON come straight off the model. Rows whose id is in + /// [hiddenIds] are flagged hidden; there is no local CRDT metadata to show. + factory DemoSnapshot.fromServer( + RelationshipCatalog catalog, + List serverRows, { + Set hiddenIds = const {}, + }) { + final rows = []; + for (final row in serverRows) { + final model = row as db.TableRow; + final id = model.id; + if (id == null) continue; + rows.add(RowView(model: model, visible: !hiddenIds.contains(id.uuid))); + } + + return DemoSnapshot( + catalog: catalog, + rows: rows, + foreignKeys: const [], + tombstones: const [], + ); + } + + int get visibleRowCount => rows.where((r) => r.visible).length; + int get hiddenRowCount => rows.where((r) => !r.visible).length; + + /// Stable ordering for tree siblings: table name, then id. + int _compareRows(RowView a, RowView b) { + final byTable = a.table.compareTo(b.table); + if (byTable != 0) return byTable; + return a.id.uuid.compareTo(b.id.uuid); + } + + /// Builds the FK forest for this snapshot. When [showHidden] is false only + /// visible rows are shown; otherwise hidden rows are included and flagged. + DemoProjection project({required bool showHidden}) { + final included = [ + for (final row in rows) + if (row.visible || showHidden) row, + ]; + final byId = {for (final row in included) row.id.uuid: row}; + + // Resolve each row's primary parent: the first of its foreign keys that is + // set and resolves to a row present in this view. + final childrenOf = >{}; + final edgeOf = {}; + final danglingIds = {}; + final roots = []; + + for (final row in included) { + Relationship? parentEdge; + String? parentId; + var hasUnresolvedRef = false; + for (final relation in catalog.parentRelationshipsOf(row.table)) { + final value = row.json[relation.fkColumn]; + if (value == null) continue; + final candidate = byId['$value']; + if (candidate != null && candidate.id.uuid != row.id.uuid) { + parentEdge = relation; + parentId = candidate.id.uuid; + break; + } + hasUnresolvedRef = true; + } + + if (parentEdge != null && parentId != null) { + childrenOf.putIfAbsent(parentId, () => []).add(row); + edgeOf[row.id.uuid] = parentEdge; + } else { + if (hasUnresolvedRef) danglingIds.add(row.id.uuid); + roots.add(row); + } + } + + TreeNode nodeFor(RowView row, Set seen) { + seen.add(row.id.uuid); + final childRows = List.of( + childrenOf[row.id.uuid] ?? const [], + )..sort(_compareRows); + final children = [ + for (final child in childRows) + if (!seen.contains(child.id.uuid)) nodeFor(child, seen), + ]; + final relation = edgeOf[row.id.uuid]; + final detail = relation != null + ? '${relationLabel(relation.fkColumn)} · ${shortId(row.id)}' + : '${tableLabel(row.table)} · ${shortId(row.id)}'; + return TreeItem( + data: DemoTreeItem.row( + catalog.displayLabel(row.model), + detail, + DemoRowRef(tableName: row.table, id: row.id), + hidden: !row.visible, + relation: relation, + dangling: danglingIds.contains(row.id.uuid), + ), + expanded: true, + children: children, + ); + } + + roots.sort(_compareRows); + + final seen = {}; + final forest = [for (final root in roots) nodeFor(root, seen)]; + + final nodes = >[ + ...forest, + if (foreignKeys.isNotEmpty || tombstones.isNotEmpty) + TreeItem( + data: DemoTreeItem.group( + 'CRDT metadata', + '${foreignKeys.length} FK projections · ${tombstones.length} tombstones', + ), + expanded: false, + children: [ + for (final fk in foreignKeys) + TreeItem( + data: DemoTreeItem.metadata( + 'field ${fk.fieldId}', + 'attempted ${shortId(fk.attemptedValue)} ' + 'visible ${shortId(fk.visibleValue)} ' + 'reason ${fk.overrideReason?.name ?? 'none'}', + ), + ), + for (final tombstone in tombstones) + TreeItem( + data: DemoTreeItem.metadata( + 'tombstone row ${tombstone.rowId}', + 'clFlag ${tombstone.clFlag}, reason ${tombstone.reason.name}', + ), + ), + ], + ), + ].expandAll(); + + return DemoProjection( + nodes: nodes, + visibleRowCount: visibleRowCount, + hiddenRowCount: hiddenRowCount, + ); + } +} + +/// Friendly name for a foreign-key column, e.g. `inhabitantId` → `inhabitant`. +String relationLabel(String fkColumn) { + if (fkColumn.endsWith('Id')) { + return fkColumn.substring(0, fkColumn.length - 2); + } + return fkColumn; +} + +/// Friendly name for a table, e.g. `fk_chain_root` → `fk chain root`. +String tableLabel(String table) => table.replaceAll('_', ' '); + +/// A small icon per table family, falling back to a generic row icon. +IconData iconForTable(String table, {required bool hidden}) { + if (hidden) return Icons.visibility_off; + return switch (table) { + 'person' => Icons.person, + 'address' => Icons.home, + 'city' => Icons.location_city, + 'town' => Icons.map, + 'organization' => Icons.apartment, + 'company' => Icons.business, + 'restrict_child' || 'required_set_null_child' => Icons.link, + 'unique' || 'unique_uuid' || 'unique_composite' => Icons.key, + 'types' => Icons.data_object, + _ when table.startsWith('fk_chain') => Icons.account_tree, + _ => Icons.table_rows, + }; +} diff --git a/example/offline_sync_demo/lib/src/table_ops.dart b/example/offline_sync_demo/lib/src/table_ops.dart new file mode 100644 index 0000000..516a844 --- /dev/null +++ b/example/offline_sync_demo/lib/src/table_ops.dart @@ -0,0 +1,264 @@ +import 'package:serverpod_database/serverpod_database.dart' + show DatabaseSession, Table, TableRow; +import 'package:serverpod_offline_sync_client/serverpod_offline_sync_client.dart' + show IncludeTombstonedRows; +import 'package:serverpod_offline_sync_test_client/serverpod_offline_sync_test_client.dart'; + +import 'models.dart'; + +/// Generic, table-name keyed CRUD over the generated Serverpod models. +/// +/// This indirection exists **only** so the demo's metadata-driven UI can act on +/// any of the synced tables without a per-type switch. A real integration does +/// not need it: you call the generated model APIs directly against the CRDT +/// session — e.g. `Person.db.insertRow(session, person)` or +/// `session.db.find()` — exactly as the `seed*` methods in +/// `DemoController` do. Read those for the plain, recommended form. +/// +/// Database operations retain generated model instances. The only +/// serialization boundary is [updateFields], where a generic UI edit has to be +/// turned back into the concrete generated type; that conversion is delegated +/// to [Protocol]. +class TableOps { + TableOps({ + required this.table, + required this.canCreateRoot, + required this.create, + required this.findAll, + required this.findById, + required this.insertRow, + required this.updateFields, + required this.deleteById, + }); + + /// The generated table metadata for this row type. + final Table table; + + /// Database table name, e.g. `person`. + String get name => table.tableName; + + /// Whether the generated constructor can build this row without a parent. + final bool canCreateRoot; + + /// Builds a generated model from an [id], a [label] for its display column, + /// and any [foreignKeys] to assign. Null when this table has no UI factory. + final TableRow? Function( + UuidValue id, + String label, + Map foreignKeys, + )? + create; + + /// Every row in the table. When [includeHidden] is true, CRDT-tombstoned + /// (soft-deleted) rows are returned too. + final Future>> Function( + DatabaseSession session, { + bool includeHidden, + }) + findAll; + + /// A single visible row by id, or null. + final Future?> Function( + DatabaseSession session, + UuidValue id, + ) + findById; + + /// Inserts a generated row. + final Future Function(DatabaseSession session, TableRow row) + insertRow; + + /// Applies JSON-shaped field values to a generated row and updates it. + final Future Function( + DatabaseSession session, + TableRow row, + Map fields, + ) + updateFields; + + /// Deletes the row with [id]; returns whether a row was found. + final Future Function(DatabaseSession session, UuidValue id) deleteById; +} + +TableOps _ops>({ + T? Function(UuidValue id, String label, Map foreignKeys)? + create, + bool canCreateRoot = true, +}) { + final table = Protocol().getTableForType(T); + if (table == null) { + throw StateError('No table is registered for type $T.'); + } + return TableOps( + table: table, + create: create, + canCreateRoot: create != null && canCreateRoot, + findAll: (session, {includeHidden = false}) async { + return session.db.find( + where: includeHidden ? table.includeHiddenRows : null, + ); + }, + findById: (session, id) => session.db.findById(id), + insertRow: (session, row) async { + await session.db.insertRow(row as T); + }, + updateFields: (session, row, fields) async { + final json = Map.of(row.toJson() as Map) + ..addAll(fields); + await session.db.updateRow(Protocol().deserialize(json)); + }, + deleteById: (session, id) async { + final row = await session.db.findById(id); + if (row == null) return false; + await session.db.deleteRow(row); + return true; + }, + ); +} + +/// Every synced demo table, keyed by its database table name. The generated +/// constructors keep required fields, defaults, and Dart types in generated +/// code instead of reconstructing those rules from table metadata. +final Map demoTableOps = { + for (final ops in [ + _ops( + create: (id, label, foreignKeys) => Person( + id: id, + name: label, + organizationId: foreignKeys['organizationId'], + oldCompanyId: foreignKeys['oldCompanyId'], + ), + ), + _ops
( + create: (id, label, foreignKeys) => Address( + id: id, + street: label, + inhabitantId: foreignKeys['inhabitantId'], + ), + ), + _ops( + create: (id, label, foreignKeys) => City(id: id, name: label), + ), + _ops( + create: (id, label, foreignKeys) => Town( + id: id, + name: label, + cityId: foreignKeys['cityId'], + mayorId: foreignKeys['mayorId'], + ), + ), + _ops( + create: (id, label, foreignKeys) => + Organization(id: id, name: label, cityId: foreignKeys['cityId']), + ), + _ops( + canCreateRoot: false, + create: (id, label, foreignKeys) => + Company(id: id, name: label, townId: foreignKeys['townId']), + ), + _ops( + create: (id, label, foreignKeys) => + RestrictChild(id: id, name: label, parentId: foreignKeys['parentId']), + ), + _ops( + canCreateRoot: false, + create: (id, label, foreignKeys) { + final parentId = foreignKeys['parentId']; + if (parentId == null) return null; + return RequiredSetNullChild(id: id, name: label, parentId: parentId); + }, + ), + _ops( + create: (id, label, foreignKeys) => Unique(id: id, name: label), + ), + _ops( + create: (id, label, foreignKeys) => UniqueUuid(id: id, value: newId()), + ), + _ops( + create: (id, label, foreignKeys) => + UniqueComposite(id: id, scope: label, value: label), + ), + _ops( + create: (id, label, foreignKeys) => UniqueSetNullChild( + id: id, + name: label, + parentId: foreignKeys['parentId'], + ), + ), + _ops(canCreateRoot: false), + _ops( + create: (id, label, foreignKeys) => FkChainRoot(id: id, name: label), + ), + _ops( + canCreateRoot: false, + create: (id, label, foreignKeys) => FkChainCascadeMiddle( + id: id, + name: label, + rootId: foreignKeys['rootId'], + ), + ), + _ops( + canCreateRoot: false, + create: (id, label, foreignKeys) => FkChainRestrictBlocker( + id: id, + name: label, + cascadeMiddleId: foreignKeys['cascadeMiddleId'], + ), + ), + _ops( + canCreateRoot: false, + create: (id, label, foreignKeys) => FkChainMiddleSetNullChild( + id: id, + name: label, + restrictBlockerId: foreignKeys['restrictBlockerId'], + ), + ), + _ops( + canCreateRoot: false, + create: (id, label, foreignKeys) => FkChainMiddleCascadeChild( + id: id, + name: label, + restrictBlockerId: foreignKeys['restrictBlockerId'], + ), + ), + _ops( + canCreateRoot: false, + create: (id, label, foreignKeys) => FkChainSetNullMiddle( + id: id, + name: label, + cascadeMiddleId: foreignKeys['cascadeMiddleId'], + ), + ), + _ops( + canCreateRoot: false, + create: (id, label, foreignKeys) => FkChainSetNullCascadeChild( + id: id, + name: label, + setNullMiddleId: foreignKeys['setNullMiddleId'], + ), + ), + _ops( + canCreateRoot: false, + create: (id, label, foreignKeys) => FkChainSetNullRestrictChild( + id: id, + name: label, + setNullMiddleId: foreignKeys['setNullMiddleId'], + ), + ), + _ops( + canCreateRoot: false, + create: (id, label, foreignKeys) => FkChainSetNullSetNullChild( + id: id, + name: label, + setNullMiddleId: foreignKeys['setNullMiddleId'], + ), + ), + ]) + ops.name: ops, +}; + +/// Tables synchronized by the demo, derived from [demoTableOps]. Mirrors the +/// server `demoSyncTables`. +final List demoSyncTables = [ + for (final ops in demoTableOps.values) ops.table, +]; diff --git a/example/offline_sync_demo/linux/.gitignore b/example/offline_sync_demo/linux/.gitignore new file mode 100644 index 0000000..d3896c9 --- /dev/null +++ b/example/offline_sync_demo/linux/.gitignore @@ -0,0 +1 @@ +flutter/ephemeral diff --git a/example/offline_sync_demo/linux/CMakeLists.txt b/example/offline_sync_demo/linux/CMakeLists.txt new file mode 100644 index 0000000..e76159e --- /dev/null +++ b/example/offline_sync_demo/linux/CMakeLists.txt @@ -0,0 +1,128 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "offline_sync_demo") +# The unique GTK application identifier for this application. See: +# https://wiki.gnome.org/HowDoI/ChooseApplicationID +set(APPLICATION_ID "com.example.offline_sync_demo") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(SET CMP0063 NEW) + +# Load bundled libraries from the lib/ directory relative to the binary. +set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") + +# Root filesystem for cross-building. +if(FLUTTER_TARGET_PLATFORM_SYSROOT) + set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) + set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) +endif() + +# Define build configuration options. +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") +endif() + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_14) + target_compile_options(${TARGET} PRIVATE -Wall -Werror) + target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") + target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) + +# Only the install-generated bundle's copy of the executable will launch +# correctly, since the resources must in the right relative locations. To avoid +# people trying to run the unbundled copy, put it in a subdirectory instead of +# the default top-level location. +set_target_properties(${BINARY_NAME} + PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" +) + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# By default, "installing" just makes a relocatable bundle in the build +# directory. +set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +# Start with a clean build bundle directory every time. +install(CODE " + file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") + " COMPONENT Runtime) + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) + install(FILES "${bundled_library}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endforeach(bundled_library) + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") + install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() diff --git a/example/offline_sync_demo/linux/flutter/CMakeLists.txt b/example/offline_sync_demo/linux/flutter/CMakeLists.txt new file mode 100644 index 0000000..d5bd016 --- /dev/null +++ b/example/offline_sync_demo/linux/flutter/CMakeLists.txt @@ -0,0 +1,88 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.10) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. + +# Serves the same purpose as list(TRANSFORM ... PREPEND ...), +# which isn't available in 3.10. +function(list_prepend LIST_NAME PREFIX) + set(NEW_LIST "") + foreach(element ${${LIST_NAME}}) + list(APPEND NEW_LIST "${PREFIX}${element}") + endforeach(element) + set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) +endfunction() + +# === Flutter Library === +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) +pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) +pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) + +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "fl_basic_message_channel.h" + "fl_binary_codec.h" + "fl_binary_messenger.h" + "fl_dart_project.h" + "fl_engine.h" + "fl_json_message_codec.h" + "fl_json_method_codec.h" + "fl_message_codec.h" + "fl_method_call.h" + "fl_method_channel.h" + "fl_method_codec.h" + "fl_method_response.h" + "fl_plugin_registrar.h" + "fl_plugin_registry.h" + "fl_standard_message_codec.h" + "fl_standard_method_codec.h" + "fl_string_codec.h" + "fl_value.h" + "fl_view.h" + "flutter_linux.h" +) +list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") +target_link_libraries(flutter INTERFACE + PkgConfig::GTK + PkgConfig::GLIB + PkgConfig::GIO +) +add_dependencies(flutter flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CMAKE_CURRENT_BINARY_DIR}/_phony_ + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" + ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} +) diff --git a/example/offline_sync_demo/linux/flutter/generated_plugin_registrant.cc b/example/offline_sync_demo/linux/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..e71a16d --- /dev/null +++ b/example/offline_sync_demo/linux/flutter/generated_plugin_registrant.cc @@ -0,0 +1,11 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + + +void fl_register_plugins(FlPluginRegistry* registry) { +} diff --git a/example/offline_sync_demo/linux/flutter/generated_plugin_registrant.h b/example/offline_sync_demo/linux/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..e0f0a47 --- /dev/null +++ b/example/offline_sync_demo/linux/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void fl_register_plugins(FlPluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/example/offline_sync_demo/linux/flutter/generated_plugins.cmake b/example/offline_sync_demo/linux/flutter/generated_plugins.cmake new file mode 100644 index 0000000..be1ee3e --- /dev/null +++ b/example/offline_sync_demo/linux/flutter/generated_plugins.cmake @@ -0,0 +1,24 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST + jni +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/example/offline_sync_demo/linux/runner/CMakeLists.txt b/example/offline_sync_demo/linux/runner/CMakeLists.txt new file mode 100644 index 0000000..e97dabc --- /dev/null +++ b/example/offline_sync_demo/linux/runner/CMakeLists.txt @@ -0,0 +1,26 @@ +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} + "main.cc" + "my_application.cc" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the application ID. +add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") + +# Add dependency libraries. Add any application-specific dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter) +target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) + +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") diff --git a/example/offline_sync_demo/linux/runner/main.cc b/example/offline_sync_demo/linux/runner/main.cc new file mode 100644 index 0000000..e7c5c54 --- /dev/null +++ b/example/offline_sync_demo/linux/runner/main.cc @@ -0,0 +1,6 @@ +#include "my_application.h" + +int main(int argc, char** argv) { + g_autoptr(MyApplication) app = my_application_new(); + return g_application_run(G_APPLICATION(app), argc, argv); +} diff --git a/example/offline_sync_demo/linux/runner/my_application.cc b/example/offline_sync_demo/linux/runner/my_application.cc new file mode 100644 index 0000000..905432e --- /dev/null +++ b/example/offline_sync_demo/linux/runner/my_application.cc @@ -0,0 +1,148 @@ +#include "my_application.h" + +#include +#ifdef GDK_WINDOWING_X11 +#include +#endif + +#include "flutter/generated_plugin_registrant.h" + +struct _MyApplication { + GtkApplication parent_instance; + char** dart_entrypoint_arguments; +}; + +G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) + +// Called when first Flutter frame received. +static void first_frame_cb(MyApplication* self, FlView* view) { + gtk_widget_show(gtk_widget_get_toplevel(GTK_WIDGET(view))); +} + +// Implements GApplication::activate. +static void my_application_activate(GApplication* application) { + MyApplication* self = MY_APPLICATION(application); + GtkWindow* window = + GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); + + // Use a header bar when running in GNOME as this is the common style used + // by applications and is the setup most users will be using (e.g. Ubuntu + // desktop). + // If running on X and not using GNOME then just use a traditional title bar + // in case the window manager does more exotic layout, e.g. tiling. + // If running on Wayland assume the header bar will work (may need changing + // if future cases occur). + gboolean use_header_bar = TRUE; +#ifdef GDK_WINDOWING_X11 + GdkScreen* screen = gtk_window_get_screen(window); + if (GDK_IS_X11_SCREEN(screen)) { + const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); + if (g_strcmp0(wm_name, "GNOME Shell") != 0) { + use_header_bar = FALSE; + } + } +#endif + if (use_header_bar) { + GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); + gtk_widget_show(GTK_WIDGET(header_bar)); + gtk_header_bar_set_title(header_bar, "offline_sync_demo"); + gtk_header_bar_set_show_close_button(header_bar, TRUE); + gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); + } else { + gtk_window_set_title(window, "offline_sync_demo"); + } + + gtk_window_set_default_size(window, 1280, 720); + + g_autoptr(FlDartProject) project = fl_dart_project_new(); + fl_dart_project_set_dart_entrypoint_arguments( + project, self->dart_entrypoint_arguments); + + FlView* view = fl_view_new(project); + GdkRGBA background_color; + // Background defaults to black, override it here if necessary, e.g. #00000000 + // for transparent. + gdk_rgba_parse(&background_color, "#000000"); + fl_view_set_background_color(view, &background_color); + gtk_widget_show(GTK_WIDGET(view)); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); + + // Show the window when Flutter renders. + // Requires the view to be realized so we can start rendering. + g_signal_connect_swapped(view, "first-frame", G_CALLBACK(first_frame_cb), + self); + gtk_widget_realize(GTK_WIDGET(view)); + + fl_register_plugins(FL_PLUGIN_REGISTRY(view)); + + gtk_widget_grab_focus(GTK_WIDGET(view)); +} + +// Implements GApplication::local_command_line. +static gboolean my_application_local_command_line(GApplication* application, + gchar*** arguments, + int* exit_status) { + MyApplication* self = MY_APPLICATION(application); + // Strip out the first argument as it is the binary name. + self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); + + g_autoptr(GError) error = nullptr; + if (!g_application_register(application, nullptr, &error)) { + g_warning("Failed to register: %s", error->message); + *exit_status = 1; + return TRUE; + } + + g_application_activate(application); + *exit_status = 0; + + return TRUE; +} + +// Implements GApplication::startup. +static void my_application_startup(GApplication* application) { + // MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application startup. + + G_APPLICATION_CLASS(my_application_parent_class)->startup(application); +} + +// Implements GApplication::shutdown. +static void my_application_shutdown(GApplication* application) { + // MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application shutdown. + + G_APPLICATION_CLASS(my_application_parent_class)->shutdown(application); +} + +// Implements GObject::dispose. +static void my_application_dispose(GObject* object) { + MyApplication* self = MY_APPLICATION(object); + g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); + G_OBJECT_CLASS(my_application_parent_class)->dispose(object); +} + +static void my_application_class_init(MyApplicationClass* klass) { + G_APPLICATION_CLASS(klass)->activate = my_application_activate; + G_APPLICATION_CLASS(klass)->local_command_line = + my_application_local_command_line; + G_APPLICATION_CLASS(klass)->startup = my_application_startup; + G_APPLICATION_CLASS(klass)->shutdown = my_application_shutdown; + G_OBJECT_CLASS(klass)->dispose = my_application_dispose; +} + +static void my_application_init(MyApplication* self) {} + +MyApplication* my_application_new() { + // Set the program name to the application ID, which helps various systems + // like GTK and desktop environments map this running application to its + // corresponding .desktop file. This ensures better integration by allowing + // the application to be recognized beyond its binary name. + g_set_prgname(APPLICATION_ID); + + return MY_APPLICATION(g_object_new(my_application_get_type(), + "application-id", APPLICATION_ID, "flags", + G_APPLICATION_NON_UNIQUE, nullptr)); +} diff --git a/example/offline_sync_demo/linux/runner/my_application.h b/example/offline_sync_demo/linux/runner/my_application.h new file mode 100644 index 0000000..db16367 --- /dev/null +++ b/example/offline_sync_demo/linux/runner/my_application.h @@ -0,0 +1,21 @@ +#ifndef FLUTTER_MY_APPLICATION_H_ +#define FLUTTER_MY_APPLICATION_H_ + +#include + +G_DECLARE_FINAL_TYPE(MyApplication, + my_application, + MY, + APPLICATION, + GtkApplication) + +/** + * my_application_new: + * + * Creates a new Flutter-based application. + * + * Returns: a new #MyApplication. + */ +MyApplication* my_application_new(); + +#endif // FLUTTER_MY_APPLICATION_H_ diff --git a/example/offline_sync_demo/macos/.gitignore b/example/offline_sync_demo/macos/.gitignore new file mode 100644 index 0000000..746adbb --- /dev/null +++ b/example/offline_sync_demo/macos/.gitignore @@ -0,0 +1,7 @@ +# Flutter-related +**/Flutter/ephemeral/ +**/Pods/ + +# Xcode-related +**/dgph +**/xcuserdata/ diff --git a/example/offline_sync_demo/macos/Flutter/Flutter-Debug.xcconfig b/example/offline_sync_demo/macos/Flutter/Flutter-Debug.xcconfig new file mode 100644 index 0000000..c2efd0b --- /dev/null +++ b/example/offline_sync_demo/macos/Flutter/Flutter-Debug.xcconfig @@ -0,0 +1 @@ +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/example/offline_sync_demo/macos/Flutter/Flutter-Release.xcconfig b/example/offline_sync_demo/macos/Flutter/Flutter-Release.xcconfig new file mode 100644 index 0000000..c2efd0b --- /dev/null +++ b/example/offline_sync_demo/macos/Flutter/Flutter-Release.xcconfig @@ -0,0 +1 @@ +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/example/offline_sync_demo/macos/Flutter/GeneratedPluginRegistrant.swift b/example/offline_sync_demo/macos/Flutter/GeneratedPluginRegistrant.swift new file mode 100644 index 0000000..cccf817 --- /dev/null +++ b/example/offline_sync_demo/macos/Flutter/GeneratedPluginRegistrant.swift @@ -0,0 +1,10 @@ +// +// Generated file. Do not edit. +// + +import FlutterMacOS +import Foundation + + +func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { +} diff --git a/example/offline_sync_demo/macos/Runner.xcodeproj/project.pbxproj b/example/offline_sync_demo/macos/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..d9efe41 --- /dev/null +++ b/example/offline_sync_demo/macos/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,705 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXAggregateTarget section */ + 33CC111A2044C6BA0003C045 /* Flutter Assemble */ = { + isa = PBXAggregateTarget; + buildConfigurationList = 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */; + buildPhases = ( + 33CC111E2044C6BF0003C045 /* ShellScript */, + ); + dependencies = ( + ); + name = "Flutter Assemble"; + productName = FLX; + }; +/* End PBXAggregateTarget section */ + +/* Begin PBXBuildFile section */ + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C80D7294CF71000263BE5 /* RunnerTests.swift */; }; + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; }; + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; }; + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; }; + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; }; + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC10EC2044A3C60003C045; + remoteInfo = Runner; + }; + 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC111A2044C6BA0003C045; + remoteInfo = FLX; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 33CC110E2044A8840003C045 /* Bundle Framework */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Bundle Framework"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 331C80D7294CF71000263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = ""; }; + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = ""; }; + 33CC10ED2044A3C60003C045 /* offline_sync_demo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "offline_sync_demo.app"; sourceTree = BUILT_PRODUCTS_DIR; }; + 33CC10F02044A3C60003C045 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 33CC10F22044A3C60003C045 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Assets.xcassets; path = Runner/Assets.xcassets; sourceTree = ""; }; + 33CC10F52044A3C60003C045 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = ""; }; + 33CC10F72044A3C60003C045 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = Runner/Info.plist; sourceTree = ""; }; + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MainFlutterWindow.swift; sourceTree = ""; }; + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Debug.xcconfig"; sourceTree = ""; }; + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Release.xcconfig"; sourceTree = ""; }; + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = "Flutter-Generated.xcconfig"; path = "ephemeral/Flutter-Generated.xcconfig"; sourceTree = ""; }; + 33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = ""; }; + 33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = ""; }; + 33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 331C80D2294CF70F00263BE5 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EA2044A3C60003C045 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C80D6294CF71000263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C80D7294CF71000263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 33BA886A226E78AF003329D5 /* Configs */ = { + isa = PBXGroup; + children = ( + 33E5194F232828860026EE4D /* AppInfo.xcconfig */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */, + ); + path = Configs; + sourceTree = ""; + }; + 33CC10E42044A3C60003C045 = { + isa = PBXGroup; + children = ( + 33FAB671232836740065AC1E /* Runner */, + 33CEB47122A05771004F2AC0 /* Flutter */, + 331C80D6294CF71000263BE5 /* RunnerTests */, + 33CC10EE2044A3C60003C045 /* Products */, + D73912EC22F37F3D000D13A0 /* Frameworks */, + ); + sourceTree = ""; + }; + 33CC10EE2044A3C60003C045 /* Products */ = { + isa = PBXGroup; + children = ( + 33CC10ED2044A3C60003C045 /* offline_sync_demo.app */, + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 33CC11242044D66E0003C045 /* Resources */ = { + isa = PBXGroup; + children = ( + 33CC10F22044A3C60003C045 /* Assets.xcassets */, + 33CC10F42044A3C60003C045 /* MainMenu.xib */, + 33CC10F72044A3C60003C045 /* Info.plist */, + ); + name = Resources; + path = ..; + sourceTree = ""; + }; + 33CEB47122A05771004F2AC0 /* Flutter */ = { + isa = PBXGroup; + children = ( + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */, + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */, + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */, + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */, + ); + path = Flutter; + sourceTree = ""; + }; + 33FAB671232836740065AC1E /* Runner */ = { + isa = PBXGroup; + children = ( + 33CC10F02044A3C60003C045 /* AppDelegate.swift */, + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */, + 33E51913231747F40026EE4D /* DebugProfile.entitlements */, + 33E51914231749380026EE4D /* Release.entitlements */, + 33CC11242044D66E0003C045 /* Resources */, + 33BA886A226E78AF003329D5 /* Configs */, + ); + path = Runner; + sourceTree = ""; + }; + D73912EC22F37F3D000D13A0 /* Frameworks */ = { + isa = PBXGroup; + children = ( + ); + name = Frameworks; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C80D4294CF70F00263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 331C80D1294CF70F00263BE5 /* Sources */, + 331C80D2294CF70F00263BE5 /* Frameworks */, + 331C80D3294CF70F00263BE5 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 331C80DA294CF71000263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C80D5294CF71000263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 33CC10EC2044A3C60003C045 /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 33CC10E92044A3C60003C045 /* Sources */, + 33CC10EA2044A3C60003C045 /* Frameworks */, + 33CC10EB2044A3C60003C045 /* Resources */, + 33CC110E2044A8840003C045 /* Bundle Framework */, + 3399D490228B24CF009A79C7 /* ShellScript */, + ); + buildRules = ( + ); + dependencies = ( + 33CC11202044C79F0003C045 /* PBXTargetDependency */, + ); + name = Runner; + productName = Runner; + productReference = 33CC10ED2044A3C60003C045 /* offline_sync_demo.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 33CC10E52044A3C60003C045 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastSwiftUpdateCheck = 0920; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C80D4294CF70F00263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 33CC10EC2044A3C60003C045; + }; + 33CC10EC2044A3C60003C045 = { + CreatedOnToolsVersion = 9.2; + LastSwiftMigration = 1100; + ProvisioningStyle = Automatic; + SystemCapabilities = { + com.apple.Sandbox = { + enabled = 1; + }; + }; + }; + 33CC111A2044C6BA0003C045 = { + CreatedOnToolsVersion = 9.2; + ProvisioningStyle = Manual; + }; + }; + }; + buildConfigurationList = 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 33CC10E42044A3C60003C045; + productRefGroup = 33CC10EE2044A3C60003C045 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 33CC10EC2044A3C60003C045 /* Runner */, + 331C80D4294CF70F00263BE5 /* RunnerTests */, + 33CC111A2044C6BA0003C045 /* Flutter Assemble */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C80D3294CF70F00263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EB2044A3C60003C045 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */, + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 3399D490228B24CF009A79C7 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + ); + outputFileListPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "echo \"$PRODUCT_NAME.app\" > \"$PROJECT_DIR\"/Flutter/ephemeral/.app_filename && \"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh embed\n"; + }; + 33CC111E2044C6BF0003C045 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + Flutter/ephemeral/FlutterInputs.xcfilelist, + ); + inputPaths = ( + Flutter/ephemeral/tripwire, + ); + outputFileListPaths = ( + Flutter/ephemeral/FlutterOutputs.xcfilelist, + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C80D1294CF70F00263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10E92044A3C60003C045 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */, + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */, + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C80DA294CF71000263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC10EC2044A3C60003C045 /* Runner */; + targetProxy = 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */; + }; + 33CC11202044C79F0003C045 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC111A2044C6BA0003C045 /* Flutter Assemble */; + targetProxy = 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 33CC10F42044A3C60003C045 /* MainMenu.xib */ = { + isa = PBXVariantGroup; + children = ( + 33CC10F52044A3C60003C045 /* Base */, + ); + name = MainMenu.xib; + path = Runner; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 331C80DB294CF71000263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.offlineSyncDemo.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/offline_sync_demo.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/offline_sync_demo"; + }; + name = Debug; + }; + 331C80DC294CF71000263BE5 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.offlineSyncDemo.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/offline_sync_demo.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/offline_sync_demo"; + }; + name = Release; + }; + 331C80DD294CF71000263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.offlineSyncDemo.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/offline_sync_demo.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/offline_sync_demo"; + }; + name = Profile; + }; + 338D0CE9231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.15; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Profile; + }; + 338D0CEA231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Profile; + }; + 338D0CEB231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Profile; + }; + 33CC10F92044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.15; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 33CC10FA2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.15; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Release; + }; + 33CC10FC2044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + }; + name = Debug; + }; + 33CC10FD2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/Release.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Release; + }; + 33CC111C2044C6BA0003C045 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Debug; + }; + 33CC111D2044C6BA0003C045 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C80DB294CF71000263BE5 /* Debug */, + 331C80DC294CF71000263BE5 /* Release */, + 331C80DD294CF71000263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10F92044A3C60003C045 /* Debug */, + 33CC10FA2044A3C60003C045 /* Release */, + 338D0CE9231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10FC2044A3C60003C045 /* Debug */, + 33CC10FD2044A3C60003C045 /* Release */, + 338D0CEA231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC111C2044C6BA0003C045 /* Debug */, + 33CC111D2044C6BA0003C045 /* Release */, + 338D0CEB231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 33CC10E52044A3C60003C045 /* Project object */; +} diff --git a/example/offline_sync_demo/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/example/offline_sync_demo/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/example/offline_sync_demo/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/example/offline_sync_demo/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/example/offline_sync_demo/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..36a6391 --- /dev/null +++ b/example/offline_sync_demo/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,99 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/example/offline_sync_demo/macos/Runner.xcworkspace/contents.xcworkspacedata b/example/offline_sync_demo/macos/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..1d526a1 --- /dev/null +++ b/example/offline_sync_demo/macos/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/example/offline_sync_demo/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/example/offline_sync_demo/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/example/offline_sync_demo/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/example/offline_sync_demo/macos/Runner/AppDelegate.swift b/example/offline_sync_demo/macos/Runner/AppDelegate.swift new file mode 100644 index 0000000..b3c1761 --- /dev/null +++ b/example/offline_sync_demo/macos/Runner/AppDelegate.swift @@ -0,0 +1,13 @@ +import Cocoa +import FlutterMacOS + +@main +class AppDelegate: FlutterAppDelegate { + override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { + return true + } + + override func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool { + return true + } +} diff --git a/example/offline_sync_demo/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/example/offline_sync_demo/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..a2ec33f --- /dev/null +++ b/example/offline_sync_demo/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,68 @@ +{ + "images" : [ + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_16.png", + "scale" : "1x" + }, + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "2x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "1x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_64.png", + "scale" : "2x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_128.png", + "scale" : "1x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "2x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "1x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "2x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "1x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_1024.png", + "scale" : "2x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/example/offline_sync_demo/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png b/example/offline_sync_demo/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png new file mode 100644 index 0000000..82b6f9d Binary files /dev/null and b/example/offline_sync_demo/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png differ diff --git a/example/offline_sync_demo/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png b/example/offline_sync_demo/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png new file mode 100644 index 0000000..13b35eb Binary files /dev/null and b/example/offline_sync_demo/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png differ diff --git a/example/offline_sync_demo/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png b/example/offline_sync_demo/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png new file mode 100644 index 0000000..0a3f5fa Binary files /dev/null and b/example/offline_sync_demo/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png differ diff --git a/example/offline_sync_demo/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png b/example/offline_sync_demo/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png new file mode 100644 index 0000000..bdb5722 Binary files /dev/null and b/example/offline_sync_demo/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png differ diff --git a/example/offline_sync_demo/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png b/example/offline_sync_demo/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png new file mode 100644 index 0000000..f083318 Binary files /dev/null and b/example/offline_sync_demo/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png differ diff --git a/example/offline_sync_demo/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png b/example/offline_sync_demo/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png new file mode 100644 index 0000000..326c0e7 Binary files /dev/null and b/example/offline_sync_demo/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png differ diff --git a/example/offline_sync_demo/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png b/example/offline_sync_demo/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png new file mode 100644 index 0000000..2f1632c Binary files /dev/null and b/example/offline_sync_demo/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png differ diff --git a/example/offline_sync_demo/macos/Runner/Base.lproj/MainMenu.xib b/example/offline_sync_demo/macos/Runner/Base.lproj/MainMenu.xib new file mode 100644 index 0000000..80e867a --- /dev/null +++ b/example/offline_sync_demo/macos/Runner/Base.lproj/MainMenu.xib @@ -0,0 +1,343 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/example/offline_sync_demo/macos/Runner/Configs/AppInfo.xcconfig b/example/offline_sync_demo/macos/Runner/Configs/AppInfo.xcconfig new file mode 100644 index 0000000..732e11d --- /dev/null +++ b/example/offline_sync_demo/macos/Runner/Configs/AppInfo.xcconfig @@ -0,0 +1,14 @@ +// Application-level settings for the Runner target. +// +// This may be replaced with something auto-generated from metadata (e.g., pubspec.yaml) in the +// future. If not, the values below would default to using the project name when this becomes a +// 'flutter create' template. + +// The application's name. By default this is also the title of the Flutter window. +PRODUCT_NAME = offline_sync_demo + +// The application's bundle identifier +PRODUCT_BUNDLE_IDENTIFIER = com.example.offlineSyncDemo + +// The copyright displayed in application information +PRODUCT_COPYRIGHT = Copyright © 2026 com.example. All rights reserved. diff --git a/example/offline_sync_demo/macos/Runner/Configs/Debug.xcconfig b/example/offline_sync_demo/macos/Runner/Configs/Debug.xcconfig new file mode 100644 index 0000000..36b0fd9 --- /dev/null +++ b/example/offline_sync_demo/macos/Runner/Configs/Debug.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Debug.xcconfig" +#include "Warnings.xcconfig" diff --git a/example/offline_sync_demo/macos/Runner/Configs/Release.xcconfig b/example/offline_sync_demo/macos/Runner/Configs/Release.xcconfig new file mode 100644 index 0000000..dff4f49 --- /dev/null +++ b/example/offline_sync_demo/macos/Runner/Configs/Release.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Release.xcconfig" +#include "Warnings.xcconfig" diff --git a/example/offline_sync_demo/macos/Runner/Configs/Warnings.xcconfig b/example/offline_sync_demo/macos/Runner/Configs/Warnings.xcconfig new file mode 100644 index 0000000..42bcbf4 --- /dev/null +++ b/example/offline_sync_demo/macos/Runner/Configs/Warnings.xcconfig @@ -0,0 +1,13 @@ +WARNING_CFLAGS = -Wall -Wconditional-uninitialized -Wnullable-to-nonnull-conversion -Wmissing-method-return-type -Woverlength-strings +GCC_WARN_UNDECLARED_SELECTOR = YES +CLANG_UNDEFINED_BEHAVIOR_SANITIZER_NULLABILITY = YES +CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE +CLANG_WARN__DUPLICATE_METHOD_MATCH = YES +CLANG_WARN_PRAGMA_PACK = YES +CLANG_WARN_STRICT_PROTOTYPES = YES +CLANG_WARN_COMMA = YES +GCC_WARN_STRICT_SELECTOR_MATCH = YES +CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES +CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES +GCC_WARN_SHADOW = YES +CLANG_WARN_UNREACHABLE_CODE = YES diff --git a/example/offline_sync_demo/macos/Runner/DebugProfile.entitlements b/example/offline_sync_demo/macos/Runner/DebugProfile.entitlements new file mode 100644 index 0000000..dddb8a3 --- /dev/null +++ b/example/offline_sync_demo/macos/Runner/DebugProfile.entitlements @@ -0,0 +1,12 @@ + + + + + com.apple.security.app-sandbox + + com.apple.security.cs.allow-jit + + com.apple.security.network.server + + + diff --git a/example/offline_sync_demo/macos/Runner/Info.plist b/example/offline_sync_demo/macos/Runner/Info.plist new file mode 100644 index 0000000..4789daa --- /dev/null +++ b/example/offline_sync_demo/macos/Runner/Info.plist @@ -0,0 +1,32 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIconFile + + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSMinimumSystemVersion + $(MACOSX_DEPLOYMENT_TARGET) + NSHumanReadableCopyright + $(PRODUCT_COPYRIGHT) + NSMainNibFile + MainMenu + NSPrincipalClass + NSApplication + + diff --git a/example/offline_sync_demo/macos/Runner/MainFlutterWindow.swift b/example/offline_sync_demo/macos/Runner/MainFlutterWindow.swift new file mode 100644 index 0000000..3cc05eb --- /dev/null +++ b/example/offline_sync_demo/macos/Runner/MainFlutterWindow.swift @@ -0,0 +1,15 @@ +import Cocoa +import FlutterMacOS + +class MainFlutterWindow: NSWindow { + override func awakeFromNib() { + let flutterViewController = FlutterViewController() + let windowFrame = self.frame + self.contentViewController = flutterViewController + self.setFrame(windowFrame, display: true) + + RegisterGeneratedPlugins(registry: flutterViewController) + + super.awakeFromNib() + } +} diff --git a/example/offline_sync_demo/macos/Runner/Release.entitlements b/example/offline_sync_demo/macos/Runner/Release.entitlements new file mode 100644 index 0000000..852fa1a --- /dev/null +++ b/example/offline_sync_demo/macos/Runner/Release.entitlements @@ -0,0 +1,8 @@ + + + + + com.apple.security.app-sandbox + + + diff --git a/example/offline_sync_demo/macos/RunnerTests/RunnerTests.swift b/example/offline_sync_demo/macos/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000..61f3bd1 --- /dev/null +++ b/example/offline_sync_demo/macos/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Cocoa +import FlutterMacOS +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/example/offline_sync_demo/pubspec.yaml b/example/offline_sync_demo/pubspec.yaml new file mode 100644 index 0000000..804758e --- /dev/null +++ b/example/offline_sync_demo/pubspec.yaml @@ -0,0 +1,61 @@ +name: offline_sync_demo +description: Demo app for Serverpod Offline Sync. +publish_to: 'none' + +version: 1.0.0+1 + +environment: + sdk: ^3.10.3 + +dependencies: + flutter: + sdk: flutter + flutter_driver: + sdk: flutter + + http: ^1.5.0 + path: ^1.9.1 + path_provider: ^2.1.5 + serverpod_database: 3.5.0-beta.10 + serverpod_offline_sync_client: + path: ../../packages/serverpod_offline_sync_client + serverpod_offline_sync_test_client: + path: ../../test/serverpod_offline_sync_test_client + shadcn_flutter: 0.0.52 + uuid: ^4.5.3 + +dev_dependencies: + flutter_lints: ^6.0.0 + +dependency_overrides: + meta: 1.18.2 + serverpod_auth_core_client: + git: + url: https://github.com/marcelomendoncasoares/serverpod.git + path: modules/serverpod_auth/serverpod_auth_core/serverpod_auth_core_client + ref: fix-double-generator-bug + serverpod_client: + git: + url: https://github.com/marcelomendoncasoares/serverpod.git + path: packages/serverpod_client + ref: fix-double-generator-bug + serverpod_database: + git: + url: https://github.com/marcelomendoncasoares/serverpod.git + path: packages/serverpod_database + ref: fix-double-generator-bug + serverpod_offline_sync_shared: + path: ../../packages/serverpod_offline_sync_shared + serverpod_serialization: + git: + url: https://github.com/marcelomendoncasoares/serverpod.git + path: packages/serverpod_serialization + ref: fix-double-generator-bug + serverpod_shared: + git: + url: https://github.com/marcelomendoncasoares/serverpod.git + path: packages/serverpod_shared + ref: fix-double-generator-bug + +flutter: + uses-material-design: true diff --git a/example/offline_sync_demo/web/favicon.png b/example/offline_sync_demo/web/favicon.png new file mode 100644 index 0000000..8aaa46a Binary files /dev/null and b/example/offline_sync_demo/web/favicon.png differ diff --git a/example/offline_sync_demo/web/icons/Icon-192.png b/example/offline_sync_demo/web/icons/Icon-192.png new file mode 100644 index 0000000..b749bfe Binary files /dev/null and b/example/offline_sync_demo/web/icons/Icon-192.png differ diff --git a/example/offline_sync_demo/web/icons/Icon-512.png b/example/offline_sync_demo/web/icons/Icon-512.png new file mode 100644 index 0000000..88cfd48 Binary files /dev/null and b/example/offline_sync_demo/web/icons/Icon-512.png differ diff --git a/example/offline_sync_demo/web/icons/Icon-maskable-192.png b/example/offline_sync_demo/web/icons/Icon-maskable-192.png new file mode 100644 index 0000000..eb9b4d7 Binary files /dev/null and b/example/offline_sync_demo/web/icons/Icon-maskable-192.png differ diff --git a/example/offline_sync_demo/web/icons/Icon-maskable-512.png b/example/offline_sync_demo/web/icons/Icon-maskable-512.png new file mode 100644 index 0000000..d69c566 Binary files /dev/null and b/example/offline_sync_demo/web/icons/Icon-maskable-512.png differ diff --git a/example/offline_sync_demo/web/index.html b/example/offline_sync_demo/web/index.html new file mode 100644 index 0000000..78330b0 --- /dev/null +++ b/example/offline_sync_demo/web/index.html @@ -0,0 +1,46 @@ + + + + + + + + + + + + + + + + + + + + offline_sync_demo + + + + + + + diff --git a/example/offline_sync_demo/web/manifest.json b/example/offline_sync_demo/web/manifest.json new file mode 100644 index 0000000..be639ba --- /dev/null +++ b/example/offline_sync_demo/web/manifest.json @@ -0,0 +1,35 @@ +{ + "name": "offline_sync_demo", + "short_name": "offline_sync_demo", + "start_url": ".", + "display": "standalone", + "background_color": "#0175C2", + "theme_color": "#0175C2", + "description": "A new Flutter project.", + "orientation": "portrait-primary", + "prefer_related_applications": false, + "icons": [ + { + "src": "icons/Icon-192.png", + "sizes": "192x192", + "type": "image/png" + }, + { + "src": "icons/Icon-512.png", + "sizes": "512x512", + "type": "image/png" + }, + { + "src": "icons/Icon-maskable-192.png", + "sizes": "192x192", + "type": "image/png", + "purpose": "maskable" + }, + { + "src": "icons/Icon-maskable-512.png", + "sizes": "512x512", + "type": "image/png", + "purpose": "maskable" + } + ] +} diff --git a/example/offline_sync_demo/windows/.gitignore b/example/offline_sync_demo/windows/.gitignore new file mode 100644 index 0000000..d492d0d --- /dev/null +++ b/example/offline_sync_demo/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ephemeral/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/example/offline_sync_demo/windows/CMakeLists.txt b/example/offline_sync_demo/windows/CMakeLists.txt new file mode 100644 index 0000000..fc9a84e --- /dev/null +++ b/example/offline_sync_demo/windows/CMakeLists.txt @@ -0,0 +1,108 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.14) +project(offline_sync_demo LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "offline_sync_demo") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(VERSION 3.14...3.25) + +# Define build configuration option. +get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) +if(IS_MULTICONFIG) + set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" + CACHE STRING "" FORCE) +else() + if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") + endif() +endif() +# Define settings for the Profile build mode. +set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") +set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") +set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") +set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") + +# Use Unicode for all projects. +add_definitions(-DUNICODE -D_UNICODE) + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_17) + target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") + target_compile_options(${TARGET} PRIVATE /EHsc) + target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") + target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# Support files are copied into place next to the executable, so that it can +# run in place. This is done instead of making a separate bundle (as on Linux) +# so that building and running from within Visual Studio will work. +set(BUILD_BUNDLE_DIR "$") +# Make the "install" step default, as it's required to run. +set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +if(PLUGIN_BUNDLED_LIBRARIES) + install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + CONFIGURATIONS Profile;Release + COMPONENT Runtime) diff --git a/example/offline_sync_demo/windows/flutter/CMakeLists.txt b/example/offline_sync_demo/windows/flutter/CMakeLists.txt new file mode 100644 index 0000000..903f489 --- /dev/null +++ b/example/offline_sync_demo/windows/flutter/CMakeLists.txt @@ -0,0 +1,109 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.14) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. +set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") + +# Set fallback configurations for older versions of the flutter tool. +if (NOT DEFINED FLUTTER_TARGET_PLATFORM) + set(FLUTTER_TARGET_PLATFORM "windows-x64") +endif() + +# === Flutter Library === +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "flutter_export.h" + "flutter_windows.h" + "flutter_messenger.h" + "flutter_plugin_registrar.h" + "flutter_texture_registrar.h" +) +list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") +add_dependencies(flutter flutter_assemble) + +# === Wrapper === +list(APPEND CPP_WRAPPER_SOURCES_CORE + "core_implementations.cc" + "standard_codec.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_PLUGIN + "plugin_registrar.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_APP + "flutter_engine.cc" + "flutter_view_controller.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") + +# Wrapper sources needed for a plugin. +add_library(flutter_wrapper_plugin STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} +) +apply_standard_settings(flutter_wrapper_plugin) +set_target_properties(flutter_wrapper_plugin PROPERTIES + POSITION_INDEPENDENT_CODE ON) +set_target_properties(flutter_wrapper_plugin PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) +target_include_directories(flutter_wrapper_plugin PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_plugin flutter_assemble) + +# Wrapper sources needed for the runner. +add_library(flutter_wrapper_app STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_APP} +) +apply_standard_settings(flutter_wrapper_app) +target_link_libraries(flutter_wrapper_app PUBLIC flutter) +target_include_directories(flutter_wrapper_app PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_app flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") +set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} + ${PHONY_OUTPUT} + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" + ${FLUTTER_TARGET_PLATFORM} $ + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} +) diff --git a/example/offline_sync_demo/windows/flutter/generated_plugin_registrant.cc b/example/offline_sync_demo/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..8b6d468 --- /dev/null +++ b/example/offline_sync_demo/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,11 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + + +void RegisterPlugins(flutter::PluginRegistry* registry) { +} diff --git a/example/offline_sync_demo/windows/flutter/generated_plugin_registrant.h b/example/offline_sync_demo/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..dc139d8 --- /dev/null +++ b/example/offline_sync_demo/windows/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void RegisterPlugins(flutter::PluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/example/offline_sync_demo/windows/flutter/generated_plugins.cmake b/example/offline_sync_demo/windows/flutter/generated_plugins.cmake new file mode 100644 index 0000000..3ad69c6 --- /dev/null +++ b/example/offline_sync_demo/windows/flutter/generated_plugins.cmake @@ -0,0 +1,24 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST + jni +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/example/offline_sync_demo/windows/runner/CMakeLists.txt b/example/offline_sync_demo/windows/runner/CMakeLists.txt new file mode 100644 index 0000000..394917c --- /dev/null +++ b/example/offline_sync_demo/windows/runner/CMakeLists.txt @@ -0,0 +1,40 @@ +cmake_minimum_required(VERSION 3.14) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} WIN32 + "flutter_window.cpp" + "main.cpp" + "utils.cpp" + "win32_window.cpp" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" + "Runner.rc" + "runner.exe.manifest" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the build version. +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") + +# Disable Windows macros that collide with C++ standard library functions. +target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") + +# Add dependency libraries and include directories. Add any application-specific +# dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) +target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/example/offline_sync_demo/windows/runner/Runner.rc b/example/offline_sync_demo/windows/runner/Runner.rc new file mode 100644 index 0000000..a840531 --- /dev/null +++ b/example/offline_sync_demo/windows/runner/Runner.rc @@ -0,0 +1,121 @@ +// Microsoft Visual C++ generated resource script. +// +#pragma code_page(65001) +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (United States) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_APP_ICON ICON "resources\\app_icon.ico" + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) +#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD +#else +#define VERSION_AS_NUMBER 1,0,0,0 +#endif + +#if defined(FLUTTER_VERSION) +#define VERSION_AS_STRING FLUTTER_VERSION +#else +#define VERSION_AS_STRING "1.0.0" +#endif + +VS_VERSION_INFO VERSIONINFO + FILEVERSION VERSION_AS_NUMBER + PRODUCTVERSION VERSION_AS_NUMBER + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK +#ifdef _DEBUG + FILEFLAGS VS_FF_DEBUG +#else + FILEFLAGS 0x0L +#endif + FILEOS VOS__WINDOWS32 + FILETYPE VFT_APP + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904e4" + BEGIN + VALUE "CompanyName", "com.example" "\0" + VALUE "FileDescription", "offline_sync_demo" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "offline_sync_demo" "\0" + VALUE "LegalCopyright", "Copyright (C) 2026 com.example. All rights reserved." "\0" + VALUE "OriginalFilename", "offline_sync_demo.exe" "\0" + VALUE "ProductName", "offline_sync_demo" "\0" + VALUE "ProductVersion", VERSION_AS_STRING "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1252 + END +END + +#endif // English (United States) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED diff --git a/example/offline_sync_demo/windows/runner/flutter_window.cpp b/example/offline_sync_demo/windows/runner/flutter_window.cpp new file mode 100644 index 0000000..955ee30 --- /dev/null +++ b/example/offline_sync_demo/windows/runner/flutter_window.cpp @@ -0,0 +1,71 @@ +#include "flutter_window.h" + +#include + +#include "flutter/generated_plugin_registrant.h" + +FlutterWindow::FlutterWindow(const flutter::DartProject& project) + : project_(project) {} + +FlutterWindow::~FlutterWindow() {} + +bool FlutterWindow::OnCreate() { + if (!Win32Window::OnCreate()) { + return false; + } + + RECT frame = GetClientArea(); + + // The size here must match the window dimensions to avoid unnecessary surface + // creation / destruction in the startup path. + flutter_controller_ = std::make_unique( + frame.right - frame.left, frame.bottom - frame.top, project_); + // Ensure that basic setup of the controller was successful. + if (!flutter_controller_->engine() || !flutter_controller_->view()) { + return false; + } + RegisterPlugins(flutter_controller_->engine()); + SetChildContent(flutter_controller_->view()->GetNativeWindow()); + + flutter_controller_->engine()->SetNextFrameCallback([&]() { + this->Show(); + }); + + // Flutter can complete the first frame before the "show window" callback is + // registered. The following call ensures a frame is pending to ensure the + // window is shown. It is a no-op if the first frame hasn't completed yet. + flutter_controller_->ForceRedraw(); + + return true; +} + +void FlutterWindow::OnDestroy() { + if (flutter_controller_) { + flutter_controller_ = nullptr; + } + + Win32Window::OnDestroy(); +} + +LRESULT +FlutterWindow::MessageHandler(HWND hwnd, UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + // Give Flutter, including plugins, an opportunity to handle window messages. + if (flutter_controller_) { + std::optional result = + flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, + lparam); + if (result) { + return *result; + } + } + + switch (message) { + case WM_FONTCHANGE: + flutter_controller_->engine()->ReloadSystemFonts(); + break; + } + + return Win32Window::MessageHandler(hwnd, message, wparam, lparam); +} diff --git a/example/offline_sync_demo/windows/runner/flutter_window.h b/example/offline_sync_demo/windows/runner/flutter_window.h new file mode 100644 index 0000000..6da0652 --- /dev/null +++ b/example/offline_sync_demo/windows/runner/flutter_window.h @@ -0,0 +1,33 @@ +#ifndef RUNNER_FLUTTER_WINDOW_H_ +#define RUNNER_FLUTTER_WINDOW_H_ + +#include +#include + +#include + +#include "win32_window.h" + +// A window that does nothing but host a Flutter view. +class FlutterWindow : public Win32Window { + public: + // Creates a new FlutterWindow hosting a Flutter view running |project|. + explicit FlutterWindow(const flutter::DartProject& project); + virtual ~FlutterWindow(); + + protected: + // Win32Window: + bool OnCreate() override; + void OnDestroy() override; + LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, + LPARAM const lparam) noexcept override; + + private: + // The project to run. + flutter::DartProject project_; + + // The Flutter instance hosted by this window. + std::unique_ptr flutter_controller_; +}; + +#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/example/offline_sync_demo/windows/runner/main.cpp b/example/offline_sync_demo/windows/runner/main.cpp new file mode 100644 index 0000000..32a7974 --- /dev/null +++ b/example/offline_sync_demo/windows/runner/main.cpp @@ -0,0 +1,43 @@ +#include +#include +#include + +#include "flutter_window.h" +#include "utils.h" + +int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, + _In_ wchar_t *command_line, _In_ int show_command) { + // Attach to console when present (e.g., 'flutter run') or create a + // new console when running with a debugger. + if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { + CreateAndAttachConsole(); + } + + // Initialize COM, so that it is available for use in the library and/or + // plugins. + ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); + + flutter::DartProject project(L"data"); + + std::vector command_line_arguments = + GetCommandLineArguments(); + + project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); + + FlutterWindow window(project); + Win32Window::Point origin(10, 10); + Win32Window::Size size(1280, 720); + if (!window.Create(L"offline_sync_demo", origin, size)) { + return EXIT_FAILURE; + } + window.SetQuitOnClose(true); + + ::MSG msg; + while (::GetMessage(&msg, nullptr, 0, 0)) { + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); + } + + ::CoUninitialize(); + return EXIT_SUCCESS; +} diff --git a/example/offline_sync_demo/windows/runner/resource.h b/example/offline_sync_demo/windows/runner/resource.h new file mode 100644 index 0000000..66a65d1 --- /dev/null +++ b/example/offline_sync_demo/windows/runner/resource.h @@ -0,0 +1,16 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Runner.rc +// +#define IDI_APP_ICON 101 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/example/offline_sync_demo/windows/runner/resources/app_icon.ico b/example/offline_sync_demo/windows/runner/resources/app_icon.ico new file mode 100644 index 0000000..c04e20c Binary files /dev/null and b/example/offline_sync_demo/windows/runner/resources/app_icon.ico differ diff --git a/example/offline_sync_demo/windows/runner/runner.exe.manifest b/example/offline_sync_demo/windows/runner/runner.exe.manifest new file mode 100644 index 0000000..153653e --- /dev/null +++ b/example/offline_sync_demo/windows/runner/runner.exe.manifest @@ -0,0 +1,14 @@ + + + + + PerMonitorV2 + + + + + + + + + diff --git a/example/offline_sync_demo/windows/runner/utils.cpp b/example/offline_sync_demo/windows/runner/utils.cpp new file mode 100644 index 0000000..3a0b465 --- /dev/null +++ b/example/offline_sync_demo/windows/runner/utils.cpp @@ -0,0 +1,65 @@ +#include "utils.h" + +#include +#include +#include +#include + +#include + +void CreateAndAttachConsole() { + if (::AllocConsole()) { + FILE *unused; + if (freopen_s(&unused, "CONOUT$", "w", stdout)) { + _dup2(_fileno(stdout), 1); + } + if (freopen_s(&unused, "CONOUT$", "w", stderr)) { + _dup2(_fileno(stdout), 2); + } + std::ios::sync_with_stdio(); + FlutterDesktopResyncOutputStreams(); + } +} + +std::vector GetCommandLineArguments() { + // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. + int argc; + wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); + if (argv == nullptr) { + return std::vector(); + } + + std::vector command_line_arguments; + + // Skip the first argument as it's the binary name. + for (int i = 1; i < argc; i++) { + command_line_arguments.push_back(Utf8FromUtf16(argv[i])); + } + + ::LocalFree(argv); + + return command_line_arguments; +} + +std::string Utf8FromUtf16(const wchar_t* utf16_string) { + if (utf16_string == nullptr) { + return std::string(); + } + unsigned int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + -1, nullptr, 0, nullptr, nullptr) + -1; // remove the trailing null character + int input_length = (int)wcslen(utf16_string); + std::string utf8_string; + if (target_length == 0 || target_length > utf8_string.max_size()) { + return utf8_string; + } + utf8_string.resize(target_length); + int converted_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, utf8_string.data(), target_length, nullptr, nullptr); + if (converted_length == 0) { + return std::string(); + } + return utf8_string; +} diff --git a/example/offline_sync_demo/windows/runner/utils.h b/example/offline_sync_demo/windows/runner/utils.h new file mode 100644 index 0000000..3879d54 --- /dev/null +++ b/example/offline_sync_demo/windows/runner/utils.h @@ -0,0 +1,19 @@ +#ifndef RUNNER_UTILS_H_ +#define RUNNER_UTILS_H_ + +#include +#include + +// Creates a console for the process, and redirects stdout and stderr to +// it for both the runner and the Flutter library. +void CreateAndAttachConsole(); + +// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string +// encoded in UTF-8. Returns an empty std::string on failure. +std::string Utf8FromUtf16(const wchar_t* utf16_string); + +// Gets the command line arguments passed in as a std::vector, +// encoded in UTF-8. Returns an empty std::vector on failure. +std::vector GetCommandLineArguments(); + +#endif // RUNNER_UTILS_H_ diff --git a/example/offline_sync_demo/windows/runner/win32_window.cpp b/example/offline_sync_demo/windows/runner/win32_window.cpp new file mode 100644 index 0000000..60608d0 --- /dev/null +++ b/example/offline_sync_demo/windows/runner/win32_window.cpp @@ -0,0 +1,288 @@ +#include "win32_window.h" + +#include +#include + +#include "resource.h" + +namespace { + +/// Window attribute that enables dark mode window decorations. +/// +/// Redefined in case the developer's machine has a Windows SDK older than +/// version 10.0.22000.0. +/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute +#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE +#define DWMWA_USE_IMMERSIVE_DARK_MODE 20 +#endif + +constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; + +/// Registry key for app theme preference. +/// +/// A value of 0 indicates apps should use dark mode. A non-zero or missing +/// value indicates apps should use light mode. +constexpr const wchar_t kGetPreferredBrightnessRegKey[] = + L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; +constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme"; + +// The number of Win32Window objects that currently exist. +static int g_active_window_count = 0; + +using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); + +// Scale helper to convert logical scaler values to physical using passed in +// scale factor +int Scale(int source, double scale_factor) { + return static_cast(source * scale_factor); +} + +// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. +// This API is only needed for PerMonitor V1 awareness mode. +void EnableFullDpiSupportIfAvailable(HWND hwnd) { + HMODULE user32_module = LoadLibraryA("User32.dll"); + if (!user32_module) { + return; + } + auto enable_non_client_dpi_scaling = + reinterpret_cast( + GetProcAddress(user32_module, "EnableNonClientDpiScaling")); + if (enable_non_client_dpi_scaling != nullptr) { + enable_non_client_dpi_scaling(hwnd); + } + FreeLibrary(user32_module); +} + +} // namespace + +// Manages the Win32Window's window class registration. +class WindowClassRegistrar { + public: + ~WindowClassRegistrar() = default; + + // Returns the singleton registrar instance. + static WindowClassRegistrar* GetInstance() { + if (!instance_) { + instance_ = new WindowClassRegistrar(); + } + return instance_; + } + + // Returns the name of the window class, registering the class if it hasn't + // previously been registered. + const wchar_t* GetWindowClass(); + + // Unregisters the window class. Should only be called if there are no + // instances of the window. + void UnregisterWindowClass(); + + private: + WindowClassRegistrar() = default; + + static WindowClassRegistrar* instance_; + + bool class_registered_ = false; +}; + +WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; + +const wchar_t* WindowClassRegistrar::GetWindowClass() { + if (!class_registered_) { + WNDCLASS window_class{}; + window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); + window_class.lpszClassName = kWindowClassName; + window_class.style = CS_HREDRAW | CS_VREDRAW; + window_class.cbClsExtra = 0; + window_class.cbWndExtra = 0; + window_class.hInstance = GetModuleHandle(nullptr); + window_class.hIcon = + LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); + window_class.hbrBackground = 0; + window_class.lpszMenuName = nullptr; + window_class.lpfnWndProc = Win32Window::WndProc; + RegisterClass(&window_class); + class_registered_ = true; + } + return kWindowClassName; +} + +void WindowClassRegistrar::UnregisterWindowClass() { + UnregisterClass(kWindowClassName, nullptr); + class_registered_ = false; +} + +Win32Window::Win32Window() { + ++g_active_window_count; +} + +Win32Window::~Win32Window() { + --g_active_window_count; + Destroy(); +} + +bool Win32Window::Create(const std::wstring& title, + const Point& origin, + const Size& size) { + Destroy(); + + const wchar_t* window_class = + WindowClassRegistrar::GetInstance()->GetWindowClass(); + + const POINT target_point = {static_cast(origin.x), + static_cast(origin.y)}; + HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); + UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); + double scale_factor = dpi / 96.0; + + HWND window = CreateWindow( + window_class, title.c_str(), WS_OVERLAPPEDWINDOW, + Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), + Scale(size.width, scale_factor), Scale(size.height, scale_factor), + nullptr, nullptr, GetModuleHandle(nullptr), this); + + if (!window) { + return false; + } + + UpdateTheme(window); + + return OnCreate(); +} + +bool Win32Window::Show() { + return ShowWindow(window_handle_, SW_SHOWNORMAL); +} + +// static +LRESULT CALLBACK Win32Window::WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + if (message == WM_NCCREATE) { + auto window_struct = reinterpret_cast(lparam); + SetWindowLongPtr(window, GWLP_USERDATA, + reinterpret_cast(window_struct->lpCreateParams)); + + auto that = static_cast(window_struct->lpCreateParams); + EnableFullDpiSupportIfAvailable(window); + that->window_handle_ = window; + } else if (Win32Window* that = GetThisFromHandle(window)) { + return that->MessageHandler(window, message, wparam, lparam); + } + + return DefWindowProc(window, message, wparam, lparam); +} + +LRESULT +Win32Window::MessageHandler(HWND hwnd, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + switch (message) { + case WM_DESTROY: + window_handle_ = nullptr; + Destroy(); + if (quit_on_close_) { + PostQuitMessage(0); + } + return 0; + + case WM_DPICHANGED: { + auto newRectSize = reinterpret_cast(lparam); + LONG newWidth = newRectSize->right - newRectSize->left; + LONG newHeight = newRectSize->bottom - newRectSize->top; + + SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, + newHeight, SWP_NOZORDER | SWP_NOACTIVATE); + + return 0; + } + case WM_SIZE: { + RECT rect = GetClientArea(); + if (child_content_ != nullptr) { + // Size and position the child window. + MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, + rect.bottom - rect.top, TRUE); + } + return 0; + } + + case WM_ACTIVATE: + if (child_content_ != nullptr) { + SetFocus(child_content_); + } + return 0; + + case WM_DWMCOLORIZATIONCOLORCHANGED: + UpdateTheme(hwnd); + return 0; + } + + return DefWindowProc(window_handle_, message, wparam, lparam); +} + +void Win32Window::Destroy() { + OnDestroy(); + + if (window_handle_) { + DestroyWindow(window_handle_); + window_handle_ = nullptr; + } + if (g_active_window_count == 0) { + WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); + } +} + +Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { + return reinterpret_cast( + GetWindowLongPtr(window, GWLP_USERDATA)); +} + +void Win32Window::SetChildContent(HWND content) { + child_content_ = content; + SetParent(content, window_handle_); + RECT frame = GetClientArea(); + + MoveWindow(content, frame.left, frame.top, frame.right - frame.left, + frame.bottom - frame.top, true); + + SetFocus(child_content_); +} + +RECT Win32Window::GetClientArea() { + RECT frame; + GetClientRect(window_handle_, &frame); + return frame; +} + +HWND Win32Window::GetHandle() { + return window_handle_; +} + +void Win32Window::SetQuitOnClose(bool quit_on_close) { + quit_on_close_ = quit_on_close; +} + +bool Win32Window::OnCreate() { + // No-op; provided for subclasses. + return true; +} + +void Win32Window::OnDestroy() { + // No-op; provided for subclasses. +} + +void Win32Window::UpdateTheme(HWND const window) { + DWORD light_mode; + DWORD light_mode_size = sizeof(light_mode); + LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey, + kGetPreferredBrightnessRegValue, + RRF_RT_REG_DWORD, nullptr, &light_mode, + &light_mode_size); + + if (result == ERROR_SUCCESS) { + BOOL enable_dark_mode = light_mode == 0; + DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE, + &enable_dark_mode, sizeof(enable_dark_mode)); + } +} diff --git a/example/offline_sync_demo/windows/runner/win32_window.h b/example/offline_sync_demo/windows/runner/win32_window.h new file mode 100644 index 0000000..e901dde --- /dev/null +++ b/example/offline_sync_demo/windows/runner/win32_window.h @@ -0,0 +1,102 @@ +#ifndef RUNNER_WIN32_WINDOW_H_ +#define RUNNER_WIN32_WINDOW_H_ + +#include + +#include +#include +#include + +// A class abstraction for a high DPI-aware Win32 Window. Intended to be +// inherited from by classes that wish to specialize with custom +// rendering and input handling +class Win32Window { + public: + struct Point { + unsigned int x; + unsigned int y; + Point(unsigned int x, unsigned int y) : x(x), y(y) {} + }; + + struct Size { + unsigned int width; + unsigned int height; + Size(unsigned int width, unsigned int height) + : width(width), height(height) {} + }; + + Win32Window(); + virtual ~Win32Window(); + + // Creates a win32 window with |title| that is positioned and sized using + // |origin| and |size|. New windows are created on the default monitor. Window + // sizes are specified to the OS in physical pixels, hence to ensure a + // consistent size this function will scale the inputted width and height as + // as appropriate for the default monitor. The window is invisible until + // |Show| is called. Returns true if the window was created successfully. + bool Create(const std::wstring& title, const Point& origin, const Size& size); + + // Show the current window. Returns true if the window was successfully shown. + bool Show(); + + // Release OS resources associated with window. + void Destroy(); + + // Inserts |content| into the window tree. + void SetChildContent(HWND content); + + // Returns the backing Window handle to enable clients to set icon and other + // window properties. Returns nullptr if the window has been destroyed. + HWND GetHandle(); + + // If true, closing this window will quit the application. + void SetQuitOnClose(bool quit_on_close); + + // Return a RECT representing the bounds of the current client area. + RECT GetClientArea(); + + protected: + // Processes and route salient window messages for mouse handling, + // size change and DPI. Delegates handling of these to member overloads that + // inheriting classes can handle. + virtual LRESULT MessageHandler(HWND window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Called when CreateAndShow is called, allowing subclass window-related + // setup. Subclasses should return false if setup fails. + virtual bool OnCreate(); + + // Called when Destroy is called. + virtual void OnDestroy(); + + private: + friend class WindowClassRegistrar; + + // OS callback called by message pump. Handles the WM_NCCREATE message which + // is passed when the non-client area is being created and enables automatic + // non-client DPI scaling so that the non-client area automatically + // responds to changes in DPI. All other messages are handled by + // MessageHandler. + static LRESULT CALLBACK WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Retrieves a class instance pointer for |window| + static Win32Window* GetThisFromHandle(HWND const window) noexcept; + + // Update the window frame's theme to match the system theme. + static void UpdateTheme(HWND const window); + + bool quit_on_close_ = false; + + // window handle for top level window. + HWND window_handle_ = nullptr; + + // window handle for hosted content. + HWND child_content_ = nullptr; +}; + +#endif // RUNNER_WIN32_WINDOW_H_ diff --git a/packages/serverpod_offline_sync_client/lib/src/crdt/client_sync.dart b/packages/serverpod_offline_sync_client/lib/src/crdt/client_sync.dart index 365a7a8..105228e 100644 --- a/packages/serverpod_offline_sync_client/lib/src/crdt/client_sync.dart +++ b/packages/serverpod_offline_sync_client/lib/src/crdt/client_sync.dart @@ -34,8 +34,11 @@ class CrdtSyncClient { /// Pushes local pending changes for [session] to the remote peer once. /// /// The [session] must be wrapped in a [CrdtDatabaseSession]. - Future syncOnce(DatabaseSession session) async { - await _startSyncSession(session, once: true).done; + Future syncOnce( + DatabaseSession session, { + CrdtSyncOnMergeSuccess? onMergeSuccess, + }) async { + await _startSyncSession(session, once: true, onMergeSuccess: onMergeSuccess).done; } /// Keeps synchronizing [session] with the remote peer until cancelled through diff --git a/packages/serverpod_offline_sync_client/lib/src/crdt/sync.dart b/packages/serverpod_offline_sync_client/lib/src/crdt/sync.dart index 7acf12f..cc80a60 100644 --- a/packages/serverpod_offline_sync_client/lib/src/crdt/sync.dart +++ b/packages/serverpod_offline_sync_client/lib/src/crdt/sync.dart @@ -340,6 +340,17 @@ class CrdtSync { yield CrdtSyncClose(); await inboundIterator.moveAndThrowIfNot(); sessionCompleted = true; + // Keep reading until the peer closes its side so the underlying + // transport subscription reaches "done" instead of being left paused. + // A paused inbound controller stalls the peer's stream teardown for + // several seconds (the transport's close timeout), which lands on the + // critical path of the next sync round over a shared connection. + // + // The drain runs detached: awaiting it here would deadlock the + // symmetric close handshake, since the peer only closes its side once + // our own outbound stream closes, which happens after this generator + // returns. + unawaited(_drainUntilDone(inboundIterator)); return; } @@ -348,8 +359,10 @@ class CrdtSync { } } finally { // Cancelling inbound on normal completion races with WebSocket stream - // teardown and produces "connection closed" errors on the peer. Keep - // cleanup for abnormal exits so listener cancellation can unblock. + // teardown and produces "connection closed" errors on the peer. On normal + // completion the inbound is instead drained to "done" (see above). Keep + // forced cancellation for abnormal exits so listener cancellation can + // unblock. if (!sessionCompleted) { // Best-effort cleanup, since the transport will close the socket anyway. const waitTimeout = Duration(milliseconds: 200); @@ -358,6 +371,24 @@ class CrdtSync { } } + /// Drains [iterator] until the peer closes the stream. + /// + /// Used to settle the inbound transport after the `once` close handshake so + /// its controller reaches "done" with an active listener instead of being + /// torn down while paused. Trailing events (idle timeouts, late frames) are + /// discarded; errors are swallowed since the transport is closing anyway. + static Future _drainUntilDone( + StreamIterator iterator, + ) async { + try { + while (await iterator.moveNext()) { + // Discard whatever the peer sends before it closes its side. + } + } on Object catch (_) { + // Best-effort: the transport is shutting down. + } + } + void _validateSyncTablesHash(String syncTablesHash) { if (syncTablesHash != currentSyncTablesHash) { throw SyncTablesHashMismatchException( diff --git a/packages/serverpod_offline_sync_client/lib/src/database/database.dart b/packages/serverpod_offline_sync_client/lib/src/database/database.dart index 2307e9f..727ac00 100644 --- a/packages/serverpod_offline_sync_client/lib/src/database/database.dart +++ b/packages/serverpod_offline_sync_client/lib/src/database/database.dart @@ -55,6 +55,8 @@ class CrdtDatabase implements Database { final Duration _continuousSyncInterval; final CrdtMutationRecorder _recorder; + bool _initialized = false; + Future? _initializing; late final CrdtSync _sync = CrdtSync( syncTables: _syncTables, @@ -65,7 +67,27 @@ class CrdtDatabase implements Database { /// Initializes the CRDT database. Future initialize() async { - await _recorder.initialize(); + final initializing = _recorder.initialize().then((_) { + _initialized = true; + }); + _initializing = initializing; + try { + await initializing; + } finally { + if (identical(_initializing, initializing)) { + _initializing = null; + } + } + } + + Future _ensureInitialized() async { + if (_initialized) return; + final initializing = _initializing; + if (initializing != null) { + await initializing; + return; + } + await initialize(); } /// The hash describing the synchronized schema configured for this database. @@ -73,6 +95,7 @@ class CrdtDatabase implements Database { /// Returns the current node identifier for the effective user. Future currentNodeId({UuidValue? userId}) async { + await _ensureInitialized(); final effectiveUserId = await _requireUserId(userId); final user = await _recorder.getOrCreateScope(effectiveUserId); return user.currentNode!.uuidNodeId; @@ -85,6 +108,7 @@ class CrdtDatabase implements Database { bool once = false, CrdtSyncOnMergeSuccess? onMergeSuccess, }) async* { + await _ensureInitialized(); final effectiveUserId = await _requireUserId(userId); yield* _sync.sync( _delegate.session, @@ -101,6 +125,7 @@ class CrdtDatabase implements Database { Hlc syncedHlc, { UuidValue? userId, }) async { + await _ensureInitialized(); final effectiveUserId = await _requireUserId(userId); await _recorder.recordSyncCheckpoint( effectiveUserId, @@ -119,6 +144,7 @@ class CrdtDatabase implements Database { UuidValue? scopeId, }) async { if (mergeSet.isEmpty) return; + await _ensureInitialized(); final effectiveScopeId = scopeId ?? @@ -181,6 +207,7 @@ class CrdtDatabase implements Database { LockMode? lockMode, LockBehavior? lockBehavior, }) async { + await _ensureInitialized(); final result = await _delegate.find( where: _whereVisibleWithTombstone(where, include, transaction), limit: limit, @@ -206,6 +233,7 @@ class CrdtDatabase implements Database { LockMode? lockMode, LockBehavior? lockBehavior, }) async { + await _ensureInitialized(); final table = serializationManager.getTableForType(T); final where = table?.id.equals(id); final result = await _delegate.findFirstRow( @@ -231,6 +259,7 @@ class CrdtDatabase implements Database { LockMode? lockMode, LockBehavior? lockBehavior, }) async { + await _ensureInitialized(); final result = await _delegate.findFirstRow( where: _whereVisibleWithTombstone(where, include, transaction), offset: offset, @@ -255,6 +284,7 @@ class CrdtDatabase implements Database { bool ignoreConflicts = false, }) async { if (rows.isEmpty) return []; + await _ensureInitialized(); return DatabaseUtil.runInTransactionOrSavepoint( _delegate, transaction, @@ -278,6 +308,7 @@ class CrdtDatabase implements Database { T row, { Transaction? transaction, }) async { + await _ensureInitialized(); return DatabaseUtil.runInTransactionOrSavepoint( _delegate, transaction, @@ -323,6 +354,7 @@ class CrdtDatabase implements Database { Expression? updateWhere, Transaction? transaction, }) async { + await _ensureInitialized(); if (T == CrdtSyncIntegrityViolation) { return _delegate.upsertRow( row, @@ -343,6 +375,7 @@ class CrdtDatabase implements Database { Transaction? transaction, }) async { if (rows.isEmpty) return []; + await _ensureInitialized(); return DatabaseUtil.runInTransactionOrSavepoint( _delegate, transaction, @@ -369,6 +402,7 @@ class CrdtDatabase implements Database { List? columns, Transaction? transaction, }) async { + await _ensureInitialized(); return DatabaseUtil.runInTransactionOrSavepoint( _delegate, transaction, @@ -423,6 +457,7 @@ class CrdtDatabase implements Database { required List columnValues, Transaction? transaction, }) async { + await _ensureInitialized(); final table = serializationManager.getTableForType(T); if (table == null) return null; @@ -447,6 +482,7 @@ class CrdtDatabase implements Database { bool orderDescending = false, Transaction? transaction, }) async { + await _ensureInitialized(); if (_recorder.isCrdtTracked()) { _assertNoScopeIdColumnValues(columnValues); } @@ -487,6 +523,7 @@ class CrdtDatabase implements Database { Transaction? transaction, }) async { if (rows.isEmpty) return []; + await _ensureInitialized(); return deleteWhere( where: rows.first.table.id.inSet( rows.map((row) => row.id).castToIdType().toSet(), @@ -505,6 +542,7 @@ class CrdtDatabase implements Database { T row, { Transaction? transaction, }) async { + await _ensureInitialized(); final deletedRows = await deleteWhere( where: row.table.id.equals(row.id), transaction: transaction, @@ -527,6 +565,7 @@ class CrdtDatabase implements Database { bool orderDescending = false, Transaction? transaction, }) async { + await _ensureInitialized(); if (!_recorder.isCrdtTracked()) { return _delegate.deleteWhere( where: where, @@ -566,6 +605,7 @@ class CrdtDatabase implements Database { bool useCache = true, Transaction? transaction, }) async { + await _ensureInitialized(); return _delegate.count( where: _whereVisibleWithTombstone(where, null, transaction), limit: limit, @@ -581,6 +621,7 @@ class CrdtDatabase implements Database { required Transaction transaction, LockBehavior lockBehavior = LockBehavior.wait, }) async { + await _ensureInitialized(); return _delegate.lockRows( where: _whereVisibleWithTombstone(where, null, transaction)!, lockMode: lockMode, @@ -594,6 +635,9 @@ class CrdtDatabase implements Database { TransactionFunction transactionFunction, { TransactionSettings? settings, }) async { + // Do not initialize CRDT here. Serverpod runs database migrations inside + // [transaction] before CRDT tables exist. Callers that need CRDT state + // ([transactionForUser], mutating ORM methods) initialize explicitly. return _delegate.transaction( transactionFunction, settings: settings, @@ -610,6 +654,7 @@ class CrdtDatabase implements Database { TransactionFunction transactionFunction, { TransactionSettings? settings, }) async { + await _ensureInitialized(); // Ensure that the user exists with a node before starting the transaction. final user = await _recorder.getOrCreateScope(userId); diff --git a/packages/serverpod_offline_sync_client/lib/src/database/merge_utils/foreign_key_projector.dart b/packages/serverpod_offline_sync_client/lib/src/database/merge_utils/foreign_key_projector.dart index 4ee0463..663d08c 100644 --- a/packages/serverpod_offline_sync_client/lib/src/database/merge_utils/foreign_key_projector.dart +++ b/packages/serverpod_offline_sync_client/lib/src/database/merge_utils/foreign_key_projector.dart @@ -239,7 +239,15 @@ extension _CrdtForeignKeyProjector on CrdtMutationRecorder { attempts[fieldKey] = (value: attemptedValue, reason: null); if (attemptedValue == null) continue; - if (await _foreignKeyTargetVisible(edge, attemptedValue, transaction)) { + final targetPresence = await _lookupForeignKeyTargetPresence( + parentTableName: edge.parentTableName, + parentColumn: edge.parentColumn, + value: attemptedValue, + transaction: transaction, + ); + if (targetPresence == _ForeignKeyTargetPresence.visible || + (targetPresence == _ForeignKeyTargetPresence.hidden && + edge.action == ForeignKeyAction.cascade)) { continue; } @@ -1053,25 +1061,6 @@ extension _CrdtForeignKeyProjector on CrdtMutationRecorder { return (valid: true, value: defaultValue); } - Future _foreignKeyTargetVisible( - _ForeignKeyEdge edge, - UuidValue value, - Transaction transaction, - ) async { - final rowIds = await _findVisibleDomainRowIdsWhere( - tableName: edge.parentTableName, - predicates: [ - _domainColumnPredicate( - 'scopeId', - _getHlcManager(transaction).normalizedScopeId, - ), - _domainColumnPredicate(edge.parentColumn, value), - ], - transaction: transaction, - ); - return rowIds.isNotEmpty; - } - Future<_ForeignKeyDefaultProjection> _defaultProjectionValueFromDatabase( _ForeignKeyEdge edge, Transaction transaction, @@ -1081,14 +1070,16 @@ extension _CrdtForeignKeyProjector on CrdtMutationRecorder { return (valid: edge.childNullable, value: null); } - final targetVisible = await _foreignKeyTargetVisible( - edge, - defaultValue, - transaction, + final targetVisible = await _lookupForeignKeyTargetPresence( + parentTableName: edge.parentTableName, + parentColumn: edge.parentColumn, + value: defaultValue, + transaction: transaction, ); - if (!targetVisible) return (valid: false, value: null); - - return (valid: true, value: defaultValue); + if (targetVisible == _ForeignKeyTargetPresence.visible) { + return (valid: true, value: defaultValue); + } + return (valid: false, value: null); } UuidValue? _parentReferenceValue( diff --git a/packages/serverpod_offline_sync_client/lib/src/database/recorder.dart b/packages/serverpod_offline_sync_client/lib/src/database/recorder.dart index 2de5e8e..77eefe4 100644 --- a/packages/serverpod_offline_sync_client/lib/src/database/recorder.dart +++ b/packages/serverpod_offline_sync_client/lib/src/database/recorder.dart @@ -52,6 +52,12 @@ enum _UniqueConflictReleaseKind { syntheticUuid, } +enum _ForeignKeyTargetPresence { + absent, + visible, + hidden, +} + /// Persists additional CRDT rows after a mutating ORM operation completes. /// /// Callbacks receive the underlying database (not the CRDT proxy) and the @@ -73,11 +79,7 @@ class CrdtMutationRecorder { late final DatabaseSession _dbSession = _db.session; - late final _session = CrdtDatabaseSession( - _db, - syncTables: syncTables, - persistentUserId: persistentUserId, - ); + late final _session = BasicDatabaseSession(_db); late final CrdtScopeManager _scopeManager = CrdtScopeManager(_dbSession); @@ -1092,6 +1094,35 @@ WHERE (${predicates.join(') AND (')}) }; } + Future<_ForeignKeyTargetPresence> _lookupForeignKeyTargetPresence({ + required String parentTableName, + required String parentColumn, + required UuidValue value, + required Transaction transaction, + }) async { + final (tableId, _) = _schema[parentTableName]!; + final scopeId = _getHlcManager(transaction).normalizedScopeId; + final result = await _db.unsafeQuery( + ''' +SELECT CASE + WHEN r."id" IS NULL OR r."visibility" <= $crdtRowLastVisibleVisibilityIndex THEN 1 + ELSE 0 +END AS visible +FROM "${_escapeIdentifier(parentTableName)}" d +LEFT JOIN "crdt_data_rows" r + ON r."scopeId" = $scopeId AND r."tblId" = $tableId AND r."uuidRowId" = d."id" +WHERE (${_domainColumnPredicate('scopeId', scopeId)}) + AND (${_domainColumnPredicate(parentColumn, value)}) +LIMIT 1 +''', + transaction: transaction, + ); + if (result.isEmpty) return _ForeignKeyTargetPresence.absent; + return (result.first[0] as num) == 1 + ? _ForeignKeyTargetPresence.visible + : _ForeignKeyTargetPresence.hidden; + } + Future _updateDomainRows( String tableName, Set rowIds, diff --git a/pubspec.yaml b/pubspec.yaml index f263ce5..5a40d8b 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -19,49 +19,59 @@ dev_dependencies: dependency_overrides: serverpod: git: - url: https://github.com/serverpod/serverpod.git + url: https://github.com/marcelomendoncasoares/serverpod.git path: packages/serverpod - ref: 1a6878faf9bf41c1a26ff4f0ebac2f0ac151b668 + ref: fix-double-generator-bug + serverpod_auth_core_client: + git: + url: https://github.com/marcelomendoncasoares/serverpod.git + path: modules/serverpod_auth/serverpod_auth_core/serverpod_auth_core_client + ref: fix-double-generator-bug + serverpod_auth_core_server: + git: + url: https://github.com/marcelomendoncasoares/serverpod.git + path: modules/serverpod_auth/serverpod_auth_core/serverpod_auth_core_server + ref: fix-double-generator-bug serverpod_cli: git: - url: https://github.com/serverpod/serverpod.git + url: https://github.com/marcelomendoncasoares/serverpod.git path: tools/serverpod_cli - ref: 1a6878faf9bf41c1a26ff4f0ebac2f0ac151b668 + ref: fix-double-generator-bug serverpod_client: git: - url: https://github.com/serverpod/serverpod.git + url: https://github.com/marcelomendoncasoares/serverpod.git path: packages/serverpod_client - ref: 1a6878faf9bf41c1a26ff4f0ebac2f0ac151b668 + ref: fix-double-generator-bug serverpod_database: git: - url: https://github.com/serverpod/serverpod.git + url: https://github.com/marcelomendoncasoares/serverpod.git path: packages/serverpod_database - ref: 1a6878faf9bf41c1a26ff4f0ebac2f0ac151b668 + ref: fix-double-generator-bug serverpod_embedded_postgres: git: - url: https://github.com/serverpod/serverpod.git + url: https://github.com/marcelomendoncasoares/serverpod.git path: packages/serverpod_embedded_postgres - ref: 1a6878faf9bf41c1a26ff4f0ebac2f0ac151b668 + ref: fix-double-generator-bug serverpod_shared: git: - url: https://github.com/serverpod/serverpod.git + url: https://github.com/marcelomendoncasoares/serverpod.git path: packages/serverpod_shared - ref: 1a6878faf9bf41c1a26ff4f0ebac2f0ac151b668 + ref: fix-double-generator-bug serverpod_serialization: git: - url: https://github.com/serverpod/serverpod.git + url: https://github.com/marcelomendoncasoares/serverpod.git path: packages/serverpod_serialization - ref: 1a6878faf9bf41c1a26ff4f0ebac2f0ac151b668 + ref: fix-double-generator-bug serverpod_service_client: git: - url: https://github.com/serverpod/serverpod.git + url: https://github.com/marcelomendoncasoares/serverpod.git path: packages/serverpod_service_client - ref: 1a6878faf9bf41c1a26ff4f0ebac2f0ac151b668 + ref: fix-double-generator-bug serverpod_test: git: - url: https://github.com/serverpod/serverpod.git + url: https://github.com/marcelomendoncasoares/serverpod.git path: packages/serverpod_test - ref: 1a6878faf9bf41c1a26ff4f0ebac2f0ac151b668 + ref: fix-double-generator-bug melos: packages: @@ -84,12 +94,8 @@ melos: exec: dart analyze . --fatal-infos --fatal-warnings generate: # Must run the module first, or the test project won't have the tables. - # Runs generate twice on the server package due to a bug in the generator. run: | - { - melos exec --scope="serverpod_offline_sync_server" -- dart run serverpod_cli generate || - melos exec --scope="serverpod_offline_sync_server" -- dart run serverpod_cli generate - } && + melos exec --scope="serverpod_offline_sync_server" -- dart run serverpod_cli generate && melos exec --scope="serverpod_offline_sync_test_server" -- dart run serverpod_cli generate create-migration: # If the module does not run first, the test project will see no module tables. diff --git a/test/serverpod_offline_sync_test_client/pubspec.yaml b/test/serverpod_offline_sync_test_client/pubspec.yaml index cfd3223..b68b528 100644 --- a/test/serverpod_offline_sync_test_client/pubspec.yaml +++ b/test/serverpod_offline_sync_test_client/pubspec.yaml @@ -8,6 +8,7 @@ environment: resolution: workspace dependencies: + serverpod_auth_core_client: 3.5.0-beta.10 serverpod_client: 3.5.0-beta.10 serverpod_database: 3.5.0-beta.10 serverpod_offline_sync_client: diff --git a/test/serverpod_offline_sync_test_server/.gitignore b/test/serverpod_offline_sync_test_server/.gitignore index 35f6869..1a753b7 100644 --- a/test/serverpod_offline_sync_test_server/.gitignore +++ b/test/serverpod_offline_sync_test_server/.gitignore @@ -15,5 +15,8 @@ doc/api/ # Test database file **/test.db* +# Development database file +**/development.db* + # Migrations do not need to be committed, as they are only for testing migrations/ diff --git a/test/serverpod_offline_sync_test_server/config/development.yaml b/test/serverpod_offline_sync_test_server/config/development.yaml new file mode 100644 index 0000000..0cec0c2 --- /dev/null +++ b/test/serverpod_offline_sync_test_server/config/development.yaml @@ -0,0 +1,29 @@ +# Configuration for the main API test server. +apiServer: + port: 8080 + publicHost: localhost + publicPort: 8080 + publicScheme: http + +# Configuration for the Insights test server. +insightsServer: + port: 8081 + publicHost: localhost + publicPort: 8081 + publicScheme: http + +# Configuration for the web test server. +webServer: + port: 8082 + publicHost: localhost + publicPort: 8082 + publicScheme: http + +# This is the database setup for your test server. +database: + filePath: development.db + +sessionLogs: + persistentEnabled: false + consoleEnabled: true + consoleLogFormat: text diff --git a/test/serverpod_offline_sync_test_server/config/generator.yaml b/test/serverpod_offline_sync_test_server/config/generator.yaml index 6f4ddea..a266782 100644 --- a/test/serverpod_offline_sync_test_server/config/generator.yaml +++ b/test/serverpod_offline_sync_test_server/config/generator.yaml @@ -6,4 +6,5 @@ client_package_path: ../serverpod_offline_sync_test_client server_test_tools_path: test/integration/test_tools modules: + serverpod_auth_core: serverpod_offline_sync: diff --git a/test/serverpod_offline_sync_test_server/config/passwords.yaml b/test/serverpod_offline_sync_test_server/config/passwords.yaml new file mode 100644 index 0000000..a53dc10 --- /dev/null +++ b/test/serverpod_offline_sync_test_server/config/passwords.yaml @@ -0,0 +1,4 @@ +development: + serviceSecret: 'super_SECRET_password' +test: + serviceSecret: 'super_SECRET_password' diff --git a/test/serverpod_offline_sync_test_server/lib/server.dart b/test/serverpod_offline_sync_test_server/lib/server.dart index 8694e08..4a5ed77 100644 --- a/test/serverpod_offline_sync_test_server/lib/server.dart +++ b/test/serverpod_offline_sync_test_server/lib/server.dart @@ -1,12 +1,27 @@ import 'package:serverpod/serverpod.dart'; +import 'package:serverpod_offline_sync_server/serverpod_offline_sync_server.dart' + hide Endpoints, Protocol; +import 'src/demo_auth.dart'; +import 'src/demo_sync_tables.dart'; import 'src/generated/endpoints.dart'; import 'src/generated/protocol.dart'; /// The starting point of the Serverpod server. Future run(List args) async { // Initialize Serverpod and connect it with your generated code. - final pod = Serverpod(args, Protocol(), Endpoints()); + final pod = Serverpod( + args, + Protocol(), + Endpoints(), + authenticationHandler: demoAuthenticationHandler, + // TODO: Remove the duplicate [syncTables] argument from here and the + // [initializeCrdtSync] call below. + databaseInterceptor: (_, inner) => CrdtDatabase( + inner, + syncTables: demoSyncTables, + ), + )..initializeCrdtSync(syncTables: demoSyncTables); // Start the server. await pod.start(); diff --git a/test/serverpod_offline_sync_test_server/lib/src/demo_auth.dart b/test/serverpod_offline_sync_test_server/lib/src/demo_auth.dart new file mode 100644 index 0000000..13f03f5 --- /dev/null +++ b/test/serverpod_offline_sync_test_server/lib/src/demo_auth.dart @@ -0,0 +1,70 @@ +import 'package:serverpod/serverpod.dart'; +import 'package:serverpod_auth_core_server/serverpod_auth_core_server.dart'; + +const _demoScopeName = 'offline-sync-demo'; +const _demoTokenPrefix = 'offline-sync-demo:'; + +/// Normalizes a demo username for deterministic auth user creation. +String normalizeDemoUsername(String username) { + final normalized = username.trim().toLowerCase(); + if (normalized.isEmpty) { + throw ArgumentError.value(username, 'username', 'Must not be empty.'); + } + return normalized; +} + +/// Returns the deterministic auth user id used by the demo username. +UuidValue demoAuthUserIdForUsername(String username) { + final normalized = normalizeDemoUsername(username); + final id = const Uuid().v5( + Namespace.url.value, + 'serverpod-offline-sync/demo-user/$normalized', + ); + return UuidValue.withValidation(id); +} + +/// Creates the bearer token accepted by [demoAuthenticationHandler]. +String demoTokenForAuthUserId(UuidValue authUserId) { + return '$_demoTokenPrefix${authUserId.uuid}'; +} + +/// Extracts the deterministic auth user id from a demo bearer token. +UuidValue? demoAuthUserIdFromToken(String token) { + if (!token.startsWith(_demoTokenPrefix)) return null; + final value = token.substring(_demoTokenPrefix.length); + try { + return UuidValue.withValidation(value); + } on FormatException { + return null; + } +} + +/// Authentication handler for the passwordless offline-sync demo users. +Future demoAuthenticationHandler( + Session session, + String token, +) async { + final authUserId = demoAuthUserIdFromToken(token); + if (authUserId == null) return null; + + final authUser = await AuthUser.db.findById(session, authUserId); + if (authUser == null || authUser.blocked) return null; + + return AuthenticationInfo( + authUserId.uuid, + authUser.scopeNames.map(Scope.new).toSet(), + authId: authUserId.uuid, + ); +} + +/// Creates a new auth user row for the passwordless offline-sync demo. +AuthUser newDemoAuthUser(String username) { + final normalized = normalizeDemoUsername(username); + return AuthUser( + id: demoAuthUserIdForUsername(normalized), + scopeNames: { + _demoScopeName, + '$_demoScopeName:$normalized', + }, + ); +} diff --git a/test/serverpod_offline_sync_test_server/lib/src/demo_sync_tables.dart b/test/serverpod_offline_sync_test_server/lib/src/demo_sync_tables.dart new file mode 100644 index 0000000..9fecfa9 --- /dev/null +++ b/test/serverpod_offline_sync_test_server/lib/src/demo_sync_tables.dart @@ -0,0 +1,29 @@ +import 'package:serverpod/serverpod.dart'; + +import 'generated/protocol.dart'; + +/// Tables exposed through the offline-sync demo server. +final demoSyncTables =
[ + Address.t, + City.t, + Company.t, + FkChainCascadeMiddle.t, + FkChainMiddleCascadeChild.t, + FkChainMiddleSetNullChild.t, + FkChainRestrictBlocker.t, + FkChainRoot.t, + FkChainSetNullCascadeChild.t, + FkChainSetNullMiddle.t, + FkChainSetNullRestrictChild.t, + FkChainSetNullSetNullChild.t, + Organization.t, + Person.t, + RequiredSetNullChild.t, + RestrictChild.t, + Town.t, + Types.t, + Unique.t, + UniqueComposite.t, + UniqueSetNullChild.t, + UniqueUuid.t, +]; diff --git a/test/serverpod_offline_sync_test_server/lib/src/endpoints/demo_auth_endpoint.dart b/test/serverpod_offline_sync_test_server/lib/src/endpoints/demo_auth_endpoint.dart new file mode 100644 index 0000000..2345877 --- /dev/null +++ b/test/serverpod_offline_sync_test_server/lib/src/endpoints/demo_auth_endpoint.dart @@ -0,0 +1,30 @@ +import 'package:serverpod/serverpod.dart'; +import 'package:serverpod_auth_core_server/serverpod_auth_core_server.dart'; + +import '../demo_auth.dart'; + +/// Passwordless auth endpoint used by the offline-sync demo app. +class DemoAuthEndpoint extends Endpoint { + @override + bool get requireLogin => false; + + /// Creates or reuses a demo auth user and returns its bearer token. + Future loginOrCreateUser( + Session session, + String username, + ) async { + final authUser = newDemoAuthUser(username); + final authUserId = authUser.id!; + + final existing = await AuthUser.db.findById(session, authUserId); + if (existing == null) { + try { + await AuthUser.db.insertRow(session, authUser); + } on DatabaseQueryException { + // A concurrent demo login may have created the deterministic row. + } + } + + return demoTokenForAuthUserId(authUserId); + } +} diff --git a/test/serverpod_offline_sync_test_server/lib/src/endpoints/demo_debug_endpoint.dart b/test/serverpod_offline_sync_test_server/lib/src/endpoints/demo_debug_endpoint.dart new file mode 100644 index 0000000..985c70f --- /dev/null +++ b/test/serverpod_offline_sync_test_server/lib/src/endpoints/demo_debug_endpoint.dart @@ -0,0 +1,334 @@ +import 'dart:typed_data'; + +import 'package:serverpod/serverpod.dart'; +import 'package:serverpod_offline_sync_server/serverpod_offline_sync_server.dart' + show CrdtDatabase, CrdtScope, IncludeTombstonedRows; + +import '../generated/protocol.dart'; + +/// Read-only inspection endpoint used by the offline-sync demo app to show the +/// server's merged truth for the authenticated user's scope. +class DemoDebugEndpoint extends Endpoint { + @override + bool get requireLogin => true; + + /// Returns every synced domain row in the caller's scope on the server as a + /// flat list of models. When [includeHidden] is true, the list also includes + /// CRDT-hidden rows (conflict losers, soft-deleted rows) via the + /// `t.includeHiddenRows` expression; otherwise only visible rows are returned. + /// + /// The rows cross the wire as `dynamic`: Serverpod tags each model with its + /// class name — the same mechanism the CRDT sync layer uses — so the client + /// deserializes them straight back into typed models with no per-table + /// plumbing on either side. The client flags hidden rows by diffing a + /// visible-only fetch against an include-hidden one. + Future> fetchScopeSnapshot( + Session session, { + bool includeHidden = false, + }) async { + final userId = UuidValue.withValidation( + session.authenticated!.userIdentifier, + ); + + final db = session.db; + if (db is! CrdtDatabase) { + return _loadRows(session, null, includeHidden: false, scopeId: null); + } + + // Run the reads in the caller's scope so the snapshot reflects what this + // user sees, not an unscoped admin view across every scope. + return db.transactionForUser(userId, (transaction) async { + final scope = await CrdtScope.db.findFirstRow( + session, + where: (t) => t.uuidScopeId.equals(userId), + transaction: transaction, + ); + return _loadRows( + session, + transaction, + includeHidden: includeHidden, + scopeId: scope?.id, + ); + }); + } + + /// Clears the caller's scope by deleting its `crdt_scopes` row. Every synced + /// table cascades on `scopeId` → `crdt_scopes`, so all domain rows and CRDT + /// metadata are removed with it — no manual per-table cleanup needed. + /// + /// The delete runs with `defer_foreign_keys` on: the scopeId cascade fans out + /// across the CRDT metadata diamond (`crdt_data_rows`/`crdt_data_fields`/ + /// `crdt_data_tombstone` reference `crdt_nodes` with NO ACTION while both sides + /// cascade off `crdt_scopes`), and SQLite's cascade order can transiently + /// violate those immediate checks. Deferring them to commit lets the whole + /// cascade complete first. + Future resetScope(Session session) async { + final userId = UuidValue.withValidation( + session.authenticated!.userIdentifier, + ); + + final db = session.db; + if (db is CrdtDatabase) { + await db.initialize(); + } + final scope = await CrdtScope.db.findFirstRow( + session, + where: (t) => t.uuidScopeId.equals(userId), + ); + final scopeId = scope?.id; + if (scopeId != null) { + await db.transaction((transaction) async { + // TODO: Remove this explicit call to defer foreign keys once foreign + // keys are deferrable by default on the Serverpod package. + await db.unsafeExecute( + 'PRAGMA defer_foreign_keys = ON', + transaction: transaction, + ); + await CrdtScope.db.deleteWhere( + session, + where: (t) => t.id.equals(scopeId), + transaction: transaction, + ); + }); + } + if (db is CrdtDatabase) { + await db.initialize(); + } + } + + /// Inserts demo rows of [kind] directly into the caller's scope on the server, + /// without going through a replica. Lets the "Server" seed target exercise the + /// fetch-from-scratch flow: seed here, reset a replica, then sync to pull it + /// down. [text] carries an optional name/value for the single-row kinds. + Future seedScope(Session session, String kind, String? text) async { + final userId = UuidValue.withValidation( + session.authenticated!.userIdentifier, + ); + + final db = session.db; + if (db is! CrdtDatabase) { + throw StateError('This endpoint only works with a CRDT database.'); + } + + final tag = DateTime.now().microsecondsSinceEpoch.toRadixString(36); + + // TODO: Expose the [transactionForUser] through an extension method on the + // base [Database] class so the cast is unnecessary. + await db.transactionForUser(userId, (transaction) async { + switch (kind) { + case 'basicGraph': + final city = await City.db.insertRow( + session, + City(id: const Uuid().v7obj(), name: 'Server City $tag'), + transaction: transaction, + ); + await Town.db.insertRow( + session, + Town( + id: const Uuid().v7obj(), + name: 'Server Town $tag', + cityId: city.id, + ), + transaction: transaction, + ); + final person = await Person.db.insertRow( + session, + Person( + id: const Uuid().v7obj(), + name: 'Server Person $tag', + surname: 'Remote', + ), + transaction: transaction, + ); + await Address.db.insertRow( + session, + Address( + id: const Uuid().v7obj(), + street: 'Server Street $tag', + inhabitantId: person.id, + ), + transaction: transaction, + ); + case 'typedRow': + await Types.db.insertRow( + session, + Types( + id: const Uuid().v7obj(), + aBool: true, + aDateTime: DateTime.now().toUtc(), + aText: 'server-typed-$tag', + anInt: 7, + anInt64: BigInt.parse('9007199254740993'), + aReal: 1.5, + aBlob: ByteData.sublistView(Uint8List.fromList([1, 2, 3])), + anEnum: TypesEnum.alpha, + optionalText: 'server-$tag', + optionalUuid: const Uuid().v7obj(), + ), + transaction: transaction, + ); + case 'person': + final name = (text == null || text.isEmpty) + ? 'Server Person $tag' + : '$text $tag'; + await Person.db.insertRow( + session, + Person(id: const Uuid().v7obj(), name: name), + transaction: transaction, + ); + case 'restrictChild': + final people = await Person.db.find(session, transaction: transaction); + Person? parent; + for (final person in people) { + if (person.id != null) { + parent = person; + break; + } + } + if (parent == null) { + throw StateError( + 'Seed or sync a visible Person before adding RestrictChild.', + ); + } + await RestrictChild.db.insertRow( + session, + RestrictChild( + id: const Uuid().v7obj(), + name: 'Server restrict child $tag', + parentId: parent.id, + ), + transaction: transaction, + ); + case 'unique': + await Unique.db.insertRow( + session, + Unique(id: const Uuid().v7obj(), name: text ?? 'server-unique-$tag'), + transaction: transaction, + ); + case 'uniqueUuid': + final value = (text == null || text.isEmpty) + ? const Uuid().v7obj() + : UuidValue.withValidation(text); + await UniqueUuid.db.insertRow( + session, + UniqueUuid(id: const Uuid().v7obj(), value: value), + transaction: transaction, + ); + case 'fkChain': + final root = await FkChainRoot.db.insertRow( + session, + FkChainRoot(id: const Uuid().v7obj(), name: 'Server Root $tag'), + transaction: transaction, + ); + final middle = await FkChainCascadeMiddle.db.insertRow( + session, + FkChainCascadeMiddle( + id: const Uuid().v7obj(), + name: 'Server Cascade middle $tag', + rootId: root.id, + ), + transaction: transaction, + ); + final blocker = await FkChainRestrictBlocker.db.insertRow( + session, + FkChainRestrictBlocker( + id: const Uuid().v7obj(), + name: 'Server Blocker $tag', + cascadeMiddleId: middle.id, + ), + transaction: transaction, + ); + await FkChainMiddleSetNullChild.db.insertRow( + session, + FkChainMiddleSetNullChild( + id: const Uuid().v7obj(), + name: 'Server set-null child $tag', + restrictBlockerId: blocker.id, + ), + transaction: transaction, + ); + await FkChainMiddleCascadeChild.db.insertRow( + session, + FkChainMiddleCascadeChild( + id: const Uuid().v7obj(), + name: 'Server cascade child $tag', + restrictBlockerId: blocker.id, + ), + transaction: transaction, + ); + } + }); + } + + /// Loads every synced domain row in the caller's scope as a flat list of + /// models. When [includeHidden] is true, CRDT-hidden rows are returned too + /// via the `t.includeHiddenRows` expression. + /// + /// `includeHiddenRows` is an extension on any [Table], so the read is uniform + /// across every synced type — each table is listed once because Dart cannot + /// turn a runtime [Table] back into the compile-time `T` that + /// `session.db.find` requires. + Future> _loadRows( + Session session, + Transaction? transaction, { + required bool includeHidden, + required int? scopeId, + }) async { + final rows = []; + Future add() async { + rows.addAll( + await session.db.find( + where: includeHidden ? _includeHiddenRowsInScope(session, scopeId) : null, + transaction: transaction, + ), + ); + } + + await add(); + await add
(); + await add(); + await add(); + await add(); + await add(); + await add(); + await add(); + await add(); + await add(); + await add(); + await add(); + await add(); + await add(); + await add(); + await add(); + await add(); + await add(); + await add(); + await add(); + await add(); + await add(); + return rows; + } + + Expression _includeHiddenRowsInScope( + Session session, + int? scopeId, + ) { + if (scopeId == null) { + throw StateError('Cannot include hidden rows without a CRDT scope.'); + } + + final table = + session.db.serializationManager.getTableForType(T) ?? + (throw StateError('No table is registered for type $T.')); + return _scopeIdColumn(table).equals(scopeId) & table.includeHiddenRows; + } + + ColumnInt _scopeIdColumn(Table table) { + for (final column in table.columns) { + if (column.columnName == 'scopeId' && column is ColumnInt) { + return column; + } + } + throw StateError('Synced table "${table.tableName}" has no scopeId column.'); + } +} diff --git a/test/serverpod_offline_sync_test_server/pubspec.yaml b/test/serverpod_offline_sync_test_server/pubspec.yaml index 272c297..1802b0e 100644 --- a/test/serverpod_offline_sync_test_server/pubspec.yaml +++ b/test/serverpod_offline_sync_test_server/pubspec.yaml @@ -9,6 +9,7 @@ resolution: workspace dependencies: serverpod: 3.5.0-beta.10 + serverpod_auth_core_server: 3.5.0-beta.10 serverpod_offline_sync_server: path: ../../packages/serverpod_offline_sync_server serverpod_offline_sync_shared: @@ -21,3 +22,10 @@ dev_dependencies: path: ../serverpod_offline_sync_test_client serverpod_test: 3.5.0-beta.10 test: ^1.25.5 + +serverpod: + flutter_apps: + Example: + path: ../../example/offline_sync_demo + auto_launch: true + device: linux diff --git a/test/serverpod_offline_sync_test_server/test/integration/crud/scope_purge_test.dart b/test/serverpod_offline_sync_test_server/test/integration/crud/scope_purge_test.dart index 732b5f2..264b30b 100644 --- a/test/serverpod_offline_sync_test_server/test/integration/crud/scope_purge_test.dart +++ b/test/serverpod_offline_sync_test_server/test/integration/crud/scope_purge_test.dart @@ -219,4 +219,146 @@ void main() { }); }, ); + + group( + 'Given a scope whose graph spans the CRDT metadata diamond — domain rows ' + 'plus the crdt_data_rows / crdt_data_fields / crdt_data_tombstone metadata ' + 'that reference crdt_nodes,', + () { + late UuidValue userId; + late CrdtScope scope; + + setUp(() async { + userId = const Uuid().v7obj(); + + // A graph wide enough to generate many CRDT metadata rows: a cascade + // chain (city -> town), a RESTRICT relation (person <- address), and the + // mixed FK chain. Every insert records crdt_data_rows / crdt_data_fields + // rows that reference crdt_nodes. + await session.db.transactionForUser(userId, (tx) async { + final city = await City.db.insertRow( + session, + City(id: const Uuid().v7obj(), name: 'City'), + transaction: tx, + ); + await Town.db.insertRow( + session, + Town(id: const Uuid().v7obj(), name: 'Town', cityId: city.id), + transaction: tx, + ); + final person = await Person.db.insertRow( + session, + Person(id: const Uuid().v7obj(), name: 'Person'), + transaction: tx, + ); + await Address.db.insertRow( + session, + Address( + id: const Uuid().v7obj(), + street: 'Street', + inhabitantId: person.id, + ), + transaction: tx, + ); + final root = await FkChainRoot.db.insertRow( + session, + FkChainRoot(id: const Uuid().v7obj(), name: 'Root'), + transaction: tx, + ); + final middle = await FkChainCascadeMiddle.db.insertRow( + session, + FkChainCascadeMiddle( + id: const Uuid().v7obj(), + name: 'Cascade middle', + rootId: root.id, + ), + transaction: tx, + ); + final blocker = await FkChainRestrictBlocker.db.insertRow( + session, + FkChainRestrictBlocker( + id: const Uuid().v7obj(), + name: 'Restrict blocker', + cascadeMiddleId: middle.id, + ), + transaction: tx, + ); + await FkChainMiddleSetNullChild.db.insertRow( + session, + FkChainMiddleSetNullChild( + id: const Uuid().v7obj(), + name: 'Set-null child', + restrictBlockerId: blocker.id, + ), + transaction: tx, + ); + await FkChainMiddleCascadeChild.db.insertRow( + session, + FkChainMiddleCascadeChild( + id: const Uuid().v7obj(), + name: 'Cascade child', + restrictBlockerId: blocker.id, + ), + transaction: tx, + ); + }); + + // An extra insert + delete records a tombstone in the scope, exercising + // the crdt_data_tombstone.nodeId -> crdt_nodes edge of the diamond. + final disposable = await session.db.transactionForUser( + userId, + (tx) => Person.db.insertRow( + session, + Person(id: const Uuid().v7obj(), name: 'Disposable'), + transaction: tx, + ), + ); + await session.db.transactionForUser( + userId, + (tx) => Person.db.deleteRow(session, disposable, transaction: tx), + ); + + scope = await CrdtScopeManager(session).getOrCreate(userId); + }); + + test( + 'when the scope is purged by deleting its crdt_scopes row, ' + 'then all domain rows and CRDT metadata are removed.', + () async { + await CrdtScope.db.deleteWhere( + session, + where: (t) => t.id.equals(scope.id), + ); + + expect(await CrdtScope.db.findById(session, scope.id!), isNull); + expect( + await Person.db.count( + session, + where: (t) => t.scopeId.equals(scope.id) & t.includeHiddenRows, + ), + 0, + ); + expect( + await CrdtDataRow.db.count( + session, + where: (t) => t.scopeId.equals(scope.id), + ), + 0, + ); + }, + skip: + 'Purging this scope by deleting its crdt_scopes row currently fails ' + 'with "FOREIGN KEY constraint failed". The scopeId cascade fans out ' + 'across the CRDT metadata diamond: crdt_data_rows / crdt_data_fields ' + '/ crdt_data_tombstone reference crdt_nodes with ON DELETE NO ACTION ' + 'while both those tables and crdt_nodes cascade off crdt_scopes, so ' + 'SQLite enforces the immediate NO ACTION checks mid-cascade before the ' + 'referencing rows are themselves deleted. The fix is to generate ' + 'those foreign keys as DEFERRABLE INITIALLY DEFERRED, which depends on ' + 'upstream Serverpod support for emitting deferrable constraints in ' + 'migrations. Until that lands, callers must wrap the purge in a ' + 'transaction with "PRAGMA defer_foreign_keys = ON".', + ); + }, + ); } diff --git a/test/serverpod_offline_sync_test_server/test/integration/merge/foreign_key_invariant_test.dart b/test/serverpod_offline_sync_test_server/test/integration/merge/foreign_key_invariant_test.dart index 00439d5..aa0aa11 100644 --- a/test/serverpod_offline_sync_test_server/test/integration/merge/foreign_key_invariant_test.dart +++ b/test/serverpod_offline_sync_test_server/test/integration/merge/foreign_key_invariant_test.dart @@ -1858,6 +1858,86 @@ void main() { }, ); + group( + 'Given a remote insert with a cascade foreign key that points to a hidden parent in scope, ', + () { + late Organization organization; + late Person person; + late CrdtMergeInsert remotePersonInsert; + + setUp(() async { + await session.db.transactionForUser(testCrdtUserId, (tx) async { + organization = await Organization.db.insertRow( + session, + Organization(id: const Uuid().v7obj(), name: 'cascade organization'), + transaction: tx, + ); + }); + + await session.db.transactionForUser(testCrdtUserId, (tx) async { + await Organization.db.deleteRow(session, organization, transaction: tx); + }); + + person = Person( + id: const Uuid().v7obj(), + name: 'cascade person', + organizationId: organization.id, + ); + + final remoteNodeId = const Uuid().v7obj(); + final hlc = Hlc(DateTime.now().toUtc(), 0, remoteNodeId); + remotePersonInsert = CrdtMergeInsert( + tableName: Person.t.tableName, + uuidRowId: person.id!, + uuidNodeId: remoteNodeId, + hlcDatetime: hlc.datetime, + hlcCounter: hlc.counter, + data: person, + ); + }); + + group('when the remote insert is merged, ', () { + setUp(() async { + await session.db.mergeChanges( + [remotePersonInsert], + scopeId: testCrdtUserId, + ); + }); + + test( + 'then the child is hidden and preserves the organization foreign key.', + () async { + expect(await Organization.db.findById(session, organization.id!), isNull); + expect(await Person.db.findById(session, person.id!), isNull); + + final hiddenPerson = await Person.db.findFirstRow( + session, + where: (t) => t.id.equals(person.id) & t.includeHiddenRows, + ); + + expect(hiddenPerson, isNotNull); + expect(hiddenPerson!.organizationId, organization.id); + }, + ); + + test( + 'then no missing-parent projection override is materialized.', + () async { + final projection = await _findForeignKeyProjection( + rowId: person.id!, + columnName: Person.t.organizationId.columnName, + ); + + expect(projection, isNotNull); + expect(projection!.attemptedValue, organization.id); + expect(projection.hasOverride, isFalse); + expect(projection.overrideReason, isNull); + }, + ); + }); + }, + ); + // Merge sets are causally complete by protocol: a sync batch is a full causal // snapshot, so the parent facts needed by its foreign key attempts always // precede or accompany the child fact. A non-nullable set-default attempt diff --git a/test/serverpod_offline_sync_test_server/test/integration/sync/sync_flow_test.dart b/test/serverpod_offline_sync_test_server/test/integration/sync/sync_flow_test.dart index ee3f54c..dbae6e7 100644 --- a/test/serverpod_offline_sync_test_server/test/integration/sync/sync_flow_test.dart +++ b/test/serverpod_offline_sync_test_server/test/integration/sync/sync_flow_test.dart @@ -87,6 +87,36 @@ void main() { }, ); + test( + 'when client syncOnce is called repeatedly on a reused client ' + 'then the rounds complete promptly instead of stalling on teardown.', + () async { + // The first round opens the shared websocket connection; later + // rounds reuse it. If a finished round leaves its inbound transport + // stream paused, closing that stream stalls for the transport close + // timeout (~6s), and the stall lands on the next round's critical + // path. Empty rounds should each take milliseconds, so several of + // them together must stay well under a single close-timeout budget, + // independent of how much data was synced. + const rounds = 6; + final stopwatch = Stopwatch()..start(); + for (var round = 0; round < rounds; round++) { + await testClient.crdt.syncOnce(clientSession); + } + stopwatch.stop(); + + expect( + stopwatch.elapsed, + lessThan(const Duration(seconds: 10)), + reason: + '$rounds empty reused syncOnce rounds took ' + '${stopwatch.elapsed}; a leaked paused inbound stream stalls ' + 'each reused round on the ~6s transport close timeout.', + ); + }, + timeout: const Timeout(Duration(seconds: 90)), + ); + test( 'when client syncContinuously is called ' 'then neither side reports a successful merge.',