Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.1

0.6.1 / src / web / html / navigator.lucb

#==============================================================================================
#
#   navigator - HTML::Navigator and its mixins: the user agent's identity, languages,
#   hardware, plugins and the objects it creates on demand
#
#   DESCRIPTION:
#       Port of Libraries/LibWeb/HTML/Navigator.cpp (lines 1-200), NavigatorBeacon.cpp (lines
#       1-96), NavigatorConcurrentHardware.cpp, NavigatorDeviceMemory.cpp, NavigatorID.cpp
#       (lines 1-123) with the inline functions of Navigator.h, NavigatorID.h,
#       NavigatorLanguage.h and NavigatorOnLine.h. The user agent string, platform and
#       languages come from the ResourceLoader (phase 2); sendBeacon fetches (phase 2).
#
#       Copyright (c) 2022, Andrew Kaster <akaster@serenityos.org>
#       Copyright (c) 2024, Jamie Mansfield <jmansfield@cadixdev.org>
#       Copyright (c) 2024, Tim Flynn <trflynn89@ladybird.org>
#       SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================

# mark: Navigator ===============================================================================

## Ported from Navigator.cpp:31 Web::HTML::Navigator::create.
pub func html_navigator_create(realm: Realm*) -> HtmlNavigator*:
    return realm_create_html_navigator(realm, realm)

## Ported from Navigator.cpp:36 Web::HTML::Navigator::Navigator.
pub func html_navigator_construct(this: HtmlNavigator*, realm: Realm*):
    bind_platform_object_construct_realm(this.bind_platform_object(), realm)
    # The vptrs of the mixin bases move to Navigator's tables.
    let class_id = this.cell().class_id
    this.navigator_beacon_partial.vtable = &html_navigator_navigator_beacon_partial_vtable
    this.navigator_beacon_partial.class_id = class_id
    this.navigator_gamepad_partial.vtable = &html_navigator_navigator_gamepad_partial_vtable
    this.navigator_gamepad_partial.class_id = class_id
    this.global_privacy_control_mixin.vtable = &html_navigator_global_privacy_control_mixin_vtable
    this.global_privacy_control_mixin.class_id = class_id
    this.navigator_encrypted_media_extensions_partial.vtable = &html_navigator_navigator_encrypted_media_extensions_partial_vtable
    this.navigator_encrypted_media_extensions_partial.class_id = class_id
    this.navigator_storage.vtable = &html_navigator_navigator_storage_vtable
    this.navigator_storage.class_id = class_id

## Ported from Navigator.cpp:43 Web::HTML::Navigator::initialize (override).
pub func html_navigator_initialize_impl(base: JsCell*, realm: Realm*):
    let this = (HtmlNavigator*)base
    web_set_prototype_for_interface(base, realm, BindInterfaceName.navigator)
    # Base::initialize(realm): PlatformObject inherits JS::Cell's.
    js_cell_initialize_impl(base, realm)
    gamepad_navigator_gamepad_partial_check_for_connected_gamepads(&this.navigator_gamepad_partial)

## Ported from Navigator.cpp:51 Web::HTML::Navigator::pdf_viewer_enabled.
# https://html.spec.whatwg.org/multipage/system-state.html#dom-navigator-pdfviewerenabled
pub func html_navigator_pdf_viewer_enabled(this: HtmlNavigator*) -> bool:
    # The NavigatorPlugins mixin's pdfViewerEnabled getter steps are to return the user agent's PDF viewer supported.
    # NOTE: The NavigatorPlugins mixin should only be exposed on the Window object.
    let window = as_html_window((gc.Cell*)html_current_global_object())
    return page_pdf_viewer_supported(html_window_page(window))

## Ported from Navigator.cpp:60 Web::HTML::Navigator::webdriver.
# https://w3c.github.io/webdriver/#dfn-webdriver
pub func html_navigator_webdriver(this: HtmlNavigator*) -> bool:
    # Returns true if webdriver-active flag is set, false otherwise.

    # NOTE: The NavigatorAutomationInformation interface should not be exposed on WorkerNavigator.
    let window = as_html_window((gc.Cell*)html_current_global_object())
    return page_is_webdriver_active(html_window_page(window))

