diff --git a/cmake/WKWebViewSupport.cmake b/cmake/WKWebViewSupport.cmake index a95d70ad..8a49393b 100644 --- a/cmake/WKWebViewSupport.cmake +++ b/cmake/WKWebViewSupport.cmake @@ -18,7 +18,7 @@ function(webfront_add_wkwebview_tests) add_executable(wkwebview_lifecycle "${webtest_source_dir}/WKWebViewLifecycle.cpp" "${webtest_source_dir}/WKWebViewHeaderConsumer.cpp") target_link_libraries(wkwebview_lifecycle PRIVATE WebFront WebFront_warnings WebFront_options) - foreach(mode repeated-show main-thread native-close quit navigation-diagnostic startup-timeout settings redirect-policy missing-response committed-navigation agent-application) + foreach(mode repeated-show main-thread native-close quit navigation-diagnostic startup-timeout settings redirect-policy missing-response committed-navigation agent-application download choose-file cancel-choose replaced-download choose-in-blank choose-in-srcdoc close-with-open-panel close-with-save-panel) add_test(NAME WKWebViewLifecycle-${mode} COMMAND wkwebview_lifecycle ${mode}) webfront_set_browser_test_properties("WKWebViewLifecycle-${mode}" "${webtest_source_dir}" 90) endforeach() diff --git a/cmake/WebKitGTKSupport.cmake b/cmake/WebKitGTKSupport.cmake index 0d0d7385..b901fd30 100644 --- a/cmake/WebKitGTKSupport.cmake +++ b/cmake/WebKitGTKSupport.cmake @@ -25,7 +25,7 @@ function(webfront_add_webkitgtk_tests) target_link_libraries(webkitgtk_lifecycle PRIVATE WebFront_test_hardening WebFront WebFront_warnings WebFront_options) add_dependencies(webtest webkitgtk_lifecycle) webfront_find_xvfb(display_runner) - foreach(mode no-display worker-thread native-close repeated-show http-error pre-run-failure profile-permissions window-title) + foreach(mode no-display worker-thread native-close repeated-show http-error pre-run-failure profile-permissions window-title download download-user-dir choose-file cancel-choose close-with-dialog) if(mode MATCHES "^(no-display|worker-thread|pre-run-failure|profile-permissions)$") add_test(NAME WebKitGTKAdapter-${mode} COMMAND webkitgtk_lifecycle ${mode}) elseif(display_runner) diff --git a/cmake/WebView2Support.cmake b/cmake/WebView2Support.cmake index b969378f..7725049b 100644 --- a/cmake/WebView2Support.cmake +++ b/cmake/WebView2Support.cmake @@ -65,7 +65,8 @@ function(webfront_add_webview2_tests) "${webtest_source_dir}/WebView2HeaderConsumer.cpp") target_link_libraries(webview2_lifecycle PRIVATE WebFront WebFront_warnings WebFront_options) foreach(mode repeated-show native-early-close navigation-diagnostic mta missing-runtime - closed-startup-timeout failed-startup-timeout late-navigation-failure runtime-ready) + closed-startup-timeout failed-startup-timeout late-navigation-failure runtime-ready + file-choose file-cancel file-download) add_test(NAME WebView2Lifecycle-${mode} COMMAND webview2_lifecycle ${mode}) webfront_set_browser_test_properties("WebView2Lifecycle-${mode}" "${webtest_source_dir}" 45) endforeach() diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 44cb6d35..ffaa02fc 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -2,6 +2,16 @@ ## Unreleased +- Embedded frontends: `` and downloads (#451, ADR-020 rule 6). WebKitGTK saves downloads to the user's + download folder (name reduced to its last component, never overwritten); WKWebView gets `runOpenPanelWithParameters` and + `WKDownload`; CEF and WebView2 use the engine's own handling. A `blob:` URL of an admitted origin + now passes the navigation policy, so a generated Blob can be downloaded. Test injection points answer the chooser and the + download without a dialog (`docs/FRONTENDS.md`). On Windows, WebView2 tests exercise chooser selection and cancellation + through DevTools and verify completed downloads on disk; the native dialog UI itself remains unqualified. + WKWebView stages downloads privately and preserves a destination created during transfer; failed downloads remove their + incomplete files. Automatic destination selection cancels instead of reusing + an occupied path when all 10,000 candidate names are taken. + - Developer environment: the distribution is served from `https://dist.webfront.fr/` (#478, ADR-021). The sources advance to 0.6.5, the first version published under that address; `site.mjs` writes the `CNAME` file of the Pages branch and `wf run pin` checks the pinned archive where it is served now. Libraries and environments up to 0.6.4 pin the former diff --git a/docs/FRONTENDS.md b/docs/FRONTENDS.md index 718e1135..ab8a0859 100644 --- a/docs/FRONTENDS.md +++ b/docs/FRONTENDS.md @@ -45,6 +45,54 @@ startup failures before any window is created. Coordination waits have a 30-seco `test/unit/WebFrontTests.cpp` also checks initialization once per frontend type, retry after failed initialization, frontend selection and unavailable-engine diagnostics. These tests need no GUI. +## File chooser and downloads + +The embedded frontends use their engine's file chooser and download handling without a WebFront API (ADR-020, rule 6). +Coverage varies by engine and does not yet qualify all native dialogs, `accept` filters or directory selection. A `blob:` URL of an +admitted origin passes the navigation policy (`webfront::detail::blobOriginUrl`); a `blob:` URL of any other origin does not. + +| Frontend | Chooser | Download | Test injection | +| --- | --- | --- | --- | +| WebKitGTK | default `run-file-chooser` dialog (portal under Flatpak) | `download-started` / `decide-destination`: the user's XDG download folder, the page's name reduced to its last component, never overwriting (`name (1).ext`), also between downloads that run at the same time (`DownloadReservations`) | `Session::chooseFiles`, `downloadDirectory`, `downloadFinished` | +| CEF (Chrome runtime) | the runtime's dialog | the runtime's download handling | `SimpleCEFClient::chooseFiles` (`CefDialogHandler::OnFileDialog`), `downloadDirectory`, `downloadFinished`. The runtime itself turns a suggested name `../x` into `_x` | +| WKWebView | `runOpenPanelWithParameters` shows an `NSOpenPanel` sheet of the window; only frames admitted by the policy | `WKDownload` (macOS 11.3+): a save panel proposes the name | `WKWebViewOptions::chooseFiles`, `downloadDirectory`, `downloadFinished` | +| WebView2 | the engine's native chooser | the engine's native download UI | DevTools intercepts the chooser in tests; `DownloadStarting` redirects the download to a private path | + +The engines require a user gesture to open a chooser, so the native scenarios click with a real pointer event (XTest under +Xvfb for WebKitGTK), a `Runtime.evaluate` with `userGesture` (CEF) or `evaluateJavaScript`, which WebKit treats as a user +gesture (WKWebView). The WKWebView scenarios (`WKWebViewLifecycle-download`, `-choose-file`, `-cancel-choose`, +`-replaced-download`) use the test injections of `WKWebViewOptions`: they qualify the delegate wiring, the blob download +policy, the destination handling and the replace-on-success logic, not the system `NSOpenPanel`/`NSSavePanel` themselves. +The real panels were driven by hand on macOS before the private staging change in `52d8c68` (accessibility actions, a +local slow server, no automated test): saving and the +"Replace" choice report the finished download and leave no `.part` file; cancelling the save sheet creates nothing; an +`` panel offers folders only; two simultaneous downloads of one name get `same.bin` and +`same (1).bin`; closing the window cancels the downloads in progress and removes their incomplete files; a response the +engine cannot display (`application/octet-stream`) is saved as a download. +These earlier manual results do not qualify the private staging implementation; the PR records subsequent validation +separately. Native dialog qualification remains incomplete. +WebKit reduces a suggested name such as `../x.txt` to `_x.txt` before the frontend sees it. +If all 10,000 candidate names are occupied, automatic destination selection fails and cancels the download. +WKWebView writes each download in a private staging directory beside the destination. On success it installs the file; +if a destination that was free appears during the download, it preserves that file and discards the download. Failed and +cancelled downloads remove their staging directory. Installing a new destination requires hard-link support on its filesystem. + +### Tests + +`ConsumerJasmine-file-services` (all engines) checks that files reach the page as `File` objects, that the `accept` and +`webkitdirectory` properties keep their values (filtering and directory selection themselves are not exercised), and +that offering a generated Blob leaves the page and the bridge working. `WebKitGTKAdapter-download|choose-file|cancel-choose` +and `CEFFileServices-download|choose|cancel` drive the dialog and the download through the injection points. +`WebKitGTKAdapter-download-user-dir` checks that, without a configured folder, the download lands in GLib's user download +directory (read from `user-dirs.dirs`, not from an environment variable). `WebKitGTKAdapter-close-with-dialog` opens the +real system dialog with a pointer click, closes the window under it and requires a clean exit; CEF and WebView2 do not +test that case. `WKWebViewLifecycle-close-with-open-panel|close-with-save-panel` close the window under an +`NSOpenPanel` / `NSSavePanel` sheet, and `choose-in-blank|choose-in-srcdoc` open a chooser from `about:blank` and `srcdoc` +frames, which WKWebView judges by their inherited origin. +`WebView2Lifecycle-file-choose|file-cancel|file-download` verifies the engine's chooser request, selection and cancellation +events, and the bytes written by a completed Blob download. It intercepts the chooser with DevTools and suppresses the download UI, +so it does not qualify the native dialogs themselves or closing the window while one is open. + ## Adding a frontend 1. Implement the type in `include/webfront/frontend/` following the contract above and include it from `Frontend.hpp`. Keep platform headers behind the option's macro. diff --git a/docs/adr/ADR-020-services-systeme.md b/docs/adr/ADR-020-services-systeme.md index 745ebcd3..11295d76 100644 --- a/docs/adr/ADR-020-services-systeme.md +++ b/docs/adr/ADR-020-services-systeme.md @@ -5,11 +5,12 @@ | Version | Date | État | Auteur | Évolution | Révision Git | | --- | --- | --- | --- | --- | --- | | 1.0 | 2026-10-31 | Proposée | Ambroise Leclerc | Décision initiale : distinction hôte/client, préalables regroupés en épiques (#446 à #450), confinement des racines pendant la résolution et hypothèse de confiance face au déplacement d'un répertoire ouvert ou de la racine, autorisation attachée à l'emplacement déclaré, propriétaires admissibles des répertoires et des ancêtres, transport du navigateur système déclaré (`loopbackAttested`) plutôt que prouvé par un secret de lancement, jetons de lecture réutilisables liés à la connexion par un cookie, exposition des jetons et transport des lectures distantes, exception de confiance explicite, liaison HTTP par profil de navigateur avec cookies nommés par client, contenu actif neutralisé, transport déclaré et association de lancement du navigateur système, racines déclarées accessibles à tout script admis, services en composants facultatifs, sélection par l'utilisateur valant autorisation (poignées plutôt que chemins), backends natif, HTML et navigateur choisis par connexion, contenu des fichiers par HTTP à jeton ; état de l'art et inventaire des autres services. | À renseigner après intégration. | +| 1.1 | 2026-11-02 | Proposée, partiellement livrée | Ambroise Leclerc | Livraison partielle de l'étape 1 pour #451 (sélecteur de fichiers et téléchargements sous WebKitGTK, CEF, WKWebView et WebView2) ; #452 reste à faire. La section « État de l'étape 1 » distingue les preuves de validation par moteur et par révision ; `docs/FRONTENDS.md` précise les limites de couverture. | Branche `451-file-chooser-downloads` (PR #484), implémentation initiale `91049ab`, stockage privé WKWebView `52d8c68` | ## État et chronologie -**Proposée** le **2026-10-31**. Aucun code n'est livré avec cette version : elle fixe le cadre des services -système et leurs préalables (épiques #446 à #450) avant l'implémentation du premier d'entre eux (sélection de fichiers). Elle passera à « Acceptée » quand les +**Proposée** le **2026-10-31**. La version 1.0 ne livrait aucun code : elle fixe le cadre des services +système et leurs préalables (épiques #446 à #450) avant l'implémentation du premier d'entre eux (sélection de fichiers). La version 1.1 livre une partie de l'étape 1 (#451) ; la décision reste proposée. Elle passera à « Acceptée » quand les critères de la section dédiée seront démontrés. ## Contexte @@ -352,6 +353,23 @@ Le code vérifié le 2026-10-31 ne permet pas encore d'implémenter ces règles. | 4 | [#449](https://github.com/ambroise-leclerc/WebFront/issues/449) Stockage modifiable et livraison des services | [#460](https://github.com/ambroise-leclerc/WebFront/issues/460) stockage sous racines déclarées, confiné pendant la résolution (révision de l'ADR-002) ; [#461](https://github.com/ambroise-leclerc/WebFront/issues/461) paquet `@webfront/services` | sélecteur HTML et écritures (règles 2 à 4) | | 5 | [#450](https://github.com/ambroise-leclerc/WebFront/issues/450) Intégration native des frontends | [#462](https://github.com/ambroise-leclerc/WebFront/issues/462) exécuteur du thread d'interface, y compris le navigateur système ; [#463](https://github.com/ambroise-leclerc/WebFront/issues/463) fenêtre native et correspondance avec les connexions | backend natif seulement | +État de l'étape 1 (#451), preuves disponibles au 2026-11-03 : sélecteur et téléchargements implémentés dans les quatre +moteurs, avec des validations de provenance et de révision distinctes. Les résultats suivants ne valent que pour les +révisions indiquées ; ils ne qualifient pas automatiquement les changements ultérieurs. + +| Moteur | Source de validation | Révision et portée | +| --- | --- | --- | +| WebKitGTK | [CI Linux](https://github.com/ambroise-leclerc/WebFront/actions/runs/41628819255/job/125892906278) | `52d8c68` : suite CTest, dont sélection, annulation et téléchargements. | +| WebView2 | [CI Windows](https://github.com/ambroise-leclerc/WebFront/actions/runs/41628819255/job/125892850205) | `52d8c68` : suite CTest ; sélection interceptée par DevTools et téléchargements redirigés, sans qualification des dialogues natifs. Les 538 tests MSVC Release locaux rapportés dans la [PR #484](https://github.com/ambroise-leclerc/WebFront/pull/484) constituent une preuve locale distincte. | +| CEF | [CI étendue GCC et Clang](https://github.com/ambroise-leclerc/WebFront/actions/runs/41614144327) | `158ceb5`, antérieure au stockage privé WKWebView : scénarios CEF de fichiers et suite Jasmine. Les essais Linux locaux rapportés dans la PR sont distincts de cette exécution CI. | +| WKWebView | [CI macOS](https://github.com/ambroise-leclerc/WebFront/actions/runs/41614129707/job/125843186922) | `158ceb5`, antérieure au stockage privé ajouté dans `52d8c68` : scénarios automatisés de sélection, téléchargement, remplacement et fermeture sous un panneau. | +| WKWebView, panneaux réels | Essais manuels locaux rapportés dans la [PR #484](https://github.com/ambroise-leclerc/WebFront/pull/484) et `docs/FRONTENDS.md` | Réalisés avant `52d8c68` ; la révision exacte de chaque essai n'est pas consignée. Ces résultats ne qualifient pas le nouveau stockage privé. | + +À la révision `52d8c68`, le nouveau stockage privé WKWebView n'avait pas été exécuté sur macOS : la compilation CI avait +échoué avant les tests. Le correctif et les validations ultérieures sont consignés dans la PR #484. La qualification +des dialogues natifs reste partielle ; les injections de test ne la remplacent pas. `docs/FRONTENDS.md` détaille les +limites par moteur. #452 reste à faire et l'ADR reste proposée. + Après l'étape 4, le premier service (sélecteur HTML, poignées, import et export côté client) fera l'objet de sa propre épique ; les dialogues natifs suivront l'étape 5. `PUT`/`POST` ne sont pas des préalables : les écritures passent par des tableaux typés en morceaux ; leur ajout au serveur, utile aux très gros envois en flux et aux formulaires sans diff --git a/include/webfront/ContentPolicy.hpp b/include/webfront/ContentPolicy.hpp index c9822843..edf263c2 100644 --- a/include/webfront/ContentPolicy.hpp +++ b/include/webfront/ContentPolicy.hpp @@ -1,6 +1,7 @@ #pragma once #include +#include #include #include #include @@ -130,6 +131,21 @@ inline std::optional contentOrigin(std::string_view url, bool origi return serializedContentOrigin(parts->scheme, authority->host, *port, defaultPort); } +/** + * @brief The URL a `blob:` URL was minted for (`blob:http://host:port/id` gives `http://host:port/id`), or empty. + * + * A page downloads a generated `Blob` by navigating to such a URL; its content always belongs to the page's own origin, + * so the origin it names is the one the navigation policy must judge. + */ +inline std::string_view blobOriginUrl(std::string_view url) { + constexpr std::string_view scheme = "blob:"; + if (url.size() <= scheme.size() || !std::ranges::equal(url.substr(0, scheme.size()), scheme, [](char a, char b) { + return std::tolower(static_cast(a)) == b; + })) + return {}; + return url.substr(scheme.size()); +} + /** @brief Validated snapshot shared by the HTTP and embedded-frontend policy hooks. */ class BoundContentPolicy { public: @@ -147,6 +163,8 @@ class BoundContentPolicy { } bool allowsNavigation(std::string_view url) const { + if (const auto inner = blobOriginUrl(url); !inner.empty()) + url = inner; // A Blob of an admitted origin (a generated download) is that origin's own content. const auto origin = contentOrigin(url); return origin && (policy.allowAnyNavigation || *origin == applicationOrigin || contains(policy.navigationAllowedOrigins, *origin)); } diff --git a/include/webfront/frontend/CEF.hpp b/include/webfront/frontend/CEF.hpp index ad5f4ed0..7fe95c26 100644 --- a/include/webfront/frontend/CEF.hpp +++ b/include/webfront/frontend/CEF.hpp @@ -6,15 +6,19 @@ #include "CEFPaths.hpp" #include "Capture.hpp" #include "DefaultBrowser.hpp" +#include "Downloads.hpp" #include "Url.hpp" #include "Window.hpp" #include #include #include +#include #include #include #include +#include +#include #include #include #include @@ -493,7 +497,9 @@ class SimpleCEFClient : public CefClient, public CefLoadHandler, public CefRequestHandler, public CefContextMenuHandler, - public CefCommandHandler { + public CefCommandHandler, + public CefDownloadHandler, + public CefDialogHandler { public: explicit SimpleCEFClient(webfront::detail::BoundContentPolicy policy = webfront::detail::BoundContentPolicy{}, browser::Launcher launch = browser::launch) : contentPolicy(std::move(policy)), popupLauncher(launch) { } @@ -512,6 +518,82 @@ class SimpleCEFClient : public CefClient, return this; } + /// The Chrome runtime already shows its own file dialog and saves downloads; these two hooks only exist for tests. + /// Test injection: answers without a dialog (an empty list cancels). Unset keeps the engine's dialog. + std::function()> chooseFiles; + /// Test injection: a non-empty folder receives downloads without a "save as" dialog. + std::filesystem::path downloadDirectory; + frontend::detail::DownloadReservations downloadReservations; + std::mutex reservedMutex; + std::map reservedByDownload; // CefDownloadItem id -> destination + /// Test injection: called with the full path of each completed download. + std::function downloadFinished; + + CefRefPtr GetDownloadHandler() override { + return this; + } + CefRefPtr GetDialogHandler() override { + return this; + } + bool OnFileDialog(CefRefPtr, + FileDialogMode, + const CefString&, + const CefString&, + const std::vector&, + const std::vector&, + const std::vector&, + CefRefPtr callback) override { + if (!chooseFiles) + return false; + std::vector files; + try { + for (const auto& file : chooseFiles()) + files.emplace_back(file); + } catch (...) { + files.clear(); + } + if (files.empty()) + callback->Cancel(); + else + callback->Continue(files); + return true; + } + bool OnBeforeDownload(CefRefPtr, + CefRefPtr item, + const CefString& suggested, + CefRefPtr callback) override { + if (downloadDirectory.empty()) + return false; + try { + const auto result = downloadReservations.reserve(downloadDirectory, suggested.ToString()); + { + std::scoped_lock lock{reservedMutex}; + reservedByDownload[item->GetId()] = result; + } + callback->Continue(result.string(), false); + } catch (const std::filesystem::filesystem_error&) { + // Returning true without continuing cancels the download, including when all candidate names are occupied. + } + return true; + } + void OnDownloadUpdated(CefRefPtr, CefRefPtr item, CefRefPtr) override { + if (item->IsComplete() && downloadFinished) + downloadFinished(item->GetFullPath().ToString()); + if (item->IsInProgress()) + return; + // Complete, cancelled or interrupted: the name can be given to another download again. + std::filesystem::path reserved; + { + std::scoped_lock lock{reservedMutex}; + if (const auto found = reservedByDownload.find(item->GetId()); found != reservedByDownload.end()) { + reserved = std::move(found->second); + reservedByDownload.erase(found); + } + } + if (!reserved.empty()) + downloadReservations.release(reserved); + } + bool OnBeforeBrowse(CefRefPtr, CefRefPtr frame, CefRefPtr request, bool, bool) override { // Frame navigations and subresources remain outside this top-level navigation policy. return frame->IsMain() && !contentPolicy.allowsNavigation(request->GetURL().ToString()); diff --git a/include/webfront/frontend/Downloads.hpp b/include/webfront/frontend/Downloads.hpp new file mode 100644 index 00000000..5686f236 --- /dev/null +++ b/include/webfront/frontend/Downloads.hpp @@ -0,0 +1,130 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef __APPLE__ + #include +#endif + +namespace webfront::frontend::detail { + +/** A private staging directory beside a download target. */ +class DownloadStaging { +public: + explicit DownloadStaging(const std::filesystem::path& parent) { +#ifdef __APPLE__ + auto pattern = (parent / ".webfront-download-XXXXXX").string(); + std::vector buffer(pattern.begin(), pattern.end()); + buffer.push_back('\0'); + if (!::mkdtemp(buffer.data())) + throw std::filesystem::filesystem_error("Cannot create download staging", parent, std::error_code(errno, std::generic_category())); + directory = buffer.data(); +#else + std::random_device random; + for (int attempt = 0; attempt < 100; ++attempt) { + auto candidate = parent / (".webfront-download-" + std::to_string(random()) + "-" + std::to_string(random())); + std::error_code error; + if (std::filesystem::create_directory(candidate, error)) { + directory = std::move(candidate); + std::filesystem::permissions(directory, std::filesystem::perms::owner_all, std::filesystem::perm_options::replace, error); + if (error) { + std::filesystem::remove(directory); + throw std::filesystem::filesystem_error("Cannot secure download staging", directory, error); + } + return; + } + if (error && error != std::errc::file_exists) + throw std::filesystem::filesystem_error("Cannot create download staging", candidate, error); + } + throw std::filesystem::filesystem_error("Cannot allocate download staging", parent, std::make_error_code(std::errc::file_exists)); +#endif + } + DownloadStaging(const DownloadStaging&) = delete; + DownloadStaging& operator=(const DownloadStaging&) = delete; + ~DownloadStaging() { + std::error_code ignored; + std::filesystem::remove_all(directory, ignored); + } + [[nodiscard]] std::filesystem::path path() const { return directory / "download"; } + bool finish(const std::filesystem::path& target, bool replace) const { + std::error_code error; + if (replace) + std::filesystem::rename(path(), target, error); + else + std::filesystem::create_hard_link(path(), target, error); + return !error; + } +private: + std::filesystem::path directory; +}; + +/** + * @brief A path in `folder` that does not exist yet, for a download whose name the page suggested. + * + * Only the final component of the suggested name is kept (a page can neither choose a folder nor climb out of it), an + * empty name becomes "download", and an existing file is kept: "name", then "name (1).ext", "name (2).ext", and so on. + * `taken` additionally rejects the names that another download has reserved but not created yet. + * Throws `std::filesystem::filesystem_error` if all 10,000 candidates are occupied. + */ +inline std::filesystem::path +uniqueDownloadPath(const std::filesystem::path& folder, std::string_view suggested, const std::function& taken = {}) { + auto name = std::filesystem::path(std::string(suggested)).filename(); + if (name.empty() || name == "." || name == "..") + name = "download"; + auto result = folder / name; + std::error_code error; + const auto unavailable = [&](const std::filesystem::path& path) { + return std::filesystem::exists(path, error) || (taken && taken(path)); + }; + for (int index = 1; unavailable(result); ++index) { + if (index == 10'000) + throw std::filesystem::filesystem_error("No free download destination", folder / name, std::make_error_code(std::errc::file_exists)); + result = folder / (name.stem().string() + " (" + std::to_string(index) + ")" + name.extension().string()); + } + return result; +} + +/** + * @brief The destinations handed to downloads that have not created their file yet. + * + * A name is free only if no file has it and no running download was given it: two downloads that ask for the same name + * before either file exists get "name" and "name (1)", never the same path. Choosing and reserving happen under one lock; + * release a path when its download ends (finished, failed or cancelled) so that the name can be used again. + */ +class DownloadReservations { +public: + [[nodiscard]] std::filesystem::path reserve(const std::filesystem::path& folder, std::string_view suggested) { + std::scoped_lock lock{mutex}; + auto result = uniqueDownloadPath(folder, suggested, [&](const std::filesystem::path& path) { + return reserved.contains(path); + }); + reserved.insert(result); + return result; + } + + void release(const std::filesystem::path& path) { + std::scoped_lock lock{mutex}; + reserved.erase(path); + } + + [[nodiscard]] bool empty() const { + std::scoped_lock lock{mutex}; + return reserved.empty(); + } + +private: + mutable std::mutex mutex; + std::set reserved; +}; + +} // namespace webfront::frontend::detail diff --git a/include/webfront/frontend/WKWebView.hpp b/include/webfront/frontend/WKWebView.hpp index ba822366..ada3d979 100644 --- a/include/webfront/frontend/WKWebView.hpp +++ b/include/webfront/frontend/WKWebView.hpp @@ -3,14 +3,20 @@ #include "../ContentPolicy.hpp" #include "Action.hpp" #include "Capture.hpp" +#include "Downloads.hpp" #include "Url.hpp" #include "Window.hpp" #include #include #include +#include +#include +#include #include +#include #include +#include #include namespace webfront::frontend { @@ -23,6 +29,12 @@ struct WKWebViewOptions { WindowOptions window{}; /** @brief Keep the native window hidden and avoid activating the application. A WindowServer is still required. */ bool visible{true}; + /** @brief Test injection: answers `` without a dialog (an empty list cancels). Unset shows the system panel. */ + std::function()> chooseFiles{}; + /** @brief Test injection: a non-empty folder receives downloads without a save panel. */ + std::filesystem::path downloadDirectory{}; + /** @brief Test injection: called with the destination of each finished download. */ + std::function downloadFinished{}; }; } // namespace webfront::frontend @@ -277,6 +289,16 @@ struct Session { WKWebViewOptions options; webfront::detail::BoundContentPolicy contentPolicy; std::function navigationCancelled; + struct PendingDownload { + std::unique_ptr staging; + std::filesystem::path target; + bool reserved; + bool replace; + }; + frontend::detail::DownloadReservations reservations; + std::map downloadDestinations; // WKDownload -> its paths, until it ends. + /// What the answers of a system panel hold instead of `this`: AppKit may deliver one after the session is gone. + std::shared_ptr alive = std::make_shared(this); id app = nullptr, window = nullptr, view = nullptr, delegate = nullptr, timer = nullptr; id previousDelegate = nullptr, previousMenu = nullptr; long previousActivationPolicy = 0; @@ -287,6 +309,9 @@ struct Session { CaptureRegistration captureRegistration; ~Session() { + *alive = nullptr; + endSheets(); // Each open panel answers "cancel" now, while the view still exists to receive it. + abandonDownloads(); captureRegistration = {}; abandonCaptures(*captureTarget); if (timer) { @@ -325,6 +350,26 @@ struct Session { } } + /// Dismisses the panels attached to the window: their completion handlers run, so WebKit gets its answers. + void endSheets() noexcept { + if (!window) + return; + const auto sheets = send(window, "sheets"); + const auto count = send(sheets, "count"); + for (auto index = count; index > 0; --index) + send(window, "endSheet:", send(sheets, "objectAtIndex:", index - 1)); + } + + /// Cancels the downloads still running and removes the incomplete files they were writing. + void abandonDownloads() noexcept { + auto pending = std::exchange(downloadDestinations, {}); // Their failure callbacks must find nothing to settle. + for (const auto& [download, paths] : pending) { + send(download, "cancel:", static_cast(nullptr)); + if (paths.reserved) + reservations.release(paths.target); + } + } + void close() noexcept { closed = true; if (!running) @@ -499,12 +544,150 @@ struct Session { const auto destination = utf8(send(send(send(action, "request"), "URL"), "absoluteString")); if (contentPolicy.allowsNavigation(destination)) { policy = 1; // WKNavigationActionPolicyAllow + // and generated Blobs: WKNavigationActionPolicyDownload (macOS 11.3). + if (send(action, "respondsToSelector:", sel_registerName("shouldPerformDownload")) && send(action, "shouldPerformDownload")) + policy = 2; } else rejectNavigation("initial navigation was denied by contentPolicy"); }); decision(policy); // Exactly once, including after a C++ exception. } + /// The address a frame is judged by. A frame the page creates without a document of its own (no `src`, or `srcdoc`) + /// is `about:blank` / `about:srcdoc` and inherits its creator's origin, which is what the policy has to see. + static std::string effectiveFrameUrl(id frame) { + auto address = utf8(send(send(send(frame, "request"), "URL"), "absoluteString")); + if (!address.empty() && !address.starts_with("about:")) + return address; + const auto origin = send(frame, "securityOrigin"); + const auto protocol = utf8(send(origin, "protocol")); + const auto host = utf8(send(origin, "host")); + if (protocol.empty() || host.empty()) + return address; // An opaque origin (sandboxed frame): not the application's. + const auto port = send(origin, "port"); + return protocol + "://" + host + (port > 0 ? ":" + std::to_string(port) : "") + "/"; + } + + /// : the system panel as a sheet of the window, or the test injection. The handler runs exactly once. + void chooseFilesForPage(id parameters, id frame, void (^completion)(id)) noexcept { + id result = nullptr; // NSArray*; nil cancels. + bool deferred = false; + guard([&] { + // Only the frames the policy admits may open a chooser. + if (!contentPolicy.allowsNavigation(effectiveFrameUrl(frame))) + return; + if (options.chooseFiles) { + const auto files = options.chooseFiles(); + if (files.empty()) + return; + const auto urls = send(type("NSMutableArray"), "array"); + for (const auto& file : files) { + Object path(text(file)); + send(urls, "addObject:", send(type("NSURL"), "fileURLWithPath:", path.get())); + } + result = urls; + return; + } + const auto panel = send(type("NSOpenPanel"), "openPanel"); + send(panel, "setAllowsMultipleSelection:", send(parameters, "allowsMultipleSelection")); + // chooses a folder, and only a folder. + const auto directories = send(parameters, "allowsDirectories"); + send(panel, "setCanChooseDirectories:", directories); + send(panel, "setCanChooseFiles:", static_cast(!directories)); + auto handler = Block_copy(completion); + send(panel, "retain"); + void (^finished)(long) = ^(long response) { + handler(response == 1 ? send(panel, "URLs") : nullptr); // NSModalResponseOK + send(panel, "release"); + Block_release(handler); + }; + deferred = true; + send(panel, "beginSheetModalForWindow:completionHandler:", window, finished); + }); + if (!deferred) + completion(result); + } + + /// A WKDownload needs a destination that does not exist: the test folder, or the user's choice in a save panel. + void chooseDownloadDestination(id download, const std::string& suggested, void (^completion)(id)) noexcept { + id result = nullptr; // NSURL*; nil cancels the download. + bool deferred = false; + guard([&] { + if (!options.downloadDirectory.empty()) { + std::filesystem::create_directories(options.downloadDirectory); // WebKit needs the folder to exist. + std::filesystem::path destination; + try { + destination = reservations.reserve(options.downloadDirectory, suggested); + } catch (const std::filesystem::filesystem_error&) { + return; // No candidate is free: nil cancels this download without stopping the session. + } + std::unique_ptr staging; + try { + staging = std::make_unique(destination.parent_path()); + } catch (...) { + reservations.release(destination); + throw; + } + const auto temporary = staging->path(); + downloadDestinations[download] = {std::move(staging), destination, true, false}; + Object path(text(temporary.string())); + result = send(type("NSURL"), "fileURLWithPath:", path.get()); + return; + } + const auto panel = send(type("NSSavePanel"), "savePanel"); + Object name(text(std::filesystem::path(suggested).filename().string())); + send(panel, "setNameFieldStringValue:", name.get()); + auto handler = Block_copy(completion); + auto token = alive; // Not `this`: the window may close, and the session end, while the panel is open. + const id key = download; // By value: the panel answers after this lambda and its references are gone. + send(panel, "retain"); + void (^finished)(long) = ^(long response) { + id chosen = response == 1 ? send(panel, "URL") : nullptr; // NSModalResponseOK + if (chosen && !*token) + chosen = nullptr; // The session is gone: nobody could move the file afterwards. + try { + if (chosen) { + const std::filesystem::path target = utf8(send(chosen, "path")); + std::error_code code; + const bool replace = std::filesystem::exists(target, code); + if (code) + throw std::filesystem::filesystem_error("Cannot inspect download target", target, code); + auto staging = std::make_unique(target.parent_path()); + const auto temporary = staging->path(); + Object path(text(temporary.string())); + chosen = send(type("NSURL"), "fileURLWithPath:", path.get()); + (*token)->downloadDestinations[key] = {std::move(staging), target, false, replace}; + } + } catch (const std::filesystem::filesystem_error&) { + chosen = nullptr; // No temporary name is free: answer WebKit once, without crossing the AppKit block. + } + handler(chosen); + send(panel, "release"); + Block_release(handler); + }; + deferred = true; + send(panel, "beginSheetModalForWindow:completionHandler:", window, finished); + }); + if (!deferred) + completion(result); + } + + void downloadEnded(id download, bool completed) noexcept { + const auto found = downloadDestinations.find(download); + if (found == downloadDestinations.end()) + return; + const auto pending = std::move(found->second); + downloadDestinations.erase(found); + if (completed) + completed = pending.staging->finish(pending.target, pending.replace); + if (pending.reserved) + reservations.release(pending.target); + if (completed && options.downloadFinished) + guard([&] { + options.downloadFinished(pending.target.string()); + }); + } + void navigationResponse(id response, void (^decision)(long)) noexcept { long policy = 1; // WKNavigationResponsePolicyAllow guard([&] { @@ -517,8 +700,12 @@ struct Session { rejectNavigation("initial navigation response was denied by contentPolicy"); return; } - if (committed) + // A response the engine cannot display (an attachment, an archive) is saved, not shown. + if (committed) { + if (!send(response, "canShowMIMEType")) + policy = 2; // WKNavigationResponsePolicyDownload return; + } if (send(http, "respondsToSelector:", sel_registerName("statusCode"))) { const auto status = send(http, "statusCode"); if (!successfulHttpStatus(status)) { @@ -620,6 +807,48 @@ inline void addNavigationMethods(Class cls) { return nullptr; }, "@@:@@@@"); + // File chooser (WKUIDelegate) and downloads (WKNavigationDelegate, WKDownloadDelegate), issue #451. + addMethod( + cls, + "webView:runOpenPanelWithParameters:initiatedByFrame:completionHandler:", + +[](id self, SEL, id, id parameters, id frame, void (^completion)(id)) { + if (auto s = session(self)) + s->chooseFilesForPage(parameters, frame, completion); + else + completion(nullptr); + }, + "v@:@@@@?"); + const auto becameDownload = +[](id self, SEL, id, id, id download) { + send(download, "setDelegate:", self); + }; + addMethod(cls, "webView:navigationAction:didBecomeDownload:", becameDownload, "v@:@@@"); + addMethod(cls, "webView:navigationResponse:didBecomeDownload:", becameDownload, "v@:@@@"); + addMethod( + cls, + "download:decideDestinationUsingResponse:suggestedFilename:completionHandler:", + +[](id self, SEL, id download, id, id suggested, void (^completion)(id)) { + if (auto s = session(self)) + s->chooseDownloadDestination(download, utf8(suggested), completion); + else + completion(nullptr); + }, + "v@:@@@@?"); + addMethod( + cls, + "downloadDidFinish:", + +[](id self, SEL, id download) { + if (auto s = session(self)) + s->downloadEnded(download, true); + }, + "v@:@"); + addMethod( + cls, + "download:didFailWithError:resumeData:", + +[](id self, SEL, id download, id, id) { + if (auto s = session(self)) + s->downloadEnded(download, false); + }, + "v@:@@@"); addMethod(cls, "webView:didFinishNavigation:", navigationFinished, "v@:@@"); addMethod(cls, "webView:didCommitNavigation:", navigationCommitted, "v@:@@"); const auto failed = +[](id self, SEL, id, id, id error) { diff --git a/include/webfront/frontend/WebKitGTK.hpp b/include/webfront/frontend/WebKitGTK.hpp index 8ddedf77..bf0c80e4 100644 --- a/include/webfront/frontend/WebKitGTK.hpp +++ b/include/webfront/frontend/WebKitGTK.hpp @@ -5,6 +5,7 @@ #include "Action.hpp" #include "Capture.hpp" #include "DefaultBrowser.hpp" +#include "Downloads.hpp" #include "Url.hpp" #include "Window.hpp" #include "WebKitGTKPolicy.hpp" @@ -90,6 +91,7 @@ class Api { Object (*settings)(Object) = symbol("webkit_web_view_get_settings"); void (*load)(Object, const char*) = symbol("webkit_web_view_load_uri"); const char* (*viewUri)(Object) = symbol("webkit_web_view_get_uri"); + const char* (*viewTitle)(Object) = symbol("webkit_web_view_get_title"); void (*windowClose)(Object) = symbol("gtk_window_close"); void (*stop)(Object) = symbol("webkit_web_view_stop_loading"); Object (*navigationAction)(Object) = symbol("webkit_navigation_policy_decision_get_navigation_action"); @@ -113,6 +115,13 @@ class Api { const void* (*bytesData)(Object, std::size_t*) = symbol("g_bytes_get_data"); void (*bytesUnref)(Object) = symbol("g_bytes_unref"); void (*errorFree)(Error*) = symbol("g_error_free"); + // GLib resolves the folder from user-dirs.dirs (a user may have moved it), not only from the environment. + const char* (*userDirectory)(int) = symbol("g_get_user_special_dir"); // G_USER_DIRECTORY_DOWNLOAD = 2 + void (*downloadDestination)(Object, const char*) = symbol("webkit_download_set_destination"); + void (*downloadCancel)(Object) = symbol("webkit_download_cancel"); + const char* (*downloadGetDestination)(Object) = symbol("webkit_download_get_destination"); + void (*chooserSelect)(Object, const char* const*) = symbol("webkit_file_chooser_request_select_files"); + void (*chooserCancel)(Object) = symbol("webkit_file_chooser_request_cancel"); }; inline Api& api() { @@ -274,6 +283,22 @@ struct Session : FailureState { webfront::detail::BoundContentPolicy policy; WindowOptions windowOptions; std::function navigationCancelled; + /// Download folder; empty selects the user's XDG download folder, else the home folder. + std::filesystem::path downloadDirectory; + /// Test injection: answers without a dialog (an empty list cancels). Unset shows the system dialog. + std::function()> chooseFiles; + /// Test hook: called when the system file dialog is about to open. + std::function chooserOpened; + /// Test injection: called with the destination of each finished download. + std::function downloadFinished; + struct Download { + Api::Object object; + std::vector handlers; + std::filesystem::path reserved; // The destination given to this download, until it ends. + }; + DownloadReservations reservations; + std::vector downloads; + unsigned long downloadStartedHandler = 0; bool closed = false; bool initialNavigation = true; unsigned navigationTimer = 0; @@ -288,6 +313,7 @@ struct Session : FailureState { Session& operator=(const Session&) = delete; ~Session() { stopNavigationTimer(); + releaseDownloads(); releaseView(); destroyWindow(); release(network); @@ -312,6 +338,17 @@ struct Session : FailureState { a.stop(view); release(view); } + void releaseDownloads() { + if (downloadStartedHandler && network) + a.disconnect(network, std::exchange(downloadStartedHandler, 0)); + for (auto& download : downloads) { + for (auto handler : download.handlers) + a.disconnect(download.object, handler); + a.downloadCancel(download.object); + a.unref(download.object); + } + downloads.clear(); + } void destroyWindow() { if (!window) return; @@ -356,6 +393,7 @@ struct Session : FailureState { a.windowChild(window, view); configureSettings(); registerHandlers(); + downloadStartedHandler = a.connect(network, "download-started", reinterpret_cast(onDownloadStarted), this, nullptr, 0); captureTarget->view = view; captureTarget->pending.open(); captureRegistration = CaptureRegistration{captureProvider(captureTarget)}; @@ -381,6 +419,49 @@ struct Session : FailureState { on("load-failed", onLoadFailed, 2); on("web-process-terminated", onProcessTerminated); on("decide-policy", onDecidePolicy); + on("run-file-chooser", onRunFileChooser); + } + + std::filesystem::path destinationFolder() const { + if (!downloadDirectory.empty()) + return downloadDirectory; + if (const auto* folder = a.userDirectory(2); folder && *folder) + return folder; + if (const auto* home = std::getenv("HOME"); home && *home) { + std::error_code error; + const auto folder = std::filesystem::path(home) / "Downloads"; + if (std::filesystem::is_directory(folder, error)) + return folder; + return home; + } + return std::filesystem::temp_directory_path(); + } + std::filesystem::path reserveDestination(std::string_view suggested) { + const auto folder = destinationFolder(); + std::error_code error; + std::filesystem::create_directories(folder, error); // WebKitGTK writes into an existing folder only. + if (error) + throw std::filesystem::filesystem_error("WebKitGTK: cannot create the download folder", folder, error); + return reservations.reserve(folder, suggested); + } + void trackDownload(Api::Object download) { + Download entry{download, {}, {}}; + a.refSink(download); + entry.handlers.push_back(a.connect(download, "decide-destination", reinterpret_cast(onDecideDestination), this, nullptr, 0)); + entry.handlers.push_back(a.connect(download, "finished", reinterpret_cast(onDownloadFinished), this, nullptr, 0)); + entry.handlers.push_back(a.connect(download, "failed", reinterpret_cast(onDownloadFailed), this, nullptr, 0)); + downloads.push_back(std::move(entry)); + } + void forgetDownload(Api::Object download) { + const auto found = std::ranges::find(downloads, download, &Download::object); + if (found == downloads.end()) + return; + for (auto handler : found->handlers) + a.disconnect(download, handler); + if (!found->reserved.empty()) + reservations.release(found->reserved); + a.unref(found->object); + downloads.erase(found); } bool initialDocumentFailed() const { @@ -478,6 +559,60 @@ struct Session : FailureState { return 1; } } + static void onDownloadStarted(Api::Object, Api::Object download, Session* self) noexcept { + self->guard([self, download] { + self->trackDownload(download); + }); + } + static int onDecideDestination(Api::Object download, const char* suggested, Session* self) noexcept { + try { + const auto destination = self->reserveDestination(suggested ? suggested : ""); + if (const auto entry = std::ranges::find(self->downloads, download, &Download::object); entry != self->downloads.end()) + entry->reserved = destination; + else + self->reservations.release(destination); + api().downloadDestination(download, destination.c_str()); + } catch (...) { + api().downloadCancel(download); + } + return 1; + } + static void onDownloadFinished(Api::Object download, Session* self) noexcept { + std::string destination; + if (const auto* path = api().downloadGetDestination(download)) + destination = path; + self->guard([self, download, destination] { + self->forgetDownload(download); + if (self->downloadFinished) + self->downloadFinished(destination); + }); + } + static void onDownloadFailed(Api::Object download, Api::Error*, Session* self) noexcept { + self->guard([self, download] { + self->forgetDownload(download); + }); + } + static int onRunFileChooser(Api::Object, Api::Object request, Session* self) noexcept { + if (!self->chooseFiles) { + if (self->chooserOpened) + self->chooserOpened(); + return 0; // The system dialog, attached to the window by WebKitGTK. + } + try { + const auto files = self->chooseFiles(); + std::vector pointers; + for (const auto& file : files) + pointers.push_back(file.c_str()); + pointers.push_back(nullptr); + if (files.empty()) + api().chooserCancel(request); + else + api().chooserSelect(request, pointers.data()); + } catch (...) { + api().chooserCancel(request); + } + return 1; + } static int onNavigationTimeout(void* data) noexcept { auto* self = static_cast(data); self->navigationTimer = 0; diff --git a/include/webfront/frontend/WebKitGTKPolicy.hpp b/include/webfront/frontend/WebKitGTKPolicy.hpp index 37c6671e..436fb753 100644 --- a/include/webfront/frontend/WebKitGTKPolicy.hpp +++ b/include/webfront/frontend/WebKitGTKPolicy.hpp @@ -24,7 +24,7 @@ struct PolicyRequest { inline bool navigationSchemeAllowed(const char* uri) { if (!uri) return false; - if (webfront::detail::contentOrigin(uri)) + if (webfront::detail::contentOrigin(uri) || webfront::detail::contentOrigin(webfront::detail::blobOriginUrl(uri))) return true; return std::string_view(uri) == "about:blank" || std::string_view(uri) == "about:srcdoc"; } diff --git a/include/webfront/testing/Process.hpp b/include/webfront/testing/Process.hpp index 87ea73a1..56edd0df 100644 --- a/include/webfront/testing/Process.hpp +++ b/include/webfront/testing/Process.hpp @@ -245,6 +245,8 @@ inline ProcessResult runProcessWindows(const ProcessSpec& spec, const std::atomi HANDLE inherited[3] = {input.handle, outWrite.handle, errWrite.handle}; SIZE_T attributeSize = 0; ::InitializeProcThreadAttributeList(nullptr, 1, 0, &attributeSize); + if (attributeSize == 0) + throw std::runtime_error("Cannot determine the process attribute size"); std::vector attributeStorage(attributeSize); auto* attributes = reinterpret_cast(attributeStorage.data()); if (!::InitializeProcThreadAttributeList(attributes, 1, 0, &attributeSize)) diff --git a/test/cmake/CheckFrontendConsumer.cmake b/test/cmake/CheckFrontendConsumer.cmake index 4ba64241..259f2342 100644 --- a/test/cmake/CheckFrontendConsumer.cmake +++ b/test/cmake/CheckFrontendConsumer.cmake @@ -2,9 +2,23 @@ cmake_minimum_required(VERSION 3.31) if(NOT ROOT OR NOT WORK_DIR) message(FATAL_ERROR "ROOT and WORK_DIR are required") endif() +set(configure_args) +if(TEST_GENERATOR) + list(APPEND configure_args -G "${TEST_GENERATOR}") +endif() +if(TEST_CXX_COMPILER) + list(APPEND configure_args "-DCMAKE_CXX_COMPILER=${TEST_CXX_COMPILER}") +endif() +if(TEST_GENERATOR_PLATFORM) + list(APPEND configure_args -A "${TEST_GENERATOR_PLATFORM}") +endif() +if(TEST_GENERATOR_TOOLSET) + list(APPEND configure_args -T "${TEST_GENERATOR_TOOLSET}") +endif() foreach(probe ON OFF) foreach(full_project OFF ON) - execute_process(COMMAND "${CMAKE_COMMAND}" --fresh + message(STATUS "Consumer configure: probe=${probe}, full_project=${full_project}") + execute_process(COMMAND "${CMAKE_COMMAND}" --fresh ${configure_args} -S "${ROOT}/test/cmake/frontend-consumer" -B "${WORK_DIR}/${probe}-${full_project}" "-DROOT=${ROOT}" "-DPROBE=${probe}" "-DFULL_PROJECT=${full_project}" "-DCPM_MODULE=${CPM_MODULE}" ${DEPENDENCY_ARGS} @@ -12,6 +26,12 @@ foreach(probe ON OFF) if(NOT result EQUAL 0) message(FATAL_ERROR "Consumer native probe ${probe}: ${output}${error}") endif() + if(TEST_GENERATOR) + file(STRINGS "${WORK_DIR}/${probe}-${full_project}/CMakeCache.txt" generator REGEX "^CMAKE_GENERATOR:INTERNAL=") + if(NOT generator STREQUAL "CMAKE_GENERATOR:INTERNAL=${TEST_GENERATOR}") + message(FATAL_ERROR "Consumer lost the parent generator: ${generator}") + endif() + endif() if(NOT probe AND NOT "${output}${error}" MATCHES "parent_app_native will open the default browser instead") message(FATAL_ERROR "Consumer fallback must explain the default browser: ${output}${error}") endif() @@ -27,7 +47,8 @@ foreach(probe ON OFF) endforeach() # Explicit OFF is distinct from a probe that cannot find the dependency. -execute_process(COMMAND "${CMAKE_COMMAND}" --fresh +message(STATUS "Consumer configure: explicit OFF") +execute_process(COMMAND "${CMAKE_COMMAND}" --fresh ${configure_args} -S "${ROOT}/test/cmake/frontend-consumer" -B "${WORK_DIR}/explicit-off" "-DROOT=${ROOT}" -DPROBE=OFF -DFULL_PROJECT=ON "-DCPM_MODULE=${CPM_MODULE}" -DWEBFRONT_EMBED_CONSUMER=OFF ${DEPENDENCY_ARGS} @@ -37,7 +58,8 @@ if(NOT result EQUAL 0 OR NOT "${output}${error}" MATCHES "explicitly disabled") endif() # A support module's final option is what other directories observe. -execute_process(COMMAND "${CMAKE_COMMAND}" --fresh +message(STATUS "Consumer configure: support option change") +execute_process(COMMAND "${CMAKE_COMMAND}" --fresh ${configure_args} -S "${ROOT}/test/cmake/frontend-consumer" -B "${WORK_DIR}/support-change" "-DROOT=${ROOT}" -DPROBE=ON -DMUTATE_OTHER=ON RESULT_VARIABLE result OUTPUT_VARIABLE output ERROR_VARIABLE error) @@ -46,7 +68,8 @@ if(NOT result EQUAL 0) endif() # A consumer opts in to one of WebFront's test options only by its prefixed name (#412). -execute_process(COMMAND "${CMAKE_COMMAND}" --fresh +message(STATUS "Consumer configure: prefixed coverage option") +execute_process(COMMAND "${CMAKE_COMMAND}" --fresh ${configure_args} -S "${ROOT}/test/cmake/frontend-consumer" -B "${WORK_DIR}/consumer-coverage" "-DROOT=${ROOT}" -DPROBE=ON -DFULL_PROJECT=ON "-DCPM_MODULE=${CPM_MODULE}" -DWEBFRONT_ENABLE_COVERAGE=ON ${DEPENDENCY_ARGS} diff --git a/test/unit/CMakeLists.txt b/test/unit/CMakeLists.txt index 6fe85792..b9c3373d 100644 --- a/test/unit/CMakeLists.txt +++ b/test/unit/CMakeLists.txt @@ -26,7 +26,7 @@ endif() set(TESTS_LIST) list(APPEND TESTS_LIST WebKitGTKPolicyTests.cpp ContentPolicyTests.cpp HTTPServerTests.cpp HTTPEncodingTests.cpp GzipExecutorTests.cpp AcceptEncodingTests.cpp GzipTests.cpp ModuleHTTPServerTests.cpp EncodingsTests.cpp WebSocketTests.cpp LoggerTests.cpp MimeTypeTests.cpp) list(APPEND TESTS_LIST FormsTests.cpp ReactStoreTests.cpp DomDocumentTests.cpp DomBatchTests.cpp JSFunctionTests.cpp TypeErasedFunctionTests.cpp MessagesTests.cpp IndexFSTests.cpp) -list(APPEND TESTS_LIST FileSystemTests.cpp NativeFSTests.cpp) +list(APPEND TESTS_LIST FileSystemTests.cpp NativeFSTests.cpp DownloadsTests.cpp) list(APPEND TESTS_LIST DefaultFSTests.cpp StdnetShutdownTests.cpp SafePathTests.cpp UISubscribersTests.cpp) list(APPEND TESTS_LIST BroadcastTests.cpp WebFrontTests.cpp WebLinkTests.cpp CEFPathsTests.cpp CEFMacrosTests.cpp) list(APPEND TESTS_LIST DeveloperTests.cpp WfDriverTests.cpp AutomationTests.cpp AutomationChannelTests.cpp AutomationStdioTests.cpp JasmineConsumerTests.cpp HostTests.cpp LifeTests.cpp StructuredShutdownTests.cpp JsFunctionSenderTests.cpp ApplicationTaskTests.cpp) @@ -296,6 +296,10 @@ add_test(NAME FrontendConsumerConfiguration -DWORK_DIR=${CMAKE_CURRENT_BINARY_DIR}/frontend-consumer -DCPM_MODULE=${CPM_DOWNLOAD_LOCATION} "-DDEPENDENCY_ARGS=${_consumer_dependency_args}" + "-DTEST_GENERATOR=${CMAKE_GENERATOR}" + "-DTEST_CXX_COMPILER=${CMAKE_CXX_COMPILER}" + "-DTEST_GENERATOR_PLATFORM=${CMAKE_GENERATOR_PLATFORM}" + "-DTEST_GENERATOR_TOOLSET=${CMAKE_GENERATOR_TOOLSET}" -P ${PROJECT_SOURCE_DIR}/test/cmake/CheckFrontendConsumer.cmake) set_tests_properties(FrontendConsumerConfiguration PROPERTIES TIMEOUT 120) # Read the actual target's launcher at generation time, including an explicitly diff --git a/test/unit/ContentPolicyTests.cpp b/test/unit/ContentPolicyTests.cpp index 06f0d6d3..b82e890f 100644 --- a/test/unit/ContentPolicyTests.cpp +++ b/test/unit/ContentPolicyTests.cpp @@ -70,6 +70,14 @@ SCENARIO("Content policy compares complete HTTP origins") { REQUIRE(policy.allowsBridge(std::nullopt)); REQUIRE(policy.allowsNavigation("http://127.0.0.1:9002/next?x=1#fragment")); } + THEN("a Blob of the application's origin (a generated download) is allowed, one of another origin is not") { + REQUIRE(policy.allowsNavigation("blob:http://127.0.0.1:9002/0b1f2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d")); + REQUIRE(policy.allowsNavigation("BLOB:http://127.0.0.1:9002/id")); + for (const auto* url : {"blob:https://example.com/id", "blob:null/id", "blob:", "blob:http://127.0.0.1:9002@evil/id", "blob:blob:http://127.0.0.1:9002/id"}) { + INFO(url); + REQUIRE_FALSE(policy.allowsNavigation(url)); + } + } THEN("other origins and ambiguous syntax fail closed") { for (const auto* origin : invalidBridgeOrigins) { INFO(origin); diff --git a/test/unit/DownloadsTests.cpp b/test/unit/DownloadsTests.cpp new file mode 100644 index 00000000..ffefe481 --- /dev/null +++ b/test/unit/DownloadsTests.cpp @@ -0,0 +1,161 @@ +#include +#include + +#include +#include +#include +#include +#include +#include + +using webfront::frontend::detail::DownloadReservations; +using webfront::frontend::detail::uniqueDownloadPath; + +SCENARIO("Download staging preserves a destination created while a download runs") { + std::random_device random; + const auto folder = std::filesystem::temp_directory_path() / ("webfront-download-staging-unit-" + std::to_string(random())); + REQUIRE(std::filesystem::create_directory(folder)); + const auto target = folder / "target.txt"; + GIVEN("another process creates the destination during the download") { + WHEN("the completed download is installed without permission to replace") { + std::filesystem::path stagingPath; + bool installed = false; + { + webfront::frontend::detail::DownloadStaging staging(folder); + stagingPath = staging.path(); + std::ofstream(stagingPath) << "download"; + std::ofstream(target) << "other file"; + installed = staging.finish(target, false); + } + THEN("the other file survives and the private staging directory is removed") { + REQUIRE_FALSE(installed); + std::ifstream stream(target); + REQUIRE(std::string(std::istreambuf_iterator(stream), {}) == "other file"); + REQUIRE_FALSE(std::filesystem::exists(stagingPath.parent_path())); + } + } + } + GIVEN("the destination is free") { + WHEN("the completed download is installed") { + std::filesystem::path stagingPath; + bool installed = false; + { + webfront::frontend::detail::DownloadStaging staging(folder); + stagingPath = staging.path(); + std::ofstream(stagingPath) << "completed"; + installed = staging.finish(target, false); + } + THEN("the destination holds the completed bytes and staging is removed") { + REQUIRE(installed); + std::ifstream completed(target); + REQUIRE(std::string(std::istreambuf_iterator(completed), {}) == "completed"); + REQUIRE_FALSE(std::filesystem::exists(stagingPath.parent_path())); + } + } + } + std::filesystem::remove(target); + std::filesystem::remove(folder); +} + +SCENARIO("A download name suggested by a page stays inside the download folder") { + const auto folder = std::filesystem::temp_directory_path() / "webfront-downloads-unit"; + std::filesystem::remove_all(folder); + std::filesystem::create_directories(folder); + GIVEN("names that try to leave the folder or name nothing") { + THEN("only the last component is kept, and an empty name becomes \"download\"") { + REQUIRE(uniqueDownloadPath(folder, "report.txt") == folder / "report.txt"); + REQUIRE(uniqueDownloadPath(folder, "../../etc/passwd") == folder / "passwd"); + REQUIRE(uniqueDownloadPath(folder, "a/b/c.bin") == folder / "c.bin"); + for (const auto* name : {"", ".", "..", "dir/.."}) { + INFO(name); + REQUIRE(uniqueDownloadPath(folder, name) == folder / "download"); + } + } + } + GIVEN("files that already exist") { + std::ofstream(folder / "report.txt") << "1"; + THEN("the name is numbered rather than overwritten") { + REQUIRE(uniqueDownloadPath(folder, "report.txt") == folder / "report (1).txt"); + std::ofstream(folder / "report (1).txt") << "2"; + REQUIRE(uniqueDownloadPath(folder, "report.txt") == folder / "report (2).txt"); + } + } + GIVEN("every candidate is reserved by another download") { + THEN("exhaustion is reported instead of returning an occupied path") { + std::size_t probes = 0; + REQUIRE_THROWS_AS(uniqueDownloadPath(folder, + "report.txt", + [&](const auto&) { + ++probes; + return true; + }), + std::filesystem::filesystem_error); + REQUIRE(probes == 10'000); + } + } + GIVEN("only the last candidate is available") { + THEN("that candidate can still be used") { + REQUIRE(uniqueDownloadPath(folder, + "report.txt", + [&](const auto& path) { + return path.filename() != "report (9999).txt"; + }) + == folder / "report (9999).txt"); + } + } + std::filesystem::remove_all(folder); +} + +SCENARIO("Downloads that ask for the same name before their files exist get different destinations") { + const auto folder = std::filesystem::temp_directory_path() / "webfront-downloads-reserved"; + std::filesystem::remove_all(folder); + std::filesystem::create_directories(folder); + DownloadReservations reservations; + GIVEN("two downloads suggesting report.txt, neither file created yet") { + const auto first = reservations.reserve(folder, "report.txt"); + const auto second = reservations.reserve(folder, "report.txt"); + THEN("the second one is numbered") { + REQUIRE(first == folder / "report.txt"); + REQUIRE(second == folder / "report (1).txt"); + REQUIRE(reservations.reserve(folder, "report.txt") == folder / "report (2).txt"); + } + AND_WHEN("the first download ends without creating a file") { + reservations.release(first); + THEN("its name is available again") { + REQUIRE(reservations.reserve(folder, "report.txt") == first); + } + } + AND_WHEN("a file appears under a released name") { + reservations.release(first); + std::ofstream(first) << "done"; + THEN("it is the existing file that keeps the name taken") { + REQUIRE(reservations.reserve(folder, "report.txt") == folder / "report (2).txt"); + } + } + } + GIVEN("many threads asking for the same name at once") { + constexpr std::size_t threads = 16; + std::vector granted(threads); + std::vector workers; + for (std::size_t index = 0; index < threads; ++index) + workers.emplace_back([&, index] { + granted[index] = reservations.reserve(folder, "same.bin"); + }); + for (auto& worker : workers) + worker.join(); + THEN("every destination is distinct") { + REQUIRE(std::set(granted.begin(), granted.end()).size() == threads); + } + } + GIVEN("released reservations") { + const auto path = reservations.reserve(folder, "once.txt"); + reservations.release(path); + THEN("nothing stays reserved") { + DownloadReservations other; + const auto again = other.reserve(folder, "x"); + other.release(again); + REQUIRE(other.empty()); + } + } + std::filesystem::remove_all(folder); +} diff --git a/test/unit/WebKitGTKPolicyTests.cpp b/test/unit/WebKitGTKPolicyTests.cpp index aa4267c7..5ddaac76 100644 --- a/test/unit/WebKitGTKPolicyTests.cpp +++ b/test/unit/WebKitGTKPolicyTests.cpp @@ -25,7 +25,8 @@ SCENARIO("WebKitGTK applies navigation policy without toolkit objects") { { PolicyEvent::navigation, "about:blank", false, 0, false, PolicyDecision::allow}, { PolicyEvent::navigation, "about:srcdoc", false, 0, false, PolicyDecision::allow}, { PolicyEvent::navigation, "data:text/html,hello", false, 0, false, PolicyDecision::cancel}, - { PolicyEvent::navigation, "blob:http://127.0.0.1:9002/id", false, 0, false, PolicyDecision::cancel}, + { PolicyEvent::navigation, "blob:http://127.0.0.1:9002/id", false, 0, false, PolicyDecision::allow}, + { PolicyEvent::navigation, "blob:null/id", false, 0, false, PolicyDecision::cancel}, { PolicyEvent::navigation, "file:///etc/passwd", false, 0, false, PolicyDecision::cancel}, { PolicyEvent::navigation, nullptr, false, 0, false, PolicyDecision::cancel}, { PolicyEvent::response, "https://other.example/page", false, 403, true, PolicyDecision::allow}, diff --git a/test/web/CEFFileServices.cpp b/test/web/CEFFileServices.cpp new file mode 100644 index 00000000..531b22d7 --- /dev/null +++ b/test/web/CEFFileServices.cpp @@ -0,0 +1,156 @@ +// Qualification of and downloads in the CEF frontend (issue #451): the chooser is answered by the +// client's injection point and opened by a real mouse click sent to the engine; the download goes to a private folder. +#include +#include +#include + +#include +#include +#include +#include + +#include + +namespace { +void require(bool value, const char* message) { + if (!value) + throw std::runtime_error(message); +} + +struct Scenario { + std::string mode; // download | choose | cancel + std::filesystem::path folder; + std::filesystem::path fixture; + std::string title; + std::string downloaded; + bool asked = false; +}; +Scenario scenario; + +class Client : public webfront::cef::SimpleCEFClient { +public: + Client() : SimpleCEFClient(webfront::detail::BoundContentPolicy{}) { + chooseFiles = [] { + scenario.asked = true; + return scenario.mode == "choose" ? std::vector{scenario.fixture.string()} : std::vector{}; + }; + downloadDirectory = scenario.folder; + downloadFinished = [this](const std::string& path) { + scenario.downloaded = path; + finish(); + }; + } + void OnTitleChange(CefRefPtr browser, const CefString& title) override { + scenario.title = title.ToString(); + window = browser; + if (scenario.title == "ready" && scenario.mode != "download") + CefPostDelayedTask(TID_UI, new Click(this, 40), 500); + else if (scenario.title.starts_with("picked:") || scenario.title == "cancelled") + finish(); + } + void OnAfterCreated(CefRefPtr browser) override { + SimpleCEFClient::OnAfterCreated(browser); + window = browser; + CefPostDelayedTask(TID_UI, new Deadline(this), 20'000); + } + void close() { + if (window) + window->GetHost()->CloseBrowser(true); + } + void finish() { + if (finishing) + return; + finishing = true; + close(); + } + +private: + CefRefPtr window; + bool finishing = false; + +public: + void clickChooser() { + // Runtime.evaluate with userGesture: the page's own click, counted as a user gesture by the engine. + auto params = CefDictionaryValue::Create(); + params->SetString("expression", "document.getElementById('picker').click()"); + params->SetBool("userGesture", true); + window->GetHost()->ExecuteDevToolsMethod(0, "Runtime.evaluate", params); + } + // The window may not take input right away: click again until the chooser was requested. + struct Click : CefTask { + Click(Client* owner, int left) : client(owner), remaining(left) {} + void Execute() override { + if (scenario.asked || remaining == 0) + return; + client->clickChooser(); + CefPostDelayedTask(TID_UI, new Click(client.get(), remaining - 1), 250); + } + CefRefPtr client; + int remaining; + IMPLEMENT_REFCOUNTING(Click); + }; + struct Deadline : CefTask { + explicit Deadline(Client* owner) : client(owner) {} + void Execute() override { + client->close(); + } + CefRefPtr client; + IMPLEMENT_REFCOUNTING(Deadline); + }; + IMPLEMENT_REFCOUNTING(Client); +}; + +struct Frontend { + static constexpr auto action = webfront::frontend::Action::closeServerAfterOpen; + static void initialize() { + webfront::frontend::CEFFrontend::initialize(); + } + static void open(std::string_view port, std::string_view page) { + open("127.0.0.1", port, page, {}); + } + static void open(std::string_view address, std::string_view port, std::string_view page, const webfront::ContentPolicy& policy) { + webfront::cef::detail::openWindow(webfront::frontend::detail::applicationUrl(address, port, page), + webfront::detail::BoundContentPolicy{webfront::detail::applicationOrigin(address, port), policy}, + new Client); + } +}; +} // namespace + +int main(int argc, char** argv) { + try { + webfront::detail::ensureFrontendInitialized(); // CEF subprocesses run this program too and end here. + require(argc == 2, "usage: cef_file_services download|choose|cancel"); + scenario.mode = argv[1]; + scenario.folder = std::filesystem::temp_directory_path() / ("webfront-cef-" + scenario.mode + "-" + std::to_string(getpid())); + std::filesystem::remove_all(scenario.folder); + std::filesystem::create_directories(scenario.folder); + scenario.fixture = scenario.folder / "fixture.txt"; + std::ofstream(scenario.fixture) << "chosen by the test"; + using FS = webfront::fs::Multi; + webfront::BasicWFWithFrontend app(webfront::WebFrontConfig{.documentRoot = std::filesystem::current_path()}); + app.show("file-services.html?" + (scenario.mode == "download" ? std::string("download") : std::string("choose"))); + if (scenario.mode == "download") { + require(!scenario.downloaded.empty(), "The download did not finish"); + // The engine neutralizes the page's "../webfront-download.txt" itself (Chrome writes "_webfront-download.txt"). + require(std::filesystem::path(scenario.downloaded).parent_path() == scenario.folder, + ("The download left its folder: " + scenario.downloaded).c_str()); + require(std::filesystem::path(scenario.downloaded).filename().string().ends_with("webfront-download.txt"), "The download lost its name"); + std::ifstream stream(scenario.downloaded, std::ios::binary); + require(stream.is_open(), "The downloaded file could not be opened"); + constexpr std::string_view expected = "downloaded by WebFront"; + std::string contents(expected.size() + 1, '\0'); + stream.read(contents.data(), static_cast(contents.size())); + contents.resize(static_cast(stream.gcount())); + require(contents == expected, "The downloaded file has the wrong content"); + } else { + require(scenario.asked, ("The file chooser was not requested; title=" + scenario.title).c_str()); + require(scenario.title == (scenario.mode == "choose" ? "picked:chosen by the test" : "cancelled"), + ("Unexpected page state: " + scenario.title).c_str()); + } + std::filesystem::remove_all(scenario.folder); + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/test/web/CMakeLists.txt b/test/web/CMakeLists.txt index b5f981b9..2aa56e02 100644 --- a/test/web/CMakeLists.txt +++ b/test/web/CMakeLists.txt @@ -182,6 +182,11 @@ if(_browser_tests_available) FRONTEND "${WEBFRONT_WEBTEST_FRONTEND}" TIMEOUT 30 SPECS "${CMAKE_CURRENT_SOURCE_DIR}/jasmine-consumer/capture.spec.js" ARGS "${CMAKE_CURRENT_SOURCE_DIR}/jasmine-consumer") + # File services of the engine (issue #451), shared by every embedded frontend. + webfront_add_jasmine_test(NAME ConsumerJasmine-file-services TARGET jasmine_consumer + FRONTEND "${WEBFRONT_WEBTEST_FRONTEND}" TIMEOUT 30 + SPECS "${CMAKE_CURRENT_SOURCE_DIR}/jasmine-consumer/file-services.spec.js" + ARGS "${CMAKE_CURRENT_SOURCE_DIR}/jasmine-consumer") add_test(NAME ConsumerJasmineCaptures COMMAND "${CMAKE_COMMAND}" "-DDIRECTORY=${CMAKE_CURRENT_BINARY_DIR}/webfront-jasmine/ConsumerJasmine-capture/captures" -P "${PROJECT_SOURCE_DIR}/test/cmake/CheckConsumerCaptures.cmake") @@ -233,6 +238,17 @@ if(WEBFRONT_EMBED_CEF AND CMAKE_SYSTEM_NAME STREQUAL "Linux") add_test(NAME CEFContentPolicy COMMAND "${_policy_xvfb}" -a $) webfront_set_browser_test_properties(CEFContentPolicy "${CMAKE_CURRENT_SOURCE_DIR}" 45) endif() + # File chooser and downloads (issue #451). + add_executable(cef_file_services CEFFileServices.cpp) + target_link_libraries(cef_file_services PRIVATE WebFront_test_hardening WebFront WebFront_warnings WebFront_options) + webfront_setup_frontends_for_target(cef_file_services) + add_dependencies(webtest cef_file_services) + if(_policy_xvfb) + foreach(mode download choose cancel) + add_test(NAME CEFFileServices-${mode} COMMAND "${_policy_xvfb}" -a $ ${mode}) + webfront_set_browser_test_properties(CEFFileServices-${mode} "${CMAKE_CURRENT_SOURCE_DIR}" 60) + endforeach() + endif() endif() if(_browser_tests_available) diff --git a/test/web/WKWebViewLifecycle.cpp b/test/web/WKWebViewLifecycle.cpp index 96dd00fd..3ac1547c 100644 --- a/test/web/WKWebViewLifecycle.cpp +++ b/test/web/WKWebViewLifecycle.cpp @@ -1,10 +1,15 @@ #include "../driver/TestFrontend.hpp" #include +#include +#include +#include #include #include +#include #include #include +#include #include #include @@ -86,7 +91,7 @@ void nativeClose(bool quit) { if (quit) send(app, "terminate:", static_cast(nullptr)); else - send(session.window, "performClose:", static_cast(nullptr)); + send(session.window, "close"); require(session.closed, "Native close/Quit did not close the session"); session.run(); } @@ -268,6 +273,226 @@ void agentApplication() { require(send(app, "activationPolicy") == previousPolicy, "Session did not restore the host activation policy"); } +std::string readFile(const std::filesystem::path& path) { + std::ifstream stream(path, std::ios::binary); + return {std::istreambuf_iterator(stream), {}}; +} + +/// Opens a page with the file-service test injections of WKWebViewOptions, which a scenario fills in before show(). +struct ScenarioFrontend : Frontend { + static inline std::function configure; + static inline std::function started; + + static void open(std::string_view port, std::string_view page) { + initialize(); + Object pool(send(type("NSAutoreleasePool"), "new")); + webfront::frontend::WKWebViewOptions options{.visible = webfront::testdriver::diagnosticWindows()}; + if (configure) + configure(options); + Session session(webfront::frontend::detail::applicationUrl("127.0.0.1", port, page), options); + session.create(); + session.start(); + if (started) + started(session); + session.run(); + } +}; +using ScenarioApp = webfront::WebFrontWithFrontend; + +/// Ends the AppKit loop from a native callback, as the Quit menu item does. +void quitApplication() { + send(send(type("NSApplication"), "sharedApplication"), "terminate:", static_cast(nullptr)); +} + +void resetScenario() { + ScenarioFrontend::configure = nullptr; + ScenarioFrontend::started = nullptr; +} + +void download() { + const auto folder = std::filesystem::temp_directory_path() / ("webfront-wk-download-" + std::to_string(getpid())); + std::filesystem::remove_all(folder); + std::string destination; + bool done = false; + ScenarioFrontend::configure = [&](webfront::frontend::WKWebViewOptions& options) { + options.downloadDirectory = folder; // Created by the frontend when the download starts. + options.downloadFinished = [&](const std::string& path) { + destination = path; + done = true; + quitApplication(); + }; + }; + ScenarioApp app(webfront::WebFrontConfig{.documentRoot = std::filesystem::current_path()}); + app.show("file-services.html?download"); + resetScenario(); + require(done, "The download did not finish"); + // The suggested name "../webfront-download.txt" must never leave the download folder. WebKit already neutralizes the + // separators before the frontend sees the name (it arrives as "_webfront-download.txt"), so the folder is what is checked. + const std::filesystem::path saved(destination); + require(saved.parent_path() == folder && saved.filename().string().ends_with("webfront-download.txt"), ("Unexpected download destination: " + destination).c_str()); + require(readFile(destination) == "downloaded by WebFront", "The downloaded file has the wrong content"); + std::filesystem::remove_all(folder); +} + +void chooseFile(bool cancel, const char* page = "file-services.html?choose", const char* click = "document.getElementById('picker').click()") { + const auto fixture = std::filesystem::temp_directory_path() / ("webfront-wk-chooser-" + std::to_string(getpid()) + ".txt"); + std::ofstream(fixture) << "chosen by the test"; + bool asked = false; + static std::string finalTitle; + finalTitle.clear(); + ScenarioFrontend::configure = [&](webfront::frontend::WKWebViewOptions& options) { + options.chooseFiles = [&]() -> std::vector { + asked = true; + return cancel ? std::vector{} : std::vector{fixture.string()}; + }; + }; + static std::string clickScript; + clickScript = std::string("document.title === 'ready' && !window.clicked && (window.clicked = true, ") + click + ")"; + ScenarioFrontend::started = [](Session& session) { + // A chooser needs a user gesture, and evaluateJavaScript counts as one. The page reports through its title. + Session* live = &session; + auto tick = ^(id timer) { + const auto title = utf8(send(live->view, "title")); + if (title.starts_with("picked:") || title == "cancelled") { + finalTitle = title; + send(timer, "invalidate"); + quitApplication(); + return; + } + Object script(text(clickScript)); + send(live->view, "evaluateJavaScript:completionHandler:", script.get(), static_cast(nullptr)); + }; + send(type("NSTimer"), "scheduledTimerWithTimeInterval:repeats:block:", 0.1, static_cast(true), tick); + }; + ScenarioApp app(webfront::WebFrontConfig{.documentRoot = std::filesystem::current_path()}); + app.show(page); + resetScenario(); + std::filesystem::remove(fixture); + require(asked, "The file chooser was not requested"); + const std::string expected = cancel ? "cancelled" : "picked:chosen by the test"; + require(finalTitle == expected, ("Unexpected page state after the chooser: " + finalTitle).c_str()); +} +void chooseOne() { + chooseFile(false); +} +void chooseCancel() { + chooseFile(true); +} +/// A frame created by the page without an address inherits its origin: its chooser is the application's own. +void chooseInBlankFrame() { + chooseFile(false, "file-services.html?blank", "document.querySelector('iframe').contentDocument.getElementById('picker').click()"); +} +void chooseInSrcdocFrame() { + chooseFile(false, "file-services.html?srcdoc", "document.querySelector('iframe').contentDocument.getElementById('picker').click()"); +} + +/// Closing the window while a system panel is open: the panel answers "cancel" and its late answer touches nothing. +void closeWithPanel(const char* page, const char* click) { + Object pool(send(type("NSAutoreleasePool"), "new")); + static bool sawPanel; + static std::string script; + sawPanel = false; + script = click; + ScenarioFrontend::configure = [](webfront::frontend::WKWebViewOptions& options) { + options.visible = true; // No injection: the real NSSavePanel / NSOpenPanel opens as a sheet of a visible window. + }; + ScenarioFrontend::started = [](Session& session) { + Session* live = &session; + auto ticks = std::make_shared(0); + auto tick = ^(id timer) { + const auto sheets = send(live->window, "sheets"); + if (send(sheets, "count") > 0) { + sawPanel = true; + if (++*ticks > 3) { // Let the sheet settle, then close the window under it. + send(timer, "invalidate"); + send(live->window, "close"); + } + return; + } + if (!script.empty()) { + Object code(text("document.title === 'ready' && !window.clicked && (window.clicked = true, " + script + ")")); + send(live->view, "evaluateJavaScript:completionHandler:", code.get(), static_cast(nullptr)); + } + }; + send(type("NSTimer"), "scheduledTimerWithTimeInterval:repeats:block:", 0.1, static_cast(true), tick); + }; + { + ScenarioApp app(webfront::WebFrontConfig{.documentRoot = std::filesystem::current_path()}); + app.show(page); + } + resetScenario(); + // A late answer from AppKit after the session ended must find nothing to touch. + send(send(type("NSRunLoop"), "currentRunLoop"), "runUntilDate:", send(type("NSDate"), "dateWithTimeIntervalSinceNow:", 0.5)); + require(sawPanel, "The system panel did not open"); +} +void closeWithOpenPanel() { + closeWithPanel("file-services.html?choose", "document.getElementById('picker').click()"); +} +void closeWithSavePanel() { + closeWithPanel("file-services.html?download", ""); +} + +/// The save panel's "Replace" choice: the page's bytes land beside the old file and replace it only on success. +void replacedDownload() { + Object pool(send(type("NSAutoreleasePool"), "new")); + const auto folder = std::filesystem::temp_directory_path() / ("webfront-wk-replace-" + std::to_string(getpid())); + std::filesystem::remove_all(folder); + std::filesystem::create_directories(folder); + const auto target = folder / "report.txt"; + std::filesystem::path temporary; + std::vector finished; + Session session("http://127.0.0.1:0/", {.visible = false, .downloadFinished = [&](const std::string& path) { + finished.push_back(path); + }}); + const auto start = [&](std::uintptr_t key, std::string_view oldContent, std::string_view downloaded) { + std::ofstream(target) << oldContent; + auto staging = std::make_unique(folder); + temporary = staging->path(); + if (!downloaded.empty()) + std::ofstream(temporary) << downloaded; + session.downloadDestinations[reinterpret_cast(key)] = {std::move(staging), target, false, true}; + }; + start(1, "old", "new"); + session.downloadEnded(reinterpret_cast(std::uintptr_t{1}), true); + require(readFile(target) == "new" && !std::filesystem::exists(temporary), "A completed download did not replace the old file"); + require(finished == std::vector{target.string()}, "The finished download was not reported at the chosen path"); + + start(2, "old", "partial"); + session.downloadEnded(reinterpret_cast(std::uintptr_t{2}), false); + require(readFile(target) == "old" && !std::filesystem::exists(temporary), "A failed download damaged the old file or left its part behind"); + + start(3, "old", ""); // The engine reported success but the part is gone: the replacement fails, the old file stays. + session.downloadEnded(reinterpret_cast(std::uintptr_t{3}), true); + require(readFile(target) == "old" && finished.size() == 1, "A failed replacement was reported as a finished download"); + + // A failed ordinary download removes its private fragment and releases its destination. + const auto ordinary = session.reservations.reserve(folder, "ordinary.txt"); + auto staging = std::make_unique(folder); + std::ofstream(staging->path()) << "partial"; + const auto key = reinterpret_cast(std::uintptr_t{4}); + session.downloadDestinations[key] = {std::move(staging), ordinary, true, false}; + session.downloadEnded(key, false); + require(!std::filesystem::exists(ordinary), "A failed ordinary download left an incomplete file"); + require(session.reservations.empty() && finished.size() == 1, "A failed download kept its reservation or reported success"); + + staging = std::make_unique(folder); + session.downloadDestinations[key] = {std::move(staging), ordinary, false, false}; + std::ofstream(ordinary) << "created by another process"; + session.downloadEnded(key, false); + require(readFile(ordinary) == "created by another process", "A failed download removed an unrelated file"); + std::filesystem::remove(ordinary); + + // Successful ordinary downloads must keep their bytes and report the destination exactly once. + staging = std::make_unique(folder); + std::ofstream(staging->path()) << "complete"; + session.downloadDestinations[key] = {std::move(staging), ordinary, false, false}; + session.downloadEnded(key, true); + require(readFile(ordinary) == "complete", "A completed ordinary download was removed"); + require(finished == std::vector{target.string(), ordinary.string()}, "An ordinary download was not reported"); + require(session.downloadDestinations.empty(), "A download outlived its end"); + std::filesystem::remove_all(folder); +} + void nativeEarlyClose() { nativeClose(false); } @@ -297,7 +522,15 @@ int main(int argc, char** argv) { {"navigation-diagnostic", navigationDiagnostic}, { "missing-response", missingResponse}, { "committed-navigation", committedNavigation}, - { "agent-application", agentApplication} + { "agent-application", agentApplication}, + { "download", download}, + { "choose-file", chooseOne}, + { "cancel-choose", chooseCancel}, + { "replaced-download", replacedDownload}, + { "choose-in-blank", chooseInBlankFrame}, + { "choose-in-srcdoc", chooseInSrcdocFrame}, + { "close-with-open-panel", closeWithOpenPanel}, + { "close-with-save-panel", closeWithSavePanel} }; cases.at(argc == 2 ? argv[1] : "")(); return 0; diff --git a/test/web/WebKitGTKLifecycle.cpp b/test/web/WebKitGTKLifecycle.cpp index 869847f7..d22fffa4 100644 --- a/test/web/WebKitGTKLifecycle.cpp +++ b/test/web/WebKitGTKLifecycle.cpp @@ -2,7 +2,10 @@ #include #include +#include #include +#include +#include #include #include #include @@ -127,6 +130,235 @@ void nativeClose() { app.show("no-bridge.html"); } +/// Runs a page of the test folder in a session configured by the scenario, for at most `seconds`. +struct ScenarioFrontend : Frontend { + static inline std::function configure; + static inline std::function finished; // Polled; true closes the window. + static void open(std::string_view port, std::string_view page) { + open("127.0.0.1", port, page, {}); + } + static void open(std::string_view address, std::string_view port, std::string_view page, const webfront::ContentPolicy& policy) { + gtk::Session session(webfront::detail::BoundContentPolicy{webfront::frontend::detail::applicationUrl(address, port, ""), policy}); + session.create(); + configure(session); + struct Poll { + gtk::Session& session; + int remaining = 150; // 15 s + unsigned timer = 0; + } poll{session, 150, 0}; + poll.timer = session.a.timeoutAdd( + 100, + [](void* data) -> int { + auto& probe = *static_cast(data); + if (probe.session.closed) { + probe.timer = 0; // Returning 0 removes the source: it must not be removed again. + return 0; + } + if (finished(probe.session) || --probe.remaining == 0) { + probe.timer = 0; + probe.session.close(); + return 0; + } + return 1; + }, + &poll); + session.run(webfront::frontend::detail::applicationUrl(address, port, page)); + if (poll.timer) + session.a.sourceRemove(poll.timer); + } +}; + +using ScenarioApp = webfront::BasicWFWithFrontend; + +std::string readFile(const std::filesystem::path& path) { + std::ifstream stream(path, std::ios::binary); + return {std::istreambuf_iterator(stream), {}}; +} + +void download() { + const auto parent = std::filesystem::temp_directory_path() / ("webfront-download-" + std::to_string(getpid())); + const auto folder = parent / "not" / "yet"; // The frontend creates the folder: WebKitGTK writes into an existing one only. + std::filesystem::remove_all(parent); + std::string destination; + bool done = false; + ScenarioFrontend::configure = [&](gtk::Session& session) { + session.downloadDirectory = folder; + session.downloadFinished = [&](const std::string& path) { + destination = path; + done = true; + }; + }; + ScenarioFrontend::finished = [&](gtk::Session&) { + return done; + }; + ScenarioApp app(webfront::WebFrontConfig{.documentRoot = std::filesystem::current_path()}); + app.show("file-services.html?download"); + if (!done) + throw std::runtime_error("The download did not finish"); + // The suggested name "../webfront-download.txt" must never leave the download folder. + if (std::filesystem::path(destination) != folder / "webfront-download.txt") + throw std::runtime_error("Unexpected download destination: " + destination); + if (readFile(destination) != "downloaded by WebFront") + throw std::runtime_error("The downloaded file has the wrong content"); + std::filesystem::remove_all(parent); +} + +/// Without a configured folder, the download lands in GLib's user download directory (user-dirs.dirs), not in an +/// XDG_DOWNLOAD_DIR environment variable, which nothing defines in a normal session. +void downloadUserDirectory() { + const auto base = std::filesystem::temp_directory_path() / ("webfront-userdir-" + std::to_string(getpid())); + std::filesystem::remove_all(base); + const auto config = base / "config"; + const auto folder = base / "Telechargements"; + const auto decoy = base / "decoy"; + std::filesystem::create_directories(config); + std::filesystem::create_directories(folder); + std::filesystem::create_directories(decoy); + std::ofstream(config / "user-dirs.dirs") << "XDG_DOWNLOAD_DIR=\"" << folder.string() << "\"\n"; + // GLib reads the configuration once, at the first query: set it before any session exists. + setenv("XDG_CONFIG_HOME", config.c_str(), 1); + setenv("XDG_DOWNLOAD_DIR", decoy.c_str(), 1); + std::string destination; + bool done = false; + ScenarioFrontend::configure = [&](gtk::Session& session) { + session.downloadFinished = [&](const std::string& path) { + destination = path; + done = true; + }; + }; + ScenarioFrontend::finished = [&](gtk::Session&) { + return done; + }; + ScenarioApp app(webfront::WebFrontConfig{.documentRoot = std::filesystem::current_path()}); + app.show("file-services.html?download"); + if (!done) + throw std::runtime_error("The download did not finish"); + if (std::filesystem::path(destination) != folder / "webfront-download.txt") + throw std::runtime_error("The download ignored GLib's user download directory: " + destination); + std::filesystem::remove_all(base); +} + +/// A real pointer click through the X server's XTest extension: web content only opens a file chooser for a user gesture. +struct FakeClick { + void* x11 = dlopen("libX11.so.6", RTLD_NOW); + void* xtest = dlopen("libXtst.so.6", RTLD_NOW); + void* gtkModule = dlopen("libgtk-4.so.1", RTLD_NOW | RTLD_LOCAL); + using Open = void* (*)(const char*); + using Flush = int (*)(void*); + using Move = int (*)(void*, int, int, int, unsigned long); + using Press = int (*)(void*, unsigned, int, unsigned long); + using Translate = int (*)(void*, unsigned long, unsigned long, int, int, int*, int*, unsigned long*); + using Root = unsigned long (*)(void*); + using Surface = void* (*)(void*); + using Xid = unsigned long (*)(void*); + Open open = x11 ? reinterpret_cast(dlsym(x11, "XOpenDisplay")) : nullptr; + Flush flush = x11 ? reinterpret_cast(dlsym(x11, "XFlush")) : nullptr; + Move move = xtest ? reinterpret_cast(dlsym(xtest, "XTestFakeMotionEvent")) : nullptr; + Press press = xtest ? reinterpret_cast(dlsym(xtest, "XTestFakeButtonEvent")) : nullptr; + Translate translate = x11 ? reinterpret_cast(dlsym(x11, "XTranslateCoordinates")) : nullptr; + Root root = x11 ? reinterpret_cast(dlsym(x11, "XDefaultRootWindow")) : nullptr; + // GTK's client surface need not start at the root window's origin, even under Xvfb. + Surface surface = gtkModule ? reinterpret_cast(dlsym(gtkModule, "gtk_native_get_surface")) : nullptr; + Xid xid = gtkModule ? reinterpret_cast(dlsym(gtkModule, "gdk_x11_surface_get_xid")) : nullptr; + void* display = open ? open(nullptr) : nullptr; + + bool available() const { + return display && move && press && flush && translate && root && surface && xid; + } + void click(void* window, int x, int y, int phase) const { + const auto native = surface(window); + if (!native) + return; + int rootX = 0, rootY = 0; + unsigned long child = 0; + if (!translate(display, xid(native), root(display), x, y, &rootX, &rootY, &child)) + throw std::runtime_error("Cannot locate the GTK file chooser in the X root window"); + // One step per poll: GTK and the web process must see the pointer enter before they receive the button events. + switch (phase) { + case 0: + move(display, 0, rootX + 120, rootY + 60, 0); + break; + case 1: + move(display, 0, rootX, rootY, 0); + break; + case 2: + press(display, 1, 1, 0); + break; + case 3: + press(display, 1, 0, 0); + break; + default: + break; + } + flush(display); + } +}; + +void chooseFile(bool cancel) { + const auto fixture = std::filesystem::temp_directory_path() / ("webfront-chooser-" + std::to_string(getpid()) + ".txt"); + std::ofstream(fixture) << "chosen by the test"; + bool asked = false; + ScenarioFrontend::configure = [&](gtk::Session& session) { + session.chooseFiles = [&]() -> std::vector { + asked = true; + return cancel ? std::vector{} : std::vector{fixture.string()}; + }; + }; + std::string title; + const FakeClick pointer; + if (!pointer.available()) + throw std::runtime_error("XTest is unavailable: run the scenario under Xvfb with libXtst"); + int ticks = 0; + ScenarioFrontend::finished = [&](gtk::Session& session) { + const char* current = session.a.viewTitle(session.view); + title = current ? current : ""; + if (title == "ready" && !asked) + pointer.click(session.window, 40, 20, ticks++ % 5); // The button's position within the GTK client surface. + return title.starts_with("picked:") || title == "cancelled"; + }; + ScenarioApp app(webfront::WebFrontConfig{.documentRoot = std::filesystem::current_path()}); + app.show("file-services.html?choose"); + std::filesystem::remove(fixture); + if (!asked) + throw std::runtime_error("The file chooser was not requested (page title \"" + title + "\", " + std::to_string(ticks) + " pointer steps)"); + const std::string expected = cancel ? "cancelled" : "picked:chosen by the test"; + if (title != expected) + throw std::runtime_error("Unexpected page state after the chooser: " + title); +} +void chooseOne() { + chooseFile(false); +} +void chooseCancel() { + chooseFile(true); +} + +/// Closing the window while the system file dialog is open must end cleanly, without waiting for an answer. +void closeWithDialog() { + bool opened = false; + int open = 0; // Poll ticks since the dialog opened. + ScenarioFrontend::configure = [&](gtk::Session& session) { + session.chooserOpened = [&] { + opened = true; + }; + }; + std::string title; + const FakeClick pointer; + if (!pointer.available()) + throw std::runtime_error("XTest is unavailable: run the scenario under Xvfb with libXtst"); + int ticks = 0; + ScenarioFrontend::finished = [&](gtk::Session& session) { + const char* current = session.a.viewTitle(session.view); + title = current ? current : ""; + if (title == "ready" && !opened) + pointer.click(session.window, 40, 20, ticks++ % 5); + return opened && ++open > 10; // Let the dialog map, then close the window under it. + }; + ScenarioApp app(webfront::WebFrontConfig{.documentRoot = std::filesystem::current_path()}); + app.show("file-services.html?choose"); + if (!opened) + throw std::runtime_error("The file dialog was not opened"); +} + void windowTitle() { gtk::initialize(); const auto titleOf = [](webfront::WindowOptions window) { @@ -177,7 +409,12 @@ void run(std::string_view mode) { { "native-close", nativeClose}, { "pre-run-failure", preRunFailure}, {"profile-permissions", profilePermissions}, - { "window-title", windowTitle} + { "window-title", windowTitle}, + { "download", download}, + {"download-user-dir", downloadUserDirectory}, + { "close-with-dialog", closeWithDialog}, + { "choose-file", chooseOne}, + { "cancel-choose", chooseCancel} }; const auto selected = cases.find(mode); if (selected == cases.end()) diff --git a/test/web/WebView2Lifecycle.cpp b/test/web/WebView2Lifecycle.cpp index 0cec7fa2..095d56a8 100644 --- a/test/web/WebView2Lifecycle.cpp +++ b/test/web/WebView2Lifecycle.cpp @@ -1,12 +1,15 @@ #include "../driver/TestFrontend.hpp" #include +#include #include #include #include #include +#include #include #include +#include #include #include #include @@ -200,6 +203,155 @@ int lateNavigationFailure() { return observed ? 0 : 1; } +// Exercise the engine's chooser and download paths. DevTools supplies the chooser answer because +// WebView2 exposes no file-dialog callback; DownloadStarting supplies a private destination. +int fileServices(std::string_view mode) { + using namespace webfront::frontend::detail::webview2; + const auto folder = std::filesystem::temp_directory_path() + / ("webfront-webview2-files-" + std::to_string(GetCurrentProcessId()) + "-" + + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count())); + require(std::filesystem::create_directory(folder), "Cannot create private test directory"); + struct Cleanup { + std::filesystem::path path; + ~Cleanup() { + std::error_code error; + std::filesystem::remove_all(path, error); + } + } cleanup{folder}; + const auto fixture = folder / "fixture.txt"; + std::ofstream(fixture) << "chosen by the test"; + const auto destination = folder / "result.txt"; + + webfront::http::Server server("127.0.0.1", "9002", std::filesystem::current_path()); + std::jthread worker([&](std::stop_token stop) { + std::stop_callback cleanupServer(stop, [&] { + server.stop(); + }); + server.run(); + }); + Apartment apartment; + auto session = std::make_shared(); + session->url = mode == "download" ? L"http://127.0.0.1:9002/file-services.html?download" : L"http://127.0.0.1:9002/file-services.html?choose"; + session->contentPolicy = webfront::detail::BoundContentPolicy{"http://127.0.0.1:9002", {}}; + session->createWindow(webfront::testdriver::diagnosticWindows()); + Actions actions; + actions.onFailure = [&] { + session->fail(); + }; + bool ready = false, interceptRequested = false, clicked = false, asked = false, finished = false; + Microsoft::WRL::ComPtr download; + Microsoft::WRL::ComPtr chooser; + session->viewReady = [&] { + EventRegistrationToken token{}; + if (mode == "download") { + Microsoft::WRL::ComPtr view4; + check(session->view.As(&view4), "querying download support"); + check(view4->add_DownloadStarting( + Microsoft::WRL::Callback([&](ICoreWebView2*, + ICoreWebView2DownloadStartingEventArgs* args) -> HRESULT { + try { + check(args->get_DownloadOperation(&download), "getting download operation"); + check(args->put_ResultFilePath(destination.c_str()), "setting download destination"); + check(args->put_Handled(TRUE), "suppressing download UI"); + } catch (...) { + session->fail(); + } + return S_OK; + }).Get(), + &token), + "registering download handler"); + ready = true; + return; + } + check(session->view->GetDevToolsProtocolEventReceiver(L"Page.fileChooserOpened", &chooser), "getting chooser event"); + check(chooser->add_DevToolsProtocolEventReceived( + Microsoft::WRL::Callback( + [&](ICoreWebView2*, ICoreWebView2DevToolsProtocolEventReceivedEventArgs* args) -> HRESULT { + try { + LPWSTR raw = nullptr; + check(args->get_ParameterObjectAsJson(&raw), "reading chooser event"); + const std::unique_ptr json(raw, CoTaskMemFree); + std::wcmatch match; + require(std::regex_search(json.get(), match, std::wregex(L"\\\"backendNodeId\\\"\\s*:\\s*(\\d+)")), + "Chooser event has no input node"); + asked = true; + if (mode == "cancel") + return S_OK; // The interception was configured to cancel and emit the page's cancel event. + const auto files = webfront::json::quote(utf8(fixture.c_str())); + const auto parameters = utf16("{\"backendNodeId\":" + utf8(match[1].str()) + ",\"files\":[" + files + "]}"); + check(session->view->CallDevToolsProtocolMethod(L"DOM.setFileInputFiles", parameters.c_str(), nullptr), "answering chooser"); + } catch (...) { + session->fail(); + } + return S_OK; + }) + .Get(), + &token), + "registering chooser handler"); + }; + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds{30}; + actions.dispatch = [&](UINT) { + if (std::chrono::steady_clock::now() >= deadline) + throw std::runtime_error("File service scenario timed out: ready=" + std::to_string(ready) + " clicked=" + std::to_string(clicked) + + " asked=" + std::to_string(asked) + " loading=" + std::to_string(session->loadingInitialPage())); + if (!session->view || session->loadingInitialPage()) + return; + if (mode != "download" && !interceptRequested) { + interceptRequested = true; + check(session->view->CallDevToolsProtocolMethod(L"Page.enable", L"{}", nullptr), "enabling page events"); + const auto parameters = mode == "cancel" ? L"{\"enabled\":true,\"cancel\":true}" : L"{\"enabled\":true}"; + check(session->view->CallDevToolsProtocolMethod( + L"Page.setInterceptFileChooserDialog", + parameters, + Microsoft::WRL::Callback([&](HRESULT result, LPCWSTR) -> HRESULT { + try { + check(result, "enabling chooser interception"); + ready = true; + } catch (...) { + session->fail(); + } + return S_OK; + }).Get()), + "enabling chooser interception"); + } + if (!ready) + return; + if (mode == "download") { + if (!download) + return; + COREWEBVIEW2_DOWNLOAD_STATE state{}; + check(download->get_State(&state), "reading download state"); + require(state != COREWEBVIEW2_DOWNLOAD_STATE_INTERRUPTED, "Download was interrupted"); + finished = state == COREWEBVIEW2_DOWNLOAD_STATE_COMPLETED; + } else { + if (!clicked) { + clicked = true; + check(session->view->CallDevToolsProtocolMethod(L"Runtime.evaluate", + L"{\"expression\":\"document.getElementById('picker').click()\",\"userGesture\":true}", + nullptr), + "opening chooser"); + } + LPWSTR raw = nullptr; + check(session->view->get_DocumentTitle(&raw), "reading page result"); + const std::unique_ptr title(raw, CoTaskMemFree); + finished = asked && std::wstring_view(title.get()) == (mode == "choose" ? L"picked:chosen by the test" : L"cancelled"); + } + if (finished) + PostMessageW(session->window, WM_CLOSE, 0, 0); + }; + require(SetTimer(actions.window, 1, 20, nullptr) != 0, "Cannot start file service watchdog"); + session->start(userDataFolder()); + session->run(); + if (actions.failure) + std::rethrow_exception(actions.failure); + require(finished, "File service did not finish"); + if (mode == "download") { + std::ifstream stream(destination, std::ios::binary); + require(std::string(std::istreambuf_iterator(stream), {}) == "downloaded by WebFront", "Wrong downloaded content"); + } + return 0; +} + int rejectMta() { if (FAILED(CoInitializeEx(nullptr, COINIT_MULTITHREADED))) return 1; @@ -354,7 +506,19 @@ int run(std::string_view mode) { if (!webView2ClosesServer()) return 1; const std::map> cases{ - { "runtime-ready",runtimeReadyBeforePageLoad }, + { "file-choose", + [] { + return fileServices("choose"); + } }, + { "file-cancel", + [] { + return fileServices("cancel"); + } }, + { "file-download", + [] { + return fileServices("download"); + } }, + { "runtime-ready", runtimeReadyBeforePageLoad}, { "closed-startup-timeout", [] { return startupCompletion(false); diff --git a/test/web/file-services.html b/test/web/file-services.html new file mode 100644 index 00000000..b8077065 --- /dev/null +++ b/test/web/file-services.html @@ -0,0 +1,49 @@ + + +File chooser and downloads + + +

