Skip to content

Truly independent web browser

UI/Qt: Offer to restart Ladybird after the system updated its package

Jelle Raaijmakers539b70070adf
diff --git a/Libraries/LibCore/Forward.h b/Libraries/LibCore/Forward.h
index b1752200dc7..4ece0937de2 100644
--- a/Libraries/LibCore/Forward.h
+++ b/Libraries/LibCore/Forward.h
@@ -22,6 +22,7 @@ class Event;
class EventLoop;
class EventReceiver;
class File;
+class FileWatcher;
class LocalServer;
class LocalSocket;
class MappedFile;
diff --git a/Tests/UI/Qt/TestSessionHistorySnapshotStorage.cpp b/Tests/UI/Qt/TestSessionHistorySnapshotStorage.cpp
index de10b7f016a..01abf58cacf 100644
--- a/Tests/UI/Qt/TestSessionHistorySnapshotStorage.cpp
+++ b/Tests/UI/Qt/TestSessionHistorySnapshotStorage.cpp
@@ -585,7 +585,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> { 9u });
+ EXPECT_EQ(TRY_OR_FAIL(database->schema_version("Sessions"sv)), Optional<u32> { 10u });
auto loaded = TRY_OR_FAIL(load_session_history_snapshot(*database, migrated_statements, 42, 0));
EXPECT_EQ(loaded.entries.size(), 1uz);
@@ -616,11 +616,12 @@ TEST_CASE(snapshot_policy_containers_saved_before_the_insecure_requests_policy_l
TRY_OR_FAIL(database->execute_raw(R"#(
DROP TABLE SessionUpgradeInsecureNavigations;
ALTER TABLE SessionPolicyContainers DROP COLUMN insecure_requests_policy;
+ ALTER TABLE SessionLifecycle DROP COLUMN restart;
UPDATE SchemaVersions SET version = 8 WHERE store = 'Sessions';
)#"sv));
auto migrated_statements = prepare_snapshot_tables(*database);
- EXPECT_EQ(TRY_OR_FAIL(database->schema_version("Sessions"sv)), Optional<u32> { 9u });
+ EXPECT_EQ(TRY_OR_FAIL(database->schema_version("Sessions"sv)), Optional<u32> { 10u });
auto loaded = TRY_OR_FAIL(load_session_history_snapshot(*database, migrated_statements, 27, 0));
auto const* container = loaded.entries[0].document_state.history_policy_container.get_pointer<Web::HTML::SerializedPolicyContainer>();
diff --git a/Tests/UI/Qt/TestSessionStore.cpp b/Tests/UI/Qt/TestSessionStore.cpp
index c57187d2ed8..cc6e5d721bf 100644
--- a/Tests/UI/Qt/TestSessionStore.cpp
+++ b/Tests/UI/Qt/TestSessionStore.cpp
@@ -107,7 +107,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, "SessionUpgradeInsecureNavigations"sv })
EXPECT(TRY_OR_FAIL(database->table_exists(table)));
- EXPECT_EQ(TRY_OR_FAIL(database->schema_version("Sessions"sv)), Optional<u32> { 9u });
+ EXPECT_EQ(TRY_OR_FAIL(database->schema_version("Sessions"sv)), Optional<u32> { 10u });
}
TEST_CASE(deleting_a_session_cascades_through_its_tabs)
@@ -154,7 +154,7 @@ 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> { 9u });
+ EXPECT_EQ(TRY_OR_FAIL(database->schema_version("Sessions"sv)), Optional<u32> { 10u });
EXPECT(TRY_OR_FAIL(database->table_exists("SessionUpgradeInsecureNavigations"sv)));
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);
@@ -1593,6 +1593,47 @@ TEST_CASE(closing_the_last_window_restores_it_at_launch)
EXPECT(!store->has_closed_units());
}
+TEST_CASE(a_restart_restores_every_window_once)
+{
+ auto database = create_session_database();
+ {
+ auto store = TRY_OR_FAIL(SessionStore::create(*database));
+ auto 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->mark_clean_exit(SessionStore::RestartAfterExit::Yes);
+ }
+ {
+ auto store = TRY_OR_FAIL(SessionStore::create(*database, SessionLaunchPolicy::PinnedOnly));
+ EXPECT(store->follows_restart());
+ EXPECT_EQ(store->take_launch_plan().size(), 2uz);
+ store->mark_clean_exit();
+ }
+
+ auto store = TRY_OR_FAIL(SessionStore::create(*database, SessionLaunchPolicy::PinnedOnly));
+ EXPECT(!store->follows_restart());
+ EXPECT(store->take_launch_plan().is_empty());
+}
+
+TEST_CASE(only_the_run_right_after_a_restart_follows_it)
+{
+ 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->mark_clean_exit(SessionStore::RestartAfterExit::Yes);
+ }
+ {
+ auto store = TRY_OR_FAIL(SessionStore::create(*database, SessionLaunchPolicy::PinnedOnly));
+ EXPECT(store->follows_restart());
+ }
+
+ auto store = TRY_OR_FAIL(SessionStore::create(*database, SessionLaunchPolicy::PinnedOnly));
+ EXPECT(!store->follows_restart());
+}
+
TEST_CASE(pinned_only_restores_the_last_windows_pins)
{
auto database = create_session_database();
diff --git a/UI/Qt/Application.cpp b/UI/Qt/Application.cpp
index 1228e396e19..9f930811ac3 100644
--- a/UI/Qt/Application.cpp
+++ b/UI/Qt/Application.cpp
@@ -10,6 +10,7 @@
#include <LibCore/BrowserVersion.h>
#include <LibCore/Environment.h>
#include <LibCore/EventLoop.h>
+#include <LibCore/FileWatcher.h>
#include <LibCore/GeolocationProvider.h>
#include <LibCore/Process.h>
#include <LibCore/Socket.h>
@@ -537,6 +538,13 @@ public:
});
m_debug_menu->addSeparator();
m_debug_menu->addAction(simulate_update_action);
+#if defined(AK_OS_LINUX)
+ auto* simulate_replaced_installation_action = make_action("Simulate Replaced Installation");
+ QObject::connect(simulate_replaced_installation_action, &QAction::triggered, this, [] {
+ Application::the().offer_restart_after_update();
+ });
+ m_debug_menu->addAction(simulate_replaced_installation_action);
+#endif
}
#if defined(AK_OS_MACOS)
@@ -707,6 +715,11 @@ ErrorOr<NonnullOwnPtr<Application>> Application::create(Main::Arguments const& a
{
auto application = adopt_own(*new Application);
application->m_command_line = MUST(String::join(' ', arguments.strings));
+ if (auto executable = Core::System::current_executable_path(); !executable.is_error()) {
+ application->m_restart_command.executable = executable.release_value();
+ for (auto argument : arguments.strings.slice(1))
+ application->m_restart_command.arguments.append(argument);
+ }
#ifdef LADYBIRD_HUB_IN_OWN_PROCESS
WebView::platform_init();
@@ -884,6 +897,7 @@ ErrorOr<void> Application::connect_to_hub(Main::Arguments const& arguments)
m_exit_status_if_done = TRY(process.wait_for_termination());
return {};
}
+ m_restart_command.hub = move(process);
auto state = initial_state.release_value();
m_hub_connection->did_initialize();
@@ -907,6 +921,7 @@ ErrorOr<void> Application::connect_to_hub(Main::Arguments const& arguments)
m_browser_options.devtools_port = state.devtools_port;
if (state.devtools_enabled)
m_devtools_port = state.devtools_port;
+ m_profile_is_temporary = state.profile_is_temporary;
# if defined(AK_OS_MACOS)
set_profile_application_icon(state.profile_identifier, state.profile_identity, state.profile_is_temporary);
# endif
@@ -1031,7 +1046,7 @@ Application::~Application()
// process at once, so it never records a clean exit.
if (m_session_store) {
m_session_store->flush_dirty_state();
- m_session_store->mark_clean_exit();
+ m_session_store->mark_clean_exit(m_restart != Restart::None ? SessionStore::RestartAfterExit::Yes : SessionStore::RestartAfterExit::No);
}
// NB: The views go along with the windows that showed them, and their timers need the QApplication.
@@ -1040,6 +1055,11 @@ Application::~Application()
m_hub->destroy_all_views();
#endif
m_application = nullptr;
+
+ // Messages that arrived while quitting hold on to the connection until an event loop handles them, which none
+ // does anymore. Closing it lets the Hub end now, which a restart waits for.
+ if (m_hub_connection)
+ m_hub_connection->transport().close();
m_hub_connection = nullptr;
#ifndef LADYBIRD_HUB_IN_OWN_PROCESS
m_connection_from_ui = nullptr;
@@ -1111,6 +1131,7 @@ void Application::create_platform_actions()
auto& hub = WebView::Application::the();
m_settings = make<WebView::Settings>(WebView::Settings::create_from_json(WebView::Application::settings().serialize_json()));
+ m_profile_is_temporary = WebView::Application::profile().is_temporary();
create_session_store(WebView::Application::profile().paths().data, hub.persists_sessions());
create_history_store(WebView::Application::profile().paths().data, WebView::Application::browser_options().disable_sql_database == WebView::DisableSQLDatabase::No);
m_bookmark_store = make<BookmarkStore>(BookmarkStore::create(LexicalPath::join(WebView::Application::profile().paths().config, "Bookmarks.json"sv).string(), *m_favicon_store));
@@ -1135,6 +1156,11 @@ void Application::create_platform_actions()
};
#if defined(AK_OS_MACOS)
m_software_updater = SoftwareUpdater::create();
+ m_software_updater->on_will_relaunch = [this] {
+ m_restart = Restart::ByUpdater;
+ };
+#elif defined(AK_OS_LINUX)
+ watch_for_replaced_installation();
#endif
m_web_ui_pages = make<WebUIPages>();
m_bookmarks = make<Bookmarks>(*m_bookmark_store);
@@ -1955,6 +1981,10 @@ void Application::finish_quit()
void Application::cancel_quit()
{
m_quit_in_progress = false;
+ // Once Sparkle has installed an update, it relaunches Ladybird whenever Ladybird next quits. A canceled quit only
+ // calls off a restart of Ladybird's own.
+ if (m_restart == Restart::ByLadybird)
+ m_restart = Restart::None;
m_windows_awaiting_quit_preflight.clear();
// The windows whose pages already agreed go back to needing their own close check.
@@ -2329,6 +2359,13 @@ void Application::display_update_check_result(WebView::UpdateCheckResult::Kind k
if (!version.has_value())
return;
+ // Once the system has installed a newer Ladybird in place of this one, restarting is what updates it.
+ if (m_installation_replaced) {
+ if (trigger != WebView::UpdateCheckTrigger::Automatic)
+ offer_restart_after_update();
+ return;
+ }
+
// A later automatic check finds the update again, but one that the user asked for answers now, in a new window if
// no window is open. On macOS, the menu bar outlives the last window.
auto* window = active_window_if_any();
@@ -2372,6 +2409,86 @@ void Application::display_update_check_result(WebView::UpdateCheckResult::Kind k
window->show_page_card(BrowserWindow::PageCardSlot::Update, qformatted("Ladybird {} is available", *version), text, move(buttons));
}
+#if defined(AK_OS_LINUX)
+// The system replaces the files of a package that it updates while Ladybird runs from the ones that it started with. The
+// processes that Ladybird starts from then on would be of the new version, so the user is asked to restart it.
+void Application::watch_for_replaced_installation()
+{
+ if (!first_is_one_of(WebView::describe_current_system().install_method, WebView::InstallMethod::DEB, WebView::InstallMethod::RPM))
+ return;
+ // /proc/self/exe stays the file that this process runs, even once another one took its place at its path.
+ auto running = Core::System::stat("/proc/self/exe"sv);
+ auto watcher = Core::FileWatcher::create();
+ if (running.is_error() || watcher.is_error())
+ return;
+
+ auto notice_replacement = [this, device = running.value().st_dev, inode = running.value().st_ino] {
+ auto executable = Core::System::stat(m_restart_command.executable);
+ if (m_installation_replaced || executable.is_error() || (executable.value().st_dev == device && executable.value().st_ino == inode))
+ return;
+ m_installation_replaced = true;
+ offer_restart_after_update();
+ };
+
+ // A package manager writes the new executable under another name, and renames it over the old one. That takes a
+ // link away from the file that this process started from, which changes its metadata.
+ m_installation_watcher = watcher.release_value();
+ m_installation_watcher->on_change = [notice_replacement](auto const&) { notice_replacement(); };
+ if (auto result = m_installation_watcher->add_watch(m_restart_command.executable, Core::FileWatcherEvent::Type::MetadataModified); result.is_error()) {
+ m_installation_watcher = nullptr;
+ return;
+ }
+
+ // An update that finished before the watch began is offered once Ladybird has opened its windows.
+ Core::deferred_invoke(move(notice_replacement));
+}
+
+#endif
+
+void Application::offer_restart_after_update()
+{
+ // Without the path of its executable, Ladybird could quit but not start again.
+ auto* window = active_window_if_any();
+ if (!window || m_restart_command.executable.is_empty())
+ return;
+
+ Vector<PageCard::Button> buttons;
+ buttons.append({ "Not now", PageCard::ButtonRole::Secondary, {} });
+ buttons.append({ "Restart", PageCard::ButtonRole::Primary, [] { Application::the().restart(); } });
+ // A temporary profile is gone once Ladybird quits, and its windows and tabs with it. A session that could not be
+ // saved, as when its database would not open, is gone as well.
+ auto reopens = !m_profile_is_temporary && m_session_store && m_session_store->is_persistent();
+ auto text = reopens ? "Restart Ladybird to use the new version. Your windows and tabs will reopen, except private ones."_string : "Restart Ladybird to use the new version."_string;
+ window->show_page_card(BrowserWindow::PageCardSlot::Update, "Ladybird was updated", qstring_from_ak_string(text), move(buttons));
+}
+
+void Application::restart()
+{
+ m_restart = Restart::ByLadybird;
+ quit();
+}
+
+Optional<Application::RestartCommand> Application::take_restart_command()
+{
+ if (m_restart == Restart::None || (m_restart == Restart::ByLadybird && m_restart_command.executable.is_empty()))
+ return {};
+ auto command = move(m_restart_command);
+ command.relaunched_by_updater = m_restart == Restart::ByUpdater;
+ return command;
+}
+
+// A restarted browser must start only once the Hub of this one is gone, as it would otherwise hand itself over to that
+// Hub. The Hub ends once the Application has closed the connection to it. An updater relaunches Ladybird by itself once
+// this process has ended, so this process ends only after the Hub has.
+ErrorOr<void> Application::RestartCommand::run()
+{
+ if (hub.has_value())
+ TRY(hub->wait_for_termination());
+ if (!relaunched_by_updater)
+ TRY(Core::Process::spawn({ .executable = executable, .arguments = arguments }));
+ return {};
+}
+
void Application::open_file(String const& path) const
{
QDesktopServices::openUrl(QUrl::fromLocalFile(qstring_from_ak_string(path)));
diff --git a/UI/Qt/Application.h b/UI/Qt/Application.h
index a9190a6b848..c0d47010172 100644
--- a/UI/Qt/Application.h
+++ b/UI/Qt/Application.h
@@ -11,7 +11,9 @@
#include <AK/Platform.h>
#include <Hub/Application.h>
#include <Hub/ConnectionFromUI.h>
+#include <LibCore/Forward.h>
#include <LibCore/Platform/ProcessStatistics.h>
+#include <LibCore/Process.h>
#include <LibURL/URL.h>
#include <LibWebCommon/Page/PageId.h>
#include <LibWebView/Application.h>
@@ -145,6 +147,17 @@ public:
// the downloads and quits; if a page refuses or the downloads are kept, the quit is canceled and no window closes.
void quit();
bool is_quit_in_progress() const { return m_quit_in_progress; }
+ struct RestartCommand {
+ ByteString executable;
+ Vector<ByteString> arguments;
+ Optional<Core::Process> hub;
+ bool relaunched_by_updater { false };
+
+ ErrorOr<void> run();
+ };
+ void offer_restart_after_update();
+ void restart();
+ Optional<RestartCommand> take_restart_command();
bool is_finishing_quit() const { return m_quit_is_finishing; }
bool confirm_stop_active_downloads(QWidget* parent = nullptr);
@@ -365,6 +378,20 @@ private:
bool m_quit_in_progress { false };
bool m_quit_is_finishing { false };
Vector<QPointer<BrowserWindow>> m_windows_awaiting_quit_preflight;
+
+#if defined(AK_OS_LINUX)
+ void watch_for_replaced_installation();
+ RefPtr<Core::FileWatcher> m_installation_watcher;
+#endif
+ enum class Restart : u8 {
+ None,
+ ByLadybird,
+ ByUpdater,
+ };
+ Restart m_restart { Restart::None };
+ bool m_installation_replaced { false };
+ bool m_profile_is_temporary { false };
+ RestartCommand m_restart_command;
};
}
diff --git a/UI/Qt/SessionStore.cpp b/UI/Qt/SessionStore.cpp
index c07eb7f864a..0d1f45c4145 100644
--- a/UI/Qt/SessionStore.cpp
+++ b/UI/Qt/SessionStore.cpp
@@ -27,6 +27,7 @@ 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;
static constexpr u32 SESSIONS_SCHEMA_UPGRADE_INSECURE_REQUESTS_VERSION = 9u;
+static constexpr u32 SESSIONS_SCHEMA_RESTART_VERSION = 10u;
// 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.
@@ -291,6 +292,12 @@ ErrorOr<Database::MigrationOutcome> SessionStore::PersistedStorage::migrate_sche
ON SessionUpgradeInsecureNavigations(container_id, tuple_ordinal);
)#"sv,
},
+ {
+ .version = SESSIONS_SCHEMA_RESTART_VERSION,
+ .sql = R"#(
+ ALTER TABLE SessionLifecycle ADD COLUMN restart INTEGER NOT NULL DEFAULT 0;
+ )#"sv,
+ },
});
return database.migrate("Sessions"sv, migrations, mode);
@@ -335,8 +342,8 @@ ErrorOr<SessionStore::PersistedStorage> SessionStore::PersistedStorage::create(D
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));
statements.delete_empty_open_sessions = TRY(database.prepare_statement("DELETE FROM Sessions WHERE kind = :open_window_kind AND NOT EXISTS (SELECT 1 FROM SessionTabs WHERE session_id = Sessions.id);"sv));
- statements.select_lifecycle = TRY(database.prepare_statement("SELECT clean_exit, consecutive_unclean_exits FROM SessionLifecycle WHERE id = 1;"sv));
- statements.write_lifecycle = TRY(database.prepare_statement("INSERT INTO SessionLifecycle (id, clean_exit, consecutive_unclean_exits) VALUES (1, :clean_exit, :consecutive_unclean_exits) ON CONFLICT (id) DO UPDATE SET clean_exit = excluded.clean_exit, consecutive_unclean_exits = excluded.consecutive_unclean_exits;"sv));
+ statements.select_lifecycle = TRY(database.prepare_statement("SELECT clean_exit, consecutive_unclean_exits, restart FROM SessionLifecycle WHERE id = 1;"sv));
+ statements.write_lifecycle = TRY(database.prepare_statement("INSERT INTO SessionLifecycle (id, clean_exit, consecutive_unclean_exits, restart) VALUES (1, :clean_exit, :consecutive_unclean_exits, :restart) ON CONFLICT (id) DO UPDATE SET clean_exit = excluded.clean_exit, consecutive_unclean_exits = excluded.consecutive_unclean_exits, restart = excluded.restart;"sv));
statements.snapshot_statements = TRY(prepare_session_history_snapshot_statements(database));
return PersistedStorage { database, move(statements) };
@@ -964,8 +971,12 @@ ErrorOr<SessionStore::RecoveryResult> SessionStore::PersistedStorage::recover_op
{
RecoveryResult result;
TRY(database->transaction([&]() -> ErrorOr<void> {
- result.consecutive_unclean_exits = TRY(record_run_start());
+ auto run_start = TRY(record_run_start());
+ result.consecutive_unclean_exits = run_start.consecutive_unclean_exits;
+ result.follows_restart = run_start.follows_restart;
auto policy = result.consecutive_unclean_exits >= UNCLEAN_EXITS_THAT_STOP_LAUNCH_RESTORE ? SessionLaunchPolicy::None : write.policy;
+ if (result.follows_restart)
+ policy = SessionLaunchPolicy::Everything;
// Only the windows that the last run left open count as left open. Those of the runs before it were already
// offered back, so they are ordinary closed windows now.
@@ -1093,20 +1104,22 @@ ErrorOr<void> SessionStore::PersistedStorage::delete_session_rows(SessionWindowI
});
}
-ErrorOr<void> SessionStore::PersistedStorage::write_lifecycle(bool clean_exit, u32 consecutive_unclean_exits)
+ErrorOr<void> SessionStore::PersistedStorage::write_lifecycle(bool clean_exit, u32 consecutive_unclean_exits, bool restart)
{
return database->try_execute_bound_statement(statements.write_lifecycle, [&](auto& bind) -> ErrorOr<void> {
TRY(bind("clean_exit"sv, i64 { clean_exit ? 1 : 0 }));
TRY(bind("consecutive_unclean_exits"sv, i64 { consecutive_unclean_exits }));
+ TRY(bind("restart"sv, i64 { restart ? 1 : 0 }));
return {};
});
}
// Runs inside the recovery transaction, so it opens none of its own.
-ErrorOr<u32> SessionStore::PersistedStorage::record_run_start()
+ErrorOr<SessionStore::PersistedStorage::RunStart> SessionStore::PersistedStorage::record_run_start()
{
// A first run has no row yet, and counts as following a clean exit.
bool last_run_exited_cleanly = true;
+ bool last_run_restarts = false;
u32 consecutive_unclean_exits = 0;
TRY(database->try_execute_bound_statement(
statements.select_lifecycle,
@@ -1117,9 +1130,11 @@ ErrorOr<u32> SessionStore::PersistedStorage::record_run_start()
// transient store, since nothing else ever rewrites the row.
auto clean_exit = row.read_integer<i64>("clean_exit"sv);
auto unclean_exits = row.read_integer<u32>("consecutive_unclean_exits"sv);
- if (clean_exit.is_error() || unclean_exits.is_error())
+ auto restart = row.read_integer<i64>("restart"sv);
+ if (clean_exit.is_error() || unclean_exits.is_error() || restart.is_error())
return {};
last_run_exited_cleanly = clean_exit.value() != 0;
+ last_run_restarts = restart.value() != 0;
consecutive_unclean_exits = unclean_exits.value();
return {};
}));
@@ -1129,9 +1144,10 @@ ErrorOr<u32> SessionStore::PersistedStorage::record_run_start()
else if (consecutive_unclean_exits < NumericLimits<u32>::max())
++consecutive_unclean_exits;
- // This run counts as unclean until mark_clean_exit() says otherwise.
+ // This run counts as unclean until mark_clean_exit() says otherwise. A run that ended to restart the browser brings
+ // back every window that it left open, and only the run right after it does.
TRY(write_lifecycle(false, consecutive_unclean_exits));
- return consecutive_unclean_exits;
+ return RunStart { .consecutive_unclean_exits = consecutive_unclean_exits, .follows_restart = last_run_exited_cleanly && last_run_restarts };
}
ErrorOr<void> SessionStore::PersistedStorage::prune_closed_units(UnitKind kind, u32 max_units)
@@ -1527,6 +1543,7 @@ ErrorOr<void> SessionStore::run_startup_recovery(UnixDateTime recovered_at, Sess
},
m_session_id_allocator, m_close_sequence_allocator));
m_consecutive_unclean_exits = recovery.consecutive_unclean_exits;
+ m_follows_restart = recovery.follows_restart;
for (auto& window : recovery.windows) {
m_transient_storage.open_window(window.id);
@@ -2217,12 +2234,12 @@ void SessionStore::application_quit_aborted()
m_quitting = false;
}
-void SessionStore::mark_clean_exit()
+void SessionStore::mark_clean_exit(RestartAfterExit restart_after_exit)
{
m_consecutive_unclean_exits = 0;
if (!m_persisted_storage.has_value())
return;
- if (auto result = m_persisted_storage->write_lifecycle(true, 0); result.is_error())
+ if (auto result = m_persisted_storage->write_lifecycle(true, 0, restart_after_exit == RestartAfterExit::Yes); result.is_error())
dbgln("Unable to record a clean exit in the session store: {}", result.error());
}
diff --git a/UI/Qt/SessionStore.h b/UI/Qt/SessionStore.h
index 0c8fb71d242..1e4823e2360 100644
--- a/UI/Qt/SessionStore.h
+++ b/UI/Qt/SessionStore.h
@@ -177,9 +177,14 @@ public:
// How many runs in a row, ending with the one before this, ended without mark_clean_exit().
u32 consecutive_unclean_exits() const { return m_consecutive_unclean_exits; }
+ bool follows_restart() const { return m_follows_restart; }
+ enum class RestartAfterExit : u8 {
+ No,
+ Yes,
+ };
// Records that this run is ending normally. Only a normal teardown calls it, so a crash never records one.
- void mark_clean_exit();
+ void mark_clean_exit(RestartAfterExit = RestartAfterExit::No);
bool is_persistent() const { return m_persisted_storage.has_value(); }
@@ -407,6 +412,7 @@ private:
struct RecoveryResult {
u32 consecutive_unclean_exits { 0 };
+ bool follows_restart { false };
Vector<RecoveredWindow> windows;
};
@@ -428,7 +434,7 @@ private:
ErrorOr<void> clear_startup_recovery_origin();
ErrorOr<void> delete_session_rows(SessionWindowId);
ErrorOr<void> prune_closed_units(UnitKind, u32 max_units);
- ErrorOr<void> write_lifecycle(bool clean_exit, u32 consecutive_unclean_exits);
+ ErrorOr<void> write_lifecycle(bool clean_exit, u32 consecutive_unclean_exits, bool restart = false);
ErrorOr<IdAllocators> create_id_allocators();
ErrorOr<WebView::SessionHistorySnapshot> load_tab_snapshot(SessionTabId, size_t current_used_step_index);
@@ -439,7 +445,11 @@ private:
Statements statements;
private:
- ErrorOr<u32> record_run_start();
+ struct RunStart {
+ u32 consecutive_unclean_exits { 0 };
+ bool follows_restart { false };
+ };
+ ErrorOr<RunStart> record_run_start();
ErrorOr<void> apply_tab_row_write(TabWrite const&);
ErrorOr<void> apply_window_metadata(WindowMetadataWrite const&);
ErrorOr<void> insert_closed_unit_row(ClosedUnitWrite const&);
@@ -557,6 +567,7 @@ private:
Vector<WindowMetadataWrite> m_retired_window_metadata;
bool m_quitting { false };
u32 m_consecutive_unclean_exits { 0 };
+ bool m_follows_restart { false };
Vector<RestoredSessionWindow> m_launch_plan;
IdAllocator m_session_id_allocator;
diff --git a/UI/Qt/SoftwareUpdaterMac.h b/UI/Qt/SoftwareUpdaterMac.h
index b255e54b7cb..1d83ab8809c 100644
--- a/UI/Qt/SoftwareUpdaterMac.h
+++ b/UI/Qt/SoftwareUpdaterMac.h
@@ -6,6 +6,7 @@
#pragma once
+#include <AK/Function.h>
#include <AK/Noncopyable.h>
#include <AK/NonnullOwnPtr.h>
@@ -30,6 +31,8 @@ public:
void install_update();
void install_latest_version();
+ Function<void()> on_will_relaunch;
+
private:
explicit SoftwareUpdater(NonnullOwnPtr<Detail::SparkleUpdater>);
diff --git a/UI/Qt/SoftwareUpdaterMac.mm b/UI/Qt/SoftwareUpdaterMac.mm
index c15f0f06112..037f928c8fe 100644
--- a/UI/Qt/SoftwareUpdaterMac.mm
+++ b/UI/Qt/SoftwareUpdaterMac.mm
@@ -16,6 +16,7 @@
@interface LadybirdUpdaterDelegate : NSObject <SPUUpdaterDelegate, SPUStandardUserDriverDelegate, SUVersionComparison, SUVersionDisplay>
@property (atomic) BOOL offersLatestVersion;
+@property (nonatomic, copy) void (^willRelaunch)(void);
@end
@@ -53,6 +54,12 @@
self.offersLatestVersion = NO;
}
+- (void)updaterWillRelaunchApplication:(SPUUpdater*)updater
+{
+ if (self.willRelaunch)
+ self.willRelaunch();
+}
+
@end
// Sparkle only runs once the user chose to install an update in Ladybird's own notice, so it installs the update and
@@ -202,6 +209,10 @@ NonnullOwnPtr<SoftwareUpdater> SoftwareUpdater::create()
SoftwareUpdater::SoftwareUpdater(NonnullOwnPtr<Detail::SparkleUpdater> sparkle)
: m_sparkle(move(sparkle))
{
+ m_sparkle->delegate.willRelaunch = ^{
+ if (on_will_relaunch)
+ on_will_relaunch();
+ };
}
SoftwareUpdater::~SoftwareUpdater() = default;
diff --git a/UI/Qt/main.cpp b/UI/Qt/main.cpp
index 06e45c2d4f2..96e7c4ea320 100644
--- a/UI/Qt/main.cpp
+++ b/UI/Qt/main.cpp
@@ -61,7 +61,7 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)
Ladybird::install_qt_geolocation_provider();
#endif
- auto app = TRY(Ladybird::Application::create(arguments));
+ OwnPtr<Ladybird::Application> app = TRY(Ladybird::Application::create(arguments));
if (auto exit_status = app->exit_status_if_done(); exit_status.has_value())
return *exit_status;
@@ -112,9 +112,11 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)
auto configuration = app->configuration_for_new_window();
if (auto* restored_window = app->restore_previous_session(configuration)) {
// A whole restored session replaces the usual startup tab, so only the URLs the user passed open with it.
- // With only pinned tabs restored, the usual startup tabs open after them.
+ // With only pinned tabs restored, the usual startup tabs open after them. A restart passes on the URLs
+ // that the browser was started with, which are among the restored tabs already.
+ auto follows_restart = Ladybird::Application::session_store(WebView::IsPrivate::No).follows_restart();
auto restored_everything = app->launch_restore_policy() == Ladybird::SessionLaunchPolicy::Everything;
- if (!restored_everything || !browser_options.raw_urls.is_empty())
+ if (!follows_restart && (!restored_everything || !browser_options.raw_urls.is_empty()))
app->open_startup_tabs(*restored_window, browser_options.urls);
app->offer_to_restore_unexpectedly_closed_tabs(*restored_window);
} else {
@@ -128,5 +130,10 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)
if (auto* hub = Ladybird::HubConnection::the_if_connected())
hub->async_ui_did_start();
- return app->execute();
+ auto exit_status = TRY(app->execute());
+ auto restart = app->take_restart_command();
+ app = nullptr;
+ if (restart.has_value())
+ TRY(restart->run());
+ return exit_status;
}