## Ported from Navigator.cpp:69 Web::HTML::Navigator::visit_edges (override).
pub func html_navigator_visit_edges_impl(base: gc.Cell*, visitor: gc.CellVisitor*):
    let this = (HtmlNavigator*)base
    gc.cell_visit_edges_impl(base, visitor)
    gamepad_navigator_gamepad_partial_visit_edges(&this.navigator_gamepad_partial, visitor)
    gc.cell_visitor_visit_cell(visitor, (gc.Cell*?)this.m_mime_type_array)  # opaque in phase 1
    gc.cell_visitor_visit_cell(visitor, (gc.Cell*?)this.m_plugin_array)  # opaque in phase 1
    gc.cell_visitor_visit_cell(visitor, (gc.Cell*?)this.m_clipboard)  # opaque in phase 1
    gc.cell_visitor_visit_cell(visitor, (gc.Cell*?)this.m_geolocation)  # opaque in phase 1
    gc.cell_visitor_visit_cell(visitor, (gc.Cell*?)this.m_serial)  # opaque in phase 1
    gc.cell_visitor_visit_cell(visitor, (gc.Cell*?)this.m_user_activation)  # opaque in phase 1
    gc.cell_visitor_visit_cell(visitor, (gc.Cell*?)this.m_service_worker_container)  # opaque in phase 1
    gc.cell_visitor_visit_cell(visitor, (gc.Cell*?)this.m_media_capabilities)  # opaque in phase 1
    gc.cell_visitor_visit_cell(visitor, (gc.Cell*?)this.m_media_devices)  # opaque in phase 1
    gc.cell_visitor_visit_cell(visitor, (gc.Cell*?)this.m_credentials)  # opaque in phase 1
    gc.cell_visitor_visit_t(visitor, this.m_battery_promise)
    gc.cell_visitor_visit_cell(visitor, (gc.Cell*?)this.m_xr)  # opaque in phase 1

## Ported from Navigator.cpp:87 Web::HTML::Navigator::mime_types.
pub func html_navigator_mime_types(this: HtmlNavigator*) -> HtmlMimeTypeArray*:
    if this.m_mime_type_array == none:
        let realm = bind_platform_object_realm(this.bind_platform_object())
        this.m_mime_type_array = realm_create_html_mime_type_array(realm, realm)
    return this.m_mime_type_array else trap("unreachable")

## Ported from Navigator.cpp:94 Web::HTML::Navigator::plugins.
pub func html_navigator_plugins(this: HtmlNavigator*) -> HtmlPluginArray*:
    if this.m_plugin_array == none:
        let realm = bind_platform_object_realm(this.bind_platform_object())
        this.m_plugin_array = realm_create_html_plugin_array(realm, realm)
    return this.m_plugin_array else trap("unreachable")

## Ported from Navigator.cpp:101 Web::HTML::Navigator::clipboard.
pub func html_navigator_clipboard(this: HtmlNavigator*) -> ClipboardClipboard*:
    if this.m_clipboard == none:
        let realm = bind_platform_object_realm(this.bind_platform_object())
        this.m_clipboard = realm_create_clipboard_clipboard(realm, realm)
    return this.m_clipboard else trap("unreachable")

## Ported from Navigator.cpp:108 Web::HTML::Navigator::geolocation.
pub func html_navigator_geolocation(this: HtmlNavigator*) -> GeolocationGeolocation*:
    if this.m_geolocation == none:
        let realm = bind_platform_object_realm(this.bind_platform_object())
        this.m_geolocation = realm_create_geolocation_geolocation(realm, realm)
    return this.m_geolocation else trap("unreachable")

## Ported from Navigator.cpp:115 Web::HTML::Navigator::serial.
pub func html_navigator_serial(this: HtmlNavigator*) -> SerialSerial*:
    if this.m_serial == none:
        let realm = bind_platform_object_realm(this.bind_platform_object())
        this.m_serial = realm_create_serial_serial(realm, realm)
    return this.m_serial else trap("unreachable")

