Skip to content

Truly independent web browser

LibWebView: Add a macOS notification backend

sideshowbarker364eb3d00d3c
diff --git a/Libraries/LibWebView/CMakeLists.txt b/Libraries/LibWebView/CMakeLists.txt
index d32e136b7e4..659f8095abf 100644
--- a/Libraries/LibWebView/CMakeLists.txt
+++ b/Libraries/LibWebView/CMakeLists.txt
@@ -99,9 +99,11 @@ if (APPLE)
list(APPEND SOURCES
CrashReportPOSIX.cpp
LaunchURLsMacOS.cpp
+ NotificationBackendMacOS.mm
PlatformColorsMacOS.cpp
ProcessReaper.cpp
)
+ set_source_files_properties(NotificationBackendMacOS.mm PROPERTIES COMPILE_FLAGS "-fobjc-arc")
elseif (LINUX)
list(APPEND SOURCES AudioDaemonSocket.cpp CrashReportPOSIX.cpp)
endif()
@@ -165,7 +167,7 @@ if (LINUX)
endif()
if (APPLE)
- target_link_libraries(LibWebView PRIVATE "-framework Carbon")
+ target_link_libraries(LibWebView PRIVATE "-framework Carbon" "-framework UserNotifications")
endif()
# Third-party
diff --git a/Libraries/LibWebView/NotificationBackendMacOS.h b/Libraries/LibWebView/NotificationBackendMacOS.h
new file mode 100644
index 00000000000..f0b7da6a0b0
--- /dev/null
+++ b/Libraries/LibWebView/NotificationBackendMacOS.h
@@ -0,0 +1,62 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/HashMap.h>
+#include <AK/NonnullOwnPtr.h>
+#include <AK/String.h>
+#include <AK/kmalloc.h>
+#include <LibWebView/NotificationBackend.h>
+
+namespace WebView {
+
+namespace Detail {
+
+struct NotificationCenterBridge {
+ AK_ALLOC_WITH_KMALLOC;
+ void* delegate { nullptr };
+ void* center { nullptr };
+};
+
+}
+
+// Shows notifications through the user notification center. Needs a bundled application: Outside one there is no
+// notification center to ask, and every show fails.
+class WEBVIEW_API NotificationBackendMacOS final : public NotificationBackend {
+public:
+ NotificationBackendMacOS();
+ virtual ~NotificationBackendMacOS() override;
+
+ virtual void show(PlatformNotification const&) override;
+ virtual void close(u64 id) override;
+
+ // What the notification center's delegate reports: the user activated or dismissed a request.
+ void did_activate(String const& identifier);
+ void did_dismiss(String const& identifier);
+
+private:
+ void request_authorization_then(Function<void(bool granted)>);
+
+ // The notification center knows requests by a string identifier. A replacement keeps the identifier of the
+ // notification it replaces, so the center swaps it in place; these maps keep track of which id holds it now.
+ HashMap<String, u64> m_id_for_identifier;
+ HashMap<u64, String> m_identifier_for_id;
+
+ enum class Authorization {
+ Unknown,
+ Pending,
+ Granted,
+ Denied,
+ };
+ Authorization m_authorization { Authorization::Unknown };
+ Vector<Function<void(bool)>> m_waiting_for_authorization;
+
+ OwnPtr<Detail::NotificationCenterBridge> m_bridge;
+ bool m_bundled { false };
+};
+
+}
diff --git a/Libraries/LibWebView/NotificationBackendMacOS.mm b/Libraries/LibWebView/NotificationBackendMacOS.mm
new file mode 100644
index 00000000000..9b7255604da
--- /dev/null
+++ b/Libraries/LibWebView/NotificationBackendMacOS.mm
@@ -0,0 +1,265 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/ByteString.h>
+#include <AK/Format.h>
+#include <LibCore/EventLoop.h>
+#include <LibGfx/ImageFormats/PNGWriter.h>
+#include <LibWebView/NotificationBackendMacOS.h>
+
+#import <Foundation/Foundation.h>
+#import <UserNotifications/UserNotifications.h>
+
+@interface LadybirdNotificationCenterDelegate : NSObject <UNUserNotificationCenterDelegate>
+- (instancetype)initWithBackend:(WebView::NotificationBackendMacOS*)backend;
+- (void)detach;
+@end
+
+namespace WebView {
+
+// The bridge holds the center and the delegate as plain pointers, so the header stays C++; these read them back.
+static UNUserNotificationCenter* center_of(Detail::NotificationCenterBridge& bridge)
+{
+ return (__bridge UNUserNotificationCenter*)bridge.center;
+}
+
+static LadybirdNotificationCenterDelegate* delegate_of(Detail::NotificationCenterBridge& bridge)
+{
+ return (__bridge LadybirdNotificationCenterDelegate*)bridge.delegate;
+}
+
+// Every callback from the center arrives on a queue of its own; the browser's state is touched on the main thread only.
+static void on_main_thread(Function<void()> function)
+{
+ __block auto held = move(function);
+ dispatch_async(dispatch_get_main_queue(), ^{
+ held();
+ });
+}
+
+static NSString* ns_string(String const& string)
+{
+ return [NSString stringWithUTF8String:string.to_byte_string().characters()];
+}
+
+static NSString* ns_string(Utf16String const& string)
+{
+ return ns_string(string.to_utf8());
+}
+
+NotificationBackendMacOS::NotificationBackendMacOS()
+ : m_bridge(make<Detail::NotificationCenterBridge>())
+{
+ m_bundled = [[NSBundle mainBundle] bundleIdentifier] != nil;
+ if (!m_bundled) {
+ dbgln("Notifications: Not running from an application bundle, so there is no notification center to show them in");
+ return;
+ }
+ m_bridge->center = (__bridge_retained void*)[UNUserNotificationCenter currentNotificationCenter];
+ m_bridge->delegate = (__bridge_retained void*)[[LadybirdNotificationCenterDelegate alloc] initWithBackend:this];
+ center_of(*m_bridge).delegate = delegate_of(*m_bridge);
+}
+
+NotificationBackendMacOS::~NotificationBackendMacOS()
+{
+ if (m_bridge->delegate) {
+ auto* delegate = (__bridge_transfer LadybirdNotificationCenterDelegate*)m_bridge->delegate;
+ auto* center = (__bridge_transfer UNUserNotificationCenter*)m_bridge->center;
+ [delegate detach];
+ if (center.delegate == delegate)
+ center.delegate = nil;
+ }
+}
+
+void NotificationBackendMacOS::request_authorization_then(Function<void(bool)> then)
+{
+ switch (m_authorization) {
+ case Authorization::Granted:
+ then(true);
+ return;
+ case Authorization::Denied:
+ then(false);
+ return;
+ case Authorization::Pending:
+ m_waiting_for_authorization.append(move(then));
+ return;
+ case Authorization::Unknown:
+ break;
+ }
+
+ m_authorization = Authorization::Pending;
+ m_waiting_for_authorization.append(move(then));
+ [center_of(*m_bridge) requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionSound)
+ completionHandler:^(BOOL granted, NSError* error) {
+ if (!granted)
+ dbgln("Notifications: The notification center denied authorization{}{}", error ? ": "sv : ""sv, error ? [[error localizedDescription] UTF8String] : "");
+ on_main_thread([this, granted = static_cast<bool>(granted)] {
+ m_authorization = granted ? Authorization::Granted : Authorization::Denied;
+ for (auto& waiting : exchange(m_waiting_for_authorization, {}))
+ waiting(granted);
+ });
+ }];
+}
+
+void NotificationBackendMacOS::show(PlatformNotification const& notification)
+{
+ if (!m_bundled) {
+ if (on_failed)
+ on_failed(notification.id);
+ return;
+ }
+
+ request_authorization_then([this, notification](bool granted) {
+ if (!granted) {
+ if (on_failed)
+ on_failed(notification.id);
+ return;
+ }
+
+ auto* content = [[UNMutableNotificationContent alloc] init];
+ content.title = ns_string(notification.data.title);
+ content.subtitle = ns_string(notification.attribution);
+ content.body = ns_string(notification.data.body);
+ content.threadIdentifier = ns_string(notification.attribution);
+ if (notification.data.silent != true)
+ content.sound = [UNNotificationSound defaultSound];
+
+ // A replacement without renotify shouldn't alert again.
+ bool replaces = notification.replaces.has_value();
+ if (replaces && !notification.data.renotify)
+ content.interruptionLevel = UNNotificationInterruptionLevelPassive;
+
+ // The center takes an attachment from a file, which it copies.
+ NSURL* icon_file = nil;
+ if (notification.icon) {
+ if (auto png = Gfx::PNGWriter::encode(*notification.icon); !png.is_error()) {
+ auto path = ByteString::formatted("{}ladybird-notification-icon-{}.png", [NSTemporaryDirectory() UTF8String], notification.id);
+ icon_file = [NSURL fileURLWithPath:[NSString stringWithUTF8String:path.characters()]];
+ NSData* data = [NSData dataWithBytes:png.value().data() length:png.value().size()];
+ if ([data writeToURL:icon_file atomically:YES]) {
+ NSError* error = nil;
+ if (auto* attachment = [UNNotificationAttachment attachmentWithIdentifier:@"icon" URL:icon_file options:nil error:&error])
+ content.attachments = @[ attachment ];
+ } else {
+ icon_file = nil;
+ }
+ }
+ }
+
+ // Reusing the replaced notification's identifier makes the center swap it in place.
+ String identifier;
+ if (replaces) {
+ if (auto existing = m_identifier_for_id.take(*notification.replaces); existing.has_value())
+ identifier = existing.release_value();
+ }
+ if (identifier.is_empty())
+ identifier = String::number(notification.id);
+ m_identifier_for_id.set(notification.id, identifier);
+ m_id_for_identifier.set(identifier, notification.id);
+
+ auto* request = [UNNotificationRequest requestWithIdentifier:ns_string(identifier) content:content trigger:nil];
+ [center_of(*m_bridge) addNotificationRequest:request
+ withCompletionHandler:^(NSError* error) {
+ if (icon_file)
+ [[NSFileManager defaultManager] removeItemAtURL:icon_file error:nil];
+ bool failed = error != nil;
+ if (failed)
+ dbgln("Notifications: The notification center refused the request: {}", [[error localizedDescription] UTF8String]);
+ on_main_thread([this, id = notification.id, failed] {
+ if (failed) {
+ if (auto identifier = m_identifier_for_id.take(id); identifier.has_value())
+ m_id_for_identifier.remove(*identifier);
+ if (on_failed)
+ on_failed(id);
+ return;
+ }
+ if (on_shown)
+ on_shown(id);
+ });
+ }];
+ });
+}
+
+void NotificationBackendMacOS::close(u64 id)
+{
+ auto identifier = m_identifier_for_id.take(id);
+ if (!identifier.has_value())
+ return;
+ m_id_for_identifier.remove(*identifier);
+ NSArray* identifiers = @[ ns_string(*identifier) ];
+ [center_of(*m_bridge) removeDeliveredNotificationsWithIdentifiers:identifiers];
+ [center_of(*m_bridge) removePendingNotificationRequestsWithIdentifiers:identifiers];
+ if (on_closed)
+ on_closed(id, ByUser::No);
+}
+
+void NotificationBackendMacOS::did_activate(String const& identifier)
+{
+ auto id = m_id_for_identifier.take(identifier);
+ if (!id.has_value())
+ return;
+ m_identifier_for_id.remove(*id);
+ if (on_clicked)
+ on_clicked(*id);
+ if (on_closed)
+ on_closed(*id, ByUser::Yes);
+}
+
+void NotificationBackendMacOS::did_dismiss(String const& identifier)
+{
+ auto id = m_id_for_identifier.take(identifier);
+ if (!id.has_value())
+ return;
+ m_identifier_for_id.remove(*id);
+ if (on_closed)
+ on_closed(*id, ByUser::Yes);
+}
+
+}
+
+@implementation LadybirdNotificationCenterDelegate
+{
+ WebView::NotificationBackendMacOS* m_backend;
+}
+
+- (instancetype)initWithBackend:(WebView::NotificationBackendMacOS*)backend
+{
+ if ((self = [super init]))
+ m_backend = backend;
+ return self;
+}
+
+- (void)detach
+{
+ m_backend = nullptr;
+}
+
+// Notifications show as banners even while the browser is the frontmost application.
+- (void)userNotificationCenter:(UNUserNotificationCenter*)center
+ willPresentNotification:(UNNotification*)notification
+ withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
+{
+ completionHandler(UNNotificationPresentationOptionBanner | UNNotificationPresentationOptionSound);
+}
+
+- (void)userNotificationCenter:(UNUserNotificationCenter*)center
+ didReceiveNotificationResponse:(UNNotificationResponse*)response
+ withCompletionHandler:(void (^)(void))completionHandler
+{
+ auto identifier = MUST(String::from_utf8(StringView { [response.notification.request.identifier UTF8String], strlen([response.notification.request.identifier UTF8String]) }));
+ bool dismissed = [response.actionIdentifier isEqualToString:UNNotificationDismissActionIdentifier];
+ WebView::on_main_thread([self, identifier, dismissed] {
+ if (!m_backend)
+ return;
+ if (dismissed)
+ m_backend->did_dismiss(identifier);
+ else
+ m_backend->did_activate(identifier);
+ });
+ completionHandler();
+}
+
+@end
diff --git a/UI/Qt/Application.cpp b/UI/Qt/Application.cpp
index 96fb483e3d0..67ec5da004a 100644
--- a/UI/Qt/Application.cpp
+++ b/UI/Qt/Application.cpp
@@ -9,6 +9,9 @@
#include <LibURL/URL.h>
#include <LibWebView/CanonicalTraversable.h>
#include <LibWebView/NotificationBackend.h>
+#if defined(AK_OS_MACOS)
+# include <LibWebView/NotificationBackendMacOS.h>
+#endif
#include <LibWebView/SessionStore.h>
#include <LibWebView/URL.h>
#include <LibWebView/Utilities.h>
@@ -1302,8 +1305,12 @@ static BrowserWindow* window_for_view(WebView::ViewImplementation const& view)
NonnullOwnPtr<WebView::NotificationBackend> Application::create_notification_backend()
{
- // The platform backends follow; until then, pages see every show fail.
+#if defined(AK_OS_MACOS)
+ return make<WebView::NotificationBackendMacOS>();
+#else
+ // The Freedesktop backend follows; until then, pages see every show fail.
return WebView::Application::create_notification_backend();
+#endif
}
void Application::focus_page_from_notification(WebView::WebContentPage& page)