Truly independent web browser
LibWebView+Hub+UI/Qt+WebContent: Let the Hub discard a background tab
Andreas Kling7b6bab28e363
diff --git a/Libraries/LibWebView/CanonicalTraversable.h b/Libraries/LibWebView/CanonicalTraversable.hindex f2fb9db7794..b3710f43498 100644--- a/Libraries/LibWebView/CanonicalTraversable.h+++ b/Libraries/LibWebView/CanonicalTraversable.h@@ -99,6 +99,7 @@ public:CanonicalNavigable& insert(NonnullRefPtr<WebContentPage> reporting_page, CanonicalNavigable& parent, CanonicalDocument& container_document, Web::HTML::CrossProcessId frame_id, Web::HTML::HostedNavigableState, NonnullRefPtr<CanonicalSessionHistoryEntry> active_session_history_entry, NonnullRefPtr<CanonicalDocument>);void adopt_nested_history_for_created_child(CanonicalNavigable const& parent, CanonicalDocument const& container_document, Web::HTML::CrossProcessId child_navigable_id);Optional<CanonicalNavigable&> find(Web::HTML::CrossProcessId navigable_id);+ void save_session_history_entry_persisted_state(Badge<WebContentPage>, CanonicalNavigable& navigable, Web::HTML::SessionHistoryEntryPersistedState const& persisted_state) { update_session_history_entry_persisted_state(navigable, persisted_state); }Optional<CanonicalNavigable const&> find(Web::HTML::CrossProcessId navigable_id) const;void remove(CanonicalNavigable&);void remove_page(WebContentPage&);diff --git a/Libraries/LibWebView/ViewImplementation.cpp b/Libraries/LibWebView/ViewImplementation.cppindex 3969520f4c0..b7d2c97b159 100644--- a/Libraries/LibWebView/ViewImplementation.cpp+++ b/Libraries/LibWebView/ViewImplementation.cpp@@ -141,8 +141,10 @@ ViewImplementation::~ViewImplementation()// location in every view that shows the site, and this one is on its way out.all_views().remove(m_view_id);session().permission_manager->remove_view(view_id());- if (m_top_level_traversable)+ if (m_top_level_traversable) {m_top_level_traversable->clear_ongoing_navigation();+ update_state_of_discarded_tab();+ }cancel_all_native_geolocation_requests();if (!m_window_handle.is_empty() && !m_owner_view_id.has_value())@@ -414,13 +416,22 @@ void ViewImplementation::set_title(Utf16String title)m_title = move(title);Application::the().media_session_coordinator().set_fallback_title(view_id(), m_title.to_utf8());+ did_change_title_or_favicon();if (on_title_change)on_title_change(m_title);}+// NB: A page shows its title and favicon as it loads, which is no work it does in the background.+void ViewImplementation::did_change_title_or_favicon()+{+ if (m_top_level_traversable && !is_loading() && traversable().system_visibility_state() == Web::HTML::VisibilityState::Hidden)+ m_changed_title_or_favicon_while_hidden = true;+}+void ViewImplementation::set_favicon(Optional<Gfx::Bitmap const&> favicon){+ did_change_title_or_favicon();if (on_favicon_change)on_favicon_change(favicon);}@@ -580,6 +591,123 @@ void ViewImplementation::set_system_visibility_state(Web::HTML::VisibilityStatetraversable().set_system_visibility_state(visibility_state);Application::the().update_compositor_context_visibility(page().compositor_context_id(), visibility_state);report_permission_presence();++ if (visibility_state == Web::HTML::VisibilityState::Visible) {+ m_hidden_since.clear();+ m_discard_requested = false;+ } else {+ m_hidden_since = MonotonicTime::now();+ m_changed_title_or_favicon_while_hidden = false;+ }+}++// The user would notice that a tab stopped playing sound, so a tab that just did is likely to play more.+static constexpr auto time_silent_before_discarding = AK::Duration::from_seconds(60);++bool ViewImplementation::may_be_discarded(DiscardReason reason, AK::Duration minimum_time_hidden, MonotonicTime now) const+{+ if (!supports_discarding() || m_discard_requested || !m_top_level_traversable)+ return false;+ if (traversable().system_visibility_state() != Web::HTML::VisibilityState::Hidden || !m_hidden_since.has_value() || now - *m_hidden_since < minimum_time_hidden)+ return false;++ // The user keeps a pinned tab at hand, and sees a window's current tab whenever they look at the window.+ if (m_pinned || m_current_tab_of_window)+ return false;++ // NB: A tab that hasn't loaded yet has nothing to restore, and a crashed tab shows the user what happened to it.+ if (is_loading() || m_crash_state.has_value())+ return false;++ // A tab that the user hears, or that listens or follows them, would stop doing it.+ if (is_playing_audio() || is_capturing_audio() || m_tab_indicators.is_active(TabIndicator::UsingLocation))+ return false;+ if (m_stopped_playing_audio_time.has_value() && now - *m_stopped_playing_audio_time < time_silent_before_discarding)+ return false;++ // A view that this one owns, such as a Picture-in-Picture window, shows the user what the tab does.+ auto owns_a_view = false;+ for_each_view([&](ViewImplementation& view) {+ if (view.owner_view_id() != m_view_id)+ return IterationDecision::Continue;+ owns_a_view = true;+ return IterationDecision::Break;+ });+ if (owns_a_view || m_devtools_connected)+ return false;++ // NB: A page asks to be checked before it's unloaded when it holds something the user would lose, such as what they+ // typed into a form.+ if (needs_beforeunload_check())+ return false;++ if (reason == DiscardReason::Inactivity) {+ // A tab that changes what it shows in the tab strip, such as the count of unread messages in its title, does+ // work for the user in the background. So does one that may show them notifications.+ if (m_changed_title_or_favicon_while_hidden)+ return false;+ if (auto origin = permission_origin(); !origin.is_opaque()) {+ if (session().permission_manager->effective_state(Web::Permissions::PermissionName::Notifications, origin) == Web::Permissions::EffectiveState::Granted)+ return false;+ } else {+ // NB: A file: page's grant goes away with the page, so it would not even come back with the tab.+ auto may_show_notifications = false;+ traversable().for_each_hosting_page([&](WebContentPage& page) {+ may_show_notifications |= page.hosts_a_local_file_document_that_may_use(Web::Permissions::PermissionName::Notifications);+ });+ if (may_show_notifications)+ return false;+ }+ }+ return true;+}++// The user should find the tab as they left it, so the processes hosting it first save where the user was in each of+// its documents to its session history. A process that doesn't answer in time leaves its documents as they were saved.+static constexpr auto time_to_save_session_history_entry_states = AK::Duration::from_seconds(1);++void ViewImplementation::request_discard()+{+ m_discard_requested = true;++ m_pages_saving_session_history_entry_states.clear();+ traversable().for_each_hosting_page([&](WebContentPage& page) {+ auto is_saving = any_of(m_pages_saving_session_history_entry_states, [&](auto const& saving_page) { return saving_page.ptr() == &page; });+ if (!page.is_open() || is_saving)+ return;+ m_pages_saving_session_history_entry_states.append(page);+ page.async_save_session_history_entry_states();+ });+ if (m_pages_saving_session_history_entry_states.is_empty()) {+ finish_discard_request();+ return;+ }++ if (!m_save_session_history_entry_states_timer) {+ m_save_session_history_entry_states_timer = Core::Timer::create_single_shot(time_to_save_session_history_entry_states, [this] {+ finish_discard_request();+ });+ }+ m_save_session_history_entry_states_timer->restart();+}++void ViewImplementation::did_save_session_history_entry_states(Badge<WebContentPage>, WebContentPage& page)+{+ if (!m_pages_saving_session_history_entry_states.remove_first_matching([&](auto const& saving_page) { return saving_page.ptr() == &page; }))+ return;+ if (m_pages_saving_session_history_entry_states.is_empty())+ finish_discard_request();+}++void ViewImplementation::finish_discard_request()+{+ if (m_save_session_history_entry_states_timer)+ m_save_session_history_entry_states_timer->stop();+ m_pages_saving_session_history_entry_states.clear();++ // NB: The user may have come back to the tab in the meantime.+ if (m_discard_requested && traversable().system_visibility_state() == Web::HTML::VisibilityState::Hidden)+ did_request_discard();}// One-time grants last only while some view shows their site, so each view tells the permission manager what it shows.@@ -591,6 +719,15 @@ void ViewImplementation::report_permission_presence()session().permission_manager->set_view_presence(view_id(), permission_origin(), visible);}+// NB: The Hub may have asked the UI to discard the tab before the UI learned of the pin, which the UI then declined. The+// tab is asked about again once it is unpinned.+void ViewImplementation::set_pinned(bool pinned)+{+ m_pinned = pinned;+ if (pinned)+ m_discard_requested = false;+}+URL::Origin ViewImplementation::permission_origin() const{if (m_top_level_traversable) {@@ -3022,7 +3159,12 @@ void ViewImplementation::insert_clipboard_item(Web::Clipboard::SystemClipboardItvoid ViewImplementation::toggle_page_mute_state(){- m_mute_state = Web::HTML::invert_mute_state(m_mute_state);+ set_page_mute_state(Web::HTML::invert_mute_state(m_mute_state));+}++void ViewImplementation::set_page_mute_state(Web::HTML::MuteState mute_state)+{+ m_mute_state = mute_state;traversable().for_each_hosting_page([&](WebContentPage& page) {page.client().set_audio_playback_mute_state(page.id(), m_mute_state);});@@ -3035,7 +3177,10 @@ void ViewImplementation::update_audibility()if (page.audibility() == Audio::Audibility::Audible)audible = true;});- m_tab_indicators.set_active(TabIndicator::PlayingAudio, audible, MonotonicTime::now());+ auto now = MonotonicTime::now();+ if (!audible && is_playing_audio())+ m_stopped_playing_audio_time = now;+ m_tab_indicators.set_active(TabIndicator::PlayingAudio, audible, now);}void ViewImplementation::update_microphone_capture()@@ -4255,6 +4400,57 @@ ErrorOr<void> ViewImplementation::restore_session_history_from_snapshot(SessionHreturn {};}+namespace {++struct DiscardedTabState {+ // NB: sessionStorage lasts as long as the tab, so a page must find it again when the tab is loaded again.+ NonnullOwnPtr<StorageJar> session_storage;+ Web::HTML::MuteState mute_state { Web::HTML::MuteState::Unmuted };+};++}++static HashMap<u64, DiscardedTabState>& discarded_tab_states()+{+ static NeverDestroyed<HashMap<u64, DiscardedTabState>> states;+ return *states;+}++u64 ViewImplementation::keep_state_for_discarding()+{+ static u64 s_next_discarded_tab_state_id = 1;+ auto discarded_tab_state_id = s_next_discarded_tab_state_id++;++ auto session_storage = StorageJar::create();+ session_storage->clone_from(traversable().session_storage());+ discarded_tab_states().set(discarded_tab_state_id, { .session_storage = move(session_storage), .mute_state = m_mute_state });+ m_discarded_tab_state_id = discarded_tab_state_id;+ return discarded_tab_state_id;+}++// NB: The pages of the tab may still write to its sessionStorage until the view closes, which the state must keep too.+void ViewImplementation::update_state_of_discarded_tab()+{+ if (!m_discarded_tab_state_id.has_value())+ return;+ if (auto state = discarded_tab_states().get(*m_discarded_tab_state_id); state.has_value())+ state.value().session_storage->clone_from(traversable().session_storage());+}++void ViewImplementation::restore_state_of_discarded_tab(u64 discarded_tab_state_id)+{+ auto state = discarded_tab_states().take(discarded_tab_state_id);+ if (!state.has_value())+ return;+ traversable().session_storage().clone_from(*state->session_storage);+ set_page_mute_state(state->mute_state);+}++void ViewImplementation::forget_state_of_discarded_tab(u64 discarded_tab_state_id)+{+ discarded_tab_states().remove(discarded_tab_state_id);+}+bool ViewImplementation::capture_session_history_snapshot_for_testing(Badge<WebContentPage>){m_captured_session_history_snapshot_for_testing = session_history_snapshot();diff --git a/Libraries/LibWebView/ViewImplementation.h b/Libraries/LibWebView/ViewImplementation.hindex 55f7571706c..c314fdbf747 100644--- a/Libraries/LibWebView/ViewImplementation.h+++ b/Libraries/LibWebView/ViewImplementation.h@@ -228,6 +228,24 @@ public:void set_window_position(Gfx::IntPoint);void set_window_size(Gfx::IntSize);void set_system_visibility_state(Web::HTML::VisibilityState);++ // A tab that the user doesn't see may be discarded: its pages close, so that the processes hosting them can let go+ // of their memory, and the tab stays in the tab strip to restore its current session history entry once the user+ // comes back to it.+ enum class DiscardReason : u8 {+ // The system is about to run out of memory.+ MemoryPressure,+ // The tab was hidden for long, without doing anything the user could notice.+ Inactivity,+ };+ bool may_be_discarded(DiscardReason, AK::Duration minimum_time_hidden, MonotonicTime now) const;+ void set_pinned(bool pinned);+ void set_current_tab_of_window(bool current_tab_of_window) { m_current_tab_of_window = current_tab_of_window; }+ // When the user last stopped seeing the view, if they don't see it now.+ Optional<MonotonicTime> hidden_since() const { return m_hidden_since; }+ void request_discard();+ void did_save_session_history_entry_states(Badge<WebContentPage>, WebContentPage&);+// Whether the view shows its frames from CPU memory for now, so that the Compositor shares them there rather than// in GPU memory that the view would have to read back for every frame.void set_presents_from_cpu_memory(bool);@@ -288,6 +306,13 @@ public:[[nodiscard]] SessionHistorySnapshot session_history_snapshot() const;[[nodiscard]] ErrorOr<void> restore_session_history_from_snapshot(SessionHistorySnapshot);+ // The UI keeps the session history of a discarded tab. The Hub keeps what else the tab should have once it is loaded+ // again, until the UI restores or forgets it.+ u64 keep_state_for_discarding();+ void restore_state_of_discarded_tab(u64 discarded_tab_state_id);+ static void forget_state_of_discarded_tab(u64 discarded_tab_state_id);+ void update_state_of_discarded_tab();+// A view whose windows and tabs the application keeps tells it of each change to its session history.void set_reports_session_history(bool);@@ -530,6 +555,7 @@ public:Web::HTML::MuteState page_mute_state() const { return m_mute_state; }void toggle_page_mute_state();+ void set_page_mute_state(Web::HTML::MuteState);// The tab plays audio while the AudioServer has recently heard any page of it.void update_audibility(Badge<WebContentPage>) { update_audibility(); }@@ -739,6 +765,10 @@ public:// Something the UI shows about this view may have changed, like whether it can undo or show its source.virtual void did_change_state() { }+ // Whether the UI can discard the view, and how it is asked to.+ virtual bool supports_discarding() const { return false; }+ virtual void did_request_discard() { }+virtual void did_change_session_history(SessionHistorySnapshot const&, URL::URL const&) { }// The application keeps browsing history: this view visited a page, or learned the title of one it visited.@@ -810,6 +840,8 @@ protected:void ignore_pending_permission_prompts();void set_title(Utf16String);void set_favicon(Optional<Gfx::Bitmap const&>);+ void did_change_title_or_favicon();+ void finish_discard_request();Optional<URL::URL const&> browser_ui_load_url() const;void update_displayed_url();void did_start_navigation();@@ -1283,6 +1315,21 @@ protected:bool m_devtools_connected { false };bool m_devtools_takes_console_messages { false };bool m_devtools_takes_console_errors { false };++ // NB: A view starts out hidden, until the UI shows it.+ Optional<MonotonicTime> m_hidden_since { MonotonicTime::now() };+ Optional<MonotonicTime> m_stopped_playing_audio_time;+ bool m_changed_title_or_favicon_while_hidden { false };+ bool m_pinned { false };+ // NB: The current tab of a minimized window is hidden, but the user sees it again as soon as they bring the window+ // back.+ bool m_current_tab_of_window { false };+ // The UI was asked to discard the view, so it isn't asked again until the user has seen it.+ bool m_discard_requested { false };+ Optional<u64> m_discarded_tab_state_id;+ // NB: These are kept alive, so that no other page can take the place of one that closes before it answers.+ Vector<NonnullRefPtr<WebContentPage>> m_pages_saving_session_history_entry_states;+ RefPtr<Core::Timer> m_save_session_history_entry_states_timer;};}diff --git a/Libraries/LibWebView/WebContentPage.cpp b/Libraries/LibWebView/WebContentPage.cppindex c5fff94d689..bbbbcf33873 100644--- a/Libraries/LibWebView/WebContentPage.cpp+++ b/Libraries/LibWebView/WebContentPage.cpp@@ -1438,6 +1438,25 @@ void WebContentPage::did_change_needs_beforeunload_check(bool needs_beforeunloadm_needs_beforeunload_check = needs_beforeunload_check;}+void WebContentPage::did_save_session_history_entry_state(Web::HTML::CrossProcessId navigable_id, Web::HTML::SessionHistoryEntryPersistedState persisted_state)+{+ if (!has_traversable())+ return;+ // NB: A page saves the state of the documents it hosts alone.+ auto navigable = hosted_navigable(navigable_id);+ if (!navigable.has_value() || !hosts_active_document_of(*navigable))+ return;+ traversable().save_session_history_entry_persisted_state({}, *navigable, persisted_state);+}++void WebContentPage::did_save_session_history_entry_states()+{+ if (!has_traversable())+ return;+ if (auto view = traversable().view(); view.has_value())+ view->did_save_session_history_entry_states({}, *this);+}+// https://html.spec.whatwg.org/multipage/interaction.html#transient-activation-durationstatic constexpr auto transient_activation_duration = AK::Duration::from_seconds(5);@@ -1769,6 +1788,11 @@ bool WebContentPage::document_may_use(Web::HTML::CrossProcessId document_id, Webreturn manager.effective_state(name, *top_level_origin) == Web::Permissions::EffectiveState::Granted;}+bool WebContentPage::hosts_a_local_file_document_that_may_use(Web::Permissions::PermissionName name) const+{+ return any_of(m_file_permission_grants, [&](auto const& grant) { return grant.name == name && document_may_use(grant.document_id, name); });+}+void WebContentPage::did_request_geolocation_position(u64 request_id, Web::HTML::CrossProcessId document_id){// The UI process hands out a position only to a document it knows the user let have one.diff --git a/Libraries/LibWebView/WebContentPage.h b/Libraries/LibWebView/WebContentPage.hindex 1faf0d71779..e8ef52dfe85 100644--- a/Libraries/LibWebView/WebContentPage.h+++ b/Libraries/LibWebView/WebContentPage.h@@ -129,6 +129,8 @@ public:RefPtr<CanonicalDocument> hosted_document_with_id(Web::HTML::CrossProcessId) const;bool hosts_a_document_with_top_level_origin(URL::Origin const&) const;bool document_may_use(Web::HTML::CrossProcessId, Web::Permissions::PermissionName) const;+ // Whether a hosted document of a file: page may use the permission, which it was granted for as long as it lives.+ bool hosts_a_local_file_document_that_may_use(Web::Permissions::PermissionName) const;Web::Permissions::PermissionSnapshot set_permission_for_testing(Web::HTML::CrossProcessId document_id, String const& name, String const& state);void set_next_permission_prompt_outcome_for_testing(String const& name, String const& outcome, bool held);@@ -265,6 +267,8 @@ private:void did_remove_blob_url_entries(Web::HTML::EnvironmentId environment_id, Vector<Utf16String> urls);Messages::WebContentClient::ConnectToStorageAreaResponse connect_to_storage_area(Web::StorageAPI::StorageEndpointType storage_endpoint, Web::HTML::EnvironmentId environment_id);virtual void did_change_needs_beforeunload_check(bool needs_beforeunload_check) override;+ virtual void did_save_session_history_entry_state(Web::HTML::CrossProcessId navigable_id, Web::HTML::SessionHistoryEntryPersistedState persisted_state) override;+ virtual void did_save_session_history_entry_states() override;virtual void did_consume_user_activation(Web::HTML::UserActivationConsumption consumption) override;virtual void did_notify_about_user_activation(Web::HTML::CrossProcessId document_id) override;virtual void webdriver_user_prompt_handling_complete(u64 request_id, Web::WebDriver::Response response) override;diff --git a/Services/Hub/ConnectionFromUI.cpp b/Services/Hub/ConnectionFromUI.cppindex 8f31ffc5f82..90f5807a70e 100644--- a/Services/Hub/ConnectionFromUI.cpp+++ b/Services/Hub/ConnectionFromUI.cpp@@ -806,6 +806,30 @@ Messages::HubServer::ViewRestoreSessionHistoryFromSnapshotResponse ConnectionFroreturn view && !view->restore_session_history_from_snapshot(move(snapshot)).is_error();}+Messages::HubServer::ViewKeepStateForDiscardingResponse ConnectionFromUI::view_keep_state_for_discarding(u64 view_id)+{+ auto* view = find_view(view_id);+ if (!view)+ return Optional<u64> {};+ return view->keep_state_for_discarding();+}++void ConnectionFromUI::view_restore_state_of_discarded_tab(u64 view_id, u64 discarded_tab_state_id)+{+ auto* view = find_view(view_id);+ if (!view) {+ WebView::ViewImplementation::forget_state_of_discarded_tab(discarded_tab_state_id);+ return;+ }+ view->restore_state_of_discarded_tab(discarded_tab_state_id);+ view->push_state_to_ui();+}++void ConnectionFromUI::forget_state_of_discarded_tab(u64 discarded_tab_state_id)+{+ WebView::ViewImplementation::forget_state_of_discarded_tab(discarded_tab_state_id);+}+Messages::HubServer::ViewHistoryStepAtDeltaResponse ConnectionFromUI::view_history_step_at_delta(u64 view_id, i32 delta){auto* view = find_view(view_id);@@ -982,6 +1006,18 @@ void ConnectionFromUI::view_commit_synchronized_resize(u64 view_id, u64 token)async_view_did_commit_synchronized_resize(view_id, token);}+void ConnectionFromUI::view_set_pinned(u64 view_id, bool pinned)+{+ if (auto* view = find_view(view_id))+ view->set_pinned(pinned);+}++void ConnectionFromUI::view_set_current_tab_of_window(u64 view_id, bool current_tab_of_window)+{+ if (auto* view = find_view(view_id))+ view->set_current_tab_of_window(current_tab_of_window);+}+void ConnectionFromUI::view_set_presents_from_cpu_memory(u64 view_id, bool presents_from_cpu_memory){if (auto* view = find_view(view_id)) {diff --git a/Services/Hub/ConnectionFromUI.h b/Services/Hub/ConnectionFromUI.hindex 0b59e1d086c..8be005353fd 100644--- a/Services/Hub/ConnectionFromUI.h+++ b/Services/Hub/ConnectionFromUI.h@@ -90,6 +90,9 @@ private:virtual Messages::HubServer::ViewSessionHistoryTraversalItemsResponse view_session_history_traversal_items(u64 view_id, i32 direction) override;virtual Messages::HubServer::ViewSessionHistorySnapshotResponse view_session_history_snapshot(u64 view_id) override;virtual Messages::HubServer::ViewRestoreSessionHistoryFromSnapshotResponse view_restore_session_history_from_snapshot(u64 view_id, WebView::SessionHistorySnapshot snapshot) override;+ virtual Messages::HubServer::ViewKeepStateForDiscardingResponse view_keep_state_for_discarding(u64 view_id) override;+ virtual void view_restore_state_of_discarded_tab(u64 view_id, u64 discarded_tab_state_id) override;+ virtual void forget_state_of_discarded_tab(u64 discarded_tab_state_id) override;virtual Messages::HubServer::ViewHistoryStepAtDeltaResponse view_history_step_at_delta(u64 view_id, i32 delta) override;virtual Messages::HubServer::ViewLookUpSelectedTextAtResponse view_look_up_selected_text_at(u64 view_id, Gfx::IntPoint position) override;virtual Messages::HubServer::ViewPageDescriptionResponse view_page_description(u64 view_id) override;@@ -162,6 +165,8 @@ private:virtual void view_set_window_position(u64 view_id, Gfx::IntPoint position) override;virtual void view_set_window_size(u64 view_id, Gfx::IntSize size) override;virtual void view_set_system_visibility_state(u64 view_id, Web::HTML::VisibilityState visibility_state) override;+ virtual void view_set_pinned(u64 view_id, bool pinned) override;+ virtual void view_set_current_tab_of_window(u64 view_id, bool current_tab_of_window) override;virtual void view_set_presents_from_cpu_memory(u64 view_id, bool presents_from_cpu_memory) override;virtual void view_set_hosts_remote_layer(u64 view_id, bool hosts_remote_layer) override;virtual void view_set_wants_frame_notifications(u64 view_id, bool wants_frame_notifications) override;diff --git a/Services/Hub/HubClient.ipc b/Services/Hub/HubClient.ipcindex 0cbf8b90dbe..b2be55ec5dd 100644--- a/Services/Hub/HubClient.ipc+++ b/Services/Hub/HubClient.ipc@@ -349,6 +349,7 @@ endpoint HubClientview_load_finish(u64 view_id, URL::URL url) =|view_activate_tab(u64 view_id) =|view_close(u64 view_id) =|+ view_discard(u64 view_id) =|view_link_hover(u64 view_id, URL::URL url) =|view_link_unhover(u64 view_id) =|view_title_change(u64 view_id, Utf16String title) =|diff --git a/Services/Hub/HubServer.ipc b/Services/Hub/HubServer.ipcindex c832103bde0..1896df5c97e 100644--- a/Services/Hub/HubServer.ipc+++ b/Services/Hub/HubServer.ipc@@ -159,6 +159,9 @@ endpoint HubServerview_session_history_traversal_items(u64 view_id, i32 direction) => (Vector<WebView::ViewImplementation::SessionHistoryTraversalItem> items)view_session_history_snapshot(u64 view_id) => (Optional<WebView::SessionHistorySnapshot> snapshot)view_restore_session_history_from_snapshot(u64 view_id, WebView::SessionHistorySnapshot snapshot) => (bool restored)+ view_keep_state_for_discarding(u64 view_id) => (Optional<u64> discarded_tab_state_id)+ view_restore_state_of_discarded_tab(u64 view_id, u64 discarded_tab_state_id) =|+ forget_state_of_discarded_tab(u64 discarded_tab_state_id) =|view_history_step_at_delta(u64 view_id, i32 delta) => (Optional<i32> step)view_look_up_selected_text_at(u64 view_id, Gfx::IntPoint position) => (bool looked_up)view_page_description(u64 view_id) => (URL::URL url, String user_agent, Gfx::IntSize viewport_size, double device_pixel_ratio, double zoom_level)@@ -243,6 +246,8 @@ endpoint HubServerview_set_window_position(u64 view_id, Gfx::IntPoint position) =|view_set_window_size(u64 view_id, Gfx::IntSize size) =|view_set_system_visibility_state(u64 view_id, Web::HTML::VisibilityState visibility_state) =|+ view_set_pinned(u64 view_id, bool pinned) =|+ view_set_current_tab_of_window(u64 view_id, bool current_tab_of_window) =|view_set_presents_from_cpu_memory(u64 view_id, bool presents_from_cpu_memory) =|view_set_hosts_remote_layer(u64 view_id, bool hosts_remote_layer) =|// The UI hears of the first frame shown in a new remote layer, and of every frame while it wants to.diff --git a/Services/Hub/View.cpp b/Services/Hub/View.cppindex 058db096322..10cae4db355 100644--- a/Services/Hub/View.cpp+++ b/Services/Hub/View.cpp@@ -99,6 +99,7 @@ View::View(InitialState initial_state), m_system_theme(move(initial_state.system_theme)), m_screen_rects(move(initial_state.screen_rects)), m_websites_prefer_dark(initial_state.websites_prefer_dark)+ , m_is_tab(initial_state.is_tab){m_device_pixel_ratio = initial_state.device_pixel_ratio;m_maximum_frames_per_second = initial_state.maximum_frames_per_second;@@ -174,6 +175,13 @@ void View::did_get_permission_answer(u64 answer_id, Web::Permissions::PromptOutc(*on_answer)(outcome);}+// NB: The UI may keep the tab, such as when the user sees it after all. It then stays as it is.+void View::did_request_discard()+{+ if (auto* ui = ConnectionFromUI::the())+ ui->async_view_discard(view_id());+}+void View::forward_callbacks_to_ui(bool is_tab){on_favicon_change = [this](Optional<Gfx::Bitmap const&> favicon) {diff --git a/Services/Hub/View.h b/Services/Hub/View.hindex 0d1d8198cc2..4c89108f3a4 100644--- a/Services/Hub/View.h+++ b/Services/Hub/View.h@@ -63,6 +63,8 @@ private:virtual Optional<ScreenRects> screen_rects() const override { return m_screen_rects; }virtual void update_zoom() override;virtual void did_change_state() override { push_state_to_ui(); }+ virtual bool supports_discarding() const override { return m_is_tab; }+ virtual void did_request_discard() override;virtual Web::DevicePixelSize viewport_size() const override { return m_viewport_size; }virtual Gfx::IntPoint to_content_position(Gfx::IntPoint widget_position) const override { return widget_position; }virtual Gfx::IntPoint to_widget_position(Gfx::IntPoint content_position) const override { return content_position; }@@ -86,6 +88,7 @@ private:Optional<ScreenRects> m_screen_rects;Web::DevicePixelSize m_viewport_size;bool m_websites_prefer_dark { false };+ bool m_is_tab { true };ByteBuffer m_last_state_pushed_to_ui;bool m_wants_frame_notifications { false };bool m_ui_hosts_remote_layer { false };diff --git a/Services/WebContent/ConnectionFromClient.cpp b/Services/WebContent/ConnectionFromClient.cppindex b9233afbd11..6ee4b083eed 100644--- a/Services/WebContent/ConnectionFromClient.cpp+++ b/Services/WebContent/ConnectionFromClient.cpp@@ -78,6 +78,7 @@#include <LibWeb/HTML/RemoteNavigable.h>#include <LibWeb/HTML/Scripting/Environments.h>#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>+#include <LibWeb/HTML/SessionHistoryEntry.h>#include <LibWeb/HTML/Storage.h>#include <LibWeb/HTML/Window.h>#include <LibWeb/HTML/WorkerAgentParent.h>@@ -2556,6 +2557,24 @@ void ConnectionFromClient::set_has_devtools_client(Web::PageId page_id, bool haspage->set_has_devtools_client(has_devtools_client);}+// The Hub holds the session history, but only learns where the user is in a document once they leave it. Each navigable+// of the page saves what it would save then, and the Hub hears when all of them have.+void ConnectionFromClient::save_session_history_entry_states(Web::PageId page_id)+{+ auto page = this->page(page_id);+ if (!page.has_value())+ return;+ for (auto const& navigable : page->page().hosted_navigables()) {+ navigable->save_persisted_state_to_active_session_history_entry();+ auto entry = navigable->active_session_history_entry();+ if (!entry)+ continue;+ if (auto persisted_state = Web::HTML::create_session_history_entry_persisted_state(*entry); persisted_state.has_value())+ async_did_save_session_history_entry_state(page_id, navigable->id(), persisted_state.release_value());+ }+ async_did_save_session_history_entry_states(page_id);+}+void ConnectionFromClient::start_sending_console_output(Web::PageId page_id, bool messages, bool errors){if (auto page = this->page(page_id); page.has_value())diff --git a/Services/WebContent/ConnectionFromClient.h b/Services/WebContent/ConnectionFromClient.hindex b5e73a89fe2..651a4efd5a3 100644--- a/Services/WebContent/ConnectionFromClient.h+++ b/Services/WebContent/ConnectionFromClient.h@@ -236,6 +236,7 @@ private:virtual void set_listen_for_dom_mutations(Web::PageId page_id, bool) override;virtual void set_has_devtools_client(Web::PageId page_id, bool has_devtools_client) override;+ virtual void save_session_history_entry_states(Web::PageId page_id) override;virtual void start_sending_console_output(Web::PageId page_id, bool messages, bool errors) override;virtual void get_dom_node_inner_html(Web::PageId page_id, Web::UniqueNodeID node_id) override;virtual void get_dom_node_outer_html(Web::PageId page_id, Web::UniqueNodeID node_id) override;diff --git a/Services/WebContent/WebContentClient.ipc b/Services/WebContent/WebContentClient.ipcindex ff47b48b2d9..8f3d0918266 100644--- a/Services/WebContent/WebContentClient.ipc+++ b/Services/WebContent/WebContentClient.ipc@@ -221,6 +221,8 @@ endpoint WebContentClient routed by Web::PageId page_id[NotRouted] did_close_browsing_context(Web::PageId page_id) =|did_complete_close_preflight(Web::PageId page_id, u64 request_id, bool approved) =|did_change_needs_beforeunload_check(Web::PageId page_id, bool needs_beforeunload_check) =|+ did_save_session_history_entry_state(Web::PageId page_id, Web::HTML::CrossProcessId navigable_id, Web::HTML::SessionHistoryEntryPersistedState persisted_state) =|+ did_save_session_history_entry_states(Web::PageId page_id) =|did_consume_user_activation(Web::PageId page_id, Web::HTML::UserActivationConsumption consumption) =|did_notify_about_user_activation(Web::PageId page_id, Web::HTML::CrossProcessId document_id) =|webdriver_user_prompt_handling_complete(Web::PageId page_id, u64 request_id, Web::WebDriver::Response response) =|diff --git a/Services/WebContent/WebContentServer.ipc b/Services/WebContent/WebContentServer.ipcindex faef6f4b00e..46ec057afe3 100644--- a/Services/WebContent/WebContentServer.ipc+++ b/Services/WebContent/WebContentServer.ipc@@ -221,6 +221,7 @@ endpoint WebContentServer routed by Web::PageId page_idset_listen_for_dom_mutations(Web::PageId page_id, bool listen_for_dom_mutations) =|set_has_devtools_client(Web::PageId page_id, bool has_devtools_client) =|+ save_session_history_entry_states(Web::PageId page_id) =|start_sending_console_output(Web::PageId page_id, bool messages, bool errors) =|get_dom_node_inner_html(Web::PageId page_id, Web::UniqueNodeID node_id) =|get_dom_node_outer_html(Web::PageId page_id, Web::UniqueNodeID node_id) =|diff --git a/UI/Qt/BrowserWindow.cpp b/UI/Qt/BrowserWindow.cppindex a8f42a835e7..f0cb2535f7a 100644--- a/UI/Qt/BrowserWindow.cpp+++ b/UI/Qt/BrowserWindow.cpp@@ -776,6 +776,8 @@ Tab& BrowserWindow::create_restored_tab(RestoredSessionTab const& restored, int.url = restored.url,.title = entry.has_value() && entry->title.has_value() ? qstring_from_ak_string(*entry->title) : qstring_from_ak_string(restored.url.serialize()),.favicon = entry.has_value() && entry->favicon_png.has_value() ? favicon_from_png(entry->favicon_png->bytes(), TAB_ICON_SIZE) : QIcon {},+ .history = {},+ .discarded_tab_state_id = {},};auto* tab = new Tab(this, AK::move(deferred_tab));tab->set_pinned(restored.pinned);@@ -1082,6 +1084,7 @@ void BrowserWindow::set_current_tab(Tab* tab)if (m_current_tab) {m_current_tab->close_popovers();m_current_tab->view().set_system_visibility_state(Web::HTML::VisibilityState::Hidden);+ m_current_tab->view().set_current_tab_of_window(false);}m_current_tab = tab;@@ -1090,6 +1093,7 @@ void BrowserWindow::set_current_tab(Tab* tab)if (m_current_tab) {m_current_tab->clear_attention();m_current_tab->view().set_system_visibility_state(Web::HTML::VisibilityState::Visible);+ m_current_tab->view().set_current_tab_of_window(true);if (auto session_tab_id = m_current_tab->session_tab_id(); session_tab_id.has_value())session().active_tab_changed(*session_tab_id);@@ -1197,6 +1201,58 @@ bool BrowserWindow::close_tab(int index, SessionStore::KeepForReopening keep_forreturn true;}+// A discarded tab stands in the tab strip as one that a restored session hasn't loaded yet, which it is replaced with.+// Closing the tab's view closes its pages, and so lets the processes that hosted them exit if they host nothing else.+void BrowserWindow::discard_tab(Tab& tab)+{+ // NB: The Hub decides which tabs to discard. The user may have selected or pinned the tab while the request was on+ // its way, which the Hub learns of soon after, and a tab that a session can't restore can't be discarded.+ // A tab that reviews a report would lose the report, which only its page holds, and one with an unfinished edit+ // of its address would lose the edit.+ auto index = tab_index(&tab);+ if (index < 0 || &tab == m_current_tab || tab.is_pinned() || tab.is_in_report_review() || tab.location_edit_with_parked_editing())+ return;+ if (!tab.is_loaded() || !tab.session_tab_id().has_value()) {+ dbgln("Unable to discard tab {}", tab.url());+ return;+ }++ DeferredTab deferred_tab {+ .session_tab_id = *tab.session_tab_id(),+ .url = tab.url(),+ .title = tab.title(),+ .favicon = tab.favicon(),+ .history = tab.view().session_history_snapshot(),+ .discarded_tab_state_id = tab.view().keep_state_for_discarding(),+ };+ auto* discarded_tab = new Tab(this, AK::move(deferred_tab));+ discarded_tab->set_needs_attention(tab.needs_attention());+ // NB: The tab that stands in for the discarded one takes its place among the tabs that the window and other tabs+ // refer to, such as the background tabs opened from the current tab, which new ones open after.+ for (auto& background_tab : m_background_tabs_from_current_tab) {+ if (background_tab == &tab)+ background_tab = discarded_tab;+ }+ for (int i = 0; i < m_tabs_container->count(); ++i) {+ if (auto* other_tab = m_tabs_container->tab(i))+ other_tab->did_replace_tab(tab, *discarded_tab);+ }++ // NB: The tab bar only hides a tab button that another takes the place of, and the old one refers to the old tab.+ uninitialize_tab(&tab);+ auto* tab_bar = m_tabs_container->tab_bar();+ if (auto* close_button = tab_bar->tabButton(index, TAB_CLOSE_BUTTON_POSITION)) {+ tab_bar->setTabButton(index, TAB_CLOSE_BUTTON_POSITION, nullptr);+ close_button->deleteLater();+ }++ m_tabs_container->replace_tab(index, discarded_tab);+ initialize_tab(discarded_tab);+ tab_title_changed(index, discarded_tab->title());+ tab_favicon_changed(index, discarded_tab->favicon());+ tab.deleteLater();+}+void BrowserWindow::move_tab(int old_index, int new_index){auto* tab = m_tabs_container->tab(old_index);diff --git a/UI/Qt/BrowserWindow.h b/UI/Qt/BrowserWindow.hindex faa7651dbe8..31196fb9d8f 100644--- a/UI/Qt/BrowserWindow.h+++ b/UI/Qt/BrowserWindow.h@@ -171,6 +171,7 @@ public:BookmarksBar& bookmarks_bar() const { return m_tabs_container->bookmarks_bar(); }// Closes a tab that isn't worth reopening, such as an empty tab that other tabs took the place of.void close_tab_without_keeping_it(int index);+ void discard_tab(Tab&);// Pinned tabs always fill the start of the strip: indices [0, pinned_tab_count()).int pinned_tab_count() const;diff --git a/UI/Qt/HubConnection.cpp b/UI/Qt/HubConnection.cppindex 903a2773d03..153ecb36c60 100644--- a/UI/Qt/HubConnection.cpp+++ b/UI/Qt/HubConnection.cpp@@ -884,6 +884,12 @@ void HubConnection::view_activate_tab(u64 view_id)view->on_activate_tab();}+void HubConnection::view_discard(u64 view_id)+{+ if (auto* view = RemoteView::find(view_id); view && view->on_discard)+ view->on_discard();+}+void HubConnection::view_close(u64 view_id){if (auto* view = RemoteView::find(view_id); view && view->on_close)diff --git a/UI/Qt/HubConnection.h b/UI/Qt/HubConnection.hindex 042b4ccc62e..6d94b64da00 100644--- a/UI/Qt/HubConnection.h+++ b/UI/Qt/HubConnection.h@@ -187,6 +187,7 @@ private:virtual void view_load_finish(u64 view_id, URL::URL url) override;virtual void view_activate_tab(u64 view_id) override;virtual void view_close(u64 view_id) override;+ virtual void view_discard(u64 view_id) override;virtual void view_link_hover(u64 view_id, URL::URL url) override;virtual void view_link_unhover(u64 view_id) override;virtual void view_title_change(u64 view_id, Utf16String title) override;diff --git a/UI/Qt/RemoteView.cpp b/UI/Qt/RemoteView.cppindex 010f4ae384e..f2879aed693 100644--- a/UI/Qt/RemoteView.cpp+++ b/UI/Qt/RemoteView.cpp@@ -376,6 +376,16 @@ ErrorOr<void> RemoteView::restore_session_history_from_snapshot(WebView::Sessionreturn Error::from_string_literal("Unable to restore the session history");return {};}++Optional<u64> RemoteView::keep_state_for_discarding()+{+ return HubConnection::the().view_keep_state_for_discarding(view_id());+}++void RemoteView::restore_state_of_discarded_tab(u64 discarded_tab_state_id)+{+ HubConnection::the().async_view_restore_state_of_discarded_tab(view_id(), discarded_tab_state_id);+}#elseOptional<i32> RemoteView::history_step_at_delta(int delta) const{@@ -416,6 +426,18 @@ ErrorOr<void> RemoteView::restore_session_history_from_snapshot(WebView::Session{return m_view->restore_session_history_from_snapshot(move(snapshot));}++Optional<u64> RemoteView::keep_state_for_discarding()+{+ return m_view->keep_state_for_discarding();+}++// NB: The tab's pages must find their sessionStorage as they load, so this can't wait for the Hub's turn.+void RemoteView::restore_state_of_discarded_tab(u64 discarded_tab_state_id)+{+ m_view->restore_state_of_discarded_tab(discarded_tab_state_id);+ m_view->push_state_to_ui();+}#endifRemoteView* RemoteView::find(u64 view_id)diff --git a/UI/Qt/RemoteView.h b/UI/Qt/RemoteView.hindex 179bfc051ab..51a3fa1ee15 100644--- a/UI/Qt/RemoteView.h+++ b/UI/Qt/RemoteView.h@@ -91,6 +91,8 @@ public:void set_window_position(Gfx::IntPoint position) { HubConnection::the().async_view_set_window_position(view_id(), position); }void set_window_size(Gfx::IntSize size) { HubConnection::the().async_view_set_window_size(view_id(), size); }void set_system_visibility_state(Web::HTML::VisibilityState visibility_state) { HubConnection::the().async_view_set_system_visibility_state(view_id(), move(visibility_state)); }+ void set_pinned(bool pinned) { HubConnection::the().async_view_set_pinned(view_id(), pinned); }+ void set_current_tab_of_window(bool current_tab_of_window) { HubConnection::the().async_view_set_current_tab_of_window(view_id(), current_tab_of_window); }void set_presents_from_cpu_memory(bool presents_from_cpu_memory) { HubConnection::the().async_view_set_presents_from_cpu_memory(view_id(), presents_from_cpu_memory); }void set_hosts_remote_layer(bool hosts_remote_layer) { HubConnection::the().async_view_set_hosts_remote_layer(view_id(), hosts_remote_layer); }void set_wants_frame_notifications(bool wants_frame_notifications) { HubConnection::the().async_view_set_wants_frame_notifications(view_id(), wants_frame_notifications); }@@ -232,6 +234,14 @@ public:Vector<SessionHistoryTraversalMenuItem> session_history_traversal_menu_items(int direction) const;WebView::SessionHistorySnapshot session_history_snapshot() const;ErrorOr<void> restore_session_history_from_snapshot(WebView::SessionHistorySnapshot);+ Optional<u64> keep_state_for_discarding();+ void restore_state_of_discarded_tab(u64 discarded_tab_state_id);+ // NB: A tab may go away after the connection to the Hub, which takes the state along with it then.+ static void forget_state_of_discarded_tab(u64 discarded_tab_state_id)+ {+ if (auto* hub = HubConnection::the_if_connected())+ hub->async_forget_state_of_discarded_tab(discarded_tab_state_id);+ }void exit_fullscreen() { HubConnection::the().async_view_exit_fullscreen(view_id()); }void deny_fullscreen_window() { HubConnection::the().async_view_deny_fullscreen_window(view_id()); }void set_is_fullscreen(Web::ViewportIsFullscreen is_fullscreen) { HubConnection::the().async_view_set_is_fullscreen(view_id(), is_fullscreen); }@@ -350,6 +360,8 @@ public:Function<void(Web::HTML::ActivateTab, Web::HTML::WebViewHints, u64 view_id)> on_open_new_view;decltype(Hub::View::on_activate_tab) on_activate_tab;decltype(Hub::View::on_close) on_close;+ // The Hub asks to discard the tab of the view, which the tab may decline.+ Function<void()> on_discard;decltype(Hub::View::on_link_hover) on_link_hover;decltype(Hub::View::on_link_unhover) on_link_unhover;decltype(Hub::View::on_title_change) on_title_change;diff --git a/UI/Qt/Tab.cpp b/UI/Qt/Tab.cppindex c5169d34b2d..6db05198180 100644--- a/UI/Qt/Tab.cpp+++ b/UI/Qt/Tab.cpp@@ -287,12 +287,23 @@ void Tab::initialize(Optional<u64> hub_view_id)update_tab_icon();});+ // NB: A tab that was discarded keeps its view until the event loop deletes it, and messages from the view that were+ // on their way still arrive, but the tab is no longer one of the window's tabs.view().on_activate_tab = [this] {- m_window->activate_tab(tab_index());+ if (auto index = tab_index(); index >= 0)+ m_window->activate_tab(index);};+ view().on_discard = [this] {+ m_window->discard_tab(*this);+ };+ view().set_pinned(m_is_pinned);+ view().set_current_tab_of_window(m_window->current_tab() == this);+view().on_close = [this] {auto index = tab_index();+ if (index < 0)+ return;if (m_tab_to_activate_on_close) {if (auto index_to_activate = m_window->tab_index(m_tab_to_activate_on_close); index_to_activate >= 0)m_window->activate_tab(index_to_activate);@@ -975,6 +986,8 @@ void Tab::create_tab_context_menu()// The window's toolbar can hold the address field while the tab goes away with the window.Tab::~Tab(){+ if (m_deferred_tab.has_value() && m_deferred_tab->discarded_tab_state_id.has_value())+ WebContentView::forget_state_of_discarded_tab(*m_deferred_tab->discarded_tab_state_id);delete m_location_edit;}@@ -993,15 +1006,19 @@ void Tab::ensure_loaded()// Until initialize() has built the view, url() reads the deferred tab's URL, so the deferred tab stays until then.auto deferred_url = m_deferred_tab->url;+ auto history = AK::move(m_deferred_tab->history);+ auto discarded_tab_state_id = m_deferred_tab->discarded_tab_state_id;initialize({});m_deferred_tab.clear();+ if (discarded_tab_state_id.has_value())+ view().restore_state_of_discarded_tab(*discarded_tab_state_id);+if (m_session_tab_id.has_value())view().set_session_tab_id(*m_session_tab_id);emit loaded();- Optional<WebView::SessionHistorySnapshot> history;- if (m_session_tab_id.has_value())+ if (!history.has_value() && m_session_tab_id.has_value())history = m_window->session().load_tab_history(*m_session_tab_id);if (!history.has_value() || view().restore_session_history_from_snapshot(history.release_value()).is_error())navigate(deferred_url);@@ -1073,6 +1090,8 @@ void Tab::set_pinned(bool pinned){m_is_pinned = pinned;m_pin_tab_action->setText(pinned ? "Un&pin Tab" : "&Pin Tab");+ if (is_loaded())+ view().set_pinned(pinned);}void Tab::navigate(URL::URL const& url)@@ -1148,6 +1167,12 @@ void Tab::enter_report_review(Tab* tab_to_activate_on_close, Optional<QString> tm_report_review_navigation_listener = view().add_navigation_listener(AK::move(listener));}+void Tab::did_replace_tab(Tab const& old_tab, Tab& new_tab)+{+ if (m_tab_to_activate_on_close == &old_tab)+ m_tab_to_activate_on_close = &new_tab;+}+// A report on its way keeps being sent, as it does when the tab closes.void Tab::leave_report_review(){diff --git a/UI/Qt/Tab.h b/UI/Qt/Tab.hindex fb1452fc56d..eeeace85719 100644--- a/UI/Qt/Tab.h+++ b/UI/Qt/Tab.h@@ -67,6 +67,9 @@ struct DeferredTab {URL::URL url;QString title;QIcon favicon;+ // The history of a discarded tab, which it restores once it is selected, and the state the Hub keeps for it.+ Optional<WebView::SessionHistorySnapshot> history;+ Optional<u64> discarded_tab_state_id;};class Popover;@@ -136,6 +139,7 @@ public:// A tab in the background whose title changes after it has loaded has news, until it is selected.bool needs_attention() const { return m_needs_attention; }void clear_attention() { m_needs_attention = false; }+ void set_needs_attention(bool needs_attention) { m_needs_attention = needs_attention; }QString title() const;QMenu* context_menu() const { return m_context_menu; }@@ -147,6 +151,9 @@ public:void update_hover_label();void enter_report_review(Tab* tab_to_activate_on_close, Optional<QString> title = {});+ bool is_in_report_review() const { return m_report_review_navigation_listener.has_value(); }+ // Another tab stands in for one that was discarded, and takes its place wherever this tab refers to it.+ void did_replace_tab(Tab const& old_tab, Tab& new_tab);bool is_pinned() const { return m_is_pinned; }// BrowserWindow pins and unpins tabs, since it keeps each window's pinned tabs at the start of its strip.diff --git a/UI/Qt/TabBar.cpp b/UI/Qt/TabBar.cppindex a55bb9847aa..82fb2bfe153 100644--- a/UI/Qt/TabBar.cpp+++ b/UI/Qt/TabBar.cpp@@ -2044,6 +2044,26 @@ HorizontalTabEndRoom TabBar::horizontal_tab_end_room(int index) constreturn { start->left + ((settled.left - start->left) * p), start->right + ((settled.right - start->right) * p) };}+void TabBar::did_replace_tab(Tab const& old_tab, Tab& new_tab)+{+ // NB: The previewed tab isn't one of these, as only a loaded tab has a preview, and the UI doesn't discard it.+ for (auto* tab : { &m_previously_selected_tab, &m_pressed_tab }) {+ if (*tab == &old_tab)+ *tab = &new_tab;+ }++ // The tab that stands in for the old one is where the old one was, so the next change of the strip doesn't animate+ // it as a new tab.+ auto move_entry = [&](auto& map) {+ if (auto value = map.take(&old_tab); value.has_value())+ map.set(&new_tab, value.release_value());+ };+ move_entry(m_settled_tab_rects);+ move_entry(m_settled_tab_end_rooms);+ move_entry(m_layout_animation_start_rects);+ move_entry(m_layout_animation_start_end_rooms);+}+void TabBar::prepare_for_tab_removal(int index){m_closing_tab.clear();@@ -3370,6 +3390,38 @@ void TabWidget::insert_tab(int index, Tab* widget, QString const& label)m_tab_bar->update_loading_ring_animation();}+Tab* TabWidget::replace_tab(int index, Tab* widget)+{+ auto* old_widget = as_if<Tab>(m_stacked_widget->widget(index));+ if (!old_widget)+ return nullptr;++ update_all_tabs_entries_soon();++ m_stacked_widget->removeWidget(old_widget);+ if (old_widget->is_loaded())+ old_widget->view().removeEventFilter(this);+ disconnect(old_widget, &Tab::loaded, this, nullptr);+ m_toolbar->release_location_edit(*old_widget);++ if (widget->is_loaded()) {+ widget->view().installEventFilter(this);+ } else {+ auto did_load = [this, widget] {+ widget->view().installEventFilter(this);+ };+ connect(widget, &Tab::loaded, this, did_load, Qt::SingleShotConnection);+ }+ m_stacked_widget->insertWidget(index, widget);+ if (m_tab_bar->currentIndex() >= 0)+ m_stacked_widget->setCurrentIndex(m_tab_bar->currentIndex());+ m_tab_bar->did_replace_tab(*old_widget, *widget);++ m_tab_bar->update();+ m_tab_bar->update_loading_ring_animation();+ return old_widget;+}+void TabWidget::remove_tab(int index){take_tab(index);diff --git a/UI/Qt/TabBar.h b/UI/Qt/TabBar.hindex a5261902f16..89937fc6463 100644--- a/UI/Qt/TabBar.h+++ b/UI/Qt/TabBar.h@@ -97,6 +97,7 @@ public:void set_pinned_tabs_in_rows(bool);void set_vertical_tabs_position(WebView::VerticalTabsPosition);void refresh_tab_layout();+ void did_replace_tab(Tab const& old_tab, Tab& new_tab);// After a tab is closed with a click, the tabs keep their width until the pointer leaves the tab bar, so the next// close button lands under the pointer.void lock_tab_widths();@@ -309,6 +310,8 @@ public:void insert_tab(int index, Tab* widget, QString const& label);void remove_tab(int index);Tab* take_tab(int index);+ // Another tab stands in for the one at the index, which keeps its place in the tab bar rather than closing.+ Tab* replace_tab(int index, Tab* widget);int count() const { return m_tab_bar->count(); }