## Ported from Navigator.cpp:122 Web::HTML::Navigator::user_activation.
pub func html_navigator_user_activation(this: HtmlNavigator*) -> HtmlUserActivation*:
    if this.m_user_activation == none:
        let realm = bind_platform_object_realm(this.bind_platform_object())
        this.m_user_activation = realm_create_html_user_activation(realm, realm)
    return this.m_user_activation else trap("unreachable")

## Ported from Navigator.cpp:129 Web::HTML::Navigator::credentials.
pub func html_navigator_credentials(this: HtmlNavigator*) -> CredentialManagementCredentialsContainer*:
    if this.m_credentials == none:
        let realm = bind_platform_object_realm(this.bind_platform_object())
        this.m_credentials = realm_create_credential_management_credentials_container(realm, realm)
    return this.m_credentials else trap("unreachable")

## Ported from Navigator.cpp:136 Web::HTML::Navigator::xr.
pub func html_navigator_xr(this: HtmlNavigator*) -> WebXrXrSystem*:
    if this.m_xr == none:
        let realm = bind_platform_object_realm(this.bind_platform_object())
        this.m_xr = realm_create_web_xr_xr_system(realm, realm)
        if html_window_is_internals_object_exposed():
            # m_xr->define_direct_property("test", realm.create<Internals::XRTest>(realm), ...): a JS
            # property for the test runner's scripts (phase 3).
            _ = 0
    return this.m_xr else trap("unreachable")

## Ported from Navigator.cpp:148 Web::HTML::Navigator::max_touch_points.
# https://w3c.github.io/pointerevents/#dom-navigator-maxtouchpoints
pub func html_navigator_max_touch_points() -> i32:
    # FIXME: Implement this for touch-capable devices.
    return 0

## Ported from Navigator.cpp:154 Web::HTML::Navigator::service_worker.
pub func html_navigator_service_worker(this: HtmlNavigator*) -> ServiceWorkerServiceWorkerContainer*:
    if this.m_service_worker_container == none:
        let realm = bind_platform_object_realm(this.bind_platform_object())
        this.m_service_worker_container = realm_create_service_worker_service_worker_container(realm, realm)
    return this.m_service_worker_container else trap("unreachable")

## Ported from Navigator.cpp:161 Web::HTML::Navigator::media_capabilities.
pub func html_navigator_media_capabilities(this: HtmlNavigator*) -> MediaCapabilitiesApiMediaCapabilities*:
    if this.m_media_capabilities == none:
        let realm = bind_platform_object_realm(this.bind_platform_object())
        this.m_media_capabilities = realm_create_media_capabilities_api_media_capabilities(realm, realm)
    return this.m_media_capabilities else trap("unreachable")

## Ported from Navigator.cpp:168 Web::HTML::Navigator::media_devices.
pub func html_navigator_media_devices(this: HtmlNavigator*) -> MediaCaptureMediaDevices*:
    if this.m_media_devices == none:
        let realm = bind_platform_object_realm(this.bind_platform_object())
        this.m_media_devices = realm_create_media_capture_media_devices(realm, realm)
    return this.m_media_devices else trap("unreachable")

## Ported from Navigator.cpp:176 Web::HTML::Navigator::get_battery.
# https://w3c.github.io/battery/#the-getbattery-method
pub func html_navigator_get_battery(this: HtmlNavigator*) -> JsPromiseCapability*:
    let realm = bind_platform_object_realm(this.bind_platform_object())

    # 1. If this.[[BatteryPromise]] is null, then set it to a new promise in this's relevant realm.
    if this.m_battery_promise == none:
        this.m_battery_promise = idl_create_promise(realm)
    let battery_promise = this.m_battery_promise else trap("unreachable")

    # 2. If this's relevant global object's associated Document is not allowed to use the "battery" policy-controlled
    #    feature, then reject this.[[BatteryPromise]] with a "NotAllowedError" DOMException.
    # (`if (true)`: the Battery Status API is not implemented.)
    idl_reject_promise(realm, battery_promise, js_value_from_object((JsObject*)idl_not_allowed_error_create(realm, ak.utf16_string_from_str("Battery Status API is not yet implemented"))))
    # 3. Otherwise:
    # FIXME: 1. If this.[[BatteryManager]] is null, then set it to the result of creating a new BatteryManager in this's
    #           relevant realm.
    # FIXME: 2. Resolve this.[[BatteryPromise]] with this.[[BatteryManager]].

    # 4. Return this.[[BatteryPromise]].
    return battery_promise

