Truly independent web browser
LibWebView+UI/Qt+LibWeb+WebContent: Ask the system for the microphone
Luke Wilde692ac381c65b
diff --git a/Libraries/LibAudio/ClientConnection.cpp b/Libraries/LibAudio/ClientConnection.cppindex a597daa0236..ce801130884 100644--- a/Libraries/LibAudio/ClientConnection.cpp+++ b/Libraries/LibAudio/ClientConnection.cpp@@ -4,6 +4,7 @@* SPDX-License-Identifier: BSD-2-Clause*/+#include <AK/AnyOf.h>#include <AK/NeverDestroyed.h>#include <LibAudio/ClientConnection.h>#include <LibAudio/RemotePlaybackStream.h>@@ -42,6 +43,14 @@ ErrorOr<NonnullRefPtr<ClientConnection>> ClientConnection::acquire()return connection;}+bool ClientConnection::capture_is_pending_for_testing()+{+ auto const& connection = *s_connection;+ if (!connection)+ return false;+ return any_of(connection->m_capture_sources, [](auto const& entry) { return !entry.value.specification.has_value(); });+}+ClientConnection::ClientConnection(NonnullOwnPtr<IPC::Transport> transport): IPC::ConnectionToServer<AudioClientEndpoint, AudioServerEndpoint>(*this, move(transport)), m_event_loop(Core::EventLoop::current())diff --git a/Libraries/LibAudio/ClientConnection.h b/Libraries/LibAudio/ClientConnection.hindex e83b1c3a087..5b354be8e3d 100644--- a/Libraries/LibAudio/ClientConnection.h+++ b/Libraries/LibAudio/ClientConnection.h@@ -45,6 +45,8 @@ public:static bool has_transport_factory();// The process's connection, established on first use and replaced after it dies.static ErrorOr<NonnullRefPtr<ClientConnection>> acquire();+ // Whether a capture waits on the server for its device, which another capture of the same device would join.+ static bool capture_is_pending_for_testing();explicit ClientConnection(NonnullOwnPtr<IPC::Transport>);virtual ~ClientConnection() override;diff --git a/Libraries/LibWeb/Internals/Internals.cpp b/Libraries/LibWeb/Internals/Internals.cppindex b9f73ef718d..697d66d98a8 100644--- a/Libraries/LibWeb/Internals/Internals.cpp+++ b/Libraries/LibWeb/Internals/Internals.cpp@@ -2257,6 +2257,26 @@ void Internals::set_next_permission_prompt_outcome(Utf16String const& name, Utf1page().client().page_did_set_next_permission_prompt_outcome_for_testing(name.to_utf8(), outcome.to_utf8(), held);}+void Internals::set_system_microphone_authorization(Utf16String const& authorization, Utf16String const& answer, bool held)+{+ page().client().page_did_set_system_microphone_authorization_for_testing(authorization.to_utf8(), answer.to_utf8(), held);+}++void Internals::release_system_microphone_answer()+{+ page().client().page_did_release_system_microphone_answer_for_testing();+}++Utf16String Internals::microphone_state()+{+ return Utf16String::from_utf8(page().client().page_did_request_microphone_state_for_testing());+}++bool Internals::audio_capture_is_pending()+{+ return Audio::ClientConnection::capture_is_pending_for_testing();+}+void Internals::release_held_permission_prompt(WebIDL::UnsignedLong waiters){page().client().page_did_release_held_permission_prompt_for_testing(waiters);diff --git a/Libraries/LibWeb/Internals/Internals.h b/Libraries/LibWeb/Internals/Internals.hindex 0907512269e..29e34c33a06 100644--- a/Libraries/LibWeb/Internals/Internals.h+++ b/Libraries/LibWeb/Internals/Internals.h@@ -270,6 +270,10 @@ public:GC::Ref<WebIDL::Promise> request_permission(Utf16String const& name);GC::Ref<WebIDL::Promise> set_permission(Utf16String const& name, Utf16String const& state);void set_next_permission_prompt_outcome(Utf16String const& name, Utf16String const& outcome, bool held);+ void set_system_microphone_authorization(Utf16String const& authorization, Utf16String const& answer, bool held);+ void release_system_microphone_answer();+ Utf16String microphone_state();+ bool audio_capture_is_pending();void release_held_permission_prompt(WebIDL::UnsignedLong waiters);GC::Ref<WebIDL::Promise> advance_permission_clock(WebIDL::UnsignedLongLong milliseconds);Vector<String> permission_cache_origins();diff --git a/Libraries/LibWeb/Internals/Internals.idl b/Libraries/LibWeb/Internals/Internals.idlindex a47102271ba..a483de5919b 100644--- a/Libraries/LibWeb/Internals/Internals.idl+++ b/Libraries/LibWeb/Internals/Internals.idl@@ -271,6 +271,11 @@ interface Internals {Promise<DOMString> requestPermission(DOMString name);Promise<undefined> setPermission(DOMString name, DOMString state);undefined setNextPermissionPromptOutcome(DOMString name, DOMString outcome, optional boolean held = false);+ undefined setSystemMicrophoneAuthorization(DOMString authorization, optional DOMString answer = "authorized", optional boolean held = false);+ undefined releaseSystemMicrophoneAnswer();+ DOMString microphoneState();+ // Whether this process has a capture waiting on the AudioServer for its device.+ boolean audioCaptureIsPending();undefined releaseHeldPermissionPrompt(optional unsigned long waiters = 1);Promise<undefined> advancePermissionClock(unsigned long long milliseconds);sequence<DOMString> permissionCacheOrigins();diff --git a/Libraries/LibWeb/Page/Page.h b/Libraries/LibWeb/Page/Page.hindex 06085530bbb..c0ab9fa7a14 100644--- a/Libraries/LibWeb/Page/Page.h+++ b/Libraries/LibWeb/Page/Page.h@@ -918,6 +918,9 @@ public:virtual Optional<Web::Permissions::PermissionSnapshot> page_did_request_permission_snapshot([[maybe_unused]] URL::Origin const& top_level_origin) { return {}; }virtual Optional<Web::Permissions::PermissionSnapshot> page_did_set_permission_for_testing([[maybe_unused]] HTML::CrossProcessId document_id, [[maybe_unused]] String const& name, [[maybe_unused]] String const& state) { return {}; }virtual void page_did_set_next_permission_prompt_outcome_for_testing([[maybe_unused]] String const& name, [[maybe_unused]] String const& outcome, [[maybe_unused]] bool held) { }+ virtual void page_did_set_system_microphone_authorization_for_testing([[maybe_unused]] String const& authorization, [[maybe_unused]] String const& answer, [[maybe_unused]] bool held) { }+ virtual void page_did_release_system_microphone_answer_for_testing() { }+ virtual String page_did_request_microphone_state_for_testing() { return "{}"_string; }virtual void page_did_release_held_permission_prompt_for_testing([[maybe_unused]] u32 waiters) { }virtual Optional<Web::Permissions::PermissionSnapshot> page_did_advance_permission_clock_for_testing([[maybe_unused]] u64 milliseconds) { return {}; }virtual void page_did_request_show_notification([[maybe_unused]] u64 notification_id, [[maybe_unused]] HTML::CrossProcessId document_id, [[maybe_unused]] NotificationsAPI::NotificationData const&, [[maybe_unused]] RefPtr<Gfx::Bitmap const> icon) { }diff --git a/Libraries/LibWebCommon/Permissions/Permissions.h b/Libraries/LibWebCommon/Permissions/Permissions.hindex 6eec5db536a..39ae4aeb3c2 100644--- a/Libraries/LibWebCommon/Permissions/Permissions.h+++ b/Libraries/LibWebCommon/Permissions/Permissions.h@@ -26,7 +26,7 @@ WEBCOMMON_API Optional<PermissionName> permission_name_from_string(StringView);WEBCOMMON_API StringView to_string(PermissionName);// What a site gets for a permission once every input is applied: the stored decision, an embargo, the global setting,-// and the operating system's own authorization.+// and for location, the operating system's own authorization.enum class EffectiveState : u8 {Granted,Denied,diff --git a/Libraries/LibWebView/Application.cpp b/Libraries/LibWebView/Application.cppindex b025eceeab6..d52b32b7474 100644--- a/Libraries/LibWebView/Application.cpp+++ b/Libraries/LibWebView/Application.cpp@@ -61,6 +61,7 @@#include <LibWebView/HelperProcess.h>#include <LibWebView/HistoryStore.h>#include <LibWebView/Menu.h>+#include <LibWebView/NoOpMicrophoneAuthorizer.h>#include <LibWebView/NoOpNotificationBackend.h>#include <LibWebView/PermissionManager.h>#include <LibWebView/PictureInPictureWindow.h>@@ -2283,6 +2284,11 @@ Core::EventLoop& Application::create_platform_event_loop()return Core::EventLoop::initialize_for_current_thread();}+NonnullOwnPtr<MicrophoneAuthorizer> Application::create_microphone_authorizer()+{+ return make<NoOpMicrophoneAuthorizer>();+}+ChildIdentity Application::add_child_process(WebView::Process&& process){return m_process_manager->add_process(move(process));@@ -3304,6 +3310,13 @@ void Application::set_spell_checker(OwnPtr<SpellChecker> spell_checker)m_spell_checker = move(spell_checker);}+MicrophoneAuthorizer& Application::microphone_authorizer()+{+ if (!m_microphone_authorizer)+ m_microphone_authorizer = create_microphone_authorizer();+ return *m_microphone_authorizer;+}+ErrorOr<NonnullRawPtr<Core::GeolocationProvider>> Application::ensure_geolocation_provider(){if (!m_geolocation_provider) {diff --git a/Libraries/LibWebView/Application.h b/Libraries/LibWebView/Application.hindex a9ae3343563..28206dfc508 100644--- a/Libraries/LibWebView/Application.h+++ b/Libraries/LibWebView/Application.h@@ -105,6 +105,7 @@ public:SpellChecker* spell_checker() { return m_spell_checker.ptr(); }void set_spell_checker(OwnPtr<SpellChecker>);+ MicrophoneAuthorizer& microphone_authorizer();static FontService& font_service() { return *the().m_font_service; }static FontServiceHost& font_service_host() { return *the().m_font_service_host; }JsonValue const& site_compatibility_data() const { return m_site_compatibility_data; }@@ -454,6 +455,7 @@ protected:virtual void create_platform_options(BrowserOptions&, RequestServerOptions&, WebContentOptions&) { }virtual void create_platform_actions() { }virtual Core::EventLoop& create_platform_event_loop();+ virtual NonnullOwnPtr<MicrophoneAuthorizer> create_microphone_authorizer();virtual bool should_coordinate_browser_process() const { return true; }virtual bool should_use_os_geolocation() const { return true; }@@ -706,6 +708,7 @@ private:OwnPtr<Core::GeolocationProvider> m_geolocation_provider;OwnPtr<SpellChecker> m_spell_checker;+ OwnPtr<MicrophoneAuthorizer> m_microphone_authorizer;OwnPtr<Core::TimeZoneWatcher> m_time_zone_watcher;Core::EventLoop* m_event_loop { nullptr };diff --git a/Libraries/LibWebView/CMakeLists.txt b/Libraries/LibWebView/CMakeLists.txtindex 35ca4f05b53..99231c7faec 100644--- a/Libraries/LibWebView/CMakeLists.txt+++ b/Libraries/LibWebView/CMakeLists.txt@@ -100,11 +100,12 @@ if (APPLE)list(APPEND SOURCESCrashReportPOSIX.cppLaunchURLsMacOS.cpp+ MicrophoneAuthorizerMacOS.mmNotificationBackendMacOS.mmPlatformColorsMacOS.cppProcessReaper.cpp)- set_source_files_properties(NotificationBackendMacOS.mm PROPERTIES COMPILE_FLAGS "-fobjc-arc")+ set_source_files_properties(MicrophoneAuthorizerMacOS.mm NotificationBackendMacOS.mm PROPERTIES COMPILE_FLAGS "-fobjc-arc")elseif (LINUX)list(APPEND SOURCES AudioDaemonSocket.cpp CrashReportPOSIX.cpp)endif()@@ -174,7 +175,7 @@ if (LINUX)endif()if (APPLE)- target_link_libraries(LibWebView PRIVATE "-framework Carbon" "-framework UserNotifications")+ target_link_libraries(LibWebView PRIVATE "-framework AVFoundation" "-framework Carbon" "-framework UserNotifications")endif()if (LINUX OR CMAKE_SYSTEM_NAME STREQUAL "FreeBSD")diff --git a/Libraries/LibWebView/Forward.h b/Libraries/LibWebView/Forward.hindex af52319d335..6460b6816c7 100644--- a/Libraries/LibWebView/Forward.h+++ b/Libraries/LibWebView/Forward.h@@ -45,6 +45,7 @@ class FontServiceHost;class HistoryStore;class HSTSStore;class Menu;+class MicrophoneAuthorizer;class NavigationLoader;class OutOfProcessWebView;class NotificationBackend;diff --git a/Libraries/LibWebView/MicrophoneAuthorizer.h b/Libraries/LibWebView/MicrophoneAuthorizer.hnew file mode 100644index 00000000000..604293ab80a--- /dev/null+++ b/Libraries/LibWebView/MicrophoneAuthorizer.h@@ -0,0 +1,38 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/Function.h>+#include <LibWebView/Export.h>++namespace WebView {++// Whether the operating system lets the browser itself use the microphone, whatever the user allows each site.+enum class MicrophoneAuthorization : u8 {+ // The system asks the user the first time the browser asks it.+ NotDetermined,+ Authorized,+ Denied,+};++// The system's consent for the microphone, which the UI process gets before any site may capture.+class WEBVIEW_API MicrophoneAuthorizer {+ AK_ALLOC_WITH_KMALLOC;++public:+ virtual ~MicrophoneAuthorizer() = default;++ virtual MicrophoneAuthorization authorization() const = 0;++ // on_complete runs on the main thread, possibly before this returns.+ virtual void request_authorization(Function<void(MicrophoneAuthorization)> on_complete) = 0;++ // Shows the user the setting that gives the browser the microphone back.+ virtual void open_system_settings() = 0;+};++}diff --git a/Libraries/LibWebView/MicrophoneAuthorizerMacOS.h b/Libraries/LibWebView/MicrophoneAuthorizerMacOS.hnew file mode 100644index 00000000000..ca38554da38--- /dev/null+++ b/Libraries/LibWebView/MicrophoneAuthorizerMacOS.h@@ -0,0 +1,35 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/NonnullRefPtr.h>+#include <LibWebView/MicrophoneAuthorizer.h>++namespace WebView {++namespace Detail {++struct PendingMicrophoneRequests;++}++// The system asks the user on behalf of the process responsible for the browser: the app, or the terminal that ran it.+// The AudioServer that opens the device answers to the same one.+class WEBVIEW_API MicrophoneAuthorizerMacOS final : public MicrophoneAuthorizer {+public:+ MicrophoneAuthorizerMacOS();+ virtual ~MicrophoneAuthorizerMacOS() override;++ virtual MicrophoneAuthorization authorization() const override;+ virtual void request_authorization(Function<void(MicrophoneAuthorization)> on_complete) override;+ virtual void open_system_settings() override;++private:+ NonnullRefPtr<Detail::PendingMicrophoneRequests> m_pending_requests;+};++}diff --git a/Libraries/LibWebView/MicrophoneAuthorizerMacOS.mm b/Libraries/LibWebView/MicrophoneAuthorizerMacOS.mmnew file mode 100644index 00000000000..671f2dc1f57--- /dev/null+++ b/Libraries/LibWebView/MicrophoneAuthorizerMacOS.mm@@ -0,0 +1,78 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <AK/AtomicRefCounted.h>+#include <AK/RefPtr.h>+#include <AK/Vector.h>+#include <LibCore/EventLoop.h>+#include <LibWebView/MicrophoneAuthorizerMacOS.h>++#import <AVFoundation/AVFoundation.h>+#import <CoreServices/CoreServices.h>++namespace WebView {++namespace Detail {++// The answer comes back on an arbitrary queue. The callbacks that take it stay on the main thread, so only this+// atomically counted holder crosses threads.+struct PendingMicrophoneRequests : public AtomicRefCounted<PendingMicrophoneRequests> {+ Vector<Function<void(MicrophoneAuthorization)>> callbacks;+};++}++MicrophoneAuthorizerMacOS::MicrophoneAuthorizerMacOS()+ : m_pending_requests(adopt_ref(*new Detail::PendingMicrophoneRequests))+{+}++MicrophoneAuthorizerMacOS::~MicrophoneAuthorizerMacOS() = default;++MicrophoneAuthorization MicrophoneAuthorizerMacOS::authorization() const+{+ switch ([AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio]) {+ case AVAuthorizationStatusNotDetermined:+ return MicrophoneAuthorization::NotDetermined;+ case AVAuthorizationStatusAuthorized:+ return MicrophoneAuthorization::Authorized;+ case AVAuthorizationStatusDenied:+ case AVAuthorizationStatusRestricted:+ return MicrophoneAuthorization::Denied;+ }+ return MicrophoneAuthorization::Denied;+}++void MicrophoneAuthorizerMacOS::request_authorization(Function<void(MicrophoneAuthorization)> on_complete)+{+ // Requests made while the system is asking share its answer.+ m_pending_requests->callbacks.append(move(on_complete));+ if (m_pending_requests->callbacks.size() > 1)+ return;++ RefPtr<Detail::PendingMicrophoneRequests> pending_requests = m_pending_requests;+ RefPtr<Core::WeakEventLoopReference> event_loop = Core::EventLoop::current_weak();+ [AVCaptureDevice requestAccessForMediaType:AVMediaTypeAudio+ completionHandler:^(BOOL granted) {+ auto strong_event_loop = event_loop->take();+ if (!strong_event_loop)+ return;+ auto authorization = granted ? MicrophoneAuthorization::Authorized : MicrophoneAuthorization::Denied;+ strong_event_loop->deferred_invoke([pending_requests, authorization] {+ auto callbacks = move(pending_requests->callbacks);+ for (auto& callback : callbacks)+ callback(authorization);+ });+ }];+}++void MicrophoneAuthorizerMacOS::open_system_settings()+{+ auto* url = [NSURL URLWithString:@"x-apple.systempreferences:com.apple.preference.security?Privacy_Microphone"];+ LSOpenCFURLRef((__bridge CFURLRef)url, nullptr);+}++}diff --git a/Libraries/LibWebView/NoOpMicrophoneAuthorizer.h b/Libraries/LibWebView/NoOpMicrophoneAuthorizer.hnew file mode 100644index 00000000000..dcaa17f2bc1--- /dev/null+++ b/Libraries/LibWebView/NoOpMicrophoneAuthorizer.h@@ -0,0 +1,22 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <LibWebView/MicrophoneAuthorizer.h>++namespace WebView {++// The authorizer of a platform whose system has no say over the microphone, which leaves it to what the user allows+// each site.+class NoOpMicrophoneAuthorizer final : public MicrophoneAuthorizer {+public:+ virtual MicrophoneAuthorization authorization() const override { return MicrophoneAuthorization::Authorized; }+ virtual void request_authorization(Function<void(MicrophoneAuthorization)> on_complete) override { on_complete(MicrophoneAuthorization::Authorized); }+ virtual void open_system_settings() override { }+};++}diff --git a/Libraries/LibWebView/PermissionManager.cpp b/Libraries/LibWebView/PermissionManager.cppindex ed528c01c73..303ebad2195 100644--- a/Libraries/LibWebView/PermissionManager.cpp+++ b/Libraries/LibWebView/PermissionManager.cpp@@ -498,6 +498,12 @@ void PermissionManager::age_origin_for_testing(URL::Origin const& origin, AK::Durun_expiry();}+u8 PermissionManager::dismissals_for_testing(PermissionName name, URL::Origin const& top_level_origin) const+{+ auto const* entry = find_entry(name, top_level_origin);+ return entry ? entry->dismissals : 0;+}+void PermissionManager::set_clock_for_testing(Function<UnixDateTime()> clock){m_clock = move(clock);diff --git a/Libraries/LibWebView/PermissionManager.h b/Libraries/LibWebView/PermissionManager.hindex 0d75461603b..bb8e8f20827 100644--- a/Libraries/LibWebView/PermissionManager.h+++ b/Libraries/LibWebView/PermissionManager.h@@ -106,6 +106,7 @@ public:// Makes the given time pass for one origin's entries only, so concurrently running tests don't disturb each other.void age_origin_for_testing(URL::Origin const&, AK::Duration);+ u8 dismissals_for_testing(Web::Permissions::PermissionName, URL::Origin const& top_level_origin) const;void set_clock_for_testing(Function<UnixDateTime()>);void set_timeouts_for_testing(PermissionTimeouts);diff --git a/Libraries/LibWebView/ViewImplementation.cpp b/Libraries/LibWebView/ViewImplementation.cppindex 848c8a48f23..bf43f16a8b3 100644--- a/Libraries/LibWebView/ViewImplementation.cpp+++ b/Libraries/LibWebView/ViewImplementation.cpp@@ -251,6 +251,8 @@ void ViewImplementation::request_permission_prompt(PermissionPromptRequest reque}outcome = next->outcome;}+ // A prompt a test answers counts as having come up on screen.+ did_show_permission_prompt(request);settle_permission_prompt(request, outcome);return;}@@ -300,6 +302,9 @@ void ViewImplementation::reset_permission_prompts_for_testing()m_next_permission_prompt_outcomes_for_testing.clear();m_held_permission_prompt_for_testing.clear();m_held_permission_prompt_release_waiters_for_testing.clear();+ m_microphone_authorizer_for_testing.clear();+ m_sites_shown_microphone_denied_notice.clear();+ m_microphone_denied_notices_shown = 0;auto pending_prompts = move(m_pending_permission_prompts);for (auto& pending : pending_prompts) {for (auto& waiter : pending.waiters)@@ -325,6 +330,7 @@ void ViewImplementation::release_held_permission_prompt_if_ready_for_testing()m_held_permission_prompt_release_waiters_for_testing.clear();auto held_request = m_held_permission_prompt_for_testing.release_value();+ did_show_permission_prompt(held_request);settle_permission_prompt(held_request, m_held_permission_prompt_outcome_for_testing);}@@ -4534,6 +4540,130 @@ void ViewImplementation::did_request_permission(Badge<WebContentPage>, Web::Permm_permissions_requested_by_page.append(name);}+class MicrophoneAuthorizerForTesting final : public MicrophoneAuthorizer {+public:+ MicrophoneAuthorizerForTesting(MicrophoneAuthorization authorization, MicrophoneAuthorization answer, bool held)+ : m_authorization(authorization)+ , m_answer(answer)+ , m_held(held)+ {+ }++ u64 requests() const { return m_requests; }++ void release()+ {+ m_held = false;+ for (auto& on_complete : exchange(m_waiting, {}))+ answer(move(on_complete));+ }++ virtual MicrophoneAuthorization authorization() const override { return m_authorization; }++ virtual void request_authorization(Function<void(MicrophoneAuthorization)> on_complete) override+ {+ ++m_requests;+ if (m_held) {+ m_waiting.append(move(on_complete));+ return;+ }+ answer(move(on_complete));+ }++ virtual void open_system_settings() override { }++private:+ void answer(Function<void(MicrophoneAuthorization)> on_complete)+ {+ m_authorization = m_answer;+ on_complete(m_authorization);+ }++ MicrophoneAuthorization m_authorization;+ MicrophoneAuthorization m_answer;+ bool m_held { false };+ u64 m_requests { 0 };+ Vector<Function<void(MicrophoneAuthorization)>> m_waiting;+};++MicrophoneAuthorizer& ViewImplementation::microphone_authorizer() const+{+ if (m_microphone_authorizer_for_testing)+ return *m_microphone_authorizer_for_testing;+ return Application::the().microphone_authorizer();+}++MicrophoneAuthorization ViewImplementation::microphone_authorization() const+{+ return microphone_authorizer().authorization();+}++void ViewImplementation::ensure_microphone_authorization(Function<void(bool authorized)> on_complete)+{+ // The notice is about the site that asked, which the tab may have left by the time the system answers.+ auto settle = [weak_this = make_weak_ptr(), requesting_origin = permission_origin(), on_complete = move(on_complete)](MicrophoneAuthorization authorization) {+ auto authorized = authorization == MicrophoneAuthorization::Authorized;+ if (auto* view = weak_this.ptr(); view && !authorized && view->permission_origin().is_same_origin(requesting_origin))+ view->show_microphone_denied_notice();+ on_complete(authorized);+ };++ auto authorization = microphone_authorization();+ if (authorization != MicrophoneAuthorization::NotDetermined) {+ settle(authorization);+ return;+ }+ microphone_authorizer().request_authorization(move(settle));+}++bool ViewImplementation::has_shown_microphone_denied_notice(URL::Origin const& top_level_origin) const+{+ return m_sites_shown_microphone_denied_notice.find_first_index_if([&](auto const& site) { return site.is_same_origin(top_level_origin); }).has_value();+}++void ViewImplementation::show_microphone_denied_notice()+{+ // Once the user has seen the notice, the site can't bring it back in this tab, however often it asks. The notice+ // goes through the prompts, so requests made while it waits to come up share it.+ auto top_level_origin = permission_origin();+ if (has_shown_microphone_denied_notice(top_level_origin))+ return;++ auto is_file = top_level_origin.is_opaque() && url().scheme() == "file"sv;+ PermissionPromptRequest request { Web::Permissions::PermissionName::Microphone, move(top_level_origin), is_file, false, PermissionPromptKind::SystemDeniedNotice };+ request_permission_prompt(move(request), [](Web::Permissions::PromptOutcome) { });+}++void ViewImplementation::did_show_permission_prompt(PermissionPromptRequest const& request)+{+ // A prompt that comes up again, once its hidden tab is shown, is still the one prompt.+ auto pending = m_pending_permission_prompts.find_if([&](auto const& candidate) { return candidate.request.is_same_request_as(request); });+ if (pending == m_pending_permission_prompts.end() || exchange(pending->shown, true))+ return;+ if (request.kind != PermissionPromptKind::SystemDeniedNotice)+ return;++ ++m_microphone_denied_notices_shown;+ if (!has_shown_microphone_denied_notice(request.top_level_origin))+ m_sites_shown_microphone_denied_notice.append(request.top_level_origin);+}++void ViewImplementation::set_microphone_authorization_for_testing(MicrophoneAuthorization authorization, MicrophoneAuthorization answer, bool held)+{+ m_microphone_authorizer_for_testing = make<MicrophoneAuthorizerForTesting>(authorization, answer, held);+}++void ViewImplementation::release_system_microphone_answer_for_testing()+{+ if (m_microphone_authorizer_for_testing)+ m_microphone_authorizer_for_testing->release();+}++u64 ViewImplementation::system_microphone_requests_for_testing() const+{+ return m_microphone_authorizer_for_testing ? m_microphone_authorizer_for_testing->requests() : 0;+}+void ViewImplementation::update_location_in_use(){auto in_use = !m_geolocation_position_request_ids.is_empty() || !m_geolocation_watch_ids.is_empty();diff --git a/Libraries/LibWebView/ViewImplementation.h b/Libraries/LibWebView/ViewImplementation.hindex 3bcba55fb55..db97a517f15 100644--- a/Libraries/LibWebView/ViewImplementation.h+++ b/Libraries/LibWebView/ViewImplementation.h@@ -77,6 +77,7 @@#include <LibWebView/ExternalURLHandler.h>#include <LibWebView/Forward.h>#include <LibWebView/HistoryVisitTransition.h>+#include <LibWebView/MicrophoneAuthorizer.h>#include <LibWebView/PermissionManager.h>#include <LibWebView/SessionHistory.h>#include <LibWebView/SessionStore.h>@@ -89,6 +90,8 @@namespace WebView {+class MicrophoneAuthorizerForTesting;+struct GeolocationRequestKey {NonnullRefPtr<WebContentPage> page;u64 request_id { 0 };@@ -96,6 +99,12 @@ struct GeolocationRequestKey {bool operator==(GeolocationRequestKey const&) const = default;};+enum class PermissionPromptKind : u8 {+ Question,+ // Tells the user the system keeps the feature from the browser, so no site can have it. Its answer decides nothing.+ SystemDeniedNotice,+};+// What the UI shows the user when a site asks for a permission. The origin is the top-level one the decision is kept// for; a file: page has none worth showing, so the prompt names it as a file instead.struct PermissionPromptRequest {@@ -103,10 +112,11 @@ struct PermissionPromptRequest {URL::Origin top_level_origin;bool is_file { false };bool show_os_hint { false };+ PermissionPromptKind kind { PermissionPromptKind::Question };bool is_same_request_as(PermissionPromptRequest const& other) const{- return name == other.name && is_file == other.is_file && top_level_origin.is_same_origin(other.top_level_origin);+ return name == other.name && kind == other.kind && is_file == other.is_file && top_level_origin.is_same_origin(other.top_level_origin);}};@@ -154,6 +164,23 @@ public:void reset_site_permissions(URL::Origin const&);void did_request_permission(Badge<WebContentPage>, Web::Permissions::PermissionName);+ MicrophoneAuthorization microphone_authorization() const;+ // Calls back with whether the system lets the browser use the microphone, once the system has asked the user if it+ // never has. The user is told why when it doesn't.+ void ensure_microphone_authorization(Function<void(bool authorized)>);+ // Tells the user the system keeps the microphone from the browser, unless this tab has already shown them that for+ // the site it shows.+ void show_microphone_denied_notice();+ // The UI calls this each time a prompt comes up on screen.+ void did_show_permission_prompt(PermissionPromptRequest const&);++ // The system answers with answer when it's asked, which it is while authorization is NotDetermined. A held answer+ // waits for release_system_microphone_answer_for_testing().+ void set_microphone_authorization_for_testing(MicrophoneAuthorization authorization, MicrophoneAuthorization answer, bool held);+ void release_system_microphone_answer_for_testing();+ u64 system_microphone_requests_for_testing() const;+ u64 microphone_denied_notices_shown_for_testing() const { return m_microphone_denied_notices_shown; }+bool location_in_use() const { return m_location_in_use; }// Ends every location request and watch whose document the user has since taken the permission away from.@@ -1141,6 +1168,7 @@ protected:struct PendingPermissionPrompt {PermissionPromptRequest request;Vector<PermissionPromptCallback> waiters;+ bool shown { false };};Vector<PendingPermissionPrompt> m_pending_permission_prompts;@@ -1154,6 +1182,12 @@ protected:Optional<u32> m_held_permission_prompt_release_waiters_for_testing;void release_held_permission_prompt_if_ready_for_testing();+ MicrophoneAuthorizer& microphone_authorizer() const;+ bool has_shown_microphone_denied_notice(URL::Origin const& top_level_origin) const;+ OwnPtr<MicrophoneAuthorizerForTesting> m_microphone_authorizer_for_testing;+ Vector<URL::Origin> m_sites_shown_microphone_denied_notice;+ u64 m_microphone_denied_notices_shown { 0 };+Core::AnonymousBuffer m_document_cookie_version_buffer;HashMap<String, Core::SharedVersionIndex> m_document_cookie_version_indices;DevTools::DevToolsDelegate::OnHostCookieChange m_on_host_cookie_change;diff --git a/Libraries/LibWebView/WebContentClient.cpp b/Libraries/LibWebView/WebContentClient.cppindex 72e502681e0..bd64a5f54c0 100644--- a/Libraries/LibWebView/WebContentClient.cpp+++ b/Libraries/LibWebView/WebContentClient.cpp@@ -1001,7 +1001,7 @@ bool WebContentClient::page_may_capture_audio(WebContentPage const& page) constreturn session().permission_manager->effective_state(Web::Permissions::PermissionName::Microphone, origin) == Web::Permissions::EffectiveState::Granted;}-bool WebContentClient::audio_capture_permitted() const+WebContentPage* WebContentClient::page_permitting_audio_capture() const{// A tab's grant reaches only the documents whose permissions policy allows them the microphone. The process may// capture if it hosts one, as it can act for any document it hosts.@@ -1010,14 +1010,37 @@ bool WebContentClient::audio_capture_permitted() constif (!page->is_open() || !page_may_capture_audio(*page))continue;if (page->hosts_a_document_allowed_to_use(Web::PermissionsPolicy::PolicyControlledFeature::Microphone))- return true;+ return page.ptr();}- return false;+ return nullptr;}void WebContentClient::decide_audio_capture_request(u64 request_id){- m_audio_server_client->async_capture_decided(request_id, audio_capture_permitted());+ auto* page = page_permitting_audio_capture();+ if (!page) {+ send_audio_capture_decision(request_id, false);+ return;+ }++ // Only a site the user allowed gets the system to ask the user, if it never has.+ // FIXME: The AudioServer doesn't say which page asked to capture, so a refusal is told in the tab of the first page+ // that may capture, which needn't be the one that asked.+ page->view().ensure_microphone_authorization([weak_self = make_weak_ptr<WebContentClient>(), request_id](bool authorized) {+ auto self = weak_self.strong_ref();+ if (!self || !self->m_audio_server_client || !self->m_audio_server_client->is_open())+ return;+ // The user may have taken the permission away while the system asked.+ self->send_audio_capture_decision(request_id, authorized && self->audio_capture_permitted());+ });+}++void WebContentClient::send_audio_capture_decision(u64 request_id, bool allowed)+{+ ++m_audio_capture_decision_count;+ if (!allowed)+ ++m_audio_capture_refusal_count;+ m_audio_server_client->async_capture_decided(request_id, allowed);}ErrorOr<void> WebContentClient::tell_audio_server_of_capture_permission()diff --git a/Libraries/LibWebView/WebContentClient.h b/Libraries/LibWebView/WebContentClient.hindex 52169b18989..864ee78d07a 100644--- a/Libraries/LibWebView/WebContentClient.h+++ b/Libraries/LibWebView/WebContentClient.h@@ -170,6 +170,8 @@ public:void add_permission_origin(URL::Origin const&);// The permission follows the origins the process's open pages show, so it goes with a navigation away.void update_audio_capture_permission();+ u64 audio_capture_decision_count() const { return m_audio_capture_decision_count; }+ u64 audio_capture_refusal_count() const { return m_audio_capture_refusal_count; }// The process's AudioServer plays the page's sound while the page is authorized. It hears of an authorization// before this returns, so a document the page goes on to run is heard from its start.void authorize_audio_playback(Web::PageId);@@ -269,9 +271,11 @@ private:ErrorOr<void> tell_audio_server_of_playback_authorization(Audio::PlaybackGroupId);void did_change_audio_playback_audibility(Audio::PlaybackGroupId, Audio::Audibility);static String audio_capture_permission_key(URL::URL const&);- bool audio_capture_permitted() const;+ bool audio_capture_permitted() const { return page_permitting_audio_capture(); }+ WebContentPage* page_permitting_audio_capture() const;bool page_may_capture_audio(WebContentPage const&) const;void decide_audio_capture_request(u64 request_id);+ void send_audio_capture_decision(u64 request_id, bool allowed);// The controller connections to the MediaServer and AudioServer spawned for this process, from its first media use// until it exits. The AudioServer mixes for this process alone, so a compromised one hears only its own site.@@ -284,6 +288,8 @@ private:HashTable<String> m_audio_capture_grants;Vector<URL::Origin> m_permission_origins;bool m_audio_capture_permitted { false };+ u64 m_audio_capture_decision_count { 0 };+ u64 m_audio_capture_refusal_count { 0 };// Likewise, the AudioServer is told again of the groups it may play, and of those the user has muted.HashTable<Audio::PlaybackGroupId> m_authorized_audio_playback_groups;HashTable<Audio::PlaybackGroupId> m_muted_audio_playback_groups;diff --git a/Libraries/LibWebView/WebContentPage.cpp b/Libraries/LibWebView/WebContentPage.cppindex 1b8ced49af4..de7d82b6360 100644--- a/Libraries/LibWebView/WebContentPage.cpp+++ b/Libraries/LibWebView/WebContentPage.cpp@@ -29,6 +29,7 @@#include <LibWebView/CookieJar.h>#include <LibWebView/GamepadManager.h>#include <LibWebView/HistoryStore.h>+#include <LibWebView/MicrophoneAuthorizer.h>#include <LibWebView/NavigationLoader.h>#include <LibWebView/NotificationManager.h>#include <LibWebView/PermissionManager.h>@@ -1799,6 +1800,14 @@ void WebContentPage::did_request_permission(u64 request_id, Web::HTML::CrossProcreturn;}+ // Allowing the site the microphone the system keeps from the browser would get it nothing, so the user is told why+ // instead of being asked. Nothing is decided for the site, which may ask again once the system relents.+ if (*permission_name == Web::Permissions::PermissionName::Microphone && view().microphone_authorization() == MicrophoneAuthorization::Denied) {+ view().show_microphone_denied_notice();+ async_permission_request_completed(request_id, Web::Permissions::EffectiveState::Prompt);+ return;+ }+auto generation_when_asked = manager.decision_generation(*permission_name, *top_level_origin);// When the system hasn't yet let the browser use the feature either, the prompt says the system will ask next.auto show_os_hint = [&] {@@ -1808,7 +1817,7 @@ void WebContentPage::did_request_permission(u64 request_id, Web::HTML::CrossProccase Web::Permissions::PermissionName::Notifications:return NotificationManager::the().backend().os_authorization_is_undetermined();case Web::Permissions::PermissionName::Microphone:- return false;+ return view().microphone_authorization() == MicrophoneAuthorization::NotDetermined;}VERIFY_NOT_REACHED();}();@@ -1843,10 +1852,24 @@ void WebContentPage::did_request_permission(u64 request_id, Web::HTML::CrossProc}// The AudioServer hears of the permission before the page does, so the page's first request finds it in place.- if (permission_name == Web::Permissions::PermissionName::Microphone)+ auto is_microphone = permission_name == Web::Permissions::PermissionName::Microphone;+ if (is_microphone)page->client().update_audio_capture_permission();- page->async_permission_request_completed(request_id, state);+ if (!is_microphone || state != Web::Permissions::EffectiveState::Granted) {+ page->async_permission_request_completed(request_id, state);+ return;+ }++ // The system may only now ask the user for the microphone. If it keeps it from the browser, the site keeps the+ // user's answer for when it relents, but this request gets nothing.+ page->view().ensure_microphone_authorization([page, request_id, document_id](bool authorized) {+ if (!page->is_open())+ return;+ // The user may have taken the permission away while the system asked.+ auto granted = authorized && page->document_may_use(document_id, Web::Permissions::PermissionName::Microphone);+ page->async_permission_request_completed(request_id, granted ? Web::Permissions::EffectiveState::Granted : Web::Permissions::EffectiveState::Prompt);+ });});}@@ -1892,6 +1915,41 @@ void WebContentPage::set_next_permission_prompt_outcome_for_testing(String constview().set_next_permission_prompt_outcome_for_testing(*permission_name, *prompt_outcome, held);}+static Optional<MicrophoneAuthorization> microphone_authorization_from_string(StringView string)+{+ if (string == "not-determined"sv)+ return MicrophoneAuthorization::NotDetermined;+ if (string == "authorized"sv)+ return MicrophoneAuthorization::Authorized;+ if (string == "denied"sv)+ return MicrophoneAuthorization::Denied;+ return {};+}++void WebContentPage::set_system_microphone_authorization_for_testing(String const& authorization, String const& answer, bool held)+{+ auto current = microphone_authorization_from_string(authorization);+ auto answered = microphone_authorization_from_string(answer);+ if (current.has_value() && answered.has_value())+ view().set_microphone_authorization_for_testing(*current, *answered, held);+}++void WebContentPage::release_system_microphone_answer_for_testing()+{+ view().release_system_microphone_answer_for_testing();+}++String WebContentPage::microphone_state_for_testing() const+{+ JsonObject state;+ state.set("noticesShown"sv, view().microphone_denied_notices_shown_for_testing());+ state.set("systemRequests"sv, view().system_microphone_requests_for_testing());+ state.set("captureDecisions"sv, client().audio_capture_decision_count());+ state.set("captureRefusals"sv, client().audio_capture_refusal_count());+ state.set("dismissals"sv, view().session().permission_manager->dismissals_for_testing(Web::Permissions::PermissionName::Microphone, view().permission_origin()));+ return state.serialized();+}+void WebContentPage::release_held_permission_prompt_for_testing(u32 waiters){view().release_held_permission_prompt_for_testing(waiters);diff --git a/Libraries/LibWebView/WebContentPage.h b/Libraries/LibWebView/WebContentPage.hindex ce77fa9074d..9eeacb3e019 100644--- a/Libraries/LibWebView/WebContentPage.h+++ b/Libraries/LibWebView/WebContentPage.h@@ -126,6 +126,9 @@ public:Web::Permissions::PermissionSnapshot set_permission_for_testing(Web::HTML::CrossProcessId document_id, String const& name, String const& state);void set_next_permission_prompt_outcome_for_testing(String const& name, String const& outcome, bool held);+ void set_system_microphone_authorization_for_testing(String const& authorization, String const& answer, bool held);+ void release_system_microphone_answer_for_testing();+ String microphone_state_for_testing() const;void release_held_permission_prompt_for_testing(u32 waiters);Web::Permissions::PermissionSnapshot advance_permission_clock_for_testing(u64 milliseconds);void close();diff --git a/Libraries/LibWebView/WebContentTestClient.cpp b/Libraries/LibWebView/WebContentTestClient.cppindex bd972c6120c..828fa017da7 100644--- a/Libraries/LibWebView/WebContentTestClient.cpp+++ b/Libraries/LibWebView/WebContentTestClient.cpp@@ -56,6 +56,25 @@ void WebContentTestClient::set_next_permission_prompt_outcome_for_testing(Web::Ppage->set_next_permission_prompt_outcome_for_testing(name, outcome, held);}+void WebContentTestClient::set_system_microphone_authorization_for_testing(Web::PageId page_id, String authorization, String answer, bool held)+{+ if (auto* page = m_client.page(page_id))+ page->set_system_microphone_authorization_for_testing(authorization, answer, held);+}++void WebContentTestClient::release_system_microphone_answer_for_testing(Web::PageId page_id)+{+ if (auto* page = m_client.page(page_id))+ page->release_system_microphone_answer_for_testing();+}++Messages::WebContentTestClient::DidRequestMicrophoneStateForTestingResponse WebContentTestClient::did_request_microphone_state_for_testing(Web::PageId page_id)+{+ if (auto* page = m_client.page(page_id))+ return page->microphone_state_for_testing();+ return "{}"_string;+}+void WebContentTestClient::release_held_permission_prompt_for_testing(Web::PageId page_id, u32 waiters){if (auto* page = m_client.page(page_id))diff --git a/Libraries/LibWebView/WebContentTestClient.h b/Libraries/LibWebView/WebContentTestClient.hindex 653c175c558..bfd80c8ecaa 100644--- a/Libraries/LibWebView/WebContentTestClient.h+++ b/Libraries/LibWebView/WebContentTestClient.h@@ -46,6 +46,9 @@ private:virtual Messages::WebContentTestClient::DidRequestSessionStoreTabStateForTestingResponse did_request_session_store_tab_state_for_testing(Web::PageId page_id) override;virtual Messages::WebContentTestClient::SetPermissionForTestingResponse set_permission_for_testing(Web::PageId, Web::HTML::CrossProcessId document_id, String name, String state) override;virtual void set_next_permission_prompt_outcome_for_testing(Web::PageId, String name, String outcome, bool held) override;+ virtual void set_system_microphone_authorization_for_testing(Web::PageId, String authorization, String answer, bool held) override;+ virtual void release_system_microphone_answer_for_testing(Web::PageId) override;+ virtual Messages::WebContentTestClient::DidRequestMicrophoneStateForTestingResponse did_request_microphone_state_for_testing(Web::PageId) override;virtual void release_held_permission_prompt_for_testing(Web::PageId, u32 waiters) override;virtual Messages::WebContentTestClient::AdvancePermissionClockForTestingResponse advance_permission_clock_for_testing(Web::PageId, u64 milliseconds) override;virtual Messages::WebContentTestClient::CreateVirtualGamepadResponse create_virtual_gamepad() override;diff --git a/Services/WebContent/PageClient.cpp b/Services/WebContent/PageClient.cppindex 311535f5a8e..c06c971fd9b 100644--- a/Services/WebContent/PageClient.cpp+++ b/Services/WebContent/PageClient.cpp@@ -1399,6 +1399,25 @@ void PageClient::page_did_set_next_permission_prompt_outcome_for_testing(String(void)test_connection->send_sync_but_allow_failure<Messages::WebContentTestClient::SetNextPermissionPromptOutcomeForTesting>(m_id, name, outcome, held);}+void PageClient::page_did_set_system_microphone_authorization_for_testing(String const& authorization, String const& answer, bool held)+{+ if (auto* test_connection = client().test_connection())+ (void)test_connection->send_sync_but_allow_failure<Messages::WebContentTestClient::SetSystemMicrophoneAuthorizationForTesting>(m_id, authorization, answer, held);+}++void PageClient::page_did_release_system_microphone_answer_for_testing()+{+ if (auto* test_connection = client().test_connection())+ (void)test_connection->send_sync_but_allow_failure<Messages::WebContentTestClient::ReleaseSystemMicrophoneAnswerForTesting>(m_id);+}++String PageClient::page_did_request_microphone_state_for_testing()+{+ if (auto* test_connection = client().test_connection())+ return test_connection->did_request_microphone_state_for_testing(m_id);+ return "{}"_string;+}+void PageClient::page_did_release_held_permission_prompt_for_testing(u32 waiters){if (auto* test_connection = client().test_connection())diff --git a/Services/WebContent/PageClient.h b/Services/WebContent/PageClient.hindex 05713d531bb..f1ebc450351 100644--- a/Services/WebContent/PageClient.h+++ b/Services/WebContent/PageClient.h@@ -366,6 +366,9 @@ private:virtual Optional<Web::Permissions::PermissionSnapshot> page_did_request_permission_snapshot(URL::Origin const& top_level_origin) override;virtual Optional<Web::Permissions::PermissionSnapshot> page_did_set_permission_for_testing(Web::HTML::CrossProcessId document_id, String const& name, String const& state) override;virtual void page_did_set_next_permission_prompt_outcome_for_testing(String const& name, String const& outcome, bool held) override;+ virtual void page_did_set_system_microphone_authorization_for_testing(String const& authorization, String const& answer, bool held) override;+ virtual void page_did_release_system_microphone_answer_for_testing() override;+ virtual String page_did_request_microphone_state_for_testing() override;virtual void page_did_release_held_permission_prompt_for_testing(u32 waiters) override;virtual Optional<Web::Permissions::PermissionSnapshot> page_did_advance_permission_clock_for_testing(u64 milliseconds) override;virtual void page_did_request_show_notification(u64 notification_id, Web::HTML::CrossProcessId document_id, Web::NotificationsAPI::NotificationData const&, RefPtr<Gfx::Bitmap const> icon) override;diff --git a/Services/WebContent/WebContentTestClient.ipc b/Services/WebContent/WebContentTestClient.ipcindex 3a3b750c2c9..4585eb8387a 100644--- a/Services/WebContent/WebContentTestClient.ipc+++ b/Services/WebContent/WebContentTestClient.ipc@@ -21,6 +21,9 @@ endpoint WebContentTestClient routed by Web::PageId page_id[NotRouted] set_permission_for_testing(Web::PageId page_id, Web::HTML::CrossProcessId document_id, String name, String state) => (Web::Permissions::PermissionSnapshot snapshot)[NotRouted] set_next_permission_prompt_outcome_for_testing(Web::PageId page_id, String name, String outcome, bool held) => ()+ [NotRouted] set_system_microphone_authorization_for_testing(Web::PageId page_id, String authorization, String answer, bool held) => ()+ [NotRouted] release_system_microphone_answer_for_testing(Web::PageId page_id) => ()+ [NotRouted] did_request_microphone_state_for_testing(Web::PageId page_id) => (String state)[NotRouted] release_held_permission_prompt_for_testing(Web::PageId page_id, u32 waiters) => ()[NotRouted] advance_permission_clock_for_testing(Web::PageId page_id, u64 milliseconds) => (Web::Permissions::PermissionSnapshot snapshot)[NotRouted] did_spoof_document_origin_for_testing(Web::PageId page_id, Web::HTML::EnvironmentId environment_id, URL::Origin origin) => ()diff --git a/Tests/LibWeb/Text/expected/PermissionsAPI/microphone-capture-refused-notice-shows-once.txt b/Tests/LibWeb/Text/expected/PermissionsAPI/microphone-capture-refused-notice-shows-once.txtnew file mode 100644index 00000000000..c402bca208e--- /dev/null+++ b/Tests/LibWeb/Text/expected/PermissionsAPI/microphone-capture-refused-notice-shows-once.txt@@ -0,0 +1,6 @@+capture decisions: 2+capture refusals: 2+notices shown: 1+dismissals: 0+query: granted+request: granteddiff --git a/Tests/LibWeb/Text/expected/PermissionsAPI/microphone-denied-by-system-skips-prompt.txt b/Tests/LibWeb/Text/expected/PermissionsAPI/microphone-denied-by-system-skips-prompt.txtnew file mode 100644index 00000000000..3c3b1bd1628--- /dev/null+++ b/Tests/LibWeb/Text/expected/PermissionsAPI/microphone-denied-by-system-skips-prompt.txt@@ -0,0 +1,2 @@+request: denied+query: promptdiff --git a/Tests/LibWeb/Text/expected/PermissionsAPI/microphone-denied-notice-cancelled-before-display.txt b/Tests/LibWeb/Text/expected/PermissionsAPI/microphone-denied-notice-cancelled-before-display.txtnew file mode 100644index 00000000000..c227751b340--- /dev/null+++ b/Tests/LibWeb/Text/expected/PermissionsAPI/microphone-denied-notice-cancelled-before-display.txt@@ -0,0 +1,3 @@+waiting to come up: 0+after returning: 1+on another page of the site: 1diff --git a/Tests/LibWeb/Text/expected/PermissionsAPI/microphone-denied-notice-shows-once.txt b/Tests/LibWeb/Text/expected/PermissionsAPI/microphone-denied-notice-shows-once.txtnew file mode 100644index 00000000000..22b8ec76562--- /dev/null+++ b/Tests/LibWeb/Text/expected/PermissionsAPI/microphone-denied-notice-shows-once.txt@@ -0,0 +1,6 @@+request 1: denied+request 2: denied+request 3: denied+notices shown: 1+dismissals: 0+query: promptdiff --git a/Tests/LibWeb/Text/expected/PermissionsAPI/microphone-denied-notice-stays-with-the-requesting-site.txt b/Tests/LibWeb/Text/expected/PermissionsAPI/microphone-denied-notice-stays-with-the-requesting-site.txtnew file mode 100644index 00000000000..e48e0f5dd27--- /dev/null+++ b/Tests/LibWeb/Text/expected/PermissionsAPI/microphone-denied-notice-stays-with-the-requesting-site.txt@@ -0,0 +1,2 @@+the system is asking+notices shown once the system says no: 0diff --git a/Tests/LibWeb/Text/expected/PermissionsAPI/microphone-denied-notices-join.txt b/Tests/LibWeb/Text/expected/PermissionsAPI/microphone-denied-notices-join.txtnew file mode 100644index 00000000000..2b06e10d902--- /dev/null+++ b/Tests/LibWeb/Text/expected/PermissionsAPI/microphone-denied-notices-join.txt@@ -0,0 +1,4 @@+first: denied+second: denied+notices shown while one waits to come up: 0+notices shown once it came up: 1diff --git a/Tests/LibWeb/Text/expected/PermissionsAPI/microphone-revoked-while-system-asks.txt b/Tests/LibWeb/Text/expected/PermissionsAPI/microphone-revoked-while-system-asks.txtnew file mode 100644index 00000000000..bd5a5dfcd54--- /dev/null+++ b/Tests/LibWeb/Text/expected/PermissionsAPI/microphone-revoked-while-system-asks.txt@@ -0,0 +1,2 @@+request: denied+query: denieddiff --git a/Tests/LibWeb/Text/expected/PermissionsAPI/microphone-system-asks-after-site-is-allowed.txt b/Tests/LibWeb/Text/expected/PermissionsAPI/microphone-system-asks-after-site-is-allowed.txtnew file mode 100644index 00000000000..f56745f3a51--- /dev/null+++ b/Tests/LibWeb/Text/expected/PermissionsAPI/microphone-system-asks-after-site-is-allowed.txt@@ -0,0 +1,4 @@+system denies, request: denied+system denies, query: granted+system allows, request: granted+system allows, query: granteddiff --git a/Tests/LibWeb/Text/input/PermissionsAPI/microphone-capture-refused-notice-shows-once.html b/Tests/LibWeb/Text/input/PermissionsAPI/microphone-capture-refused-notice-shows-once.htmlnew file mode 100644index 00000000000..e99c0875104--- /dev/null+++ b/Tests/LibWeb/Text/input/PermissionsAPI/microphone-capture-refused-notice-shows-once.html@@ -0,0 +1,38 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ // A site the user allowed earlier asks the AudioServer to capture once something reads its track. While the system+ // denies the browser the microphone, every such capture is refused, but the user is told only once, and the site's+ // permission is left as it was.+ asyncTest(async done => {+ const state = () => JSON.parse(internals.microphoneState());+ // The process counts its capture decisions, and an earlier test may have run in it.+ const { captureDecisions: decisionsBefore, captureRefusals: refusalsBefore } = state();+ const captureDecisions = () => state().captureDecisions - decisionsBefore;+ const captureRefusals = () => state().captureRefusals - refusalsBefore;+ const captureDecided = count => waitForCondition(() => captureDecisions() >= count);++ await internals.setPermission("microphone", "granted");+ internals.setSystemMicrophoneAuthorization("denied");+ internals.setNextPermissionPromptOutcome("microphone", "dismiss");++ const context = new AudioContext();+ for (let i = 1; i <= 2; ++i) {+ const stream = await navigator.mediaDevices.getUserMedia({ audio: true });+ context.createMediaStreamSource(stream);+ await captureDecided(i);+ // A capture of the same device joins one that waits on the AudioServer, so the next starts once this one's+ // refusal has reached this process.+ await waitForCondition(() => !internals.audioCaptureIsPending());+ }++ const { noticesShown, dismissals } = state();+ println(`capture decisions: ${captureDecisions()}`);+ println(`capture refusals: ${captureRefusals()}`);+ println(`notices shown: ${noticesShown}`);+ println(`dismissals: ${dismissals}`);+ println(`query: ${(await navigator.permissions.query({ name: "microphone" })).state}`);+ println(`request: ${await internals.requestPermission("microphone")}`);+ done();+ });+</script>diff --git a/Tests/LibWeb/Text/input/PermissionsAPI/microphone-denied-by-system-skips-prompt.html b/Tests/LibWeb/Text/input/PermissionsAPI/microphone-denied-by-system-skips-prompt.htmlnew file mode 100644index 00000000000..e6c84ffa9f4--- /dev/null+++ b/Tests/LibWeb/Text/input/PermissionsAPI/microphone-denied-by-system-skips-prompt.html@@ -0,0 +1,11 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ asyncTest(async done => {+ internals.setSystemMicrophoneAuthorization("denied");+ internals.setNextPermissionPromptOutcome("microphone", "allow");+ println(`request: ${await internals.requestPermission("microphone")}`);+ println(`query: ${(await navigator.permissions.query({ name: "microphone" })).state}`);+ done();+ });+</script>diff --git a/Tests/LibWeb/Text/input/PermissionsAPI/microphone-denied-notice-cancelled-before-display.html b/Tests/LibWeb/Text/input/PermissionsAPI/microphone-denied-notice-cancelled-before-display.htmlnew file mode 100644index 00000000000..35f953051b0--- /dev/null+++ b/Tests/LibWeb/Text/input/PermissionsAPI/microphone-denied-notice-cancelled-before-display.html@@ -0,0 +1,52 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ // A notice the user never saw, because its page went away while it waited to come up, doesn't count against the+ // site: the site's next request in the tab shows one, and only then does the site go quiet there. The site is a+ // host of its own, shown in a popup.+ asyncTest(async done => {+ const httpServer = httpTestServer();+ const runId = crypto.randomUUID();+ const htmlHeaders = { "Content-Type": "text/html" };+ const site = uniqueLocalhostHostname("microphone-notice-site");+ const elsewhere = uniqueLocalhostHostname("microphone-notice-elsewhere");++ const echo = async (host, name, body) => {+ const url = new URL(await httpServer.createEcho("GET", `/${name}-${runId}`, {+ status: 200,+ headers: htmlHeaders,+ body: `<!DOCTYPE html><script>${body}<\/script>`,+ }));+ url.hostname = host;+ return url.href;+ };+ const report = `const report = message => opener.postMessage(message, "*");+ const noticesShown = () => JSON.parse(internals.microphoneState()).noticesShown;`;++ const againUrl = await echo(site, "again", `${report}+ internals.requestPermission("microphone").then(() => report(\`on another page of the site: \${noticesShown()}\`));`);+ const returnUrl = await echo(site, "return", `${report}+ internals.requestPermission("microphone").then(() => {+ report(\`after returning: \${noticesShown()}\`);+ location.href = ${JSON.stringify(againUrl)};+ });`);+ const elsewhereUrl = await echo(elsewhere, "elsewhere", `location.href = ${JSON.stringify(returnUrl)};`);+ const firstUrl = await echo(site, "first", `${report}+ internals.setSystemMicrophoneAuthorization("denied");+ internals.setNextPermissionPromptOutcome("microphone", "dismiss", true);+ internals.requestPermission("microphone").then(() => {+ report(\`waiting to come up: \${noticesShown()}\`);+ location.href = ${JSON.stringify(elsewhereUrl)};+ });`);++ let popup;+ addEventListener("message", event => {+ println(event.data);+ if (event.data.startsWith("on another page of the site")) {+ popup.close();+ done();+ }+ });+ popup = window.open(firstUrl);+ });+</script>diff --git a/Tests/LibWeb/Text/input/PermissionsAPI/microphone-denied-notice-shows-once.html b/Tests/LibWeb/Text/input/PermissionsAPI/microphone-denied-notice-shows-once.htmlnew file mode 100644index 00000000000..c398339a1de--- /dev/null+++ b/Tests/LibWeb/Text/input/PermissionsAPI/microphone-denied-notice-shows-once.html@@ -0,0 +1,16 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ asyncTest(async done => {+ internals.setSystemMicrophoneAuthorization("denied");+ internals.setNextPermissionPromptOutcome("microphone", "dismiss");+ for (let i = 1; i <= 3; ++i)+ println(`request ${i}: ${await internals.requestPermission("microphone")}`);++ const state = JSON.parse(internals.microphoneState());+ println(`notices shown: ${state.noticesShown}`);+ println(`dismissals: ${state.dismissals}`);+ println(`query: ${(await navigator.permissions.query({ name: "microphone" })).state}`);+ done();+ });+</script>diff --git a/Tests/LibWeb/Text/input/PermissionsAPI/microphone-denied-notice-stays-with-the-requesting-site.html b/Tests/LibWeb/Text/input/PermissionsAPI/microphone-denied-notice-stays-with-the-requesting-site.htmlnew file mode 100644index 00000000000..83d55586f9c--- /dev/null+++ b/Tests/LibWeb/Text/input/PermissionsAPI/microphone-denied-notice-stays-with-the-requesting-site.html@@ -0,0 +1,46 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ // The tab leaves the site the user allowed while the system asks about the microphone, and the system says no once+ // another site is shown. The notice is about the site that asked, so it doesn't come up over the other one. The+ // sites are hosts of their own, shown in a popup.+ asyncTest(async done => {+ const httpServer = httpTestServer();+ const runId = crypto.randomUUID();+ const echo = async (host, name, body) => {+ const url = new URL(await httpServer.createEcho("GET", `/${name}-${runId}`, {+ status: 200,+ headers: { "Content-Type": "text/html" },+ body: `<!DOCTYPE html><script>${body}<\/script>`,+ }));+ url.hostname = host;+ return url.href;+ };+ const report = `const report = message => opener.postMessage(message, "*");+ const microphoneState = () => JSON.parse(internals.microphoneState());`;++ const elsewhereUrl = await echo(uniqueLocalhostHostname("microphone-notice-elsewhere"), "elsewhere", `${report}+ internals.releaseSystemMicrophoneAnswer();+ report(\`notices shown once the system says no: \${microphoneState().noticesShown}\`);`);+ const siteUrl = await echo(uniqueLocalhostHostname("microphone-notice-site"), "site", `${report}+ internals.setSystemMicrophoneAuthorization("not-determined", "denied", true);+ internals.setNextPermissionPromptOutcome("microphone", "allow");+ internals.requestPermission("microphone");+ (async () => {+ while (microphoneState().systemRequests < 1)+ await new Promise(resolve => setTimeout(resolve, 10));+ report("the system is asking");+ location.href = ${JSON.stringify(elsewhereUrl)};+ })();`);++ let popup;+ addEventListener("message", event => {+ println(event.data);+ if (event.data.startsWith("notices shown")) {+ popup.close();+ done();+ }+ });+ popup = window.open(siteUrl);+ });+</script>diff --git a/Tests/LibWeb/Text/input/PermissionsAPI/microphone-denied-notices-join.html b/Tests/LibWeb/Text/input/PermissionsAPI/microphone-denied-notices-join.htmlnew file mode 100644index 00000000000..7b42ada3e41--- /dev/null+++ b/Tests/LibWeb/Text/input/PermissionsAPI/microphone-denied-notices-join.html@@ -0,0 +1,19 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ asyncTest(async done => {+ const noticesShown = () => JSON.parse(internals.microphoneState()).noticesShown;++ internals.setSystemMicrophoneAuthorization("denied");+ internals.setNextPermissionPromptOutcome("microphone", "dismiss", true);+ const first = internals.requestPermission("microphone");+ const second = internals.requestPermission("microphone");+ println(`first: ${await first}`);+ println(`second: ${await second}`);+ println(`notices shown while one waits to come up: ${noticesShown()}`);++ internals.releaseHeldPermissionPrompt(2);+ println(`notices shown once it came up: ${noticesShown()}`);+ done();+ });+</script>diff --git a/Tests/LibWeb/Text/input/PermissionsAPI/microphone-revoked-while-system-asks.html b/Tests/LibWeb/Text/input/PermissionsAPI/microphone-revoked-while-system-asks.htmlnew file mode 100644index 00000000000..a185f6a89f7--- /dev/null+++ b/Tests/LibWeb/Text/input/PermissionsAPI/microphone-revoked-while-system-asks.html@@ -0,0 +1,21 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ // The user allows the site, and blocks it again while the system is still asking them about the microphone. The+ // system's yes doesn't bring the site's permission back.+ asyncTest(async done => {+ const systemRequests = () => JSON.parse(internals.microphoneState()).systemRequests;++ internals.setSystemMicrophoneAuthorization("not-determined", "authorized", true);+ internals.setNextPermissionPromptOutcome("microphone", "allow");+ const request = internals.requestPermission("microphone");+ while (systemRequests() < 1)+ await new Promise(resolve => setTimeout(resolve, 10));++ await internals.setPermission("microphone", "denied");+ internals.releaseSystemMicrophoneAnswer();+ println(`request: ${await request}`);+ println(`query: ${(await navigator.permissions.query({ name: "microphone" })).state}`);+ done();+ });+</script>diff --git a/Tests/LibWeb/Text/input/PermissionsAPI/microphone-system-asks-after-site-is-allowed.html b/Tests/LibWeb/Text/input/PermissionsAPI/microphone-system-asks-after-site-is-allowed.htmlnew file mode 100644index 00000000000..ee6944ecc7c--- /dev/null+++ b/Tests/LibWeb/Text/input/PermissionsAPI/microphone-system-asks-after-site-is-allowed.html@@ -0,0 +1,17 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ asyncTest(async done => {+ internals.setSystemMicrophoneAuthorization("not-determined", "denied");+ internals.setNextPermissionPromptOutcome("microphone", "allow");+ println(`system denies, request: ${await internals.requestPermission("microphone")}`);+ println(`system denies, query: ${(await navigator.permissions.query({ name: "microphone" })).state}`);++ await internals.setPermission("microphone", "prompt");+ internals.setSystemMicrophoneAuthorization("not-determined", "authorized");+ internals.setNextPermissionPromptOutcome("microphone", "allow");+ println(`system allows, request: ${await internals.requestPermission("microphone")}`);+ println(`system allows, query: ${(await navigator.permissions.query({ name: "microphone" })).state}`);+ done();+ });+</script>diff --git a/Tests/UI/Qt/TestPermissionPromptPopover.cpp b/Tests/UI/Qt/TestPermissionPromptPopover.cppindex 79b167cb64d..7afb06797c6 100644--- a/Tests/UI/Qt/TestPermissionPromptPopover.cpp+++ b/Tests/UI/Qt/TestPermissionPromptPopover.cpp@@ -26,6 +26,13 @@ static WebView::PermissionPromptRequest request_for(StringView url, PermissionNareturn { name, parsed_url->origin(), parsed_url->scheme() == "file"sv, show_os_hint };}+static WebView::PermissionPromptRequest notice_for(StringView url)+{+ auto request = request_for(url, PermissionName::Microphone);+ request.kind = WebView::PermissionPromptKind::SystemDeniedNotice;+ return request;+}+template<typename T>static T& child(QWidget& parent, char const* name){@@ -153,10 +160,13 @@ TEST_CASE(notifications_prompt_has_two_answers)TEST_CASE(hint_text_names_the_feature){PermissionPromptPopover location(nullptr, request_for("https://maps.example.com/"sv, PermissionName::Geolocation, true));- EXPECT_EQ(child<QLabel>(location, "LadybirdPermissionPromptHint").text(), QStringLiteral("macOS will then ask you to let Ladybird use your location."));+ EXPECT_EQ(child<QLabel>(location, "LadybirdPermissionPromptHint").text(), QStringLiteral("Your system will then ask you to let Ladybird know your location."));++ PermissionPromptPopover microphone(nullptr, request_for("https://talk.example.org/"sv, PermissionName::Microphone, true));+ EXPECT_EQ(child<QLabel>(microphone, "LadybirdPermissionPromptHint").text(), QStringLiteral("Your system will then ask you to let Ladybird use your microphone."));PermissionPromptPopover notifications(nullptr, request_for("https://mail.example.com/"sv, PermissionName::Notifications, true));- EXPECT_EQ(child<QLabel>(notifications, "LadybirdPermissionPromptHint").text(), QStringLiteral("macOS will then ask you to let Ladybird show notifications."));+ EXPECT_EQ(child<QLabel>(notifications, "LadybirdPermissionPromptHint").text(), QStringLiteral("Your system will then ask you to let Ladybird send you notifications."));}TEST_CASE(hint_shows_only_when_requested)@@ -167,7 +177,7 @@ TEST_CASE(hint_shows_only_when_requested)PermissionPromptPopover with_hint(nullptr, request_for("https://maps.example.com/"sv, PermissionName::Geolocation, true));auto& hint = child<QLabel>(with_hint, "LadybirdPermissionPromptHint");EXPECT(!hint.isHidden());- EXPECT_EQ(hint.text(), QStringLiteral("macOS will then ask you to let Ladybird use your location."));+ EXPECT_EQ(hint.text(), QStringLiteral("Your system will then ask you to let Ladybird know your location."));}TEST_CASE(suspending_hides_without_an_answer)@@ -231,6 +241,46 @@ TEST_CASE(queued_requests_show_one_at_a_time)EXPECT(second_outcomes == Vector { PromptOutcome::Ignored });}+TEST_CASE(a_notice_tells_and_offers_the_setting)+{+ PermissionPromptPopover popover(nullptr, notice_for("https://talk.example.org/"sv));+ EXPECT_EQ(child<QLabel>(popover, "LadybirdPermissionPromptTitle").text(), QStringLiteral("Ladybird can't use your microphone"));+ EXPECT_EQ(child<QLabel>(popover, "LadybirdPermissionPromptBody").text(), QStringLiteral("Your system's privacy settings don't let Ladybird use your microphone."));+ EXPECT(!popover.findChild<QPushButton*>(QStringLiteral("LadybirdPermissionPromptAllowAlways")));++ Recorder recorder;+ recorder.attach(popover);+ auto settings_opened = 0;+ popover.on_open_settings = [&] { ++settings_opened; };+ popover.show();+ child<QPushButton>(popover, "LadybirdPermissionPromptOpenSettings").click();+ EXPECT_EQ(settings_opened, 1);+ EXPECT(recorder.outcomes == Vector { PromptOutcome::Dismissed });+}++TEST_CASE(a_suspended_queue_shows_its_notice_once_resumed)+{+ PermissionPromptQueue queue;+ PermissionPromptPopover* popover = nullptr;+ auto times_shown = 0;+ queue.create_popover = [&](WebView::PermissionPromptRequest const& request) {+ popover = new PermissionPromptPopover(nullptr, request);+ popover->on_shown = [&] { ++times_shown; };+ return popover;+ };++ queue.suspend();+ queue.enqueue(notice_for("https://talk.example.org/"sv), [](PromptOutcome) { });+ VERIFY(popover);+ EXPECT(!popover->isVisible());+ EXPECT_EQ(times_shown, 0);++ queue.resume();+ EXPECT(popover->isVisible());+ EXPECT_EQ(times_shown, 1);+ queue.ignore_all();+}+TEST_CASE(cancelling_a_queued_request_drops_it_silently){PermissionPromptQueue queue;diff --git a/UI/Qt/Application.cpp b/UI/Qt/Application.cppindex 0661756b50d..6ac2e0a18f9 100644--- a/UI/Qt/Application.cpp+++ b/UI/Qt/Application.cpp@@ -8,8 +8,10 @@#include <LibURL/InternalURLs.h>#include <LibURL/URL.h>#include <LibWebView/CanonicalTraversable.h>+#include <LibWebView/MicrophoneAuthorizer.h>#include <LibWebView/NotificationBackend.h>#if defined(AK_OS_MACOS)+# include <LibWebView/MicrophoneAuthorizerMacOS.h># include <LibWebView/NotificationBackendMacOS.h>#elif defined(AK_OS_LINUX) || defined(AK_OS_FREEBSD)# include <LibWebView/NotificationBackendFreedesktop.h>@@ -667,6 +669,15 @@ Core::EventLoop& Application::create_platform_event_loop()return event_loop;}+NonnullOwnPtr<WebView::MicrophoneAuthorizer> Application::create_microphone_authorizer()+{+#if defined(AK_OS_MACOS)+ return make<WebView::MicrophoneAuthorizerMacOS>();+#else+ return WebView::Application::create_microphone_authorizer();+#endif+}+Optional<String> Application::ui_font_family() const{if (!m_application)diff --git a/UI/Qt/Application.h b/UI/Qt/Application.hindex c6dec74cba3..2529f66ec4a 100644--- a/UI/Qt/Application.h+++ b/UI/Qt/Application.h@@ -137,6 +137,7 @@ private:virtual Core::EventLoop& create_platform_event_loop() override;virtual void create_platform_actions() override;+ virtual NonnullOwnPtr<WebView::MicrophoneAuthorizer> create_microphone_authorizer() override;virtual Optional<String> ui_font_family() const override;virtual Web::CSS::PreferredColorScheme interface_color_scheme() const override;diff --git a/UI/Qt/PermissionPromptPopover.cpp b/UI/Qt/PermissionPromptPopover.cppindex 6d146aa207c..7396286fed6 100644--- a/UI/Qt/PermissionPromptPopover.cpp+++ b/UI/Qt/PermissionPromptPopover.cpp@@ -49,20 +49,6 @@ static QString feature_text(Web::Permissions::PermissionName name)VERIFY_NOT_REACHED();}-// Shown while the system hasn't yet been asked whether Ladybird may use the feature: it asks right after this prompt.-static QString hint_text(Web::Permissions::PermissionName name)-{- switch (name) {- case Web::Permissions::PermissionName::Geolocation:- return QStringLiteral("macOS will then ask you to let Ladybird use your location.");- case Web::Permissions::PermissionName::Microphone:- return QStringLiteral("macOS will then ask you to let Ladybird use your microphone.");- case Web::Permissions::PermissionName::Notifications:- return QStringLiteral("macOS will then ask you to let Ladybird show notifications.");- }- VERIFY_NOT_REACHED();-}-// A notification grant has no one-time form: One that lapsed once the site had no visible tab for a while would end// right when a notification is wanted. So that prompt offers a lasting Allow and Never allow only.static bool offers_one_time_grant(Web::Permissions::PermissionName name)@@ -104,19 +90,31 @@ PermissionPromptPopover::PermissionPromptPopover(QWidget* parent, WebView::Permim_icon_tile->setFixedSize(32, 32);m_icon_tile->setAlignment(Qt::AlignCenter);header->addWidget(m_icon_tile, 0, Qt::AlignTop);- auto* title = new QLabel(QStringLiteral("%1 wants to %2").arg(requester_text(request), feature_text(request.name)), &card());+ auto is_notice = request.kind == WebView::PermissionPromptKind::SystemDeniedNotice;+ auto title_text = is_notice+ ? QStringLiteral("Ladybird can't %1").arg(feature_text(request.name))+ : QStringLiteral("%1 wants to %2").arg(requester_text(request), feature_text(request.name));+ auto* title = new QLabel(title_text, &card());title->setObjectName("LadybirdPermissionPromptTitle");title->setTextFormat(Qt::PlainText);title->setWordWrap(true);header->addWidget(title, 1);layout->addLayout(header);- auto* hint = new QLabel(hint_text(request.name), &card());+ // Shown while the system hasn't yet been asked whether Ladybird may use the feature: it asks right after this prompt.+ auto* hint = new QLabel(QStringLiteral("Your system will then ask you to let Ladybird %1.").arg(feature_text(request.name)), &card());hint->setObjectName("LadybirdPermissionPromptHint");hint->setWordWrap(true);hint->setVisible(request.show_os_hint);layout->addWidget(hint);+ if (is_notice) {+ auto* body = new QLabel(QStringLiteral("Your system's privacy settings don't let Ladybird %1.").arg(feature_text(request.name)), &card());+ body->setObjectName("LadybirdPermissionPromptBody");+ body->setWordWrap(true);+ layout->addWidget(body);+ }+layout->addSpacing(8);auto add_button = [&](char const* name, QString const& text, Web::Permissions::PromptOutcome outcome) {auto* button = new QPushButton(text, &card());@@ -126,12 +124,23 @@ PermissionPromptPopover::PermissionPromptPopover(QWidget* parent, WebView::Permibutton->setAttribute(Qt::WA_LayoutUsesWidgetRect);QObject::connect(button, &QPushButton::clicked, this, [this, outcome] { finish(outcome); });layout->addWidget(button);+ return button;};- auto one_time_grant = offers_one_time_grant(request.name);- add_button("LadybirdPermissionPromptAllowAlways", one_time_grant ? QStringLiteral("Allow while visiting the site") : QStringLiteral("Allow"), Web::Permissions::PromptOutcome::AllowAlways);- if (one_time_grant)- add_button("LadybirdPermissionPromptAllowOnce", QStringLiteral("Allow this time"), Web::Permissions::PromptOutcome::AllowOnce);- add_button("LadybirdPermissionPromptBlock", QStringLiteral("Never allow"), Web::Permissions::PromptOutcome::Block);+ if (is_notice) {+ // The notice decides nothing for the site, so either button only closes it.+ auto* open_settings = add_button("LadybirdPermissionPromptOpenSettings", QStringLiteral("Open Settings"), Web::Permissions::PromptOutcome::Dismissed);+ QObject::connect(open_settings, &QPushButton::clicked, this, [this] {+ if (on_open_settings)+ on_open_settings();+ });+ add_button("LadybirdPermissionPromptNotNow", QStringLiteral("Not now"), Web::Permissions::PromptOutcome::Dismissed);+ } else {+ auto one_time_grant = offers_one_time_grant(request.name);+ add_button("LadybirdPermissionPromptAllowAlways", one_time_grant ? QStringLiteral("Allow while visiting the site") : QStringLiteral("Allow"), Web::Permissions::PromptOutcome::AllowAlways);+ if (one_time_grant)+ add_button("LadybirdPermissionPromptAllowOnce", QStringLiteral("Allow this time"), Web::Permissions::PromptOutcome::AllowOnce);+ add_button("LadybirdPermissionPromptBlock", QStringLiteral("Never allow"), Web::Permissions::PromptOutcome::Block);+ }update_icon();adjustSize();diff --git a/UI/Qt/PermissionPromptPopover.h b/UI/Qt/PermissionPromptPopover.hindex 74d8f57281c..206a0bbdd9c 100644--- a/UI/Qt/PermissionPromptPopover.h+++ b/UI/Qt/PermissionPromptPopover.h@@ -43,6 +43,8 @@ public:Function<void(Web::Permissions::PromptOutcome)> on_outcome;// Runs each time the prompt comes up, so whoever shows it can place it by its anchor.Function<void()> on_shown;+ // A notice that the system denies the browser the feature offers to show the system's setting for it.+ Function<void()> on_open_settings;private:virtual void keyPressEvent(QKeyEvent*) override;diff --git a/UI/Qt/Tab.cpp b/UI/Qt/Tab.cppindex 47f1cfa08be..bf360cdb980 100644--- a/UI/Qt/Tab.cpp+++ b/UI/Qt/Tab.cpp@@ -14,6 +14,7 @@#include <LibWakeLock/DisplaySleepInhibitor.h>#include <LibWebCommon/HTML/SelectedFile.h>#include <LibWebView/Application.h>+#include <LibWebView/MicrophoneAuthorizer.h>#include <LibWebView/URL.h>#include <LibWebView/Utilities.h>#include <LibWebView/WebContentClient.h>@@ -555,7 +556,13 @@ void Tab::initialize(Optional<WebView::CanonicalTraversable&> traversable)};popover->adjustSize();position();- popover->on_shown = AK::move(position);+ popover->on_shown = [this, position = AK::move(position), request] {+ position();+ view().did_show_permission_prompt(request);+ };+ popover->on_open_settings = [] {+ Application::the().microphone_authorizer().open_system_settings();+ };return popover;};