Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions lib/core/user_state/window_session_store.dart
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,26 @@ class WindowSessionStore {
return _loadIn(db, slot);
}

/// קורא רק גבולות, בלי להעתיק את הכרטיסיות השמורות.
Future<String?> 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<String?> 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 ואינו
Expand Down
5 changes: 2 additions & 3 deletions lib/core/window_persistence.dart
Original file line number Diff line number Diff line change
Expand Up @@ -139,8 +139,7 @@ class WindowPersistenceBinding {
(Settings.getValue<String>(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(
Expand Down Expand Up @@ -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);

Expand Down
5 changes: 2 additions & 3 deletions lib/core/windowing/multiview/view_window_opener.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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),
Expand Down
2 changes: 1 addition & 1 deletion lib/workspaces/workspace_repository.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Expand Down
137 changes: 137 additions & 0 deletions test/core/user_state/window_session_metadata_read_test.dart
Original file line number Diff line number Diff line change
@@ -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<void>();
final started = Completer<void>();
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<void>.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<SqliteException>()),
);
await expectLater(
sessions.loadActiveWorkspaceId(1),
throwsA(isA<SqliteException>()),
);
});
}
157 changes: 157 additions & 0 deletions test/core/window_persistence_metadata_test.dart
Original file line number Diff line number Diff line change
@@ -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<void>? beforeRead;
final reads = <int>[];
final writes = <(int, String?)>[];

@override
Future<String?> loadBoundsJson(int slot) async {
reads.add(slot);
await beforeRead?.future;
return bounds;
}

@override
Future<WindowSession?> load(int slot) =>
throw StateError('שמירת גבולות אינה זקוקה לכרטיסיות');

@override
Future<void> 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<bool> isMinimized() async => minimized;

@override
Future<bool> isMaximized() async => maximized;

@override
Future<bool> isFullScreen() async => fullscreen;

@override
Future<Rect> 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<void>();
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]);
});
}
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,9 @@ class _MemorySessions extends WindowSessionStore {
);
}

@override
Future<String?> loadBoundsJson(int slot) async => rows[slot]?.boundsJson;

@override
Future<WindowSession?> load(int slot) async {
final row = rows[slot];
Expand Down
3 changes: 3 additions & 0 deletions test/core/windowing/multiview/view_window_opener_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,9 @@ class _MemorySessions extends WindowSessionStore {
);
}

@override
Future<String?> loadBoundsJson(int slot) async => rows[slot]?.boundsJson;

@override
Future<WindowSession?> load(int slot) async => rows[slot];

Expand Down
Loading
Loading