## Ported from Navigator.h:52 Web::HTML::Navigator::cookie_enabled.
# https://html.spec.whatwg.org/multipage/system-state.html#dom-navigator-cookieenabled
pub func html_navigator_cookie_enabled(this: HtmlNavigator*) -> bool:
    # FIXME: Hook up to Agent level state
    return true

## Ported from Navigator.h:56 Web::HTML::Navigator::java_enabled.
# https://html.spec.whatwg.org/multipage/system-state.html#dom-navigator-javaenabled
pub func html_navigator_java_enabled(this: HtmlNavigator*) -> bool:
    return false

## Ported from Navigator.h:90 Web::HTML::Navigator::this_navigator_storage_object (override).
pub func html_navigator_this_navigator_storage_object_impl(base: StorageApiNavigatorStorage*) -> BindPlatformObject*:
    return (BindPlatformObject*)((u8*)base - memory.offset_of(HtmlNavigator, navigator_storage))

# mark: NavigatorBeaconPartial ==================================================================

## Ported from NavigatorBeacon.cpp:21 Web::HTML::NavigatorBeaconPartial::send_beacon.
# https://w3c.github.io/beacon/#sendbeacon-method
pub func html_navigator_beacon_partial_send_beacon(this: HtmlNavigatorBeaconPartial*, url: ak.String, data: FetchNullableBodyInit) -> bool!:
    # Steps 1-7 parse the URL against the relevant settings object's API base URL, extract the
    # body with the keepalive flag and fetch a keepalive POST request: fetching is phase 2.
    trap("unported (P2): Web::HTML::NavigatorBeaconPartial::send_beacon (Fetch)")

# mark: NavigatorConcurrentHardwareMixin and NavigatorDeviceMemoryMixin =========================

## Ported from NavigatorConcurrentHardware.cpp:14 Web::HTML::NavigatorConcurrentHardwareMixin::hardware_concurrency.
# https://html.spec.whatwg.org/multipage/workers.html#dom-navigator-hardwareconcurrency
pub func html_navigator_concurrent_hardware_mixin_hardware_concurrency() -> u64:
    return core_system_hardware_concurrency()

## AK::count_required_bits (AK/BuiltinWrappers.h): the number of bits needed to write value
## (1 for 0).
func html_count_required_bits(value: u64) -> u64:
    if value == 0:
        return 1
    var bits: u64 = 0
    var rest = value
    while rest != 0:
        bits += 1
        rest >>= 1
    return bits

## Ported from NavigatorDeviceMemory.cpp:14 Web::HTML::NavigatorDeviceMemoryMixin::device_memory.
# https://www.w3.org/TR/device-memory/#computing-device-memory-value
pub func html_navigator_device_memory_mixin_device_memory(this: const HtmlNavigatorDeviceMemoryMixin*) -> f64:
    # The value is calculated by using the actual device memory in MiB then rounding it to the nearest number where
    # only the most significant bit can be set and the rest are zeros (nearest power of two).
    let memory_in_bytes = core_system_physical_memory_bytes()
    let memory_in_mib = memory_in_bytes // (1024 * 1024)
    let required_bits = html_count_required_bits(memory_in_mib)
    let lower_memory_in_mib = (u64)1 << (u64)(required_bits - 1)
    let upper_memory_in_mib = (u64)1 << (u64)required_bits
    var rounded_memory_in_mib = lower_memory_in_mib
    if upper_memory_in_mib - memory_in_mib <= memory_in_mib - lower_memory_in_mib:
        rounded_memory_in_mib = upper_memory_in_mib

    # Then dividing that number by 1024.0 to get the value in GiB.
    let memory_in_gib = (f64)rounded_memory_in_mib / 1024.0

    # An upper bound and a lower bound should be set on the list of values.
    return ak.clamp_f64(memory_in_gib, 1.0, 4.0)

# mark: NavigatorIDMixin ========================================================================

