diff --git a/lib/core/user_state/window_session_store.dart b/lib/core/user_state/window_session_store.dart index cdd625af6f..562e1986d2 100644 --- a/lib/core/user_state/window_session_store.dart +++ b/lib/core/user_state/window_session_store.dart @@ -93,6 +93,26 @@ class WindowSessionStore { return _loadIn(db, slot); } + /// קורא רק גבולות, בלי להעתיק את הכרטיסיות השמורות. + Future loadBoundsJson(int slot) async { + final db = await _database.database; + final rows = db.select( + 'SELECT bounds_json FROM window_sessions WHERE slot = ?', + [slot], + ); + return rows.isEmpty ? null : rows.first['bounds_json'] as String?; + } + + /// קורא רק את השולחן הפעיל, בלי להעתיק את הכרטיסיות השמורות. + Future loadActiveWorkspaceId(int slot) async { + final db = await _database.database; + final rows = db.select( + 'SELECT active_workspace_id FROM window_sessions WHERE slot = ?', + [slot], + ); + return rows.isEmpty ? null : rows.first['active_workspace_id'] as String?; + } + /// הסשן מהמסד **שכבר פתוח**, בלי await, ו-null כשטרם נפתח. /// /// ⚠️ קיים בשביל `TabsRepository.loadTabs`, שנקרא מבנאי של bloc ואינו diff --git a/lib/core/window_persistence.dart b/lib/core/window_persistence.dart index 5dca011037..c0e698823c 100644 --- a/lib/core/window_persistence.dart +++ b/lib/core/window_persistence.dart @@ -139,8 +139,7 @@ class WindowPersistenceBinding { (Settings.getValue(SettingsRepository.keyLibraryPath) ?? '') .isNotEmpty; if (slot != null && hasLibrary) { - final session = await _store.load(slot); - final bounds = WindowBounds.decode(session?.boundsJson); + final bounds = WindowBounds.decode(await _store.loadBoundsJson(slot)); if (bounds != null) return bounds; } return WindowBounds( @@ -396,7 +395,7 @@ class WindowPersistenceBinding { final isMaximized = await _window.isMaximized(); final store = _store; var next = - (WindowBounds.decode((await store.load(slot))?.boundsJson) ?? + (WindowBounds.decode(await store.loadBoundsJson(slot)) ?? const WindowBounds()) .copyWith(maximized: isMaximized); diff --git a/lib/core/windowing/multiview/view_window_opener.dart b/lib/core/windowing/multiview/view_window_opener.dart index 12c45ff644..bd39873086 100644 --- a/lib/core/windowing/multiview/view_window_opener.dart +++ b/lib/core/windowing/multiview/view_window_opener.dart @@ -148,7 +148,7 @@ class ViewWindowOpener implements WindowOpener { if (maximized && (cocoa || (_native is GtkViewWindowNative && view == null))) { var saved = WindowBounds.decode( - (await _store.load(view?.slot ?? 1))?.boundsJson, + await _store.loadBoundsJson(view?.slot ?? 1), ); if (cocoa && view == null && saved?.hasRect != true) { saved = await WindowPersistence.current.loadSavedBounds(); @@ -280,8 +280,7 @@ class ViewWindowOpener implements WindowOpener { if (registry.isSlotOpen(slot) || !_canOpen) { return false; } - final session = await _store.load(slot); - final saved = WindowBounds.decode(session?.boundsJson); + final saved = WindowBounds.decode(await _store.loadBoundsJson(slot)); return _open( slot: slot, bounds: saved?.toPhysical(screenPoints: _native is CocoaViewWindowNative), diff --git a/lib/workspaces/workspace_repository.dart b/lib/workspaces/workspace_repository.dart index 854d7a930d..323179b088 100644 --- a/lib/workspaces/workspace_repository.dart +++ b/lib/workspaces/workspace_repository.dart @@ -48,7 +48,7 @@ class WorkspaceRepository { final slot = _slot(); var currentId = slot == null ? null - : (await _sessions.load(slot))?.activeWorkspaceId; + : await _sessions.loadActiveWorkspaceId(slot); // חלון ללא שולחן פעיל מתחיל על הראשון; חלון חדש מקבל אחד רק כשהמשתמש // בוחר — כך שני חלונות אינם נועלים על אותו שולחן בלי כוונה. if (currentId != null && !workspaces.any((w) => w.id == currentId)) { diff --git a/test/core/user_state/window_session_metadata_read_test.dart b/test/core/user_state/window_session_metadata_read_test.dart new file mode 100644 index 0000000000..bfd410c23e --- /dev/null +++ b/test/core/user_state/window_session_metadata_read_test.dart @@ -0,0 +1,137 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:otzaria/core/user_state/user_state_database.dart'; +import 'package:otzaria/core/user_state/window_session_store.dart'; +import 'package:sqlite3/sqlite3.dart'; + +void main() { + late Directory directory; + late UserStateDatabase database; + late WindowSessionStore sessions; + + setUp(() async { + directory = Directory.systemTemp.createTempSync('session_metadata_'); + database = UserStateDatabase.openAt('${directory.path}/user_state.db'); + sessions = WindowSessionStore(database: database); + await database.database; + }); + + tearDown(() async { + await database.flushWrites(); + database.close(); + directory.deleteSync(recursive: true); + }); + + test('שורה חסרה ועמודות ריקות מחזירות null', () async { + expect(await sessions.loadBoundsJson(1), isNull); + expect(await sessions.loadActiveWorkspaceId(1), isNull); + await sessions.save(1, tabsJson: '[]', currentIndex: 0); + expect(await sessions.loadBoundsJson(1), isNull); + expect(await sessions.loadActiveWorkspaceId(1), isNull); + + await sessions.saveBounds(1, ''); + await sessions.saveActiveWorkspace(1, ''); + expect(await sessions.loadBoundsJson(1), ''); + expect(await sessions.loadActiveWorkspaceId(1), ''); + }); + + test('השליפות מבודדות משבצות ונשארות עדכניות בלי לשנות כרטיסיות', () async { + await sessions.save(1, tabsJson: '["a","b"]', currentIndex: 1); + await sessions.saveBounds(1, '{"left":10}'); + await sessions.saveActiveWorkspace(1, 'first'); + await sessions.saveBounds(2, '{"left":20}'); + await sessions.saveActiveWorkspace(2, 'second'); + + expect(await sessions.loadBoundsJson(1), '{"left":10}'); + expect(await sessions.loadBoundsJson(2), '{"left":20}'); + expect(await sessions.loadActiveWorkspaceId(1), 'first'); + expect(await sessions.loadActiveWorkspaceId(2), 'second'); + + await sessions.saveBounds(1, null); + await sessions.saveActiveWorkspace(1, 'updated'); + expect(await sessions.loadBoundsJson(1), isNull); + expect(await sessions.loadActiveWorkspaceId(1), 'updated'); + expect(await sessions.loadBoundsJson(2), '{"left":20}'); + expect(await sessions.loadActiveWorkspaceId(2), 'second'); + final full = (await sessions.load(1))!; + expect(full.tabsJson, '["a","b"]'); + expect(full.currentIndex, 1); + }); + + test('קריאות מטא־נתונים ממתינות לכתיבות שכבר בתור', () async { + final release = Completer(); + final started = Completer(); + final barrier = database.runInWriteQueue((_) async { + started.complete(); + await release.future; + }); + await started.future; + final boundsWrite = sessions.saveBounds(1, '{"left":42}'); + final workspaceWrite = sessions.saveActiveWorkspace(1, 'queued'); + var boundsReadFinished = false; + var workspaceReadFinished = false; + final boundsRead = sessions.loadBoundsJson(1).then((value) { + boundsReadFinished = true; + return value; + }); + final workspaceRead = sessions.loadActiveWorkspaceId(1).then((value) { + workspaceReadFinished = true; + return value; + }); + + await Future.delayed(Duration.zero); + expect(boundsReadFinished, isFalse); + expect(workspaceReadFinished, isFalse); + release.complete(); + await Future.wait([barrier, boundsWrite, workspaceWrite]); + expect(await boundsRead, '{"left":42}'); + expect(await workspaceRead, 'queued'); + }); + + test('השליפות אינן מעריכות את עמודת הכרטיסיות ב-SQLite', () async { + final tabs = '["${'א' * 500000}"]'; + await sessions.save(1, tabsJson: tabs, currentIndex: 0); + await sessions.saveBounds(1, '{"left":7}'); + await sessions.saveActiveWorkspace(1, 'workspace'); + final connection = await database.database; + var tabReads = 0; + connection.createFunction( + functionName: 'read_tabs', + argumentCount: const AllowedArgumentCount(1), + directOnly: false, + function: (arguments) { + tabReads++; + return arguments.single; + }, + ); + connection.execute('ALTER TABLE window_sessions RENAME TO session_rows'); + connection.execute(''' + CREATE VIEW window_sessions AS + SELECT slot, read_tabs(tabs_json) AS tabs_json, current_index, + active_workspace_id, bounds_json, updated_at + FROM session_rows + '''); + + expect((await sessions.load(1))!.tabsJson, tabs); + expect(tabReads, 1); + tabReads = 0; + expect(await sessions.loadBoundsJson(1), '{"left":7}'); + expect(await sessions.loadActiveWorkspaceId(1), 'workspace'); + expect(tabReads, 0); + }); + + test('שגיאת SQLite מתפשטת ואינה נראית כמו שורה חסרה', () async { + final connection = await database.database; + connection.execute('DROP TABLE window_sessions'); + await expectLater( + sessions.loadBoundsJson(1), + throwsA(isA()), + ); + await expectLater( + sessions.loadActiveWorkspaceId(1), + throwsA(isA()), + ); + }); +} diff --git a/test/core/window_persistence_metadata_test.dart b/test/core/window_persistence_metadata_test.dart new file mode 100644 index 0000000000..94a551bd7f --- /dev/null +++ b/test/core/window_persistence_metadata_test.dart @@ -0,0 +1,157 @@ +import 'dart:async'; +import 'dart:ui'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:otzaria/core/user_state/window_bounds.dart'; +import 'package:otzaria/core/user_state/window_session_store.dart'; +import 'package:otzaria/core/window_persistence.dart'; +import 'package:otzaria/core/windowing/app_window_controller.dart'; +import 'package:otzaria/settings/engine/app_settings_store.dart'; +import 'package:otzaria/settings/engine/settings_repository.dart'; + +import '../test_helpers/memory_cache_provider.dart'; + +class _BoundsSessions extends WindowSessionStore { + String? bounds; + Completer? beforeRead; + final reads = []; + final writes = <(int, String?)>[]; + + @override + Future loadBoundsJson(int slot) async { + reads.add(slot); + await beforeRead?.future; + return bounds; + } + + @override + Future load(int slot) => + throw StateError('שמירת גבולות אינה זקוקה לכרטיסיות'); + + @override + Future saveBounds(int slot, String? boundsJson) async { + writes.add((slot, boundsJson)); + bounds = boundsJson; + } +} + +class _Window implements AppWindowController, AppWindowGeometry { + bool minimized = false; + bool maximized = false; + bool fullscreen = false; + int geometryReads = 0; + final Rect bounds = const Rect.fromLTWH(40, 60, 900, 700); + + @override + Future isMinimized() async => minimized; + + @override + Future isMaximized() async => maximized; + + @override + Future isFullScreen() async => fullscreen; + + @override + Future getBounds() async { + geometryReads++; + return bounds; + } + + @override + dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); +} + +void main() { + late _BoundsSessions sessions; + late _Window window; + late WindowPersistenceBinding persistence; + int? slot; + + setUp(() async { + sessions = _BoundsSessions(); + window = _Window(); + slot = 2; + persistence = WindowPersistenceBinding( + controller: window, + geometry: window, + sessions: sessions, + slot: () => slot, + devicePixelRatio: () => 1.5, + ); + await Settings.init(cacheProvider: MemoryCacheProvider()); + await Settings.setValue(SettingsRepository.keyLibraryPath, '/library'); + }); + + testWidgets('חלון רגיל שומר גבולות ו-DPR דרך שליפת המטא־נתונים', ( + tester, + ) async { + persistence.scheduleSave(); + await tester.pump(const Duration(milliseconds: 401)); + final saved = WindowBounds.decode(sessions.writes.single.$2)!; + expect(sessions.reads, [2]); + expect(sessions.writes.single.$1, 2); + expect(saved.toPhysical(), (left: 60, top: 90, width: 1350, height: 1050)); + expect(saved.dpr, 1.5); + expect(saved.maximized, isFalse); + }); + + for (final fullscreen in [false, true]) { + testWidgets('מצב מוגדל/מלא ($fullscreen) משמר גאומטריה רגילה', ( + tester, + ) async { + const previous = WindowBounds( + left: 10, + top: 20, + width: 800, + height: 600, + dpr: 2, + ); + sessions.bounds = previous.encode(); + window.fullscreen = fullscreen; + window.maximized = !fullscreen; + persistence.scheduleSave(); + await tester.pump(const Duration(milliseconds: 401)); + + final saved = WindowBounds.decode(sessions.writes.single.$2)!; + expect(saved.toPhysical(), previous.toPhysical()); + expect(saved.dpr, 2); + expect(saved.maximized, !fullscreen); + expect(window.geometryReads, 0); + }); + } + + testWidgets('חלון ממוזער אינו קורא או שומר גבולות', (tester) async { + window.minimized = true; + persistence.scheduleSave(); + await tester.pump(const Duration(milliseconds: 401)); + expect(sessions.reads, isEmpty); + expect(sessions.writes, isEmpty); + }); + + testWidgets('סגירת חלון בזמן שליפת הגבולות אינה יוצרת מחדש את השורה', ( + tester, + ) async { + sessions.beforeRead = Completer(); + persistence.scheduleSave(); + await tester.pump(const Duration(milliseconds: 401)); + expect(sessions.reads, [2]); + slot = null; + sessions.beforeRead!.complete(); + await tester.pump(); + expect(sessions.writes, isEmpty); + }); + + test('גבולות חסרים או פגומים חוזרים להגדרות הישנות', () async { + await Settings.setValue('window_bounds_left', 12.0); + await Settings.setValue('window_bounds_top', 24.0); + await Settings.setValue('window_bounds_width', 600.0); + await Settings.setValue('window_bounds_height', 400.0); + await Settings.setValue('window_bounds_dpr', 2.0); + for (final raw in [null, '{invalid']) { + sessions.bounds = raw; + final saved = await persistence.loadSavedBounds(); + expect(saved.toPhysical(), (left: 24, top: 48, width: 1200, height: 800)); + } + expect(sessions.reads, [2, 2]); + }); +} diff --git a/test/core/windowing/multiview/in_process_tab_drop_close_test.dart b/test/core/windowing/multiview/in_process_tab_drop_close_test.dart index f45633ca32..1e9847f084 100644 --- a/test/core/windowing/multiview/in_process_tab_drop_close_test.dart +++ b/test/core/windowing/multiview/in_process_tab_drop_close_test.dart @@ -66,6 +66,9 @@ class _MemorySessions extends WindowSessionStore { ); } + @override + Future loadBoundsJson(int slot) async => rows[slot]?.boundsJson; + @override Future load(int slot) async { final row = rows[slot]; diff --git a/test/core/windowing/multiview/view_window_opener_test.dart b/test/core/windowing/multiview/view_window_opener_test.dart index 7d99bcd0eb..047c04a187 100644 --- a/test/core/windowing/multiview/view_window_opener_test.dart +++ b/test/core/windowing/multiview/view_window_opener_test.dart @@ -72,6 +72,9 @@ class _MemorySessions extends WindowSessionStore { ); } + @override + Future loadBoundsJson(int slot) async => rows[slot]?.boundsJson; + @override Future load(int slot) async => rows[slot]; diff --git a/test/workspaces/workspace_metadata_test.dart b/test/workspaces/workspace_metadata_test.dart new file mode 100644 index 0000000000..42391d707a --- /dev/null +++ b/test/workspaces/workspace_metadata_test.dart @@ -0,0 +1,65 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:otzaria/core/user_state/user_state_database.dart'; +import 'package:otzaria/core/user_state/user_state_list_store.dart'; +import 'package:otzaria/core/user_state/window_session_store.dart'; +import 'package:otzaria/workspaces/workspace.dart'; +import 'package:otzaria/workspaces/workspace_repository.dart'; + +class _MetadataSessions extends WindowSessionStore { + _MetadataSessions({required super.database}); + + @override + Future load(int slot) => + throw StateError('טעינת שולחנות אינה זקוקה לכרטיסיות הסשן'); +} + +void main() { + late Directory directory; + late UserStateDatabase database; + late UserStateListStore lists; + late _MetadataSessions sessions; + + setUp(() { + directory = Directory.systemTemp.createTempSync('workspace_metadata_'); + database = UserStateDatabase.openAt('${directory.path}/state.db'); + lists = UserStateListStore(database: database); + sessions = _MetadataSessions(database: database); + }); + + tearDown(() async { + await database.flushWrites(); + lists.dispose(); + database.close(); + directory.deleteSync(recursive: true); + }); + + WorkspaceRepository repository(int? slot) => WorkspaceRepository( + store: lists, + sessions: sessions, + slot: () => slot, + ); + + test('זהות השולחן שייכת למשבצת ונקראת בלי סשן מלא', () async { + final first = Workspace(id: 'first', name: 'ראשון', tabs: []); + final second = Workspace(id: 'second', name: 'שני', tabs: []); + await repository(1).replaceWorkspaces([first, second], first.id); + await sessions.saveActiveWorkspace(2, second.id); + + expect((await repository(1).loadWorkspaces()).$2, first.id); + expect((await repository(2).loadWorkspaces()).$2, second.id); + expect((await repository(3).loadWorkspaces()).$2, isNull); + expect((await repository(null).loadWorkspaces()).$2, isNull); + }); + + test('מזהה לא קיים חוזר לשולחן הראשון או ל-null ברשימה ריקה', () async { + final first = Workspace(id: 'first', name: 'ראשון', tabs: []); + await repository(1).replaceWorkspaces([first], 'missing'); + final (workspaces, activeId) = await repository(1).loadWorkspaces(); + expect(workspaces, [first]); + expect(activeId, first.id); + await repository(1).replaceWorkspaces([], 'missing'); + expect((await repository(1).loadWorkspaces()).$2, isNull); + }); +}