Truly independent web browser
LibWeb+LibWebView+WebContent: Keep tabs the user typed into loaded
Andreas Klingf8a18e5925b2
diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cppindex b16cd8a9899..2adb757f0fe 100644--- a/Libraries/LibWeb/DOM/Document.cpp+++ b/Libraries/LibWeb/DOM/Document.cpp@@ -11023,10 +11023,17 @@ void Document::set_navigable(GC::Ptr<HTML::LocalNavigable> navigable)rendering_pending_document_changed(*this);rendering_pending_document_changed(*this);- if (previous_page)+ // NB: A page without user edits keeps none as a document without any comes or goes.+ if (previous_page) {previous_page->update_needs_beforeunload_check();- if (navigable && &navigable->page() != previous_page.ptr())+ if (m_had_user_edits || previous_page->had_user_edits())+ previous_page->update_had_user_edits();+ }+ if (navigable && &navigable->page() != previous_page.ptr()) {navigable->page().update_needs_beforeunload_check();+ if (m_had_user_edits || navigable->page().had_user_edits())+ navigable->page().update_had_user_edits();+ }}void Document::set_needs_repaint(InvalidateDisplayList should_invalidate_display_list)diff --git a/Libraries/LibWeb/DOM/Document.h b/Libraries/LibWeb/DOM/Document.hindex 8aedfb2c7a8..9fb40232b0a 100644--- a/Libraries/LibWeb/DOM/Document.h+++ b/Libraries/LibWeb/DOM/Document.h@@ -1264,6 +1264,11 @@ public:Yes,};WebIDL::ExceptionOr<bool> exec_command(Utf16FlyString const& command, bool show_ui, TrustedTypes::TrustedHTMLOrString const& value);++ // Whether the user changed the value of a text control or the content of an editing host in this document, which+ // they would lose if the document were unloaded without asking them.+ bool had_user_edits() const { return m_had_user_edits; }+ void did_make_user_edit();WebIDL::ExceptionOr<bool> exec_command_internal(Utf16FlyString const& command, bool show_ui, Utf16View value, DispatchInputEvent, Optional<Utf16FlyString> const& user_input_type = {}, GC::Ptr<StaticRange> deletion_range = nullptr, GC::Ptr<DocumentFragment> pasted_fragment = nullptr);WebIDL::ExceptionOr<bool> query_command_enabled(Utf16FlyString const& command);WebIDL::ExceptionOr<bool> query_command_indeterm(Utf16FlyString const& command);@@ -1882,6 +1887,8 @@ protected:void initialize_document();private:+ bool script_edits_for_the_user() const;+bool update_is_fully_active() const;bool compute_is_fully_active() const;@@ -2579,6 +2586,8 @@ private:GC::Ptr<Editing::EditingHistory> m_editing_history;bool m_inside_exec_command { false };+ bool m_inside_script_edit_on_its_own { false };+ bool m_had_user_edits { false };bool m_inside_clipboard_exec_command { false };bool m_running_editing_command_action { false };bool m_preserve_selection_offsets_during_identical_character_data_replacement { false };diff --git a/Libraries/LibWeb/DOM/EditingHostManager.cpp b/Libraries/LibWeb/DOM/EditingHostManager.cppindex c4ed08b2c03..dd1e2cf9c12 100644--- a/Libraries/LibWeb/DOM/EditingHostManager.cpp+++ b/Libraries/LibWeb/DOM/EditingHostManager.cpp@@ -40,6 +40,18 @@ void EditingHostManager::visit_edges(Cell::Visitor& visitor)visitor.visit(m_active_contenteditable_element);}+Array<u64, 2> EditingHostManager::content_versions(Document const& document)+{+ return { document.dom_tree_version(), document.character_data_version() };+}++// NB: A command can succeed without changing anything, such as a deletion at the start of the editing host.+void EditingHostManager::did_run_user_edit(Document& document, WebIDL::ExceptionOr<bool>& editing_result, Array<u64, 2> content_versions_before)+{+ if (!editing_result.is_exception() && editing_result.value() && content_versions(document) != content_versions_before)+ document.did_make_user_edit();+}+void EditingHostManager::handle_insert(Utf16FlyString const& input_type, Utf16View value){// https://w3c.github.io/editing/docs/execCommand/#additional-requirements@@ -51,9 +63,11 @@ void EditingHostManager::handle_insert(Utf16FlyString const& input_type, Utf16Vi//// NB: The user's input type is passed along so pastes fire an input event with inputType "insertFromPaste" and// form their own undo unit, even though they run the insertText command.+ auto content_versions_before = content_versions(*m_document);auto editing_result = m_document->exec_command_internal(Editing::CommandNames::insertText, false, value, Document::DispatchInputEvent::Yes, input_type);if (editing_result.is_exception())dbgln("handle_insert(): editing resulted in exception: {}", editing_result.exception());+ did_run_user_edit(*m_document, editing_result, content_versions_before);}void EditingHostManager::handle_insert_from_clipboard(Utf16FlyString const& input_type, Utf16View plain_text, Optional<Utf16View> html)@@ -78,9 +92,11 @@ void EditingHostManager::handle_insert_from_clipboard(Utf16FlyString const& inpu// Run insertHTML as one user edit so its DOM mutations and final selection form one undo unit.// NB: insertHTML inserts the sanitized fragment itself. Serializing and reparsing it could produce a different// tree from the one the sanitizer inspected.+ auto content_versions_before = content_versions(*m_document);auto editing_result = m_document->exec_command_internal(Editing::CommandNames::insertHTML, false, {}, Document::DispatchInputEvent::Yes, input_type, nullptr, fragment.value());if (editing_result.is_exception())dbgln("handle_insert_from_clipboard(): editing resulted in exception: {}", editing_result.exception());+ did_run_user_edit(*m_document, editing_result, content_versions_before);}void EditingHostManager::select_all()@@ -298,9 +314,11 @@ void EditingHostManager::handle_delete(Utf16FlyString const& input_type, [[maybe}auto forward = first_is_one_of(input_type, UIEvents::InputTypes::deleteContentForward, UIEvents::InputTypes::deleteWordForward, UIEvents::InputTypes::deleteHardLineForward);auto command = forward ? Editing::CommandNames::forwardDelete : Editing::CommandNames::delete_;+ auto content_versions_before = content_versions(*m_document);auto editing_result = m_document->exec_command_internal(command, false, {}, Document::DispatchInputEvent::Yes, input_type, range.ptr());if (editing_result.is_exception())dbgln("handle_delete(): editing resulted in exception: {}", editing_result.exception());+ did_run_user_edit(*m_document, editing_result, content_versions_before);}EventResult EditingHostManager::handle_return_key(Utf16FlyString const& ui_input_type)@@ -319,11 +337,13 @@ EventResult EditingHostManager::handle_return_key(Utf16FlyString const& ui_input: Editing::CommandNames::insertLineBreak;// NB: Use the internal entry point like the other user edits, so that a script that focuses a text control// during the key press does not redirect this edit to that text control.+ auto content_versions_before = content_versions(*m_document);auto editing_result = m_document->exec_command_internal(command, false, {}, Document::DispatchInputEvent::Yes);if (editing_result.is_exception()) {dbgln("handle_return_key(): editing resulted in exception: {}", editing_result.exception());return EventResult::Dropped;}+ did_run_user_edit(*m_document, editing_result, content_versions_before);return editing_result.value() ? EventResult::Handled : EventResult::Dropped;}diff --git a/Libraries/LibWeb/DOM/EditingHostManager.h b/Libraries/LibWeb/DOM/EditingHostManager.hindex b45bab96fc3..1fe339b5a17 100644--- a/Libraries/LibWeb/DOM/EditingHostManager.h+++ b/Libraries/LibWeb/DOM/EditingHostManager.h@@ -6,6 +6,7 @@#pragma once+#include <AK/Array.h>#include <LibGC/CellAllocator.h>#include <LibJS/Heap/Cell.h>#include <LibWeb/DOM/InputEventsTarget.h>@@ -54,6 +55,10 @@ public:m_active_contenteditable_element = element;}+ // What changes whenever the document's content does, which tells whether an edit changed anything.+ static Array<u64, 2> content_versions(Document const&);+ static void did_run_user_edit(Document&, WebIDL::ExceptionOr<bool>& editing_result, Array<u64, 2> content_versions_before);+private:EditingHostManager(GC::Ref<Document>);diff --git a/Libraries/LibWeb/Editing/ExecCommand.cpp b/Libraries/LibWeb/Editing/ExecCommand.cppindex 1c50e32a3ab..9ec30d227ca 100644--- a/Libraries/LibWeb/Editing/ExecCommand.cpp+++ b/Libraries/LibWeb/Editing/ExecCommand.cpp@@ -8,6 +8,7 @@#include <AK/ScopeGuard.h>#include <AK/TemporaryChange.h>#include <LibWeb/DOM/Document.h>+#include <LibWeb/DOM/EditingHostManager.h>#include <LibWeb/DOM/ElementFactory.h>#include <LibWeb/DOM/Event.h>#include <LibWeb/DOM/HTMLCollection.h>@@ -28,8 +29,10 @@#include <LibWeb/HTML/LocalNavigable.h>#include <LibWeb/HTML/Parser/HTMLParser.h>#include <LibWeb/HTML/Scripting/Environments.h>+#include <LibWeb/HTML/Window.h>#include <LibWeb/HighResolutionTime/TimeOrigin.h>#include <LibWeb/Page/EventHandler.h>+#include <LibWeb/Page/Page.h>#include <LibWeb/Selection/Selection.h>#include <LibWeb/TrustedTypes/RequireTrustedTypesForDirective.h>#include <LibWeb/TrustedTypes/TrustedTypePolicy.h>@@ -159,6 +162,10 @@ WebIDL::ExceptionOr<bool> Document::exec_command(Utf16FlyString const& command,if (m_inside_clipboard_exec_command)return false;+ // NB: An edit a script makes on its own is not one the user would lose. Whether it edits for the user is decided+ // here, as an input listener may consume the window's transient activation while the command runs.+ TemporaryChange inside_script_edit_on_its_own { m_inside_script_edit_on_its_own, !script_edits_for_the_user() };+// AD-HOC: The spec gets the Trusted Types compliant string for an insertHTML value in step 1 of the insertHTML// command's action. Get it here instead, where only a script's value arrives: The action also inserts the// HTML a user pastes, which isn't an injection sink. And so a script's string is rejected even when the@@ -217,7 +224,32 @@ WebIDL::ExceptionOr<bool> Document::exec_command(Utf16FlyString const& command,}}- return exec_command_internal(command, show_ui, value, DispatchInputEvent::Yes);+ auto content_versions_before = EditingHostManager::content_versions(*this);+ auto result = exec_command_internal(command, show_ui, value, DispatchInputEvent::Yes);+ // NB: A page that edits for the user in an editing host, such as from a keydown or paste handler or a toolbar+ // button's click handler, makes the user's edit.+ EditingHostManager::did_run_user_edit(*this, result, content_versions_before);+ return result;+}++// NB: A page may edit for the user, such as with execCommand("insertText") from a keydown handler, or from the click+// handler of a toolbar button, which gives the window transient activation. That edit is the user's, unlike one a+// script makes on its own.+bool Document::script_edits_for_the_user() const+{+ if (Web::EventHandler::is_handling_user_key_press_or_paste())+ return true;+ auto window = this->window();+ return window && window->has_transient_activation();+}++void Document::did_make_user_edit()+{+ if (m_had_user_edits || m_inside_script_edit_on_its_own)+ return;+ m_had_user_edits = true;+ if (auto navigable = this->navigable())+ navigable->page().update_had_user_edits();}WebIDL::ExceptionOr<bool> Document::exec_command_internal(Utf16FlyString const& command, [[maybe_unused]] bool show_ui, Utf16View value, DispatchInputEvent dispatch_input_event, Optional<Utf16FlyString> const& user_input_type, GC::Ptr<StaticRange> deletion_range, GC::Ptr<DocumentFragment> pasted_fragment)diff --git a/Libraries/LibWeb/HTML/FormAssociatedElement.cpp b/Libraries/LibWeb/HTML/FormAssociatedElement.cppindex 7f8cd8438f6..530721b1962 100644--- a/Libraries/LibWeb/HTML/FormAssociatedElement.cpp+++ b/Libraries/LibWeb/HTML/FormAssociatedElement.cpp@@ -1322,6 +1322,7 @@ void FormAssociatedTextControlElement::handle_insert(Utf16FlyString const& inputauto history = html_element.document().editing_history();history->begin_recording(html_element, category);auto old_value = relevant_value();+ auto old_text_node_data = text_node->data();auto clamped_start = min(selection_start, old_value.length_in_code_units());auto clamped_end = min(selection_end, old_value.length_in_code_units());auto removed_data = Utf16String::from_utf16(old_value.substring_view(clamped_start, clamped_end - clamped_start));@@ -1347,6 +1348,10 @@ void FormAssociatedTextControlElement::handle_insert(Utf16FlyString const& inputif (first_is_one_of(input_type, UIEvents::InputTypes::insertText, UIEvents::InputTypes::insertCompositionText, UIEvents::InputTypes::insertFromPaste, UIEvents::InputTypes::insertReplacementText))data_for_input_event = Utf16String::from_utf16(data_for_insertion);+ // NB: Typing into a control that is at its maximum length changes nothing. A listener for the input event may undo+ // the edit, so this checks before it runs.+ if (!html_element.document().had_user_edits() && text_node->data() != old_text_node_data)+ html_element.document().did_make_user_edit();did_edit_text_node(input_type, data_for_input_event, old_value);html_element.document().spell_check_controller().did_user_edit(html_element);html_element.document().writing_suggestion_controller().did_user_edit(html_element);@@ -1422,6 +1427,7 @@ void FormAssociatedTextControlElement::handle_delete(Utf16FlyString const& inputauto history = html_element.document().editing_history();history->begin_recording(html_element, category);auto old_value = relevant_value();+ auto old_text_node_data = text_node->data();auto clamped_start = min(selection_start, old_value.length_in_code_units());auto clamped_end = min(selection_end, old_value.length_in_code_units());auto removed_data = Utf16String::from_utf16(old_value.substring_view(clamped_start, clamped_end - clamped_start));@@ -1437,6 +1443,10 @@ void FormAssociatedTextControlElement::handle_delete(Utf16FlyString const& input}history->end_recording();+ // NB: Deleting at the start or end of a control changes nothing. A listener for the input event may undo the edit,+ // so this checks before it runs.+ if (!html_element.document().had_user_edits() && text_node->data() != old_text_node_data)+ html_element.document().did_make_user_edit();did_edit_text_node(input_type, {}, old_value);html_element.document().spell_check_controller().did_user_edit(html_element);html_element.document().writing_suggestion_controller().did_user_edit(html_element);diff --git a/Libraries/LibWeb/Internals/Internals.cpp b/Libraries/LibWeb/Internals/Internals.cppindex 1b06d8b0c78..5ba1a83579f 100644--- a/Libraries/LibWeb/Internals/Internals.cpp+++ b/Libraries/LibWeb/Internals/Internals.cpp@@ -479,6 +479,11 @@ bool Internals::initial_paint_had_pending_fonts() constreturn window().associated_document().font_computer().initial_paint_had_pending_fonts();}+bool Internals::had_user_edits() const+{+ return window().associated_document().had_user_edits();+}+bool Internals::has_pending_image_loads() const{// A shared resource request stays in its fetching state until its image has decoded.diff --git a/Libraries/LibWeb/Internals/Internals.h b/Libraries/LibWeb/Internals/Internals.hindex 8722254e1f2..4cce231e30b 100644--- a/Libraries/LibWeb/Internals/Internals.h+++ b/Libraries/LibWeb/Internals/Internals.h@@ -65,6 +65,7 @@ public:bool has_completed_initial_paint() const;bool initial_paint_had_pending_fonts() const;bool has_pending_image_loads() const;+ bool had_user_edits() const;void set_font_display_time(CSS::FontFace&, u32 milliseconds);WebIDL::ExceptionOr<Utf16String> set_time_zone(Utf16String const& time_zone);diff --git a/Libraries/LibWeb/Internals/Internals.idl b/Libraries/LibWeb/Internals/Internals.idlindex ac7e2d73364..f3566d31575 100644--- a/Libraries/LibWeb/Internals/Internals.idl+++ b/Libraries/LibWeb/Internals/Internals.idl@@ -25,6 +25,8 @@ interface Internals {readonly attribute boolean initialPaintHadPendingFonts;// Whether any image this document fetched is still loading or decoding.readonly attribute boolean hasPendingImageLoads;+ // Whether the user edited a text control or an editing host in this document.+ readonly attribute boolean hadUserEdits;// Freezes the font display clock at the given elapsed time, without starting a font load.undefined setFontDisplayTime(FontFace fontFace, unsigned long milliseconds);DOMString setTimeZone(DOMString timeZone);diff --git a/Libraries/LibWeb/Page/EventHandler.cpp b/Libraries/LibWeb/Page/EventHandler.cppindex bdeb24d44e5..ab1da08cacf 100644--- a/Libraries/LibWeb/Page/EventHandler.cpp+++ b/Libraries/LibWeb/Page/EventHandler.cpp@@ -11,6 +11,7 @@#include <AK/Base64.h>#include <AK/Debug.h>#include <AK/Math.h>+#include <AK/TemporaryChange.h>#include <LibCompositing/DisplayList/DisplayListResources.h>#include <LibGC/Heap.h>#include <LibGC/RootHashTable.h>@@ -1940,8 +1941,16 @@ EventResult EventHandler::handle_text_editing_command(TextEditingCommand const&return EventResult::Handled;}+static bool s_is_handling_user_key_press_or_paste = false;++bool EventHandler::is_handling_user_key_press_or_paste()+{+ return s_is_handling_user_key_press_or_paste;+}+EventResult EventHandler::handle_keydown(UIEvents::KeyCode key, u32 modifiers, u32 code_point, bool repeat, bool should_insert_text, bool async_scroll_performed_default_action, ReadonlySpan<TextEditingCommand> editing_commands, bool native_editing_binding_resolved){+ TemporaryChange handling_user_key_press { s_is_handling_user_key_press_or_paste, true };if (!m_navigable->active_document())return EventResult::Dropped;if (!m_navigable->active_document()->is_fully_active())@@ -2465,6 +2474,7 @@ EventResult EventHandler::handle_keydown(UIEvents::KeyCode key, u32 modifiers, uEventResult EventHandler::handle_keyup(UIEvents::KeyCode key, u32 modifiers, u32 code_point, bool repeat){+ TemporaryChange handling_user_key_press { s_is_handling_user_key_press_or_paste, true };// Keyup events as a result of auto-repeat are not fired.// See: https://w3c.github.io/uievents/#events-keyboard-event-orderif (repeat)@@ -2940,6 +2950,9 @@ EventResult EventHandler::perform_paste_action(NonnullRefPtr<HTML::DragDataStoreif (!document || !document->is_fully_active())return EventResult::Dropped;+ // NB: Only the user pastes, with a key or the UI's Paste command, so an edit the page makes in response is theirs.+ TemporaryChange handling_user_paste { s_is_handling_user_key_press_or_paste, true };+data_store->set_mode(HTML::DragDataStore::Mode::ReadOnly);auto data_transfer = HTML::DataTransfer::create(data_store);diff --git a/Libraries/LibWeb/Page/EventHandler.h b/Libraries/LibWeb/Page/EventHandler.hindex 3e135220a5c..a4bab04fd42 100644--- a/Libraries/LibWeb/Page/EventHandler.h+++ b/Libraries/LibWeb/Page/EventHandler.h@@ -112,6 +112,8 @@ public:GC::Ptr<DOM::Node> target_node_for_mouse_position(CSSPixelPoint);EventResult handle_keydown(UIEvents::KeyCode, unsigned modifiers, u32 code_point, bool repeat, bool should_insert_text, bool async_scroll_performed_default_action = false, ReadonlySpan<TextEditingCommand> editing_commands = {}, bool native_editing_binding_resolved = false);+ // Whether a key the user pressed or a paste is being handled, along with what the page does in response to it.+ static bool is_handling_user_key_press_or_paste();EventResult handle_text_editing_command(TextEditingCommand const&);struct KeyboardScrollSnapshot {Compositing::KeyboardScrollState state;diff --git a/Libraries/LibWeb/Page/Page.cpp b/Libraries/LibWeb/Page/Page.cppindex f03a33c218d..643d1f466ac 100644--- a/Libraries/LibWeb/Page/Page.cpp+++ b/Libraries/LibWeb/Page/Page.cpp@@ -803,6 +803,25 @@ void Page::update_needs_beforeunload_check()client().page_did_change_needs_beforeunload_check(m_needs_beforeunload_check);}+// Whether the user edited a document this page hosts, so that they would lose what they typed if the page went away.+void Page::update_had_user_edits()+{+ auto had_user_edits = false;+ for (auto const& navigable : hosted_navigables()) {+ // NB: A document that is leaving its navigable, such as that of a removed iframe, is still its active document.+ if (auto document = navigable->active_document(); document && document->navigable().ptr() == navigable.ptr() && document->had_user_edits()) {+ had_user_edits = true;+ break;+ }+ }++ if (m_had_user_edits == had_user_edits)+ return;++ m_had_user_edits = had_user_edits;+ client().page_did_change_had_user_edits(m_had_user_edits);+}+void Page::set_top_level_traversable(GC::Ref<HTML::Navigable> navigable){VERIFY(!m_top_level_traversable); // Replacement is not allowed!@@ -957,6 +976,7 @@ void Page::discard_provisional_navigable_of(HTML::RemoteNavigable& remote_navigaif (m_top_level_traversable.ptr() == navigable.ptr()) {m_top_level_traversable = remote_navigable;update_needs_beforeunload_check();+ update_had_user_edits();retire_page_compositor_context(navigable->take_compositor_context());}navigable->set_has_been_destroyed();@@ -992,6 +1012,7 @@ GC::Ref<HTML::LocalNavigable> Page::begin_hosting(HTML::CrossProcessId id, HTML:VERIFY(m_top_level_traversable.ptr() == navigable.ptr());m_top_level_traversable = stand_in;update_needs_beforeunload_check();+ update_had_user_edits();return stand_in;}return HTML::LocalNavigable::create_stand_in({}, *navigable, current_history_entry);diff --git a/Libraries/LibWeb/Page/Page.h b/Libraries/LibWeb/Page/Page.hindex a4cfeaa332d..a9bc5371907 100644--- a/Libraries/LibWeb/Page/Page.h+++ b/Libraries/LibWeb/Page/Page.h@@ -280,6 +280,8 @@ public:Compositing::KeyboardScrollState take_keyboard_scroll_state_for_compositor(u64 visual_context_tree_structural_epoch);bool needs_beforeunload_check() const { return m_needs_beforeunload_check; }void update_needs_beforeunload_check();+ bool had_user_edits() const { return m_had_user_edits; }+ void update_had_user_edits();bool is_webdriver_active() const { return m_is_webdriver_active; }void set_is_webdriver_active(bool b) { m_is_webdriver_active = b; }@@ -608,6 +610,7 @@ private:Vector<GC::Weak<DOM::EventTarget>> m_keyboard_scroll_event_path;GC::Weak<DOM::Node> m_keyboard_scroll_dom_target;bool m_needs_beforeunload_check { true };+ bool m_had_user_edits { false };// https://w3c.github.io/webdriver/#dfn-webdriver-active-flag// The webdriver-active flag is set to true when the user agent is under remote control. It is initially false.@@ -967,6 +970,7 @@ public:virtual void page_did_request_fully_exit_fullscreen() { }virtual void page_did_request_unload_check(HTML::CrossProcessId, GC::Ref<GC::Function<void(HTML::CheckIfUnloadingIsCanceledResult)>>) { VERIFY_NOT_REACHED(); }virtual void page_did_change_needs_beforeunload_check([[maybe_unused]] bool needs_beforeunload_check) { }+ virtual void page_did_change_had_user_edits([[maybe_unused]] bool had_user_edits) { }virtual void page_did_consume_user_activation([[maybe_unused]] HTML::UserActivationConsumption consumption) { }virtual void page_did_notify_about_user_activation([[maybe_unused]] HTML::CrossProcessId document_id) { }diff --git a/Libraries/LibWebView/DiscardBlockers.h b/Libraries/LibWebView/DiscardBlockers.hindex 3ff2cd8da82..ace6cf06ab9 100644--- a/Libraries/LibWebView/DiscardBlockers.h+++ b/Libraries/LibWebView/DiscardBlockers.h@@ -27,7 +27,7 @@ enum class DiscardBlockers : u32 {UsingLocation = 1 << 9,OwnsAView = 1 << 10,DevToolsConnected = 1 << 11,- AsksBeforeUnloading = 1 << 12,+ UserEdits = 1 << 12,// Only a tab hidden for long is kept for these, as they're work the tab does for the user in the background.ChangedTitleOrFaviconWhileHidden = 1 << 13,MayShowNotifications = 1 << 14,diff --git a/Libraries/LibWebView/ViewImplementation.cpp b/Libraries/LibWebView/ViewImplementation.cppindex dff1f4ef54c..8d1f7f6fa79 100644--- a/Libraries/LibWebView/ViewImplementation.cpp+++ b/Libraries/LibWebView/ViewImplementation.cpp@@ -687,10 +687,11 @@ DiscardBlockers ViewImplementation::discard_blockers(DiscardReason reason, Monotif (m_devtools_connected)blockers |= DiscardBlockers::DevToolsConnected;- // 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())- blockers |= DiscardBlockers::AsksBeforeUnloading;+ // The user would lose what they typed, as nothing brings it back when the tab is loaded again.+ // NB: Many pages listen for beforeunload whether or not they hold anything the user would lose, so that says+ // little about whether the tab can be unloaded.+ if (had_user_edits())+ blockers |= DiscardBlockers::UserEdits;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@@ -3309,6 +3310,17 @@ void ViewImplementation::did_change_screen_wake_lock_state(Badge<WebContentPage>on_screen_wake_lock_state_changed(m_screen_wake_lock_state);}+bool ViewImplementation::had_user_edits() const+{+ // Each page of the tab reports for the documents it hosts.+ bool had_user_edits = false;+ traversable().for_each_hosting_page([&](WebContentPage& page) {+ if (page.had_user_edits())+ had_user_edits = true;+ });+ return had_user_edits;+}+bool ViewImplementation::needs_beforeunload_check() const{// Each page of the tab reports for the documents it hosts.diff --git a/Libraries/LibWebView/ViewImplementation.h b/Libraries/LibWebView/ViewImplementation.hindex c78df378fa0..02b8e45a93a 100644--- a/Libraries/LibWebView/ViewImplementation.h+++ b/Libraries/LibWebView/ViewImplementation.h@@ -640,6 +640,7 @@ public:void prepare_for_immediate_close();void close_tab_for_testing();bool needs_beforeunload_check() const;+ bool had_user_edits() const;struct NavigationListener {Function<void(URL::URL const&)> on_load_start;diff --git a/Libraries/LibWebView/WebContentPage.cpp b/Libraries/LibWebView/WebContentPage.cppindex bbbbcf33873..2102abf9d2b 100644--- a/Libraries/LibWebView/WebContentPage.cpp+++ b/Libraries/LibWebView/WebContentPage.cpp@@ -681,6 +681,7 @@ void WebContentPage::close()view->did_lose_input_event_endpoint({}, *this);}m_needs_beforeunload_check = true;+ m_had_user_edits = false;m_history_recorded_url_for_current_load.clear();if (m_client) {m_client->update_audio_capture_permission();@@ -1438,6 +1439,11 @@ void WebContentPage::did_change_needs_beforeunload_check(bool needs_beforeunloadm_needs_beforeunload_check = needs_beforeunload_check;}+void WebContentPage::did_change_had_user_edits(bool had_user_edits)+{+ m_had_user_edits = had_user_edits;+}+void WebContentPage::did_save_session_history_entry_state(Web::HTML::CrossProcessId navigable_id, Web::HTML::SessionHistoryEntryPersistedState persisted_state){if (!has_traversable())diff --git a/Libraries/LibWebView/WebContentPage.h b/Libraries/LibWebView/WebContentPage.hindex e8ef52dfe85..a024b36eb1d 100644--- a/Libraries/LibWebView/WebContentPage.h+++ b/Libraries/LibWebView/WebContentPage.h@@ -154,6 +154,7 @@ public:bool consume_transient_user_activation();bool needs_beforeunload_check() const { return m_needs_beforeunload_check; }+ bool had_user_edits() const { return m_had_user_edits; }bool detached_close_pending() const { return m_detached_close_pending; }void set_detached_close_pending(bool pending) { m_detached_close_pending = pending; }@@ -267,6 +268,7 @@ 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_change_had_user_edits(bool had_user_edits) 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;@@ -448,6 +450,7 @@ private:bool m_capturing_audio { false };Optional<PresentedBackingStores> m_presented_backing_stores;bool m_needs_beforeunload_check { true };+ bool m_had_user_edits { false };bool m_detached_close_pending { false };Optional<String> m_history_recorded_url_for_current_load;HashTable<u64> m_renderer_owned_downloads;diff --git a/Services/WebContent/PageClient.cpp b/Services/WebContent/PageClient.cppindex 1be1310f573..f5f5bc0db07 100644--- a/Services/WebContent/PageClient.cpp+++ b/Services/WebContent/PageClient.cpp@@ -1853,6 +1853,11 @@ void PageClient::page_did_change_needs_beforeunload_check(bool needs_beforeunloaclient().async_did_change_needs_beforeunload_check(m_id, needs_beforeunload_check);}+void PageClient::page_did_change_had_user_edits(bool had_user_edits)+{+ client().async_did_change_had_user_edits(m_id, had_user_edits);+}+void PageClient::page_did_consume_user_activation(Web::HTML::UserActivationConsumption consumption){client().async_did_consume_user_activation(m_id, consumption);diff --git a/Services/WebContent/PageClient.h b/Services/WebContent/PageClient.hindex c5e5316115e..8f4b6bb72a7 100644--- a/Services/WebContent/PageClient.h+++ b/Services/WebContent/PageClient.h@@ -326,6 +326,7 @@ private:virtual NewWebViewResult page_did_request_new_web_view(Web::HTML::ActivateTab, Web::HTML::WebViewHints, Web::HTML::CrossProcessId current_navigable_id, Utf16String const& name, Web::HTML::TokenizedFeature::NoOpener no_opener, Optional<URL::URL> current_document_base_url) override;virtual void page_did_close() override;virtual void page_did_change_needs_beforeunload_check(bool needs_beforeunload_check) override;+ virtual void page_did_change_had_user_edits(bool had_user_edits) override;virtual void page_did_consume_user_activation(Web::HTML::UserActivationConsumption) override;virtual void page_did_notify_about_user_activation(Web::HTML::CrossProcessId document_id) override;virtual void page_did_update_session_history_entry_navigation_api_state(Web::HTML::CrossProcessId navigable_id, Web::HTML::SessionHistoryEntryIdentity const& entry_identity, Web::HTML::StorageSerializationRecord const& navigation_api_state) override;diff --git a/Services/WebContent/WebContentClient.ipc b/Services/WebContent/WebContentClient.ipcindex 8f3d0918266..7ce57518004 100644--- a/Services/WebContent/WebContentClient.ipc+++ b/Services/WebContent/WebContentClient.ipc@@ -221,6 +221,7 @@ 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_change_had_user_edits(Web::PageId page_id, bool had_user_edits) =|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) =|diff --git a/Tests/LibWeb/Text/expected/document-had-user-edits-without-change.txt b/Tests/LibWeb/Text/expected/document-had-user-edits-without-change.txtnew file mode 100644index 00000000000..96fe77b8d60--- /dev/null+++ b/Tests/LibWeb/Text/expected/document-had-user-edits-without-change.txt@@ -0,0 +1,16 @@+Typing into a full text control: false (value abc)+Deleting in an empty text control: false+Deleting in an empty editing host: false+text-control-typing-through-script, after execCommand: false+text-control-typing-through-script, after typing: true+editing-host-typing-through-script, after execCommand: false+editing-host-typing-through-script, after typing: true+editing-host-typing-through-script-on-keyup, after typing: true (x)+editing-host-toolbar-button, after execCommand: false+editing-host-toolbar-button, after clicking: true (scriptinserted)+text-control-pasting-through-script, after execCommand: false+text-control-pasting-through-script, after pasting: true (scriptpasted)+editing-host-pasting-through-script, after execCommand: false+editing-host-pasting-through-script, after pasting: true (scriptpasted)+text-control-undone-by-input-listener, after typing: true (value "")+textarea-undone-by-input-listener, after typing: true (value "")diff --git a/Tests/LibWeb/Text/expected/document-had-user-edits.txt b/Tests/LibWeb/Text/expected/document-had-user-edits.txtnew file mode 100644index 00000000000..a87dc2ddf91--- /dev/null+++ b/Tests/LibWeb/Text/expected/document-had-user-edits.txt@@ -0,0 +1,10 @@+text-control:+ Initially: false+ After execCommand: false+ After a script change: false+ After typing: true+editing-host:+ Initially: false+ After execCommand: false+ After a script change: false+ After typing: truediff --git a/Tests/LibWeb/Text/input/document-had-user-edits-without-change.html b/Tests/LibWeb/Text/input/document-had-user-edits-without-change.htmlnew file mode 100644index 00000000000..6f8f1dae52c--- /dev/null+++ b/Tests/LibWeb/Text/input/document-had-user-edits-without-change.html@@ -0,0 +1,104 @@+<!DOCTYPE html>+<iframe id="full-text-control" srcdoc="<input maxlength=3 value=abc>"></iframe>+<iframe id="delete-in-empty-text-control" srcdoc="<input>"></iframe>+<iframe id="delete-in-empty-editing-host" srcdoc="<div contenteditable></div>"></iframe>+<iframe id="text-control-typing-through-script" srcdoc="<input>"></iframe>+<iframe id="editing-host-typing-through-script" srcdoc="<div contenteditable></div>"></iframe>+<iframe id="editing-host-typing-through-script-on-keyup" srcdoc="<div contenteditable></div>"></iframe>+<iframe id="editing-host-toolbar-button" srcdoc="<button>Insert</button><div contenteditable></div>"></iframe>+<iframe id="text-control-pasting-through-script" srcdoc="<input>"></iframe>+<iframe id="editing-host-pasting-through-script" srcdoc="<div contenteditable></div>"></iframe>+<iframe id="text-control-undone-by-input-listener" srcdoc="<input>"></iframe>+<iframe id="textarea-undone-by-input-listener" srcdoc="<textarea></textarea>"></iframe>+<script src="include.js"></script>+<script>+ asyncTest(async done => {+ await new Promise(resolve => window.addEventListener("load", resolve));++ const frameFor = id => document.getElementById(id).contentWindow;+ const elementIn = frame => frame.document.querySelector("input, textarea, div");++ let frame = frameFor("full-text-control");+ let element = elementIn(frame);+ element.focus();+ element.setSelectionRange(3, 3);+ frame.internals.sendText(element, "d");+ println(`Typing into a full text control: ${frame.internals.hadUserEdits} (value ${element.value})`);++ frame = frameFor("delete-in-empty-text-control");+ element = elementIn(frame);+ element.focus();+ frame.internals.sendKey(element, "Backspace");+ println(`Deleting in an empty text control: ${frame.internals.hadUserEdits}`);++ frame = frameFor("delete-in-empty-editing-host");+ element = elementIn(frame);+ element.focus();+ frame.internals.sendKey(element, "Backspace");+ println(`Deleting in an empty editing host: ${frame.internals.hadUserEdits}`);++ for (const id of ["text-control-typing-through-script", "editing-host-typing-through-script"]) {+ frame = frameFor(id);+ element = elementIn(frame);+ element.addEventListener("keydown", event => {+ event.preventDefault();+ frame.document.execCommand("insertText", false, event.key);+ });+ element.focus();+ frame.document.execCommand("insertText", false, "script");+ println(`${id}, after execCommand: ${frame.internals.hadUserEdits}`);+ frame.internals.sendText(element, "x");+ println(`${id}, after typing: ${frame.internals.hadUserEdits}`);+ }++ frame = frameFor("editing-host-typing-through-script-on-keyup");+ element = elementIn(frame);+ element.addEventListener("keydown", event => event.preventDefault());+ element.addEventListener("keyup", event => frame.document.execCommand("insertText", false, event.key));+ element.focus();+ frame.internals.sendText(element, "x");+ println(`editing-host-typing-through-script-on-keyup, after typing: ${frame.internals.hadUserEdits} (${element.textContent})`);++ frame = frameFor("editing-host-toolbar-button");+ element = frame.document.querySelector("div");+ const button = frame.document.querySelector("button");+ button.addEventListener("mousedown", event => event.preventDefault());+ button.addEventListener("click", () => frame.document.execCommand("insertText", false, "inserted"));+ element.focus();+ frame.document.execCommand("insertText", false, "script");+ println(`editing-host-toolbar-button, after execCommand: ${frame.internals.hadUserEdits}`);+ const frameRect = document.getElementById("editing-host-toolbar-button").getBoundingClientRect();+ const buttonRect = button.getBoundingClientRect();+ frame.internals.click(+ frameRect.x + frame.frameElement.clientLeft + buttonRect.x + buttonRect.width / 2,+ frameRect.y + frame.frameElement.clientTop + buttonRect.y + buttonRect.height / 2+ );+ println(`editing-host-toolbar-button, after clicking: ${frame.internals.hadUserEdits} (${element.textContent})`);++ for (const id of ["text-control-pasting-through-script", "editing-host-pasting-through-script"]) {+ frame = frameFor(id);+ element = elementIn(frame);+ element.addEventListener("paste", event => {+ event.preventDefault();+ frame.document.execCommand("insertText", false, event.clipboardData.getData("text/plain"));+ });+ element.focus();+ frame.document.execCommand("insertText", false, "script");+ println(`${id}, after execCommand: ${frame.internals.hadUserEdits}`);+ frame.internals.paste(element, "pasted");+ println(`${id}, after pasting: ${frame.internals.hadUserEdits} (${element.value ?? element.textContent})`);+ }++ for (const id of ["text-control-undone-by-input-listener", "textarea-undone-by-input-listener"]) {+ frame = frameFor(id);+ element = elementIn(frame);+ element.addEventListener("input", () => {+ element.value = "";+ });+ element.focus();+ frame.internals.sendText(element, "x");+ println(`${id}, after typing: ${frame.internals.hadUserEdits} (value "${element.value}")`);+ }+ done();+ });+</script>diff --git a/Tests/LibWeb/Text/input/document-had-user-edits.html b/Tests/LibWeb/Text/input/document-had-user-edits.htmlnew file mode 100644index 00000000000..90971ee711e--- /dev/null+++ b/Tests/LibWeb/Text/input/document-had-user-edits.html@@ -0,0 +1,30 @@+<!DOCTYPE html>+<iframe id="text-control" srcdoc="<input>"></iframe>+<iframe id="editing-host" srcdoc="<div contenteditable></div>"></iframe>+<script src="include.js"></script>+<script>+ asyncTest(async done => {+ await new Promise(resolve => window.addEventListener("load", resolve));++ for (const [id, selector] of [["text-control", "input"], ["editing-host", "div"]]) {+ const frame = document.getElementById(id).contentWindow;+ const element = frame.document.querySelector(selector);+ println(`${id}:`);+ println(` Initially: ${frame.internals.hadUserEdits}`);++ element.focus();+ frame.document.execCommand("insertText", false, "script");+ println(` After execCommand: ${frame.internals.hadUserEdits}`);++ if (selector === "input")+ element.value = "value";+ else+ element.textContent = "content";+ println(` After a script change: ${frame.internals.hadUserEdits}`);++ frame.internals.sendText(element, "typed");+ println(` After typing: ${frame.internals.hadUserEdits}`);+ }+ done();+ });+</script>diff --git a/UI/Qt/ProcessManagerWindow.cpp b/UI/Qt/ProcessManagerWindow.cppindex 5dcdb7ebe5a..a0a738f0069 100644--- a/UI/Qt/ProcessManagerWindow.cpp+++ b/UI/Qt/ProcessManagerWindow.cpp@@ -328,7 +328,7 @@ static CanUnloadState can_unload_state(WebView::ProcessTabSnapshot const& tab)Description { DiscardBlockers::UsingLocation, QT_TRANSLATE_NOOP("QObject", "It's using your location") },Description { DiscardBlockers::OwnsAView, QT_TRANSLATE_NOOP("QObject", "It has a Picture-in-Picture window") },Description { DiscardBlockers::DevToolsConnected, QT_TRANSLATE_NOOP("QObject", "DevTools are open for it") },- Description { DiscardBlockers::AsksBeforeUnloading, QT_TRANSLATE_NOOP("QObject", "The page asks to be checked before it's unloaded") },+ Description { DiscardBlockers::UserEdits, QT_TRANSLATE_NOOP("QObject", "You typed into the page") },Description { DiscardBlockers::ChangedTitleOrFaviconWhileHidden, QT_TRANSLATE_NOOP("QObject", "It changed its title or icon while hidden") },Description { DiscardBlockers::MayShowNotifications, QT_TRANSLATE_NOOP("QObject", "The site may show notifications") },};