## Ported from NavigatorID.h:20 Web::HTML::NavigatorIDMixin::app_code_name.
# https://html.spec.whatwg.org/multipage/system-state.html#dom-navigator-appcodename
pub func html_navigator_id_mixin_app_code_name(this: const HtmlNavigatorIdMixin*) -> ak.String:
    return ak.string_from_str("Mozilla")

## Ported from NavigatorID.h:23 Web::HTML::NavigatorIDMixin::app_name.
# https://html.spec.whatwg.org/multipage/system-state.html#dom-navigator-appcodename
pub func html_navigator_id_mixin_app_name(this: const HtmlNavigatorIdMixin*) -> ak.String:
    return ak.string_from_str("Netscape")

## Ported from NavigatorID.cpp:16 Web::HTML::NavigatorIDMixin::app_version.
# https://html.spec.whatwg.org/multipage/system-state.html#dom-navigator-appversion
pub func html_navigator_id_mixin_app_version(this: const HtmlNavigatorIdMixin*) -> ak.String:
    # 1. Let userAgent be this's relevant settings object's environment default `User-Agent` value.
    # FIXME: Store that on the settings object?
    let user_agent = resource_loader_user_agent()

    # 2. If userAgent does not start with `Mozilla/5.0 (`, then return the empty string.
    if not ak.string_starts_with_bytes(&user_agent, ak.sv("Mozilla/5.0 (")):
        return ak.String()

    # 3. Let trail be the substring of userAgent, isomorphic decoded, that follows the "Mozilla/" prefix.
    let prefix = ak.sv("Mozilla/")
    let trail = ak.string_substring_from_byte_offset(&user_agent, ak.string_view_length(&prefix)) else trap("MUST: substring_from_byte_offset")

    # 4. -> If the navigator compatibility mode is Chrome or WebKit
    let navigator_compatibility_mode = resource_loader_navigator_compatibility_mode()
    if navigator_compatibility_mode == NavigatorCompatibilityMode.chrome or navigator_compatibility_mode == NavigatorCompatibilityMode.web_kit:
        # Return trail.
        return trail
    #    -> If the navigator compatibility mode is Gecko
    if navigator_compatibility_mode == NavigatorCompatibilityMode.gecko:
        # If trail starts with "5.0 (Windows", then return "5.0 (Windows)".
        if ak.string_starts_with_bytes(&trail, ak.sv("5.0 (Windows")):
            return ak.string_from_str("5.0 (Windows)")

        # Otherwise, return the prefix of trail up to but not including the first U+003B (;), concatenated with the
        # character U+0029 RIGHT PARENTHESIS. For example, "5.0 (Macintosh)", "5.0 (Android 10)", or "5.0 (X11)".
        if let index = ak.string_find_byte_offset_u32(&trail, (u32)';'):
            var output = ak.string_builder_new()
            let prefix_of_trail = ak.string_substring_from_byte_offset_usize(&trail, 0, index) else trap("MUST: substring_from_byte_offset")
            ak.string_builder_append_string_view(&output, ak.string_bytes_as_string_view(&prefix_of_trail))
            ak.string_builder_append(&output, ")")
            return ak.string_from_string_builder(&output) else trap("MUST: StringBuilder::to_string")
        return trail

    trap("VERIFY_NOT_REACHED")

## Ported from NavigatorID.cpp:56 Web::HTML::NavigatorIDMixin::platform.
# https://html.spec.whatwg.org/multipage/system-state.html#dom-navigator-platform
pub func html_navigator_id_mixin_platform(this: const HtmlNavigatorIdMixin*) -> ak.String:
    # Must return a string representing the platform on which the browser is executing (e.g. "MacIntel", "Win32",
    # "Linux x86_64", "Linux armv81") or, for privacy and compatibility, a string that is commonly returned on another
    # platform.

    # FIXME: Use some portion of the user agent string to make spoofing work 100%
    return resource_loader_platform()

## Ported from NavigatorID.h:32 Web::HTML::NavigatorIDMixin::product.
# https://html.spec.whatwg.org/multipage/system-state.html#dom-navigator-product
pub func html_navigator_id_mixin_product(this: const HtmlNavigatorIdMixin*) -> ak.String:
    return ak.string_from_str("Gecko")

