Truly independent web browser
LibWebView+UI/Qt: Ask for a download path without blocking
Shannon Booth03c5fdd27583
diff --git a/Libraries/LibWebView/Application.cpp b/Libraries/LibWebView/Application.cppindex 17bada94abe..dcfab529224 100644--- a/Libraries/LibWebView/Application.cpp+++ b/Libraries/LibWebView/Application.cpp@@ -2423,16 +2423,23 @@ ErrorOr<LexicalPath> Application::default_path_for_downloaded_file(ByteString coreturn unique_download_path(downloads_directory, Web::sanitize_suggested_download_filename(file));}-ErrorOr<LexicalPath> Application::path_for_downloaded_file(ByteString const& file) const+NonnullRefPtr<Core::Promise<LexicalPath>> Application::path_for_downloaded_file(ByteString const& file) const{- if (browser_options().headless_mode.has_value())- return default_path_for_downloaded_file(file);+ if (browser_options().headless_mode.has_value()) {+ auto download_path = default_path_for_downloaded_file(file);+ if (download_path.is_error())+ return Core::Promise<LexicalPath>::rejected(download_path.release_error());+ return Core::Promise<LexicalPath>::resolved(download_path.release_value());+ }- auto download_path = ask_user_for_download_path(Web::sanitize_suggested_download_filename(file));- if (!download_path.has_value())- return Error::from_errno(ECANCELED);+ return ask_user_for_download_path(Web::sanitize_suggested_download_filename(file))->map<LexicalPath>([](auto& download_path) {+ return LexicalPath { download_path };+ });+}- return LexicalPath { download_path.release_value() };+NonnullRefPtr<Core::Promise<ByteString>> Application::ask_user_for_download_path(ByteString const&) const+{+ return Core::Promise<ByteString>::rejected(Error::from_errno(ECANCELED));}void Application::display_download_confirmation_dialog(StringView download_name, LexicalPath const& path) constdiff --git a/Libraries/LibWebView/Application.h b/Libraries/LibWebView/Application.hindex 34a8856fdcb..305b694b9c6 100644--- a/Libraries/LibWebView/Application.h+++ b/Libraries/LibWebView/Application.h@@ -316,7 +316,7 @@ public:virtual bool should_capture_web_content_output() const { return false; }virtual ErrorOr<LexicalPath> default_path_for_downloaded_file(ByteString const& file) const;- ErrorOr<LexicalPath> path_for_downloaded_file(ByteString const& file) const;+ NonnullRefPtr<Core::Promise<LexicalPath>> path_for_downloaded_file(ByteString const& file) const;virtual void display_download_confirmation_dialog(StringView download_name, LexicalPath const& path) const;virtual void display_error_dialog(StringView error_message) const;@@ -445,7 +445,7 @@ protected:virtual bool should_use_os_geolocation() const { return true; }virtual SiteIsolationMode default_site_isolation_mode() const { return SiteIsolationMode::IFrame; }- virtual Optional<ByteString> ask_user_for_download_path([[maybe_unused]] ByteString const& file) const { return {}; }+ virtual NonnullRefPtr<Core::Promise<ByteString>> ask_user_for_download_path(ByteString const& file) const;virtual void display_crash_report_notification([[maybe_unused]] ByteString const& report_name) { }diff --git a/Libraries/LibWebView/ViewImplementation.cpp b/Libraries/LibWebView/ViewImplementation.cppindex c285b5de307..92f835c7ddd 100644--- a/Libraries/LibWebView/ViewImplementation.cpp+++ b/Libraries/LibWebView/ViewImplementation.cpp@@ -4533,36 +4533,67 @@ void ViewImplementation::update_bookmark_action()m_toggle_bookmark_action->set_engaged(is_bookmarked);}-static ErrorOr<LexicalPath> write_screenshot(Gfx::Bitmap const* bitmap)+static ErrorOr<void> write_screenshot_to_path(ReadonlyBytes encoded, LexicalPath const& path)+{+ auto dump_file = TRY(Core::File::open(path.string(), Core::File::OpenMode::Write));+ TRY(dump_file->write_until_depleted(encoded));++ return {};+}++static NonnullRefPtr<Core::Promise<LexicalPath>> write_screenshot(Gfx::Bitmap const* bitmap){if (!bitmap)- return Error::from_string_literal("Failed to take a screenshot");+ return Core::Promise<LexicalPath>::rejected(Error::from_string_literal("Failed to take a screenshot"));- auto path = TRY([] -> ErrorOr<LexicalPath> {+ // NB: The bitmap may be gone, or show something else, by the time a path is chosen.+ auto encoded = Gfx::PNGWriter::encode(*bitmap);+ if (encoded.is_error())+ return Core::Promise<LexicalPath>::rejected(encoded.release_error());++ auto destination = [] {if (auto const& screenshot_path = Application::browser_options().screenshot_path; screenshot_path.has_value())- return LexicalPath { *screenshot_path };+ return Core::Promise<LexicalPath>::resolved(LexicalPath { *screenshot_path });auto file = AK::UnixDateTime::now().to_byte_string("screenshot-%Y-%m-%d-%H-%M-%S.png"sv);return Application::the().path_for_downloaded_file(file);- }());+ }();- auto encoded = TRY(Gfx::PNGWriter::encode(*bitmap));+ auto promise = Core::Promise<LexicalPath>::construct();+ destination+ ->when_resolved([promise, encoded = encoded.release_value()](auto const& path) {+ if (auto result = write_screenshot_to_path(encoded, path); result.is_error())+ promise->reject(result.release_error());+ else+ promise->resolve(path);+ })+ .when_rejected([promise](auto& error) {+ promise->reject(move(error));+ });+ return promise;+}- auto dump_file = TRY(Core::File::open(path.string(), Core::File::OpenMode::Write));- TRY(dump_file->write_until_depleted(encoded));+static void report_saved_screenshot(Core::Promise<LexicalPath>& screenshot)+{+ screenshot+ .when_resolved([](auto const& path) {+ Application::the().display_download_confirmation_dialog("Screenshot"sv, path);+ })+ .when_rejected([](auto const& error) {+ if (error.is_errno() && error.code() == ECANCELED)+ return;- return path;+ auto error_message = MUST(String::formatted("{}", error));+ Application::the().display_error_dialog(error_message);+ });}NonnullRefPtr<Core::Promise<LexicalPath>> ViewImplementation::take_screenshot(ScreenshotType type){- auto promise = Core::Promise<LexicalPath>::construct();-if (m_pending_screenshot) {// For simplicity, only allow taking one screenshot at a time for now. Revisit if we need// to allow spamming screenshot requests for some reason.- promise->reject(Error::from_string_literal("A screenshot request is already in progress"));- return promise;+ return Core::Promise<LexicalPath>::rejected(Error::from_string_literal("A screenshot request is already in progress"));}switch (type) {@@ -4574,50 +4605,32 @@ NonnullRefPtr<Core::Promise<LexicalPath>> ViewImplementation::take_screenshot(Sc} else if (m_backup_shared_image_buffer) {visible_bitmap = m_backup_shared_image_buffer->bitmap_if_present();}- if (visible_bitmap) {- if (auto result = write_screenshot(visible_bitmap.ptr()); result.is_error())- promise->reject(result.release_error());- else- promise->resolve(result.release_value());- } else {- // GPU-shared backing stores have no CPU-visible pixels, so ask WebContent to paint a screenshot for us.- m_pending_screenshot = promise;- page().async_take_document_screenshot();- }+ if (visible_bitmap)+ return write_screenshot(visible_bitmap.ptr());++ // GPU-shared backing stores have no CPU-visible pixels, so ask WebContent to paint a screenshot for us.break;}case ScreenshotType::Full:- m_pending_screenshot = promise;- page().async_take_document_screenshot();break;}+ auto promise = Core::Promise<LexicalPath>::construct();+ m_pending_screenshot = promise;+ page().async_take_document_screenshot();return promise;}void ViewImplementation::take_and_save_screenshot(ScreenshotType type){- take_screenshot(type)- ->when_resolved([](auto const& path) {- Application::the().display_download_confirmation_dialog("Screenshot"sv, path);- })- .when_rejected([](auto const& error) {- if (error.is_errno() && error.code() == ECANCELED)- return;-- auto error_message = MUST(String::formatted("{}", error));- Application::the().display_error_dialog(error_message);- });+ report_saved_screenshot(*take_screenshot(type));}// A screenshot the UI took itself, such as of the part of the page the user selected.void ViewImplementation::save_screenshot(Gfx::Bitmap const& bitmap){- if (auto result = write_screenshot(&bitmap); result.is_error())- Application::the().display_error_dialog(MUST(String::formatted("{}", result.error())));- else- Application::the().display_download_confirmation_dialog("Screenshot"sv, result.value());+ report_saved_screenshot(*write_screenshot(&bitmap));}NonnullRefPtr<Core::Promise<LexicalPath>> ViewImplementation::take_dom_node_screenshot(Web::UniqueNodeID node_id)@@ -4645,10 +4658,13 @@ void ViewImplementation::did_receive_screenshot(Badge<WebContentPage>, Gfx::Sharreturn;}- if (auto result = write_screenshot(screenshot.bitmap()); result.is_error())- m_pending_screenshot->reject(result.release_error());- else- m_pending_screenshot->resolve(result.release_value());+ write_screenshot(screenshot.bitmap())+ ->when_resolved([pending_screenshot = m_pending_screenshot](auto const& path) {+ pending_screenshot->resolve(path);+ })+ .when_rejected([pending_screenshot = m_pending_screenshot](auto& error) {+ pending_screenshot->reject(move(error));+ });m_pending_screenshot = nullptr;}@@ -5463,17 +5479,20 @@ void ViewImplementation::download_context_menu_url(PromptForPath prompt_for_path// URLs with an opaque path, such as data: URLs, do not contain a usable filename, so the default filename is// used instead.auto suggested_filename = m_context_menu_url.has_an_opaque_path() ? ByteString {} : m_context_menu_url.basename();- auto download_path = prompt_for_path == PromptForPath::Yes- ? Application::the().path_for_downloaded_file(suggested_filename)- : Application::the().default_path_for_downloaded_file(suggested_filename);- if (download_path.is_error())++ if (prompt_for_path == PromptForPath::No) {+ if (auto download_path = Application::the().default_path_for_downloaded_file(suggested_filename); !download_path.is_error())+ Application::the().file_downloader().download_file(is_private(), m_context_menu_url, download_path.release_value(), FileDownloader::MayReplaceDestination::No);return;+ }- // NB: A file at a path the user chose was there when the user chose to replace it, as saving asks before replacing.- auto may_replace_destination = prompt_for_path == PromptForPath::Yes && FileSystem::exists(download_path.value().string())- ? FileDownloader::MayReplaceDestination::Yes- : FileDownloader::MayReplaceDestination::No;- Application::the().file_downloader().download_file(is_private(), m_context_menu_url, download_path.release_value(), may_replace_destination);+ Application::the().path_for_downloaded_file(suggested_filename)->when_resolved([is_private = is_private(), url = m_context_menu_url](auto const& download_path) {+ // NB: A file at a path the user chose was there when the user chose to replace it, as saving asks before replacing.+ auto may_replace_destination = FileSystem::exists(download_path.string())+ ? FileDownloader::MayReplaceDestination::Yes+ : FileDownloader::MayReplaceDestination::No;+ Application::the().file_downloader().download_file(is_private, url, download_path, may_replace_destination);+ });}void ViewImplementation::did_request_image_context_menu(Badge<WebContentPage>, Gfx::IntPoint content_position, Web::HTML::PreparedNavigationDescriptor navigation, Optional<Gfx::ShareableBitmap> bitmap)diff --git a/Libraries/LibWebView/WebUI/BookmarksUI.cpp b/Libraries/LibWebView/WebUI/BookmarksUI.cppindex 406b37d9635..50007a4e9b8 100644--- a/Libraries/LibWebView/WebUI/BookmarksUI.cpp+++ b/Libraries/LibWebView/WebUI/BookmarksUI.cpp@@ -86,20 +86,18 @@ void BookmarksUI::export_bookmarks(JsonValue const& data)if (!data.is_string())return;- auto destination = Application::the().path_for_downloaded_file(ByteString { "bookmarks.html" });- if (destination.is_error())- return;-- auto file = Core::File::open(destination.value().string(), Core::File::OpenMode::Write);- if (file.is_error()) {- Application::the().display_error_dialog(MUST(String::formatted("Unable to export bookmarks: {}", file.error())));- return;- }-- if (auto result = file.value()->write_until_depleted(data.as_string().bytes()); result.is_error()) {- Application::the().display_error_dialog(MUST(String::formatted("Unable to export bookmarks: {}", result.error())));- return;- }+ Application::the().path_for_downloaded_file(ByteString { "bookmarks.html" })->when_resolved([bookmarks = data.as_string()](auto const& destination) {+ auto file = Core::File::open(destination.string(), Core::File::OpenMode::Write);+ if (file.is_error()) {+ Application::the().display_error_dialog(MUST(String::formatted("Unable to export bookmarks: {}", file.error())));+ return;+ }++ if (auto result = file.value()->write_until_depleted(bookmarks.bytes()); result.is_error()) {+ Application::the().display_error_dialog(MUST(String::formatted("Unable to export bookmarks: {}", result.error())));+ return;+ }+ });}void BookmarksUI::show_context_menu(JsonValue const& data)diff --git a/UI/Qt/Application.cpp b/UI/Qt/Application.cppindex b4b33448eb7..4259611a2ae 100644--- a/UI/Qt/Application.cpp+++ b/UI/Qt/Application.cpp@@ -1419,20 +1419,26 @@ void Application::open_navigation_in_new_window(Web::HTML::PreparedNavigationDesnew_window({ move(url) }, configuration_for_new_window(), BrowserWindow::IsPopupWindow::No, is_private, nullptr, {}, ShowWindow::Yes, move(navigation));}-Optional<ByteString> Application::ask_user_for_download_path(ByteString const& file) const+NonnullRefPtr<Core::Promise<ByteString>> Application::ask_user_for_download_path(ByteString const& file) const{- auto default_path = QStandardPaths::writableLocation(QStandardPaths::DownloadLocation);+ auto* dialog = new QFileDialog(nullptr, "Select save location", QStandardPaths::writableLocation(QStandardPaths::DownloadLocation));+ dialog->setAttribute(Qt::WA_DeleteOnClose);+ dialog->setAcceptMode(QFileDialog::AcceptSave);+ dialog->selectFile(qstring_from_ak_string(file.view()));- if (default_path.isNull() || default_path.isEmpty())- default_path = qstring_from_ak_string(file.view());- else- default_path = QDir { default_path }.filePath(qstring_from_ak_string(file.view()));+ auto promise = Core::Promise<ByteString>::construct();- auto path = QFileDialog::getSaveFileName(nullptr, "Select save location", default_path);- if (path.isNull())- return {};+ QObject::connect(dialog, &QDialog::finished, [promise, dialog = QPointer { dialog }](auto result) {+ if (result != QDialog::Accepted || !dialog || dialog->selectedFiles().isEmpty()) {+ promise->reject(Error::from_errno(ECANCELED));+ return;+ }- return ak_byte_string_from_qstring(path);+ promise->resolve(ak_byte_string_from_qstring(dialog->selectedFiles().first()));+ });++ dialog->open();+ return promise;}void Application::display_download_confirmation_dialog(StringView download_name, LexicalPath const& path) constdiff --git a/UI/Qt/Application.h b/UI/Qt/Application.hindex 308cad1aff8..78a2c8633e7 100644--- a/UI/Qt/Application.h+++ b/UI/Qt/Application.h@@ -161,7 +161,7 @@ private:virtual void resolve_external_url_handler(URL::URL const&, WebView::ExternalURLHandlerCallback) const override;- virtual Optional<ByteString> ask_user_for_download_path(ByteString const& file) const override;+ virtual NonnullRefPtr<Core::Promise<ByteString>> ask_user_for_download_path(ByteString const& file) const override;virtual void display_download_confirmation_dialog(StringView download_name, LexicalPath const& path) const override;virtual void display_error_dialog(StringView error_message) const override;virtual void open_download(WebView::FileDownloader::Download const&) const override;