WebFront file services

+

waiting

+ diff --git a/test/web/host/HostProbe.cpp b/test/web/host/HostProbe.cpp index 70617d91..93234505 100644 --- a/test/web/host/HostProbe.cpp +++ b/test/web/host/HostProbe.cpp @@ -93,8 +93,8 @@ void startAgain(const char* self, const char* mode, const char* argument) { int main(int argc, char** argv) { #ifdef _WIN32 // Text mode would turn each '\n' into "\r\n": the tests compare bytes. - _setmode(_fileno(stdout), _O_BINARY); - _setmode(_fileno(stderr), _O_BINARY); + if (_setmode(_fileno(stdout), _O_BINARY) == -1 || _setmode(_fileno(stderr), _O_BINARY) == -1) + return 1; std::vector utf8Arguments; std::vector utf8Pointers; { diff --git a/test/web/jasmine-consumer/file-services.spec.js b/test/web/jasmine-consumer/file-services.spec.js new file mode 100644 index 00000000..534b76f0 --- /dev/null +++ b/test/web/jasmine-consumer/file-services.spec.js @@ -0,0 +1,55 @@ +// Qualification of the file services every engine must give a page without any native API (issue #451): files reach the +// page as File objects, a generated Blob can be offered for download, and the page keeps working afterwards. +describe('File services in the embedded engine', () => { + let host; + beforeEach(() => { + host = document.createElement('section'); + document.body.append(host); + }); + afterEach(() => host.remove()); + + it('reads the content of files given to an and to a drop', async () => { + const input = document.createElement('input'); + input.type = 'file'; + input.multiple = true; + host.append(input); + const transfer = new DataTransfer(); + transfer.items.add(new File(['first file'], 'first.txt', {type: 'text/plain'})); + transfer.items.add(new File([new Uint8Array([1, 2, 3, 255])], 'second.bin')); + const changed = new Promise(resolve => input.addEventListener('change', resolve, {once: true})); + input.files = transfer.files; + input.dispatchEvent(new Event('change', {bubbles: true})); + await changed; + expect(input.files.length).toBe(2); + expect(await input.files[0].text()).toBe('first file'); + expect(Array.from(new Uint8Array(await input.files[1].arrayBuffer()))).toEqual([1, 2, 3, 255]); + const summary = document.createElement('p'); + summary.textContent = Array.from(input.files, file => `${file.name} (${file.size} bytes)`).join(', '); + host.append(summary); + expect(await webFrontCapture.screenshot('file-input')).toBeGreaterThan(100); + }); + + it('accepts the directory flag and the accept filter on the input', () => { + const input = document.createElement('input'); + input.type = 'file'; + input.accept = '.txt,image/*'; + input.webkitdirectory = true; + host.append(input); + expect(input.accept).toBe('.txt,image/*'); + expect(input.webkitdirectory).toBe(true); + }); + + it('offers a generated Blob for download without breaking the page or the bridge', async () => { + const link = document.createElement('a'); + link.href = URL.createObjectURL(new Blob(['generated by the page'], {type: 'text/plain'})); + link.download = 'generated.txt'; + link.textContent = 'generated.txt'; + host.append(link); + link.click(); + await new Promise(resolve => setTimeout(resolve, 500)); + expect(location.protocol).toMatch(/^https?:$/); // The window stayed on the application. + expect(await webFront.cppFunction('consumer.answer')()).toBe(42); + expect(await webFrontCapture.screenshot('download-link')).toBeGreaterThan(100); + URL.revokeObjectURL(link.href); + }); +});