## Ported from NavigatorID.cpp:67 Web::HTML::NavigatorIDMixin::product_sub.
# https://html.spec.whatwg.org/multipage/system-state.html#dom-navigator-productsub
pub func html_navigator_id_mixin_product_sub(this: const HtmlNavigatorIdMixin*) -> ak.String:
    let navigator_compatibility_mode = resource_loader_navigator_compatibility_mode()

    # Must return the appropriate string from the following list:

    # If the navigator compatibility mode is Chrome or WebKit
    if navigator_compatibility_mode == NavigatorCompatibilityMode.chrome or navigator_compatibility_mode == NavigatorCompatibilityMode.web_kit:
        # The string "20030107".
        return ak.string_from_str("20030107")

    # If the navigator compatibility mode is Gecko
    if navigator_compatibility_mode == NavigatorCompatibilityMode.gecko:
        # The string "20100101".
        return ak.string_from_str("20100101")

    trap("VERIFY_NOT_REACHED")

## Ported from NavigatorID.cpp:89 Web::HTML::NavigatorIDMixin::user_agent.
# https://html.spec.whatwg.org/multipage/system-state.html#dom-navigator-useragent
pub func html_navigator_id_mixin_user_agent(this: const HtmlNavigatorIdMixin*) -> ak.String:
    # Must return the default `User-Agent` value.
    return resource_loader_user_agent()

## Ported from NavigatorID.cpp:96 Web::HTML::NavigatorIDMixin::vendor.
# https://html.spec.whatwg.org/multipage/system-state.html#dom-navigator-vendor
pub func html_navigator_id_mixin_vendor(this: const HtmlNavigatorIdMixin*) -> ak.String:
    let navigator_compatibility_mode = resource_loader_navigator_compatibility_mode()

    # Must return the appropriate string from the following list:

    # If the navigator compatibility mode is Chrome
    if navigator_compatibility_mode == NavigatorCompatibilityMode.chrome:
        # The string "Google Inc.".
        return ak.string_from_str("Google Inc.")

    # If the navigator compatibility mode is Gecko
    if navigator_compatibility_mode == NavigatorCompatibilityMode.gecko:
        # The empty string.
        return ak.string_from_str("")

    # If the navigator compatibility mode is WebKit
    if navigator_compatibility_mode == NavigatorCompatibilityMode.web_kit:
        # The string "Apple Computer, Inc.".
        return ak.string_from_str("Apple Computer, Inc.")

    trap("VERIFY_NOT_REACHED")

## Ported from NavigatorID.h:44 Web::HTML::NavigatorIDMixin::vendor_sub.
# https://html.spec.whatwg.org/multipage/system-state.html#dom-navigator-vendorsub
pub func html_navigator_id_mixin_vendor_sub(this: const HtmlNavigatorIdMixin*) -> ak.String:
    return ak.String()

# mark: NavigatorLanguageMixin and NavigatorOnLineMixin =========================================

## Ported from NavigatorLanguage.h:20 Web::HTML::NavigatorLanguageMixin::language.
# https://html.spec.whatwg.org/multipage/system-state.html#dom-navigator-language
pub func html_navigator_language_mixin_language(this: const HtmlNavigatorLanguageMixin*) -> ak.String:
    # FIXME: Honor WebDriver BiDi emulated language.
    return *ak.vector_at_const(resource_loader_preferred_languages(), 0)

## Ported from NavigatorLanguage.h:24 Web::HTML::NavigatorLanguageMixin::languages.
# https://html.spec.whatwg.org/multipage/system-state.html#dom-navigator-languages
pub func html_navigator_language_mixin_languages(this: const HtmlNavigatorLanguageMixin*) -> const ak.String[]:
    # FIXME: Honor WebDriver BiDi emulated language.
    return ak.vector_span_const(resource_loader_preferred_languages())

## Ported from NavigatorOnLine.h:15 Web::HTML::NavigatorOnLineMixin::on_line.
# https://html.spec.whatwg.org/multipage/system-state.html#dom-navigator-online
pub func html_navigator_on_line_mixin_on_line(this: const HtmlNavigatorOnLineMixin*) -> bool:
    return true