Truly independent web browser
LibWebView: Have the final suggestions for the text sooner
Andreas Kling62d6723cfad5
diff --git a/Libraries/LibWebView/Autocomplete.cpp b/Libraries/LibWebView/Autocomplete.cppindex a3b459487a1..9c97add7a35 100644--- a/Libraries/LibWebView/Autocomplete.cpp+++ b/Libraries/LibWebView/Autocomplete.cpp@@ -48,10 +48,7 @@ Autocomplete::~Autocomplete()void Autocomplete::cancel_pending_query(){- if (m_remote_query_timer) {- m_remote_query_timer->stop();- m_remote_query_timer.clear();- }+ stop_remote_query_timers();if (auto cancel_remote_query = move(m_cancel_remote_query))cancel_remote_query();@@ -390,10 +387,7 @@ void Autocomplete::search_engine_settings_changed()void Autocomplete::query_autocomplete_engine(AutocompleteQueryID query_id, String query, size_t max_suggestions, Vector<AutocompleteSuggestion> additional_suggestions){- if (m_remote_query_timer) {- m_remote_query_timer->stop();- m_remote_query_timer.clear();- }+ stop_remote_query_timers();if (auto cancel_remote_query = move(m_cancel_remote_query))cancel_remote_query();m_host.autocomplete_service().cancel(m_service_client_id);@@ -401,17 +395,17 @@ void Autocomplete::query_autocomplete_engine(AutocompleteQueryID query_id, Strinm_max_suggestions = max_suggestions;m_query_id = query_id;- auto trimmed_query = MUST(String::from_utf8(query.bytes_as_string_view().trim_whitespace()));- m_remote_suggestions.remove_all_matching([&](auto const& suggestion) {- return !remote_autocomplete_suggestion_matches_input(suggestion.text, trimmed_query);- });+ // NB: The remote rows for the previous text stay until the ones for this text arrive. Dropping them now would+ // shrink the list at every key press, only for it to grow again when the search engine answers. They are never+ // where Return goes, as no remote row is selected automatically.// NB: The sites the user visited only matter for remote rows that carry over to this query.if (m_remote_suggestions.is_empty())m_visited_host_families.clear();- m_trimmed_query = move(trimmed_query);+ m_trimmed_query = MUST(String::from_utf8(query.bytes_as_string_view().trim_whitespace()));m_query = move(query);m_local_query_complete = false;m_remote_query_complete = false;+ m_stopped_waiting_for_remote_query = false;m_classified_query = classify_user_input(m_trimmed_query);m_external_url = m_classified_query.classification == UserInputClassification::ExternalURL? m_classified_query.url@@ -466,21 +460,62 @@ void Autocomplete::query_autocomplete_engine(AutocompleteQueryID query_id, Strindbgln_if(WEBVIEW_HISTORY_DEBUG, "[History] Scheduling remote autocomplete suggestions from {} for '{}'", engine->name, m_query);- static constexpr auto remote_query_debounce_delay_ms = 100;- m_remote_query_timer = Core::Timer::create_single_shot(AK::Duration::from_milliseconds(remote_query_debounce_delay_ms), [this, query_id, engine = engine.release_value(), query = m_query] {+ // The search engine is asked right away, unless it was asked less than this long ago. The first key press after a+ // pause is thus answered as soon as can be, and fast typing asks no more often than this.+ // NB: The request starts from the timer even without a delay, as its answer must not arrive before this returns.+ static constexpr auto minimum_time_between_remote_queries = AK::Duration::from_milliseconds(100);+ auto remote_query_delay = AK::Duration::zero();+ if (m_last_remote_query_time.has_value())+ remote_query_delay = max(AK::Duration::zero(), minimum_time_between_remote_queries - (MonotonicTime::now() - *m_last_remote_query_time));+ m_remote_query_timer = Core::Timer::create_single_shot(remote_query_delay, [this, query_id, engine = engine.release_value(), query = m_query] {if (m_query_id != query_id)return;start_remote_query(query_id, engine, move(query));});m_remote_query_timer->start();++ // The search engine only has so long after the key press to answer. After that, the rows without its answer are+ // final, as the popup waits for the final rows to change, and a late answer makes new final rows.+ // NB: Of the remote rows for the previous text, the ones that start with the new text stand in for the answer then.+ // The others would show the new text among suggestions for another.+ static constexpr auto remote_query_deadline_ms = 400;+ m_remote_query_deadline_timer = Core::Timer::create_single_shot(AK::Duration::from_milliseconds(remote_query_deadline_ms), [this, query_id] {+ if (m_query_id != query_id || m_remote_query_complete)+ return;+ m_stopped_waiting_for_remote_query = true;+ drop_remote_suggestions_for_other_text();+ if (m_local_query_complete && m_external_url_handler_query_complete)+ deliver_current_result();+ });+ m_remote_query_deadline_timer->start();+}++void Autocomplete::stop_remote_query_timers()+{+ for (auto* timer : { &m_remote_query_timer, &m_remote_query_deadline_timer }) {+ if (!*timer)+ continue;+ (*timer)->stop();+ timer->clear();+ }+}++// Lets go of the remote suggestions for the previous text that the current text no longer starts.+void Autocomplete::drop_remote_suggestions_for_other_text()+{+ m_remote_suggestions.remove_all_matching([&](auto const& suggestion) {+ return !remote_autocomplete_suggestion_matches_input(suggestion.text, m_trimmed_query);+ });}void Autocomplete::start_remote_query(AutocompleteQueryID query_id, SearchEngine engine, String query){dbgln_if(WEBVIEW_HISTORY_DEBUG, "[History] Fetching remote autocomplete suggestions from {} for '{}'", engine.name, query);+ m_last_remote_query_time = MonotonicTime::now();if (!engine.suggestions_url_for_query(query).has_value()) {m_remote_query_complete = true;+ drop_remote_suggestions_for_other_text();deliver_current_result();return;}@@ -495,15 +530,21 @@ void Autocomplete::start_remote_query(AutocompleteQueryID query_id, SearchEngine}m_remote_query_complete = true;+ // NB: Without an answer, the remote rows for the previous text are all there is. Only the ones that still start+ // with the text stay then.+ auto deliver_without_an_answer = [&] {+ drop_remote_suggestions_for_other_text();+ deliver_current_result();+ };if (response.had_network_error) {warnln("Unable to fetch autocomplete suggestions");- deliver_current_result();+ deliver_without_an_answer();return;}if (response.response_code.has_value() && *response.response_code >= 400) {warnln("Received error response code {} from autocomplete engine", *response.response_code);- deliver_current_result();+ deliver_without_an_answer();return;}@@ -513,7 +554,7 @@ void Autocomplete::start_remote_query(AutocompleteQueryID query_id, SearchEngineif (auto result = received_autocomplete_response(*engine.suggestions, content_type, StringView { response.body.bytes() }); result.is_error()) {warnln("Unable to handle autocomplete response: {}", result.error());- deliver_current_result();+ deliver_without_an_answer();} else {dbgln_if(WEBVIEW_HISTORY_DEBUG, "[History] Remote autocomplete suggestions for '{}': {}", query, history_log_suggestions(result.value()));m_remote_suggestions = classify_remote_autocomplete_suggestions(result.release_value());@@ -571,6 +612,7 @@ void Autocomplete::deliver_current_result()additional_suggestions.extend(m_local_suggestions);auto remote_suggestions = make_remote_autocomplete_suggestions(m_remote_suggestions.span(), m_visited_host_families,m_local_query_complete ? LocalSuggestionsAreComplete::Yes : LocalSuggestionsAreComplete::No);+ auto waits_for_remote_query = !m_remote_query_complete && !m_stopped_waiting_for_remote_query;auto merged_suggestions = mux_autocomplete_suggestions(m_trimmed_query,move(verbatim_suggestion),@@ -579,7 +621,7 @@ void Autocomplete::deliver_current_result()m_max_suggestions);for (auto& suggestion : merged_suggestions)suggestion.highlight_input = m_trimmed_query;- auto result_kind = m_local_query_complete && m_remote_query_complete && m_external_url_handler_query_complete+ auto result_kind = m_local_query_complete && !waits_for_remote_query && m_external_url_handler_query_complete? AutocompleteResultKind::Final: AutocompleteResultKind::Intermediate;diff --git a/Libraries/LibWebView/Autocomplete.h b/Libraries/LibWebView/Autocomplete.hindex 802469d006b..7a715d9cc79 100644--- a/Libraries/LibWebView/Autocomplete.h+++ b/Libraries/LibWebView/Autocomplete.h@@ -15,6 +15,7 @@#include <AK/RefPtr.h>#include <AK/String.h>#include <AK/StringView.h>+#include <AK/Time.h>#include <AK/Vector.h>#include <AK/Weakable.h>#include <LibCore/Forward.h>@@ -108,7 +109,8 @@ enum class LocalSuggestionsAreComplete {WEBVIEW_API String autocomplete_suggestion_display_text(AutocompleteSuggestion const&);WEBVIEW_API Vector<AutocompleteMatchRange> autocomplete_match_ranges(StringView input, StringView text);-// Remote suggestions for the previous text stay while the user types, as long as they still start with the text.+// Remote suggestions for the previous text stay while the ones for the new text load, so that the list keeps its rows.+// If none arrive, only those that still start with the text stay.WEBVIEW_API bool remote_autocomplete_suggestion_matches_input(StringView suggestion, StringView input);// The rows for remote suggestions. A web address without a scheme is a page only for a site among the local rows. Until// the local rows are complete, such an address for a site not among them yet is left out, rather than shown as a search@@ -163,6 +165,8 @@ private:static ErrorOr<Vector<String>> received_autocomplete_response(SearchSuggestions const&, Optional<ByteString const&> content_type, StringView response);void start_remote_query(AutocompleteQueryID, SearchEngine, String query);+ void stop_remote_query_timers();+ void drop_remote_suggestions_for_other_text();void local_query_complete(AutocompleteQueryID, Vector<AutocompleteSuggestion>);void external_url_handler_query_complete(AutocompleteQueryID, RefPtr<ExternalURLHandler>);void deliver_current_result();@@ -179,6 +183,8 @@ private:size_t m_max_suggestions { default_autocomplete_suggestion_limit };bool m_local_query_complete { false };bool m_remote_query_complete { false };+ // The search engine took too long, so the rows without its answer are final, until it answers after all.+ bool m_stopped_waiting_for_remote_query { false };bool m_external_url_handler_query_complete { true };bool m_external_url_has_handler { false };Optional<URL::URL> m_external_url;@@ -188,6 +194,8 @@ private:HashTable<String> m_visited_host_families;Vector<RemoteAutocompleteSuggestion> m_remote_suggestions;RefPtr<Core::Timer> m_remote_query_timer;+ RefPtr<Core::Timer> m_remote_query_deadline_timer;+ Optional<MonotonicTime> m_last_remote_query_time;Function<void()> m_cancel_remote_query;};diff --git a/Tests/LibWebView/TestAutocomplete.cpp b/Tests/LibWebView/TestAutocomplete.cppindex 91e965a1274..17acb6173dd 100644--- a/Tests/LibWebView/TestAutocomplete.cpp+++ b/Tests/LibWebView/TestAutocomplete.cpp@@ -64,8 +64,15 @@ public:virtual WebView::Settings& autocomplete_settings() override { return WebView::Application::settings(); }+ // While set, a test answers the requests for remote suggestions itself.+ Function<void(Function<void(RemoteResponse)>)> on_fetch_remote_suggestions;+virtual Function<void()> fetch_remote_suggestions(WebView::SearchEngine const& engine, String const& query, WebView::IsPrivate is_private, Function<void(RemoteResponse)> on_response) override{+ if (on_fetch_remote_suggestions) {+ on_fetch_remote_suggestions(move(on_response));+ return [] { };+ }auto url = engine.suggestions_url_for_query(query);auto client = WebView::Application::request_server_client(is_private);if (!url.has_value() || client.is_error()) {@@ -498,4 +505,99 @@ TEST_CASE(autocomplete)Core::EventLoop::current().spin_until([&]() { return request_completed; });outln("PASS: cancel_pending_query during query completion did not crash");++ // The remote rows for the previous text stay while the search engine has yet to answer for the new text, so that+ // the list does not shrink at every key press.+ {+ Vector<Function<void(WebView::AutocompleteHost::RemoteResponse)>> pending_requests;+ app->on_fetch_remote_suggestions = [&](auto on_response) { pending_requests.append(move(on_response)); };++ WebView::Autocomplete remote_autocomplete { *app, WebView::IsPrivate::No };+ Vector<String> remote_rows;+ size_t deliveries = 0;+ auto last_kind = WebView::AutocompleteResultKind::Intermediate;+ remote_autocomplete.on_autocomplete_query_complete = [&](auto, auto const& suggestions, WebView::AutocompleteResultKind kind) {+ remote_rows.clear();+ for (auto const& suggestion : suggestions) {+ if (suggestion.source == WebView::AutocompleteSuggestionSource::Search && !suggestion.is_verbatim)+ remote_rows.append(suggestion.text);+ }+ last_kind = kind;+ ++deliveries;+ };+ auto query = [&](WebView::AutocompleteQueryID query_id, StringView text) {+ deliveries = 0;+ last_kind = WebView::AutocompleteResultKind::Intermediate;+ remote_autocomplete.query_autocomplete_engine(query_id, MUST(String::from_utf8(text)));+ };+ auto wait_for_request = [&] {+ Core::EventLoop::current().spin_until([&]() { return !pending_requests.is_empty(); });+ };+ auto answer = [&](StringView body) {+ pending_requests.take_first()({+ .had_network_error = false,+ .response_code = 200,+ .content_type = "application/json"sv,+ .body = MUST(ByteBuffer::copy(body.bytes())),+ });+ };+ auto fail_request = [&] {+ pending_requests.take_first()({ .had_network_error = true, .response_code = {}, .content_type = {}, .body = {} });+ };+ // NB: The rows are final once the local ones have arrived too.+ auto wait_for_final_rows = [&] {+ Core::EventLoop::current().spin_until([&]() { return last_kind == WebView::AutocompleteResultKind::Final; });+ };++ query(200, "gi"sv);+ wait_for_request();+ answer(R"(["gi",["gina","gift"]])"sv);+ wait_for_final_rows();+ VERIFY(remote_rows == Vector<String> { "gina"_string, "gift"_string });++ // Neither row starts with the new text, and both stay until the answer for it.+ query(201, "git"sv);+ Core::EventLoop::current().spin_until([&]() { return deliveries > 0; });+ VERIFY(last_kind == WebView::AutocompleteResultKind::Intermediate);+ VERIFY(remote_rows == Vector<String> { "gina"_string, "gift"_string });+ wait_for_request();+ answer(R"(["git",["github","gitlab"]])"sv);+ wait_for_final_rows();+ VERIFY(remote_rows == Vector<String> { "github"_string, "gitlab"_string });++ // Without an answer, only the rows that still start with the text stay.+ query(202, "gith"sv);+ wait_for_request();+ VERIFY(remote_rows == Vector<String> { "github"_string, "gitlab"_string });+ fail_request();+ wait_for_final_rows();+ VERIFY(remote_rows == Vector<String> { "github"_string });++ // A row that does not start with the new text cannot stand in for the answer, so the final rows are without it.+ query(203, "gitx"sv);+ wait_for_request();+ VERIFY(remote_rows == Vector<String> { "github"_string });+ VERIFY(last_kind == WebView::AutocompleteResultKind::Intermediate);+ wait_for_final_rows();+ VERIFY(remote_rows.is_empty());++ // A late answer makes new final rows.+ answer(R"(["gitx",["gitxyz"]])"sv);+ wait_for_final_rows();+ VERIFY(remote_rows == Vector<String> { "gitxyz"_string });++ // Rows that all start with the new text stand in for the answer in the final rows.+ query(204, "git"sv);+ wait_for_request();+ VERIFY(last_kind == WebView::AutocompleteResultKind::Intermediate);+ wait_for_final_rows();+ VERIFY(remote_rows == Vector<String> { "gitxyz"_string });+ answer(R"(["git",["github","gitlab"]])"sv);+ wait_for_final_rows();+ VERIFY(remote_rows == Vector<String> { "github"_string, "gitlab"_string });++ remote_autocomplete.cancel_pending_query();+ app->on_fetch_remote_suggestions = nullptr;+ outln("PASS: remote suggestions for the previous text stay until the ones for the new text arrive");+ }}