Skip to content

Truly independent web browser

LibWebView+UI/Qt: Restore each window’s size and position

sideshowbarker1919f943b7a2
diff --git a/Libraries/LibWebView/SessionStore.cpp b/Libraries/LibWebView/SessionStore.cpp
index 6d87d5c6322..8d02ed134a1 100644
--- a/Libraries/LibWebView/SessionStore.cpp
+++ b/Libraries/LibWebView/SessionStore.cpp
@@ -25,6 +25,7 @@ static constexpr u32 SESSIONS_SCHEMA_DOCUMENT_POLICY_VERSION = 4u;
static constexpr u32 SESSIONS_SCHEMA_PINNED_TABS_VERSION = 5u;
static constexpr u32 SESSIONS_SCHEMA_SESSION_LIFECYCLE_VERSION = 6u;
static constexpr u32 SESSIONS_SCHEMA_LAUNCH_RESTORE_VERSION = 7u;
+static constexpr u32 SESSIONS_SCHEMA_WINDOW_GEOMETRY_VERSION = 8u;
// After this many unclean exits in a row, launch restore stops, so a session that crashes the browser doesn't restore
// into the same crash every time.
@@ -47,6 +48,24 @@ static Optional<size_t> index_as_size(i64 index)
return static_cast<size_t>(index);
}
+// A row whose geometry is missing, or isn't a usable size, has none.
+static ErrorOr<Optional<SessionWindowGeometry>> read_window_geometry(Database::ResultRow& row)
+{
+ auto x = TRY(row.read_optional_integer<i32>("x"sv));
+ auto y = TRY(row.read_optional_integer<i32>("y"sv));
+ auto width = TRY(row.read_optional_integer<i32>("width"sv));
+ auto height = TRY(row.read_optional_integer<i32>("height"sv));
+ if (!x.has_value() || !y.has_value() || !width.has_value() || !height.has_value() || *width <= 0 || *height <= 0)
+ return Optional<SessionWindowGeometry> {};
+ return Optional<SessionWindowGeometry> { SessionWindowGeometry {
+ .x = *x,
+ .y = *y,
+ .width = *width,
+ .height = *height,
+ .maximized = TRY(row.read_integer<i64>("maximized"sv)) != 0,
+ } };
+}
+
ErrorOr<Database::MigrationOutcome> SessionStore::PersistedStorage::migrate_schema(Database::Database& database, Database::MigrationMode mode)
{
auto migrations = to_array<Database::Migration>({
@@ -245,6 +264,16 @@ ErrorOr<Database::MigrationOutcome> SessionStore::PersistedStorage::migrate_sche
ALTER TABLE Sessions ADD COLUMN restore_at_launch INTEGER NOT NULL DEFAULT 0;
)#"sv,
},
+ {
+ .version = SESSIONS_SCHEMA_WINDOW_GEOMETRY_VERSION,
+ .sql = R"#(
+ ALTER TABLE Sessions ADD COLUMN x INTEGER;
+ ALTER TABLE Sessions ADD COLUMN y INTEGER;
+ ALTER TABLE Sessions ADD COLUMN width INTEGER;
+ ALTER TABLE Sessions ADD COLUMN height INTEGER;
+ ALTER TABLE Sessions ADD COLUMN maximized INTEGER NOT NULL DEFAULT 0;
+ )#"sv,
+ },
});
return database.migrate("Sessions"sv, migrations, mode);
@@ -278,11 +307,12 @@ ErrorOr<SessionStore::PersistedStorage> SessionStore::PersistedStorage::create(D
statements.select_max_session_id = TRY(database.prepare_statement("SELECT MAX(id) AS maximum_id FROM Sessions;"sv));
statements.select_max_tab_id = TRY(database.prepare_statement("SELECT MAX(id) AS maximum_id FROM SessionTabs;"sv));
statements.select_max_close_sequence = TRY(database.prepare_statement("SELECT MAX(close_sequence) AS maximum_id FROM Sessions;"sv));
- statements.select_closed_sessions = TRY(database.prepare_statement("SELECT id, closed_time, close_sequence, source_window_id, source_tab_index, origin, active_tab_index FROM Sessions WHERE kind = :kind ORDER BY close_sequence DESC, closed_time DESC, id DESC LIMIT :max_units;"sv));
+ statements.select_closed_sessions = TRY(database.prepare_statement("SELECT id, closed_time, close_sequence, source_window_id, source_tab_index, origin, active_tab_index, x, y, width, height, maximized FROM Sessions WHERE kind = :kind ORDER BY close_sequence DESC, closed_time DESC, id DESC LIMIT :max_units;"sv));
statements.select_session_tabs = TRY(database.prepare_statement("SELECT id, tab_ordinal, active_url, current_used_step_index, pinned FROM SessionTabs WHERE session_id = :session_id ORDER BY tab_ordinal;"sv));
statements.select_max_activation_sequence = TRY(database.prepare_statement("SELECT MAX(activation_sequence) AS maximum_id FROM Sessions;"sv));
- statements.select_open_sessions = TRY(database.prepare_statement("SELECT id, active_tab_index, activation_sequence FROM Sessions WHERE kind = :open_window_kind ORDER BY activation_sequence, id;"sv));
- statements.select_restore_at_launch_session = TRY(database.prepare_statement("SELECT id, active_tab_index, activation_sequence FROM Sessions WHERE kind = :closed_window_kind AND restore_at_launch != 0 ORDER BY close_sequence DESC, id DESC LIMIT 1;"sv));
+ statements.update_session_geometry = TRY(database.prepare_statement("UPDATE Sessions SET x = :x, y = :y, width = :width, height = :height, maximized = :maximized WHERE id = :id;"sv));
+ statements.select_open_sessions = TRY(database.prepare_statement("SELECT id, active_tab_index, activation_sequence, x, y, width, height, maximized FROM Sessions WHERE kind = :open_window_kind ORDER BY activation_sequence, id;"sv));
+ statements.select_restore_at_launch_session = TRY(database.prepare_statement("SELECT id, active_tab_index, activation_sequence, x, y, width, height, maximized FROM Sessions WHERE kind = :closed_window_kind AND restore_at_launch != 0 ORDER BY close_sequence DESC, id DESC LIMIT 1;"sv));
statements.clear_restore_at_launch = TRY(database.prepare_statement("UPDATE Sessions SET restore_at_launch = 0 WHERE restore_at_launch != 0;"sv));
statements.reopen_closed_session = TRY(database.prepare_statement("UPDATE Sessions SET kind = :open_window_kind, closed_time = 0, close_sequence = 0, source_window_id = NULL, source_tab_index = NULL, origin = :origin WHERE id = :id;"sv));
statements.recover_open_session = TRY(database.prepare_statement("UPDATE Sessions SET kind = :closed_window_kind, closed_time = :closed_time, close_sequence = :close_sequence, source_window_id = NULL, source_tab_index = NULL, origin = :origin WHERE id = :id;"sv));
@@ -430,6 +460,16 @@ void SessionStore::TransientStorage::set_activation_sequence(SessionWindowId win
window->value.metadata_dirty = true;
}
+void SessionStore::TransientStorage::set_geometry(SessionWindowId window_id, SessionWindowGeometry geometry)
+{
+ auto window = m_windows.find(window_id);
+ if (window == m_windows.end() || window->value.geometry == geometry)
+ return;
+
+ window->value.geometry = geometry;
+ window->value.metadata_dirty = true;
+}
+
void SessionStore::TransientStorage::set_tab_order(SessionWindowId window_id, Vector<SessionTabId> const& ordered_tabs)
{
auto window = m_windows.find(window_id);
@@ -626,7 +666,11 @@ ErrorOr<void> SessionStore::PersistedStorage::apply_window_metadata(WindowMetada
++tab_ordinal;
}
- return write_session_metadata(write.id, write.active_tab_index, write.activation_sequence);
+ TRY(write_session_metadata(write.id, write.active_tab_index, write.activation_sequence));
+ // A write for a window that's already closing carries no geometry, and leaves its saved one as it is.
+ if (write.geometry.has_value())
+ TRY(write_session_geometry(write.id, *write.geometry));
+ return {};
}
ErrorOr<void> SessionStore::PersistedStorage::insert_closed_unit_row(ClosedUnitWrite const& write)
@@ -795,6 +839,19 @@ ErrorOr<void> SessionStore::PersistedStorage::write_session_metadata(SessionWind
});
}
+ErrorOr<void> SessionStore::PersistedStorage::write_session_geometry(SessionWindowId window_id, SessionWindowGeometry const& geometry)
+{
+ return database->try_execute_bound_statement(statements.update_session_geometry, [&](auto& bind) -> ErrorOr<void> {
+ TRY(bind("x"sv, i64 { geometry.x }));
+ TRY(bind("y"sv, i64 { geometry.y }));
+ TRY(bind("width"sv, i64 { geometry.width }));
+ TRY(bind("height"sv, i64 { geometry.height }));
+ TRY(bind("maximized"sv, i64 { geometry.maximized ? 1 : 0 }));
+ TRY(bind("id"sv, window_id));
+ return {};
+ });
+}
+
ErrorOr<void> SessionStore::PersistedStorage::clear_restore_at_launch()
{
return database->try_execute_bound_statement(statements.clear_restore_at_launch, [](auto&) -> ErrorOr<void> { return {}; });
@@ -893,14 +950,17 @@ ErrorOr<SessionStore::RecoveryResult> SessionStore::PersistedStorage::recover_op
i64 active_tab_index { 0 };
i64 activation_sequence { 0 };
bool was_open { true };
+ Optional<SessionWindowGeometry> geometry;
};
Vector<Candidate> candidates;
auto read_candidate = [&](Database::ResultRow& row, bool was_open) -> ErrorOr<void> {
+ auto geometry = read_window_geometry(row);
candidates.append({
.id = TRY(row.read_integer<SessionWindowId>("id"sv)),
.active_tab_index = TRY(row.read_integer<i64>("active_tab_index"sv)),
.activation_sequence = TRY(row.read_integer<i64>("activation_sequence"sv)),
.was_open = was_open,
+ .geometry = geometry.is_error() ? Optional<SessionWindowGeometry> {} : geometry.release_value(),
});
return {};
};
@@ -964,7 +1024,7 @@ ErrorOr<SessionStore::RecoveryResult> SessionStore::PersistedStorage::recover_op
window_tabs.extend(move(unpinned_tabs));
TRY(reparent_tabs(candidate.id, window_tabs));
TRY(write_session_metadata(candidate.id, active_tab_index, candidate.activation_sequence));
- result.windows.append({ .id = candidate.id, .tabs = move(window_tabs), .active_tab_index = active_tab_index, .activation_sequence = candidate.activation_sequence });
+ result.windows.append({ .id = candidate.id, .tabs = move(window_tabs), .active_tab_index = active_tab_index, .activation_sequence = candidate.activation_sequence, .geometry = candidate.geometry });
continue;
}
@@ -974,7 +1034,9 @@ ErrorOr<SessionStore::RecoveryResult> SessionStore::PersistedStorage::recover_op
TRY(reparent_tabs(pinned_window_id, pinned_tabs));
auto pinned_active_tab_index = index_as_i64(active_pinned_tab.value_or(0));
TRY(write_session_metadata(pinned_window_id, pinned_active_tab_index, candidate.activation_sequence));
- result.windows.append({ .id = pinned_window_id, .tabs = move(pinned_tabs), .active_tab_index = pinned_active_tab_index, .activation_sequence = candidate.activation_sequence });
+ if (candidate.geometry.has_value())
+ TRY(write_session_geometry(pinned_window_id, *candidate.geometry));
+ result.windows.append({ .id = pinned_window_id, .tabs = move(pinned_tabs), .active_tab_index = pinned_active_tab_index, .activation_sequence = candidate.activation_sequence, .geometry = candidate.geometry });
}
if (unpinned_tabs.is_empty()) {
@@ -1099,6 +1161,7 @@ ErrorOr<Vector<SessionStore::ClosedUnit>> SessionStore::PersistedStorage::load_c
Optional<ClosedSessionUnit::Origin> origin;
// Empty when the stored index is not a usable one, which retires only this unit.
Optional<i64> active_tab_index;
+ Optional<SessionWindowGeometry> geometry;
};
Vector<ClosedUnit> units;
@@ -1119,6 +1182,7 @@ ErrorOr<Vector<SessionStore::ClosedUnit>> SessionStore::PersistedStorage::load_c
auto origin = row.read_integer<i64>("origin"sv);
auto session_id = row.read_integer<i64>("id"sv);
auto closed_time = row.read_integer<i64>("closed_time"sv);
+ auto geometry = read_window_geometry(row);
Optional<ClosedSessionUnit::Origin> validated_origin;
if (!origin.is_error()) {
@@ -1136,6 +1200,7 @@ ErrorOr<Vector<SessionStore::ClosedUnit>> SessionStore::PersistedStorage::load_c
.source_tab_index = !source_tab_index.is_error() && source_tab_index.value().value_or(-1) >= 0 ? source_tab_index.value() : Optional<i64> {},
.origin = validated_origin,
.active_tab_index = !active_tab_index.is_error() && active_tab_index.value() >= 0 ? Optional<i64> { active_tab_index.value() } : Optional<i64> {},
+ .geometry = geometry.is_error() ? Optional<SessionWindowGeometry> {} : geometry.release_value(),
});
return {};
}));
@@ -1197,6 +1262,7 @@ ErrorOr<Vector<SessionStore::ClosedUnit>> SessionStore::PersistedStorage::load_c
.source_tab_index = session_row.source_tab_index,
.origin = *session_row.origin,
.tabs = move(tabs),
+ .geometry = session_row.geometry,
});
}
}
@@ -1432,7 +1498,7 @@ ErrorOr<void> SessionStore::run_startup_recovery(UnixDateTime recovered_at, Sess
for (auto& window : recovery.windows) {
m_transient_storage.open_window(window.id);
- RestoredSessionWindow restored { .window_id = window.id, .tabs = {}, .active_tab_index = window.active_tab_index };
+ RestoredSessionWindow restored { .window_id = window.id, .tabs = {}, .active_tab_index = window.active_tab_index, .geometry = window.geometry };
for (auto& tab : window.tabs) {
restored.tabs.append({ .tab_id = tab.id, .url = tab.url, .pinned = tab.pinned });
(void)m_transient_storage.open_tab(window.id, tab.id,
@@ -1441,6 +1507,8 @@ ErrorOr<void> SessionStore::run_startup_recovery(UnixDateTime recovered_at, Sess
if (auto active_tab_index = index_as_size(window.active_tab_index); active_tab_index.has_value() && *active_tab_index < restored.tabs.size())
m_transient_storage.set_active_tab(restored.tabs[*active_tab_index].tab_id);
m_transient_storage.set_activation_sequence(window.id, window.activation_sequence);
+ if (window.geometry.has_value())
+ m_transient_storage.set_geometry(window.id, *window.geometry);
// Recovery already wrote these windows' rows as they stand.
m_transient_storage.mark_window_metadata_clean(window.id);
m_launch_plan.append(move(restored));
@@ -1452,7 +1520,7 @@ ErrorOr<void> SessionStore::run_startup_recovery(UnixDateTime recovered_at, Sess
SessionStore::WindowMetadataWrite SessionStore::window_metadata_write(SessionWindowId window_id, OpenWindow const& window) const
{
- WindowMetadataWrite write { .id = window_id, .tabs_in_order = window.tabs, .pinned_tabs = {}, .active_tab_index = 0, .activation_sequence = window.activation_sequence };
+ WindowMetadataWrite write { .id = window_id, .tabs_in_order = window.tabs, .pinned_tabs = {}, .active_tab_index = 0, .activation_sequence = window.activation_sequence, .geometry = window.geometry };
for (auto tab_id : window.tabs) {
if (auto const* tab = m_transient_storage.find_tab(tab_id); tab && tab->pinned)
write.pinned_tabs.set(tab_id);
@@ -1482,7 +1550,7 @@ Optional<SessionStore::WindowMetadataWrite> SessionStore::remaining_window_write
for (auto const& pending : m_pending_window_closes) {
if (pending.window_id != window_id)
continue;
- WindowMetadataWrite write { .id = window_id, .tabs_in_order = {}, .pinned_tabs = {}, .active_tab_index = 0, .activation_sequence = pending.activation_sequence };
+ WindowMetadataWrite write { .id = window_id, .tabs_in_order = {}, .pinned_tabs = {}, .active_tab_index = 0, .activation_sequence = pending.activation_sequence, .geometry = {} };
for (auto const& member : pending.members) {
if (member.tab_id == closing_tab)
continue;
@@ -1607,6 +1675,7 @@ void SessionStore::window_detached(SessionWindowId window_id)
.members = {},
.closed_at = {},
.discard = true,
+ .geometry = {},
});
}
@@ -1620,6 +1689,11 @@ ErrorOr<SessionWindowId> SessionStore::default_window()
return *m_transient_storage.default_window;
}
+void SessionStore::window_geometry_changed(SessionWindowId window_id, SessionWindowGeometry geometry)
+{
+ m_transient_storage.set_geometry(window_id, geometry);
+}
+
void SessionStore::window_activated(SessionWindowId window_id)
{
if (!m_transient_storage.find_window(window_id))
@@ -1753,6 +1827,7 @@ void SessionStore::append_closed_tab_unit(PendingTabClose const& pending)
.source_tab_index = pending.source_tab_index,
.origin = ClosedSessionUnit::Origin::CloseAction,
.tabs = {},
+ .geometry = {},
};
unit.tabs.append({
.active_url = pending.tab.url,
@@ -1776,6 +1851,7 @@ void SessionStore::append_closed_window_unit(PendingWindowClose const& pending)
.source_tab_index = {},
.origin = ClosedSessionUnit::Origin::CloseAction,
.tabs = {},
+ .geometry = pending.geometry,
};
for (auto const& member : pending.members) {
size_t mirror_step_index = member.tab.current_used_step_index;
@@ -2027,6 +2103,7 @@ ErrorOr<void> SessionStore::window_closing(WindowClosing closing)
.discard = discard,
.restore_at_launch = restore_at_launch,
.activation_sequence = window->activation_sequence,
+ .geometry = window->geometry,
};
for (auto member_id : window->tabs) {
if (auto const* tab = m_transient_storage.find_tab(member_id))
@@ -2154,6 +2231,7 @@ ErrorOr<Optional<ClosedSessionUnit>> SessionStore::take_most_recently_closed()
.source_window_id = unit->source_window_id,
.source_tab_index = unit->source_tab_index,
.origin = unit->origin,
+ .geometry = unit->geometry,
};
if (m_persisted_storage.has_value()) {
diff --git a/Libraries/LibWebView/SessionStore.h b/Libraries/LibWebView/SessionStore.h
index a607d21e921..14ef778459f 100644
--- a/Libraries/LibWebView/SessionStore.h
+++ b/Libraries/LibWebView/SessionStore.h
@@ -26,6 +26,17 @@ using SessionWindowId = i64;
using SessionTabId = i64;
using SessionCloseSequence = i64;
+// A window's normal (not maximized) geometry, plus whether it's maximized.
+struct SessionWindowGeometry {
+ i32 x { 0 };
+ i32 y { 0 };
+ i32 width { 0 };
+ i32 height { 0 };
+ bool maximized { false };
+
+ bool operator==(SessionWindowGeometry const&) const = default;
+};
+
struct ClosedSessionTab {
URL::URL active_url;
Optional<SessionHistorySnapshot> history;
@@ -44,6 +55,7 @@ struct ClosedSessionUnit {
Optional<SessionWindowId> source_window_id;
Optional<i64> source_tab_index;
Origin origin { Origin::CloseAction };
+ Optional<SessionWindowGeometry> geometry;
};
// What startup recovery does with the windows the last run left open.
@@ -67,6 +79,7 @@ struct RestoredSessionWindow {
SessionWindowId window_id { 0 };
Vector<RestoredSessionTab> tabs;
i64 active_tab_index { 0 };
+ Optional<SessionWindowGeometry> geometry;
};
// Persists live windows and tabs plus a bounded recently-closed stack. State updates coalesce; lifecycle mutations
@@ -130,6 +143,7 @@ public:
ErrorOr<void> window_closing(WindowClosing);
void window_detached(SessionWindowId);
void window_activated(SessionWindowId);
+ void window_geometry_changed(SessionWindowId, SessionWindowGeometry);
ErrorOr<SessionTabId> tab_opened(TabOpened);
void update_tab_state(TabStateUpdate);
ErrorOr<void> tab_closed(TabClosed);
@@ -205,6 +219,7 @@ private:
Database::StatementID update_tab_parent;
Database::StatementID update_session_closed;
Database::StatementID update_session_metadata;
+ Database::StatementID update_session_geometry;
Database::StatementID delete_session;
Database::StatementID delete_tab;
Database::StatementID prune_closed;
@@ -247,6 +262,7 @@ private:
SessionTabId active_tab { 0 };
bool metadata_dirty { false };
i64 activation_sequence { 0 };
+ Optional<SessionWindowGeometry> geometry;
};
struct ClosedTab {
@@ -268,6 +284,7 @@ private:
Optional<i64> source_tab_index;
ClosedSessionUnit::Origin origin { ClosedSessionUnit::Origin::CloseAction };
Vector<ClosedTab> tabs;
+ Optional<SessionWindowGeometry> geometry;
};
enum class SnapshotDisposition {
@@ -295,6 +312,7 @@ private:
HashTable<SessionTabId> pinned_tabs;
i64 active_tab_index { 0 };
i64 activation_sequence { 0 };
+ Optional<SessionWindowGeometry> geometry;
};
struct OpenTabWrite {
@@ -366,6 +384,7 @@ private:
Vector<RecoveredTab> tabs;
i64 active_tab_index { 0 };
i64 activation_sequence { 0 };
+ Optional<SessionWindowGeometry> geometry;
};
struct RecoveryResult {
@@ -409,6 +428,7 @@ private:
ErrorOr<Vector<RecoveredTab>> read_recovered_tabs(SessionWindowId);
ErrorOr<void> reparent_tabs(SessionWindowId, Vector<RecoveredTab> const&);
ErrorOr<void> write_session_metadata(SessionWindowId, i64 active_tab_index, i64 activation_sequence);
+ ErrorOr<void> write_session_geometry(SessionWindowId, SessionWindowGeometry const&);
ErrorOr<void> demote_to_startup_recovery_unit(SessionWindowId, UnixDateTime recovered_at, IdAllocator& close_sequence_allocator);
ErrorOr<void> reopen_session(SessionWindowId);
};
@@ -434,6 +454,7 @@ private:
bool discard { false };
bool restore_at_launch { false };
i64 activation_sequence { 0 };
+ Optional<SessionWindowGeometry> geometry;
};
// Owns in-memory membership, ordering, and dirty state.
@@ -451,6 +472,7 @@ private:
void mark_tab_flushed(SessionTabId, size_t current_used_step_index);
void set_active_tab(SessionTabId);
void set_activation_sequence(SessionWindowId, i64);
+ void set_geometry(SessionWindowId, SessionWindowGeometry);
void set_tab_order(SessionWindowId, Vector<SessionTabId> const&);
Optional<SessionWindowId> move_tab(SessionTabId, SessionWindowId, size_t ordinal);
void remove_tab(SessionTabId);
diff --git a/Tests/LibWebView/TestSessionHistorySnapshotStorage.cpp b/Tests/LibWebView/TestSessionHistorySnapshotStorage.cpp
index 889f3087dec..9bec14a8481 100644
--- a/Tests/LibWebView/TestSessionHistorySnapshotStorage.cpp
+++ b/Tests/LibWebView/TestSessionHistorySnapshotStorage.cpp
@@ -533,6 +533,11 @@ TEST_CASE(snapshot_entries_saved_before_the_user_agent_initiated_column_load_as_
// Take the database back to the baseline schema, keeping the entry's row.
TRY_OR_FAIL(database->execute_raw(R"#(
+ ALTER TABLE Sessions DROP COLUMN maximized;
+ ALTER TABLE Sessions DROP COLUMN height;
+ ALTER TABLE Sessions DROP COLUMN width;
+ ALTER TABLE Sessions DROP COLUMN y;
+ ALTER TABLE Sessions DROP COLUMN x;
ALTER TABLE Sessions DROP COLUMN restore_at_launch;
ALTER TABLE Sessions DROP COLUMN activation_sequence;
DROP TABLE SessionLifecycle;
@@ -546,7 +551,7 @@ TEST_CASE(snapshot_entries_saved_before_the_user_agent_initiated_column_load_as_
)#"sv));
auto migrated_statements = prepare_snapshot_tables(*database);
- EXPECT_EQ(TRY_OR_FAIL(database->schema_version("Sessions"sv)), Optional<u32> { 7u });
+ EXPECT_EQ(TRY_OR_FAIL(database->schema_version("Sessions"sv)), Optional<u32> { 8u });
auto loaded = TRY_OR_FAIL(load_session_history_snapshot(*database, migrated_statements, 42, 0));
EXPECT_EQ(loaded.entries.size(), 1uz);
diff --git a/Tests/LibWebView/TestSessionStore.cpp b/Tests/LibWebView/TestSessionStore.cpp
index 0701bbd9468..d5c90765fba 100644
--- a/Tests/LibWebView/TestSessionStore.cpp
+++ b/Tests/LibWebView/TestSessionStore.cpp
@@ -75,6 +75,11 @@ static SessionTabId open_tab(SessionStore& store, SessionWindowId window, String
// Takes the schema back to SESSIONS_SCHEMA_DOCUMENT_POLICY_VERSION, so every migration after it runs again.
static void rewind_sessions_schema_to_version_4(Database::Database& database)
{
+ MUST(database.execute_raw("ALTER TABLE Sessions DROP COLUMN maximized;"sv));
+ MUST(database.execute_raw("ALTER TABLE Sessions DROP COLUMN height;"sv));
+ MUST(database.execute_raw("ALTER TABLE Sessions DROP COLUMN width;"sv));
+ MUST(database.execute_raw("ALTER TABLE Sessions DROP COLUMN y;"sv));
+ MUST(database.execute_raw("ALTER TABLE Sessions DROP COLUMN x;"sv));
MUST(database.execute_raw("ALTER TABLE Sessions DROP COLUMN restore_at_launch;"sv));
MUST(database.execute_raw("ALTER TABLE Sessions DROP COLUMN activation_sequence;"sv));
MUST(database.execute_raw("DROP TABLE SessionLifecycle;"sv));
@@ -99,7 +104,7 @@ TEST_CASE(fresh_database_migrates_to_the_latest_schema)
for (auto table : { "Sessions"sv, "SessionTabs"sv, "SessionUsedSteps"sv, "SessionHistories"sv, "SessionNestedHistories"sv, "SessionEntries"sv })
EXPECT(TRY_OR_FAIL(database->table_exists(table)));
- EXPECT_EQ(TRY_OR_FAIL(database->schema_version("Sessions"sv)), Optional<u32> { 7u });
+ EXPECT_EQ(TRY_OR_FAIL(database->schema_version("Sessions"sv)), Optional<u32> { 8u });
}
TEST_CASE(deleting_a_session_cascades_through_its_tabs)
@@ -146,8 +151,10 @@ TEST_CASE(version_4_database_migrates_to_the_latest_schema)
rewind_sessions_schema_to_version_4(*database);
EXPECT_EQ(TRY_OR_FAIL(SessionStore::migrate_schema(*database)), Database::MigrationOutcome::Success);
- EXPECT_EQ(TRY_OR_FAIL(database->schema_version("Sessions"sv)), Optional<u32> { 7u });
+ EXPECT_EQ(TRY_OR_FAIL(database->schema_version("Sessions"sv)), Optional<u32> { 8u });
EXPECT_EQ(select_i64(*database, "SELECT pinned FROM SessionTabs WHERE id = 2;"_string), 0);
+ EXPECT_EQ(select_i64(*database, "SELECT COUNT(*) FROM Sessions WHERE id = 1 AND width IS NULL;"_string), 1);
+ EXPECT_EQ(select_i64(*database, "SELECT maximized FROM Sessions WHERE id = 1;"_string), 0);
}
TEST_CASE(pushed_tab_state_flushes_to_rows)
@@ -1815,6 +1822,134 @@ TEST_CASE(a_transient_store_has_no_launch_plan)
EXPECT(!store->load_tab_history(1).has_value());
}
+static constexpr SessionWindowGeometry test_geometry { .x = 10, .y = 20, .width = 800, .height = 600, .maximized = true };
+
+TEST_CASE(window_geometry_waits_for_a_flush)
+{
+ auto database = create_session_database();
+ auto store = TRY_OR_FAIL(SessionStore::create(*database));
+ auto window = TRY_OR_FAIL(store->window_opened());
+ (void)open_tab(*store, window, "https://a.example/"sv);
+
+ store->window_geometry_changed(window, { .x = 10, .y = 20, .width = 800, .height = 600, .maximized = false });
+ EXPECT_EQ(select_i64(*database, MUST(String::formatted("SELECT COUNT(*) FROM Sessions WHERE id = {} AND width IS NULL;", window))), 1);
+
+ store->flush_dirty_state();
+ EXPECT_EQ(select_i64(*database, MUST(String::formatted("SELECT width FROM Sessions WHERE id = {};", window))), 800);
+ EXPECT_EQ(select_i64(*database, MUST(String::formatted("SELECT maximized FROM Sessions WHERE id = {};", window))), 0);
+}
+
+TEST_CASE(a_closed_window_keeps_its_geometry)
+{
+ auto database = create_session_database();
+ SessionWindowId first_window = 0;
+ {
+ auto store = TRY_OR_FAIL(SessionStore::create(*database));
+ first_window = TRY_OR_FAIL(store->window_opened());
+ auto second_window = TRY_OR_FAIL(store->window_opened());
+ (void)open_tab(*store, first_window, "https://a.example/"sv);
+ (void)open_tab(*store, second_window, "https://b.example/"sv);
+ store->window_geometry_changed(first_window, test_geometry);
+ TRY_OR_FAIL(store->window_closing({ .window_id = first_window, .active_tab_index = 0, .closed_at = UnixDateTime::now() }));
+ quit_cleanly(*store, { second_window });
+ }
+
+ // After a relaunch, the unit's geometry comes from its row.
+ auto store = TRY_OR_FAIL(SessionStore::create(*database));
+ Optional<ClosedSessionUnit> first_window_unit;
+ for (;;) {
+ auto unit = TRY_OR_FAIL(store->take_most_recently_closed());
+ if (!unit.has_value())
+ break;
+ if (unit->tabs[0].active_url.serialize() == "https://a.example/"sv)
+ first_window_unit = unit.release_value();
+ }
+ EXPECT(first_window_unit.has_value());
+ EXPECT(first_window_unit->geometry.has_value());
+ EXPECT(*first_window_unit->geometry == test_geometry);
+}
+
+TEST_CASE(transient_closed_windows_keep_their_geometry)
+{
+ auto store = SessionStore::create();
+ auto window = TRY_OR_FAIL(store->window_opened());
+ (void)open_tab(*store, window, "https://a.example/"sv);
+ store->window_geometry_changed(window, test_geometry);
+ TRY_OR_FAIL(store->window_closing({ .window_id = window, .active_tab_index = 0, .closed_at = UnixDateTime::now() }));
+
+ auto unit = TRY_OR_FAIL(store->take_most_recently_closed());
+ EXPECT(unit.has_value());
+ EXPECT(unit->geometry.has_value());
+ EXPECT(*unit->geometry == test_geometry);
+}
+
+TEST_CASE(launch_plans_keep_window_geometry)
+{
+ for (auto policy : { SessionLaunchPolicy::Everything, SessionLaunchPolicy::PinnedOnly }) {
+ auto database = create_session_database();
+ {
+ auto store = TRY_OR_FAIL(SessionStore::create(*database));
+ auto window = TRY_OR_FAIL(store->window_opened());
+ auto tab = open_tab(*store, window, "https://a.example/"sv);
+ TRY_OR_FAIL(store->tab_pinned_changed(tab, true));
+ store->window_geometry_changed(window, test_geometry);
+ quit_cleanly(*store, { window });
+ }
+
+ auto store = TRY_OR_FAIL(SessionStore::create(*database, policy));
+ auto plan = store->take_launch_plan();
+ EXPECT_EQ(plan.size(), 1uz);
+ EXPECT(plan[0].geometry.has_value());
+ EXPECT(*plan[0].geometry == test_geometry);
+
+ // The window the plan keeps has its row hold the geometry too.
+ EXPECT_EQ(select_i64(*database, MUST(String::formatted("SELECT COUNT(*) FROM Sessions WHERE id = {} AND x = 10 AND y = 20 AND width = 800 AND height = 600 AND maximized = 1;", plan[0].window_id))), 1);
+ }
+}
+
+TEST_CASE(a_corrupt_saved_geometry_is_dropped_instead_of_failing_recovery)
+{
+ auto database = create_session_database();
+ {
+ auto store = TRY_OR_FAIL(SessionStore::create(*database));
+ auto window = TRY_OR_FAIL(store->window_opened());
+ (void)open_tab(*store, window, "https://a.example/"sv);
+ store->window_geometry_changed(window, test_geometry);
+ store->flush_dirty_state();
+ TRY_OR_FAIL(database->execute_raw("UPDATE Sessions SET width = 'wide' WHERE kind = 0;"sv));
+ }
+
+ auto store = TRY_OR_FAIL(SessionStore::create(*database, SessionLaunchPolicy::Everything));
+ auto plan = store->take_launch_plan();
+ EXPECT_EQ(plan.size(), 1uz);
+ EXPECT(!plan[0].geometry.has_value());
+}
+
+TEST_CASE(a_pending_tab_close_in_a_closing_window_leaves_the_saved_geometry)
+{
+ auto database = create_session_database();
+ auto store = TRY_OR_FAIL(SessionStore::create(*database));
+ auto window = TRY_OR_FAIL(store->window_opened());
+ (void)open_tab(*store, window, "https://a.example/"sv);
+ auto second = open_tab(*store, window, "https://b.example/"sv);
+ store->window_geometry_changed(window, test_geometry);
+ store->flush_dirty_state();
+
+ // The tab close fails and the window close stays pending, so the tab's close is retried against a window that's
+ // already closing.
+ TRY_OR_FAIL(database->execute_raw("CREATE TRIGGER InjectedTabFailure BEFORE INSERT ON Sessions BEGIN SELECT RAISE(ABORT, 'injected'); END;"sv));
+ TRY_OR_FAIL(database->execute_raw("CREATE TRIGGER InjectedKindFailure BEFORE UPDATE OF kind ON Sessions BEGIN SELECT RAISE(ABORT, 'injected'); END;"sv));
+ EXPECT(store->tab_closed({ .tab_id = second, .closed_at = UnixDateTime::from_seconds_since_epoch(100) }).is_error());
+ (void)store->window_closing({ .window_id = window, .active_tab_index = 0, .closed_at = UnixDateTime::from_seconds_since_epoch(101) });
+
+ // The row's width is changed behind the store's back, so a retry that rewrote the window's geometry would show.
+ TRY_OR_FAIL(database->execute_raw("UPDATE Sessions SET width = 999;"sv));
+ TRY_OR_FAIL(database->execute_raw("DROP TRIGGER InjectedTabFailure;"sv));
+ store->flush_dirty_state();
+
+ EXPECT_EQ(select_i64(*database, "SELECT width FROM Sessions WHERE kind = 0;"_string), 999);
+}
+
TEST_CASE(retention_keeps_the_newest_closed_units)
{
auto database = create_session_database();
diff --git a/UI/Qt/Application.cpp b/UI/Qt/Application.cpp
index 3db88d05351..d7bad2432d5 100644
--- a/UI/Qt/Application.cpp
+++ b/UI/Qt/Application.cpp
@@ -45,6 +45,7 @@
#include <QMimeDatabase>
#include <QPointer>
#include <QSaveFile>
+#include <QScreen>
#include <QShortcut>
#include <QStandardPaths>
#include <QTimer>
@@ -715,6 +716,30 @@ WebView::SessionLaunchPolicy Application::launch_restore_policy() const
return WebView::SessionLaunchPolicy::PinnedOnly;
}
+static WindowConfiguration window_configuration_for(WebView::SessionWindowGeometry const& geometry)
+{
+ QRect rect { geometry.x, geometry.y, geometry.width, geometry.height };
+
+ // The display a window was on may be gone since the last run, so the window comes back on a screen that's there.
+ auto* screen = QGuiApplication::screenAt(rect.center());
+ if (!screen)
+ screen = QGuiApplication::primaryScreen();
+ if (screen) {
+ auto available = screen->availableGeometry();
+ rect.setSize(rect.size().boundedTo(available.size()));
+ rect.moveLeft(clamp(rect.left(), available.left(), available.right() - rect.width() + 1));
+ rect.moveTop(clamp(rect.top(), available.top(), available.bottom() - rect.height() + 1));
+ }
+
+ return {
+ .x = Web::DevicePixels { rect.x() },
+ .y = Web::DevicePixels { rect.y() },
+ .width = Web::DevicePixels { rect.width() },
+ .height = Web::DevicePixels { rect.height() },
+ .maximized = geometry.maximized,
+ };
+}
+
BrowserWindow* Application::restore_previous_session(WindowConfiguration const& frontmost_window_configuration)
{
auto plan = WebView::Application::default_session().session_store->take_launch_plan();
@@ -723,7 +748,9 @@ BrowserWindow* Application::restore_previous_session(WindowConfiguration const&
for (size_t i = 0; i < plan.size(); ++i) {
auto const& restored = plan[i];
// The plan lists the frontmost window last, and opening the windows in that order leaves it on top.
- auto configuration = i == plan.size() - 1 ? frontmost_window_configuration : configuration_for_new_window();
+ auto configuration = restored.geometry.has_value()
+ ? window_configuration_for(*restored.geometry)
+ : (i == plan.size() - 1 ? frontmost_window_configuration : configuration_for_new_window());
auto* window = new BrowserWindow({}, BrowserWindow::IsPopupWindow::No, WebView::IsPrivate::No, nullptr, {}, restored.window_id);
window->restore_tabs(restored.tabs, restored.active_tab_index);
@@ -920,8 +947,10 @@ void Application::reopen_recently_closed_tab(BrowserWindow* target_window)
break;
}
}
- if (unit.was_window || !window)
- window = &new_window({}, configuration_for_new_window(), BrowserWindow::IsPopupWindow::No, is_private);
+ if (unit.was_window || !window) {
+ auto configuration = unit.geometry.has_value() ? window_configuration_for(*unit.geometry) : configuration_for_new_window();
+ window = &new_window({}, configuration, BrowserWindow::IsPopupWindow::No, is_private);
+ }
Optional<int> next_insertion_index;
if (restoring_to_source_window && unit.source_tab_index.has_value())
diff --git a/UI/Qt/BrowserWindow.cpp b/UI/Qt/BrowserWindow.cpp
index e363a986022..ad0592fcb8d 100644
--- a/UI/Qt/BrowserWindow.cpp
+++ b/UI/Qt/BrowserWindow.cpp
@@ -1607,6 +1607,8 @@ void BrowserWindow::resizeEvent(QResizeEvent* event)
for_each_tab([&](auto& tab) {
tab.view().set_window_size({ width(), height() });
});
+
+ report_session_window_geometry();
}
void BrowserWindow::changeEvent(QEvent* event)
@@ -1619,6 +1621,7 @@ void BrowserWindow::changeEvent(QEvent* event)
update_menu_bar_window_control_icons();
m_tabs_container->update_window_button_icons();
update_window_border();
+ report_session_window_geometry();
QWindowStateChangeEvent* stateChangeEvent = static_cast<QWindowStateChangeEvent*>(event);
bool was_fullscreen = stateChangeEvent->oldState() & Qt::WindowFullScreen;
@@ -1685,6 +1688,8 @@ void BrowserWindow::moveEvent(QMoveEvent* event)
for_each_tab([&](auto& tab) {
tab.view().set_window_position({ x(), y() });
});
+
+ report_session_window_geometry();
}
void BrowserWindow::wheelEvent(QWheelEvent* event)
@@ -1796,6 +1801,28 @@ void BrowserWindow::report_activation_to_session_store()
m_session->session_store->window_activated(*m_session_window_id);
}
+void BrowserWindow::report_session_window_geometry()
+{
+ if (!m_session_window_id.has_value())
+ return;
+
+ // Entering full screen clears the maximized state, and the window then fills the screen — so the last report from
+ // before it, with its normal rect and maximized flag, stands as the window's saved geometry.
+ if (isFullScreen())
+ return;
+
+ // A maximized window keeps the geometry it had before, for when it's restored.
+ auto rect = isMaximized() ? normalGeometry() : geometry();
+ WebView::SessionWindowGeometry window_geometry {
+ .x = rect.x(),
+ .y = rect.y(),
+ .width = rect.width(),
+ .height = rect.height(),
+ .maximized = isMaximized(),
+ };
+ m_session->session_store->window_geometry_changed(*m_session_window_id, window_geometry);
+}
+
void BrowserWindow::begin_window_close_preflight(Function<void(bool approved)> on_complete)
{
m_window_close_active_tab_index = static_cast<i64>(max(m_tabs_container->current_index(), 0));
diff --git a/UI/Qt/BrowserWindow.h b/UI/Qt/BrowserWindow.h
index bfbd7013389..6feb5151b4a 100644
--- a/UI/Qt/BrowserWindow.h
+++ b/UI/Qt/BrowserWindow.h
@@ -253,6 +253,7 @@ private:
void clear_resize_cursor();
bool should_draw_window_border() const;
void update_window_border();
+ void report_session_window_geometry();
void initialize_application_actions();
void initialize_application_menu();