From 8ee16badc41f4e2f47ee78e2fe24c6553e7f4c9a Mon Sep 17 00:00:00 2001 From: zhangjing Date: Tue, 24 Sep 2024 17:36:12 +0800 Subject: [PATCH] =?UTF-8?q?=E8=93=9D=E9=BB=84=E4=B8=80=E8=87=B4=E6=80=A7?= =?UTF-8?q?=E4=BB=A3=E7=A0=81=E5=90=8C=E6=AD=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: zhangjing --- BUILD.gn | 85 ++-- cef_paths.gypi | 8 +- include/capi/cef_browser_capi.h | 262 ++++++----- include/capi/cef_client_capi.h | 13 +- include/capi/cef_context_menu_handler_capi.h | 8 +- include/capi/cef_cookie_capi.h | 8 +- include/capi/cef_custom_media_info_capi.h | 0 .../cef_custom_media_player_delegate_capi.h | 0 include/capi/cef_load_handler_capi.h | 14 +- include/capi/cef_media_player_listener_capi.h | 0 include/capi/cef_permission_request_capi.h | 47 +- include/capi/cef_render_handler_capi.h | 43 +- include/capi/cef_request_capi.h | 189 ++++---- include/capi/cef_request_handler_capi.h | 9 +- .../capi/cef_web_extension_api_handler_capi.h | 73 ++++ include/cef_api_hash.h | 10 +- include/cef_browser.h | 237 ++++++---- include/cef_client.h | 12 + include/cef_context_menu_handler.h | 6 +- include/cef_cookie.h | 6 +- include/cef_first_meaningful_paint_details.h | 2 +- include/cef_keyboard_handler.h | 1 + include/cef_load_handler.h | 21 +- include/cef_permission_request.h | 36 ++ include/cef_render_handler.h | 44 +- include/cef_request_handler.h | 13 +- include/cef_resource_request_handler.h | 29 +- include/cef_values.h | 1 - include/cef_web_extension_api_handler.h | 58 +++ include/internal/cef_types.h | 23 +- include/internal/cef_types_wrappers.h | 19 +- libcef/browser/alloy/alloy_browser_context.cc | 42 +- libcef/browser/alloy/alloy_browser_context.h | 9 +- .../browser/alloy/alloy_browser_host_impl.cc | 111 +++-- .../browser/alloy/alloy_browser_host_impl.h | 39 +- .../alloy/alloy_content_browser_client.cc | 123 ++++-- .../alloy/alloy_content_browser_client.h | 13 +- .../alloy_off_the_record_browser_context.cc | 5 + .../alloy/browser_platform_delegate_alloy.cc | 4 +- .../alloy/chrome_browser_process_alloy.cc | 3 +- .../chrome_off_the_record_profile_alloy.cc | 10 +- .../anti_tracking_delegate_ohos.cc | 2 +- .../third_party_cookie_access_policy.cc | 10 +- .../third_party_cookie_access_policy.h | 5 +- libcef/browser/autofill/oh_autofill_client.cc | 19 +- libcef/browser/autofill/oh_autofill_client.h | 2 +- .../browser/autofill/oh_autofill_manager.cc | 34 +- libcef/browser/autofill/oh_autofill_manager.h | 3 +- libcef/browser/browser_contents_delegate.cc | 76 +++- libcef/browser/browser_contents_delegate.h | 10 + ...browser_context_keyed_service_factories.cc | 2 + libcef/browser/browser_frame.cc | 8 +- libcef/browser/browser_frame.h | 4 +- libcef/browser/browser_host_base.cc | 409 ++++++++++++------ libcef/browser/browser_host_base.h | 74 +++- libcef/browser/browser_platform_delegate.cc | 22 +- libcef/browser/browser_platform_delegate.h | 10 +- .../chrome_content_browser_client_cef.cc | 4 +- libcef/browser/context.cc | 16 +- libcef/browser/download_manager_delegate.cc | 6 +- .../browser/extensions/api/tabs/tabs_api.cc | 31 +- libcef/browser/extensions/api/tabs/tabs_api.h | 9 + .../extensions/api/tabs/tabs_event_router.cc | 164 +++++++ .../extensions/api/tabs/tabs_event_router.h | 55 +++ .../extensions/api/tabs/tabs_windows_api.cc | 93 ++++ .../extensions/api/tabs/tabs_windows_api.h | 62 +++ .../extensions/browser_extensions_util.cc | 31 ++ .../extensions/browser_extensions_util.h | 10 + .../extensions/chrome_api_registration.cc | 9 + .../component_extension_resource_manager.cc | 2 +- .../extensions/extension_function_details.cc | 11 + .../extensions/extension_host_delegate.cc | 16 +- libcef/browser/extensions/extension_system.cc | 63 ++- libcef/browser/extensions/extension_system.h | 10 + .../extensions/extensions_browser_client.cc | 3 + .../first_meaningful_paint_details_impl.cc | 2 +- .../first_meaningful_paint_details_impl.h | 2 +- libcef/browser/frame_host_impl.cc | 111 ++++- libcef/browser/frame_host_impl.h | 7 +- ...h_gin_javascript_bridge_dispatcher_host.cc | 25 +- ...oh_gin_javascript_bridge_dispatcher_host.h | 3 +- libcef/browser/javascript_dialog_manager.cc | 34 +- .../largest_contentful_paint_details_impl.cc | 2 +- .../largest_contentful_paint_details_impl.h | 2 +- .../browser_platform_delegate_native_aura.h | 2 +- libcef/browser/net/ohos_applink_throttle.cc | 11 +- libcef/browser/net/ohos_applink_throttle.h | 2 + libcef/browser/net/throttle_handler.cc | 1 - libcef/browser/net_service/cookie_helper.cc | 60 ++- .../net_service/cookie_manager_impl.cc | 24 +- .../browser/net_service/cookie_manager_impl.h | 11 +- .../net_service/cookie_manager_ohos_impl.cc | 49 ++- .../net_service/cookie_manager_ohos_impl.h | 14 +- .../incognito_cookie_manager_ohos_impl.cc | 21 +- .../incognito_cookie_manager_ohos_impl.h | 12 +- libcef/browser/net_service/login_delegate.cc | 15 +- libcef/browser/net_service/login_delegate.h | 2 +- libcef/browser/net_service/net_helpers.cc | 80 +++- libcef/browser/net_service/net_helpers.h | 3 + .../net_service/proxy_url_loader_factory.cc | 93 +++- .../resource_request_handler_wrapper.cc | 192 ++++++-- .../net_service/restrict_cookie_manager.cc | 66 +++ .../net_service/stream_reader_url_loader.cc | 16 +- .../osr/browser_platform_delegate_osr.cc | 7 + .../osr/browser_platform_delegate_osr.h | 1 + .../osr/render_widget_host_view_osr.cc | 167 ++++--- .../browser/osr/render_widget_host_view_osr.h | 12 +- .../browser/osr/touch_handle_drawable_osr.cc | 6 +- .../touch_selection_controller_client_osr.cc | 29 +- libcef/browser/osr/web_contents_view_osr.cc | 24 +- .../oh_page_load_metrics_observer.cc | 37 +- .../oh_page_load_metrics_observer.h | 19 + .../password/oh_password_manager_client.cc | 162 +++++-- .../password/oh_password_manager_client.h | 50 ++- .../browser/permission/alloy_access_request.h | 1 + .../permission/alloy_permission_manager.cc | 55 ++- libcef/browser/prefs/browser_prefs.cc | 114 ++++- libcef/browser/prefs/browser_prefs.h | 21 + libcef/browser/prefs/renderer_prefs.cc | 78 +++- libcef/browser/printing/ohos_print_manager.cc | 36 +- libcef/browser/printing/ohos_print_manager.h | 12 +- libcef/browser/request_context_impl.cc | 10 +- libcef/browser/request_context_impl.h | 2 +- libcef/browser/res_reporter.cc | 16 +- libcef/browser/storage/web_storage_impl.cc | 2 +- libcef/common/app_manager.cc | 3 +- .../common/extensions/api/_api_features.json | 15 +- libcef/common/mojom/cef.mojom | 12 +- libcef/common/request_impl.cc | 100 ++++- libcef/common/request_impl.h | 23 +- libcef/common/response_impl.cc | 5 + libcef/common/values_impl.cc | 4 +- .../alloy/alloy_content_renderer_client.cc | 27 +- .../alloy/alloy_content_settings_client.cc | 150 +++++++ .../alloy/alloy_content_settings_client.h | 47 ++ .../alloy/alloy_render_thread_observer.cc | 14 + .../alloy/alloy_render_thread_observer.h | 14 + ...ng_error_page_controller_delegate_impl.cc} | 23 +- ...ing_error_page_controller_delegate_impl.h} | 17 +- libcef/renderer/browser_impl.cc | 43 +- libcef/renderer/browser_impl.h | 26 +- .../extensions_dispatcher_delegate.cc | 15 + .../extensions_dispatcher_delegate.h | 9 + libcef/renderer/frame_impl.cc | 29 +- libcef/renderer/frame_impl.h | 2 +- ...n_javascript_function_invocation_helper.cc | 2 +- libcef_dll/wrapper_types.h | 5 +- 147 files changed, 4026 insertions(+), 1203 deletions(-) create mode 100644 include/capi/cef_custom_media_info_capi.h create mode 100644 include/capi/cef_custom_media_player_delegate_capi.h create mode 100644 include/capi/cef_media_player_listener_capi.h create mode 100644 include/capi/cef_web_extension_api_handler_capi.h create mode 100644 include/cef_web_extension_api_handler.h create mode 100644 libcef/browser/extensions/api/tabs/tabs_event_router.cc create mode 100644 libcef/browser/extensions/api/tabs/tabs_event_router.h create mode 100644 libcef/browser/extensions/api/tabs/tabs_windows_api.cc create mode 100644 libcef/browser/extensions/api/tabs/tabs_windows_api.h rename libcef/renderer/alloy/{ohos_safe_browsing_error_page_controller_delegate_impl.cc => alloy_safe_browsing_error_page_controller_delegate_impl.cc} (60%) rename libcef/renderer/alloy/{ohos_safe_browsing_error_page_controller_delegate_impl.h => alloy_safe_browsing_error_page_controller_delegate_impl.h} (71%) diff --git a/BUILD.gn b/BUILD.gn index 9862d7230..69165ab83 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -954,8 +954,8 @@ source_set("libcef_static") { "libcef/renderer/alloy/alloy_content_renderer_client.h", "libcef/renderer/alloy/alloy_render_thread_observer.cc", "libcef/renderer/alloy/alloy_render_thread_observer.h", - "libcef/renderer/alloy/ohos_safe_browsing_error_page_controller_delegate_impl.cc", - "libcef/renderer/alloy/ohos_safe_browsing_error_page_controller_delegate_impl.h", + "libcef/renderer/alloy/alloy_safe_browsing_error_page_controller_delegate_impl.cc", + "libcef/renderer/alloy/alloy_safe_browsing_error_page_controller_delegate_impl.h", "libcef/renderer/alloy/url_loader_throttle_provider_impl.cc", "libcef/renderer/alloy/url_loader_throttle_provider_impl.h", "libcef/renderer/browser_impl.cc", @@ -1027,24 +1027,26 @@ source_set("libcef_static") { "libcef/browser/autofill/oh_autofill_manager.h", "libcef/browser/autofill/oh_autofill_provider.cc", "libcef/browser/autofill/oh_autofill_provider.h", - "libcef/browser/ohos_safe_browsing/ohos_safe_browsing_response.h", - "libcef/browser/ohos_safe_browsing/ohos_sb_block_page.cc", - "libcef/browser/ohos_safe_browsing/ohos_sb_block_page.h", - "libcef/browser/ohos_safe_browsing/ohos_sb_client.cc", - "libcef/browser/ohos_safe_browsing/ohos_sb_client.h", - "libcef/browser/ohos_safe_browsing/ohos_sb_controller_client.cc", - "libcef/browser/ohos_safe_browsing/ohos_sb_controller_client.h", - "libcef/browser/ohos_safe_browsing/ohos_sb_prefs.cc", - "libcef/browser/ohos_safe_browsing/ohos_sb_prefs.h", - "libcef/browser/ohos_safe_browsing/ohos_url_trust_list_interface.h", - "libcef/browser/ohos_safe_browsing/ohos_url_trust_list_manager.cc", - "libcef/browser/ohos_safe_browsing/ohos_url_trust_list_manager.h", - "libcef/browser/ohos_safe_browsing/ohos_url_trust_list_navigation_throttle.cc", - "libcef/browser/ohos_safe_browsing/ohos_url_trust_list_navigation_throttle.h", "libcef/browser/report_manager.cc", "libcef/browser/report_manager.h", "libcef/browser/res_reporter.cc", "libcef/browser/res_reporter.h", + "libcef/browser/safe_browsing/safe_browsing_response.h", + "libcef/browser/safe_browsing/safe_browsing_tab_helper.cc", + "libcef/browser/safe_browsing/safe_browsing_tab_helper.h", + "libcef/browser/safe_browsing/sb_block_page.cc", + "libcef/browser/safe_browsing/sb_block_page.h", + "libcef/browser/safe_browsing/sb_client.cc", + "libcef/browser/safe_browsing/sb_client.h", + "libcef/browser/safe_browsing/sb_controller_client.cc", + "libcef/browser/safe_browsing/sb_controller_client.h", + "libcef/browser/safe_browsing/sb_prefs.cc", + "libcef/browser/safe_browsing/sb_prefs.h", + "libcef/browser/safe_browsing/url_trust_list_interface.h", + "libcef/browser/safe_browsing/url_trust_list_manager.cc", + "libcef/browser/safe_browsing/url_trust_list_manager.h", + "libcef/browser/safe_browsing/url_trust_list_navigation_throttle.cc", + "libcef/browser/safe_browsing/url_trust_list_navigation_throttle.h", "libcef/renderer/alloy/alloy_content_settings_client.cc", "libcef/renderer/alloy/alloy_content_settings_client.h", ] @@ -1092,6 +1094,18 @@ source_set("libcef_static") { #endif + #ifdef OHOS_EX_EXCEPTION_LIST + if (defined(ohos_ex_exception_list) && ohos_ex_exception_list) { + sources += [ + "libcef/browser/content_settings/oh_host_content_settings_observer.cc", + "libcef/browser/content_settings/oh_host_content_settings_observer.h", + "libcef/browser/content_settings/oh_host_content_settings_observer_factory.cc", + "libcef/browser/content_settings/oh_host_content_settings_observer_factory.h", + ] + } + + #endif + #ifdef OHOS_EX_PASSWORD || OHOS_PASSWORD_AUTOFILL if ((defined(ohos_ex_password) && ohos_ex_password) || (defined(ohos_password_autofill) && ohos_password_autofill)) { @@ -1107,16 +1121,6 @@ source_set("libcef_static") { #endif - #ifdef OHOS_NAVIGATION - if (defined(ohos_navigation) && ohos_navigation) { - sources += [ - "libcef/browser/load_committed_details_impl.cc", - "libcef/browser/load_committed_details_impl.h", - ] - } - - #endif - #ifdef OHOS_INCOGNITO_MODE if (defined(ohos_incognito_mode) && ohos_incognito_mode) { sources += [ @@ -1133,6 +1137,16 @@ source_set("libcef_static") { #endif + #ifdef OHOS_NAVIGATION + if (defined(ohos_navigation) && ohos_navigation) { + sources += [ + "libcef/browser/load_committed_details_impl.cc", + "libcef/browser/load_committed_details_impl.h", + ] + } + + #endif + #if defined(OHOS_CUSTOM_VIDEO_PLAYER) if (defined(ohos_custom_video_player) && ohos_custom_video_player) { sources += [ @@ -1144,7 +1158,7 @@ source_set("libcef_static") { #endif // OHOS_CUSTOM_VIDEO_PLAYER - #if defined(OHOS_ADSBLOCK) + #if defined(OHOS_ARKWEB_ADBLOCK) sources += [ "libcef/browser/adsblock_manager_impl.cc", "libcef/browser/adsblock_manager_impl.h", @@ -1283,9 +1297,12 @@ source_set("libcef_static") { if (defined(ohos_nweb_ex) && ohos_nweb_ex) { deps += [ "//ohos_nweb_ex/overrides/cef" ] + + import("//ohos_nweb_ex/build/env.gni") + configs += [ "//ohos_nweb_ex/build:build_config" ] } - #ifdef OHOS_EX_ADBLOCK + #ifdef OHOS_ARKWEB_ADBLOCK if (defined(ohos_arkweb_adblock) && ohos_arkweb_adblock) { sources += [ "libcef/browser/subresource_filter/adblock_content_subresource_filter_web_contents_helper_factory.cc", @@ -1311,6 +1328,18 @@ source_set("libcef_static") { #endif + #ifdef OHOS_ARKWEB_EXTENSIONS + if (defined(ohos_arkweb_extensions) && ohos_arkweb_extensions) { + sources += [ + "libcef/browser/extensions/api/tabs/tabs_event_router.cc", + "libcef/browser/extensions/api/tabs/tabs_event_router.h", + "libcef/browser/extensions/api/tabs/tabs_windows_api.cc", + "libcef/browser/extensions/api/tabs/tabs_windows_api.h", + ] + } + + #endif + #if defined(OHOS_PRINT) if (defined(ohos_print) && ohos_print) { sources += [ diff --git a/cef_paths.gypi b/cef_paths.gypi index 97e1f9903..b3529910d 100644 --- a/cef_paths.gypi +++ b/cef_paths.gypi @@ -8,7 +8,7 @@ # by hand. See the translator.README.txt file in the tools directory for # more information. # -# $hash=c1b8ac822713f57ce24a7a854fa47b402cd084f3$ +# $hash=a9ed856c5a6fe3d0ab5287807ccbf3a85c31f2a7$ # { @@ -97,6 +97,7 @@ 'include/cef_v8.h', 'include/cef_values.h', 'include/cef_waitable_event.h', + 'include/cef_web_extension_api_handler.h', 'include/cef_web_storage.h', 'include/cef_x509_certificate.h', 'include/cef_xml_reader.h', @@ -213,6 +214,7 @@ 'include/capi/cef_v8_capi.h', 'include/capi/cef_values_capi.h', 'include/capi/cef_waitable_event_capi.h', + 'include/capi/cef_web_extension_api_handler_capi.h', 'include/capi/cef_web_storage_capi.h', 'include/capi/cef_x509_certificate_capi.h', 'include/capi/cef_xml_reader_capi.h', @@ -611,6 +613,8 @@ 'libcef_dll/ctocpp/views/view_delegate_ctocpp.h', 'libcef_dll/cpptoc/waitable_event_cpptoc.cc', 'libcef_dll/cpptoc/waitable_event_cpptoc.h', + 'libcef_dll/ctocpp/web_extension_api_handler_ctocpp.cc', + 'libcef_dll/ctocpp/web_extension_api_handler_ctocpp.h', 'libcef_dll/ctocpp/web_message_receiver_ctocpp.cc', 'libcef_dll/ctocpp/web_message_receiver_ctocpp.h', 'libcef_dll/cpptoc/web_storage_cpptoc.cc', @@ -999,6 +1003,8 @@ 'libcef_dll/cpptoc/views/view_delegate_cpptoc.h', 'libcef_dll/ctocpp/waitable_event_ctocpp.cc', 'libcef_dll/ctocpp/waitable_event_ctocpp.h', + 'libcef_dll/cpptoc/web_extension_api_handler_cpptoc.cc', + 'libcef_dll/cpptoc/web_extension_api_handler_cpptoc.h', 'libcef_dll/cpptoc/web_message_receiver_cpptoc.cc', 'libcef_dll/cpptoc/web_message_receiver_cpptoc.h', 'libcef_dll/ctocpp/web_storage_ctocpp.cc', diff --git a/include/capi/cef_browser_capi.h b/include/capi/cef_browser_capi.h index eacdb3d0e..0fd934b2d 100644 --- a/include/capi/cef_browser_capi.h +++ b/include/capi/cef_browser_capi.h @@ -33,7 +33,7 @@ // by hand. See the translator.README.txt file in the tools directory for // more information. // -// $hash=dbbd9202c9a9de9eeaeef1b22d2f222d9b9500fc$ +// $hash=67cb87503c87044494ef015d3ed927c0f7873bf0$ // #ifndef CEF_INCLUDE_CAPI_CEF_BROWSER_CAPI_H_ @@ -101,7 +101,7 @@ typedef struct _cef_store_web_archive_result_callback_t { /// /// Structure to implement to be notified of asynchronous completion via -/// cef_browser_host_tBase::SetGestureEventResult(). +/// cef_browser_host_tBase::set_gesture_event_result(). /// typedef struct _cef_gesture_event_callback_t { /// @@ -131,8 +131,30 @@ typedef struct _cef_web_message_receiver_t { /// void(CEF_CALLBACK* on_message)(struct _cef_web_message_receiver_t* self, struct _cef_value_t* message); + + /// + /// The same as OnMessage, the result of the execution will be returned. + /// + int(CEF_CALLBACK* on_message_with_bool_result)( + struct _cef_web_message_receiver_t* self, + struct _cef_value_t* message); } cef_web_message_receiver_t; +/// +/// cef_set_lock_callback_t. +/// +typedef struct _cef_set_lock_callback_t { + /// + /// Base structure. + /// + cef_base_ref_counted_t base; + + /// + /// Handle. + /// + void(CEF_CALLBACK* handle)(struct _cef_set_lock_callback_t* self, int key); +} cef_set_lock_callback_t; + /// /// Structure to implement to be notified of compiling javascript completion via /// cef_browser_host_tBase::precompile_java_script(). @@ -167,21 +189,6 @@ typedef struct _cef_cache_options_t { struct _cef_cache_options_t* self); } cef_cache_options_t; -/// -/// cef_set_lock_callback_t -/// -typedef struct _cef_set_lock_callback_t { - /// - /// Base structure. - /// - cef_base_ref_counted_t base; - - /// - /// Handle. - /// - void(CEF_CALLBACK* handle)(struct _cef_set_lock_callback_t* self, int key); -} cef_set_lock_callback_t; - /// /// Structure used to represent a browser. When used in the browser process the /// functions of this structure may be called on any thread unless otherwise @@ -352,12 +359,12 @@ typedef struct _cef_browser_t { /// /// display the selection control when click Free copy structure /// - void(CEF_CALLBACK* select_and_copy)(struct _cef_browser_t* self); + void(CEF_CALLBACK* show_free_copy_menu)(struct _cef_browser_t* self); /// /// should show free copy menu /// - int(CEF_CALLBACK* should_show_free_copy)(struct _cef_browser_t* self); + int(CEF_CALLBACK* should_show_free_copy_menu)(struct _cef_browser_t* self); /// /// select password dialog to fill @@ -428,11 +435,20 @@ typedef struct _cef_browser_t { int(CEF_CALLBACK* get_nweb_id)(struct _cef_browser_t* self); /// - /// Set whether the target_blank pop-up window is opened in the current tab. + /// Get whether Ads block is enabled. /// - void(CEF_CALLBACK* set_enable_blank_target_popup_intercept)( - struct _cef_browser_t* self, - int enableBlankTargetPopup); + int(CEF_CALLBACK* is_ads_block_enabled)(struct _cef_browser_t* self); + + /// + /// Get whether Ads block is enabled for current page. + /// + int(CEF_CALLBACK* is_ads_block_enabled_for_cur_page)( + struct _cef_browser_t* self); + + /// + /// Set enable to allow automatically save password + /// + void(CEF_CALLBACK* enable_ads_block)(struct _cef_browser_t* self, int enable); /// /// Whether automatically saving password had been enabled. @@ -464,11 +480,6 @@ typedef struct _cef_browser_t { void(CEF_CALLBACK* set_save_password)(struct _cef_browser_t* self, int enable); - /// - /// Get security level for current page. - /// - int(CEF_CALLBACK* get_security_level)(struct _cef_browser_t* self); - /// /// Enable the ability to check website security risks. /// @@ -481,33 +492,41 @@ typedef struct _cef_browser_t { int(CEF_CALLBACK* is_safe_browsing_enabled)(struct _cef_browser_t* self); /// - /// Enable the ability to intelligent tracking prevention, default disabled. + /// Get security level for current page. /// - void(CEF_CALLBACK* enable_intelligent_tracking_prevention)( - struct _cef_browser_t* self, - int enable); + int(CEF_CALLBACK* get_security_level)(struct _cef_browser_t* self); /// - /// Get whether intelligent tracking prevention is enabled. + /// Get the shrink viewport height. /// - int(CEF_CALLBACK* is_intelligent_tracking_prevention_enabled)( - struct _cef_browser_t* self); + int(CEF_CALLBACK* insert_back_forward_entry)(struct _cef_browser_t* self, + int index, + const cef_string_t* url); /// - /// Get whether Ads block is enabled. + /// Get the shrink viewport height. /// - int(CEF_CALLBACK* is_ads_block_enabled)(struct _cef_browser_t* self); + int(CEF_CALLBACK* update_navigation_entry_url)(struct _cef_browser_t* self, + int index, + const cef_string_t* url); /// - /// Get whether Ads block is enabled for current page. + /// Get the shrink viewport height. /// - int(CEF_CALLBACK* is_ads_block_enabled_for_cur_page)( - struct _cef_browser_t* self); + void(CEF_CALLBACK* clear_forward_list)(struct _cef_browser_t* self); /// - /// Set enable to allow automatically save password + /// Enable the ability to intelligent tracking prevention, default disabled. /// - void(CEF_CALLBACK* enable_ads_block)(struct _cef_browser_t* self, int enable); + void(CEF_CALLBACK* enable_intelligent_tracking_prevention)( + struct _cef_browser_t* self, + int enable); + + /// + /// Get whether intelligent tracking prevention is enabled. + /// + int(CEF_CALLBACK* is_intelligent_tracking_prevention_enabled)( + struct _cef_browser_t* self); /// /// Set url trust list. @@ -518,7 +537,17 @@ typedef struct _cef_browser_t { cef_string_t* detailErrMsg); /// - /// Set url trust list. + /// Set tabId. + /// + void(CEF_CALLBACK* set_tab_id)(struct _cef_browser_t* self, int tab_id); + + /// + /// Get tabId. + /// + int(CEF_CALLBACK* get_tab_id)(struct _cef_browser_t* self); + + /// + /// Set back forward cache options. /// void(CEF_CALLBACK* set_back_forward_cache_options)( struct _cef_browser_t* self, @@ -1322,13 +1351,15 @@ typedef struct _cef_browser_host_t { /// GetImageForContextNode /// void(CEF_CALLBACK* get_image_for_context_node)( - struct _cef_browser_host_t* self); + struct _cef_browser_host_t* self, + int command_id); /// /// GetImageFromCache /// void(CEF_CALLBACK* get_image_from_cache)(struct _cef_browser_host_t* self, - const cef_string_t* url); + const cef_string_t* url, + int command_id); /// /// ExitFullScreen @@ -1500,7 +1531,7 @@ typedef struct _cef_browser_host_t { /// Post a message to the port. /// void(CEF_CALLBACK* post_port_message)(struct _cef_browser_host_t* self, - cef_string_t* port_handle, + const cef_string_t* port_handle, struct _cef_value_t* message); /// @@ -1508,7 +1539,7 @@ typedef struct _cef_browser_host_t { /// void(CEF_CALLBACK* set_port_message_callback)( struct _cef_browser_host_t* self, - cef_string_t* port_handle, + const cef_string_t* port_handle, struct _cef_web_message_receiver_t* callback); /// @@ -1774,6 +1805,14 @@ typedef struct _cef_browser_host_t { void(CEF_CALLBACK* set_overscroll_mode)(struct _cef_browser_host_t* self, int mode); + /// + /// Change the zoom factor for browser zoom. If called on the UI thread the + /// change will be applied immediately. Otherwise, the change will be applied + /// asynchronously on the UI thread. + /// + void(CEF_CALLBACK* set_browser_zoom_level)(struct _cef_browser_host_t* self, + double zoomFactor); + /// /// Discard a webview window /// @@ -1784,14 +1823,6 @@ typedef struct _cef_browser_host_t { /// int(CEF_CALLBACK* restore)(struct _cef_browser_host_t* self); - /// - /// Change the zoom factor for browser zoom. If called on the UI thread the - /// change will be applied immediately. Otherwise, the change will be applied - /// asynchronously on the UI thread. - /// - void(CEF_CALLBACK* set_browser_zoom_level)(struct _cef_browser_host_t* self, - double zoomFactor); - /// /// Get the top controls offset. /// @@ -1803,6 +1834,26 @@ typedef struct _cef_browser_host_t { int(CEF_CALLBACK* get_shrink_viewport_height)( struct _cef_browser_host_t* self); + /// + /// Get the shrink viewport height. + /// + int(CEF_CALLBACK* insert_back_forward_entry)(struct _cef_browser_host_t* self, + int index, + const cef_string_t* url); + + /// + /// Get the shrink viewport height. + /// + int(CEF_CALLBACK* update_navigation_entry_url)( + struct _cef_browser_host_t* self, + int index, + const cef_string_t* url); + + /// + /// Get the shrink viewport height. + /// + void(CEF_CALLBACK* clear_forward_list)(struct _cef_browser_host_t* self); + /// /// Set background print enable. /// @@ -1822,7 +1873,15 @@ typedef struct _cef_browser_host_t { int scrollType); /// - /// Start current camera. + /// Get the last javascript proxy calling frame url. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t( + CEF_CALLBACK* get_last_javascript_proxy_calling_frame_url)( + struct _cef_browser_host_t* self); + + /// + /// Start current camera. /// void(CEF_CALLBACK* start_camera)(struct _cef_browser_host_t* self); @@ -1836,14 +1895,6 @@ typedef struct _cef_browser_host_t { /// void(CEF_CALLBACK* close_camera)(struct _cef_browser_host_t* self); - /// - /// Get the last javascript proxy calling frame url. - /// - // The resulting string must be freed by calling cef_string_userfree_free(). - cef_string_userfree_t( - CEF_CALLBACK* get_last_javascript_proxy_calling_frame_url)( - struct _cef_browser_host_t* self); - /// /// Set NWebID. /// @@ -1855,14 +1906,11 @@ typedef struct _cef_browser_host_t { int(CEF_CALLBACK* get_pending_size_status)(struct _cef_browser_host_t* self); /// - /// precompile javascript and generate code cache. + /// Get cef_download_item_t by download_item_id. /// - void(CEF_CALLBACK* precompile_java_script)( + struct _cef_download_item_t*(CEF_CALLBACK* get_download_item)( struct _cef_browser_host_t* self, - const char* url, - const char* script, - struct _cef_cache_options_t* cacheOptions, - struct _cef_precompile_callback_t* callback); + uint32 item_id); /// /// SetWakeLockHandler. @@ -1873,37 +1921,30 @@ typedef struct _cef_browser_host_t { struct _cef_set_lock_callback_t* callback); /// - /// Get cef_download_item_t by download_item_id. - /// - struct _cef_download_item_t*(CEF_CALLBACK* get_download_item)( - struct _cef_browser_host_t* self, - uint32 item_id); - - /// - /// Notify browser host needs reload when the render process terminated. + /// Notify browser host needs reoload when the render process terminated. /// - void(CEF_CALLBACK* notify_needs_reload)(struct _cef_browser_host_t* self, - int needs_reload); + void(CEF_CALLBACK* set_needs_reload)(struct _cef_browser_host_t* self, + int needs_reload); /// - /// Return true if needs reload page, or false if nees not reload. + /// Return true (1) if needs reload page, or false (0) if needs not reload. /// int(CEF_CALLBACK* needs_reload)(struct _cef_browser_host_t* self); /// - /// Terminate render process + /// precompile javascript and generate code cache. /// - int(CEF_CALLBACK* terminate_render_process)(struct _cef_browser_host_t* self); + void(CEF_CALLBACK* precompile_java_script)( + struct _cef_browser_host_t* self, + const char* url, + const char* script, + struct _cef_cache_options_t* cacheOptions, + struct _cef_precompile_callback_t* callback); /// - /// RegisterNativeJSProxy + /// update DrawRect. /// - void(CEF_CALLBACK* register_native_jsproxy)(struct _cef_browser_host_t* self, - const cef_string_t* object_name, - cef_string_list_t method_list, - int32_t object_id, - int is_async, - const cef_string_t* permission); + void(CEF_CALLBACK* update_draw_rect)(struct _cef_browser_host_t* self); /// /// SendTouchpadFlingEvent @@ -1921,9 +1962,19 @@ typedef struct _cef_browser_host_t { int mode); /// - /// update draw_rect state. + /// Terminate render process /// - void(CEF_CALLBACK* update_draw_rect)(struct _cef_browser_host_t* self); + int(CEF_CALLBACK* terminate_render_process)(struct _cef_browser_host_t* self); + + /// + /// RegisterNativeJSProxy + /// + void(CEF_CALLBACK* register_native_jsproxy)(struct _cef_browser_host_t* self, + const cef_string_t* object_name, + cef_string_list_t method_list, + int32_t object_id, + int is_async, + const cef_string_t* permission); /// /// Called when text is selected. @@ -1951,6 +2002,12 @@ typedef struct _cef_browser_host_t { void(CEF_CALLBACK* advance_focus_for_ime)(struct _cef_browser_host_t* self, int focusType); + /// + /// Called when image analyzer overlay is destoryed. + /// + void(CEF_CALLBACK* on_destroy_image_analyzer_overlay)( + struct _cef_browser_host_t* self); + /// /// OnSafeInsetsChange /// @@ -1973,6 +2030,21 @@ typedef struct _cef_browser_host_t { struct _cef_browser_host_t* self, cef_string_list_t dir_list); + /// + /// Receiving the tab updated notification. + /// + void(CEF_CALLBACK* web_extension_tab_updated)( + struct _cef_browser_host_t* self, + int tab_id, + cef_string_list_t changed_property_names, + const cef_string_t* url); + + /// + /// ScrollFocusedEditableNodeIntoView. + /// + void(CEF_CALLBACK* scroll_focused_editable_node_into_view)( + struct _cef_browser_host_t* self); + /// /// Set the callback of the autofill event. /// @@ -1986,12 +2058,6 @@ typedef struct _cef_browser_host_t { void(CEF_CALLBACK* fill_autofill_data)(struct _cef_browser_host_t* self, struct _cef_value_t* message); - /// - /// ScrollFocusedEditableNodeIntoView. - /// - void(CEF_CALLBACK* scroll_focused_editable_node_into_view)( - struct _cef_browser_host_t* self); - /// /// Process autofill cancel content. /// diff --git a/include/capi/cef_client_capi.h b/include/capi/cef_client_capi.h index 787d5e6a9..d3ec72309 100644 --- a/include/capi/cef_client_capi.h +++ b/include/capi/cef_client_capi.h @@ -33,7 +33,7 @@ // by hand. See the translator.README.txt file in the tools directory for // more information. // -// $hash=0814b0c8da2385498d0770cc58f5b5b9f1678958$ +// $hash=9157d7b0ec525fdca339a4a3c71ed09ec5d379a0$ // #ifndef CEF_INCLUDE_CAPI_CEF_CLIENT_CAPI_H_ @@ -44,6 +44,8 @@ #include "include/capi/cef_base_capi.h" #include "include/capi/cef_command_handler_capi.h" #include "include/capi/cef_context_menu_handler_capi.h" +#include "include/capi/cef_custom_media_info_capi.h" +#include "include/capi/cef_custom_media_player_delegate_capi.h" #include "include/capi/cef_dialog_handler_capi.h" #include "include/capi/cef_display_handler_capi.h" #include "include/capi/cef_download_handler_capi.h" @@ -57,12 +59,14 @@ #include "include/capi/cef_life_span_handler_capi.h" #include "include/capi/cef_load_handler_capi.h" #include "include/capi/cef_media_handler_capi.h" +#include "include/capi/cef_media_player_listener_capi.h" #include "include/capi/cef_permission_handler_capi.h" #include "include/capi/cef_permission_request_capi.h" #include "include/capi/cef_print_handler_capi.h" #include "include/capi/cef_process_message_capi.h" #include "include/capi/cef_render_handler_capi.h" #include "include/capi/cef_request_handler_capi.h" +#include "include/capi/cef_web_extension_api_handler_capi.h" #ifdef __cplusplus extern "C" { @@ -281,6 +285,13 @@ typedef struct _cef_client_t { /// int(CEF_CALLBACK* do_browser_controls_shrink_renderer_size)( struct _cef_client_t* self); + + /// + /// Return the handler for web extension api. If no handler is provided the + /// default implementation will be used. + /// + struct _cef_web_extension_api_handler_t*( + CEF_CALLBACK* get_web_extension_api_handler)(struct _cef_client_t* self); } cef_client_t; #ifdef __cplusplus diff --git a/include/capi/cef_context_menu_handler_capi.h b/include/capi/cef_context_menu_handler_capi.h index f56c788ea..20dbc0973 100644 --- a/include/capi/cef_context_menu_handler_capi.h +++ b/include/capi/cef_context_menu_handler_capi.h @@ -185,7 +185,7 @@ typedef struct _cef_context_menu_handler_t { int is_mouse_trigger); /// - /// UpdateClippedSelectionBounds. + /// UpdateClippedSelectionBounds /// int(CEF_CALLBACK* update_clipped_selection_bounds)( struct _cef_context_menu_handler_t* self, @@ -222,14 +222,16 @@ typedef struct _cef_context_menu_handler_t { void(CEF_CALLBACK* on_get_image_for_context_node)( struct _cef_context_menu_handler_t* self, struct _cef_browser_t* browser, - struct _cef_image_t* image); + struct _cef_image_t* image, + int command_id); /// /// Called when GetImageFromCache function to get image from memory cache. /// void(CEF_CALLBACK* on_get_image_from_cache)( struct _cef_context_menu_handler_t* self, - struct _cef_image_t* image); + struct _cef_image_t* image, + int command_id); /// /// Called when you need to temporarily hide/restore the handle menu. diff --git a/include/capi/cef_cookie_capi.h b/include/capi/cef_cookie_capi.h index 20adae8ac..ba42ad0c1 100644 --- a/include/capi/cef_cookie_capi.h +++ b/include/capi/cef_cookie_capi.h @@ -33,7 +33,7 @@ // by hand. See the translator.README.txt file in the tools directory for // more information. // -// $hash=cb6483fc6c0cda8419cd2be92b97f98392a417b9$ +// $hash=1a8af0e7a531b4b8768225572a3f18940fbbf276$ // #ifndef CEF_INCLUDE_CAPI_CEF_COOKIE_CAPI_H_ @@ -81,7 +81,8 @@ typedef struct _cef_cookie_manager_t { const cef_string_t* url, int includeHttpOnly, struct _cef_cookie_visitor_t* visitor, - int is_sync); + int is_sync, + int is_from_ndk); /// /// Sets a cookie given a valid URL and explicit user-provided cookie @@ -97,7 +98,8 @@ typedef struct _cef_cookie_manager_t { const struct _cef_cookie_t* cookie, struct _cef_set_cookie_callback_t* callback, int is_sync, - const cef_string_t* str_cookie); + const cef_string_t* str_cookie, + int includeHttpOnly); /// /// Delete all cookies that match the specified parameters. If both |url| and diff --git a/include/capi/cef_custom_media_info_capi.h b/include/capi/cef_custom_media_info_capi.h new file mode 100644 index 000000000..e69de29bb diff --git a/include/capi/cef_custom_media_player_delegate_capi.h b/include/capi/cef_custom_media_player_delegate_capi.h new file mode 100644 index 000000000..e69de29bb diff --git a/include/capi/cef_load_handler_capi.h b/include/capi/cef_load_handler_capi.h index 615328d03..c4528efb3 100644 --- a/include/capi/cef_load_handler_capi.h +++ b/include/capi/cef_load_handler_capi.h @@ -178,6 +178,13 @@ typedef struct _cef_load_handler_t { int64_t navigationStartTick, int64_t firstContentfulPaintMs); + /// + /// Called when received website security risk check result. + /// + void(CEF_CALLBACK* on_safe_browsing_check_result)( + struct _cef_load_handler_t* self, + int threat_type); + /// /// Called when the first meaningful paint rendering of web page. /// @@ -199,13 +206,6 @@ typedef struct _cef_load_handler_t { struct _cef_load_handler_t* self, struct _cef_load_committed_details_t* details); - /// - /// Called when received website security risk check result. - /// - void(CEF_CALLBACK* on_safe_browsing_check_result)( - struct _cef_load_handler_t* self, - int threat_type); - /// /// Called when tracker's cookie is prevented. /// diff --git a/include/capi/cef_media_player_listener_capi.h b/include/capi/cef_media_player_listener_capi.h new file mode 100644 index 000000000..e69de29bb diff --git a/include/capi/cef_permission_request_capi.h b/include/capi/cef_permission_request_capi.h index 3e007d4df..94768e1e5 100644 --- a/include/capi/cef_permission_request_capi.h +++ b/include/capi/cef_permission_request_capi.h @@ -33,7 +33,7 @@ // by hand. See the translator.README.txt file in the tools directory for // more information. // -// $hash=e09e9bcd5575c1878e9439e8d3932b4c37bd32ca$ +// $hash=78adaf2cb74f85760d331e10ad4311a1c4d16ad9$ // #ifndef CEF_INCLUDE_CAPI_CEF_PERMISSION_REQUEST_CAPI_H_ @@ -258,6 +258,51 @@ typedef struct _cef_browser_permission_request_delegate_t { struct _cef_browser_permission_request_delegate_t* self, int value, const cef_string_t* origin); + + /// + /// Handle the Audio Capture permission requests. + /// + void(CEF_CALLBACK* ask_audio_capture_permission)( + struct _cef_browser_permission_request_delegate_t* self, + const cef_string_t* origin, + cef_permission_callback_t callback); + + /// + /// Cancel the Audio Capturepermission requests. + /// + void(CEF_CALLBACK* abort_ask_audio_capture_permission)( + struct _cef_browser_permission_request_delegate_t* self, + const cef_string_t* origin); + + /// + /// Handle the Video Capture permission requests. + /// + void(CEF_CALLBACK* ask_video_capture_permission)( + struct _cef_browser_permission_request_delegate_t* self, + const cef_string_t* origin, + cef_permission_callback_t callback); + + /// + /// Cancel the Video Capturepermission requests. + /// + void(CEF_CALLBACK* abort_ask_video_capture_permission)( + struct _cef_browser_permission_request_delegate_t* self, + const cef_string_t* origin); + + /// + /// Handle the Clipboard Sanitized permission requests. + /// + void(CEF_CALLBACK* ask_clipboard_sanitized_write_permission)( + struct _cef_browser_permission_request_delegate_t* self, + const cef_string_t* origin, + cef_permission_callback_t callback); + + /// + /// Cancel the Clipboard Read Sanitezed permission requests. + /// + void(CEF_CALLBACK* abort_ask_clipboard_sanitized_write_permission)( + struct _cef_browser_permission_request_delegate_t* self, + const cef_string_t* origin); } cef_browser_permission_request_delegate_t; /// diff --git a/include/capi/cef_render_handler_capi.h b/include/capi/cef_render_handler_capi.h index 6826ca9c0..5cd1f00e9 100644 --- a/include/capi/cef_render_handler_capi.h +++ b/include/capi/cef_render_handler_capi.h @@ -33,7 +33,7 @@ // by hand. See the translator.README.txt file in the tools directory for // more information. // -// $hash=898a08a55883581483a35459d60c09c1553fc3ec$ +// $hash=b8463f4ad34bf2e28a067fe989a1d926db95d5a7$ // #ifndef CEF_INCLUDE_CAPI_CEF_RENDER_HANDLER_CAPI_H_ @@ -381,16 +381,6 @@ typedef struct _cef_render_handler_t { void(CEF_CALLBACK* release_resize_hold)(struct _cef_render_handler_t* self, struct _cef_browser_t* browser); - /// - /// Called when text input state has changed for the specified |browser|. - /// - void(CEF_CALLBACK* on_update_text_input_state_called)( - struct _cef_render_handler_t* self, - struct _cef_browser_t* browser, - const cef_string_t* text, - const cef_range_t* selected_range, - const cef_range_t* compositon_range); - /// /// Called when selecting word. /// @@ -419,21 +409,23 @@ typedef struct _cef_render_handler_t { const cef_rect_t* cef_screen_rect); /// - /// Called to retrieve the visible view rectangle in screen DIP coordinates. - /// This function must always provide a non-NULL rectangle. + /// Called when text input state has changed for the specified |browser|. /// - void(CEF_CALLBACK *get_visible_viewport_rect)( - struct _cef_render_handler_t *self, - struct _cef_browser_t *browser, - cef_rect_t *rect); + void(CEF_CALLBACK* on_update_text_input_state_called)( + struct _cef_render_handler_t* self, + struct _cef_browser_t* browser, + const cef_string_t* text, + const cef_range_t* selected_range, + const cef_range_t* compositon_range); /// - /// Called when loss frame. + /// Called to retrieve the view rectangle in screen DIP coordinates. This + /// function must always provide a non-NULL rectangle. /// - void(CEF_CALLBACK* send_dynamic_frame_loss_event)(struct _cef_render_handler_t* self, - struct _cef_browser_t* browser, - const cef_string_t* sceneId, - bool isStart); + void(CEF_CALLBACK* get_visible_viewport_rect)( + struct _cef_render_handler_t* self, + struct _cef_browser_t* browser, + cef_rect_t* rect); /// /// OnResizeScrollableViewport. @@ -447,6 +439,13 @@ typedef struct _cef_render_handler_t { /// void(CEF_CALLBACK* set_fill_content)(struct _cef_render_handler_t* self, const char* content); + + /// + /// SetGestureEventResult + /// + void(CEF_CALLBACK* set_gesture_event_result)( + struct _cef_render_handler_t* self, + const int result); } cef_render_handler_t; #ifdef __cplusplus diff --git a/include/capi/cef_request_capi.h b/include/capi/cef_request_capi.h index 2475ba790..beaf50e6a 100644 --- a/include/capi/cef_request_capi.h +++ b/include/capi/cef_request_capi.h @@ -63,78 +63,78 @@ typedef struct _cef_request_t { /// /// Returns true (1) if this object is read-only. /// - int(CEF_CALLBACK *is_read_only)(struct _cef_request_t *self); + int(CEF_CALLBACK* is_read_only)(struct _cef_request_t* self); /// /// Get the fully qualified URL. /// // The resulting string must be freed by calling cef_string_userfree_free(). - cef_string_userfree_t(CEF_CALLBACK *get_url)(struct _cef_request_t *self); + cef_string_userfree_t(CEF_CALLBACK* get_url)(struct _cef_request_t* self); /// /// Set the fully qualified URL. /// - void(CEF_CALLBACK *set_url)(struct _cef_request_t *self, - const cef_string_t *url); + void(CEF_CALLBACK* set_url)(struct _cef_request_t* self, + const cef_string_t* url); /// /// Get the request function type. The value will default to POST if post data /// is provided and GET otherwise. /// // The resulting string must be freed by calling cef_string_userfree_free(). - cef_string_userfree_t(CEF_CALLBACK *get_method)(struct _cef_request_t *self); + cef_string_userfree_t(CEF_CALLBACK* get_method)(struct _cef_request_t* self); /// /// Set the request function type. /// - void(CEF_CALLBACK *set_method)(struct _cef_request_t *self, - const cef_string_t *method); + void(CEF_CALLBACK* set_method)(struct _cef_request_t* self, + const cef_string_t* method); /// /// Set the referrer URL and policy. If non-NULL the referrer URL must be /// fully qualified with an HTTP or HTTPS scheme component. Any username, /// password or ref component will be removed. /// - void(CEF_CALLBACK *set_referrer)(struct _cef_request_t *self, - const cef_string_t *referrer_url, + void(CEF_CALLBACK* set_referrer)(struct _cef_request_t* self, + const cef_string_t* referrer_url, cef_referrer_policy_t policy); /// /// Get the referrer URL. /// // The resulting string must be freed by calling cef_string_userfree_free(). - cef_string_userfree_t(CEF_CALLBACK *get_referrer_url)( - struct _cef_request_t *self); + cef_string_userfree_t(CEF_CALLBACK* get_referrer_url)( + struct _cef_request_t* self); /// /// Get the referrer policy. /// - cef_referrer_policy_t(CEF_CALLBACK *get_referrer_policy)( - struct _cef_request_t *self); + cef_referrer_policy_t(CEF_CALLBACK* get_referrer_policy)( + struct _cef_request_t* self); /// /// Get the post data. /// - struct _cef_post_data_t *(CEF_CALLBACK *get_post_data)( - struct _cef_request_t *self); + struct _cef_post_data_t*(CEF_CALLBACK* get_post_data)( + struct _cef_request_t* self); /// /// Set the post data. /// - void(CEF_CALLBACK *set_post_data)(struct _cef_request_t *self, - struct _cef_post_data_t *postData); + void(CEF_CALLBACK* set_post_data)(struct _cef_request_t* self, + struct _cef_post_data_t* postData); /// /// Get the header values. Will not include the Referer value if any. /// - void(CEF_CALLBACK *get_header_map)(struct _cef_request_t *self, + void(CEF_CALLBACK* get_header_map)(struct _cef_request_t* self, cef_string_multimap_t headerMap); /// /// Set the header values. If a Referer value exists in the header map it will /// be removed and ignored. /// - void(CEF_CALLBACK *set_header_map)(struct _cef_request_t *self, + void(CEF_CALLBACK* set_header_map)(struct _cef_request_t* self, cef_string_multimap_t headerMap); /// @@ -143,8 +143,9 @@ typedef struct _cef_request_t { /// |name| might have multiple values. /// // The resulting string must be freed by calling cef_string_userfree_free(). - cef_string_userfree_t(CEF_CALLBACK *get_header_by_name)( - struct _cef_request_t *self, const cef_string_t *name); + cef_string_userfree_t(CEF_CALLBACK* get_header_by_name)( + struct _cef_request_t* self, + const cef_string_t* name); /// /// Set the header |name| to |value|. If |overwrite| is true (1) any existing @@ -152,60 +153,61 @@ typedef struct _cef_request_t { /// any existing values will not be overwritten. The Referer value cannot be /// set using this function. /// - void(CEF_CALLBACK *set_header_by_name)(struct _cef_request_t *self, - const cef_string_t *name, - const cef_string_t *value, + void(CEF_CALLBACK* set_header_by_name)(struct _cef_request_t* self, + const cef_string_t* name, + const cef_string_t* value, int overwrite); /// /// Set all values at one time. /// - void(CEF_CALLBACK *set)(struct _cef_request_t *self, const cef_string_t *url, - const cef_string_t *method, - struct _cef_post_data_t *postData, + void(CEF_CALLBACK* set)(struct _cef_request_t* self, + const cef_string_t* url, + const cef_string_t* method, + struct _cef_post_data_t* postData, cef_string_multimap_t headerMap); /// /// Get the flags used in combination with cef_urlrequest_t. See /// cef_urlrequest_flags_t for supported values. /// - int(CEF_CALLBACK *get_flags)(struct _cef_request_t *self); + int(CEF_CALLBACK* get_flags)(struct _cef_request_t* self); /// /// Set the flags used in combination with cef_urlrequest_t. See /// cef_urlrequest_flags_t for supported values. /// - void(CEF_CALLBACK *set_flags)(struct _cef_request_t *self, int flags); + void(CEF_CALLBACK* set_flags)(struct _cef_request_t* self, int flags); /// /// Get the URL to the first party for cookies used in combination with /// cef_urlrequest_t. /// // The resulting string must be freed by calling cef_string_userfree_free(). - cef_string_userfree_t(CEF_CALLBACK *get_first_party_for_cookies)( - struct _cef_request_t *self); + cef_string_userfree_t(CEF_CALLBACK* get_first_party_for_cookies)( + struct _cef_request_t* self); /// /// Set the URL to the first party for cookies used in combination with /// cef_urlrequest_t. /// - void(CEF_CALLBACK *set_first_party_for_cookies)(struct _cef_request_t *self, - const cef_string_t *url); + void(CEF_CALLBACK* set_first_party_for_cookies)(struct _cef_request_t* self, + const cef_string_t* url); /// /// Get the resource type for this request. Only available in the browser /// process. /// - cef_resource_type_t(CEF_CALLBACK *get_resource_type)( - struct _cef_request_t *self); + cef_resource_type_t(CEF_CALLBACK* get_resource_type)( + struct _cef_request_t* self); /// /// Get the transition type for this request. Only available in the browser /// process and only applies to requests that represent a main frame or sub- /// frame navigation. /// - cef_transition_type_t(CEF_CALLBACK *get_transition_type)( - struct _cef_request_t *self); + cef_transition_type_t(CEF_CALLBACK* get_transition_type)( + struct _cef_request_t* self); /// /// Returns the globally unique identifier for this request or 0 if not @@ -213,35 +215,35 @@ typedef struct _cef_request_t { /// in the browser process to track a single request across multiple /// callbacks. /// - uint64(CEF_CALLBACK *get_identifier)(struct _cef_request_t *self); + uint64(CEF_CALLBACK* get_identifier)(struct _cef_request_t* self); /// /// Returns whether the request was made for the main frame document. Will be /// false (0) for subresources or iframes /// - int(CEF_CALLBACK *is_main_frame)(struct _cef_request_t *self); + int(CEF_CALLBACK* is_main_frame)(struct _cef_request_t* self); /// /// Returns whether the request was redirect. /// - int(CEF_CALLBACK *is_redirect)(struct _cef_request_t *self); + int(CEF_CALLBACK* is_redirect)(struct _cef_request_t* self); /// /// Returns whether the request was triggered by user gesture. /// - int(CEF_CALLBACK *has_user_gesture)(struct _cef_request_t *self); + int(CEF_CALLBACK* has_user_gesture)(struct _cef_request_t* self); /// /// Get the upload stream. /// - struct _cef_post_data_stream_t *(CEF_CALLBACK *get_upload_stream)( - struct _cef_request_t *self); + struct _cef_post_data_stream_t*(CEF_CALLBACK* get_upload_stream)( + struct _cef_request_t* self); } cef_request_t; /// /// Create a new cef_request_t object. /// -CEF_EXPORT cef_request_t *cef_request_create(void); +CEF_EXPORT cef_request_t* cef_request_create(void); /// /// Callback for init the stream. @@ -255,7 +257,7 @@ typedef struct _cef_post_data_stream_init_callback_t { /// /// Callback for init the stream. /// - void(CEF_CALLBACK *cont)(struct _cef_post_data_stream_init_callback_t *self, + void(CEF_CALLBACK* cont)(struct _cef_post_data_stream_init_callback_t* self, int result); } cef_post_data_stream_init_callback_t; @@ -271,8 +273,9 @@ typedef struct _cef_post_data_stream_read_callback_t { /// /// Callback for read from stream. /// - void(CEF_CALLBACK *cont)(struct _cef_post_data_stream_read_callback_t *self, - char *buffer, int bytes_read); + void(CEF_CALLBACK* cont)(struct _cef_post_data_stream_read_callback_t* self, + char* buffer, + int bytes_read); } cef_post_data_stream_read_callback_t; /// @@ -288,64 +291,66 @@ typedef struct _cef_post_data_stream_t { /// /// Set ready callback. /// - void(CEF_CALLBACK *set_read_callback)( - struct _cef_post_data_stream_t *self, - struct _cef_post_data_stream_read_callback_t *read_callback); + void(CEF_CALLBACK* set_read_callback)( + struct _cef_post_data_stream_t* self, + struct _cef_post_data_stream_read_callback_t* read_callback); /// /// Init the stream. /// - void(CEF_CALLBACK *init)( - struct _cef_post_data_stream_t *self, - struct _cef_post_data_stream_init_callback_t *init_callback); + void(CEF_CALLBACK* init)( + struct _cef_post_data_stream_t* self, + struct _cef_post_data_stream_init_callback_t* init_callback); /// /// Read the stream. /// - void(CEF_CALLBACK *read)( - struct _cef_post_data_stream_t *self, void *buffer, int buf_len, - struct _cef_post_data_stream_read_callback_t *read_callback); + void(CEF_CALLBACK* read)( + struct _cef_post_data_stream_t* self, + void* buffer, + int buf_len, + struct _cef_post_data_stream_read_callback_t* read_callback); /// /// Get the size of stream. /// - uint64(CEF_CALLBACK *get_size)(struct _cef_post_data_stream_t *self); + uint64(CEF_CALLBACK* get_size)(struct _cef_post_data_stream_t* self); /// /// Get the position of stream. /// - uint64(CEF_CALLBACK *get_position)(struct _cef_post_data_stream_t *self); + uint64(CEF_CALLBACK* get_position)(struct _cef_post_data_stream_t* self); /// /// Get if the stream is trunked. /// - int(CEF_CALLBACK *is_chunked)(struct _cef_post_data_stream_t *self); + int(CEF_CALLBACK* is_chunked)(struct _cef_post_data_stream_t* self); /// /// Get if the stream is trunked. /// - int(CEF_CALLBACK *has_null_source)(struct _cef_post_data_stream_t *self); + int(CEF_CALLBACK* has_null_source)(struct _cef_post_data_stream_t* self); /// /// Get if the stream is trunked. /// - int(CEF_CALLBACK *is_eof)(struct _cef_post_data_stream_t *self); + int(CEF_CALLBACK* is_eof)(struct _cef_post_data_stream_t* self); /// /// Get if the stream is trunked. /// - int(CEF_CALLBACK *is_in_memory)(struct _cef_post_data_stream_t *self); + int(CEF_CALLBACK* is_in_memory)(struct _cef_post_data_stream_t* self); /// /// reset(); /// - void(CEF_CALLBACK *reset)(struct _cef_post_data_stream_t *self); + void(CEF_CALLBACK* reset)(struct _cef_post_data_stream_t* self); } cef_post_data_stream_t; /// /// Create a new cef_post_data_stream_t object. /// -CEF_EXPORT cef_post_data_stream_t *cef_post_data_stream_create(void); +CEF_EXPORT cef_post_data_stream_t* cef_post_data_stream_create(void); /// /// Structure used to represent post data for a web request. The functions of @@ -360,7 +365,7 @@ typedef struct _cef_post_data_t { /// /// Returns true (1) if this object is read-only. /// - int(CEF_CALLBACK *is_read_only)(struct _cef_post_data_t *self); + int(CEF_CALLBACK* is_read_only)(struct _cef_post_data_t* self); /// /// Returns true (1) if the underlying POST data includes elements that are @@ -368,44 +373,44 @@ typedef struct _cef_post_data_t { /// file upload data). Modifying cef_post_data_t objects with excluded /// elements may result in the request failing. /// - int(CEF_CALLBACK *has_excluded_elements)(struct _cef_post_data_t *self); + int(CEF_CALLBACK* has_excluded_elements)(struct _cef_post_data_t* self); /// /// Returns the number of existing post data elements. /// - size_t(CEF_CALLBACK *get_element_count)(struct _cef_post_data_t *self); + size_t(CEF_CALLBACK* get_element_count)(struct _cef_post_data_t* self); /// /// Retrieve the post data elements. /// - void(CEF_CALLBACK *get_elements)(struct _cef_post_data_t *self, - size_t *elementsCount, - struct _cef_post_data_element_t **elements); + void(CEF_CALLBACK* get_elements)(struct _cef_post_data_t* self, + size_t* elementsCount, + struct _cef_post_data_element_t** elements); /// /// Remove the specified post data element. Returns true (1) if the removal /// succeeds. /// - int(CEF_CALLBACK *remove_element)(struct _cef_post_data_t *self, - struct _cef_post_data_element_t *element); + int(CEF_CALLBACK* remove_element)(struct _cef_post_data_t* self, + struct _cef_post_data_element_t* element); /// /// Add the specified post data element. Returns true (1) if the add /// succeeds. /// - int(CEF_CALLBACK *add_element)(struct _cef_post_data_t *self, - struct _cef_post_data_element_t *element); + int(CEF_CALLBACK* add_element)(struct _cef_post_data_t* self, + struct _cef_post_data_element_t* element); /// /// Remove all existing post data elements. /// - void(CEF_CALLBACK *remove_elements)(struct _cef_post_data_t *self); + void(CEF_CALLBACK* remove_elements)(struct _cef_post_data_t* self); } cef_post_data_t; /// /// Create a new cef_post_data_t object. /// -CEF_EXPORT cef_post_data_t *cef_post_data_create(void); +CEF_EXPORT cef_post_data_t* cef_post_data_create(void); /// /// Structure used to represent a single element in the request post data. The @@ -420,59 +425,61 @@ typedef struct _cef_post_data_element_t { /// /// Returns true (1) if this object is read-only. /// - int(CEF_CALLBACK *is_read_only)(struct _cef_post_data_element_t *self); + int(CEF_CALLBACK* is_read_only)(struct _cef_post_data_element_t* self); /// /// Remove all contents from the post data element. /// - void(CEF_CALLBACK *set_to_empty)(struct _cef_post_data_element_t *self); + void(CEF_CALLBACK* set_to_empty)(struct _cef_post_data_element_t* self); /// /// The post data element will represent a file. /// - void(CEF_CALLBACK *set_to_file)(struct _cef_post_data_element_t *self, - const cef_string_t *fileName); + void(CEF_CALLBACK* set_to_file)(struct _cef_post_data_element_t* self, + const cef_string_t* fileName); /// /// The post data element will represent bytes. The bytes passed in will be /// copied. /// - void(CEF_CALLBACK *set_to_bytes)(struct _cef_post_data_element_t *self, - size_t size, const void *bytes); + void(CEF_CALLBACK* set_to_bytes)(struct _cef_post_data_element_t* self, + size_t size, + const void* bytes); /// /// Return the type of this post data element. /// - cef_postdataelement_type_t(CEF_CALLBACK *get_type)( - struct _cef_post_data_element_t *self); + cef_postdataelement_type_t(CEF_CALLBACK* get_type)( + struct _cef_post_data_element_t* self); /// /// Return the file name. /// // The resulting string must be freed by calling cef_string_userfree_free(). - cef_string_userfree_t(CEF_CALLBACK *get_file)( - struct _cef_post_data_element_t *self); + cef_string_userfree_t(CEF_CALLBACK* get_file)( + struct _cef_post_data_element_t* self); /// /// Return the number of bytes. /// - size_t(CEF_CALLBACK *get_bytes_count)(struct _cef_post_data_element_t *self); + size_t(CEF_CALLBACK* get_bytes_count)(struct _cef_post_data_element_t* self); /// /// Read up to |size| bytes into |bytes| and return the number of bytes /// actually read. /// - size_t(CEF_CALLBACK *get_bytes)(struct _cef_post_data_element_t *self, - size_t size, void *bytes); + size_t(CEF_CALLBACK* get_bytes)(struct _cef_post_data_element_t* self, + size_t size, + void* bytes); } cef_post_data_element_t; /// /// Create a new cef_post_data_element_t object. /// -CEF_EXPORT cef_post_data_element_t *cef_post_data_element_create(void); +CEF_EXPORT cef_post_data_element_t* cef_post_data_element_create(void); #ifdef __cplusplus } #endif -#endif // CEF_INCLUDE_CAPI_CEF_REQUEST_CAPI_H_ +#endif // CEF_INCLUDE_CAPI_CEF_REQUEST_CAPI_H_ diff --git a/include/capi/cef_request_handler_capi.h b/include/capi/cef_request_handler_capi.h index b62892003..32c329b93 100644 --- a/include/capi/cef_request_handler_capi.h +++ b/include/capi/cef_request_handler_capi.h @@ -33,7 +33,7 @@ // by hand. See the translator.README.txt file in the tools directory for // more information. // -// $hash=b94100cfe1feea0a2b66e806163f1d5081299d1c$ +// $hash=c28fc87fe1ab76d594610e0171fbced678728165$ // #ifndef CEF_INCLUDE_CAPI_CEF_REQUEST_HANDLER_CAPI_H_ @@ -272,6 +272,13 @@ typedef struct _cef_request_handler_t { void(CEF_CALLBACK* on_render_process_responding)( struct _cef_request_handler_t* self, struct _cef_browser_t* browser); + + /// + /// Called when mouse hovering the link + /// + void(CEF_CALLBACK* on_update_target_url)(struct _cef_request_handler_t* self, + struct _cef_browser_t* browser, + const cef_string_t* url); } cef_request_handler_t; #ifdef __cplusplus diff --git a/include/capi/cef_web_extension_api_handler_capi.h b/include/capi/cef_web_extension_api_handler_capi.h new file mode 100644 index 000000000..621740cd3 --- /dev/null +++ b/include/capi/cef_web_extension_api_handler_capi.h @@ -0,0 +1,73 @@ +// Copyright (c) 2024 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// +// $hash=790c9adad66b57add27f42b4ce0bdc6a0115c384$ +// + +#ifndef CEF_INCLUDE_CAPI_CEF_WEB_EXTENSION_API_HANDLER_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_WEB_EXTENSION_API_HANDLER_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/// +/// Implement this structure to handle webextension's api events. The functions +/// of +/// this class will be called on the UI thread. +/// +typedef struct _cef_web_extension_api_handler_t { + /// + /// Base structure. + /// + cef_base_ref_counted_t base; + + /// + /// Called when chrome.tabs.update. + /// + void(CEF_CALLBACK* on_tab_update_url)( + struct _cef_web_extension_api_handler_t* self, + int tab_id, + const cef_string_t* url); +} cef_web_extension_api_handler_t; + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_WEB_EXTENSION_API_HANDLER_CAPI_H_ diff --git a/include/cef_api_hash.h b/include/cef_api_hash.h index 278d18f5b..757356099 100644 --- a/include/cef_api_hash.h +++ b/include/cef_api_hash.h @@ -42,15 +42,15 @@ // way that may cause binary incompatibility with other builds. The universal // hash value will change if any platform is affected whereas the platform hash // values will change only if that particular platform is affected. -#define CEF_API_HASH_UNIVERSAL "e3aadab4a80bd6529a80633ed156f63a14fc5c23" +#define CEF_API_HASH_UNIVERSAL "4850ab65e441835dfe63926709ee8b6b50b8238f" #if defined(OS_WIN) -#define CEF_API_HASH_PLATFORM "a73f1dc906b69b0d3c94de68d5b67aaae5cd9621" +#define CEF_API_HASH_PLATFORM "8eebd51af2dbc28fc70f5d36adbe7a8221aa27b6" #elif defined(OS_MAC) -#define CEF_API_HASH_PLATFORM "c0609907fd324fc678945449b70011b8f8fee3b0" +#define CEF_API_HASH_PLATFORM "7e15ca6b76032fdd5a7d5a1eb35ddbe7e36436ba" #elif defined(OS_LINUX) -#define CEF_API_HASH_PLATFORM "12803848bab219b8091b50116663c6560cc26c89" +#define CEF_API_HASH_PLATFORM "f9f71c232b46380f9fb0c8b27640e25819d8f945" #elif defined(OS_OHOS) -#define CEF_API_HASH_PLATFORM "12803848bab219b8091b50116663c6560cc26c89" +#define CEF_API_HASH_PLATFORM "f9f71c232b46380f9fb0c8b27640e25819d8f945" #endif #ifdef __cplusplus diff --git a/include/cef_browser.h b/include/cef_browser.h index 19e4c2b84..57f27c8a5 100644 --- a/include/cef_browser.h +++ b/include/cef_browser.h @@ -39,6 +39,9 @@ #pragma once #include +#include +#include + #include "include/cef_base.h" #include "include/cef_devtools_message_observer.h" #include "include/cef_drag_data.h" @@ -117,6 +120,25 @@ class CefWebMessageReceiver : public virtual CefBaseRefCounted { /// /*--cef()--*/ virtual void OnMessage(CefRefPtr message) = 0; + + /// + /// The same as OnMessage, the result of the execution will be returned. + /// + /*--cef()--*/ + virtual bool OnMessageWithBoolResult(CefRefPtr message) = 0; +}; + +/// +/// CefSetLockCallback. +/// +/*--cef(source=client)--*/ +class CefSetLockCallback : public virtual CefBaseRefCounted { + public: + /// + /// Handle. + /// + /*--cef()--*/ + virtual void Handle(bool key) = 0; }; /// @@ -145,20 +167,6 @@ class CefCacheOptions : public virtual CefBaseRefCounted { /*--cef(default_retval=nullptr)--*/ virtual cef_string_map_t GetResponseHeaders() = 0; }; - -/// -/// CefSetLockCallback -/// -/*--cef(source=client)--*/ -class CefSetLockCallback : public virtual CefBaseRefCounted { - public: - /// - /// Handle. - /// - /*--cef()--*/ - virtual void Handle(bool key) = 0; -}; - /* ---------- ohos webview add end --------- */ #endif // BUILDFLAG(IS_OHOS) @@ -343,13 +351,13 @@ class CefBrowser : public virtual CefBaseRefCounted { /// display the selection control when click Free copy interface /// /*--cef()--*/ - virtual void SelectAndCopy() = 0; + virtual void ShowFreeCopyMenu() = 0; /// /// should show free copy menu /// /*--cef()--*/ - virtual bool ShouldShowFreeCopy() = 0; + virtual bool ShouldShowFreeCopyMenu() = 0; /// /// select password dialog to fill @@ -422,11 +430,22 @@ class CefBrowser : public virtual CefBaseRefCounted { virtual int GetNWebId() = 0; /// - /// Set whether the target_blank pop-up window is opened in the current tab. + /// Get whether Ads block is enabled. /// /*--cef()--*/ - virtual void SetEnableBlankTargetPopupIntercept( - bool enableBlankTargetPopup) = 0; + virtual bool IsAdsBlockEnabled() = 0; + + /// + /// Get whether Ads block is enabled for current page. + /// + /*--cef()--*/ + virtual bool IsAdsBlockEnabledForCurPage() = 0; + + /// + /// Set enable to allow automatically save password + /// + /*--cef()--*/ + virtual void EnableAdsBlock(bool enable) = 0; /// /// Whether automatically saving password had been enabled. @@ -458,12 +477,6 @@ class CefBrowser : public virtual CefBaseRefCounted { /*--cef()--*/ virtual void SetSavePassword(bool enable) = 0; - /// - /// Get security level for current page. - /// - /*--cef()--*/ - virtual int GetSecurityLevel() = 0; - /// /// Enable the ability to check website security risks. /// @@ -477,34 +490,40 @@ class CefBrowser : public virtual CefBaseRefCounted { virtual bool IsSafeBrowsingEnabled() = 0; /// - /// Enable the ability to intelligent tracking prevention, default disabled. + /// Get security level for current page. /// /*--cef()--*/ - virtual void EnableIntelligentTrackingPrevention(bool enable) = 0; + virtual int GetSecurityLevel() = 0; /// - /// Get whether intelligent tracking prevention is enabled. + /// Get the shrink viewport height. /// /*--cef()--*/ - virtual bool IsIntelligentTrackingPreventionEnabled() = 0; + virtual int InsertBackForwardEntry(int index, const CefString& url) = 0; /// - /// Get whether Ads block is enabled. + /// Get the shrink viewport height. /// /*--cef()--*/ - virtual bool IsAdsBlockEnabled() = 0; + virtual int UpdateNavigationEntryUrl(int index, const CefString& url) = 0; /// - /// Get whether Ads block is enabled for current page. + /// Get the shrink viewport height. /// /*--cef()--*/ - virtual bool IsAdsBlockEnabledForCurPage() = 0; + virtual void ClearForwardList() = 0; /// - /// Set enable to allow automatically save password + /// Enable the ability to intelligent tracking prevention, default disabled. /// /*--cef()--*/ - virtual void EnableAdsBlock(bool enable) = 0; + virtual void EnableIntelligentTrackingPrevention(bool enable) = 0; + + /// + /// Get whether intelligent tracking prevention is enabled. + /// + /*--cef()--*/ + virtual bool IsIntelligentTrackingPreventionEnabled() = 0; /// /// Set url trust list. @@ -514,7 +533,19 @@ class CefBrowser : public virtual CefBaseRefCounted { const CefString& urlTrustList, CefString& detailErrMsg) = 0; /// - /// Set url trust list. + /// Set tabId. + /// + /*--cef()--*/ + virtual void SetTabId(int tab_id) = 0; + + /// + /// Get tabId. + /// + /*--cef()--*/ + virtual int GetTabId() = 0; + + /// + /// Set back forward cache options. /// /*--cef()--*/ virtual void SetBackForwardCacheOptions(int32_t size, int32_t timeToLive) = 0; @@ -1316,7 +1347,6 @@ class CefBrowserHost : public virtual CefBaseRefCounted { const std::string& code, CefRefPtr callback, bool extention) = 0; - /// /// Execute a string of JavaScript code, return result by callback /// @@ -1349,13 +1379,13 @@ class CefBrowserHost : public virtual CefBaseRefCounted { /// GetImageForContextNode /// /*--cef()--*/ - virtual void GetImageForContextNode() = 0; + virtual void GetImageForContextNode(int command_id) = 0; /// /// GetImageFromCache /// /*--cef()--*/ - virtual void GetImageFromCache(const CefString& url) = 0; + virtual void GetImageFromCache(const CefString& url, int command_id) = 0; /// /// ExitFullScreen @@ -1524,7 +1554,7 @@ class CefBrowserHost : public virtual CefBaseRefCounted { /// Post a message to the port. /// /*--cef()--*/ - virtual void PostPortMessage(CefString& port_handle, + virtual void PostPortMessage(const CefString& port_handle, CefRefPtr message) = 0; /// @@ -1532,7 +1562,7 @@ class CefBrowserHost : public virtual CefBaseRefCounted { /// /*--cef()--*/ virtual void SetPortMessageCallback( - CefString& port_handle, + const CefString& port_handle, CefRefPtr callback) = 0; /// @@ -1794,6 +1824,14 @@ class CefBrowserHost : public virtual CefBaseRefCounted { virtual void SetOverscrollMode(int mode) = 0; + /// + /// Change the zoom factor for browser zoom. + /// If called on the UI thread the change will be applied immediately. + /// Otherwise, the change will be applied asynchronously on the UI thread. + /// + /*--cef()--*/ + virtual void SetBrowserZoomLevel(double zoomFactor) = 0; + /// /// Discard a webview window /// @@ -1807,24 +1845,34 @@ class CefBrowserHost : public virtual CefBaseRefCounted { virtual bool Restore() = 0; /// - /// Change the zoom factor for browser zoom. - /// If called on the UI thread the change will be applied immediately. - /// Otherwise, the change will be applied asynchronously on the UI thread. + /// Get the top controls offset. /// /*--cef()--*/ - virtual void SetBrowserZoomLevel(double zoomFactor) = 0; + virtual int GetTopControlsOffset() = 0; /// - /// Get the top controls offset. + /// Get the shrink viewport height. /// /*--cef()--*/ - virtual int GetTopControlsOffset() = 0; + virtual int GetShrinkViewportHeight() = 0; /// /// Get the shrink viewport height. /// /*--cef()--*/ - virtual int GetShrinkViewportHeight() = 0; + virtual int InsertBackForwardEntry(int index, const CefString& url) = 0; + + /// + /// Get the shrink viewport height. + /// + /*--cef()--*/ + virtual int UpdateNavigationEntryUrl(int index, const CefString& url) = 0; + + /// + /// Get the shrink viewport height. + /// + /*--cef()--*/ + virtual void ClearForwardList() = 0; /// /// Set background print enable. @@ -1845,7 +1893,13 @@ class CefBrowserHost : public virtual CefBaseRefCounted { virtual void SetScrollable(bool enable, int scrollType) = 0; /// - /// Start current camera. + /// Get the last javascript proxy calling frame url. + /// + /*--cef()--*/ + virtual CefString GetLastJavascriptProxyCallingFrameUrl() = 0; + + /// + /// Start current camera. /// /*--cef()--*/ virtual void StartCamera() = 0; @@ -1862,12 +1916,6 @@ class CefBrowserHost : public virtual CefBaseRefCounted { /*--cef()--*/ virtual void CloseCamera() = 0; - /// - /// Get the last javascript proxy calling frame url. - /// - /*--cef()--*/ - virtual CefString GetLastJavascriptProxyCallingFrameUrl() = 0; - /// /// Set NWebID. /// @@ -1881,14 +1929,10 @@ class CefBrowserHost : public virtual CefBaseRefCounted { virtual bool GetPendingSizeStatus() = 0; /// - /// precompile javascript and generate code cache. + /// Get CefDownloadItem by download_item_id. /// /*--cef()--*/ - virtual void PrecompileJavaScript( - const std::string& url, - const std::string& script, - CefRefPtr cacheOptions, - CefRefPtr callback) = 0; + virtual CefRefPtr GetDownloadItem(uint32 item_id) = 0; /// /// SetWakeLockHandler. @@ -1897,38 +1941,32 @@ class CefBrowserHost : public virtual CefBaseRefCounted { virtual void SetWakeLockHandler(int32_t windowId, CefRefPtr callback) = 0; /// - /// Get CefDownloadItem by download_item_id. + /// Notify browser host needs reoload when the render process terminated. /// /*--cef()--*/ - virtual CefRefPtr GetDownloadItem(uint32 item_id) = 0; + virtual void SetNeedsReload(bool needs_reload) = 0; /// - /// Notify browser host needs reload when the render process terminated. - /// - /*--cef()--*/ - virtual void NotifyNeedsReload(bool needs_reload) = 0; - - /// - /// Return true if needs reload page, or false if nees not reload. + /// Return true if needs reload page, or false if needs not reload. /// /*--cef()--*/ virtual bool NeedsReload() = 0; /// - /// Terminate render process + /// precompile javascript and generate code cache. /// /*--cef()--*/ - virtual bool TerminateRenderProcess() = 0; + virtual void PrecompileJavaScript( + const std::string& url, + const std::string& script, + CefRefPtr cacheOptions, + CefRefPtr callback) = 0; /// - /// RegisterNativeJSProxy + /// update DrawRect. /// /*--cef()--*/ - virtual void RegisterNativeJSProxy(const CefString& object_name, - const std::vector& method_list, - const int32_t object_id, - bool is_async, - const CefString& permission) = 0; + virtual void UpdateDrawRect() = 0; /// /// SendTouchpadFlingEvent @@ -1943,10 +1981,20 @@ class CefBrowserHost : public virtual CefBaseRefCounted { virtual void SetFitContentMode(int mode) = 0; /// - /// update draw_rect state. + /// Terminate render process /// /*--cef()--*/ - virtual void UpdateDrawRect() = 0; + virtual bool TerminateRenderProcess() = 0; + + /// + /// RegisterNativeJSProxy + /// + /*--cef()--*/ + virtual void RegisterNativeJSProxy(const CefString& object_name, + const std::vector& method_list, + const int32_t object_id, + bool is_async, + const CefString& permission) = 0; /// /// Called when text is selected. @@ -1974,6 +2022,12 @@ class CefBrowserHost : public virtual CefBaseRefCounted { /// /*--cef()--*/ virtual void AdvanceFocusForIME(int focusType) = 0; + + /// + /// Called when image analyzer overlay is destoryed. + /// + /*--cef()--*/ + virtual void OnDestroyImageAnalyzerOverlay() = 0; #endif // BUILDFLAG(IS_OHOS) /// @@ -1994,23 +2048,34 @@ class CefBrowserHost : public virtual CefBaseRefCounted { /*--cef()--*/ virtual void SetGrantFileAccessDirs(const std::vector& dir_list) = 0; +#if defined(OHOS_ARKWEB_EXTENSIONS) /// - /// Set the callback of the autofill event. + /// Receiving the tab updated notification. /// /*--cef()--*/ - virtual void SetAutofillCallback(CefRefPtr callback) = 0; + virtual void WebExtensionTabUpdated( + int tab_id, + const std::vector& changed_property_names, + const CefString& url) = 0; +#endif /// - /// Fill autofill data. + /// ScrollFocusedEditableNodeIntoView. /// /*--cef()--*/ - virtual void FillAutofillData(CefRefPtr message) = 0; + virtual void ScrollFocusedEditableNodeIntoView() = 0; /// - /// ScrollFocusedEditableNodeIntoView. + /// Set the callback of the autofill event. /// /*--cef()--*/ - virtual void ScrollFocusedEditableNodeIntoView() = 0; + virtual void SetAutofillCallback(CefRefPtr callback) = 0; + + /// + /// Fill autofill data. + /// + /*--cef()--*/ + virtual void FillAutofillData(CefRefPtr message) = 0; /// /// Process autofill cancel content. diff --git a/include/cef_client.h b/include/cef_client.h index e6905e71b..c29044f64 100644 --- a/include/cef_client.h +++ b/include/cef_client.h @@ -59,6 +59,7 @@ #include "include/cef_process_message.h" #include "include/cef_render_handler.h" #include "include/cef_request_handler.h" +#include "include/cef_web_extension_api_handler.h" #if BUILDFLAG(IS_OHOS) #include "include/cef_media_handler.h" @@ -316,6 +317,17 @@ class CefClient : public virtual CefBaseRefCounted { CefOwnPtr listener, const CefCustomMediaInfo& media_info) { return nullptr; } #endif // OHOS_CUSTOM_VIDEO_PLAYER + +#if defined(OHOS_ARKWEB_EXTENSIONS) + /// + /// Return the handler for web extension api. If no handler is provided the + /// default implementation will be used. + /// + /*--cef()--*/ + virtual CefRefPtr GetWebExtensionApiHandler() { + return nullptr; + } +#endif }; #endif // CEF_INCLUDE_CEF_CLIENT_H_ diff --git a/include/cef_context_menu_handler.h b/include/cef_context_menu_handler.h index 50e0254c3..e88dded8b 100644 --- a/include/cef_context_menu_handler.h +++ b/include/cef_context_menu_handler.h @@ -176,7 +176,7 @@ class CefContextMenuHandler : public virtual CefBaseRefCounted { } /// - /// UpdateClippedSelectionBounds. + /// UpdateClippedSelectionBounds /// /*--cef()--*/ virtual bool UpdateClippedSelectionBounds(CefRefPtr browser, @@ -215,14 +215,14 @@ class CefContextMenuHandler : public virtual CefBaseRefCounted { /// /*--cef()--*/ virtual void OnGetImageForContextNode(CefRefPtr browser, - CefRefPtr image) {} + CefRefPtr image, int command_id) {} /// /// Called when GetImageFromCache function to get image from /// memory cache. /// /*--cef()--*/ - virtual void OnGetImageFromCache(CefRefPtr image) {} + virtual void OnGetImageFromCache(CefRefPtr image, int command_id) {} /// /// Called when you need to temporarily hide/restore the handle menu. diff --git a/include/cef_cookie.h b/include/cef_cookie.h index ee6b4d85e..5b13e3615 100644 --- a/include/cef_cookie.h +++ b/include/cef_cookie.h @@ -97,7 +97,8 @@ class CefCookieManager : public virtual CefBaseRefCounted { virtual bool VisitUrlCookies(const CefString& url, bool includeHttpOnly, CefRefPtr visitor, - bool is_sync) = 0; + bool is_sync, + bool is_from_ndk) = 0; /// /// Sets a cookie given a valid URL and explicit user-provided cookie @@ -113,7 +114,8 @@ class CefCookieManager : public virtual CefBaseRefCounted { const CefCookie& cookie, CefRefPtr callback, bool is_sync, - const CefString& str_cookie) = 0; + const CefString& str_cookie, + bool includeHttpOnly) = 0; /// /// Delete all cookies that match the specified parameters. If both |url| and diff --git a/include/cef_first_meaningful_paint_details.h b/include/cef_first_meaningful_paint_details.h index b92e162f5..b0a11e6ae 100644 --- a/include/cef_first_meaningful_paint_details.h +++ b/include/cef_first_meaningful_paint_details.h @@ -59,4 +59,4 @@ class CefFirstMeaningfulPaintDetails : public virtual CefBaseRefCounted { virtual int64_t GetFirstMeaningfulPaintTime() = 0; }; -#endif //CEF_INCLUDE_CEF_FIRST_MEANINGFUL_PAINT_DETAILS_H +#endif //CEF_INCLUDE_CEF_FIRST_MEANINGFUL_PAINT_DETAILS_H \ No newline at end of file diff --git a/include/cef_keyboard_handler.h b/include/cef_keyboard_handler.h index 33f8ba5bd..469cdeae0 100644 --- a/include/cef_keyboard_handler.h +++ b/include/cef_keyboard_handler.h @@ -75,6 +75,7 @@ class CefKeyboardHandler : public virtual CefBaseRefCounted { CefEventHandle os_event) { return false; } + #if defined(OHOS_INPUT_EVENTS) /// /// This interface is invoked to notify the upper-layer application whether the key is used diff --git a/include/cef_load_handler.h b/include/cef_load_handler.h index 04c55cd7a..6bfaa8e44 100644 --- a/include/cef_load_handler.h +++ b/include/cef_load_handler.h @@ -174,6 +174,12 @@ class CefLoadHandler : public virtual CefBaseRefCounted { virtual void OnFirstContentfulPaint(int64_t navigationStartTick, int64_t firstContentfulPaintMs) {} + /// + /// Called when received website security risk check result. + /// + /*--cef()--*/ + virtual void OnSafeBrowsingCheckResult(int threat_type) {} + /// /// Called when the first meaningful paint rendering of web page. /// @@ -195,13 +201,6 @@ class CefLoadHandler : public virtual CefBaseRefCounted { virtual void OnNavigationEntryCommitted( CefRefPtr details) {} - - /// - /// Called when received website security risk check result. - /// - /*--cef()--*/ - virtual void OnSafeBrowsingCheckResult(int threat_type) {} - /// /// Called when tracker's cookie is prevented. /// @@ -210,6 +209,14 @@ class CefLoadHandler : public virtual CefBaseRefCounted { const CefString& website_host, const CefString& tracker_host) {} +#ifdef OHOS_BFCACHE + /// + /// Called when page load from bfcache. + /// + /*--cef()--*/ + virtual void UpdateFavicon(CefRefPtr browser) {} +#endif // OHOS_BFCACHE + #endif // BUILDFLAG(IS_OHOS) }; diff --git a/include/cef_permission_request.h b/include/cef_permission_request.h index 5f79ee4ca..e44ecd8a7 100644 --- a/include/cef_permission_request.h +++ b/include/cef_permission_request.h @@ -183,6 +183,42 @@ class CefBrowserPermissionRequestDelegate : public virtual CefBaseRefCounted { /*--cef()--*/ virtual void NotifyGeolocationPermission(bool value, const CefString& origin) = 0; + + /// + /// Handle the Audio Capture permission requests. + /// + /*--cef()--*/ + virtual void AskAudioCapturePermission(const CefString& origin, + cef_permission_callback_t callback) = 0; + /// + /// Cancel the Audio Capturepermission requests. + /// + /*--cef()--*/ + virtual void AbortAskAudioCapturePermission(const CefString& origin) = 0; + + /// + /// Handle the Video Capture permission requests. + /// + /*--cef()--*/ + virtual void AskVideoCapturePermission(const CefString& origin, + cef_permission_callback_t callback) = 0; + /// + /// Cancel the Video Capturepermission requests. + /// + /*--cef()--*/ + virtual void AbortAskVideoCapturePermission(const CefString& origin) = 0; + + /// + /// Handle the Clipboard Sanitized permission requests. + /// + /*--cef()--*/ + virtual void AskClipboardSanitizedWritePermission(const CefString& origin, + cef_permission_callback_t callback) = 0; + /// + /// Cancel the Clipboard Read Sanitezed permission requests. + /// + /*--cef()--*/ + virtual void AbortAskClipboardSanitizedWritePermission(const CefString& origin) = 0; }; /// diff --git a/include/cef_render_handler.h b/include/cef_render_handler.h index c8d930533..cec3c99df 100644 --- a/include/cef_render_handler.h +++ b/include/cef_render_handler.h @@ -374,13 +374,13 @@ class CefRenderHandler : public virtual CefBaseRefCounted { /*--cef()--*/ virtual void OnNativeEmbedLifecycleChange(CefRefPtr browser, const CefNativeEmbedData& info) {} - + /// - /// Called when embed visibility. + /// Called when embed visible. /// /*--cef()--*/ virtual void OnNativeEmbedVisibilityChange(const std::string& embed_id, - bool visibility) {} + bool visibility) {} /// /// Called when select all is clicked. @@ -393,16 +393,7 @@ class CefRenderHandler : public virtual CefBaseRefCounted { /// /*--cef()--*/ virtual void ReleaseResizeHold(CefRefPtr browser) {} - - /// - /// Called when text input state has changed for the specified |browser|. - /// - /*--cef()--*/ - virtual void OnUpdateTextInputStateCalled(CefRefPtr browser, - const CefString& text, - const CefRange& selected_range, - const CefRange& compositon_range) {} - + /// /// Called when selecting word. /// @@ -411,7 +402,7 @@ class CefRenderHandler : public virtual CefBaseRefCounted { const CefString& text, int8_t offset, CefPoint& select) {} - + /// /// Called when creating overlay. /// @@ -421,7 +412,7 @@ class CefRenderHandler : public virtual CefBaseRefCounted { const CefRect& cef_image_rect, const CefPoint& cef_touch_point, const CefRect& cef_screen_rect) {} - + /// /// Called when overlay state is changed. /// @@ -430,20 +421,21 @@ class CefRenderHandler : public virtual CefBaseRefCounted { const CefRect& cef_screen_rect) {} /// - /// Called to retrieve the visible view rectangle in screen DIP coordinates. This - /// method must always provide a non-empty rectangle. + /// Called when text input state has changed for the specified |browser|. /// /*--cef()--*/ - virtual void GetVisibleViewportRect(CefRefPtr browser, - CefRect& rect) {} + virtual void OnUpdateTextInputStateCalled(CefRefPtr browser, + const CefString& text, + const CefRange& selected_range, + const CefRange& compositon_range) {} /// - /// SendDynamicFrameLossEvent + /// Called to retrieve the view rectangle in screen DIP coordinates. This + /// method must always provide a non-empty rectangle. /// /*--cef()--*/ - virtual void SendDynamicFrameLossEvent(CefRefPtr browser, - const CefString& sceneId, - bool isStart) {} + virtual void GetVisibleViewportRect(CefRefPtr browser, + CefRect& rect) {} /// /// OnResizeScrollableViewport. @@ -456,6 +448,12 @@ class CefRenderHandler : public virtual CefBaseRefCounted { /// /*--cef()--*/ virtual void SetFillContent(const std::string& content) {} + + /// + /// SetGestureEventResult + /// + /*--cef()--*/ + virtual void SetGestureEventResult(const bool result) {} #endif // BUILDFLAG(IS_OHOS) }; diff --git a/include/cef_request_handler.h b/include/cef_request_handler.h index e7bb2cb75..f94e279e2 100644 --- a/include/cef_request_handler.h +++ b/include/cef_request_handler.h @@ -286,16 +286,16 @@ class CefRequestHandler : public virtual CefBaseRefCounted { virtual bool OnOpenAppLink(const CefString &url, CefRefPtr callback) { return false; - } + } /// /// Called when render process not responding /// /*--cef()--*/ virtual void OnRenderProcessNotResponding(CefRefPtr browser, - const CefString& referrer, - int pid, - int reason) {} + const CefString& referrer, + int pid, + int reason) {} /// /// Called when render process responding again @@ -303,6 +303,11 @@ class CefRequestHandler : public virtual CefBaseRefCounted { /*--cef()--*/ virtual void OnRenderProcessResponding(CefRefPtr browser) {} + /// + /// Called when mouse hovering the link + /// + /*--cef()--*/ + virtual void OnUpdateTargetURL(CefRefPtr browser, const CefString& url) {} }; #endif // CEF_INCLUDE_CEF_REQUEST_HANDLER_H_ diff --git a/include/cef_resource_request_handler.h b/include/cef_resource_request_handler.h index 01d667815..dd97a0ff7 100644 --- a/include/cef_resource_request_handler.h +++ b/include/cef_resource_request_handler.h @@ -47,8 +47,23 @@ #include "include/cef_response.h" #include "include/cef_response_filter.h" +#include "include/cef_scheme.h" + class CefCookieAccessFilter; +/// +/// CefInterceptCallback +/// +/*--cef(source=library)--*/ +class CefInterceptCallback : public virtual CefBaseRefCounted { + public: + /// + /// Continue. + /// + /*--cef(capi_name=cont)--*/ + virtual void ContinueLoad(CefRefPtr resource_handler) {} +}; + /// /// Implement this interface to handle events related to browser requests. The /// methods of this class will be called on the IO thread unless otherwise @@ -195,7 +210,7 @@ class CefResourceRequestHandler : public virtual CefBaseRefCounted { /// of the request, and may be NULL for requests originating from service /// workers or CefURLRequest. |request| cannot be modified in this callback. /// Set |allow_os_execution| to true to attempt execution via the registered - /// OS protocol handler, if any. SECURITY WARNING: YOU SHOULD USE THIS METHOD + /// OS protocol handler, if any. SECURITY WARNING: YOU SHOULD USE THIS MET /// TO ENFORCE RESTRICTIONS BASED ON SCHEME, HOST OR OTHER URL ANALYSIS BEFORE /// ALLOWING OS EXECUTION. /// @@ -204,6 +219,18 @@ class CefResourceRequestHandler : public virtual CefBaseRefCounted { CefRefPtr frame, CefRefPtr request, bool& allow_os_execution) {} + + /// + /// GetResourceHandlerByIO. + /// + /*--cef(optional_param=browser,optional_param=frame)--*/ + virtual void GetResourceHandlerByIO( + CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request, + CefRefPtr callback, + CefRefPtr scheme_factory, + const CefString& scheme) {} }; /// diff --git a/include/cef_values.h b/include/cef_values.h index 913f361a6..006528ee4 100644 --- a/include/cef_values.h +++ b/include/cef_values.h @@ -204,7 +204,6 @@ class CefValue : public virtual CefBaseRefCounted { /*--cef(optional_param=value)--*/ virtual bool SetString(const CefString& value) = 0; virtual bool SetStdString(const std::string& value) = 0; - /// /// Sets the underlying value as type binary. Returns true if the value was /// set successfully. This object keeps a reference to |value| and ownership diff --git a/include/cef_web_extension_api_handler.h b/include/cef_web_extension_api_handler.h new file mode 100644 index 000000000..d87223ab5 --- /dev/null +++ b/include/cef_web_extension_api_handler.h @@ -0,0 +1,58 @@ +// Copyright (c) 2012 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_WEB_EXTENSION_API_HANDLER_H_ +#define CEF_INCLUDE_CEF_WEB_EXTENSION_API_HANDLER_H_ +#pragma once + +#include "include/cef_base.h" + +/// +/// Implement this interface to handle webextension's api events. The methods of +/// this class will be called on the UI thread. +/// +/*--cef(source=client)--*/ +class CefWebExtensionApiHandler : public virtual CefBaseRefCounted { + public: + + /// + /// Called when chrome.tabs.update. + /// + /*--cef()--*/ + virtual void OnUpdateTabUrl(int tab_id, const CefString& url) {} +}; + +#endif // CEF_INCLUDE_CEF_WEB_EXTENSION_API_HANDLER_H_ diff --git a/include/internal/cef_types.h b/include/internal/cef_types.h index b6ef91895..ed6df0b96 100644 --- a/include/internal/cef_types.h +++ b/include/internal/cef_types.h @@ -526,6 +526,11 @@ typedef struct _cef_request_context_settings_t { #if defined(OHOS_INCOGNITO_MODE) bool incognito_mode; #endif + +#if defined(OHOS_ARKWEB_EXTENSIONS) + /// Only used by Extensions's background script initialization during startup. + void* global_request_context; +#endif } cef_request_context_settings_t; /// @@ -697,15 +702,15 @@ typedef struct _cef_browser_settings_t { cef_state_t hide_horizontal_scrollbars; bool contextmenu_customization_enabled; cef_color_t scrollbar_color; - bool blank_target_popup_intercept_enabled; + bool is_safe_browsing_enable; cef_state_t native_embed_mode_enabled; cef_string_t embed_tag; cef_string_t embed_tag_type; bool scroll_enabled; - bool is_safe_browsing_enable; int draw_mode; cef_state_t text_autosizing_enabled; cef_state_t universal_access_from_file_urls; + bool force_zero_layout_height; /* ohos webview end */ #endif // BUILDFLAG(IS_OHOS) @@ -727,17 +732,20 @@ typedef struct _cef_browser_settings_t { bool custom_video_player_enable; bool custom_video_player_overlay; #endif // OHOS_CUSTOM_VIDEO_PLAYER +#if defined(OHOS_MULTI_WINDOW) + bool supports_multiple_windows; +#endif // OHOS_MULTI_WINDOW #if defined(OHOS_SOFTWARE_COMPOSITOR) bool record_whole_document; #endif -#if defined(OHOS_MULTI_WINDOW) - bool supports_multiple_windows; -#endif // OHOS_MULTI_WINDOW #if defined(OHOS_RENDER_PROCESS_SHARE) cef_string_t shared_render_process_token; #endif +#ifdef OHOS_MEDIA_NETWORK_TRAFFIC_PROMPT + bool enable_media_network_traffic_prompt; +#endif // OHOS_MEDIA_NETWORK_TRAFFIC_PROMPT } cef_browser_settings_t; /// @@ -1863,6 +1871,11 @@ typedef enum { #if BUILDFLAG(IS_OHOS) MENU_ID_IMAGE_COPY = 221, #endif // BUILDFLAG(IS_OHOS) + +#if BUILDFLAG(IS_OHOS) + MENU_ID_IMAGE_SHARE = 222, + MENU_ID_FEED_SHARE = 223, +#endif MENU_ID_CUSTOM_LAST = 250, // All user-defined menu IDs should come between MENU_ID_USER_FIRST and diff --git a/include/internal/cef_types_wrappers.h b/include/internal/cef_types_wrappers.h index 6c990e387..e6e00102c 100644 --- a/include/internal/cef_types_wrappers.h +++ b/include/internal/cef_types_wrappers.h @@ -500,6 +500,10 @@ struct CefRequestContextSettingsTraits { #if defined(OHOS_INCOGNITO_MODE) target->incognito_mode = src->incognito_mode; #endif + +#if defined(OHOS_ARKWEB_EXTENSIONS) + target->global_request_context = src->global_request_context; +#endif } }; @@ -605,17 +609,15 @@ struct CefBrowserSettingsTraits { target->contextmenu_customization_enabled = src->contextmenu_customization_enabled; target->scrollbar_color = src->scrollbar_color; - target->blank_target_popup_intercept_enabled = - src->blank_target_popup_intercept_enabled; - target->native_embed_mode_enabled = - src->native_embed_mode_enabled; + target->is_safe_browsing_enable = src->is_safe_browsing_enable; + target->native_embed_mode_enabled = src->native_embed_mode_enabled; cef_string_set(src->embed_tag.str, src->embed_tag.length, &target->embed_tag, copy); cef_string_set(src->embed_tag.str, src->embed_tag.length, &target->embed_tag_type, copy); target->scroll_enabled = src->scroll_enabled; - target->is_safe_browsing_enable = src->is_safe_browsing_enable; target->draw_mode = src->draw_mode; + target->force_zero_layout_height = src->force_zero_layout_height; /* ohos webview end */ #endif // BUILDFLAG(IS_OHOS) @@ -626,15 +628,14 @@ struct CefBrowserSettingsTraits { target->custom_video_player_enable = src->custom_video_player_enable; target->custom_video_player_overlay = src->custom_video_player_overlay; #endif // OHOS_CUSTOM_VIDEO_PLAYER +#if defined(OHOS_MULTI_WINDOW) + target->supports_multiple_windows = src->supports_multiple_windows; +#endif // OHOS_MULTI_WINDOW #if defined(OHOS_SOFTWARE_COMPOSITOR) target->record_whole_document = src->record_whole_document; #endif -#if defined(OHOS_MULTI_WINDOW) - target->supports_multiple_windows = src->supports_multiple_windows; -#endif // OHOS_MULTI_WINDOW - #ifdef OHOS_NETWORK_LOAD target->universal_access_from_file_urls = src->universal_access_from_file_urls; #endif diff --git a/libcef/browser/alloy/alloy_browser_context.cc b/libcef/browser/alloy/alloy_browser_context.cc index 41eb2b17b..7240ae63e 100644 --- a/libcef/browser/alloy/alloy_browser_context.cc +++ b/libcef/browser/alloy/alloy_browser_context.cc @@ -72,6 +72,11 @@ #include "extensions/browser/browser_context_keyed_service_factories.h" #endif +#ifdef OHOS_EX_UA +#include "content/public/common/content_switches.h" +#include "ohos_nweb_ex/overrides/cef/libcef/browser/alloy/alloy_browser_ua_config.h" +#endif + using content::BrowserThread; // Creates and manages VisitedLinkEventListener objects for each @@ -210,7 +215,12 @@ void AlloyBrowserContext::Initialize() { #endif extension_system_ = static_cast( extensions::ExtensionSystem::Get(this)); - +#if defined(OHOS_ARKWEB_EXTENSIONS) + if (settings_.global_request_context) { + extension_system_->SetGlobalRequestContext( + static_cast(settings_.global_request_context)); + } +#endif extension_system_->InitForRegularProfile(true); // Make sure the ProcessManager is created so that it receives extension // load notifications. This is necessary for the proper initialization of @@ -241,6 +251,22 @@ void AlloyBrowserContext::Initialize() { ChromePluginServiceFilter::GetInstance()->RegisterProfile(this); media_device_id_salt_ = new MediaDeviceIDSalt(pref_service); + +#ifdef OHOS_EX_UA + if (base::CommandLine::ForCurrentProcess()->HasSwitch( + switches::kForBrowser)) { + nweb_ex::AlloyBrowserUAConfig::GetInstance()->Init(pref_service); + std::string path; + uint64_t version = 0; + (void)nweb_ex::AlloyBrowserUAConfig::GetInstance() + ->ReadCloudConfigInfoFromPrefs(path, version); + nweb_ex::AlloyBrowserUAConfig::GetInstance() + ->UpdateCloudUAConfigAfterBrowserContextInit(path, version); + } +#endif +#if defined(OHOS_CLOUD_CONTROL) + OnContextInitialized(); +#endif } void AlloyBrowserContext::Shutdown() { @@ -579,3 +605,17 @@ AlloyBrowserContext::GetExtensionSpecialStoragePolicy() { #endif } #endif + +#if defined(OHOS_CLOUD_CONTROL) +void AlloyBrowserContext::OnWebViewShow() { + ScheduleUpdateCloudControl(this); +} + +void AlloyBrowserContext::OnContextInitialized() { + ScheduleUpdateCloudControl(this); +} +#endif + +#if defined(OHOS_CLOUD_CONTROL) && !defined(OHOS_NWEB_EX) +void AlloyBrowserContext::ScheduleUpdateCloudControl(content::BrowserContext* context) {} +#endif diff --git a/libcef/browser/alloy/alloy_browser_context.h b/libcef/browser/alloy/alloy_browser_context.h index 5ce3aa295..882d394e1 100644 --- a/libcef/browser/alloy/alloy_browser_context.h +++ b/libcef/browser/alloy/alloy_browser_context.h @@ -134,9 +134,16 @@ class AlloyBrowserContext : public ChromeProfileAlloy, #if defined(OHOS_ARKWEB_EXTENSIONS) ExtensionSpecialStoragePolicy* GetExtensionSpecialStoragePolicy() override; #endif + +#if defined(OHOS_CLOUD_CONTROL) + void OnWebViewShow(); + void OnContextInitialized(); +#endif private: ~AlloyBrowserContext() override; - +#if defined(OHOS_CLOUD_CONTROL) + void ScheduleUpdateCloudControl(content::BrowserContext* context); +#endif std::unique_ptr pref_service_; std::unique_ptr pref_proxy_config_tracker_; diff --git a/libcef/browser/alloy/alloy_browser_host_impl.cc b/libcef/browser/alloy/alloy_browser_host_impl.cc index 253d15ee6..732f2b2a7 100644 --- a/libcef/browser/alloy/alloy_browser_host_impl.cc +++ b/libcef/browser/alloy/alloy_browser_host_impl.cc @@ -59,6 +59,7 @@ #include "base/ohos/ltpo/include/dynamic_frame_rate_decision.h" #include "base/ohos/sys_info_utils.h" #include "content/browser/gpu/gpu_process_host.h" +#include "content/public/common/content_switches.h" #include "libcef/browser/osr/render_widget_host_view_osr.h" #include "libcef/browser/osr/touch_selection_controller_client_osr.h" #include "libcef/browser/prefs/renderer_prefs.h" @@ -98,6 +99,8 @@ #include "libcef/browser/alloy/alloy_off_the_record_browser_context.h" #endif +#include "libcef/browser/safe_browsing/safe_browsing_tab_helper.h" + #if defined(OHOS_SECURE_JAVASCRIPT_PROXY) #include "libcef/browser/javascript/oh_javascript_injector.h" #endif @@ -713,7 +716,6 @@ void AlloyBrowserHostImpl::ScrollFocusedEditableNodeIntoView() { base::BindOnce(&AlloyBrowserHostImpl::ScrollFocusedEditableNodeIntoView, this)); return; } - if (platform_delegate_) { platform_delegate_->ScrollFocusedEditableNodeIntoView(); } @@ -855,7 +857,7 @@ void AlloyBrowserHostImpl::ReportRenderProcessStatus(bool is_web_hidden) { base::ProcessId process_id = render_process_host->GetProcess().Pid(); ResSchedClientAdapter::ReportRenderProcessStatus(status, process_id); TRACE_EVENT2("base", "ResSchedClientAdapter::ReportRenderProcessStatus", "status", static_cast(status), - "process_id", process_id); + "process_id", process_id); LOG(DEBUG) << "AlloyBrowserHostImpl::ReportRenderProcessStatus is_web_hidden: " << is_web_hidden << " process_id: " << process_id; } else { LOG(ERROR) << "AlloyBrowserHostImpl::ReportRenderProcessStatus render_view_host is null"; @@ -1564,6 +1566,21 @@ void AlloyBrowserHostImpl::UpdateTargetURL(content::WebContents* source, contents_delegate_->UpdateTargetURL(source, url); } +#if defined(OHOS_ARKWEB_EXTENSIONS) +void AlloyBrowserHostImpl::WebExtensionUpdateTabUrl( + int32_t tab_id, const GURL& url) { + contents_delegate_->WebExtensionUpdateTabUrl(tab_id, url); +} + +void AlloyBrowserHostImpl::SetTabId(int32_t tab_id) { + tab_id_ = tab_id; +} + +int32_t AlloyBrowserHostImpl::GetTabId() { + return tab_id_; +} +#endif + bool AlloyBrowserHostImpl::DidAddMessageToConsole( content::WebContents* source, blink::mojom::ConsoleMessageLevel level, @@ -1654,7 +1671,6 @@ bool AlloyBrowserHostImpl::WebHandleKeyboardEvent( ContentsZoomChange(zoom_in); return true; } - return false; } #endif @@ -1897,17 +1913,10 @@ void AlloyBrowserHostImpl::ExitPictureInPicture() { } bool AlloyBrowserHostImpl::IsBackForwardCacheSupported() { -#if BUILDFLAG(IS_OHOS) - // Turn this switch on and see if there's anything wrong, - // issue #3237 not reproduced, maybe had been fixed. #ifdef OHOS_BFCACHE if (base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kEnableBFCache)) -#endif return true; - -#ifdef OHOS_BFCACHE return false; -#endif #else // Disabled due to issue #3237. return false; @@ -1974,6 +1983,7 @@ void AlloyBrowserHostImpl::OnNativeEmbedStatusUpdate( data_info.info.params = native_embed_info.params; platform_delegate_->OnNativeEmbedLifecycleChange(data_info); + } void AlloyBrowserHostImpl::OnLayerRectVisibilityChange(const std::string& embed_id, bool visibility) { @@ -1983,6 +1993,7 @@ void AlloyBrowserHostImpl::OnLayerRectVisibilityChange(const std::string& embed_ platform_delegate_->OnNativeEmbedVisibilityChange(embed_id, visibility); } + #endif // content::WebContentsObserver methods. // ----------------------------------------------------------------------------- @@ -1996,6 +2007,7 @@ void AlloyBrowserHostImpl::DidFinishNavigation( return; } #endif + auto cef_browser_context = static_cast(web_contents()->GetBrowserContext()); if (cef_browser_context) { @@ -2274,6 +2286,7 @@ void AlloyBrowserHostImpl::AddVisitedLinks(const std::vector& urls) { return; } #endif + auto cef_browser_context = static_cast(web_contents()->GetBrowserContext()); if (cef_browser_context) { @@ -2429,6 +2442,7 @@ void AlloyBrowserHostImpl::RenderViewReady() { } ReportWindowStatus(true); ReportRenderProcessStatus(is_hidden_); + LOG(DEBUG) << "AlloyBrowserHostImpl::RenderViewReady"; SetVisible(true); #if BUILDFLAG(IS_OHOS) @@ -2485,9 +2499,7 @@ void AlloyBrowserHostImpl::ReportWindowStatus(bool first_view_ready) { void AlloyBrowserHostImpl::UpdateZoomSupportEnabled() { auto rvh = web_contents()->GetRenderViewHost(); - CefRenderWidgetHostViewOSR* view = - static_cast(rvh->GetWidget()->GetView()); - + auto view = rvh->GetWidget()->GetView(); if (view) { view->SetDoubleTapSupportEnabled(settings_.supports_double_tap_zoom); view->SetMultiTouchZoomSupportEnabled(settings_.supports_multi_touch_zoom); @@ -2673,12 +2685,8 @@ void AlloyBrowserHostImpl::SetDrawRect(int x, int y, int width, int height) { } void AlloyBrowserHostImpl::SetDrawMode(int mode) { - if (drawMode_ != mode) { - drawMode_ = mode; - - if (platform_delegate_) - platform_delegate_->SetDrawMode(drawMode_); - } + if (platform_delegate_) + platform_delegate_->SetDrawMode(mode); } void AlloyBrowserHostImpl::SetFitContentMode(int mode) { @@ -2686,10 +2694,6 @@ void AlloyBrowserHostImpl::SetFitContentMode(int mode) { platform_delegate_->SetFitContentMode(mode); } -int AlloyBrowserHostImpl::GetDrawMode() { - return drawMode_; -} - void AlloyBrowserHostImpl::SetShouldFrameSubmissionBeforeDraw(bool should) { if (!CEF_CURRENTLY_ON_UIT()) { CEF_POST_TASK(CEF_UIT, @@ -2766,7 +2770,6 @@ bool AlloyBrowserHostImpl::GetPrintBackground() { } #endif // defined(OHOS_PRINT) - bool AlloyBrowserHostImpl::Discard() { if (!CEF_CURRENTLY_ON_UIT()) { LOG(ERROR) << "AlloyBrowserHostImpl::Discard failed, called on invalid thread"; @@ -2850,6 +2853,20 @@ CefString AlloyBrowserHostImpl::GetLastJavascriptProxyCallingFrameUrl() { } #endif +#ifdef OHOS_RENDER_PROCESS_MODE +void AlloyBrowserHostImpl::SetNeedsReload(bool needs_reload) { + if (is_hidden_ && needs_reload) { + web_contents()->GetController().SetNeedsReload(); + } + LOG(INFO) << "Set needs reload: " << needs_reload; + needs_reload_ = needs_reload; +} + +bool AlloyBrowserHostImpl::NeedsReload() { + return needs_reload_; +} +#endif // OHOS_RENDER_PROCESS_MODE + #if defined(OHOS_CUSTOM_VIDEO_PLAYER) std::unique_ptr AlloyBrowserHostImpl::CreateCustomMediaPlayer( @@ -2903,17 +2920,41 @@ AlloyBrowserHostImpl::CreateCustomMediaPlayer( } #endif // OHOS_CUSTOM_VIDEO_PLAYER -#ifdef OHOS_RENDER_PROCESS_MODE -void AlloyBrowserHostImpl::NotifyNeedsReload(bool needs_reload) { - if (is_hidden_ && needs_reload) { - web_contents()->GetController().SetNeedsReload(); +#if defined(OHOS_RENDERER_ANR_DUMP) +void AlloyBrowserHostImpl::RendererUnresponsive( + content::WebContents* source, + content::RenderWidgetHost* render_widget_host, + base::RepeatingClosure hang_monitor_restarter, + content::RenderProcessNotRespondingReason reason + +) { + content::RenderProcessHost* host = + source->GetPrimaryMainFrame()->GetProcess(); + if (!host->IsReady() || !source->GetPrimaryMainFrame()->IsRenderFrameLive()) { + OnDumpJavaScriptStackCallback(host->GetProcess().Pid(), reason, ""); + return; } - LOG(INFO) << "NotifyNeedsReload set needs reload: " << needs_reload; - needs_reload_ = needs_reload; + host->dumpCurrentJavaScriptStackInMainThread( + base::BindOnce(&AlloyBrowserHostImpl::OnDumpJavaScriptStackCallback, this, + host->GetProcess().Pid(), reason)); } -bool AlloyBrowserHostImpl::NeedsReload() { - return needs_reload_; +void AlloyBrowserHostImpl::OnDumpJavaScriptStackCallback( + int pid, + content::RenderProcessNotRespondingReason reason, + const std::string& stack) { + if (auto handler = client_->GetRequestHandler()) { + handler->OnRenderProcessNotResponding(this, stack, pid, + static_cast(reason)); + } +} + +void AlloyBrowserHostImpl::RendererResponsive( + content::WebContents* source, + content::RenderWidgetHost* render_widget_host) { + if (auto handler = client_->GetRequestHandler()) { + handler->OnRenderProcessResponding(this); + } } #endif @@ -2933,6 +2974,12 @@ void AlloyBrowserHostImpl::OnTextSelected(bool flag) { } } +void AlloyBrowserHostImpl::OnDestroyImageAnalyzerOverlay() { + if (platform_delegate_) { + platform_delegate_->OnDestroyImageAnalyzerOverlay(); + } +} + float AlloyBrowserHostImpl::GetPageScaleFactor() { if (platform_delegate_) { return platform_delegate_->GetPageScaleFactor(); diff --git a/libcef/browser/alloy/alloy_browser_host_impl.h b/libcef/browser/alloy/alloy_browser_host_impl.h index 5bc03f5fb..25cde8ea9 100644 --- a/libcef/browser/alloy/alloy_browser_host_impl.h +++ b/libcef/browser/alloy/alloy_browser_host_impl.h @@ -251,8 +251,20 @@ class AlloyBrowserHostImpl : public CefBrowserHostBase, #endif #ifdef OHOS_RENDER_PROCESS_MODE -void NotifyNeedsReload(bool needs_reload) override; -bool NeedsReload() override; + void SetNeedsReload(bool needs_reload) override; + bool NeedsReload() override; +#endif + +#if defined(OHOS_RENDERER_ANR_DUMP) + void RendererUnresponsive( + content::WebContents* source, + content::RenderWidgetHost* render_widget_host, + base::RepeatingClosure hang_monitor_restarter, + content::RenderProcessNotRespondingReason reason) override; + + void RendererResponsive( + content::WebContents* source, + content::RenderWidgetHost* render_widget_host) override; #endif enum DestructionState { @@ -403,7 +415,6 @@ bool NeedsReload() override; void SetBackgroundColor(int color) override; SkColor GetBackgroundColor() const; void GetZoomLevelCallback(); - int GetDrawMode(); void SetTouchInsertHandleMenuShow(bool show) { web_contents()->SetTouchInsertHandleMenuShow(show); @@ -437,6 +448,12 @@ bool NeedsReload() override; bool is_site_first_report) override; #endif +#if defined(OHOS_ARKWEB_EXTENSIONS) + void WebExtensionUpdateTabUrl(int32_t tab_id, const GURL& url) override; + void SetTabId(int32_t tab_id) override; + int32_t GetTabId() override; +#endif + #if defined(OHOS_EX_PASSWORD) void ShowPasswordDialog(bool is_update, const std::string& url) override; #endif @@ -472,6 +489,7 @@ bool NeedsReload() override; const gfx::Point& touch_point, const gfx::Rect& screen_rect); void OnTextSelected(bool flag) override; + void OnDestroyImageAnalyzerOverlay() override; float GetPageScaleFactor() override; #endif @@ -535,9 +553,10 @@ bool NeedsReload() override; void SetFitContentMode(int mode) override; #endif // defined(OHOS_COMPOSITE_RENDER) #if defined(OHOS_RENDERER_ANR_DUMP) - void OnDumpJavaScriptStackCallback(int pid, - content::RenderProcessNotRespondingReason reason, - const std::string& stack); + void OnDumpJavaScriptStackCallback( + int pid, + content::RenderProcessNotRespondingReason reason, + const std::string& stack); #endif CefWindowHandle opener_; @@ -578,19 +597,23 @@ bool NeedsReload() override; int window_id_ = -1; int nweb_id_ = -1; base::ProcessId last_pid_ = -1; + + int video_stream_cnt_ = 0; bool has_video_playing_ = false; bool has_touch_event_ = false; bool set_lower_frame_rate_ = false; static constexpr int WAIT_TOUCH_EVENT_DELAY_TIME = 3000/*ms*/; - int video_stream_cnt_ = 0; +#endif - int drawMode_ = 0; +#if defined(OHOS_ARKWEB_EXTENSIONS) + int tab_id_ = -1; #endif bool start_play_ = false; #ifdef OHOS_RENDER_PROCESS_MODE bool needs_reload_ = false; #endif + }; #endif // CEF_LIBCEF_BROWSER_ALLOY_ALLOY_BROWSER_HOST_IMPL_H_ diff --git a/libcef/browser/alloy/alloy_content_browser_client.cc b/libcef/browser/alloy/alloy_content_browser_client.cc index 2cb276c44..5f5ca6bc7 100644 --- a/libcef/browser/alloy/alloy_content_browser_client.cc +++ b/libcef/browser/alloy/alloy_content_browser_client.cc @@ -218,7 +218,7 @@ constexpr int32_t APPLICATION_API_10 = 10; #endif #if OHOS_URL_TRUST_LIST -#include "libcef/browser/ohos_safe_browsing/ohos_url_trust_list_navigation_throttle.h" +#include "libcef/browser/safe_browsing/url_trust_list_navigation_throttle.h" #endif #if defined(OHOS_EX_PASSWORD) || defined(OHOS_PASSWORD_AUTOFILL) @@ -250,9 +250,11 @@ constexpr int32_t APPLICATION_API_10 = 10; #include "components/embedder_support/content_settings_utils.h" #include "content/public/browser/allow_service_worker_result.h" #include "content/public/browser/site_isolation_policy.h" +#include "extensions/browser/api/messaging/messaging_api_message_filter.h" #include "extensions/browser/api/web_request/web_request_api.h" #include "extensions/browser/api/web_request/web_request_proxying_webtransport.h" #include "extensions/browser/extension_navigation_throttle.h" +#include "extensions/browser/extension_service_worker_message_filter.h" #include "extensions/browser/extension_util.h" #include "extensions/browser/service_worker/service_worker_host.h" #include "services/network/public/cpp/self_deleting_url_loader_factory.h" @@ -273,6 +275,14 @@ using extensions::mojom::APIPermissionID; #include "components/security_interstitials/content/security_interstitial_tab_helper.h" +#if defined(OHOS_EX_EXCEPTION_LIST) +#include "chrome/browser/content_settings/host_content_settings_map_factory.h" +#include "chrome/browser/content_settings/page_specific_content_settings_delegate.h" +#include "components/content_settings/browser/page_specific_content_settings.h" +#include "libcef/browser/content_settings/oh_host_content_settings_observer.h" +#include "libcef/browser/content_settings/oh_host_content_settings_observer_factory.h" +#endif + #if defined(OHOS_CRASHPAD) #include "components/crash/content/browser/crash_handler_host_linux.h" #endif @@ -289,6 +299,12 @@ using extensions::mojom::APIPermissionID; #if defined(OHOS_SITE_ISOLATION) bool g_siteIsolationMode = false; #endif + +#ifdef OHOS_ARKWEB_ADBLOCK +#include "components/subresource_filter/content/browser/content_subresource_filter_throttle_manager.h" +#include "libcef/browser/subresource_filter/adblock_content_subresource_filter_web_contents_helper_factory.h" +#endif // OHOS_ARKWEB_ADBLOCK + namespace { #if BUILDFLAG(IS_OHOS) void TransferVector(const std::vector& source, @@ -990,6 +1006,11 @@ void AlloyContentBrowserClient::RenderProcessWillLaunch( if (extensions::ExtensionsEnabled()) { host->AddFilter(new extensions::ExtensionMessageFilter(id, profile)); +#if defined(OHOS_ARKWEB_EXTENSIONS) + host->AddFilter(new extensions::ExtensionServiceWorkerMessageFilter( + id, profile, host->GetStoragePartition()->GetServiceWorkerContext())); + host->AddFilter(new extensions::MessagingAPIMessageFilter(id, profile)); +#endif } // If the renderer process crashes then the host may already have @@ -1002,6 +1023,18 @@ void AlloyContentBrowserClient::RenderProcessWillLaunch( Profile* original_profile = profile->GetOriginalProfile(); RendererUpdaterFactory::GetForProfile(original_profile) ->InitializeRenderer(host); + +#if defined(OHOS_EX_EXCEPTION_LIST) + if (base::CommandLine::ForCurrentProcess()->HasSwitch( + switches::kForBrowser)) { + auto renderer_configuration = GetRendererConfiguration(host); + RendererContentSettingRules rules; + content_settings::GetRendererContentSettingRules( + HostContentSettingsMapFactory::GetForProfile(host->GetBrowserContext()), + &rules); + renderer_configuration->SetContentSettingRules(rules); + } +#endif // defined(OHOS_EX_EXCEPTION_LIST) } bool AlloyContentBrowserClient::ShouldUseProcessPerSite( @@ -1162,35 +1195,7 @@ void AlloyContentBrowserClient::SiteInstanceGotProcess( } extensions::ProcessMap::Get(context)->Insert( - extension->id(), site_instance->GetProcess()->GetID(), - site_instance->GetId()); -} - -void AlloyContentBrowserClient::SiteInstanceDeleting( - content::SiteInstance* site_instance) { - if (!extensions::ExtensionsEnabled()) { - return; - } - - if (!site_instance->HasProcess()) { - return; - } - - auto context = site_instance->GetBrowserContext(); - auto registry = extensions::ExtensionRegistry::Get(context); - if (!registry) { - return; - } - - auto extension = registry->enabled_extensions().GetExtensionOrAppByURL( - site_instance->GetSiteURL()); - if (!extension) { - return; - } - - extensions::ProcessMap::Get(context)->Remove( - extension->id(), site_instance->GetProcess()->GetID(), - site_instance->GetId()); + extension->id(), site_instance->GetProcess()->GetID()); } void AlloyContentBrowserClient::BindHostReceiverForRenderer( @@ -1627,11 +1632,6 @@ void AlloyContentBrowserClient::OverrideWebkitPrefs( prefs->force_enable_zoom = web_contents->GetForceEnableZoom(); #endif -#if BUILDFLAG(IS_OHOS) && defined(OHOS_EX_BLANK_TARGET_POPUP_INTERCEPT) - prefs->blank_target_popup_intercept_enabled = - web_contents->GetEnableBlankTargetPopupIntercept(); -#endif - web_contents->SetPageBaseBackgroundColor(base_background_color); } @@ -1810,7 +1810,7 @@ AlloyContentBrowserClient::CreateThrottlesForNavigation( #endif #if OHOS_URL_TRUST_LIST - throttles.push_back(ohos_safe_browsing::OhosUrlTrustListNavigationThrottle::Create( + throttles.push_back(ohos_safe_browsing::UrlTrustListNavigationThrottle::Create( navigation_handle)); #endif @@ -1905,7 +1905,8 @@ AlloyContentBrowserClient::CreateURLLoaderThrottles( } if (!is_same_host) { - result.push_back(std::make_unique(frame_tree_node_id)); + result.push_back(std::make_unique(frame_tree_node_id, + (request.transition_type & ui::PAGE_TRANSITION_CLIENT_REDIRECT) != 0)); } } #endif @@ -2629,6 +2630,10 @@ void AlloyContentBrowserClient::OnNetworkServiceCreated( DCHECK(SystemNetworkContextManager::GetInstance()); SystemNetworkContextManager::GetInstance()->OnNetworkServiceCreated( network_service); +#ifdef OHOS_EX_NETWORK_CONNECTION + network_service->BindDnsToNetwork(net_service::NetHelpers::network); + net::NetworkChangeNotifier::BindToNetwork(net_service::NetHelpers::network); +#endif #if defined(OHOS_HTTP_DNS) if (net_service::NetHelpers::HasValidDnsOverHttpConfig()) { @@ -2756,7 +2761,7 @@ bool AlloyContentBrowserClient::ConfigureNetworkContextParams( // In order to make better use of cache, we use the same strategy as // chromium for httpcache. // Determined by DiskCache itself. - network_context_params->http_cache_max_size = 0; + network_context_params->http_cache_max_size = 0; } else { network_context_params->http_cache_max_size = 20 * 1024 * 1024; } @@ -2787,6 +2792,16 @@ bool AlloyContentBrowserClient::ConfigureNetworkContextParams( } #endif // defined(OHOS_COOKIE) +#if defined(OHOS_EX_EXCEPTION_LIST) + if (base::CommandLine::ForCurrentProcess()->HasSwitch( + switches::kForBrowser)) { + OhHostContentSettingsObserverFactory::GetInstance()->RegisterObserver( + context); + LOG(INFO) << "ExceptionList " + "AlloyContentBrowserClient::ConfigureNetworkContextParams "; + } +#endif // defined(OHOS_EX_EXCEPTION_LIST) + #ifdef OHOS_NETWORK_PROXY // Add proxy settings NWEB::ProxyConfigMonitor::GetInstance()->AddProxyToNetworkContextParams( @@ -3026,6 +3041,12 @@ void AlloyContentBrowserClient::OnWebContentsCreated( #ifdef OHOS_FCP cef::InitializePageLoadMetricsForWebContents(web_contents); #endif + +#if defined(OHOS_EX_EXCEPTION_LIST) + content_settings::PageSpecificContentSettings::CreateForWebContents( + web_contents, + std::make_unique(web_contents)); +#endif // defined(OHOS_EX_EXCEPTION_LIST) } bool AlloyContentBrowserClient::IsFindInPageDisabledForOrigin( @@ -3084,6 +3105,17 @@ bool AlloyContentBrowserClient::ShouldAllowInsecureLocalNetworkRequests( return content_settings::ShouldAllowInsecureLocalNetworkRequests( HostContentSettingsMapFactory::GetForProfile(browser_context), origin); } + +bool AlloyContentBrowserClient::ShouldDisableOriginAgentClusterDefault( + content::BrowserContext* browser_context) { + // The enterprise policy for kOriginAgentClusterDefaultEnabled defaults to + // true to defer to Chromium's decision. If it is set to false, it should + // override Chromium's decision and use site-keyed agent clusters by default + // instead. + return !Profile::FromBrowserContext(browser_context) + ->GetPrefs() + ->GetBoolean(prefs::kOriginAgentClusterDefaultEnabled); +} #endif #if BUILDFLAG(IS_OHOS) @@ -3167,6 +3199,21 @@ bool AlloyContentBrowserClient::WillCreateRestrictedCookieManager( #endif +#if defined(OHOS_EX_EXCEPTION_LIST) +mojo::AssociatedRemote +AlloyContentBrowserClient::GetRendererConfiguration( + content::RenderProcessHost* render_process_host) { + IPC::ChannelProxy* channel = render_process_host->GetChannel(); + if (!channel) + return mojo::AssociatedRemote(); + + mojo::AssociatedRemote + renderer_configuration; + channel->GetRemoteAssociatedInterface(&renderer_configuration); + return renderer_configuration; +} +#endif // defined(OHOS_EX_EXCEPTION_LIST) + #if BUILDFLAG(IS_OHOS) bool AlloyContentBrowserClient::ShouldOverrideUrlLoading( int frame_tree_node_id, diff --git a/libcef/browser/alloy/alloy_content_browser_client.h b/libcef/browser/alloy/alloy_content_browser_client.h index b5810cea4..341f7eaf4 100644 --- a/libcef/browser/alloy/alloy_content_browser_client.h +++ b/libcef/browser/alloy/alloy_content_browser_client.h @@ -20,6 +20,11 @@ #include "libcef/browser/net_service/proxy_config_monitor.h" #endif +#if defined(OHOS_EX_EXCEPTION_LIST) +#include "chrome/common/renderer_configuration.mojom.h" +#include "mojo/public/cpp/bindings/associated_remote.h" +#endif + class AlloyBrowserMainParts; class CefDevToolsDelegate; @@ -68,7 +73,6 @@ class AlloyContentBrowserClient : public content::ContentBrowserClient { bool IsWebUIAllowedToMakeNetworkRequests(const url::Origin& origin) override; bool IsHandledURL(const GURL& url) override; void SiteInstanceGotProcess(content::SiteInstance* site_instance) override; - void SiteInstanceDeleting(content::SiteInstance* site_instance) override; void BindHostReceiverForRenderer( content::RenderProcessHost* render_process_host, mojo::GenericPendingReceiver receiver) override; @@ -275,6 +279,8 @@ class AlloyContentBrowserClient : public content::ContentBrowserClient { bool ShouldAllowInsecureLocalNetworkRequests( content::BrowserContext* browser_context, const url::Origin& origin) override; + bool ShouldDisableOriginAgentClusterDefault( + content::BrowserContext* browser_context) override; #endif #if BUILDFLAG(IS_OHOS) @@ -418,6 +424,11 @@ CefRefPtr off_the_record_request_context() const; #endif AlloyBrowserMainParts* browser_main_parts_ = nullptr; + +#if defined(OHOS_EX_EXCEPTION_LIST) + mojo::AssociatedRemote + GetRendererConfiguration(content::RenderProcessHost* render_process_host); +#endif // defined(OHOS_EX_EXCEPTION_LIST) }; #endif // CEF_LIBCEF_BROWSER_ALLOY_ALLOY_CONTENT_BROWSER_CLIENT_H_ diff --git a/libcef/browser/alloy/alloy_off_the_record_browser_context.cc b/libcef/browser/alloy/alloy_off_the_record_browser_context.cc index c5338e495..a6736677c 100644 --- a/libcef/browser/alloy/alloy_off_the_record_browser_context.cc +++ b/libcef/browser/alloy/alloy_off_the_record_browser_context.cc @@ -103,6 +103,9 @@ void AlloyOffTheRecordBrowserContext::StoreOrTriggerInitCallback( void AlloyOffTheRecordBrowserContext::Initialize() { CefBrowserContext::Initialize(); + LOG(INFO) << "OffTheRecordBrowserContext Initialize cache_path_ is empty:" + << cache_path_.empty(); + Profile* original_profile = AsProfile()->GetOriginalProfile(); DCHECK(original_profile); key_ = std::make_unique(cache_path_, @@ -171,6 +174,7 @@ void AlloyOffTheRecordBrowserContext::Initialize() { DCHECK(pref_service); user_prefs::UserPrefs::Set(this, pref_service); key_->SetPrefs(pref_service); + media_device_id_salt_ = new MediaDeviceIDSalt(pref_service); TrackZoomLevelsFromParent(); @@ -243,6 +247,7 @@ CefRefPtr AlloyOffTheRecordBrowserContext::GetExtension( } bool AlloyOffTheRecordBrowserContext::UnloadExtension(const CefString& extension_id) { + DCHECK(extensions::ExtensionsEnabled()); return true; } diff --git a/libcef/browser/alloy/browser_platform_delegate_alloy.cc b/libcef/browser/alloy/browser_platform_delegate_alloy.cc index ede6319b7..ab0de2a22 100644 --- a/libcef/browser/alloy/browser_platform_delegate_alloy.cc +++ b/libcef/browser/alloy/browser_platform_delegate_alloy.cc @@ -245,12 +245,12 @@ void CefBrowserPlatformDelegateAlloy::BrowserCreated( } #if defined(OHOS_DATALIST) - autofill::OhAutofillClient::CreateForWebContents(web_contents_, true); + autofill::OhAutofillClient::CreateForWebContents(web_contents_, false); #endif #if defined(OHOS_EX_PASSWORD) || defined(OHOS_DATALIST) || defined(OHOS_PASSWORD_AUTOFILL) // need use components/autofill/core/browser/ module impl save password - autofill::OhAutofillClient::CreateForWebContents(web_contents_, true); + autofill::OhAutofillClient::CreateForWebContents(web_contents_, false); OhPasswordManagerClient::CreateForWebContentsWithAutofillClient( web_contents_, autofill::OhAutofillClient::FromWebContents(web_contents_)); diff --git a/libcef/browser/alloy/chrome_browser_process_alloy.cc b/libcef/browser/alloy/chrome_browser_process_alloy.cc index a7cd7af36..d744e75ca 100644 --- a/libcef/browser/alloy/chrome_browser_process_alloy.cc +++ b/libcef/browser/alloy/chrome_browser_process_alloy.cc @@ -56,7 +56,7 @@ ChromeBrowserProcessAlloy::ChromeBrowserProcessAlloy() ChromeBrowserProcessAlloy::~ChromeBrowserProcessAlloy() { DCHECK((!initialized_ && !context_initialized_) || shutdown_); - + LOG(INFO) << "ChromeBrowserProcessAlloy::~ChromeBrowserProcessAlloy"; if (extensions::ExtensionsEnabled()) { extensions::ExtensionsBrowserClient::Set(nullptr); extensions_browser_client_.reset(); @@ -212,7 +212,6 @@ PrefService* ChromeBrowserProcessAlloy::local_state() { if (!base::PathExists(root_cache_path)) { if (!base::CreateDirectory(root_cache_path)) { LOG(ERROR) << "Create directory failed:" << root_cache_path.value(); - return nullptr; } } } diff --git a/libcef/browser/alloy/chrome_off_the_record_profile_alloy.cc b/libcef/browser/alloy/chrome_off_the_record_profile_alloy.cc index b19fb12c6..3f2c65cb7 100644 --- a/libcef/browser/alloy/chrome_off_the_record_profile_alloy.cc +++ b/libcef/browser/alloy/chrome_off_the_record_profile_alloy.cc @@ -12,7 +12,6 @@ #include "net/url_request/url_request_context.h" #include "chrome/browser/ui/zoom/chrome_zoom_level_prefs.h" #include "components/zoom/zoom_event_manager.h" - namespace { class CefVariationsClient : public variations::VariationsClient { @@ -187,9 +186,10 @@ void ChromeOffTheRecordProfileAlloy::TrackZoomLevelsFromParent() { // Also track changes to the parent profile's default zoom level. parent_default_zoom_level_subscription_ = original_profile_->GetZoomLevelPrefs() - ->RegisterDefaultZoomLevelCallback(base::BindRepeating( - &ChromeOffTheRecordProfileAlloy::UpdateDefaultZoomLevel, - base::Unretained(this))); + ->RegisterDefaultZoomLevelCallback( + base::BindRepeating( + &ChromeOffTheRecordProfileAlloy::UpdateDefaultZoomLevel, + base::Unretained(this))); } void ChromeOffTheRecordProfileAlloy::OnParentZoomLevelChanged( @@ -211,7 +211,7 @@ void ChromeOffTheRecordProfileAlloy::OnParentZoomLevelChanged( void ChromeOffTheRecordProfileAlloy::UpdateDefaultZoomLevel() { if (!original_profile_->GetZoomLevelPrefs()) { - return; + return; } content::HostZoomMap* host_zoom_map = content::HostZoomMap::GetDefaultForBrowserContext(this); diff --git a/libcef/browser/anti_tracking/anti_tracking_delegate_ohos.cc b/libcef/browser/anti_tracking/anti_tracking_delegate_ohos.cc index 75f6bdd78..92c913462 100644 --- a/libcef/browser/anti_tracking/anti_tracking_delegate_ohos.cc +++ b/libcef/browser/anti_tracking/anti_tracking_delegate_ohos.cc @@ -20,4 +20,4 @@ namespace ohos_anti_tracking { void ThirdPartyCookieAccessPolicy::EnableIntelligentTrackingPrevention( content::BrowserContext* browser_context, bool enable) {} -} // ohos_anti_tracking +} // ohos_anti_tracking \ No newline at end of file diff --git a/libcef/browser/anti_tracking/third_party_cookie_access_policy.cc b/libcef/browser/anti_tracking/third_party_cookie_access_policy.cc index 2f92937fb..621bd9892 100644 --- a/libcef/browser/anti_tracking/third_party_cookie_access_policy.cc +++ b/libcef/browser/anti_tracking/third_party_cookie_access_policy.cc @@ -123,7 +123,8 @@ bool ThirdPartyCookieAccessPolicy::IsHostInITPBypassingList(const std::string& h return bypassing_host_list_.find(host) != bypassing_host_list_.end(); } -bool ThirdPartyCookieAccessPolicy::AllowGetCookies(const network::ResourceRequest& request) { +bool ThirdPartyCookieAccessPolicy::AllowGetCookies( + const network::ResourceRequest& request, const GURL& main_frame_url) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); if (request.resource_type == static_cast(blink::mojom::ResourceType::kMainFrame)) { @@ -136,7 +137,8 @@ bool ThirdPartyCookieAccessPolicy::AllowGetCookies(const network::ResourceReques return true; } - if (IsHostInITPBypassingList(request.url.host())) { + if (main_frame_url.is_valid() && main_frame_url.has_host() && + IsHostInITPBypassingList(main_frame_url.host())) { return true; } @@ -211,9 +213,7 @@ void ThirdPartyCookieAccessPolicy::AddITPBypassingListOnIOThread( const std::vector& host_list) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); - bypassing_host_list_.clear(); - bypassing_host_list_ = - std::set(host_list.begin(), host_list.end()); + bypassing_host_list_.insert(host_list.begin(), host_list.end()); LOG(INFO) << "AddITPBypassingListOnIOThread done, host_list size " << host_list.size() << ", block host allow list size " diff --git a/libcef/browser/anti_tracking/third_party_cookie_access_policy.h b/libcef/browser/anti_tracking/third_party_cookie_access_policy.h index 08f37b96c..4a147d584 100644 --- a/libcef/browser/anti_tracking/third_party_cookie_access_policy.h +++ b/libcef/browser/anti_tracking/third_party_cookie_access_policy.h @@ -28,7 +28,8 @@ class ThirdPartyCookieAccessPolicy { public: static ThirdPartyCookieAccessPolicy* GetInstance(); - bool AllowGetCookies(const network::ResourceRequest& request); + bool AllowGetCookies(const network::ResourceRequest& request, + const GURL& main_frame_host); void SetTBWFilePath(const base::FilePath& tbw_path); void AddITPBypassingList(const std::vector& host_list); @@ -63,4 +64,4 @@ class ThirdPartyCookieAccessPolicy { } // namespace ohos_anti_tracking -#endif // CEF_LIBCEF_BROWSER_ANTI_TRACKING_THIRD_PARTY_COOKIE_ACCESS_POLICY_H +#endif // CEF_LIBCEF_BROWSER_ANTI_TRACKING_THIRD_PARTY_COOKIE_ACCESS_POLICY_H \ No newline at end of file diff --git a/libcef/browser/autofill/oh_autofill_client.cc b/libcef/browser/autofill/oh_autofill_client.cc index a1a848761..2d808f1d6 100644 --- a/libcef/browser/autofill/oh_autofill_client.cc +++ b/libcef/browser/autofill/oh_autofill_client.cc @@ -55,22 +55,25 @@ OhAutofillClient::~OhAutofillClient() { } void OhAutofillClient::FillData(CefRefPtr data) { +#if defined(OHOS_AUTOFILL) std::string json_str = data->GetStdString(); content::RenderFrameHost* rfh = GetWebContents().GetFocusedFrame(); autofill::ContentAutofillDriver* driver = autofill::ContentAutofillDriver::GetForRenderFrameHost(rfh); - auto mgr = static_cast(driver->autofill_manager()); + auto mgr = static_cast(driver->oh_autofill_manager()); if (mgr) { mgr->FillData(json_str); } +#endif } -void OhAutofillClient::OnAutofillEvent(const std::string& json_str) { +bool OhAutofillClient::OnAutofillEvent(const std::string& json_str) { if (callback_) { CefRefPtr data = CefValue::Create(); data->SetStdString(json_str); - callback_->OnMessage(data); + return callback_->OnMessageWithBoolResult(data); } + return false; } void OhAutofillClient::SetSaveFormData(bool enabled) { @@ -440,6 +443,14 @@ void OhAutofillClient::SuggestionSelected(int position) { } } +void DriverInit(AutofillClient* client, const std::string& app_locale, + ContentAutofillDriver* driver) { + autofill::BrowserDriverInitHook(client, app_locale, driver); +#if defined(OHOS_AUTOFILL) + autofill::OhDriverInitHook(client, driver); +#endif +} + // Ownership: The native object is created (if autofill enabled) and owned by // AwContents. The native object creates the java peer which handles most // autofill functionality at the java side. The java peer is owned by Java @@ -450,7 +461,7 @@ OhAutofillClient::OhAutofillClient(WebContents* contents, contents, use_autofill_manager ? base::BindRepeating(&autofill::OhDriverInitHook, this) - : base::BindRepeating(&autofill::BrowserDriverInitHook, + : base::BindRepeating(&autofill::DriverInit, this, g_browser_process->GetApplicationLocale())) #if DCHECK_IS_ON() diff --git a/libcef/browser/autofill/oh_autofill_client.h b/libcef/browser/autofill/oh_autofill_client.h index 1e7304f2c..f80b0d7bc 100644 --- a/libcef/browser/autofill/oh_autofill_client.h +++ b/libcef/browser/autofill/oh_autofill_client.h @@ -82,7 +82,7 @@ class OhAutofillClient : public autofill::ContentAutofillClient, callback_ = callback; } void FillData(CefRefPtr data); - void OnAutofillEvent(const std::string& json_str); + bool OnAutofillEvent(const std::string& json_str); bool IsOffTheRecord() override; scoped_refptr GetURLLoaderFactory() override; autofill::AutofillDownloadManager* GetDownloadManager() override; diff --git a/libcef/browser/autofill/oh_autofill_manager.cc b/libcef/browser/autofill/oh_autofill_manager.cc index bf0960592..fd5bd42bb 100644 --- a/libcef/browser/autofill/oh_autofill_manager.cc +++ b/libcef/browser/autofill/oh_autofill_manager.cc @@ -48,9 +48,10 @@ const std::string KEY_PLACEHOLDER = "placeholder"; const std::string KEY_VALUE = "value"; #if defined(OHOS_PASSWORD_AUTOFILL) -const std::string KEY_PAGE_URL = "pageUrl"; const std::string KEY_USERNAME = "username"; const std::string KEY_PASSWORD = "password"; +const std::string KEY_RETURN_PAGE_URL = "autofill_viewdata_origin_pageurl"; +const std::string KEY_RETURN_OTHER_ACCOUNT = "autofill_viewdata_other_account"; #endif } // namespace @@ -59,12 +60,15 @@ namespace autofill { using base::TimeTicks; void OhDriverInitHook(AutofillClient* client, ContentAutofillDriver* driver) { +#if defined(OHOS_AUTOFILL) + driver->set_oh_autofill_manager( + base::WrapUnique(new OhAutofillManager(driver, client))); +#else driver->set_autofill_manager( base::WrapUnique(new OhAutofillManager(driver, client))); +#endif driver->GetAutofillAgent()->SetUserGestureRequired(false); - driver->GetAutofillAgent()->SetSecureContextRequired(true); driver->GetAutofillAgent()->SetFocusRequiresScroll(false); - driver->GetAutofillAgent()->SetQueryPasswordSuggestion(true); } OhAutofillManager::OhAutofillManager(AutofillDriver* driver, @@ -187,10 +191,6 @@ absl::optional OhAutofillManager::FormDataToJsonForSave(const FormD } void OhAutofillManager::FillData(const std::string& json_str) { - if (form_ == nullptr) { - return; - } - absl::optional root = base::JSONReader::Read(json_str); if (!root.has_value()) { return; @@ -202,17 +202,23 @@ void OhAutofillManager::FillData(const std::string& json_str) { } #if defined(OHOS_PASSWORD_AUTOFILL) - const std::string* page_url = root_dict->FindString(KEY_PAGE_URL); const std::string* username = root_dict->FindString(KEY_USERNAME); const std::string* password = root_dict->FindString(KEY_PASSWORD); + const std::string* page_url = root_dict->FindString(KEY_RETURN_PAGE_URL); + bool is_other_account = root_dict->FindBool(KEY_RETURN_OTHER_ACCOUNT).value_or(false); if (username || password) { ForwardDataToPasswordManager(page_url ? *page_url : std::string(), username ? *username : std::string(), - password ? *password : std::string()); + password ? *password : std::string(), + is_other_account); return; } #endif + if (form_ == nullptr) { + return; + } + std::wstring_convert, char16_t> convert; for (const FormFieldData& field_data : form_->fields) { const std::string* value = root_dict->FindString(field_data.autocomplete_attribute); @@ -229,8 +235,9 @@ void OhAutofillManager::FillData(const std::string& json_str) { void OhAutofillManager::ForwardDataToPasswordManager( const std::string& page_url, const std::string& username, - const std::string& password) { - LOG(INFO) << "autofill save, forward to password_manager"; + const std::string& password, + bool is_other_account) { + LOG(INFO) << "autofill fill data, forward to password_manager"; auto* rfh = static_cast(driver())->render_frame_host(); if (!rfh || !rfh->IsActive()) { @@ -248,10 +255,7 @@ void OhAutofillManager::ForwardDataToPasswordManager( return; } - std::wstring_convert, char16_t> convert; - password_manager->FillAccountSuggestion(GURL(page_url), - convert.from_bytes(username), - convert.from_bytes(password)); + password_manager->FillData(page_url, username, password, is_other_account); } bool OhAutofillManager::IsUsernamePasswordFormField(FormRendererId form_id, diff --git a/libcef/browser/autofill/oh_autofill_manager.h b/libcef/browser/autofill/oh_autofill_manager.h index af53aa408..ad0432b1d 100644 --- a/libcef/browser/autofill/oh_autofill_manager.h +++ b/libcef/browser/autofill/oh_autofill_manager.h @@ -98,7 +98,8 @@ class OhAutofillManager : public AutofillManager { #if defined(OHOS_PASSWORD_AUTOFILL) void ForwardDataToPasswordManager(const std::string& page_url, const std::string& username, - const std::string& password); + const std::string& password, + bool is_other_account); bool IsUsernamePasswordFormField(FormRendererId form_id, FieldRendererId field_id); diff --git a/libcef/browser/browser_contents_delegate.cc b/libcef/browser/browser_contents_delegate.cc index 3f58f5483..4988045ab 100644 --- a/libcef/browser/browser_contents_delegate.cc +++ b/libcef/browser/browser_contents_delegate.cc @@ -46,6 +46,11 @@ #include "libcef/browser/load_committed_details_impl.h" #endif // defined(OHOS_NAVIGATION) +#if defined(OHOS_ARKWEB_EXTENSIONS) +#include "chrome/browser/extensions/api/tabs/tabs_constants.h" +#include "libcef/browser/extensions/api/tabs/tabs_windows_api.h" +#endif + using content::KeyboardEventProcessingResult; namespace { @@ -78,7 +83,12 @@ void MaybeSetUserAgentOverrideForMainFrame( } std::string host = url.host(); - if (!navigation->HasUserGesture()) { + bool is_reload = + PageTransitionCoreTypeIs(navigation->GetPageTransition(), + ui::PageTransition::PAGE_TRANSITION_RELOAD); + // Check whether the UA of referrer_url is used only when the main frame + // is not overloaded or triggered by user gestures. + if (navigation->IsInMainFrame() && !navigation->HasUserGesture() && !is_reload) { const GURL referrer_url = navigation->GetReferrer().url; if (referrer_url.is_valid() && !referrer_url.is_empty() && referrer_url.has_host()) { @@ -96,8 +106,9 @@ void MaybeSetUserAgentOverrideForMainFrame( std::string final_ua = nweb_ex::AlloyBrowserUAConfig::GetInstance()->GetUserAgentForHost(host); LOG(DEBUG) << "DidStartNavigation, host " << host << ", final_ua " << final_ua - << ", user_gesture " << navigation->HasUserGesture() << ", url " - << url.spec(); + << ", user_gesture " << navigation->HasUserGesture() + << ", is_main_frame " << navigation->IsInMainFrame() + << ", is_reload " << is_reload << ", url " << url.spec(); navigation->SetRequestHeader(net::HttpRequestHeaders::kUserAgent, final_ua); if (!navigation->IsInMainFrame()) { @@ -300,6 +311,17 @@ void CefBrowserContentsDelegate::LoadingStateChanged( can_go_forward); } } + +#if defined(OHOS_ARKWEB_EXTENSIONS) + int32_t tab_id = browser()->GetTabId(); + if (tab_id >= 0) { + std::vector changed_properties; + changed_properties.push_back(extensions::tabs_constants::kStatusKey); + extensions::cef::TabsWindowsAPI::Get( + source->GetBrowserContext())->TabUpdated( + tab_id, source, changed_properties, ""); + } +#endif } void CefBrowserContentsDelegate::UpdateTargetURL(content::WebContents* source, @@ -309,7 +331,25 @@ void CefBrowserContentsDelegate::UpdateTargetURL(content::WebContents* source, handler->OnStatusMessage(browser(), url.spec()); } } +#ifdef OHOS_NWEB_EX + if (auto c = client()) { + if (auto handler = c->GetRequestHandler()) { + handler->OnUpdateTargetURL(browser(), url.spec()); + } + } +#endif +} + +#if defined(OHOS_ARKWEB_EXTENSIONS) +void CefBrowserContentsDelegate::WebExtensionUpdateTabUrl( + int32_t tab_id, const GURL& url) { + if (auto c = client()) { + if (auto handler = c->GetWebExtensionApiHandler()) { + handler->OnUpdateTabUrl(tab_id, url.spec()); + } + } } +#endif bool CefBrowserContentsDelegate::DidAddMessageToConsole( content::WebContents* source, @@ -674,7 +714,7 @@ void CefBrowserContentsDelegate::PrimaryMainFrameRenderProcessGone( #ifdef OHOS_RENDER_PROCESS_MODE } else if (status == base::TERMINATION_STATUS_NORMAL_TERMINATION) { if (browser() && browser()->GetHost()) { - browser()->GetHost()->NotifyNeedsReload(true); + browser()->GetHost()->SetNeedsReload(true); } #endif } else if (status != base::TERMINATION_STATUS_ABNORMAL_TERMINATION) { @@ -858,6 +898,15 @@ void CefBrowserContentsDelegate::DidFinishNavigation( OnLoadStart(frame.get(), navigation_handle->GetPageTransition()); if (navigation_handle->IsServedFromBackForwardCache()) { // We won't get an OnLoadEnd notification from anywhere else. +#ifdef OHOS_BFCACHE + LOG(INFO) << "[Favicon] page load form bfcache."; + if (auto c = client()) { + if (auto handler = c->GetLoadHandler()) { + auto navigation_lock = browser_info_->CreateNavigationLock(); + handler->UpdateFavicon(browser()); + } + } +#endif // OHOS_BFCACHE OnLoadEnd(frame.get(), navigation_handle->GetURL(), 0); } } @@ -953,8 +1002,14 @@ void CefBrowserContentsDelegate::TitleWasSet(content::NavigationEntry* entry) { // navigated. if (entry) { OnTitleChange(entry->GetTitle()); +#ifdef OHOS_NETWORK_LOAD + observe_need_report_title_ = false; +#endif } else if (web_contents()) { OnTitleChange(web_contents()->GetTitle()); +#ifdef OHOS_NETWORK_LOAD + observe_need_report_title_ = false; +#endif } } @@ -1003,15 +1058,28 @@ void CefBrowserContentsDelegate::WebContentsDestroyed() { } } +#ifdef OHOS_NETWORK_LOAD +void CefBrowserContentsDelegate::DidStartLoading() { + observe_need_report_title_ = true; +} +#endif + void CefBrowserContentsDelegate::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { DCHECK_EQ(type, content::NOTIFICATION_LOAD_STOP); +#ifdef OHOS_NETWORK_LOAD + if (type == content::NOTIFICATION_LOAD_STOP && observe_need_report_title_) { + OnTitleChange(web_contents()->GetTitle()); + observe_need_report_title_ = false; + } +#else if (type == content::NOTIFICATION_LOAD_STOP) { OnTitleChange(web_contents()->GetTitle()); } +#endif } bool CefBrowserContentsDelegate::OnSetFocus(cef_focus_source_t source) { diff --git a/libcef/browser/browser_contents_delegate.h b/libcef/browser/browser_contents_delegate.h index a1f06bf07..c104c70dd 100644 --- a/libcef/browser/browser_contents_delegate.h +++ b/libcef/browser/browser_contents_delegate.h @@ -94,6 +94,9 @@ class CefBrowserContentsDelegate : public content::WebContentsDelegate, void LoadingStateChanged(content::WebContents* source, bool should_show_loading_ui) override; void UpdateTargetURL(content::WebContents* source, const GURL& url) override; +#if defined(OHOS_ARKWEB_EXTENSIONS) + void WebExtensionUpdateTabUrl(int32_t tab_id, const GURL& url) override; +#endif bool DidAddMessageToConsole(content::WebContents* source, blink::mojom::ConsoleMessageLevel log_level, const std::u16string& message, @@ -157,6 +160,9 @@ class CefBrowserContentsDelegate : public content::WebContentsDelegate, content::RenderWidgetHost* render_widget_host) override; void OnFocusChangedInPage(content::FocusedNodeDetails* details) override; void WebContentsDestroyed() override; +#ifdef OHOS_NETWORK_LOAD + void DidStartLoading() override; +#endif #if defined(OHOS_WPT) void DidStartNavigation(content::NavigationHandle* navigation) override; @@ -292,6 +298,10 @@ class CefBrowserContentsDelegate : public content::WebContentsDelegate, base::WeakPtrFactory weak_factory_{this}; #endif + +#ifdef OHOS_NETWORK_LOAD + bool observe_need_report_title_ = false; +#endif }; #endif // CEF_LIBCEF_BROWSER_BROWSER_CONTENTS_DELEGATE_H_ diff --git a/libcef/browser/browser_context_keyed_service_factories.cc b/libcef/browser/browser_context_keyed_service_factories.cc index 5739cde36..9455f415c 100644 --- a/libcef/browser/browser_context_keyed_service_factories.cc +++ b/libcef/browser/browser_context_keyed_service_factories.cc @@ -23,6 +23,7 @@ #include "extensions/browser/renderer_startup_helper.h" #include "services/network/public/cpp/features.h" #if defined(OHOS_ARKWEB_EXTENSIONS) +#include "libcef/browser/extensions/api/tabs/tabs_windows_api.h" #include "chrome/browser/extensions/api/developer_private/developer_private_api.h" #include "extensions/browser/api/management/management_api.h" #endif @@ -45,6 +46,7 @@ void EnsureBrowserContextKeyedServiceFactoriesBuilt() { extensions::DeveloperPrivateAPI::GetFactoryInstance(); extensions::ManagementAPI::GetFactoryInstance(); extensions::WebRequestAPI::GetFactoryInstance(); + extensions::cef::TabsWindowsAPI::GetFactoryInstance(); #endif } diff --git a/libcef/browser/browser_frame.cc b/libcef/browser/browser_frame.cc index a58611482..a6e9605cc 100644 --- a/libcef/browser/browser_frame.cc +++ b/libcef/browser/browser_frame.cc @@ -83,15 +83,15 @@ CefRefPtr CefBrowserFrame::GetFrameHost( #if BUILDFLAG(IS_OHOS) void CefBrowserFrame::OnGetImageForContextNode( - cef::mojom::GetImageForContextNodeParamsPtr params) { + cef::mojom::GetImageForContextNodeParamsPtr params, int command_id) { if (auto host = GetFrameHost()) { - host->OnGetImageForContextNode(std::move(params)); + host->OnGetImageForContextNode(std::move(params), command_id); } } -void CefBrowserFrame::OnGetImageForContextNodeNull() { +void CefBrowserFrame::OnGetImageForContextNodeNull(int command_id) { if (auto host = GetFrameHost()) { - host->OnGetImageForContextNodeNull(); + host->OnGetImageForContextNodeNull(command_id); } } diff --git a/libcef/browser/browser_frame.h b/libcef/browser/browser_frame.h index 3c464acb6..55ed1dcc2 100644 --- a/libcef/browser/browser_frame.h +++ b/libcef/browser/browser_frame.h @@ -47,8 +47,8 @@ class CefBrowserFrame #if BUILDFLAG(IS_OHOS) void OnGetImageForContextNode( - cef::mojom::GetImageForContextNodeParamsPtr params) override; - void OnGetImageForContextNodeNull() override; + cef::mojom::GetImageForContextNodeParamsPtr params, int command_id) override; + void OnGetImageForContextNodeNull(int command_id) override; void ShouldOverrideUrlLoading(const std::string& url, const std::string& request_method, diff --git a/libcef/browser/browser_host_base.cc b/libcef/browser/browser_host_base.cc index 93ce007f2..1fba944b2 100644 --- a/libcef/browser/browser_host_base.cc +++ b/libcef/browser/browser_host_base.cc @@ -49,6 +49,7 @@ #include "content/public/browser/message_port_provider.h" #include "content/public/common/mhtml_generation_params.h" #include "content/public/common/url_constants.h" +#include "content/public/common/referrer.h" #include "libcef/browser/devtools/devtools_manager_delegate.h" #include "libcef/browser/javascript/oh_javascript_injector.h" #include "libcef/browser/navigation_state_serializer.h" @@ -64,6 +65,10 @@ #include "content/browser/media/session/media_session_impl.h" #endif // defined(OHOS_MEDIA_POLICY) +#if defined(OHOS_MEDIA_POLICY) +#include "content/browser/media/session/media_session_impl.h" +#endif // defined(OHOS_MEDIA_POLICY) + #if defined(OHOS_EX_UA) #include "content/public/common/content_switches.h" #endif @@ -96,6 +101,10 @@ #include "cc/input/browser_controls_state.h" #endif +#if defined(OHOS_EX_NAVIGATION) +#include "content/public/browser/navigation_controller.h" +#endif + #ifdef OHOS_ITP #include "cef/libcef/browser/anti_tracking/third_party_cookie_access_policy.h" #endif @@ -111,9 +120,12 @@ #endif #ifdef OHOS_URL_TRUST_LIST -#include "libcef/browser/ohos_safe_browsing/ohos_url_trust_list_manager.h" +#include "libcef/browser/safe_browsing/url_trust_list_manager.h" #endif +#if defined(OHOS_ARKWEB_EXTENSIONS) +#include "libcef/browser/extensions/api/tabs/tabs_windows_api.h" +#endif namespace { #if defined(OHOS_INPUT_EVENTS) @@ -332,8 +344,10 @@ CefBrowserHostBase::CefBrowserHostBase( contents_delegate_->AddObserver(this); #if BUILDFLAG(IS_OHOS) contents_delegate_->InitIconHelper(); - permission_request_handler_.reset(new AlloyPermissionRequestHandler( - client_->GetPermissionRequest(), GetWebContents())); + if (client) { + permission_request_handler_.reset(new AlloyPermissionRequestHandler( + client->GetPermissionRequest(), GetWebContents())); + } #endif } @@ -434,7 +448,7 @@ void CefBrowserHostBase::StartDownload(const CefString& url) { web_contents, gurl, MISSING_TRAFFIC_ANNOTATION)); content::Referrer referrer = content::Referrer::SanitizeForRequest( gurl, content::Referrer(web_contents->GetLastCommittedURL(), - network::mojom::ReferrerPolicy::kDefault)); + network::mojom::ReferrerPolicy::kDefault)); params->set_referrer(referrer.url); manager->DownloadUrl(std::move(params)); } @@ -894,6 +908,7 @@ void CefBrowserHostBase::UpdateBrowserSettings( settings_.embed_tag_type); settings_.draw_mode = browser_settings.draw_mode; settings_.text_autosizing_enabled = browser_settings.text_autosizing_enabled; + settings_.force_zero_layout_height = browser_settings.force_zero_layout_height; #endif // BUILDFLAG(IS_OHOS) #ifdef OHOS_SCROLLBAR settings_.scrollbar_color = browser_settings.scrollbar_color; @@ -913,18 +928,22 @@ void CefBrowserHostBase::UpdateBrowserSettings( settings_.custom_video_player_overlay = browser_settings.custom_video_player_overlay; #endif // OHOS_CUSTOM_VIDEO_PLAYER +#if defined(OHOS_MULTI_WINDOW) + settings_.supports_multiple_windows = browser_settings.supports_multiple_windows; +#endif // OHOS_MULTI_WINDOW #if defined(OHOS_SOFTWARE_COMPOSITOR) settings_.record_whole_document = browser_settings.record_whole_document; #endif -#if defined(OHOS_MULTI_WINDOW) - settings_.supports_multiple_windows = browser_settings.supports_multiple_windows; -#endif // OHOS_MULTI_WINDOW - #ifdef OHOS_NETWORK_LOAD settings_.universal_access_from_file_urls = browser_settings.universal_access_from_file_urls; #endif + +#ifdef OHOS_MEDIA_NETWORK_TRAFFIC_PROMPT + settings_.enable_media_network_traffic_prompt = + browser_settings.enable_media_network_traffic_prompt; +#endif // OHOS_MEDIA_NETWORK_TRAFFIC_PROMPT } void CefBrowserHostBase::SetWebPreferences( @@ -1049,8 +1068,7 @@ void CefBrowserHostBase::JavaScriptOnDocumentStart( js_injection::JsCommunicationHost::AddScriptResult result = host->AddDocumentStartJavaScript(script, scriptRules); if (result.script_id.has_value()) { - document_start_script_result_map_.emplace( - std::make_pair(stdScript, result.script_id.value())); + document_start_script_result_map_[stdScript] = result.script_id.value(); } } } @@ -1079,8 +1097,7 @@ void CefBrowserHostBase::JavaScriptOnDocumentEnd( js_injection::JsCommunicationHost::AddScriptResult result = host->AddDocumentEndJavaScript(script, scriptRules); if (result.script_id.has_value()) { - document_end_script_result_map_.emplace( - std::make_pair(stdScript, result.script_id.value())); + document_end_script_result_map_[stdScript] = result.script_id.value(); } } } @@ -1297,7 +1314,7 @@ bool CefBrowserHostBase::TerminateRenderProcess() { auto frame = GetMainFrame(); if (frame && frame->IsValid()) { static_cast(frame.get())->TerminateRenderProcess(result); - LOG(DEBUG) << "TerminateRenderProcess result:" << result; + LOG(INFO) << "TerminateRenderProcess result:" << result; } return result; } @@ -1557,10 +1574,12 @@ void CefBrowserHostBase::SetBrowserUserAgentString( #if defined(OHOS_I18N) void CefBrowserHostBase::UpdateLocale(const CefString& locale) { std::string update_locale = locale.ToString(); + // need to notify renderer preference to change accepted_language. if (!GetWebContents()) { return; } + auto prefs = GetWebContents()->GetMutableRendererPrefs(); if (prefs->accept_languages.compare(update_locale)) { prefs->accept_languages = update_locale; @@ -1986,6 +2005,48 @@ void CefBrowserHostBase::AbortAskClipboardReadWritePermission( permission_request_handler_->CancelRequest( origin, AlloyAccessRequest::Resources::CLIPBOARD_READ_WRITE); } + +void CefBrowserHostBase::AskClipboardSanitizedWritePermission( + const CefString& origin, + cef_permission_callback_t callback) { + permission_request_handler_->SendRequest(new AlloyAccessRequest( + origin, AlloyAccessRequest::Resources::CLIPBOARD_SANITIZED_WRITE, + std::move(callback))); +} + +void CefBrowserHostBase::AbortAskClipboardSanitizedWritePermission( + const CefString& origin) { + permission_request_handler_->CancelRequest( + origin, AlloyAccessRequest::Resources::CLIPBOARD_SANITIZED_WRITE); +} + +void CefBrowserHostBase::AskAudioCapturePermission( + const CefString& origin, + cef_permission_callback_t callback) { + permission_request_handler_->SendRequest(new AlloyAccessRequest( + origin, AlloyAccessRequest::Resources::AUDIO_CAPTURE, + std::move(callback))); +} + +void CefBrowserHostBase::AbortAskAudioCapturePermission( + const CefString& origin) { + permission_request_handler_->CancelRequest( + origin, AlloyAccessRequest::Resources::AUDIO_CAPTURE); +} + +void CefBrowserHostBase::AskVideoCapturePermission( + const CefString& origin, + cef_permission_callback_t callback) { + permission_request_handler_->SendRequest(new AlloyAccessRequest( + origin, AlloyAccessRequest::Resources::VIDEO_CAPTURE, + std::move(callback))); +} + +void CefBrowserHostBase::AbortAskVideoCapturePermission( + const CefString& origin) { + permission_request_handler_->CancelRequest( + origin, AlloyAccessRequest::Resources::VIDEO_CAPTURE); +} #endif CefRefPtr CefBrowserHostBase::GetFrameForHost( @@ -2305,6 +2366,11 @@ CefString CefBrowserHostBase::Title() { // WebMessagePort>> portMap_; first is the paif of port_handles. second is the // WebMessagePort of the pipe. void CefBrowserHostBase::CreateWebMessagePorts(std::vector& ports) { + if (!CEF_CURRENTLY_ON_UIT()) { + CHECK(false) << "called on invalid thread"; + return; + } + base::AutoLock msg_lock(web_message_lock_); auto web_contents = GetWebContents(); if (web_contents) { int retry_times = 0; @@ -2322,11 +2388,10 @@ void CefBrowserHostBase::CreateWebMessagePorts(std::vector& ports) { continue; } uint64_t pointer1 = pointer0 + 1; - auto iter = std::find_if(portMap_.begin(), portMap_.end(), [&pointer0, &pointer1](auto& cc){ + auto iter = std::find_if(portMap_.begin(), portMap_.end(), [&pointer0, &pointer1](auto& cc) { std::pair rnd = cc.first; return (rnd.first == pointer0 || rnd.second == pointer0 || rnd.first == pointer1); }); - if (iter == portMap_.end()) { portMap_[std::make_pair(pointer0, pointer1)] = std::make_pair(std::move(portArr[0]), std::move(portArr[1])); @@ -2347,6 +2412,11 @@ void CefBrowserHostBase::CreateWebMessagePorts(std::vector& ports) { void CefBrowserHostBase::PostWebMessage(CefString& message, std::vector& port_handles, CefString& targetUri) { + if (!CEF_CURRENTLY_ON_UIT()) { + CHECK(false) << "called on invalid thread"; + return; + } + base::AutoLock msg_lock(web_message_lock_); auto web_contents = GetWebContents(); if (!web_contents) { LOG(ERROR) << "PostWebMessage web_contents its null"; @@ -2390,6 +2460,11 @@ void CefBrowserHostBase::PostWebMessage(CefString& message, // WebMessagePort>> portMap_; first is the paif of port_handles. second is the // WebMessagePort of the pipe. void CefBrowserHostBase::ClosePort(CefString& portHandle) { + if (!CEF_CURRENTLY_ON_UIT()) { + CHECK(false) << "called on invalid thread"; + return; + } + base::AutoLock msg_lock(web_message_lock_); LOG(DEBUG) << "ClosePort ClosePort"; auto web_contents = GetWebContents(); if (!web_contents) { @@ -2535,14 +2610,10 @@ bool CefBrowserHostBase::ConvertCefValueToBlinkMsg( return true; } -void CefBrowserHostBase::PostPortMessage(CefString& portHandle, +void CefBrowserHostBase::PostPortMessageInternal(const CefString& portHandle, CefRefPtr data) { - auto web_contents = GetWebContents(); - if (!web_contents) { - LOG(ERROR) << "GetWebContents null"; - return; - } - + base::ScopedAllowBlocking scoped_allow_blocking; + base::AutoLock msg_lock(web_message_lock_); // construct blink message blink::WebMessagePort::Message message; if (!ConvertCefValueToBlinkMsg(data, message)) { @@ -2571,27 +2642,19 @@ void CefBrowserHostBase::PostPortMessage(CefString& portHandle, } } -// in the std::map, std::pair> portMap_; first is the paif of port_handles. second is the -// WebMessagePort of the pipe. -void CefBrowserHostBase::SetPortMessageCallback( - CefString& portHandle, - CefRefPtr callback) { - auto web_contents = GetWebContents(); - if (!web_contents) { - LOG(ERROR) << "GetWebContents null"; - return; - } +void CefBrowserHostBase::PostPortMessage(const CefString& portHandle, + CefRefPtr data) { + sequenced_task_runner_->PostTask( + FROM_HERE, base::BindOnce(&CefBrowserHostBase::PostPortMessageInternal, + this, portHandle, data)); +} - // get sequenced task runner +void CefBrowserHostBase::SetPortMessageCallbackInternal( + const CefString& portHandle, + CefRefPtr callback) { + base::ScopedAllowBlocking scoped_allow_blocking; + base::AutoLock msg_lock(web_message_lock_); std::string pointer0 = portHandle.ToString(); - if (!base::SequencedTaskRunner::HasCurrentDefault()) - { - LOG(ERROR) << "not in SequencedTaskRunner"; - return; - } - - auto sequenced_task_runner_ = base::SequencedTaskRunner::GetCurrentDefault(); // get web message receiver instance std::shared_ptr webMsgReceiver; @@ -2628,7 +2691,19 @@ void CefBrowserHostBase::SetPortMessageCallback( receiverMap_[pointer0] = webMsgReceiver; } +// in the std::map, std::pair> portMap_; first is the paif of port_handles. second is the +// WebMessagePort of the pipe. +void CefBrowserHostBase::SetPortMessageCallback( + const CefString& portHandle, + CefRefPtr callback) { + sequenced_task_runner_->PostTask( + FROM_HERE, base::BindOnce(&CefBrowserHostBase::SetPortMessageCallbackInternal, + this, portHandle, callback)); +} + void CefBrowserHostBase::DestroyAllWebMessagePorts() { + base::AutoLock msg_lock(web_message_lock_); LOG(DEBUG) << "clear all message ports"; portMap_.clear(); receiverMap_.clear(); @@ -2804,10 +2879,16 @@ void CefBrowserHostBase::LoadWithDataAndBaseUrl(const CefString& baseUrl, } buildData.append(";base64"); buildData.append(","); + std::string emtry_data_url = buildData; dataBase = GetDataURI(dataBase); buildData.append(dataBase); GURL data_url = GURL(buildData); content::NavigationController::LoadURLParams loadUrlParams(data_url); + if (data_url.spec().size() > url::kMaxURLChars) { + loadUrlParams.url = GURL(emtry_data_url); + loadUrlParams.data_url_as_string = + base::MakeRefCounted(std::move(buildData)); + } if (!(url.find("data:") == 0)) { loadUrlParams.virtual_url_for_data_url = GURL(historyUrlBase); @@ -2843,9 +2924,15 @@ void CefBrowserHostBase::LoadWithData(const CefString& data, buildData.append(";base64"); } buildData.append(","); + std::string emtry_data_url = buildData; buildData.append(dataBase); GURL data_url = GURL(buildData); content::NavigationController::LoadURLParams loadUrlParams(data_url); + if (data_url.spec().size() > url::kMaxURLChars) { + loadUrlParams.url = GURL(emtry_data_url); + loadUrlParams.data_url_as_string = + base::MakeRefCounted(std::move(buildData)); + } auto web_contents = GetWebContents(); if (web_contents) { @@ -3057,26 +3144,26 @@ bool CefBrowserHostBase::GetWebDebuggingAccess() { return is_web_debugging_access_; } -void CefBrowserHostBase::GetImageForContextNode() { +void CefBrowserHostBase::GetImageForContextNode(int command_id) { auto frame = GetMainFrame(); if (frame && frame->IsValid()) { - static_cast(frame.get())->GetImageForContextNode(); + static_cast(frame.get())->GetImageForContextNode(command_id); } } -void CefBrowserHostBase::GetImageFromCache(const CefString& url) { - LOG(ERROR) << "CefBrowserHostBase::GetImageFromCache"; +void CefBrowserHostBase::GetImageFromCache(const CefString& url, int command_id) { + LOG(INFO) << "CefBrowserHostBase::GetImageFromCache"; auto web_contents = GetWebContents(); auto frame = GetMainFrame(); if (web_contents && frame && frame->IsValid()) { content::RenderFrameHost* rfh = web_contents->GetPrimaryMainFrame(); if (rfh) { - LOG(ERROR) << "CefBrowserHostBase::GetImageFromCache"; + LOG(INFO) << "CefBrowserHostBase::GetImageFromCache"; rfh->GetImageFromCache( url.ToString(), base::BindOnce(&CefFrameHostImpl::OnGetImageFromCache, static_cast(frame.get()), - url.ToString())); + url.ToString(), command_id)); } } } @@ -3094,6 +3181,7 @@ void CefBrowserHostBase::WasOccluded(bool occluded) { // TODO(ohos): please impl the function and remove this comment. } + // TODO(ohos): please impl the function and remove this comment. void CefBrowserHostBase::OnWindowShow() { // TODO(ohos): please impl the function and remove this comment. } @@ -3106,8 +3194,7 @@ void CefBrowserHostBase::OnOnlineRenderToForeground() { // TODO(ohos): please impl the function and remove this comment. } -void CefBrowserHostBase::SendTouchEventList( - const std::vector& event_list) { +void CefBrowserHostBase::SendTouchEventList(const std::vector& event_list) { // TODO(ohos): please impl the function and remove this comment. } @@ -3320,22 +3407,22 @@ void CefBrowserHostBase::SetShouldFrameSubmissionBeforeDraw(bool should) { // TODO(ohos): please impl the function and remove this comment. } -void CefBrowserHostBase::SelectAndCopy() { +void CefBrowserHostBase::ShowFreeCopyMenu() { #if defined(OHOS_EX_FREE_COPY) if (!GetWebContents()) { return; } LOG(DEBUG) << "select and copy invoke"; - GetWebContents()->SelectAndCopy(); + GetWebContents()->ShowFreeCopyMenu(); #endif } -bool CefBrowserHostBase::ShouldShowFreeCopy() { +bool CefBrowserHostBase::ShouldShowFreeCopyMenu() { #if defined(OHOS_EX_FREE_COPY) if (!GetWebContents()) { return false; } - return GetWebContents()->ShouldShowFreeCopy(); + return GetWebContents()->ShouldShowFreeCopyMenu(); #else return false; #endif @@ -3463,16 +3550,6 @@ bool CefBrowserHostBase::GetForceEnableZoom() { #endif // #if defined (OHOS_EX_FORCE_ZOOM) } -void CefBrowserHostBase::SetEnableBlankTargetPopupIntercept( - bool enableBlankTargetPopup) { -#ifdef OHOS_EX_BLANK_TARGET_POPUP_INTERCEPT - if (!GetWebContents()) { - return; - } - GetWebContents()->SetEnableBlankTargetPopupIntercept(enableBlankTargetPopup); -#endif -} - void CefBrowserHostBase::SaveOrUpdatePassword(bool is_update) { #if defined(OHOS_EX_PASSWORD) if (!GetWebContents()) { @@ -3493,6 +3570,7 @@ void CefBrowserHostBase::EnableAdsBlock(bool enable) { return; } GetWebContents()->EnableAdsBlock(enable); + LOG(INFO) << "web adblock enabled : " << enable; OHOS::adblock::AdBlockConfig::GetInstance()->ReadFromPrefService(); @@ -3656,6 +3734,28 @@ bool CefBrowserHostBase::GetSavePassword() { } // #endif // defined(OHOS_NWEB_EX) +int CefBrowserHostBase::GetTopControlsOffset() { +#if defined(OHOS_EX_TOPCONTROLS) + if (platform_delegate_) { + return platform_delegate_->GetTopControlsOffset(); + } + return 0; +#else + return 0; +#endif +} + +int CefBrowserHostBase::GetShrinkViewportHeight() { +#if defined(OHOS_EX_TOPCONTROLS) + if (platform_delegate_) { + return platform_delegate_->GetShrinkViewportHeight(); + } + return 0; +#else + return 0; +#endif +} + #if BUILDFLAG(IS_OHOS) int CefBrowserHostBase::GetSecurityLevel() { if (!GetWebContents()) { @@ -3673,27 +3773,76 @@ int CefBrowserHostBase::GetSecurityLevel() { } #endif // BUILDFLAG(IS_OHOS) -int CefBrowserHostBase::GetTopControlsOffset() { -#if defined(OHOS_EX_TOPCONTROLS) - if (platform_delegate_) { - return platform_delegate_->GetTopControlsOffset(); +#if defined(OHOS_EX_NAVIGATION) +int CefBrowserHostBase::InsertBackForwardEntry(int index, + const CefString& url) { + if (!GetWebContents()) { + return static_cast( + content::NavigationController::NavigationEntryUpdateError::ERR_OTHER); } - return 0; -#else - return 0; + GURL gurl = GURL(url.ToString()); + if (gurl.is_empty() || !gurl.is_valid()) { + return static_cast( + content::NavigationController::NavigationEntryUpdateError::ERR_OTHER); + } + return static_cast( + GetWebContents()->GetController().InsertBackForwardEntry(index, gurl)); +} + +int CefBrowserHostBase::UpdateNavigationEntryUrl(int index, + const CefString& url) { + if (!GetWebContents()) { + return static_cast( + content::NavigationController::NavigationEntryUpdateError::ERR_OTHER); + } + GURL gurl = GURL(url.ToString()); + if (gurl.is_empty() || !gurl.is_valid()) { + return static_cast( + content::NavigationController::NavigationEntryUpdateError::ERR_OTHER); + } + return static_cast( + GetWebContents()->GetController().UpdateNavigationEntryUrl(index, gurl)); +} +void CefBrowserHostBase::ClearForwardList() { + if (!GetWebContents()) { + return; + } + + GetWebContents()->GetController().PruneForwardEntries(); +} #endif + +#ifdef OHOS_ITP +void CefBrowserHostBase::EnableIntelligentTrackingPrevention(bool enable) { + { + base::AutoLock locker(lock_); + intelligent_tracking_prevention_cookies_enabled_ = enable; + } + LOG(INFO) << "Intelligent tracking prevention cookies enabled " << enable; + ohos_anti_tracking::ThirdPartyCookieAccessPolicy::GetInstance()-> + EnableIntelligentTrackingPrevention(GetBrowserContext(), enable); } -int CefBrowserHostBase::GetShrinkViewportHeight() { -#if defined(OHOS_EX_TOPCONTROLS) - if (platform_delegate_) { - return platform_delegate_->GetShrinkViewportHeight(); +bool CefBrowserHostBase::IsIntelligentTrackingPreventionEnabled() { + base::AutoLock locker(lock_); + return intelligent_tracking_prevention_cookies_enabled_; +} + +GURL CefBrowserHostBase::GetLastCommittedURL() { + GURL url; + if (!GetWebContents()) { + return url; } - return 0; -#else - return 0; + url = GetWebContents()->GetLastCommittedURL(); + return url; +} #endif + +#if defined(OHOS_SECURE_JAVASCRIPT_PROXY) +CefString CefBrowserHostBase::GetLastJavascriptProxyCallingFrameUrl() { + return base::EmptyString(); } +#endif void CefBrowserHostBase::StartCamera() { #if defined(OHOS_WEBRTC) @@ -3728,29 +3877,6 @@ void CefBrowserHostBase::CloseCamera() { #endif // defined(OHOS_WEBRTC) } -#if defined(OHOS_SECURE_JAVASCRIPT_PROXY) -CefString CefBrowserHostBase::GetLastJavascriptProxyCallingFrameUrl() { - return base::EmptyString(); -} -#endif - -#ifdef OHOS_ITP -void CefBrowserHostBase::EnableIntelligentTrackingPrevention(bool enable) { - { - base::AutoLock locker(lock_); - intelligent_tracking_prevention_cookies_enabled_ = enable; - } - LOG(INFO) << "Intelligent tracking prevention cookies enabled " << enable; - ohos_anti_tracking::ThirdPartyCookieAccessPolicy::GetInstance()-> - EnableIntelligentTrackingPrevention(GetBrowserContext(), enable); -} - -bool CefBrowserHostBase::IsIntelligentTrackingPreventionEnabled() { - base::AutoLock locker(lock_); - return intelligent_tracking_prevention_cookies_enabled_; -} -#endif - void CefBrowserHostBase::SetNWebId(int NWebID) { #if defined(OHOS_WEBRTC) auto web_contents = GetWebContents(); @@ -3762,6 +3888,14 @@ void CefBrowserHostBase::SetNWebId(int NWebID) { #endif // defined(OHOS_WEBRTC) } +#ifdef OHOS_RENDER_PROCESS_MODE +void CefBrowserHostBase::SetNeedsReload(bool needs_reload) {} + +bool CefBrowserHostBase::NeedsReload() { + return false; +} +#endif + #if BUILDFLAG(IS_OHOS) void CefBrowserHostBase::PrecompileJavaScript(const std::string& url, const std::string& script, @@ -3795,7 +3929,7 @@ oh_code_cache::NextOp CefBrowserHostBase::WriteResponseCache( auto response_cache = oh_code_cache::ResponseCache::CreateResponseCache(url); if (!response_cache) { - LOG(ERROR) << "Create response cache error."; + LOG(DEBUG) << "Create response cache error."; return oh_code_cache::NextOp::THROW_ERROR; } @@ -3843,14 +3977,20 @@ void CefBrowserHostBase::OnDidGenerateCodeCache(CefRefPtr } #endif -#ifdef OHOS_RENDER_PROCESS_MODE -void CefBrowserHostBase::NotifyNeedsReload(bool needs_reload) { +#ifdef OHOS_AI +void CefBrowserHostBase::OnTextSelected(bool flag) { // TODO(ohos): please impl the function and remove this comment. } -bool CefBrowserHostBase::NeedsReload() { +void CefBrowserHostBase::OnDestroyImageAnalyzerOverlay() { // TODO(ohos): please impl the function and remove this comment. - return false; +} + +float CefBrowserHostBase::GetPageScaleFactor() { + if (platform_delegate_) { + return platform_delegate_->GetPageScaleFactor(); + } + return 1; } #endif @@ -3876,19 +4016,6 @@ void CefBrowserHostBase::NotifyForNextTouchEvent() { } #endif -#ifdef OHOS_AI -void CefBrowserHostBase::OnTextSelected(bool flag) { - // TODO(ohos): please impl the function and remove this comment. -} - -float CefBrowserHostBase::GetPageScaleFactor() { - if (platform_delegate_) { - return platform_delegate_->GetPageScaleFactor(); - } - return 1; -} -#endif - #if defined(OHOS_SOFTWARE_COMPOSITOR) bool CefBrowserHostBase::WebPageSnapshot( const char* id, @@ -3912,19 +4039,18 @@ int CefBrowserHostBase::SetUrlTrustListWithErrMsg( LOG(ERROR) << "SetUrlTrustListWithErrMsg failed, web contents is error."; return static_cast(ohos_safe_browsing::UrlListSetResult::INIT_ERROR); } - ohos_safe_browsing::OhosUrlTrustListManager* manager = - reinterpret_cast( + ohos_safe_browsing::UrlTrustListManager* manager = + reinterpret_cast( webContents->GetUserData( - &ohos_safe_browsing::OhosUrlTrustListInterface::interfaceKey)); + &ohos_safe_browsing::UrlTrustListInterface::interfaceKey)); if (!manager) { - manager = new ohos_safe_browsing::OhosUrlTrustListManager(); + manager = new ohos_safe_browsing::UrlTrustListManager(); if (!manager) { LOG(ERROR) << "SetUrlTrustListWithErrMsg failed, new UrlTrustListManager failed."; - return static_cast( - ohos_safe_browsing::UrlListSetResult::INIT_ERROR); + return static_cast(ohos_safe_browsing::UrlListSetResult::INIT_ERROR); } webContents->SetUserData( - &ohos_safe_browsing::OhosUrlTrustListInterface::interfaceKey, + &ohos_safe_browsing::UrlTrustListInterface::interfaceKey, std::unique_ptr(manager)); } int res = static_cast(manager->SetUrlTrustListWithErrMsg( @@ -3934,6 +4060,37 @@ int CefBrowserHostBase::SetUrlTrustListWithErrMsg( } #endif +#if defined(OHOS_ARKWEB_EXTENSIONS) +void CefBrowserHostBase::SetTabId(int tab_id) {} +int CefBrowserHostBase::GetTabId() { return -1; } + +void CefBrowserHostBase::WebExtensionTabUpdated( + int tab_id, + const std::vector& changed_property_names, + const CefString& url) { + content::WebContents* web_contents = GetWebContents(); + if (!web_contents) { + LOG(ERROR) << "TabUpdated get contents failed."; + return; + } + + auto browser_context = web_contents->GetBrowserContext(); + if (!browser_context) { + LOG(ERROR) << "TabUpdated get browser context failed."; + return; + } + + std::vector changed_properties; + std::for_each(changed_property_names.begin(), changed_property_names.end(), + [&changed_properties] (const CefString& name) { + changed_properties.emplace_back(name.ToString()); + }); + + extensions::cef::TabsWindowsAPI::Get(browser_context)->TabUpdated( + tab_id, web_contents, changed_properties, url.ToString()); +} +#endif + #ifdef OHOS_BFCACHE void CefBrowserHostBase::SetBackForwardCacheOptions(int32_t size, int32_t timeToLive) { auto web_contents = GetWebContents(); @@ -3942,6 +4099,8 @@ void CefBrowserHostBase::SetBackForwardCacheOptions(int32_t size, int32_t timeTo return; } + LOG(INFO) << "SetBackForwardCacheOptions size: " << size + << " timeToLive: " << timeToLive; content::NavigationController& controller = web_contents->GetController(); controller.GetBackForwardCache().SetCacheSize(size); controller.GetBackForwardCache().SetTimeToLive(timeToLive); diff --git a/libcef/browser/browser_host_base.h b/libcef/browser/browser_host_base.h index 8c58f3dcd..a98aa302b 100644 --- a/libcef/browser/browser_host_base.h +++ b/libcef/browser/browser_host_base.h @@ -260,6 +260,7 @@ class CefBrowserHostBase : public CefBrowserHost, void PutUserAgent(const CefString& ua) override; CefString DefaultUserAgent() override; void UpdateBrowserSettings(const CefBrowserSettings& browser_settings); + void RegisterNativeJSProxy(const CefString& object_name, const std::vector& method_list, const int32_t object_id, @@ -297,8 +298,8 @@ class CefBrowserHostBase : public CefBrowserHost, const CefString& base_name, bool auto_name, CefRefPtr callback) override; - void GetImageForContextNode() override; - void GetImageFromCache(const CefString& url) override; + void GetImageForContextNode(int command_id) override; + void GetImageFromCache(const CefString& url, int command_id) override; void SetBrowserUserAgentString(const CefString& user_agent) override; void ExitFullScreen() override; void GetRootBrowserAccessibilityManager(void** manager) override; @@ -333,7 +334,6 @@ class CefBrowserHostBase : public CefBrowserHost, int current, bool animate) override; void UpdateBrowserControlsHeight(int height, bool animate) override; - void StartCamera() override; void StopCamera() override; void CloseCamera() override; @@ -351,8 +351,8 @@ class CefBrowserHostBase : public CefBrowserHost, #endif #ifdef OHOS_RENDER_PROCESS_MODE -void NotifyNeedsReload(bool needs_reload) override; -bool NeedsReload() override; + void SetNeedsReload(bool needs_reload) override; + bool NeedsReload() override; #endif // CefBrowser methods: @@ -436,6 +436,7 @@ bool NeedsReload() override; void WasKeyboardResized() override; void SetWindowId(int window_id, int nweb_id) override; void SetWakeLockHandler(int32_t windowId, CefRefPtr callback) override; + #if defined(OHOS_PRINT) void SetToken(void* token) override; void CreateWebPrintDocumentAdapter(const CefString& jobName, @@ -475,13 +476,14 @@ bool NeedsReload() override; bool Discard() override { return false; } bool Restore() override { return false; } // #ifdef OHOS_EX_FREE_COPY - void SelectAndCopy() override; - bool ShouldShowFreeCopy() override; + void ShowFreeCopyMenu() override; + bool ShouldShowFreeCopyMenu() override; // #endif int GetNWebId() override; #ifdef OHOS_ITP void EnableIntelligentTrackingPrevention(bool enable) override; bool IsIntelligentTrackingPreventionEnabled() override; + GURL GetLastCommittedURL(); #endif #endif // BUILDFLAG(IS_OHOS) @@ -505,10 +507,10 @@ bool NeedsReload() override; void ClosePort(CefString& port_handle) override; bool ConvertCefValueToBlinkMsg(CefRefPtr& original, blink::WebMessagePort::Message& message); - void PostPortMessage(CefString& port_handle, + void PostPortMessage(const CefString& port_handle, CefRefPtr message) override; void SetPortMessageCallback( - CefString& port_handle, + const CefString& port_handle, CefRefPtr callback) override; void DestroyAllWebMessagePorts() override; #endif // defined(OHOS_MSGPORT) @@ -530,9 +532,7 @@ bool NeedsReload() override; void SetForceEnableZoom(bool forceEnableZoom) override; bool GetForceEnableZoom() override; - // #ifdef OHOS_EX_BLANK_TARGET_POPUP_INTERCEPT - void SetEnableBlankTargetPopupIntercept(bool enableBlankTargetPopup) override; - // #endif + // if defined(OHOS_EX_PASSWORD) void PasswordSuggestionSelected(int list_index) override; bool GetSavePasswordAutomatically() override; @@ -684,6 +684,18 @@ bool TerminateRenderProcess() override; void AskClipboardReadWritePermission(const CefString& origin, cef_permission_callback_t callback) override; void AbortAskClipboardReadWritePermission(const CefString& origin) override; + + void AskClipboardSanitizedWritePermission(const CefString& origin, + cef_permission_callback_t callback) override; + void AbortAskClipboardSanitizedWritePermission( + const CefString& origin) override; + + void AskAudioCapturePermission(const CefString& origin, + cef_permission_callback_t callback) override; + void AbortAskAudioCapturePermission(const CefString& origin) override; + void AskVideoCapturePermission(const CefString& origin, + cef_permission_callback_t callback) override; + void AbortAskVideoCapturePermission(const CefString& origin) override; // Geolocation API support void PopupGeolocationPrompt(std::string origin, cef_permission_callback_t callback); @@ -713,17 +725,24 @@ bool TerminateRenderProcess() override; #if defined(OHOS_SECURE_JAVASCRIPT_PROXY) CefString GetLastJavascriptProxyCallingFrameUrl() override; #endif -#endif // IS_OHOS -#ifdef OHOS_DISPLAY_CUTOUT - void OnSafeInsetsChange(int left, int top, int right, int bottom) override; +#endif // IS_OHOS +#if defined(OHOS_EX_NAVIGATION) + int InsertBackForwardEntry(int index, const CefString& url) override; + int UpdateNavigationEntryUrl(int index, const CefString& url) override; + void ClearForwardList() override; #endif #ifdef OHOS_AI void OnTextSelected(bool flag) override; + void OnDestroyImageAnalyzerOverlay() override; float GetPageScaleFactor() override; #endif +#ifdef OHOS_DISPLAY_CUTOUT + void OnSafeInsetsChange(int left, int top, int right, int bottom) override; +#endif + #ifdef OHOS_URL_TRUST_LIST int SetUrlTrustListWithErrMsg( const CefString& urlTrustList, CefString& detailErrMsg) override; @@ -736,6 +755,15 @@ bool TerminateRenderProcess() override; cef_web_snapshot_callback_t callback)override; #endif +#if defined(OHOS_ARKWEB_EXTENSIONS) + void WebExtensionTabUpdated( + int tab_id, + const std::vector& changed_property_names, + const CefString& url) override; + void SetTabId(int tab_id) override; + int GetTabId() override; +#endif + #ifdef OHOS_BFCACHE void SetBackForwardCacheOptions(int32_t size, int32_t timeToLive) override; #endif @@ -823,6 +851,13 @@ bool TerminateRenderProcess() override; CefRefPtr callback); void OnDidGenerateCodeCache(CefRefPtr callback, int32_t result); + + void SetPortMessageCallbackInternal( + const CefString& portHandle, + CefRefPtr callback); + void PostPortMessageInternal(const CefString& portHandle, + CefRefPtr data); + // GURL is supplied by the content layer as requesting frame. // Callback is supplied by the content layer, and is invoked with the result // from the permission prompt. @@ -832,10 +867,13 @@ bool TerminateRenderProcess() override; using MessagePipe = std::pair; using PortHandle = std::pair; - std::map portMap_; - std::set postedPorts_; + base::Lock web_message_lock_; + std::map portMap_ GUARDED_BY(web_message_lock_); + std::set postedPorts_ GUARDED_BY(web_message_lock_); std::unordered_map> - receiverMap_; + receiverMap_ GUARDED_BY(web_message_lock_); + scoped_refptr sequenced_task_runner_ = + base::ThreadPool::CreateSequencedTaskRunner({}); #if defined(OHOS_INPUT_EVENTS) uint64_t last_zoom_time_ = 0; diff --git a/libcef/browser/browser_platform_delegate.cc b/libcef/browser/browser_platform_delegate.cc index b1eeb6459..0acc165c5 100644 --- a/libcef/browser/browser_platform_delegate.cc +++ b/libcef/browser/browser_platform_delegate.cc @@ -495,15 +495,6 @@ int CefBrowserPlatformDelegate::GetShrinkViewportHeight() { } #endif -#ifdef OHOS_DISPLAY_CUTOUT -void CefBrowserPlatformDelegate::OnSafeInsetsChange(int left, - int top, - int right, - int bottom) { - NOTIMPLEMENTED(); -} -#endif - #ifdef OHOS_AI void CefBrowserPlatformDelegate::CreateOverlay(const gfx::ImageSkia& image, const gfx::Rect& image_rect, @@ -516,11 +507,24 @@ void CefBrowserPlatformDelegate::OnTextSelected(bool flag) { DCHECK(false); } +void CefBrowserPlatformDelegate::OnDestroyImageAnalyzerOverlay() { + DCHECK(false); +} + float CefBrowserPlatformDelegate::GetPageScaleFactor() { return 1; } #endif +#ifdef OHOS_DISPLAY_CUTOUT +void CefBrowserPlatformDelegate::OnSafeInsetsChange(int left, + int top, + int right, + int bottom) { + NOTIMPLEMENTED(); +} +#endif + #if defined(OHOS_SOFTWARE_COMPOSITOR) bool CefBrowserPlatformDelegate::WebPageSnapshot( const char* id, diff --git a/libcef/browser/browser_platform_delegate.h b/libcef/browser/browser_platform_delegate.h index fdb652144..ec61a09d7 100644 --- a/libcef/browser/browser_platform_delegate.h +++ b/libcef/browser/browser_platform_delegate.h @@ -467,6 +467,7 @@ class CefBrowserPlatformDelegate { int32_t height, double keyboard) {} virtual bool ShouldVirtualKeyboardOverlay() { return false; } + virtual void OnNativeEmbedLifecycleChange( const CefRenderHandler::CefNativeEmbedData& info) {} virtual void OnNativeEmbedVisibilityChange( @@ -480,19 +481,20 @@ class CefBrowserPlatformDelegate { virtual int GetShrinkViewportHeight(); #endif -#ifdef OHOS_DISPLAY_CUTOUT - virtual void OnSafeInsetsChange(int left, int top, int right, int bottom); -#endif - #ifdef OHOS_AI virtual void CreateOverlay(const gfx::ImageSkia& image, const gfx::Rect& image_rect, const gfx::Point& touch_point, const gfx::Rect& screen_rect); virtual void OnTextSelected(bool flag); + virtual void OnDestroyImageAnalyzerOverlay(); virtual float GetPageScaleFactor(); #endif +#ifdef OHOS_DISPLAY_CUTOUT + virtual void OnSafeInsetsChange(int left, int top, int right, int bottom); +#endif + #if defined(OHOS_SOFTWARE_COMPOSITOR) virtual bool WebPageSnapshot(const char* id, int width, diff --git a/libcef/browser/chrome/chrome_content_browser_client_cef.cc b/libcef/browser/chrome/chrome_content_browser_client_cef.cc index b875ed946..055b3f1d8 100644 --- a/libcef/browser/chrome/chrome_content_browser_client_cef.cc +++ b/libcef/browser/chrome/chrome_content_browser_client_cef.cc @@ -170,7 +170,7 @@ void ChromeContentBrowserClientCef::AllowCertificateError( #ifdef OHOS_NETWORK_LOAD auto returned_callback = certificate_query::AllowAllCertificateError( web_contents, cert_error, ssl_info, request_url, is_main_frame_request, - strict_enforcement, + strict_enforcement, origin_url, referrer, std::move(callback), /*default_disallow=*/false @@ -178,7 +178,7 @@ void ChromeContentBrowserClientCef::AllowCertificateError( #else auto returned_callback = certificate_query::AllowCertificateError( web_contents, cert_error, ssl_info, request_url, is_main_frame_request, - strict_enforcement, + strict_enforcement, std::move(callback), /*default_disallow=*/false ); #endif diff --git a/libcef/browser/context.cc b/libcef/browser/context.cc index 495c0e521..308d5dc82 100644 --- a/libcef/browser/context.cc +++ b/libcef/browser/context.cc @@ -486,15 +486,15 @@ void CefSetDownloadHandler(CefRefPtr download_handler) { #endif // OHOS_EX_DOWNLOAD } -CefRefPtr CefGetDownloadItem(const std::string& guid){ +CefRefPtr CefGetDownloadItem(const std::string& guid) { LOG(DEBUG) << "get download item for " << guid; - for(auto& context: CefBrowserContext::GetAll()){ + for (auto& context: CefBrowserContext::GetAll()) { content::DownloadManager* manager = context->AsBrowserContext()->GetDownloadManager(); - if(!manager){ + if (!manager) { continue; } download::DownloadItem* item = manager->GetDownloadByGuid(guid); - if(item){ + if (item) { CefRefPtr download_item( new CefDownloadItemImpl(item)); return download_item; @@ -688,6 +688,10 @@ void CefContext::PopulateGlobalRequestContextSettings( #if defined(OHOS_INCOGNITO_MODE) settings->incognito_mode = false; #endif + +#if defined(OHOS_ARKWEB_EXTENSIONS) + settings->global_request_context = nullptr; +#endif } #if defined(OHOS_INCOGNITO_MODE) @@ -704,6 +708,10 @@ void CefContext::PopulateGlobalOTRRequestContextSettings( settings->cookieable_schemes_exclude_defaults = settings_.cookieable_schemes_exclude_defaults; settings->incognito_mode = true; + +#if defined(OHOS_ARKWEB_EXTENSIONS) + settings->global_request_context = nullptr; +#endif } #endif diff --git a/libcef/browser/download_manager_delegate.cc b/libcef/browser/download_manager_delegate.cc index 29255524a..44d8e4817 100644 --- a/libcef/browser/download_manager_delegate.cc +++ b/libcef/browser/download_manager_delegate.cc @@ -53,9 +53,9 @@ class CefBeforeDownloadCallbackImpl : public CefBeforeDownloadCallback { suggested_name_(suggested_name), callback_(std::move(callback)) { #if defined(OHOS_EX_DOWNLOAD) - download_id_for_ohos_ = download_id; + download_id_for_ohos_ = download_id; #endif - } +} CefBeforeDownloadCallbackImpl(const CefBeforeDownloadCallbackImpl&) = delete; CefBeforeDownloadCallbackImpl& operator=( @@ -462,10 +462,12 @@ void CefDownloadManagerDelegate::OnDownloadCreated(DownloadManager* manager, // associated WebContents and consequently no associated CEF browser. In // that case DetermineDownloadTarget will be called before this method. // TODO(cef): Figure out how to expose this via a client callback. +#if !defined(OHOS_EX_DOWNLOAD) const std::vector& url_chain = item->GetUrlChain(); if (!url_chain.empty()) { LOG(INFO) << "Rejected download of " << url_chain.back().spec(); } +#endif #if defined(OHOS_EX_DOWNLOAD) // When download item not has associated browser, do not cancel the download item. #else diff --git a/libcef/browser/extensions/api/tabs/tabs_api.cc b/libcef/browser/extensions/api/tabs/tabs_api.cc index 8da799d3b..eb6f44661 100644 --- a/libcef/browser/extensions/api/tabs/tabs_api.cc +++ b/libcef/browser/extensions/api/tabs/tabs_api.cc @@ -212,6 +212,9 @@ bool TabsUpdateFunction::UpdateURL(const std::string& url_string, return false; } +#if defined(OHOS_ARKWEB_EXTENSIONS) + web_contents_->WebExtensionUpdateTabUrl(tab_id, url); +#else content::NavigationController::LoadURLParams load_params(url); // Treat extension-initiated navigations as renderer-initiated so that the URL @@ -234,7 +237,7 @@ bool TabsUpdateFunction::UpdateURL(const std::string& url_string, DCHECK_EQ(url, web_contents_->GetController().GetPendingEntry()->GetVirtualURL()); - +#endif return true; } @@ -545,5 +548,31 @@ ExtensionFunction::ResponseAction TabsGetZoomSettingsFunction::Run() { ArgumentList(api::tabs::GetZoomSettings::Results::Create(zoom_settings))); } +#if defined(OHOS_ARKWEB_EXTENSIONS) +ExtensionFunction::ResponseAction TabsReloadFunction::Run() { + absl::optional params = + tabs::Reload::Params::Create(args()); + EXTENSION_FUNCTION_VALIDATE(params); + + bool bypass_cache = false; + if (params->reload_properties && params->reload_properties->bypass_cache) { + bypass_cache = *params->reload_properties->bypass_cache; + } + + int tab_id = params->tab_id ? *params->tab_id : -1; + content::WebContents* web_contents = GetWebContents(tab_id); + if (!web_contents) { + return RespondNow(Error(std::move(error_))); + } + + web_contents->GetController().Reload( + bypass_cache ? content::ReloadType::BYPASSING_CACHE + : content::ReloadType::NORMAL, + true); + + return RespondNow(NoArguments()); +} +#endif + } // namespace cef } // namespace extensions diff --git a/libcef/browser/extensions/api/tabs/tabs_api.h b/libcef/browser/extensions/api/tabs/tabs_api.h index 409d758db..cc7bf54a9 100644 --- a/libcef/browser/extensions/api/tabs/tabs_api.h +++ b/libcef/browser/extensions/api/tabs/tabs_api.h @@ -181,6 +181,15 @@ class TabsGetZoomSettingsFunction : public BaseAPIFunction { DECLARE_EXTENSION_FUNCTION("tabs.getZoomSettings", TABS_GETZOOMSETTINGS) }; +#if defined(OHOS_ARKWEB_EXTENSIONS) +class TabsReloadFunction : public BaseAPIFunction { +private: + ~TabsReloadFunction() override {} + ResponseAction Run() override; + DECLARE_EXTENSION_FUNCTION("tabs.reload", TABS_RELOAD) +}; +#endif + } // namespace cef } // namespace extensions diff --git a/libcef/browser/extensions/api/tabs/tabs_event_router.cc b/libcef/browser/extensions/api/tabs/tabs_event_router.cc new file mode 100644 index 000000000..a0e13ba1a --- /dev/null +++ b/libcef/browser/extensions/api/tabs/tabs_event_router.cc @@ -0,0 +1,164 @@ +// Copyright 2013 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/browser/extensions/api/tabs/tabs_event_router.h" + +#include + +#include +#include +#include + +#include "base/functional/bind.h" +#include "chrome/browser/extensions/api/tabs/tabs_constants.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/common/extensions/extension_constants.h" +#include "content/public/browser/browser_context.h" +#include "content/public/browser/favicon_status.h" +#include "content/public/browser/navigation_entry.h" +#include "content/public/browser/render_process_host.h" +#include "content/public/browser/web_contents.h" +#include "extensions/common/features/feature.h" +#include "extensions/common/mojom/event_dispatcher.mojom-forward.h" +#include "third_party/abseil-cpp/absl/types/optional.h" +#include "ui/gfx/geometry/size.h" + +using base::Value; +using content::WebContents; + +namespace extensions { +namespace cef{ +namespace { + +bool HasValidMainFrameProcess(content::WebContents* contents) { + content::RenderFrameHost* main_frame_host = contents->GetPrimaryMainFrame(); + content::RenderProcessHost* process_host = main_frame_host->GetProcess(); + return process_host->IsReady() && process_host->IsInitializedAndNotDead(); +} + +api::tabs::TabStatus GetLoadingStatus(WebContents* contents) { + if (contents->IsLoading()) + return api::tabs::TAB_STATUS_LOADING; + + // Anything that isn't backed by a process is considered unloaded. + if (!HasValidMainFrameProcess(contents)) + return api::tabs::TAB_STATUS_UNLOADED; + + // Otherwise its considered loaded. + return api::tabs::TAB_STATUS_COMPLETE; +} + +api::tabs::MutedInfo CreateMutedInfo( + content::WebContents* contents) { + DCHECK(contents); + api::tabs::MutedInfo info; + info.muted = contents->IsAudioMuted(); + return info; +} + +api::tabs::Tab CreateTabObject( + int tab_id, + WebContents* contents, + const std::string& url) { + api::tabs::Tab tab_object; + tab_object.id = tab_id; + tab_object.index = -1; + tab_object.window_id = -1; + tab_object.status = GetLoadingStatus(contents); + tab_object.active = false; + tab_object.selected = false; + tab_object.highlighted = false; + tab_object.pinned = false; + tab_object.group_id = -1; + tab_object.audible = false; + tab_object.discarded = false; + tab_object.auto_discardable = false; + tab_object.muted_info = CreateMutedInfo(contents); + tab_object.incognito = contents->GetBrowserContext()->IsOffTheRecord(); + gfx::Size contents_size = contents->GetContainerBounds().size(); + tab_object.width = contents_size.width(); + tab_object.height = contents_size.height(); + tab_object.url = url.length() > 0 ? url : + contents->GetLastCommittedURL().spec(); + + content::NavigationEntry* pending_entry = + contents->GetController().GetPendingEntry(); + if (pending_entry) { + tab_object.pending_url = pending_entry->GetVirtualURL().spec(); + } + tab_object.title = base::UTF16ToUTF8(contents->GetTitle()); + content::NavigationEntry* visible_entry = + contents->GetController().GetVisibleEntry(); + if (visible_entry && visible_entry->GetFavicon().valid) { + tab_object.fav_icon_url = visible_entry->GetFavicon().url.spec(); + } + return tab_object; +} + +bool WillDispatchTabUpdatedEvent( + int tab_id, + WebContents* contents, + std::string url, + const std::vector changed_property_names, + content::BrowserContext* browser_context, + Feature::Context target_context, + const Extension* extension, + const base::Value::Dict* listener_filter, + absl::optional& event_args_out, + mojom::EventFilteringInfoPtr& event_filtering_info_out) { + api::tabs::Tab tab_object = CreateTabObject(tab_id, contents, url); + + base::Value::Dict tab_value = tab_object.ToValue(); + + base::Value::Dict changed_properties; + for (const auto& property : changed_property_names) { + if (const base::Value* value = tab_value.Find(property)) { + changed_properties.Set(property, value->Clone()); + } + } + + event_args_out.emplace(); + event_args_out->Append(tab_id); + event_args_out->Append(std::move(changed_properties)); + event_args_out->Append(std::move(tab_value)); + return true; +} + +} // namespace + +TabsEventRouter::TabsEventRouter(Profile* profile) : profile_(profile) { + DCHECK(!profile->IsOffTheRecord()); +} + +TabsEventRouter::~TabsEventRouter() {} + +void TabsEventRouter::DispatchTabUpdatedEvent( + int tab_id, + WebContents* contents, + const std::vector& changed_property_names, + const std::string& url) { + DCHECK(!changed_property_names.empty()); + DCHECK(contents); + + std::vector changes = changed_property_names; + if (url.length() > 0) { + changes.push_back(tabs_constants::kStatusKey); + } + + Profile* profile = Profile::FromBrowserContext(contents->GetBrowserContext()); + + auto event = std::make_unique( + events::TABS_ON_UPDATED, api::tabs::OnUpdated::kEventName, + // The event arguments depend on the extension's permission. They are set + // in WillDispatchTabUpdatedEvent(). + base::Value::List(), profile); + event->user_gesture = EventRouter::USER_GESTURE_NOT_ENABLED; + event->will_dispatch_callback = + base::BindRepeating(&WillDispatchTabUpdatedEvent, tab_id, + contents, url, std::move(changes)); + EventRouter::Get(profile)->BroadcastEvent(std::move(event)); +} + +} // namespace cef +} // namespace extensions diff --git a/libcef/browser/extensions/api/tabs/tabs_event_router.h b/libcef/browser/extensions/api/tabs/tabs_event_router.h new file mode 100644 index 000000000..0790c7a49 --- /dev/null +++ b/libcef/browser/extensions/api/tabs/tabs_event_router.h @@ -0,0 +1,55 @@ +// Copyright 2013 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_EXTENSIONS_API_TABS_TABS_EVENT_ROUTER_H_ +#define CEF_LIBCEF_BROWSER_EXTENSIONS_API_TABS_TABS_EVENT_ROUTER_H_ + +#include +#include +#include + +#include "base/memory/raw_ptr.h" +#include "base/scoped_multi_source_observation.h" +#include "base/scoped_observation.h" +#include "libcef/browser/extensions/api/tabs/tabs_api.h" +#include "content/public/browser/web_contents_observer.h" +#include "extensions/browser/event_router.h" + +namespace content { +class WebContents; +} + +namespace extensions { +namespace cef { + +// The TabsEventRouter listens to tab events and routes them to listeners inside +// extension process renderers. +// TabsEventRouter will only route events from windows/tabs within a profile to +// extension processes in the same profile. +class TabsEventRouter { + public: + explicit TabsEventRouter(Profile* profile); + + TabsEventRouter(const TabsEventRouter&) = delete; + TabsEventRouter& operator=(const TabsEventRouter&) = delete; + + ~TabsEventRouter(); + + // Packages |changed_property_names| as a tab updated event for the tab + // |contents| and dispatches the event to the extension. + void DispatchTabUpdatedEvent( + int tab_id, + content::WebContents* contents, + const std::vector& changed_property_names, + const std::string& url); + + private: + // The main profile that owns this event router. + raw_ptr profile_; +}; + +} // namespace cef +} // namespace extensions + +#endif // CEF_LIBCEF_BROWSER_EXTENSIONS_API_TABS_TABS_EVENT_ROUTER_H_ diff --git a/libcef/browser/extensions/api/tabs/tabs_windows_api.cc b/libcef/browser/extensions/api/tabs/tabs_windows_api.cc new file mode 100644 index 000000000..84ecafe99 --- /dev/null +++ b/libcef/browser/extensions/api/tabs/tabs_windows_api.cc @@ -0,0 +1,93 @@ +// Copyright 2012 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/browser/extensions/api/tabs/tabs_windows_api.h" + +#include + +#include "base/lazy_instance.h" +#include "chrome/browser/profiles/profile.h" +#include "libcef/browser/extensions/api/tabs/tabs_event_router.h" +#include "libcef/browser/extensions/api/tabs/tabs_api.h" +#include "extensions/browser/event_router.h" +#include "extensions/browser/extension_system.h" + +namespace extensions { +namespace cef { + +TabsWindowsAPI::TabsWindowsAPI(content::BrowserContext* context) + : browser_context_(context) { + EventRouter* event_router = EventRouter::Get(browser_context_); + + // Register these events' observer for initialize tabs_event_router. + // Tabs API Events. + event_router->RegisterObserver(this, api::tabs::OnCreated::kEventName); + event_router->RegisterObserver(this, api::tabs::OnUpdated::kEventName); + event_router->RegisterObserver(this, api::tabs::OnMoved::kEventName); + event_router->RegisterObserver(this, + api::tabs::OnSelectionChanged::kEventName); + event_router->RegisterObserver(this, api::tabs::OnActiveChanged::kEventName); + event_router->RegisterObserver(this, api::tabs::OnActivated::kEventName); + event_router->RegisterObserver(this, + api::tabs::OnHighlightChanged::kEventName); + event_router->RegisterObserver(this, api::tabs::OnHighlighted::kEventName); + event_router->RegisterObserver(this, api::tabs::OnDetached::kEventName); + event_router->RegisterObserver(this, api::tabs::OnAttached::kEventName); + event_router->RegisterObserver(this, api::tabs::OnRemoved::kEventName); + event_router->RegisterObserver(this, api::tabs::OnReplaced::kEventName); + event_router->RegisterObserver(this, api::tabs::OnZoomChange::kEventName); + + // Windows API Events. + event_router->RegisterObserver(this, api::windows::OnCreated::kEventName); + event_router->RegisterObserver(this, api::windows::OnRemoved::kEventName); + event_router->RegisterObserver(this, + api::windows::OnFocusChanged::kEventName); + event_router->RegisterObserver(this, + api::windows::OnBoundsChanged::kEventName); +} + +TabsWindowsAPI::~TabsWindowsAPI() { +} + +// static +TabsWindowsAPI* TabsWindowsAPI::Get(content::BrowserContext* context) { + return BrowserContextKeyedAPIFactory::Get(context); +} + +TabsEventRouter* TabsWindowsAPI::tabs_event_router() { + if (!tabs_event_router_.get()) { + tabs_event_router_ = std::make_unique( + Profile::FromBrowserContext(browser_context_)); + } + return tabs_event_router_.get(); +} + +void TabsWindowsAPI::TabUpdated(int tab_id, + content::WebContents* contents, + const std::vector& changed_property_names, + const std::string& url) { + tabs_event_router()->DispatchTabUpdatedEvent( + tab_id, contents, changed_property_names, url); +} + +void TabsWindowsAPI::Shutdown() { + EventRouter::Get(browser_context_)->UnregisterObserver(this); +} + +static base::LazyInstance>:: + DestructorAtExit g_tabs_windows_api_factory = LAZY_INSTANCE_INITIALIZER; + +BrowserContextKeyedAPIFactory* +TabsWindowsAPI::GetFactoryInstance() { + return g_tabs_windows_api_factory.Pointer(); +} + +void TabsWindowsAPI::OnListenerAdded(const EventListenerInfo& details) { + // Initialize the event routers. + tabs_event_router(); + EventRouter::Get(browser_context_)->UnregisterObserver(this); +} + +} // namespace cef +} // namespace extensions diff --git a/libcef/browser/extensions/api/tabs/tabs_windows_api.h b/libcef/browser/extensions/api/tabs/tabs_windows_api.h new file mode 100644 index 000000000..acc721239 --- /dev/null +++ b/libcef/browser/extensions/api/tabs/tabs_windows_api.h @@ -0,0 +1,62 @@ +// Copyright 2012 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_EXTENSIONS_API_TABS_TABS_WINDOWS_API_H_ +#define CEF_LIBCEF_BROWSER_EXTENSIONS_API_TABS_TABS_WINDOWS_API_H_ + +#include + +#include "base/memory/raw_ptr.h" +#include "components/keyed_service/core/keyed_service.h" +#include "content/public/browser/web_contents.h" +#include "extensions/browser/browser_context_keyed_api_factory.h" +#include "extensions/browser/event_router.h" + +namespace extensions { +namespace cef { + +class TabsEventRouter; + +class TabsWindowsAPI : public BrowserContextKeyedAPI, + public EventRouter::Observer { + public: + explicit TabsWindowsAPI(content::BrowserContext* context); + ~TabsWindowsAPI() override; + + // Convenience method to get the TabsWindowsAPI for a profile. + static TabsWindowsAPI* Get(content::BrowserContext* context); + + TabsEventRouter* tabs_event_router(); + + // KeyedService implementation. + void Shutdown() override; + + // BrowserContextKeyedAPI implementation. + static BrowserContextKeyedAPIFactory* GetFactoryInstance(); + + // EventRouter::Observer implementation. + void OnListenerAdded(const extensions::EventListenerInfo& details) override; + + void TabUpdated(int tab_id, + content::WebContents* contents, + const std::vector& changed_property_names, + const std::string& url); + + private: + friend class BrowserContextKeyedAPIFactory; + + raw_ptr browser_context_; + + // BrowserContextKeyedAPI implementation. + static const char* service_name() { + return "TabsWindowsAPI"; + } + + std::unique_ptr tabs_event_router_; +}; + +} // namespace cef +} // namespace extensions + +#endif // CEF_LIBCEF_BROWSER_EXTENSIONS_API_TABS_TABS_WINDOWS_API_H_ diff --git a/libcef/browser/extensions/browser_extensions_util.cc b/libcef/browser/extensions/browser_extensions_util.cc index 9a780e229..b495680bd 100644 --- a/libcef/browser/extensions/browser_extensions_util.cc +++ b/libcef/browser/extensions/browser_extensions_util.cc @@ -167,6 +167,37 @@ CefRefPtr GetBrowserForTabId( return nullptr; } +#if defined(OHOS_ARKWEB_EXTENSIONS) +/* + * Sometimes the extension function is called from background script, and it's + * windowless AlloyBrowser does not have a client or handler. + * Try to get an AlloyBrowserHostImpl with a non-null client, that means it has + * a nweb_handler can be used to interact with APP. + */ +CefRefPtr GetClientAvailableBrowser(int tab_id) { + for (const auto& browser_info : + CefBrowserInfoManager::GetInstance()->GetBrowserInfoList()) { + CefRefPtr current_browser = + static_cast(browser_info->browser().get()); + if (current_browser && + current_browser->GetTabId() == tab_id && tab_id >= 0) { + return current_browser; + } + } + + for (const auto& browser_info : + CefBrowserInfoManager::GetInstance()->GetBrowserInfoList()) { + CefRefPtr current_browser = + static_cast(browser_info->browser().get()); + if (current_browser && + current_browser->web_contents() && current_browser->client()) { + return current_browser; + } + } + return nullptr; +} +#endif + const Extension* GetExtensionForUrl(content::BrowserContext* browser_context, const GURL& url) { ExtensionRegistry* registry = ExtensionRegistry::Get(browser_context); diff --git a/libcef/browser/extensions/browser_extensions_util.h b/libcef/browser/extensions/browser_extensions_util.h index b4adb7baf..12c3cf384 100644 --- a/libcef/browser/extensions/browser_extensions_util.h +++ b/libcef/browser/extensions/browser_extensions_util.h @@ -53,6 +53,16 @@ CefRefPtr GetOwnerBrowserForHost( content::RenderFrameHost* host, bool* is_guest_view); +#if defined(OHOS_ARKWEB_EXTENSIONS) +/* + * Sometimes the extension function is called from background script, and it's + * windowless AlloyBrowser does not have a client or handler. + * Try to get an AlloyBrowserHostImpl with a non-null client, that means it has + * a nweb_handler can be used to interact with APP. + */ +CefRefPtr GetClientAvailableBrowser(int tab_id); +#endif + // Returns the browser matching |tab_id| and |browser_context|. Returns false if // |tab_id| is < 0 or a matching browser cannot be found within // |browser_context|. Similar in concept to ExtensionTabUtil::GetTabById. diff --git a/libcef/browser/extensions/chrome_api_registration.cc b/libcef/browser/extensions/chrome_api_registration.cc index f3853f3e7..ec8821cba 100644 --- a/libcef/browser/extensions/chrome_api_registration.cc +++ b/libcef/browser/extensions/chrome_api_registration.cc @@ -66,6 +66,14 @@ const char* const kSupportedAPIs[] = { EXTENSION_FUNCTION_NAME(cefimpl::TabsGetZoomFunction), EXTENSION_FUNCTION_NAME(cefimpl::TabsSetZoomSettingsFunction), EXTENSION_FUNCTION_NAME(cefimpl::TabsGetZoomSettingsFunction), +#if defined(OHOS_ARKWEB_EXTENSIONS) + EXTENSION_FUNCTION_NAME(cefimpl::TabsReloadFunction), +#endif +#if defined(OHOS_ARKWEB_EXTENSIONS) + // chrome.extension.getURL()'s implementation is in the renderer. + "extension", + "extension.getURL", +#endif #if defined(OHOS_ARKWEB_EXTENSIONS) "developerPrivate", EXTENSION_FUNCTION_NAME(DeveloperPrivateGetExtensionsInfoFunction), @@ -153,6 +161,7 @@ void ChromeFunctionRegistry::RegisterAll(ExtensionFunctionRegistry* registry) { registry->RegisterFunction(); registry->RegisterFunction(); registry->RegisterFunction(); + registry->RegisterFunction(); #endif } diff --git a/libcef/browser/extensions/component_extension_resource_manager.cc b/libcef/browser/extensions/component_extension_resource_manager.cc index d8ec4f421..627ec7e5f 100644 --- a/libcef/browser/extensions/component_extension_resource_manager.cc +++ b/libcef/browser/extensions/component_extension_resource_manager.cc @@ -32,7 +32,7 @@ CefComponentExtensionResourceManager::CefComponentExtensionResourceManager() { bool enable_printing = true; #if BUILDFLAG(IS_OHOS) - // The printing service is temporarily not supported on mobile device. + // The printing service is temporarily supported on pc device. enable_printing = (*base::CommandLine::ForCurrentProcess()).HasSwitch( switches::kEnablePrinting); #endif diff --git a/libcef/browser/extensions/extension_function_details.cc b/libcef/browser/extensions/extension_function_details.cc index efed281fb..60fc48a8e 100644 --- a/libcef/browser/extensions/extension_function_details.cc +++ b/libcef/browser/extensions/extension_function_details.cc @@ -222,6 +222,17 @@ CefExtensionFunctionDetails::GetBrowserForTabIdFirstTime( CefRefPtr browser; +#if defined(OHOS_ARKWEB_EXTENSIONS) + // TODO: The mapping between tab_id and nweb_id should be supported. + // tab_id <-> nweb_id <-> browser_id <-> web_contents + browser = GetClientAvailableBrowser(tab_id); + if (browser) { + LOG(INFO) << "Found a client available browser for " << function_->name() + << " interact with tab()" << tab_id << ")"; + return browser; + } +#endif + if (tab_id >= 0) { // May be an invalid tabId or in the wrong BrowserContext. browser = GetBrowserForTabId(tab_id, function_->browser_context()); diff --git a/libcef/browser/extensions/extension_host_delegate.cc b/libcef/browser/extensions/extension_host_delegate.cc index 6720ea23a..529dae50a 100644 --- a/libcef/browser/extensions/extension_host_delegate.cc +++ b/libcef/browser/extensions/extension_host_delegate.cc @@ -10,6 +10,12 @@ #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_delegate.h" +#if defined(OHOS_ARKWEB_EXTENSIONS) +#include "chrome/browser/extensions/extension_service.h" +#include "extensions/browser/extension_host.h" +#include "extensions/browser/extension_system.h" +#endif + namespace extensions { CefExtensionHostDelegate::CefExtensionHostDelegate( @@ -21,7 +27,15 @@ void CefExtensionHostDelegate::OnExtensionHostCreated( content::WebContents* web_contents) {} void CefExtensionHostDelegate::OnMainFrameCreatedForBackgroundPage( - ExtensionHost* host) {} + ExtensionHost* host) { +#if defined(OHOS_ARKWEB_EXTENSIONS) + // Start connect devtools + ExtensionService* service = + ExtensionSystem::Get(host->browser_context())->extension_service(); + if (service) + service->DidCreateMainFrameForBackgroundPage(host); +#endif +} content::JavaScriptDialogManager* CefExtensionHostDelegate::GetJavaScriptDialogManager() { diff --git a/libcef/browser/extensions/extension_system.cc b/libcef/browser/extensions/extension_system.cc index c57e4ecff..13c421190 100644 --- a/libcef/browser/extensions/extension_system.cc +++ b/libcef/browser/extensions/extension_system.cc @@ -54,6 +54,7 @@ #if defined(OHOS_ARKWEB_EXTENSIONS) #include "base/base_switches.h" #include "base/command_line.h" +#include "cef/libcef/common/app_manager.h" #include "chrome/browser/extensions/chrome_app_sorting.h" #include "chrome/browser/extensions/chrome_content_verifier_delegate.h" #include "chrome/browser/extensions/component_loader.h" @@ -201,6 +202,9 @@ CefExtensionSystem::CefExtensionSystem(BrowserContext* browser_context) renderer_helper_( extensions::RendererStartupHelperFactory::GetForBrowserContext( browser_context)), +#if defined(OHOS_ARKWEB_EXTENSIONS) + global_request_context_(nullptr), +#endif weak_ptr_factory_(this) { InitPrefs(); } @@ -217,7 +221,7 @@ void CefExtensionSystem::Init() { profile, base::CommandLine::ForCurrentProcess(), profile->GetPath().AppendASCII(extensions::kInstallDirectoryName), profile->GetPath().AppendASCII(extensions::kUnpackedInstallDirectoryName), - ExtensionPrefs::Get(profile), Blocklist::Get(profile), false, true, + ExtensionPrefs::Get(profile), Blocklist::Get(profile), true, true, &ready_); #endif // There's complexity here related to the ordering of message delivery. For @@ -780,6 +784,63 @@ void CefExtensionSystem::UnloadExtension(const std::string& extension_id, } #if defined(OHOS_ARKWEB_EXTENSIONS) +void CefExtensionSystem::SetGlobalRequestContext(CefRequestContext* context) { + if (!global_request_context_) { + global_request_context_ = context; + } +} + +// Originally, Cef only supported loading Extensions through cef' api interfaces +// and creating CefExtension. Now it supports loading extensions from internal +// enterprise policies and extension management interfaces. This type of loading +// is not loaded through Cef's LoadExtension interface, so CefExtension is not +// created, resulting in no background script running environment. +void CefExtensionSystem::NotifyExtensionLoadedFromInternal( + const Extension* extension) { + if (!extension || GetExtension(extension->id())) { + // Extension invalid or CefExtension already added. + return; + } + + CefRefPtr context = CefRequestContext::GetGlobalContext(); + if (!context) { + // CefRequestContext::GetGlobalContext will be null at startup during + // CefRequestContextImpl::CreateGlobalRequestContext + // -> CefRequestContextImpl::Initialize() + // -> AlloyMainDelegate::CreateNewBrowserContext() + // -> AlloyBrowserContext::Initialize() + // -> ExtensionSystem::Init() + // -> ExtensionService::Init() + // -> component_loader_->LoadAll()/ + // -> InstalledLoader(this).LoadAllExtensions() + // But the CefRequestContext is an essential member in + // CefBrowserCreateParams during + // CefExtensionsBrowserClient::CreateBackgroundExtensionHost(). + context = global_request_context_; + } + + CefRefPtr cef_extension = + new CefExtensionImpl( + extension, context ? context.get() : nullptr, nullptr); + extension_map_.insert(std::make_pair(extension->id(), cef_extension)); +} + +void CefExtensionSystem::NotifyExtensionUnLoadedFromInternal( + const Extension* extension) { + if (!extension || !GetExtension(extension->id())) { + // Extension invalid or CefExtension already removed. + return; + } + + ExtensionMap::iterator it = extension_map_.find(extension->id()); + if (it == extension_map_.end()) { + // No CEF representation so we've already unloaded it. + return; + } + + extension_map_.erase(it); +} + void CefExtensionSystem::MaybeSpinUpLazyContext(const Extension* extension, bool is_newly_added) { DCHECK(BackgroundInfo::HasLazyContext(extension)); diff --git a/libcef/browser/extensions/extension_system.h b/libcef/browser/extensions/extension_system.h index fc17052f9..fd774a6c1 100644 --- a/libcef/browser/extensions/extension_system.h +++ b/libcef/browser/extensions/extension_system.h @@ -120,6 +120,10 @@ class CefExtensionSystem : public ExtensionSystem { bool initialized() const { return initialized_; } +#if defined(OHOS_ARKWEB_EXTENSIONS) + void SetGlobalRequestContext(CefRequestContext* context); +#endif + private: virtual void InitPrefs(); @@ -161,6 +165,10 @@ class CefExtensionSystem : public ExtensionSystem { #if defined(OHOS_ARKWEB_EXTENSIONS) void InitInstallGates(); void MaybeSpinUpLazyContext(const Extension* extension, bool is_newly_added); + void NotifyExtensionLoadedFromInternal( + const Extension* extension) override; + void NotifyExtensionUnLoadedFromInternal( + const Extension* extension) override; #endif content::BrowserContext* browser_context_; // Not owned. @@ -200,6 +208,8 @@ class CefExtensionSystem : public ExtensionSystem { // For verifying the contents of extensions read from disk. scoped_refptr content_verifier_; std::unique_ptr uninstall_ping_sender_; + + CefRefPtr global_request_context_; #endif // Must be the last member. diff --git a/libcef/browser/extensions/extensions_browser_client.cc b/libcef/browser/extensions/extensions_browser_client.cc index 00f270408..487f72ca4 100644 --- a/libcef/browser/extensions/extensions_browser_client.cc +++ b/libcef/browser/extensions/extensions_browser_client.cc @@ -274,6 +274,7 @@ bool CefExtensionsBrowserClient::CreateBackgroundExtensionHost( cef_browser_context->GetExtension(extension->id()); DCHECK(cef_extension); if (!cef_extension) { + LOG(INFO) << "Cancel the background host creation :" << extension->id(); // Cancel the background host creation. return true; } @@ -283,6 +284,7 @@ bool CefExtensionsBrowserClient::CreateBackgroundExtensionHost( CefRefPtr request_context = cef_extension->GetLoaderContext(); if (!request_context) { + LOG(INFO) << "request_context empty for :" << extension->id(); // Cancel the background host creation. return true; } @@ -309,6 +311,7 @@ bool CefExtensionsBrowserClient::CreateBackgroundExtensionHost( AlloyBrowserHostImpl::Create(create_params); if (browser) { *host = browser->GetExtensionHost(); + LOG(INFO) << "Background extension host created for :" << extension->id(); DCHECK(*host); } return true; diff --git a/libcef/browser/first_meaningful_paint_details_impl.cc b/libcef/browser/first_meaningful_paint_details_impl.cc index 940700c48..cfcdb1713 100644 --- a/libcef/browser/first_meaningful_paint_details_impl.cc +++ b/libcef/browser/first_meaningful_paint_details_impl.cc @@ -16,4 +16,4 @@ int64_t CefFirstMeaningfulPaintDetailsImpl::GetNavigationStartTime() { int64_t CefFirstMeaningfulPaintDetailsImpl::GetFirstMeaningfulPaintTime() { return firstMeaningfulPaintTime_; -} +} \ No newline at end of file diff --git a/libcef/browser/first_meaningful_paint_details_impl.h b/libcef/browser/first_meaningful_paint_details_impl.h index b66902c6a..4ff88f97b 100644 --- a/libcef/browser/first_meaningful_paint_details_impl.h +++ b/libcef/browser/first_meaningful_paint_details_impl.h @@ -30,4 +30,4 @@ class CefFirstMeaningfulPaintDetailsImpl: public CefFirstMeaningfulPaintDetails IMPLEMENT_REFCOUNTING(CefFirstMeaningfulPaintDetailsImpl); }; -#endif // CEF_LIBCEF_BROWSER_FIRST_MEANINGFUL_PAINT_DETAILS_IMPL_H_ +#endif // CEF_LIBCEF_BROWSER_FIRST_MEANINGFUL_PAINT_DETAILS_IMPL_H_ \ No newline at end of file diff --git a/libcef/browser/frame_host_impl.cc b/libcef/browser/frame_host_impl.cc index 5853228b9..9a2fe4cff 100644 --- a/libcef/browser/frame_host_impl.cc +++ b/libcef/browser/frame_host_impl.cc @@ -22,6 +22,7 @@ #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "services/service_manager/public/cpp/interface_provider.h" +#include "base/strings/escape.h" #if BUILDFLAG(IS_OHOS) #include "content/public/browser/browsing_data_remover.h" @@ -32,6 +33,10 @@ #include "third_party/skia/include/core/SkImage.h" #endif // BUILDFLAG(IS_OHOS) +#ifdef OHOS_CLIPBOARD +#include "skia/ext/image_operations.h" +#endif + namespace { void StringVisitCallback(CefRefPtr visitor, @@ -78,6 +83,48 @@ void ExecWebContentsCommand(CefFrameHostImpl* fh, fh->SendCommand(command); } +#ifdef OHOS_CLIPBOARD +const int kMaxContextImageNodeSizeIfDownScale = 1024; + +bool NeedsDownScale(const gfx::Size& original_image_size) { + if (original_image_size.width() <= kMaxContextImageNodeSizeIfDownScale && + original_image_size.height() <= kMaxContextImageNodeSizeIfDownScale) { + return false; + } + LOG(DEBUG) << "The origin image size width: " << original_image_size.width() + << ", height: " << original_image_size.height(); + return true; +} + +SkBitmap DownScale(const SkBitmap& image) { + if (image.isNull()) { + return SkBitmap(); + } + + gfx::Size image_size(image.width(), image.height()); + if (!NeedsDownScale(image_size)) { + return image; + } + + gfx::SizeF scaled_size = gfx::SizeF(image_size); + + if (scaled_size.width() > kMaxContextImageNodeSizeIfDownScale) { + scaled_size.Scale(kMaxContextImageNodeSizeIfDownScale / + scaled_size.width()); + } + + if (scaled_size.height() > kMaxContextImageNodeSizeIfDownScale) { + scaled_size.Scale(kMaxContextImageNodeSizeIfDownScale / + scaled_size.height()); + } + + return skia::ImageOperations::Resize(image, + skia::ImageOperations::RESIZE_GOOD, + static_cast(scaled_size.width()), + static_cast(scaled_size.height())); +} +#endif + #define EXEC_WEBCONTENTS_COMMAND(name) \ ExecWebContentsCommand(this, &CefFrameHostImpl::name, \ &content::WebContents::name, #name); @@ -408,6 +455,11 @@ void CefFrameHostImpl::LoadURLWithExtras(const std::string& url, // Any necessary fixup will occur in LoadRequest. #ifdef OHOS_NETWORK_LOAD GURL gurl = url_util::FixupGURL(url); + if(gurl.SchemeIsFile()) { + std::string unscaped_url_str = base::UnescapeURLComponent(gurl.spec(), + base::UnescapeRule::URL_SPECIAL_CHARS_EXCEPT_PATH_SEPARATORS); + gurl = GURL(unscaped_url_str); + } #else GURL gurl = url_util::MakeGURL(url, /*fixup=*/false); #endif @@ -809,7 +861,7 @@ void CefFrameHostImpl::UpdateLocale(const CefString& locale) { #endif // #ifdef OHOS_I18N void CefFrameHostImpl::OnGetImageForContextNode( - cef::mojom::GetImageForContextNodeParamsPtr params) { + cef::mojom::GetImageForContextNodeParamsPtr params, int command_id) { CefImageImpl* image_impl = new (std::nothrow) CefImageImpl(); if (image_impl != nullptr && params->image.width() > 0 && params->image.height() > 0) { @@ -828,11 +880,11 @@ void CefFrameHostImpl::OnGetImageForContextNode( handler = client->GetContextMenuHandler(); } if (handler) { - handler->OnGetImageForContextNode(GetBrowser(), image); + handler->OnGetImageForContextNode(GetBrowser(), image, command_id); } } -void CefFrameHostImpl::OnGetImageForContextNodeNull() { +void CefFrameHostImpl::OnGetImageForContextNodeNull(int command_id) { CefRefPtr image(new CefImageImpl()); CefRefPtr handler = nullptr; auto browser = GetBrowserHostBase(); @@ -844,12 +896,13 @@ void CefFrameHostImpl::OnGetImageForContextNodeNull() { handler = client->GetContextMenuHandler(); } if (handler) { - handler->OnGetImageForContextNode(GetBrowser(), image); + handler->OnGetImageForContextNode(GetBrowser(), image, command_id); } } void CefFrameHostImpl::OnGetImageFromCache( std::string url, + int command_id, uint32_t buffer_size, base::ReadOnlySharedMemoryRegion region) { auto browser = GetBrowserHostBase(); @@ -870,27 +923,33 @@ void CefFrameHostImpl::OnGetImageFromCache( if (!region.IsValid()) { LOG(ERROR) << "OnGetImageFromCache: Read-only shared memory region is invalid"; - handler->OnGetImageFromCache(image_impl); + handler->OnGetImageFromCache(image_impl, command_id); return; } base::ReadOnlySharedMemoryMapping mapping = region.MapAt(0, buffer_size); if (!mapping.IsValid()) { LOG(ERROR) << "OnGetImageFromCache: Read-only shared memory mapping is invalid"; - handler->OnGetImageFromCache(image_impl); + handler->OnGetImageFromCache(image_impl, command_id); return; } uint8_t* buffer = (uint8_t*)(mapping.memory()); + sk_sp sk_data = SkData::MakeWithoutCopy(buffer, buffer_size); if (sk_data) { sk_sp sk_image = SkImages::DeferredFromEncodedData(sk_data); if (sk_image) { SkBitmap bitmap; sk_image->asLegacyBitmap(&bitmap); +#ifdef OHOS_CLIPBOARD + SkBitmap resize_image = DownScale(bitmap); + image_impl->AddBitmap(1.0, resize_image); +#else image_impl->AddBitmap(1.0, bitmap); +#endif } } - handler->OnGetImageFromCache(image_impl); + handler->OnGetImageFromCache(image_impl, command_id); } #ifdef OHOS_NETWORK_LOAD @@ -967,11 +1026,12 @@ void CefFrameHostImpl::SetJsOnlineProperty(bool network_up) { } #endif -void CefFrameHostImpl::GetImageForContextNode() { +void CefFrameHostImpl::GetImageForContextNode(int command_id) { SendToRenderFrame(__FUNCTION__, - base::BindOnce([](const RenderFrameType& render_frame) { - render_frame->GetImageForContextNode(); - })); + base::BindOnce([](int command_id, const RenderFrameType& render_frame) { + render_frame->GetImageForContextNode(command_id); + }, + command_id)); } void CefFrameHostImpl::PutZoomingForTextFactor(float factor) { @@ -1115,22 +1175,27 @@ void CefFrameHostImpl::SetScrollable(bool enable) { void CefFrameHostImpl::GetHitData(int& type, CefString& extra_data) { std::string temp_extra_data; - SendToRenderFrame(__FUNCTION__, - base::BindOnce( - [](int32_t* out_type, std::string* out_extra_data, - const RenderFrameType& render_frame) { - render_frame->GetHitData(out_type, out_extra_data); - }, - &type, &temp_extra_data)); + if (is_temporary()) { + extra_data = temp_extra_data; + return; + } else if (!render_frame_host_) { + extra_data = temp_extra_data; + return; + } + + if (!render_frame_.is_bound()) { + extra_data = temp_extra_data; + return; + } + render_frame_->GetHitData(&type, &temp_extra_data); extra_data = temp_extra_data; } void CefFrameHostImpl::UpdateDrawRect() { - SendToRenderFrame(__FUNCTION__, - base::BindOnce( - [](const RenderFrameType& render_frame) { - render_frame->UpdateDrawRect(); - })); + SendToRenderFrame(__FUNCTION__, base::BindOnce( + [](const RenderFrameType& render_frame) { + render_frame->UpdateDrawRect(); + })); } #endif // defined(OHOS_INPUT_EVENTS) diff --git a/libcef/browser/frame_host_impl.h b/libcef/browser/frame_host_impl.h index 62aefac5e..4cad8144f 100644 --- a/libcef/browser/frame_host_impl.h +++ b/libcef/browser/frame_host_impl.h @@ -178,6 +178,7 @@ class CefFrameHostImpl : public CefFrame, public cef::mojom::BrowserFrame { cef::mojom::BrowserFrame::ShouldOverrideUrlLoadingCallback callback) override; void OnGetImageFromCache(std::string url, + int command_id, uint32_t buffer_size, base::ReadOnlySharedMemoryRegion region); @@ -185,8 +186,8 @@ class CefFrameHostImpl : public CefFrame, public cef::mojom::BrowserFrame { void UpdateLocale(const CefString& locale); #endif // #ifdef OHOS_I18N void OnGetImageForContextNode( - cef::mojom::GetImageForContextNodeParamsPtr params) override; - void OnGetImageForContextNodeNull() override; + cef::mojom::GetImageForContextNodeParamsPtr params, int command_id) override; + void OnGetImageForContextNodeNull(int command_id) override; void LoadHeaderUrl(const CefString& url, const CefString& additionalHttpHeaders) override; // Send the touch point to the rederer to get hitdata. @@ -198,7 +199,7 @@ class CefFrameHostImpl : public CefFrame, public cef::mojom::BrowserFrame { void SetJsOnlineProperty(bool network_up); #endif - void GetImageForContextNode(); + void GetImageForContextNode(int command_id); // Sets the zoom factor for text only. Used in layout modes other than // Text Autosizing. diff --git a/libcef/browser/javascript/oh_gin_javascript_bridge_dispatcher_host.cc b/libcef/browser/javascript/oh_gin_javascript_bridge_dispatcher_host.cc index e70811b9c..ccddcdae2 100644 --- a/libcef/browser/javascript/oh_gin_javascript_bridge_dispatcher_host.cc +++ b/libcef/browser/javascript/oh_gin_javascript_bridge_dispatcher_host.cc @@ -80,6 +80,7 @@ OhGinJavascriptBridgeDispatcherHost::~OhGinJavascriptBridgeDispatcherHost() { javascript_sync_permission_map_.clear(); javascript_async_permission_map_.clear(); object_id_map_.clear(); + async_object_id_map_.clear(); } // Run on the UI thread. @@ -151,8 +152,7 @@ void OhGinJavascriptBridgeDispatcherHost::RenderFrameCreated( // sync_method_map_ has no async method infomation, so send an empty list. base::Value::List empty_list; render_frame_host->Send(new OhGinJavascriptBridgeMsg_AddNamedObject( - render_frame_host->GetRoutingID(), object_name, object_id, empty_list, - false)); + render_frame_host->GetRoutingID(), object_name, object_id, empty_list, false)); } } } @@ -377,6 +377,7 @@ void OhGinJavascriptBridgeDispatcherHost::AddNamedObjectForWebController( async_object_pair.first = object_name; async_object_pair.second = async_method_set; async_method_map_[object_id_] = async_object_pair; + async_object_id_map_[object_id_].insert(object_name); ParseJson(permission, object_id_, true); } @@ -430,6 +431,7 @@ void OhGinJavascriptBridgeDispatcherHost::AddNamedObjectForWebViewController( async_object_pair.first = object_name; async_object_pair.second = async_method_set; async_method_map_[object_id] = async_object_pair; + async_object_id_map_[object_id].insert(object_name); ParseJson(permission, object_id, true); } @@ -554,21 +556,23 @@ void OhGinJavascriptBridgeDispatcherHost::RemoveNamedObject( } bool OhGinJavascriptBridgeDispatcherHost::RemoveNamedObjectInternal( - const std::string& object_name, - bool is_async) { + const std::string& object_name, bool is_async) { + LOG(DEBUG) << "OhGinJavascriptBridgeDispatcherHost::RemoveNamedObjectInternal " + << "target object name: " << object_name; + auto& method_map = is_async ? async_method_map_ : sync_method_map_; bool ret = false; - auto& map = is_async ? async_method_map_ : sync_method_map_; - if (map.empty()) { - return ret = false; + if (method_map.empty()) { + return ret; } + auto& id_map = is_async ? async_object_id_map_ : object_id_map_; std::unique_lock lock(share_mutex_); - for (auto& [object_id, object_name_set] : object_id_map_) { + for (auto& [object_id, object_name_set] : id_map) { for (const std::string& now_object_name : object_name_set) { if (now_object_name == object_name) { object_name_set.erase(object_name); if (object_name_set.size() == 0) { - object_id_map_.erase(object_id); - map.erase(object_id); + id_map.erase(object_id); + method_map.erase(object_id); } ret = true; @@ -586,6 +590,7 @@ bool OhGinJavascriptBridgeDispatcherHost::RemoveNamedObjectInternal( new OhGinJavascriptBridgeMsg_RemoveNamedObject( render_frame_host->GetRoutingID(), copied_name)); }); + return ret; } } } diff --git a/libcef/browser/javascript/oh_gin_javascript_bridge_dispatcher_host.h b/libcef/browser/javascript/oh_gin_javascript_bridge_dispatcher_host.h index 181e0a263..e82b73de0 100644 --- a/libcef/browser/javascript/oh_gin_javascript_bridge_dispatcher_host.h +++ b/libcef/browser/javascript/oh_gin_javascript_bridge_dispatcher_host.h @@ -196,8 +196,9 @@ class OhGinJavascriptBridgeDispatcherHost PermissionMap javascript_async_permission_map_; std::shared_mutex share_mutex_; int32_t object_id_ = MIN_NATIVE_OBJ_ID; - std::unordered_map> object_id_map_; + std::unordered_map> object_id_map_; + std::unordered_map> async_object_id_map_; CefRefPtr client_; bool install_filter_when_render_process_gone_ = false; }; diff --git a/libcef/browser/javascript_dialog_manager.cc b/libcef/browser/javascript_dialog_manager.cc index 2e318b4fa..97d60c34a 100644 --- a/libcef/browser/javascript_dialog_manager.cc +++ b/libcef/browser/javascript_dialog_manager.cc @@ -16,12 +16,38 @@ #include "components/javascript_dialogs/tab_modal_dialog_manager.h" #if BUILDFLAG(IS_OHOS) +#include + +#include "base/base_switches.h" +#include "base/command_line.h" #include "components/strings/grit/components_strings.h" +#include "content/public/common/content_switches.h" #include "ui/base/l10n/l10n_util.h" #endif namespace { +#if BUILDFLAG(IS_OHOS) +constexpr int32_t API_TARGET_VERSION_12 = 12; +// Same as API_VERSION_MOD in js_ui_ability.cpp of ability_runtime +constexpr int32_t API_VERSION_MOD = 100; + +int32_t GetApiTargetVersion() { + if (!base::CommandLine::ForCurrentProcess()->HasSwitch( + switches::kOhosAppApiVersion)) { + LOG(ERROR) << "kOhosAppApiVersion not exist"; + return -1; + } + std::string apiVersion = + base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( + switches::kOhosAppApiVersion); + if (apiVersion.empty()) { + return -1; + } + return std::stoi(apiVersion) % API_VERSION_MOD; +} +#endif + class CefJSDialogCallbackImpl : public CefJSDialogCallback { public: using CallbackType = content::JavaScriptDialogManager::DialogClosedCallback; @@ -175,8 +201,12 @@ void CefJavaScriptDialogManager::RunBeforeUnloadDialog( } #if BUILDFLAG(IS_OHOS) - const std::u16string& message_text = - l10n_util::GetStringUTF16(IDS_BEFOREUNLOAD_MESSAGEBOX_MESSAGE); + static int32_t api_target_version = GetApiTargetVersion(); + std::u16string message = u"Is it OK to leave/reload this page?"; + if (api_target_version >= API_TARGET_VERSION_12) { + message = l10n_util::GetStringUTF16(IDS_BEFOREUNLOAD_MESSAGEBOX_MESSAGE); + } + const std::u16string& message_text = message; #else const std::u16string& message_text = u"Is it OK to leave/reload this page?"; #endif diff --git a/libcef/browser/largest_contentful_paint_details_impl.cc b/libcef/browser/largest_contentful_paint_details_impl.cc index b371c315c..5191a1e35 100644 --- a/libcef/browser/largest_contentful_paint_details_impl.cc +++ b/libcef/browser/largest_contentful_paint_details_impl.cc @@ -40,4 +40,4 @@ int64_t CefLargestContentfulPaintDetailsImpl::GetLargestImageLoadEndTime() { double_t CefLargestContentfulPaintDetailsImpl::GetImageBPP() { return imageBPP_; -} +} \ No newline at end of file diff --git a/libcef/browser/largest_contentful_paint_details_impl.h b/libcef/browser/largest_contentful_paint_details_impl.h index 00d54874a..7468c80b7 100644 --- a/libcef/browser/largest_contentful_paint_details_impl.h +++ b/libcef/browser/largest_contentful_paint_details_impl.h @@ -42,4 +42,4 @@ class CefLargestContentfulPaintDetailsImpl: public CefLargestContentfulPaintDeta IMPLEMENT_REFCOUNTING(CefLargestContentfulPaintDetailsImpl); }; -#endif // CEF_LIBCEF_BROWSER_LARGEST_CONTENTFUL_PAINT_DETAILS_IMPL_H_ +#endif // CEF_LIBCEF_BROWSER_LARGEST_CONTENTFUL_PAINT_DETAILS_IMPL_H_ \ No newline at end of file diff --git a/libcef/browser/native/browser_platform_delegate_native_aura.h b/libcef/browser/native/browser_platform_delegate_native_aura.h index 952c95e92..be3d05a7c 100644 --- a/libcef/browser/native/browser_platform_delegate_native_aura.h +++ b/libcef/browser/native/browser_platform_delegate_native_aura.h @@ -51,7 +51,7 @@ class CefBrowserPlatformDelegateNativeAura blink::WebMouseEvent TranslateWebMoveEvent(const CefMouseEvent& mouse_event, bool mouseLeave) const override; blink::WebGestureEvent TranslateTouchpadFlingEvent( - const CefMouseEvent& mouse_event) const override; + const CefMouseEvent& mouse_event) const override; blink::WebMouseWheelEvent TranslateWebWheelEvent( const CefMouseEvent& mouse_event, int deltaX, diff --git a/libcef/browser/net/ohos_applink_throttle.cc b/libcef/browser/net/ohos_applink_throttle.cc index 7e43659e2..c9055d7e8 100644 --- a/libcef/browser/net/ohos_applink_throttle.cc +++ b/libcef/browser/net/ohos_applink_throttle.cc @@ -39,6 +39,11 @@ class CefOpenAppLinkCallbackImpl : public CefOpenAppLinkCallback { OhosAppLinkThrottle::OhosAppLinkThrottle(int frame_tree_node_id) : frame_tree_node_id_(frame_tree_node_id) {} +OhosAppLinkThrottle::OhosAppLinkThrottle( + int frame_tree_node_id, bool is_client_redirect) + : frame_tree_node_id_(frame_tree_node_id), + is_client_redirect_(is_client_redirect) {} + OhosAppLinkThrottle::~OhosAppLinkThrottle() {} void OhosAppLinkThrottle::WillStartRequest( @@ -87,7 +92,11 @@ void OhosAppLinkThrottle::ContinueLoad() { void OhosAppLinkThrottle::CancelLoad() { if (delegate_) { - delegate_->CancelWithError(net::ERR_ABORTED); + if (is_client_redirect_) { + delegate_->Resume(); + } else { + delegate_->CancelWithError(net::ERR_ABORTED); + } } } } // namespace throttle \ No newline at end of file diff --git a/libcef/browser/net/ohos_applink_throttle.h b/libcef/browser/net/ohos_applink_throttle.h index c7adcfc50..4a5f692c8 100644 --- a/libcef/browser/net/ohos_applink_throttle.h +++ b/libcef/browser/net/ohos_applink_throttle.h @@ -16,6 +16,7 @@ namespace throttle { class OhosAppLinkThrottle : public blink::URLLoaderThrottle { public: explicit OhosAppLinkThrottle(int frame_tree_node_id); + OhosAppLinkThrottle(int frame_tree_node_id, bool is_client_redirect); OhosAppLinkThrottle(const OhosAppLinkThrottle&) = delete; OhosAppLinkThrottle& operator=(const OhosAppLinkThrottle&) = delete; ~OhosAppLinkThrottle() override; @@ -38,6 +39,7 @@ class OhosAppLinkThrottle : public blink::URLLoaderThrottle { private: int frame_tree_node_id_; + bool is_client_redirect_ = false; SEQUENCE_CHECKER(sequence_checker_); base::WeakPtrFactory weak_factory_{this}; diff --git a/libcef/browser/net/throttle_handler.cc b/libcef/browser/net/throttle_handler.cc index 62d838ec8..5ff6fc065 100644 --- a/libcef/browser/net/throttle_handler.cc +++ b/libcef/browser/net/throttle_handler.cc @@ -21,7 +21,6 @@ #if defined(OHOS_ARKWEB_EXTENSIONS) #include "extensions/common/constants.h" #endif - namespace throttle { namespace { diff --git a/libcef/browser/net_service/cookie_helper.cc b/libcef/browser/net_service/cookie_helper.cc index 732804d40..481bf4b6b 100644 --- a/libcef/browser/net_service/cookie_helper.cc +++ b/libcef/browser/net_service/cookie_helper.cc @@ -17,6 +17,12 @@ #include "services/network/cookie_manager.h" #include "services/network/public/cpp/resource_request.h" +#if defined(OHOS_EX_EXCEPTION_LIST) +#include "base/ranges/algorithm.h" +#include "chrome/browser/content_settings/host_content_settings_map_factory.h" +#include "components/content_settings/core/browser/host_content_settings_map.h" +#endif + namespace net_service { namespace cookie_helper { @@ -242,6 +248,43 @@ bool IsCookieableScheme( return url.SchemeIsHTTPOrHTTPS() || url.SchemeIsWSOrWSS(); } +#if defined(OHOS_EX_EXCEPTION_LIST) +bool CanSaveOrLoadCookies(const CefBrowserContext::Getter& browser_context_getter, + const network::ResourceRequest& request) { + auto cef_browser_context = GetBrowserContext(browser_context_getter); + auto browser_context = + cef_browser_context ? cef_browser_context->AsBrowserContext() : nullptr; + if (!browser_context) { + LOG(ERROR) << "Can not get browser_context."; + return true; + } + + HostContentSettingsMap* host_content_settings_map = + HostContentSettingsMapFactory::GetForProfile(browser_context); + if (!host_content_settings_map) { + LOG(ERROR) << "Can not get host_content_settings_map."; + return true; + } + + ContentSettingsForOneType cookie_settings; + host_content_settings_map-> + GetSettingsForOneType(ContentSettingsType::COOKIES, &cookie_settings); + + const auto& entry = base::ranges::find_if( + cookie_settings, [&](const ContentSettingPatternSource& entry) { + // The primary pattern is for the request URL; the secondary pattern + // is for the first-party URL (which is the top-frame origin [if + // available] or the site-for-cookies). + return !entry.IsExpired() && + entry.primary_pattern.Matches(request.url) && + entry.secondary_pattern.Matches(request.url); + }); + const ContentSettingPatternSource* match = + (entry == cookie_settings.end() ? nullptr : &*entry); + return !(match && match->GetContentSetting() == CONTENT_SETTING_BLOCK); +} +#endif + void LoadCookies(const CefBrowserContext::Getter& browser_context_getter, const network::ResourceRequest& request, const AllowCookieCallback& allow_cookie_callback, @@ -250,7 +293,11 @@ void LoadCookies(const CefBrowserContext::Getter& browser_context_getter, if ((request.load_flags & net::LOAD_DO_NOT_SEND_COOKIES) || request.credentials_mode == network::mojom::CredentialsMode::kOmit || - request.url.IsAboutBlank()) { + request.url.IsAboutBlank() +#if defined(OHOS_EX_EXCEPTION_LIST) + || !CanSaveOrLoadCookies(browser_context_getter, request) +#endif + ) { // Continue immediately without loading cookies. std::move(done_callback).Run(0, {}); return; @@ -304,6 +351,17 @@ void SaveCookies(const CefBrowserContext::Getter& browser_context_getter, continue; } +#if defined(OHOS_EX_EXCEPTION_LIST) + if (cookie && !CanSaveOrLoadCookies(browser_context_getter, request)) { + returned_status.AddExclusionReason( + net::CookieInclusionStatus::EXCLUDE_USER_PREFERENCES); + } + + if (!returned_status.IsInclude()) { + continue; + } +#endif + bool allow = false; allow_cookie_callback.Run(*cookie, &allow); if (allow) { diff --git a/libcef/browser/net_service/cookie_manager_impl.cc b/libcef/browser/net_service/cookie_manager_impl.cc index e8d4332a8..c80e87433 100644 --- a/libcef/browser/net_service/cookie_manager_impl.cc +++ b/libcef/browser/net_service/cookie_manager_impl.cc @@ -207,7 +207,8 @@ bool CefCookieManagerImpl::VisitUrlCookies( const CefString& url, bool includeHttpOnly, CefRefPtr visitor, - bool is_sync) { + bool is_sync, + bool is_from_ndk) { if (!visitor.get()) { return false; } @@ -226,28 +227,29 @@ bool CefCookieManagerImpl::VisitUrlCookies( if (!ValidContext()) { StoreOrTriggerInitCallback(base::BindOnce( base::IgnoreResult(&CefCookieManagerImpl::VisitUrlCookiesInternal), - this, gurl, includeHttpOnly, visitor, is_sync)); + this, gurl, includeHttpOnly, visitor, is_sync, is_from_ndk)); return true; } - return VisitUrlCookiesInternal(gurl, includeHttpOnly, visitor, is_sync); + return VisitUrlCookiesInternal(gurl, includeHttpOnly, visitor, is_sync, is_from_ndk); } bool CefCookieManagerImpl::SetCookie(const CefString& url, const CefCookie& cookie, CefRefPtr callback, bool is_sync, - const CefString& str_cookie) { + const CefString& str_cookie, + bool includeHttpOnly) { GURL gurl = GURL(url.ToString()); if (!ValidContext()) { StoreOrTriggerInitCallback(base::BindOnce( base::IgnoreResult(&CefCookieManagerImpl::SetCookieInternal), this, - gurl, cookie, callback, is_sync, str_cookie)); + gurl, cookie, callback, is_sync, str_cookie, includeHttpOnly)); return true; } - return SetCookieInternal(gurl, cookie, callback, is_sync, str_cookie); + return SetCookieInternal(gurl, cookie, callback, is_sync, str_cookie, includeHttpOnly); } bool CefCookieManagerImpl::DeleteCookies( @@ -329,13 +331,17 @@ bool CefCookieManagerImpl::VisitUrlCookiesInternal( const GURL& url, bool includeHttpOnly, CefRefPtr visitor, - bool is_sync) { + bool is_sync, + bool is_from_ndk) { DCHECK(ValidContext()); DCHECK(visitor); DCHECK(url.is_valid()); #ifdef OHOS_COOKIE net::CookieOptions options = net::CookieOptions::MakeAllInclusive(); + if (is_from_ndk && !includeHttpOnly) { + options.set_exclude_httponly(); + } #else net::CookieOptions options; if (includeHttpOnly) { @@ -383,7 +389,7 @@ bool CefCookieManagerImpl::SetCookieInternal( const GURL& url, const CefCookie& cookie, CefRefPtr callback, - bool is_sync, const CefString& str_cookie) { + bool is_sync, const CefString& str_cookie, bool includeHttpOnly) { DCHECK(ValidContext()); DCHECK(url.is_valid()); @@ -426,7 +432,7 @@ bool CefCookieManagerImpl::SetCookieInternal( } net::CookieOptions options; - if (cookie.httponly) { + if (includeHttpOnly || cookie.httponly) { options.set_include_httponly(); } options.set_same_site_cookie_context( diff --git a/libcef/browser/net_service/cookie_manager_impl.h b/libcef/browser/net_service/cookie_manager_impl.h index 86b0dc8cb..23194a954 100644 --- a/libcef/browser/net_service/cookie_manager_impl.h +++ b/libcef/browser/net_service/cookie_manager_impl.h @@ -38,12 +38,14 @@ class CefCookieManagerImpl : public CefCookieManager { bool VisitUrlCookies(const CefString& url, bool includeHttpOnly, CefRefPtr visitor, - bool is_sync) override; + bool is_sync, + bool is_from_ndk) override; bool SetCookie(const CefString& url, const CefCookie& cookie, CefRefPtr callback, bool is_sync, - const CefString& str_cookie) override; + const CefString& str_cookie, + bool includeHttpOnly) override; bool DeleteCookies(const CefString& url, const CefString& cookie_name, #if BUILDFLAG(IS_OHOS) @@ -67,12 +69,13 @@ class CefCookieManagerImpl : public CefCookieManager { bool VisitAllCookiesInternal(CefRefPtr visitor, bool sync); bool VisitUrlCookiesInternal(const GURL& url, bool includeHttpOnly, - CefRefPtr visitor, bool sync); + CefRefPtr visitor, bool sync, bool is_from_ndk); bool SetCookieInternal(const GURL& url, const CefCookie& cookie, CefRefPtr callback, bool sync, - const CefString& str_cookie); + const CefString& str_cookie + bool includeHttpOnly); bool DeleteCookiesInternal(const GURL& url, const CefString& cookie_name, bool is_session, diff --git a/libcef/browser/net_service/cookie_manager_ohos_impl.cc b/libcef/browser/net_service/cookie_manager_ohos_impl.cc index 717b3c9f2..dc8b52e03 100644 --- a/libcef/browser/net_service/cookie_manager_ohos_impl.cc +++ b/libcef/browser/net_service/cookie_manager_ohos_impl.cc @@ -37,6 +37,13 @@ #include "services/network/cookie_access_delegate_impl.h" #include "services/network/cookie_manager.h" +#if defined(OHOS_EX_EXCEPTION_LIST) +#include "base/command_line.h" +#include "content/public/common/content_switches.h" +#include "components/content_settings/core/browser/host_content_settings_map.h" +#include "chrome/browser/content_settings/host_content_settings_map_factory.h" +#endif // defined(OHOS_EX_EXCEPTION_LIST) + using network::mojom::CookieManager; namespace { @@ -287,7 +294,7 @@ void CefCookieManagerImpl::Initialize( CefBrowserContext::Getter browser_context_getter, CefRefPtr callback) { CEF_REQUIRE_UIT(); - (void)browser_context_getter; + browser_context_getter_ = browser_context_getter; RunAsyncCompletionOnUIThread(callback); } @@ -297,6 +304,25 @@ bool CefCookieManagerImpl::IsAcceptCookieAllowed() { void CefCookieManagerImpl::PutAcceptCookieEnabled(bool accept) { net_service::NetHelpers::accept_cookies = accept; + +#if defined(OHOS_EX_EXCEPTION_LIST) + if (base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kForBrowser)) { + if (browser_context_getter_) { + auto cef_browser_context = browser_context_getter_.Run(); + if (cef_browser_context) { + HostContentSettingsMap* host_content_settings_map = + HostContentSettingsMapFactory::GetForProfile( + cef_browser_context->AsBrowserContext()); + if (host_content_settings_map) { + host_content_settings_map->SetDefaultContentSetting( + ContentSettingsType::COOKIES, + net_service::NetHelpers::IsAllowAcceptCookies() ? ContentSetting::CONTENT_SETTING_ALLOW + : ContentSetting::CONTENT_SETTING_BLOCK); + } + } + } + } +#endif // defined(OHOS_EX_EXCEPTION_LIST) } bool CefCookieManagerImpl::IsThirdPartyCookieAllowed() { @@ -331,7 +357,8 @@ bool CefCookieManagerImpl::VisitUrlCookies( const CefString& url, bool includeHttpOnly, CefRefPtr visitor, - bool is_sync) { + bool is_sync, + bool is_from_ndk) { if (!visitor.get()) { return false; } @@ -341,16 +368,17 @@ bool CefCookieManagerImpl::VisitUrlCookies( return false; } LOG(DEBUG) << "CefCookieManagerImpl::VisitUrlCookies is_sync: " << is_sync; - return VisitUrlCookiesInternal(gurl, includeHttpOnly, visitor, is_sync); + return VisitUrlCookiesInternal(gurl, includeHttpOnly, visitor, is_sync, is_from_ndk); } bool CefCookieManagerImpl::SetCookie(const CefString& url, const CefCookie& cookie, CefRefPtr callback, - bool is_sync, const CefString& str_cookie) { + bool is_sync, const CefString& str_cookie, + bool includeHttpOnly) { GURL gurl = GURL(url.ToString()); LOG(DEBUG) << "CefCookieManagerImpl::SetCookie is_sync: " << is_sync; - return SetCookieInternal(gurl, cookie, callback, is_sync, str_cookie); + return SetCookieInternal(gurl, cookie, callback, is_sync, str_cookie, includeHttpOnly); } bool CefCookieManagerImpl::DeleteCookies( @@ -491,11 +519,15 @@ bool CefCookieManagerImpl::VisitUrlCookiesInternal( const GURL& url, bool includeHttpOnly, CefRefPtr visitor, - bool is_sync) { + bool is_sync, + bool is_from_ndk) { DCHECK(visitor); DCHECK(url.is_valid()); net::CookieOptions options = net::CookieOptions::MakeAllInclusive(); + if (is_from_ndk && !includeHttpOnly) { + options.set_exclude_httponly(); + } LOG(DEBUG) << "CefCookieManagerImpl::VisitUrlCookiesInternal is_sync : " << is_sync; if (is_sync) { RunCookieTaskSync(base::BindOnce(&CefCookieManagerImpl::GetCookieListCookieTask, @@ -538,7 +570,8 @@ bool CefCookieManagerImpl::SetCookieInternal( const CefCookie& cookie, CefRefPtr callback, bool is_sync, - const CefString& str_cookie) { + const CefString& str_cookie, + bool includeHttpOnly) { DCHECK(url.is_valid()); std::unique_ptr canonical_cookie(net::CanonicalCookie::Create( @@ -551,7 +584,7 @@ bool CefCookieManagerImpl::SetCookieInternal( } net::CookieOptions options; - if (cookie.httponly) { + if (includeHttpOnly || cookie.httponly) { options.set_include_httponly(); } options.set_same_site_cookie_context( diff --git a/libcef/browser/net_service/cookie_manager_ohos_impl.h b/libcef/browser/net_service/cookie_manager_ohos_impl.h index 00f66ccba..91a3e16ab 100644 --- a/libcef/browser/net_service/cookie_manager_ohos_impl.h +++ b/libcef/browser/net_service/cookie_manager_ohos_impl.h @@ -55,12 +55,14 @@ class CefCookieManagerImpl : public CefCookieManager { bool VisitUrlCookies(const CefString& url, bool includeHttpOnly, CefRefPtr visitor, - bool is_sync) override; + bool is_sync, + bool is_from_ndk) override; bool SetCookie(const CefString& url, const CefCookie& cookie, CefRefPtr callback, bool is_sync, - const CefString& str_cookie) override; + const CefString& str_cookie, + bool includeHttpOnly) override; bool DeleteCookies(const CefString& url, const CefString& cookie_name, bool is_session, @@ -121,12 +123,14 @@ class CefCookieManagerImpl : public CefCookieManager { bool VisitUrlCookiesInternal(const GURL& url, bool includeHttpOnly, CefRefPtr visitor, - bool is_sync); + bool is_sync, + bool is_from_ndk); bool SetCookieInternal(const GURL& url, const CefCookie& cookie, CefRefPtr callback, bool is_sync, - const CefString& str_cookie); + const CefString& str_cookie, + bool includeHttpOnly); bool DeleteCookiesInternal(const GURL& url, const CefString& cookie_name, bool is_session, @@ -172,6 +176,8 @@ class CefCookieManagerImpl : public CefCookieManager { mojo::Remote network_cookie_manager_; + CefBrowserContext::Getter browser_context_getter_; + IMPLEMENT_REFCOUNTING(CefCookieManagerImpl); }; diff --git a/libcef/browser/net_service/incognito_cookie_manager_ohos_impl.cc b/libcef/browser/net_service/incognito_cookie_manager_ohos_impl.cc index e30205309..1da4503bb 100644 --- a/libcef/browser/net_service/incognito_cookie_manager_ohos_impl.cc +++ b/libcef/browser/net_service/incognito_cookie_manager_ohos_impl.cc @@ -354,7 +354,8 @@ bool CefIncognitoCookieManagerImpl::VisitUrlCookies( const CefString& url, bool includeHttpOnly, CefRefPtr visitor, - bool is_sync) { + bool is_sync, + bool is_from_ndk) { if (!visitor.get()) { return false; } @@ -364,15 +365,15 @@ bool CefIncognitoCookieManagerImpl::VisitUrlCookies( return false; } LOG(DEBUG) << "VisitUrlCookies is_sync: " << is_sync; - return VisitUrlCookiesInternal(gurl, includeHttpOnly, visitor, is_sync); + return VisitUrlCookiesInternal(gurl, includeHttpOnly, visitor, is_sync, is_from_ndk); } bool CefIncognitoCookieManagerImpl::SetCookie(const CefString& url, const CefCookie& cookie, CefRefPtr callback, - bool is_sync, const CefString& str_cookie) { + bool is_sync, const CefString& str_cookie, bool includeHttpOnly) { GURL gurl = GURL(url.ToString()); LOG(DEBUG) << "SetCookie is_sync: " << is_sync; - return SetCookieInternal(gurl, cookie, callback, is_sync, str_cookie); + return SetCookieInternal(gurl, cookie, callback, is_sync, str_cookie, includeHttpOnly); } bool CefIncognitoCookieManagerImpl::DeleteCookies( @@ -523,11 +524,16 @@ bool CefIncognitoCookieManagerImpl::VisitUrlCookiesInternal( const GURL& url, bool includeHttpOnly, CefRefPtr visitor, - bool is_sync) { + bool is_sync, + bool is_from_ndk) { DCHECK(visitor); DCHECK(url.is_valid()); net::CookieOptions options = net::CookieOptions::MakeAllInclusive(); + if (is_from_ndk && !includeHttpOnly) { + options.set_exclude_httponly(); + } + LOG(DEBUG) << "VisitUrlCookiesInternal is_sync : " << is_sync; if (is_sync) { RunCookieTaskSync(base::BindOnce( @@ -573,7 +579,8 @@ bool CefIncognitoCookieManagerImpl::SetCookieInternal( const CefCookie& cookie, CefRefPtr callback, bool is_sync, - const CefString& str_cookie) { + const CefString& str_cookie, + bool includeHttpOnly) { DCHECK(url.is_valid()); std::unique_ptr canonical_cookie( @@ -589,7 +596,7 @@ bool CefIncognitoCookieManagerImpl::SetCookieInternal( } net::CookieOptions options; - if (cookie.httponly) { + if (includeHttpOnly || cookie.httponly) { options.set_include_httponly(); } options.set_same_site_cookie_context( diff --git a/libcef/browser/net_service/incognito_cookie_manager_ohos_impl.h b/libcef/browser/net_service/incognito_cookie_manager_ohos_impl.h index e2e457afb..703bde304 100644 --- a/libcef/browser/net_service/incognito_cookie_manager_ohos_impl.h +++ b/libcef/browser/net_service/incognito_cookie_manager_ohos_impl.h @@ -55,12 +55,14 @@ class CefIncognitoCookieManagerImpl : public CefCookieManager { bool VisitUrlCookies(const CefString& url, bool includeHttpOnly, CefRefPtr visitor, - bool is_sync) override; + bool is_sync, + bool is_from_ndk = false) override; bool SetCookie(const CefString& url, const CefCookie& cookie, CefRefPtr callback, bool is_sync, - const CefString& str_cookie) override; + const CefString& str_cookie, + bool includeHttpOnly) override; bool DeleteCookies(const CefString& url, const CefString& cookie_name, bool is_session, @@ -121,12 +123,14 @@ class CefIncognitoCookieManagerImpl : public CefCookieManager { bool VisitUrlCookiesInternal(const GURL& url, bool includeHttpOnly, CefRefPtr visitor, - bool is_sync); + bool is_sync, + bool is_from_ndk); bool SetCookieInternal(const GURL& url, const CefCookie& cookie, CefRefPtr callback, bool is_sync, - const CefString& str_cookie); + const CefString& str_cookie, + bool includeHttpOnly); bool DeleteCookiesInternal(const GURL& url, const CefString& cookie_name, bool is_session, diff --git a/libcef/browser/net_service/login_delegate.cc b/libcef/browser/net_service/login_delegate.cc index e57316f0c..4ff4cdbef 100644 --- a/libcef/browser/net_service/login_delegate.cc +++ b/libcef/browser/net_service/login_delegate.cc @@ -56,6 +56,7 @@ class AuthCallbackImpl : public CefAuthCallback { } void Continue(const CefString& username, const CefString& password) override { + LOG(INFO) << "HttpAuth user continue"; if (!task_runner_->RunsTasksInCurrentSequence()) { task_runner_->PostTask( FROM_HERE, base::BindOnce(&AuthCallbackImpl::Continue, this, username, @@ -87,9 +88,11 @@ class AuthCallbackImpl : public CefAuthCallback { constexpr int32_t MAX_PWD_LENGTH = 256; auto dataBase = CefDataBase::GetGlobalDataBase(); if (dataBase == nullptr) { + LOG(ERROR) << "IsHttpAuthInfoSaved dataBase is empty"; return false; } if (!dataBase->ExistHttpAuthCredentials()) { + LOG(WARNING) << "IsHttpAuthInfoSaved dataBase is existHttpAuth"; return false; } CefString username; @@ -98,6 +101,7 @@ class AuthCallbackImpl : public CefAuthCallback { MAX_PWD_LENGTH + 1); if (username.empty() || strlen(password) == 0) { memset(password, 0, MAX_PWD_LENGTH + 1); + LOG(WARNING) << "IsHttpAuthInfoSaved name or password is empty"; return false; } CefString passwordCef(password, strlen(password)); @@ -107,15 +111,18 @@ class AuthCallbackImpl : public CefAuthCallback { FROM_HERE, base::BindOnce(&AuthCallbackImpl::Continue, this, username, passwordCef)); passwordCef.MemsetToZero(); + LOG(INFO) << "IsHttpAuthInfoSaved continue"; return true; } if (delegate_) { delegate_->Continue(username, passwordCef); delegate_ = nullptr; passwordCef.MemsetToZero(); + LOG(INFO) << "IsHttpAuthInfoSaved login byself"; return true; } passwordCef.MemsetToZero(); + LOG(WARNING) << "IsHttpAuthInfoSaved is not found"; return false; } #endif @@ -204,10 +211,10 @@ LoginDelegate::LoginDelegate(const net::AuthChallengeInfo& auth_info, #if defined(OHOS_ARKWEB_EXTENSIONS) // |callback| needs to be executed asynchronously. - CEF_POST_TASK(CEF_UIT, base::BindOnce(&LoginDelegate::Start, - weak_ptr_factory_.GetWeakPtr(), browser, + CEF_POST_TASK(CEF_UIT, base::BindOnce(&LoginDelegate::Start, + weak_ptr_factory_.GetWeakPtr(), browser, auth_info, request_id, - is_request_for_main_frame, + is_request_for_main_frame, origin_url, response_headers)); #else // |callback| needs to be executed asynchronously. @@ -263,7 +270,7 @@ void LoginDelegate::ContinueBeforeCommit( } void LoginDelegate::StartInternal(CefRefPtr browser, - const net::AuthChallengeInfo& auth_info, + const net::AuthChallengeInfo& auth_info, const content::GlobalRequestID& request_id, const GURL& origin_url) { auto url_request_info = CefBrowserURLRequest::FromRequestID(request_id); diff --git a/libcef/browser/net_service/login_delegate.h b/libcef/browser/net_service/login_delegate.h index b51d87eb9..1a7c78aa8 100644 --- a/libcef/browser/net_service/login_delegate.h +++ b/libcef/browser/net_service/login_delegate.h @@ -56,7 +56,7 @@ class LoginDelegate : public content::LoginDelegate { const GURL& origin_url, scoped_refptr response_headers); void StartInternal(CefRefPtr browser, - const net::AuthChallengeInfo& auth_info, + const net::AuthChallengeInfo& auth_info, const content::GlobalRequestID& request_id, const GURL& origin_url); void ContinueBeforeCommit( diff --git a/libcef/browser/net_service/net_helpers.cc b/libcef/browser/net_service/net_helpers.cc index d410be1b0..aa7226858 100644 --- a/libcef/browser/net_service/net_helpers.cc +++ b/libcef/browser/net_service/net_helpers.cc @@ -4,13 +4,17 @@ #include "libcef/browser/net_service/net_helpers.h" +#include "base/base_switches.h" +#include "base/command_line.h" #include "base/base_paths_ohos.h" #include "base/files/file_path.h" +#include "base/files/file_util.h" #include "base/path_service.h" #include "base/strings/string_util.h" #include "include/base/cef_logging.h" #include "net/base/load_flags.h" #include "url/gurl.h" +#include "content/public/common/content_switches.h" #if defined(OHOS_HTTP_DNS) #include @@ -18,6 +22,8 @@ #include "net/dns/public/secure_dns_mode.h" #endif // defined(OHOS_HTTP_DNS) +#include "libcef/common/command_line_impl.h" + namespace net_service { namespace { @@ -34,7 +40,7 @@ int UpdateCacheLoadFlags(int load_flags, int cache_control_flags) { } // namespace static const std::string APP_READ_ONLY_PATH = - "/data/storage/el1/bundle/entry/resources/resfile"; + "/data/storage/el1/bundle/entry/resources/resfile/"; bool NetHelpers::allow_content_access = false; bool NetHelpers::allow_file_access = false; @@ -43,11 +49,15 @@ bool NetHelpers::accept_cookies = true; bool NetHelpers::third_party_cookies = false; int NetHelpers::cache_mode = 0; int NetHelpers::connection_timeout = 30; +constexpr int32_t APPLICATION_API_12 = 12; #if defined(OHOS_HTTP_DNS) int NetHelpers::doh_mode = -1; std::string NetHelpers::doh_config = ""; #endif // defined(OHOS_HTTP_DNS) +#if defined(OHOS_EX_NETWORK_CONNECTION) +int NetHelpers::network = -1; +#endif #if defined(OHOS_CUSTOM_DNS) std::map NetHelpers::custom_dns = {}; @@ -157,12 +167,54 @@ void NetHelpers::ClearHostIP() { } #endif // defined(OHOS_CUSTOM_DNS) +int32_t GetApplicationApiVersion() { + if (!base::CommandLine::ForCurrentProcess()->HasSwitch( + switches::kOhosAppApiVersion)) { + LOG(ERROR) << "kOhosAppApiVersion not exist"; + return -1; + } + std::string apiVersion = + base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( + switches::kOhosAppApiVersion); + if (apiVersion.empty()) { + return -1; + } + return std::stoi(apiVersion); +} + bool IsSpecialFileUrl(const GURL& url) { if (!url.is_valid() || !url.SchemeIsFile() || !url.has_path()) { return false; } - if (base::StartsWith(url.path(), APP_READ_ONLY_PATH, + if (GetApplicationApiVersion() >= APPLICATION_API_12) { + if (base::StartsWith(url.path(), APP_READ_ONLY_PATH, + base::CompareCase::SENSITIVE)) { + LOG(INFO) << "Is special file url, the path is in: " << APP_READ_ONLY_PATH; + return true; + } + LOG(INFO) << "Is not special file url, the path is not in: " << APP_READ_ONLY_PATH; + return false; + } + + base::FilePath app_data_path; + if (!base::PathService::Get(base::DIR_OHOS_APP_DATA, &app_data_path)) { + return false; + } + base::FilePath app_bundle_path; + if (!base::PathService::Get(base::DIR_OHOS_APP_INSTALLATION, + &app_bundle_path)) { + return false; + } + LOG(INFO) << "app_data_path:" << app_data_path.value() + << ", app_bundle_path:" << app_bundle_path.value(); + + if (base::StartsWith(url.path(), app_data_path.value(), + base::CompareCase::SENSITIVE)) { + return true; + } + + if (base::StartsWith(url.path(), app_bundle_path.value(), base::CompareCase::SENSITIVE)) { return true; } @@ -174,10 +226,25 @@ bool IsInFileAccessList(const GURL& url, const std::vector& pass_di return false; } + auto url_path = + base::MakeAbsoluteFilePathNoResolveSymbolicLinks(base::FilePath(url.path())) + .value_or(base::FilePath()); + if (url_path.empty()) { + return false; + } for (auto& path: pass_dir) { - LOG(ERROR) << "IsInFileAccessList url path:" << url.path(); - LOG(ERROR) << "IsInFileAccessList pass path:" << path; - if (base::StartsWith(url.path(), path, base::CompareCase::SENSITIVE)) { + auto pass_path = + base::MakeAbsoluteFilePathNoResolveSymbolicLinks(base::FilePath(path)) + .value_or(base::FilePath()); + if (pass_path.empty()) { + return false; + } + if (!pass_path.IsParent(url_path)) { + if (pass_path == url_path) { + LOG(INFO) << "IsInFileAccessList equal"; + return true; + } + } else { return true; } } @@ -198,9 +265,8 @@ bool IsURLBlocked(const GURL& url if (url.SchemeIsFile() && !setting.file_access_dirs_list.empty()) { bool result = IsInFileAccessList(url, setting.file_access_dirs_list); - LOG(ERROR) << "IsInFileAccessList url result:" << result; if (!result) { - LOG(ERROR) << "Blocked by file access list"; + LOG(WARNING) << "Blocked by file access list"; } return !result; } diff --git a/libcef/browser/net_service/net_helpers.h b/libcef/browser/net_service/net_helpers.h index d58cfc1a3..e7e678b98 100644 --- a/libcef/browser/net_service/net_helpers.h +++ b/libcef/browser/net_service/net_helpers.h @@ -69,6 +69,9 @@ class NETHELPERS_EXPORT NetHelpers { static int doh_mode; static std::string doh_config; #endif // defined(OHOS_HTTP_DNS) +#if defined(OHOS_EX_NETWORK_CONNECTION) + static int network; +#endif }; bool IsSpecialFileUrl(const GURL& url); diff --git a/libcef/browser/net_service/proxy_url_loader_factory.cc b/libcef/browser/net_service/proxy_url_loader_factory.cc index 84faea6f0..ff7c6706b 100644 --- a/libcef/browser/net_service/proxy_url_loader_factory.cc +++ b/libcef/browser/net_service/proxy_url_loader_factory.cc @@ -36,6 +36,10 @@ #include "libcef/browser/res_reporter.h" #include "libcef/common/request_impl.h" #include "net/base/load_flags.h" +#if defined(OHOS_EX_DOWNLOAD) +#include "content/public/browser/download_utils.h" +#include "third_party/blink/public/common/mime_util/mime_util.h" +#endif #endif namespace net_service { @@ -407,6 +411,10 @@ class InterceptedRequest : public network::mojom::URLLoader, StreamReaderURLLoader* stream_loader_ = nullptr; +#if defined(OHOS_EX_DOWNLOAD) + bool is_download_{ false }; +#endif + base::WeakPtrFactory weak_factory_; }; @@ -517,8 +525,17 @@ void InterceptedRequest::Restart() { } } +#if BUILDFLAG(IS_OHOS) + if (request_.method == "OPTIONS") { + current_request_uses_header_client_ = false; + } else { + current_request_uses_header_client_ = + factory_->url_loader_header_client_receiver_.is_bound(); + } +#else current_request_uses_header_client_ = factory_->url_loader_header_client_receiver_.is_bound(); +#endif if (request_.request_initiator && network::cors::ShouldCheckCors(request_.url, request_.request_initiator, @@ -664,6 +681,17 @@ void InterceptedRequest::OnReceiveResponse( current_body_ = std::move(body); current_cached_metadata_ = std::move(cached_metadata); +#if defined(OHOS_EX_DOWNLOAD) + bool must_download = + content::download_utils::MustDownload( + request_.url, current_response_->headers.get(), current_response_->mime_type); + bool known_mime_type = + blink::IsSupportedMimeType(current_response_->mime_type); + is_download_ = + !current_response_->intercepted_by_plugin && + (must_download || !known_mime_type); +#endif + #if BUILDFLAG(IS_OHOS) if (current_response_->headers && current_response_->headers->response_code() >= 400) { @@ -941,7 +969,9 @@ void InterceptedRequest::InterceptResponseReceived( if (response) { // Non-null response: make sure to use it as an override for the // normal network data. +#if BUILDFLAG(IS_OHOS) TRACE_EVENT1("net", "InterceptedRequest::InterceptResponseReceived", "url", request_.url.spec()); +#endif ContinueAfterInterceptWithOverride(std::move(response)); } else { // Request was not intercepted/overridden. Proceed with loading @@ -971,6 +1001,27 @@ void InterceptedRequest::ContinueAfterInterceptWithOverride( std::unique_ptr response) { // StreamReaderURLLoader will synthesize TrustedHeaderClient callbacks to // avoid having Set-Cookie headers stripped by the IPC layer. +#if BUILDFLAG(IS_OHOS) + if (request_.method == "OPTIONS") { + current_request_uses_header_client_ = false; + + stream_loader_ = new StreamReaderURLLoader( + id_, request_, proxied_client_receiver_.BindNewPipeAndPassRemote(), + mojo::NullRemote(), traffic_annotation_, + std::move(current_cached_metadata_), + std::make_unique(std::move(response), + weak_factory_.GetWeakPtr())); + } else { + current_request_uses_header_client_ = true; + + stream_loader_ = new StreamReaderURLLoader( + id_, request_, proxied_client_receiver_.BindNewPipeAndPassRemote(), + header_client_receiver_.BindNewPipeAndPassRemote(), traffic_annotation_, + std::move(current_cached_metadata_), + std::make_unique(std::move(response), + weak_factory_.GetWeakPtr())); + } +#else current_request_uses_header_client_ = true; stream_loader_ = new StreamReaderURLLoader( @@ -979,6 +1030,7 @@ void InterceptedRequest::ContinueAfterInterceptWithOverride( std::move(current_cached_metadata_), std::make_unique(std::move(response), weak_factory_.GetWeakPtr())); +#endif stream_loader_->Start(); } @@ -1240,19 +1292,21 @@ void InterceptedRequest::OnDestroy() { // We don't want any callbacks after this point. weak_factory_.InvalidateWeakPtrs(); +#ifdef OHOS_BUGFIX_CRASH + if (!factory_) { + LOG(ERROR) << "InterceptedRequest::OnDestroy factory_ is nullptr"; + return; + } + if (!factory_->request_handler_) { + LOG(ERROR) << "InterceptedRequest::OnDestroy factory_->request_handler_ is nullptr"; + return; + } +#endif + factory_->request_handler_->OnRequestComplete(id_, request_, status_); -#ifdef OHOS_NETWORK_LOAD - if (request_.method == "OPTIONS") { - delete this; - } else { - // Destroys |this|. - factory_->RemoveRequest(this); - } -#else // Destroys |this|. factory_->RemoveRequest(this); -#endif } void InterceptedRequest::OnProcessRequestHeaders( @@ -1328,12 +1382,14 @@ void InterceptedRequest::CallOnComplete( #if defined(OHOS_EX_DOWNLOAD) void InterceptedRequest::CancelRequest(int error_code) { - // network::URLLoaderCompletionStatus status(error_code); - // status.abort_due_to_cef_browser_destroyed = true; - // SendErrorStatusAndCompleteImmediately(status); // Donn't cancel network requests. Network requests should be canceled by the holder // instead of following the tab, such as serviceworker download, etc. Although the // tab is destroyed, the request still needs to be maintained. + if (!is_download_) { + network::URLLoaderCompletionStatus status(error_code); + status.abort_due_to_cef_browser_destroyed = true; + SendErrorStatusAndCompleteImmediately(status); + } } #endif // OHOS_EX_DOWNLOAD @@ -1506,15 +1562,15 @@ void ProxyURLLoaderFactory::CreateProxy( mojo::PendingReceiver proxied_receiver; mojo::PendingRemote target_factory_remote; - + if (factory_override) { // We are interested in factories "inside" of CORS, so use // |factory_override|. *factory_override = network::mojom::URLLoaderFactoryOverride::New(); - proxied_receiver = + proxied_receiver = (*factory_override) ->overriding_factory.InitWithNewPipeAndPassReceiver(); - (*factory_override)->overridden_factory_receiver = + (*factory_override)->overridden_factory_receiver = target_factory_remote.InitWithNewPipeAndPassReceiver(); (*factory_override)->skip_cors_enabled_scheme_check = true; } else { @@ -1648,14 +1704,7 @@ void ProxyURLLoaderFactory::CreateLoaderAndStart( InterceptedRequest* req = new InterceptedRequest( this, request_id, options, request, traffic_annotation, std::move(receiver), std::move(client), std::move(target_factory_clone)); -#ifdef OHOS_NETWORK_LOAD - // Donn't track options request, because the request id for options always 0. - if (request.method != "OPTIONS") { - requests_.insert(std::make_pair(request_id, base::WrapUnique(req))); - } -#else requests_.insert(std::make_pair(request_id, base::WrapUnique(req))); -#endif #if BUILDFLAG(IS_OHOS) req->Restart(false); #else diff --git a/libcef/browser/net_service/resource_request_handler_wrapper.cc b/libcef/browser/net_service/resource_request_handler_wrapper.cc index 193ae1e70..e7813697d 100644 --- a/libcef/browser/net_service/resource_request_handler_wrapper.cc +++ b/libcef/browser/net_service/resource_request_handler_wrapper.cc @@ -103,6 +103,47 @@ class RequestCallbackWrapper : public CefCallback { IMPLEMENT_REFCOUNTING(RequestCallbackWrapper); }; +#ifdef OHOS_NETWORK_LOAD +class OhosInterceptCallbackWrapper : public CefInterceptCallback { + public: + using ResourceCallback = base::OnceCallback)>; + explicit OhosInterceptCallbackWrapper(ResourceCallback callback) + : callback_(std::move(callback)), + work_thread_task_runner_( + base::SequencedTaskRunner::GetCurrentDefault()) {} + + OhosInterceptCallbackWrapper(const OhosInterceptCallbackWrapper&) = delete; + OhosInterceptCallbackWrapper& operator=(const OhosInterceptCallbackWrapper&) = delete; + + ~OhosInterceptCallbackWrapper() override { + if (!callback_.is_null()) { + // Make sure it executes on the correct thread. + work_thread_task_runner_->PostTask( + FROM_HERE, base::BindOnce(std::move(callback_), nullptr)); + } + } + + void ContinueLoad(CefRefPtr resource_handler) override { + if (!work_thread_task_runner_->RunsTasksInCurrentSequence()) { + work_thread_task_runner_->PostTask( + FROM_HERE, + base::BindOnce(&OhosInterceptCallbackWrapper::ContinueLoad, this, resource_handler)); + return; + } + if (!callback_.is_null()) { + std::move(callback_).Run(resource_handler); + } + } + + private: + ResourceCallback callback_; + + scoped_refptr work_thread_task_runner_; + + IMPLEMENT_REFCOUNTING(OhosInterceptCallbackWrapper); +}; +#endif + #if OHOS_NETWORK_LOAD void OnRequestErrorInUiTask(CefRefPtr browser, CefRefPtr frame, @@ -147,7 +188,7 @@ void ReportITPResultInUiTask(CefRefPtr browser, return; } CefRefPtr load_handler = client->GetLoadHandler(); - if (load_handler) { + if (!load_handler) { LOG(ERROR) << "ReportITPResultInUiTask for load_handler is nullptr"; return; } @@ -677,9 +718,6 @@ class InterceptedRequestHandlerWrapper : public InterceptedRequestHandler { CEF_REQUIRE_IOT(); if (!cookie_helper::IsCookieableScheme(request->url, init_state_->cookieable_schemes_) -#if BUILDFLAG(IS_OHOS) - || !net_service::NetHelpers::IsThirdPartyCookieAllowed() -#endif ) { // The scheme does not support cookies. std::move(callback).Run(); @@ -724,26 +762,28 @@ class InterceptedRequestHandlerWrapper : public InterceptedRequestHandler { DCHECK(state->cookie_filter_); -#ifdef OHOS_ITP - bool itp_cookies_enabled = IsIntelligentTrackingPreventionEnabled(); - if (itp_cookies_enabled && request) { - bool third_party_cookie_access_policy = - ohos_anti_tracking::ThirdPartyCookieAccessPolicy::GetInstance() - ->AllowGetCookies(*request); - if (!third_party_cookie_access_policy) { - ReportITPResult(*request); - *allow = false; - return; - } - } -#endif // OHOS_ITP - CefCookie cef_cookie; if (net_service::MakeCefCookie(cookie, cef_cookie)) { *allow = state->cookie_filter_->CanSendCookie( init_state_->browser_, init_state_->frame_, state->pending_request_.get(), cef_cookie); } + +#ifdef OHOS_ITP + if (*allow == true) { + bool itp_cookies_enabled = IsIntelligentTrackingPreventionEnabled(); + if (itp_cookies_enabled && request) { + bool third_party_cookie_access_policy = + ohos_anti_tracking::ThirdPartyCookieAccessPolicy::GetInstance() + ->AllowGetCookies(*request, GetWebContentsLastCommittedURL()); + if (!third_party_cookie_access_policy) { + ReportITPResult(*request); + *allow = false; + return; + } + } + } +#endif } void ContinueWithLoadedCookies(int32_t request_id, @@ -866,7 +906,7 @@ class InterceptedRequestHandlerWrapper : public InterceptedRequestHandler { #if BUILDFLAG(IS_OHOS) auto response_cache = oh_code_cache::ResponseCache::CreateResponseCache(request->url.spec()); if (response_cache != nullptr && response_cache->CanUseCache()) { - TRACE_EVENT1("net", "Response Cache InterceptRequest", "url", request->url.spec().c_str()); + TRACE_EVENT1("net","Response Cache InterceptRequest", "url", request->url.spec().c_str()); auto resource_response = std::make_unique(std::move(response_cache)); std::move(callback).Run(std::move(resource_response)); return; @@ -911,6 +951,17 @@ class InterceptedRequestHandlerWrapper : public InterceptedRequestHandler { // The request will be handled by the NetworkService. Remove the // "Accept-Language" header here so that it can be re-added in // URLRequestHttpJob::AddExtraHeaders with correct ordering applied. +#if defined(OHOS_SCHEME_HANDLER) + // Get the chunked data pipe remote back. + if (state->pending_request_) { + CefRefPtr post_data_stream = state->pending_request_->GetUploadStream(); + if (post_data_stream && post_data_stream->IsChunked()) { + LOG(INFO) << "scheme_handler get the chunked stream back."; + static_cast(post_data_stream.get()) + ->GetChunkedDataPipeGetter(request->request_body.get()); + } + } +#endif } // Continue the request. @@ -920,7 +971,8 @@ class InterceptedRequestHandlerWrapper : public InterceptedRequestHandler { void GetOhosResourceHandlerInUiTask( int32_t request_id, network::ResourceRequest* request, - ShouldInterceptRequestResultCallback callback) { + ShouldInterceptRequestResultCallback callback, + std::string url) { CEF_REQUIRE_UIT(); RequestState* state = GetState(request_id); if (!state) { @@ -942,9 +994,11 @@ class InterceptedRequestHandlerWrapper : public InterceptedRequestHandler { // Try to get scheme handler from ets UI thread. if (!resource_handler && state->scheme_factory_) { // Does the scheme factory want to handle the request? - resource_handler = state->scheme_factory_->Create( + if (!url.starts_with("hwweb")) { + resource_handler = state->scheme_factory_->Create( init_state_->browser_, init_state_->frame_, request->url.scheme(), state->pending_request_.get()); + } } CEF_POST_TASK( @@ -955,10 +1009,70 @@ class InterceptedRequestHandlerWrapper : public InterceptedRequestHandler { resource_handler, std::move(callback))); } + void GetOhosResourceHandlerResultInIO(int32_t request_id, + network::ResourceRequest* request, + ShouldInterceptRequestResultCallback callback, + CefRefPtr resource_handler) { + CEF_REQUIRE_IOT(); + GetOhosResourceHandlerResult(request_id, request, resource_handler, std::move(callback)); + } + + void GetOhosResourceHandlerStillInIO( + int32_t request_id, + network::ResourceRequest* request, + ShouldInterceptRequestResultCallback callback) { + CEF_REQUIRE_IOT(); + RequestState* state = GetState(request_id); + if (!state || !request) { + std::move(callback).Run(nullptr); + return; + } + CefRefPtr callback_ptr = + new OhosInterceptCallbackWrapper(base::BindOnce( + &InterceptedRequestHandlerWrapper::GetOhosResourceHandlerResultInIO, + weak_ptr_factory_.GetWeakPtr(), + request_id, base::Unretained(request), std::move(callback))); + + if (state->handler_) { + // Does the client want to handle the request? + if (request) { + state->pending_request_->SetDestination(request->destination); + } + state->handler_->GetResourceHandlerByIO( + init_state_->browser_, init_state_->frame_, + state->pending_request_.get(), callback_ptr, state->scheme_factory_, + request->url.scheme()); + } else { + GetOhosResourceHandlerFromETS(state->scheme_factory_, state->pending_request_.get(), + request->url.scheme(), callback_ptr); + } + } + + void GetOhosResourceHandlerFromETS(CefRefPtr scheme_factory, + CefRefPtr request, + const CefString& scheme, + CefRefPtr callback) { + if (!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) { + content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE, + base::BindOnce(&InterceptedRequestHandlerWrapper::GetOhosResourceHandlerFromETS, + weak_ptr_factory_.GetWeakPtr(), + scheme_factory, request, scheme, callback)); + return; + } + + CefRefPtr resource_handler = nullptr; + if (scheme_factory) { + // Does the scheme factory want to handle the request? + resource_handler = scheme_factory->Create( + init_state_->browser_, init_state_->frame_, scheme, request); + } + callback->ContinueLoad(resource_handler); + } + void GetOhosResourceHandler(int32_t request_id, network::ResourceRequest* request, ShouldInterceptRequestResultCallback callback) { - #ifdef OHOS_NETWORK_LOAD +#ifdef OHOS_NETWORK_LOAD RequestState* state = GetState(request_id); if (state && request) { // Add fetch meta data headers. @@ -977,22 +1091,23 @@ class InterceptedRequestHandlerWrapper : public InterceptedRequestHandler { } state->pending_request_->SetFrameUrl(frame_url); } + bool has_user_activation = false; + if (request->trusted_params) { + has_user_activation = request->trusted_params->has_user_activation; + } std::map headers = network::GetFetchMetadataHeaders( - request->url, request->mode, request->has_user_gesture, + request->url, request->mode, has_user_activation, request->destination, request->request_initiator); for (auto& entry : headers) { state->pending_request_->SetHeaderByName(entry.first, entry.second, false); } state->pending_request_->SetReadOnly(old_flag); } - #endif - CEF_POST_TASK( - CEF_UIT, - base::BindOnce( - &InterceptedRequestHandlerWrapper::GetOhosResourceHandlerInUiTask, - weak_ptr_factory_.GetWeakPtr(), request_id, request, - std::move(callback))); +#endif + + CEF_REQUIRE_IOT(); + GetOhosResourceHandlerStillInIO(request_id, request, std::move(callback)); } #endif @@ -1210,10 +1325,11 @@ class InterceptedRequestHandlerWrapper : public InterceptedRequestHandler { std::move(exec_callback).Run(); return; } - // Clear the headers first. we will get cookie for this redirect. - request->headers.Clear(); + // Clear the cookie first. we will get cookie for this redirect. + request->headers.RemoveHeader(net::HttpRequestHeaders::kCookie); // Get cookies for redirect url. request->url = new_url; + MaybeLoadCookies(request_id, state, request, std::move(exec_callback)); } #endif @@ -1283,9 +1399,6 @@ class InterceptedRequestHandlerWrapper : public InterceptedRequestHandler { if (!cookie_helper::IsCookieableScheme(request->url, init_state_->cookieable_schemes_) -#if BUILDFLAG(IS_OHOS) - || !net_service::NetHelpers::IsThirdPartyCookieAllowed() -#endif ) { // The scheme does not support cookies. std::move(callback).Run(); @@ -1676,6 +1789,13 @@ class InterceptedRequestHandlerWrapper : public InterceptedRequestHandler { CefString(request.url.host()), CefString(request.request_initiator->host()))); } + + GURL GetWebContentsLastCommittedURL() { + if (!init_state_ || !init_state_->browser_) { + return GURL(); + } + return init_state_->browser_->GetLastCommittedURL(); + } #endif scoped_refptr init_helper_; @@ -1811,7 +1931,7 @@ std::unique_ptr CreateInterceptedRequestHandler( browserPtr = CefBrowserHostBase::GetBrowserForHost(frame); #ifdef OHOS_NETWORK_LOAD bool is_guest_view = false; - if (browserPtr->browser_info()) { + if (browserPtr && browserPtr->browser_info()) { realFramePtr = browserPtr->browser_info()->GetFrameForHost(frame, &is_guest_view, true); } diff --git a/libcef/browser/net_service/restrict_cookie_manager.cc b/libcef/browser/net_service/restrict_cookie_manager.cc index 148fd87d2..9eadd07ad 100644 --- a/libcef/browser/net_service/restrict_cookie_manager.cc +++ b/libcef/browser/net_service/restrict_cookie_manager.cc @@ -18,6 +18,11 @@ #include "net_helpers.h" #include "url/gurl.h" +#if defined(OHOS_EX_EXCEPTION_LIST) +#include "base/command_line.h" +#include "content/public/common/content_switches.h" +#endif + class ProxyingRestrictedCookieManagerListener : public network::mojom::CookieChangeListener { public: @@ -74,6 +79,21 @@ void ProxyingRestrictedCookieManager::GetAllForUrl( GetAllForUrlCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); +#if defined(OHOS_EX_EXCEPTION_LIST) + if (base::CommandLine::ForCurrentProcess()->HasSwitch( + switches::kForBrowser)) { + if (site_for_cookies.IsFirstParty(url) || + AllowCookies(url, site_for_cookies)) { + underlying_restricted_cookie_manager_->GetAllForUrl( + url, site_for_cookies, top_frame_origin, has_storage_access, + std::move(options), std::move(callback)); + return; + } + std::move(callback).Run(std::vector()); + return; + } +#endif // defined(OHOS_EX_EXCEPTION_LIST) + if (AllowCookies(url, site_for_cookies)) { underlying_restricted_cookie_manager_->GetAllForUrl( url, site_for_cookies, top_frame_origin, has_storage_access, @@ -93,6 +113,21 @@ void ProxyingRestrictedCookieManager::SetCanonicalCookie( SetCanonicalCookieCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); +#if defined(OHOS_EX_EXCEPTION_LIST) + if (base::CommandLine::ForCurrentProcess()->HasSwitch( + switches::kForBrowser)) { + if (site_for_cookies.IsFirstParty(url) || + AllowCookies(url, site_for_cookies)) { + underlying_restricted_cookie_manager_->SetCanonicalCookie( + cookie, url, site_for_cookies, top_frame_origin, has_storage_access, + status, std::move(callback)); + return; + } + std::move(callback).Run(false); + return; + } +#endif // defined(OHOS_EX_EXCEPTION_LIST) + if (AllowCookies(url, site_for_cookies)) { underlying_restricted_cookie_manager_->SetCanonicalCookie( cookie, url, site_for_cookies, top_frame_origin, has_storage_access, @@ -151,6 +186,22 @@ void ProxyingRestrictedCookieManager::SetCookieFromString( SetCookieFromStringCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); +#if defined(OHOS_EX_EXCEPTION_LIST) + if (base::CommandLine::ForCurrentProcess()->HasSwitch( + switches::kForBrowser)) { + if (site_for_cookies.IsFirstParty(url) || + AllowCookies(url, site_for_cookies)) { + underlying_restricted_cookie_manager_->SetCookieFromString( + url, site_for_cookies, top_frame_origin, has_storage_access, cookie, + std::move(callback)); + return; + } + std::move(callback).Run(/*site_for_cookies_ok=*/true, + /*top_frame_origin_ok=*/true); + return; + } +#endif // defined(OHOS_EX_EXCEPTION_LIST) + if (AllowCookies(url, site_for_cookies)) { underlying_restricted_cookie_manager_->SetCookieFromString( url, site_for_cookies, top_frame_origin, has_storage_access, cookie, @@ -169,6 +220,21 @@ void ProxyingRestrictedCookieManager::GetCookiesString( GetCookiesStringCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); +#if defined(OHOS_EX_EXCEPTION_LIST) + if (base::CommandLine::ForCurrentProcess()->HasSwitch( + switches::kForBrowser)) { + if (site_for_cookies.IsFirstParty(url) || + AllowCookies(url, site_for_cookies)) { + underlying_restricted_cookie_manager_->GetCookiesString( + url, site_for_cookies, top_frame_origin, has_storage_access, + std::move(callback)); + return; + } + std::move(callback).Run(""); + return; + } +#endif // defined(OHOS_EX_EXCEPTION_LIST) + if (AllowCookies(url, site_for_cookies)) { underlying_restricted_cookie_manager_->GetCookiesString( url, site_for_cookies, top_frame_origin, has_storage_access, diff --git a/libcef/browser/net_service/stream_reader_url_loader.cc b/libcef/browser/net_service/stream_reader_url_loader.cc index 6f3e00046..47e9b5f8d 100644 --- a/libcef/browser/net_service/stream_reader_url_loader.cc +++ b/libcef/browser/net_service/stream_reader_url_loader.cc @@ -648,12 +648,12 @@ void StreamReaderURLLoader::HeadersComplete(int orig_status_code, &content_length, &extra_headers); LOG(DEBUG) << "intercept StreamReaderURLLoader::HeadersComplete" - << " request_id=" << request_id_ - << " status_code=" << status_code - << " status_text=" << status_text - << " mime_type=" << mime_type - << " charset=" << charset - << " content_length=" << content_length; + << " request_id_=" << request_id_ + << " status_code=" << status_code + << " status_text=" << status_text + << " mime_type=" << mime_type + << " charset=" << charset + << " content_length=" << content_length; if (status_code < 0) { // Early exit if the handler reported an error. RequestComplete(status_code); @@ -826,10 +826,10 @@ void StreamReaderURLLoader::ContinueWithResponseHeaders( client_->OnReceiveResponse(std::move(pending_response), std::move(consumer_handle), std::move(cached_metadata_)); - + #if BUILDFLAG(IS_OHOS) LOG(DEBUG) << "intercept StreamReaderURLLoader::ContinueWithResponseHeaders request_id_=" << request_id_ - << ", request_.is_sync_mode=" << request_.is_sync_mode; + << ", request_.is_sync_mode=" << request_.is_sync_mode; if (!request_.is_sync_mode || !TryTransferDataWithSharedMemory()) { ReadMore(); } diff --git a/libcef/browser/osr/browser_platform_delegate_osr.cc b/libcef/browser/osr/browser_platform_delegate_osr.cc index aa8622ef3..1c0de77d7 100644 --- a/libcef/browser/osr/browser_platform_delegate_osr.cc +++ b/libcef/browser/osr/browser_platform_delegate_osr.cc @@ -1003,6 +1003,7 @@ CefRenderWidgetHostViewOSR* CefBrowserPlatformDelegateOsr::GetOSRHostView() if (!web_contents_) { return nullptr; } + content::RenderViewHost* host = web_contents_->GetRenderViewHost(); if (host) { return static_cast( @@ -1192,6 +1193,12 @@ void CefBrowserPlatformDelegateOsr::OnTextSelected(bool flag) { } } +void CefBrowserPlatformDelegateOsr::OnDestroyImageAnalyzerOverlay() { + if (CefRenderWidgetHostViewOSR* view = GetOSRHostView()) { + view->OnDestroyImageAnalyzerOverlay(); + } +} + float CefBrowserPlatformDelegateOsr::GetPageScaleFactor() { if (CefRenderWidgetHostViewOSR* view = GetOSRHostView()) { return view->GetPageScaleFactor(); diff --git a/libcef/browser/osr/browser_platform_delegate_osr.h b/libcef/browser/osr/browser_platform_delegate_osr.h index 5bdab9ebf..0879125e2 100644 --- a/libcef/browser/osr/browser_platform_delegate_osr.h +++ b/libcef/browser/osr/browser_platform_delegate_osr.h @@ -186,6 +186,7 @@ class CefBrowserPlatformDelegateOsr const gfx::Point& touch_point, const gfx::Rect& screen_rect) override; void OnTextSelected(bool flag) override; + void OnDestroyImageAnalyzerOverlay() override; float GetPageScaleFactor() override; #endif diff --git a/libcef/browser/osr/render_widget_host_view_osr.cc b/libcef/browser/osr/render_widget_host_view_osr.cc index a79404464..0831d1735 100644 --- a/libcef/browser/osr/render_widget_host_view_osr.cc +++ b/libcef/browser/osr/render_widget_host_view_osr.cc @@ -54,7 +54,6 @@ #include "ui/gfx/geometry/dip_util.h" #include "ui/gfx/geometry/size_conversions.h" #include "ui/touch_selection/touch_selection_controller.h" -#include "ohos_nweb/src/nweb_resize_helper.h" #ifdef OHOS_EX_TOPCONTROLS #include "content/browser/renderer_host/render_view_host_delegate_view.h" @@ -89,14 +88,11 @@ namespace { // The maximum number of damage rects to cache for outstanding frame requests // (for OnAcceleratedPaint). const size_t kMaxDamageRects = 10; -const int SOC_PERF_WEB_DRAG_RESIZE_ID = 10073; const float kDefaultScaleFactor = 1.0; #if BUILDFLAG(IS_OHOS) #if defined(OHOS_PERFORMANCE_JITTER) const size_t kMaxGestureQueueSize = 10; - -const size_t KTouchEventCachedThreaShold = 1; const int SOC_PERF_WEB_GESTURE_ID = 10012; const int TOUCH_DOWN_DELAY_TIME = 200; const int TOUCH_UP_DURATION_TIME = 100; @@ -406,7 +402,6 @@ CefRenderWidgetHostViewOSR::CefRenderWidgetHostViewOSR( compositor->SetAcceleratedWidget(browser_impl_->GetAcceleratedWidget()); CefRenderWidgetHostViewOSR::AddCompositor( browser_impl_->GetAcceleratedWidget(), compositor); - UpdateDrawMode(); } #endif // IS_OHOS #endif @@ -790,6 +785,9 @@ void CefRenderWidgetHostViewOSR::SendTouchEventList(const std::vectordelegate()->GetInputEventRouter()->RouteTouchEvent( - this, &touch_event, latency_info); - } else { - render_widget_host_->ForwardTouchEventWithLatencyInfo(touch_event, - latency_info); - } -} -#endif - void CefRenderWidgetHostViewOSR::EvictFrameBackBuffers(bool invisible) { TRACE_EVENT1("base", "CefRenderWidgetHostViewOSR::EvictFrameBackBuffers", "invisible", invisible); @@ -1356,14 +1347,6 @@ void CefRenderWidgetHostViewOSR::SetFitContentMode(int mode) { is_fit_content_ = mode; } -void CefRenderWidgetHostViewOSR::UpdateDrawMode() { - int mode = browser_impl_->GetDrawMode(); - if (auto compositor = CefRenderWidgetHostViewOSR::GetCompositor( - browser_impl_->GetAcceleratedWidget())) { - compositor->SetDrawMode(mode); - } -} - bool CefRenderWidgetHostViewOSR::GetPendingSizeStatus() { return false; } @@ -1643,6 +1626,9 @@ bool CefRenderWidgetHostViewOSR::WebPageSnapshot( height = (std::abs(height) * pageSize.height()) / 100; } + pageSize.Scale(page_scale_factor_); + pageOffsize.Scale(page_scale_factor_); + software_compositor_->DemandDrawSwAsync(id, width, height, pageSize, pageOffsize, std::move(callback)); return true; @@ -1670,7 +1656,7 @@ void CefRenderWidgetHostViewOSR::OnRenderFrameMetadataChangedBeforeActivation( if (for_browser_) { // Set parameters for adaptive handle orientation. gfx::SizeF viewport_size(metadata.scrollable_viewport_size); - viewport_size.Scale(metadata.page_scale_factor); + viewport_size.Scale(page_scale_factor_); gfx::RectF viewport_rect(0.0f, metadata.top_controls_height * metadata.top_controls_shown_ratio / @@ -1754,17 +1740,6 @@ void CefRenderWidgetHostViewOSR::OnRenderFrameMetadataChangedAfterActivation( } #endif -#if defined(OHOS_INPUT_EVENTS) - if (size_changed && needFocusViewport_ > 0) { - CefRefPtr handler = - browser_impl_->GetClient()->GetRenderHandler(); - if (handler) { - needFocusViewport_--; - handler->OnResizeScrollableViewport(browser_impl_->GetBrowser()); - } - } -#endif - gfx::Size viewport_size_in_pixels = metadata.viewport_size_in_pixels; float device_scale_factor = metadata.device_scale_factor; if (viewport_size_in_pixels != viewport_size_in_pixels_ || @@ -1803,12 +1778,10 @@ void CefRenderWidgetHostViewOSR::OnRenderFrameMetadataChangedAfterActivation( selection_start_ = metadata.selection.start; selection_end_ = metadata.selection.end; #ifdef OHOS_CLIPBOARD - // When all is selected, the right handle coordinates are in front of the left handle. + // When all is selected, the right handle coordinates are in front of the left handle if (metadata.selection.start.edge_end().y() > metadata.selection.end.edge_end().y()) { - selection_end_.SetEdgeEnd(gfx::PointF(metadata.clipped_selection_bounds.x() + - metadata.clipped_selection_bounds.width(), - metadata.clipped_selection_bounds.y() + - metadata.clipped_selection_bounds.height())); + selection_end_.SetEdgeEnd(gfx::PointF(clipped_selection_bounds_.x() + clipped_selection_bounds_.width(), + clipped_selection_bounds_.y() + clipped_selection_bounds_.height())); } #endif selection_controller_client_->UpdateClientSelectionBounds(selection_start_, @@ -1821,6 +1794,16 @@ void CefRenderWidgetHostViewOSR::OnRenderFrameMetadataChangedAfterActivation( selection_controller_client_->UpdateClientClippedSelectionBounds(clipped_selection_bounds_); } #endif // OHOS_CLIPBOARD + +#if defined(OHOS_INPUT_EVENTS) + if (size_changed) { + CefRefPtr handler = + browser_impl_->GetClient()->GetRenderHandler(); + if (handler) { + handler->OnResizeScrollableViewport(browser_impl_->GetBrowser()); + } + } +#endif } std::unique_ptr @@ -1983,7 +1966,9 @@ void CefRenderWidgetHostViewOSR::SynchronizeVisualProperties( if (render_widget_host_) { #if defined(OHOS_COMPOSITE_RENDER) if (isKeyboard) { - needFocusViewport_++; + LOG(INFO) << "scroll focused node into view"; + render_widget_host_->SynchronizeVisualProperties(isKeyboard); + return; } #endif // defined(OHOS_COMPOSITE_RENDER) render_widget_host_->SynchronizeVisualProperties(); @@ -2264,7 +2249,6 @@ void CefRenderWidgetHostViewOSR::SendMouseWheelEvent( if (render_widget_host_ && render_widget_host_->GetView()) { blink::WebMouseWheelEvent mouse_wheel_event(event); - #if defined(OHOS_INPUT_EVENTS) bool shouldRoute = ShouldRouteEvents(); mouse_wheel_phase_handler_.SendWheelEndForTouchpadScrollingIfNeeded(shouldRoute); @@ -2275,7 +2259,6 @@ void CefRenderWidgetHostViewOSR::SendMouseWheelEvent( mouse_wheel_phase_handler_.AddPhaseIfNeededAndScheduleEndEvent( mouse_wheel_event, false); #endif - if (ShouldRouteEvents()) { render_widget_host_->delegate() ->GetInputEventRouter() @@ -2289,6 +2272,19 @@ void CefRenderWidgetHostViewOSR::SendMouseWheelEvent( } } +#if defined(OHOS_PERFORMANCE_JITTER) +void CefRenderWidgetHostViewOSR::SendTouchGestureEvent(blink::WebTouchEvent& touch_event) { + ui::LatencyInfo latency_info = CreateLatencyInfo(touch_event); + if (ShouldRouteEvents()) { + render_widget_host_->delegate()->GetInputEventRouter()->RouteTouchEvent( + this, &touch_event, latency_info); + } else { + render_widget_host_->ForwardTouchEventWithLatencyInfo(touch_event, + latency_info); + } +} +#endif + void CefRenderWidgetHostViewOSR::SendTouchEvent(const CefTouchEvent& event) { TRACE_EVENT0("cef", "CefRenderWidgetHostViewOSR::SendTouchEvent"); @@ -2334,6 +2330,9 @@ void CefRenderWidgetHostViewOSR::SendTouchEvent(const CefTouchEvent& event) { // Update the touch event first. #ifdef OHOS_CLIPBOARD pointer_state_.SetFromOverlay(event.from_overlay); + if (event.from_overlay) { + TriggerVsync(); + } #endif // #ifdef OHOS_CLIPBOARD if (!pointer_state_.OnTouch(event)) { return; @@ -2352,11 +2351,7 @@ void CefRenderWidgetHostViewOSR::SendTouchEvent(const CefTouchEvent& event) { gesture_provider_.OnTouchEvent(pointer_state_); blink::WebTouchEvent touch_event = ui::CreateWebTouchEventFromMotionEvent( - pointer_state_, result.moved_beyond_slop_region, false -#if BUILDFLAG(IS_OHOS) - , is_fit_content_ -#endif - ); + pointer_state_, result.moved_beyond_slop_region, false); pointer_state_.CleanupRemovedTouchPoints(event); @@ -2436,7 +2431,6 @@ void CefRenderWidgetHostViewOSR::OnTouchDown() { base::BindOnce(&CefRenderWidgetHostViewOSR::StopBoosting, weak_ptr_factory_.GetWeakPtr()), TOUCH_UP_DURATION_TIME); isBoosting_ = false; - // maintaince 120fps for 3s if (auto* host = content::GpuProcessHost::Get()) { if (auto* host_impl = host->gpu_host()) { host_impl->SetHasTouchPoint(false); @@ -2448,6 +2442,8 @@ void CefRenderWidgetHostViewOSR::OnTouchDown() { OHOS::NWeb::OhosAdapterHelper::GetInstance() .CreateSocPerfClientAdapter() ->ApplySocPerfConfigByIdEx(SOC_PERF_WEB_GESTURE_ID, true); + OHOS::NWeb::ResSchedClientAdapter::ReportScene( + OHOS::NWeb::ResSchedStatusAdapter::WEB_SCENE_ENTER, OHOS::NWeb::ResSchedSceneAdapter::SLIDE); if (!isBoosting_) { if (auto* host = content::GpuProcessHost::Get()) { if (auto* host_impl = host->gpu_host()) { @@ -2457,8 +2453,8 @@ void CefRenderWidgetHostViewOSR::OnTouchDown() { } isBoosting_ = true; CEF_POST_DELAYED_TASK(CEF_UIT, - base::BindOnce(&CefRenderWidgetHostViewOSR::OnTouchDown, - weak_ptr_factory_.GetWeakPtr()), TOUCH_DOWN_DELAY_TIME); + base::BindOnce(&CefRenderWidgetHostViewOSR::OnTouchDown, + weak_ptr_factory_.GetWeakPtr()), TOUCH_DOWN_DELAY_TIME); } #endif @@ -2667,12 +2663,6 @@ void CefRenderWidgetHostViewOSR::OnVsync() { gesture_event_queue_.clear(); } - if (web_touch_event_queue_.size() > KTouchEventCachedThreaShold) { - blink::WebTouchEvent touchEvent = web_touch_event_queue_.front(); - SendTouchGestureEvent(touchEvent); - web_touch_event_queue_.pop_front(); - } - if (!gesture_event_queue_.empty()) { SendGestureEvent(std::move(gesture_event_queue_.front())); gesture_event_queue_.pop_front(); @@ -2687,7 +2677,7 @@ void CefRenderWidgetHostViewOSR::OnVsyncReceived() { << web_touch_event_queue_.size(); } - while (!web_touch_event_queue_.empty()) { + if (!web_touch_event_queue_.empty()) { blink::WebTouchEvent touchEvent = web_touch_event_queue_.front(); SendTouchGestureEvent(touchEvent); web_touch_event_queue_.pop_front(); @@ -2738,6 +2728,9 @@ void CefRenderWidgetHostViewOSR::SendGestureEvent( selection_controller_->HandleLongPressEvent( web_event.TimeStamp(), web_event.PositionInWidget()); break; + case blink::WebInputEvent::Type::kGestureScrollBegin: + selection_controller_->OnScrollBeginEvent(); + break; default: break; } @@ -3029,12 +3022,9 @@ bool CefRenderWidgetHostViewOSR::ResizeRootLayer(bool isKeyboard, bool& visible_ bool CefRenderWidgetHostViewOSR::ResizeRootLayer() { #endif if (!hold_resize_) { + bool reseize = SetRootLayerSize(false /* force */, &visible_changed); // The resize hold is not currently active. -#if defined(OHOS_INPUT_EVENTS) - if (SetRootLayerSize(false /* force */, &visible_changed)) { -#else - if (SetRootLayerSize(false /* force */)) { -#endif + if (reseize) { // The size has changed. Avoid resizing again until ReleaseResizeHold() is // called. hold_resize_ = true; @@ -3063,12 +3053,12 @@ void CefRenderWidgetHostViewOSR::ReleaseResizeHold() { isKeyboardResized_ = false; CEF_POST_TASK(CEF_UIT, base::BindOnce(&CefRenderWidgetHostViewOSR::WasKeyboardResized, - weak_ptr_factory_.GetWeakPtr())); + weak_ptr_factory_.GetWeakPtr())); } else { #endif CEF_POST_TASK(CEF_UIT, base::BindOnce(&CefRenderWidgetHostViewOSR::WasResized, - weak_ptr_factory_.GetWeakPtr())); + weak_ptr_factory_.GetWeakPtr())); #if defined(OHOS_COMPOSITE_RENDER) } #endif @@ -3078,13 +3068,6 @@ void CefRenderWidgetHostViewOSR::ReleaseResizeHold() { browser_impl_->client()->GetRenderHandler(); CHECK(handler); } - bool isDragResized = OHOS::NWeb::NWebResizeHelper::GetInstance().IsDragResizeStart(); - if (isDragResized) { - OHOS::NWeb::OhosAdapterHelper::GetInstance() - .CreateSocPerfClientAdapter() - ->ApplySocPerfConfigByIdEx(SOC_PERF_WEB_DRAG_RESIZE_ID, false); - OHOS::NWeb::NWebResizeHelper::GetInstance().SetDragResizeStart(false); - } } void CefRenderWidgetHostViewOSR::CancelWidget() { @@ -3249,8 +3232,8 @@ std::vector CefRenderWidgetHostViewOSR::GetWordSelection(const std::stri if (browser_impl_.get()) { CefRefPtr handler = browser_impl_->client()->GetRenderHandler(); - CHECK(handler); - handler->GetWordSelection(browser_impl_.get(), text, offset, temp); + CHECK(handler); + handler->GetWordSelection(browser_impl_.get(), text, offset, temp); } std::vector select = { temp.x, temp.y }; return select; @@ -3416,14 +3399,6 @@ std::pair CefRenderWidgetHostViewOSR::HandleCursorOffset() { return std::make_pair(x, y); } -void CefRenderWidgetHostViewOSR::DynamicFrameLossEvent(const std::string& sceneId, bool isStart) { - if (browser_impl_.get()) { - CefRefPtr handler = browser_impl_->client()->GetRenderHandler(); - CHECK(handler); - handler->SendDynamicFrameLossEvent(browser_impl_.get(), sceneId, isStart); - } -} - void CefRenderWidgetHostViewOSR::DidOverscroll( const ui::DidOverscrollParams& params) { if (browser_impl_.get()) { @@ -3551,7 +3526,7 @@ void CefRenderWidgetHostViewOSR::FilterScrollEventImpl( #ifdef OHOS_EX_TOPCONTROLS int CefRenderWidgetHostViewOSR::GetTopControlsOffset() const { - return for_browser_ ? top_controls_offset_ : 0; + return (for_browser_ ? top_controls_offset_ : 0); } int CefRenderWidgetHostViewOSR::GetShrinkViewportHeight() { @@ -3628,9 +3603,10 @@ void CefRenderWidgetHostViewOSR::SetVirtualKeyBoardArg(int32_t width, int32_t he void CefRenderWidgetHostViewOSR::DidNativeEmbedEvent(const blink::mojom::NativeEmbedTouchEventPtr& touchEvent) { if (touchEvent->type == blink::mojom::NativeTouchType::UP) { gesture_provider_.SetNativeEmbedEnabled(false); - } else { + }else{ gesture_provider_.SetNativeEmbedEnabled(true); } + if (browser_impl_.get()) { CefRefPtr handler = browser_impl_->client()->GetRenderHandler(); @@ -3656,13 +3632,13 @@ void CefRenderWidgetHostViewOSR::OnNativeEmbedLifecycleChange(const CefRenderHan } } -void CefRenderWidgetHostViewOSR::OnNativeEmbedVisibilityChange(const std::string& embed_id, bool visibility) { +void CefRenderWidgetHostViewOSR::OnNativeEmbedVisibilityChange(const std::string& embed_id, bool visibility){ if (browser_impl_.get()) { CefRefPtr handler = browser_impl_->client()->GetRenderHandler(); CHECK(handler); + handler->OnNativeEmbedVisibilityChange(embed_id, visibility); - } } @@ -3674,6 +3650,11 @@ void CefRenderWidgetHostViewOSR::SetGestureEventResult(bool result) { gesture_provider_.SetNativeEmbedEnabled(false); } render_widget_host_->input_router()->SetGestureEventResult(result); + CefRefPtr handler = + browser_impl_->client()->GetRenderHandler(); + if (handler) { + handler->SetGestureEventResult(result); + } } void CefRenderWidgetHostViewOSR::SetScrollable(bool enable) { @@ -3744,6 +3725,12 @@ void CefRenderWidgetHostViewOSR::OnTextSelected(bool flag) { } } +void CefRenderWidgetHostViewOSR::OnDestroyImageAnalyzerOverlay() { + if (render_widget_host_) { + render_widget_host_->OnDestroyImageAnalyzerOverlay(); + } +} + float CefRenderWidgetHostViewOSR::GetPageScaleFactor() { return page_scale_factor_; } diff --git a/libcef/browser/osr/render_widget_host_view_osr.h b/libcef/browser/osr/render_widget_host_view_osr.h index fac31b00d..d464cd7d0 100644 --- a/libcef/browser/osr/render_widget_host_view_osr.h +++ b/libcef/browser/osr/render_widget_host_view_osr.h @@ -142,9 +142,9 @@ class CefRenderWidgetHostViewOSR void EvictFrameBackBuffers(bool invisible) override; void UpdateVSyncFrequency(); void ResetVSyncFrequency(); + void UpdateDrawRect(const gfx::Rect &rect); void NotifyForNextTouchEvent(bool need_wait_for_touch_move = true); void TriggerVsync(); - void UpdateDrawRect(const gfx::Rect &rect); #endif #ifdef OHOS_EX_TOPCONTROLS gfx::Rect GetPhysicalViewBounds(); @@ -213,7 +213,6 @@ class CefRenderWidgetHostViewOSR #if BUILDFLAG(IS_OHOS) void SendInternalBeginFrame() override; ui::Compositor* GetCompositor() override; - void UpdateDrawMode(); #endif #if !BUILDFLAG(IS_MAC) @@ -336,7 +335,6 @@ class CefRenderWidgetHostViewOSR void FocusedNodeChanged(bool is_editable_node, const gfx::Rect& node_bounds_in_screen) override; void DidOverscroll(const ui::DidOverscrollParams& params) override; - void DynamicFrameLossEvent(const std::string& sceneId, bool isStart) override; void DidStopFlinging() override; blink::mojom::InputEventResultState FilterInputEvent( const blink::WebInputEvent& input_event) override; @@ -364,10 +362,10 @@ class CefRenderWidgetHostViewOSR void SendTouchpadFlingEvent(blink::WebGestureEvent event); void SendMouseWheelEvent(const blink::WebMouseWheelEvent& event); void SendTouchEvent(const CefTouchEvent& event); + bool ShouldRouteEvents() const; #ifdef OHOS_CLIPBOARD void ResetGestureDetection(bool is_lost_focus); #endif - bool ShouldRouteEvents() const; void SetFocus(bool focus); void UpdateFrameRate(); @@ -438,8 +436,8 @@ class CefRenderWidgetHostViewOSR #if BUILDFLAG(IS_OHOS) bool IsMouseLocked() override; - void SetDoubleTapSupportEnabled(bool enabled); - void SetMultiTouchZoomSupportEnabled(bool enabled); + void SetDoubleTapSupportEnabled(bool enabled) override; + void SetMultiTouchZoomSupportEnabled(bool enabled) override; static void AddCompositor(gfx::AcceleratedWidget widget, ui::Compositor* compositor); @@ -469,6 +467,7 @@ class CefRenderWidgetHostViewOSR #ifdef OHOS_AI void OnTextSelected(bool flag); + void OnDestroyImageAnalyzerOverlay(); float GetPageScaleFactor(); #endif @@ -721,7 +720,6 @@ class CefRenderWidgetHostViewOSR #ifdef OHOS_AI bool overlay_in_progress_ = false; #endif - int32_t needFocusViewport_ = 0; base::WeakPtrFactory weak_ptr_factory_; }; diff --git a/libcef/browser/osr/touch_handle_drawable_osr.cc b/libcef/browser/osr/touch_handle_drawable_osr.cc index d021a2170..6d6a8ba0e 100644 --- a/libcef/browser/osr/touch_handle_drawable_osr.cc +++ b/libcef/browser/osr/touch_handle_drawable_osr.cc @@ -158,13 +158,13 @@ void CefTouchHandleDrawableOSR::UpdateVisiableBounds() { int handle_width = image_size.width() + 2 * kSelectionHandlePadding; int handle_height = image_size.height() + 2 * kSelectionHandlePadding; if (orientation_ != ui::TouchHandleOrientation::LEFT) { - relative_bounds_ = gfx::RectF(-handle_width / 2.0, 0, - handle_width, handle_height); + relative_bounds_ = gfx::RectF(-handle_width / 2.0, -edge_height_, + handle_width, handle_height + edge_height_); } else { relative_bounds_ = gfx::RectF(-handle_width / 2.0, -edge_height_ - handle_height, - handle_width, handle_height); + handle_width, handle_height + edge_height_); } } #endif // #ifdef OHOS_CLIPBOARD diff --git a/libcef/browser/osr/touch_selection_controller_client_osr.cc b/libcef/browser/osr/touch_selection_controller_client_osr.cc index 02cead954..f4a441dbb 100644 --- a/libcef/browser/osr/touch_selection_controller_client_osr.cc +++ b/libcef/browser/osr/touch_selection_controller_client_osr.cc @@ -32,7 +32,12 @@ namespace { // Delay before showing the quick menu, in milliseconds. +#ifdef OHOS_DRAG_DROP +constexpr int kQuickMenuDelayInMs = 0; +#else constexpr int kQuickMenuDelayInMs = 100; +#endif + #ifdef OHOS_CLIPBOARD constexpr int kSelectHandleMoveDelayMixInMs = 400; constexpr cef_quick_menu_edit_state_flags_t kMenuCommands[] = { @@ -485,17 +490,17 @@ void CefTouchSelectionControllerClientOSR::MouseSelectMenuShow(bool show) { } } } - LOG(INFO) << "Mouse Quit Menu Flags Is = " << quickmenuflags; + LOG(INFO) << "Mouse Quick Menu Flags Is = " << quickmenuflags; CefRefPtr callbackImpl( - new CefRunQuickMenuCallbackImpl(base::BindOnce( - &CefTouchSelectionControllerClientOSR::ExecuteCommandMouse, - weak_ptr_factory_.GetWeakPtr()))); + new CefRunQuickMenuCallbackImpl(base::BindOnce( + &CefTouchSelectionControllerClientOSR::ExecuteCommandMouse, + weak_ptr_factory_.GetWeakPtr()))); if (!handler->RunQuickMenu( - browser, browser->GetFocusedFrame(), {0, 0}, {0, 0}, - {clipped_selection_bounds_.x(), clipped_selection_bounds_.y(), - clipped_selection_bounds_.width(), clipped_selection_bounds_.height()}, - static_cast(quickmenuflags), - callbackImpl, true)) { + browser, browser->GetFocusedFrame(), {0, 0}, {0, 0}, + {clipped_selection_bounds_.x(), clipped_selection_bounds_.y(), + clipped_selection_bounds_.width(), clipped_selection_bounds_.height()}, + static_cast(quickmenuflags), + callbackImpl, true)) { callbackImpl->Disconnect(); auto render = browser->client()->GetRenderHandler(); if (render) { @@ -723,7 +728,6 @@ void CefTouchSelectionControllerClientOSR::OnSelectionEvent( quick_menu_requested_ = true; NotifyTouchSelectionChanged(false); UpdateQuickMenu(); - rwhv_->ResetGestureDetection(false); break; case ui::INSERTION_HANDLE_SHOWN: if (rwhv_->browser_impl()) { @@ -734,7 +738,6 @@ void CefTouchSelectionControllerClientOSR::OnSelectionEvent( if (quick_menu_requested_) { ShowQuickMenu(); } - rwhv_->ResetGestureDetection(false); break; case ui::SELECTION_HANDLES_CLEARED: case ui::INSERTION_HANDLE_CLEARED: @@ -947,7 +950,7 @@ void CefTouchSelectionControllerClientOSR::ExecuteCommand(int command_id, #ifndef OHOS_CLIPBOARD if (command_id == kInvalidCommandId) { - LOG(ERROR) << "Quick menu Command id is invaild"; + LOG(ERROR) << "Quick menu command id is invaild"; return; } #endif // #ifndef OHOS_CLIPBOARD @@ -977,7 +980,7 @@ void CefTouchSelectionControllerClientOSR::ExecuteCommand(int command_id, #ifdef OHOS_CLIPBOARD absl::optional value; - LOG(INFO) << "Quick menu Command id = " << command_id; + LOG(INFO) << "Quick menu command id = " << command_id; #endif // #ifdef OHOS_CLIPBOARD switch (command_id) { case QM_EDITFLAG_CAN_CUT: diff --git a/libcef/browser/osr/web_contents_view_osr.cc b/libcef/browser/osr/web_contents_view_osr.cc index a45938e29..6eb706b23 100644 --- a/libcef/browser/osr/web_contents_view_osr.cc +++ b/libcef/browser/osr/web_contents_view_osr.cc @@ -335,18 +335,6 @@ void CefWebContentsViewOSR::UpdateBrowserControlsHeight(int height, } #endif // OHOS_EX_TOPCONTROLS -#ifdef OHOS_DISPLAY_CUTOUT -void CefWebContentsViewOSR::OnSafeInsetsChange(const gfx::Insets& safe_insets) { - if (web_contents_) { - content::WebContentsImpl* web_contents_impl = - static_cast(web_contents_); - if (web_contents_impl) { - web_contents_impl->SetDisplayCutoutSafeArea(safe_insets); - } - } -} -#endif - #ifdef OHOS_AI void CefWebContentsViewOSR::CreateOverlay(const gfx::ImageSkia& image, const gfx::Rect& image_rect, @@ -358,3 +346,15 @@ void CefWebContentsViewOSR::CreateOverlay(const gfx::ImageSkia& image, } } #endif + +#ifdef OHOS_DISPLAY_CUTOUT +void CefWebContentsViewOSR::OnSafeInsetsChange(const gfx::Insets& safe_insets) { + if (web_contents_) { + content::WebContentsImpl* web_contents_impl = + static_cast(web_contents_); + if (web_contents_impl) { + web_contents_impl->SetDisplayCutoutSafeArea(safe_insets); + } + } +} +#endif diff --git a/libcef/browser/page_load_metrics/oh_page_load_metrics_observer.cc b/libcef/browser/page_load_metrics/oh_page_load_metrics_observer.cc index f62d6bc94..0eaa4ca43 100644 --- a/libcef/browser/page_load_metrics/oh_page_load_metrics_observer.cc +++ b/libcef/browser/page_load_metrics/oh_page_load_metrics_observer.cc @@ -70,11 +70,11 @@ OhPageLoadMetricsObserver::FlushMetricsOnAppEnterBackground( const page_load_metrics::mojom::PageLoadTiming& timing) { #if defined(REPORT_SYS_EVENT) ReportBufferedMetrics(timing); + ReportLargestContentfulPaint(timing); #endif // We continue observing after being backgrounded, in case we are foregrounded // again without being killed. In those cases we may still report non-buffered // metrics such as FCP after being re-foregrounded. - ReportLargestContentfulPaint(timing); return CONTINUE_OBSERVING; } @@ -82,8 +82,8 @@ OhPageLoadMetricsObserver::ObservePolicy OhPageLoadMetricsObserver::OnHidden( const page_load_metrics::mojom::PageLoadTiming& timing) { #if defined(REPORT_SYS_EVENT) ReportBufferedMetrics(timing); -#endif ReportLargestContentfulPaint(timing); +#endif return CONTINUE_OBSERVING; } @@ -91,8 +91,8 @@ void OhPageLoadMetricsObserver::OnComplete( const page_load_metrics::mojom::PageLoadTiming& timing) { #if defined(REPORT_SYS_EVENT) ReportBufferedMetrics(timing); -#endif ReportLargestContentfulPaint(timing); +#endif } int64_t OhPageLoadMetricsObserver::GetNavigationStartTime() { @@ -108,6 +108,37 @@ int64_t OhPageLoadMetricsObserver::GetNavigationStartTime() { return navigation_start_time; } +#ifdef OHOS_BFCACHE +void OhPageLoadMetricsObserver::OnRestoreFromBackForwardCache( + const page_load_metrics::mojom::PageLoadTiming& timing, + content::NavigationHandle* navigation_handle) { + back_forward_cache_navigation_ids_.push_back( + navigation_handle->GetNavigationId()); +} + +page_load_metrics::PageLoadMetricsObserver::ObservePolicy +OhPageLoadMetricsObserver::OnEnterBackForwardCache( + const page_load_metrics::mojom::PageLoadTiming& timing) { + return CONTINUE_OBSERVING; +} + +void OhPageLoadMetricsObserver:: + OnFirstContentfulPaintAfterBackForwardCacheRestoreInPage( + const page_load_metrics::mojom::BackForwardCacheTiming& timing, + size_t index) { + if (index >= back_forward_cache_navigation_ids_.size()) + return; + + int64_t first_contentful_paint_ms = + timing.first_paint_after_back_forward_cache_restore.InMilliseconds(); +#if defined(REPORT_SYS_EVENT) + web_performance_timing_.first_contentful_paint = first_contentful_paint_ms; +#endif + int64_t navigation_start_time = GetNavigationStartTime(); + ReportFirstContentfulPaint(navigation_start_time, first_contentful_paint_ms); +} +#endif + void OhPageLoadMetricsObserver::OnFirstContentfulPaintInPage( const page_load_metrics::mojom::PageLoadTiming& timing) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); diff --git a/libcef/browser/page_load_metrics/oh_page_load_metrics_observer.h b/libcef/browser/page_load_metrics/oh_page_load_metrics_observer.h index 20171f7d9..6c953253e 100644 --- a/libcef/browser/page_load_metrics/oh_page_load_metrics_observer.h +++ b/libcef/browser/page_load_metrics/oh_page_load_metrics_observer.h @@ -32,6 +32,11 @@ class OhPageLoadMetricsObserver ObservePolicy OnStart(content::NavigationHandle* navigation_handle, const GURL& currently_committed_url, bool started_in_foreground) override; +#ifdef OHOS_BFCACHE + page_load_metrics::PageLoadMetricsObserver::ObservePolicy + OnEnterBackForwardCache( + const page_load_metrics::mojom::PageLoadTiming& timing) override; +#endif ObservePolicy OnFencedFramesStart( content::NavigationHandle* navigation_handle, const GURL& currently_committed_url) override; @@ -51,6 +56,9 @@ class OhPageLoadMetricsObserver const page_load_metrics::mojom::PageLoadTiming& timing) override; void OnFirstMeaningfulPaintInMainFrameDocument( const page_load_metrics::mojom::PageLoadTiming& timing) override; +#if OHOS_BFCACHE + void OnFirstContentfulPaintAfterBackForwardCacheRestoreInPage(const page_load_metrics::mojom::BackForwardCacheTiming& timing, size_t index) override; +#endif #if defined(REPORT_SYS_EVENT) ObservePolicy OnRedirect( @@ -65,6 +73,11 @@ class OhPageLoadMetricsObserver void OnFirstPaintInPage( const page_load_metrics::mojom::PageLoadTiming& timing) override; static void OnNavigationStart(); +#ifdef OHOS_BFCACHE + void OnRestoreFromBackForwardCache( + const page_load_metrics::mojom::PageLoadTiming& timing, + content::NavigationHandle* navigation_handle) override; +#endif #endif protected: OhPageLoadMetricsObserver( @@ -97,6 +110,12 @@ class OhPageLoadMetricsObserver OhWebPerformanceTiming web_performance_timing_; static int64_t navigation_start_timestamp_; #endif + +#ifdef OHOS_BFCACHE + // IDs for the navigations when the page is restored from the back-forward + // cache. + std::vector back_forward_cache_navigation_ids_; +#endif }; #endif // CEF_LIBCEF_BROWSER_PAGE_LOAD_METRICS_OH_PAGE_LOAD_METRICS_OBSERVER_H_ diff --git a/libcef/browser/password/oh_password_manager_client.cc b/libcef/browser/password/oh_password_manager_client.cc index d129165db..5076e5d57 100644 --- a/libcef/browser/password/oh_password_manager_client.cc +++ b/libcef/browser/password/oh_password_manager_client.cc @@ -113,6 +113,7 @@ #include "content/public/browser/storage_partition.h" #include "content/public/browser/web_contents.h" #include "content/public/common/content_switches.h" +#include "crypto/sha2.h" #include "extensions/buildflags/buildflags.h" #include "net/base/url_util.h" #include "net/cert/cert_status_flags.h" @@ -153,6 +154,8 @@ typedef autofill::SavePasswordProgressLogger Logger; namespace { #if defined(OHOS_PASSWORD_AUTOFILL) +const std::string SOURCE = "source"; +const std::string SOURCE_LOGIN = "login"; const std::string EVENT = "event"; const std::string EVENT_SAVE = "save"; const std::string EVENT_FILL = "fill"; @@ -172,6 +175,8 @@ const std::string KEY_IS_OTHER_ACCOUNT = "isOtherAccount"; const std::string KEY_USERNAME = "username"; const std::string KEY_PASSWORD = "password"; + +const std::string HASH_SALT = "OHOS@PASSWORD@AUTOFILL"; #endif } // namespace @@ -281,11 +286,10 @@ bool OhPasswordManagerClient::PromptUserToSaveOrUpdatePassword( return false; } - auto autofill_id = - form_to_save->GetPendingCredentials().password_element_renderer_id; - if (auto_filled_forms_.find(autofill_id) != auto_filled_forms_.end()) { + // If the information used when the user logs in is current site filled in and + // not modified, then do not prompt the user to save. + if (IsLoginInfoConsistentWithFilled(form_to_save->GetPendingCredentials())) { LOG(INFO) << "auto filled password, not save on login"; - auto_filled_forms_.erase(autofill_id); return false; } @@ -299,7 +303,11 @@ bool OhPasswordManagerClient::PromptUserToSaveOrUpdatePassword( PasswordFormToJsonForSave(form_to_save->GetPendingCredentials()); if (json_str.has_value()) { LOG(INFO) << "call autofill for save from system."; - autofill_client->OnAutofillEvent(json_str.value()); + bool result = autofill_client->OnAutofillEvent(json_str.value()); + if (!result) { + LOG(ERROR) << "failed to call autofill for save"; + return false; + } } #endif return false; @@ -720,6 +728,8 @@ OhPasswordManagerClient::GetURLLoaderFactory() { } #if defined(OHOS_PASSWORD_AUTOFILL) +using autofill::mojom::OhosPasswordFormAutofillState; + absl::optional OhPasswordManagerClient::PasswordFormToJsonForRequest( const std::string& event, @@ -745,9 +755,14 @@ OhPasswordManagerClient::PasswordFormToJsonForRequest( float ratio = browser->GetVirtualPixelRatio(); auto offset = content::WebContents::FromRenderFrameHost(rfh)->GetContainerBounds(); + int32_t view_port_height = 0; + if (browser && browser->GetHost()) { + view_port_height = browser->GetHost()->GetShrinkViewportHeight(); + } base::Value::List view_data_list; view_data_list.Append(base::Value::Dict().Set(EVENT, event)); + view_data_list.Append(base::Value::Dict().Set(SOURCE, SOURCE_LOGIN)); view_data_list.Append(base::Value::Dict().Set(KEY_PAGE_URL, page_url.spec())); if (imf_info) { view_data_list.Append( @@ -768,7 +783,7 @@ OhPasswordManagerClient::PasswordFormToJsonForRequest( static_cast((item.second.bounds.x() + offset.x()) * ratio))); list.Append(base::Value::Dict().Set( KEY_RECT_Y, - static_cast((item.second.bounds.y() + offset.y()) * ratio))); + static_cast((item.second.bounds.y() + offset.y() + view_port_height) * ratio))); list.Append(base::Value::Dict().Set( KEY_RECT_W, static_cast(item.second.bounds.width() * ratio))); list.Append(base::Value::Dict().Set( @@ -787,6 +802,7 @@ absl::optional OhPasswordManagerClient::PasswordFormToJsonForSave( const password_manager::PasswordForm& form) { base::Value::List view_data_list; view_data_list.Append(base::Value::Dict().Set(EVENT, EVENT_SAVE)); + view_data_list.Append(base::Value::Dict().Set(SOURCE, SOURCE_LOGIN)); view_data_list.Append(base::Value::Dict().Set( KEY_PAGE_URL, url::Origin::Create(form.url).GetURL().spec())); @@ -806,11 +822,16 @@ absl::optional OhPasswordManagerClient::PasswordFormToJsonForSave( void OhPasswordManagerClient::ProcessAutofillCancel( const std::string& fillContent) { - LOG(INFO) << "autofill process fill cancel"; - if (is_keyboard_supressed_) { - SetShouldSuppressKeyboard(false); + // If it is on the PC platform, or if the request is not sent by me, I will + // not handle the fill cancle event. + if (!is_keyboard_supressed_) { + LOG(INFO) << "don't need to handle the fill cancle event"; + return; } + LOG(INFO) << "autofill handle fill cancel event"; + SetShouldSuppressKeyboard(false); + if (!web_contents()) { LOG(ERROR) << "web_contents is nullptr"; return; @@ -864,12 +885,40 @@ void OhPasswordManagerClient::AutoFillWithIMFEvent(bool is_username, auto json_str = PasswordFormToJsonForRequest(EVENT_FILL, form_to_request_url_, username, password, &imf_info); if (json_str.has_value()) { - LOG(INFO) << "call autofill for save from IMF"; + LOG(INFO) << "call autofill for request from IMF"; + bool result = autofill_client->OnAutofillEvent(json_str.value()); + if (!result) { + LOG(ERROR) << "failed to call autofill for request"; + return; + } SetShouldSuppressKeyboard(true); - autofill_client->OnAutofillEvent(json_str.value()); } } +void OhPasswordManagerClient::FillData(const std::string& page_url, + const std::string& username, + const std::string& password, + bool is_other_account) { + if (is_keyboard_supressed_) { + SetShouldSuppressKeyboard(false); + } + auto username_id = last_request_fill_username_.field_renderer_id; + auto password_id = last_request_fill_password_.field_renderer_id; + auto digest = is_other_account + ? std::string() + : crypto::SHA256HashString(username + HASH_SALT + password); + if (username_id) { + auto_filled_forms_username_[*username_id] = digest; + } + if (password_id) { + auto_filled_forms_passsword_[*password_id] = digest; + } + + std::wstring_convert, char16_t> convert; + FillAccountSuggestion(GURL(page_url), convert.from_bytes(username), + convert.from_bytes(password)); +} + void OhPasswordManagerClient::SetShouldSuppressKeyboard(bool suppress) { if (!web_contents()) { LOG(ERROR) << "web_contents is nullptr"; @@ -886,43 +935,59 @@ void OhPasswordManagerClient::SetShouldSuppressKeyboard(bool suppress) { LOG(ERROR) << "autofill_driver is nullptr"; return; } - LOG(INFO) << "SetShouldSuppressKeyboard=" << (suppress ? "true" : "false"); + LOG(INFO) << "set the keyboard suppressd=" << (suppress ? "true" : "false"); autofill_driver->SetShouldSuppressKeyboardCallback(suppress); is_keyboard_supressed_ = suppress; } +bool OhPasswordManagerClient::IsLoginInfoConsistentWithFilled( + const password_manager::PasswordForm& info) { + auto username_id = info.username_element_renderer_id; + auto password_id = info.password_element_renderer_id; + AutofilledMap::iterator it; + AutofilledMap* auto_filled_forms = nullptr; + LOG(INFO) << "login autosave, username renderer_id:" << username_id + << ", password renderer_id:" << password_id; + if (password_id) { + auto_filled_forms = &auto_filled_forms_passsword_; + it = auto_filled_forms->find(*password_id); + } else if (username_id) { + auto_filled_forms = &auto_filled_forms_username_; + it = auto_filled_forms->find(*username_id); + } + + if (auto_filled_forms && it != auto_filled_forms->end() && + !it->second.empty()) { + std::wstring_convert, char16_t> convert; + std::string login_digest = crypto::SHA256HashString( + convert.to_bytes(info.username_value) + HASH_SALT + + convert.to_bytes(info.password_value)); + if (it->second == login_digest) { + auto_filled_forms->erase(it); + return true; + } + } + return false; +} + void OhPasswordManagerClient::UpdateLastRequestFilledItems( const autofill::InputFillRequestData& username_data, - const autofill::InputFillRequestData& password_data, - autofill::FormRendererId form_id) { + const autofill::InputFillRequestData& password_data) { last_request_fill_username_ = username_data; last_request_fill_password_ = password_data; - last_filled_form_id_ = form_id; - if (last_request_fill_username_.is_focused) { - last_fill_focus_renderer_id_ = - last_request_fill_username_.field_renderer_id; - } else if (last_request_fill_password_.is_focused) { - last_fill_focus_renderer_id_ = - last_request_fill_password_.field_renderer_id; - } } void OhPasswordManagerClient::FillAccountSuggestion( const GURL& page_url, const std::u16string& username, const std::u16string& password) { - if (is_keyboard_supressed_) { - SetShouldSuppressKeyboard(false); - } password_manager::ContentPasswordManagerDriver* driver = driver_factory_->GetDriverForFrame(web_contents()->GetFocusedFrame()); if (!driver) { return; } - if (!last_request_fill_password_.field_renderer_id.is_null()) { - auto_filled_forms_.insert(last_request_fill_password_.field_renderer_id); - } + LOG(INFO) << "[Autofill] Try to fill account suggestion."; driver->FillAccountSuggestion(page_url, username, password); } @@ -933,7 +998,8 @@ void OhPasswordManagerClient::OnRequestAutofill( const autofill::mojom::OhosPasswordFormAutofillState state, const autofill::InputFillRequestData& username_data, const autofill::InputFillRequestData& password_data) { - LOG(INFO) << "On request autofill, state=" << static_cast(state) + LOG(INFO) << "[Autofill] On request autofill" + << ", state="<< static_cast(state) << ", username.bounds=" << username_data.bounds.ToString() << ", username.is_focus=" << username_data.is_focused << ", username.type=" << username_data.type @@ -951,22 +1017,26 @@ void OhPasswordManagerClient::OnRequestAutofill( LOG(ERROR) << "autofill_client is nullptr"; return; } - if (state == autofill::mojom::OhosPasswordFormAutofillState::kTextChanged) { - auto_filled_forms_.erase(password_data.field_renderer_id); - } form_to_request_url_ = page_url; + last_fill_form_id_ = form_id; + last_fill_focus_renderer_id_ = username_data.is_focused + ? username_data.field_renderer_id + : password_data.field_renderer_id; if (!base::ohos::IsPcDevice()) { - if (state == - autofill::mojom::OhosPasswordFormAutofillState::kNotRequested) { + if (state == OhosPasswordFormAutofillState::kNotRequested) { auto json_str = PasswordFormToJsonForRequest( EVENT_FILL, page_url, username_data, password_data); if (json_str.has_value()) { - SetShouldSuppressKeyboard(true); LOG(INFO) << "call autofill for request from system, form_id=" << form_id; - autofill_client->OnAutofillEvent(json_str.value()); - UpdateLastRequestFilledItems(username_data, password_data, form_id); + bool result = autofill_client->OnAutofillEvent(json_str.value()); + if (!result) { + LOG(ERROR) << "failed to call autofill for request"; + return; + } + SetShouldSuppressKeyboard(true); + UpdateLastRequestFilledItems(username_data, password_data); } } } else { @@ -974,22 +1044,24 @@ void OhPasswordManagerClient::OnRequestAutofill( // trigger a filling request when it is clicked for the first time. After // the PC mode is fully supported, it requests filling every time it is // clicked. - if (state == - autofill::mojom::OhosPasswordFormAutofillState::kHasBeenRequested) { + if (state == OhosPasswordFormAutofillState::kHasBeenRequested) { return; } - auto event = - state == autofill::mojom::OhosPasswordFormAutofillState::kTextChanged - ? EVENT_UPDATE - : EVENT_FILL; + auto event = (state == OhosPasswordFormAutofillState::kTextChanged) + ? EVENT_UPDATE + : EVENT_FILL; auto json_str = PasswordFormToJsonForRequest(event, page_url, username_data, password_data); if (json_str.has_value()) { LOG(INFO) << "call autofill for request from system, state=" << static_cast(state); - autofill_client->OnAutofillEvent(json_str.value()); - UpdateLastRequestFilledItems(username_data, password_data, form_id); + bool result = autofill_client->OnAutofillEvent(json_str.value()); + if (!result) { + LOG(ERROR) << "failed to call autofill for request"; + return; + } + UpdateLastRequestFilledItems(username_data, password_data); } } } diff --git a/libcef/browser/password/oh_password_manager_client.h b/libcef/browser/password/oh_password_manager_client.h index c7f5fe13d..1411da877 100644 --- a/libcef/browser/password/oh_password_manager_client.h +++ b/libcef/browser/password/oh_password_manager_client.h @@ -170,16 +170,6 @@ class OhPasswordManagerClient bool is_new_password = false; }; - absl::optional PasswordFormToJsonForRequest( - const std::string& event, - const GURL& page_url, - const autofill::InputFillRequestData& username_data, - const autofill::InputFillRequestData& password_data, - AutofillIMFInfo* imf_info = nullptr); - - absl::optional PasswordFormToJsonForSave( - const password_manager::PasswordForm& form); - void ProcessAutofillCancel(const std::string& fillContent); void AutoFillWithIMFEvent(bool is_username, @@ -187,15 +177,13 @@ class OhPasswordManagerClient bool is_new_password, const std::string& content); - void SetShouldSuppressKeyboard(bool suppress); - - void UpdateLastRequestFilledItems( - const autofill::InputFillRequestData& username_data, - const autofill::InputFillRequestData& password_data, - autofill::FormRendererId form_id); + void FillData(const std::string& page_url, + const std::string& username, + const std::string& password, + bool is_other_account); bool IsUsernamePasswordForm(autofill::FormRendererId form_id) { - return form_id == last_filled_form_id_; + return form_id == last_fill_form_id_; } bool IsUsernamePasswordField(autofill::FieldRendererId field_id) { @@ -333,6 +321,27 @@ class OhPasswordManagerClient content::RenderFrameHost* frame_host, const gfx::RectF& bounds_in_frame_coordinates); +#if defined(OHOS_PASSWORD_AUTOFILL) + absl::optional PasswordFormToJsonForRequest( + const std::string& event, + const GURL& page_url, + const autofill::InputFillRequestData& username_data, + const autofill::InputFillRequestData& password_data, + AutofillIMFInfo* imf_info = nullptr); + + absl::optional PasswordFormToJsonForSave( + const password_manager::PasswordForm& form); + + void SetShouldSuppressKeyboard(bool suppress); + + bool IsLoginInfoConsistentWithFilled( + const password_manager::PasswordForm& info); + + void UpdateLastRequestFilledItems( + const autofill::InputFillRequestData& username_data, + const autofill::InputFillRequestData& password_data); +#endif + content::BrowserContext* const context_; password_manager::PasswordManager password_manager_; @@ -373,12 +382,15 @@ class OhPasswordManagerClient bool was_on_paste_called_ = false; #if defined(OHOS_PASSWORD_AUTOFILL) + using AutofilledMap = std::unordered_map; + GURL form_to_request_url_; - autofill::FormRendererId last_filled_form_id_; + autofill::FormRendererId last_fill_form_id_; autofill::FieldRendererId last_fill_focus_renderer_id_; - std::set auto_filled_forms_; + AutofilledMap auto_filled_forms_username_; + AutofilledMap auto_filled_forms_passsword_; autofill::InputFillRequestData last_request_fill_username_; autofill::InputFillRequestData last_request_fill_password_; diff --git a/libcef/browser/permission/alloy_access_request.h b/libcef/browser/permission/alloy_access_request.h index 9836a407a..09f5fbea0 100755 --- a/libcef/browser/permission/alloy_access_request.h +++ b/libcef/browser/permission/alloy_access_request.h @@ -31,6 +31,7 @@ class AlloyAccessRequest : public CefAccessRequest { PROTECTED_MEDIA_ID = 1 << 3, MIDI_SYSEX = 1 << 4, CLIPBOARD_READ_WRITE = 1 << 5, + CLIPBOARD_SANITIZED_WRITE = 1 << 6, SENSORS = 1 << 7, }; diff --git a/libcef/browser/permission/alloy_permission_manager.cc b/libcef/browser/permission/alloy_permission_manager.cc index df77ece35..009422535 100644 --- a/libcef/browser/permission/alloy_permission_manager.cc +++ b/libcef/browser/permission/alloy_permission_manager.cc @@ -237,12 +237,13 @@ void AlloyPermissionManager::RequestPermissionByType( weak_ptr_factory_.GetWeakPtr(), request_id, permission_type)); break; case PermissionType::CLIPBOARD_READ_WRITE: - if(GetApplicationApiVersion() <= APPLICATION_API_10){ + if (GetApplicationApiVersion() <= APPLICATION_API_10){ LOG(INFO) << "application version <= 10"; pending_request_raw->SetPermissionStatus(permission_type, - PermissionStatus::GRANTED); + PermissionStatus::GRANTED); break; } + LOG(INFO) << "application version > 10, ask clipboard readwrite permission."; browser->AskClipboardReadWritePermission( pending_request_raw->requesting_origin_.spec(), base::BindRepeating( @@ -261,7 +262,19 @@ void AlloyPermissionManager::RequestPermissionByType( break; #endif // defined(OHOS_SENSOR) case PermissionType::AUDIO_CAPTURE: + browser->AskAudioCapturePermission( + pending_request_raw->requesting_origin_.spec(), + base::BindRepeating( + &AlloyPermissionManager::OnRequestResponseCallBack, + weak_ptr_factory_.GetWeakPtr(), request_id, permission_type)); + break; case PermissionType::VIDEO_CAPTURE: + browser->AskVideoCapturePermission( + pending_request_raw->requesting_origin_.spec(), + base::BindRepeating( + &AlloyPermissionManager::OnRequestResponseCallBack, + weak_ptr_factory_.GetWeakPtr(), request_id, permission_type)); + break; case PermissionType::NOTIFICATIONS: case PermissionType::DURABLE_STORAGE: case PermissionType::BACKGROUND_SYNC: @@ -285,7 +298,23 @@ void AlloyPermissionManager::RequestPermissionByType( pending_request_raw->SetPermissionStatus(permission_type, PermissionStatus::DENIED); break; +#ifdef OHOS_EX_PERMISSION case PermissionType::CLIPBOARD_SANITIZED_WRITE: + if ((*base::CommandLine::ForCurrentProcess()).HasSwitch( + switches::kForBrowser)) { + browser->AskClipboardSanitizedWritePermission( + pending_request_raw->requesting_origin_.spec(), + base::BindRepeating( + &AlloyPermissionManager::OnRequestResponseCallBack, + weak_ptr_factory_.GetWeakPtr(), request_id, permission_type)); + } else { + pending_request_raw->SetPermissionStatus(permission_type, + PermissionStatus::GRANTED); + } + break; +#else + case PermissionType::CLIPBOARD_SANITIZED_WRITE: +#endif case PermissionType::WAKE_LOCK_SCREEN: pending_request_raw->SetPermissionStatus(permission_type, PermissionStatus::GRANTED); @@ -298,6 +327,8 @@ void AlloyPermissionManager::OnRequestResponseCallBack( int request_id, PermissionType permission, bool allowed) { + LOG(INFO) << "OnRequestResponseCallBack permission:" << (int)permission + << ", allowed:" << allowed; // All delegate functions should be cancelled when the manager runs // destructor. Therefore |manager| should be always valid here. DCHECK(manager); @@ -507,6 +538,23 @@ void AlloyPermissionManager::AbortPermissionRequestByType( if (browser) browser->AbortAskClipboardReadWritePermission(requesting_origin.spec()); break; + case PermissionType::CLIPBOARD_SANITIZED_WRITE: + if ((*base::CommandLine::ForCurrentProcess()).HasSwitch( + switches::kForBrowser) && browser) { + browser->AbortAskClipboardSanitizedWritePermission( + requesting_origin.spec()); + } else { + NOTREACHED() << "Invalid PermissionType."; + } + break; + case PermissionType::AUDIO_CAPTURE: + if (browser) + browser->AbortAskAudioCapturePermission(requesting_origin.spec()); + break; + case PermissionType::VIDEO_CAPTURE: + if (browser) + browser->AbortAskVideoCapturePermission(requesting_origin.spec()); + break; case PermissionType::SENSORS: #if defined(OHOS_SENSOR) if (browser) @@ -515,11 +563,8 @@ void AlloyPermissionManager::AbortPermissionRequestByType( #endif // defined(OHOS_SENSOR) case PermissionType::NOTIFICATIONS: case PermissionType::DURABLE_STORAGE: - case PermissionType::AUDIO_CAPTURE: - case PermissionType::VIDEO_CAPTURE: case PermissionType::BACKGROUND_SYNC: case PermissionType::ACCESSIBILITY_EVENTS: - case PermissionType::CLIPBOARD_SANITIZED_WRITE: case PermissionType::PAYMENT_HANDLER: case PermissionType::BACKGROUND_FETCH: case PermissionType::IDLE_DETECTION: diff --git a/libcef/browser/prefs/browser_prefs.cc b/libcef/browser/prefs/browser_prefs.cc index f7c468ea4..42dfd403a 100644 --- a/libcef/browser/prefs/browser_prefs.cc +++ b/libcef/browser/prefs/browser_prefs.cc @@ -98,9 +98,19 @@ #include "chrome/browser/extensions/preinstalled_apps.h" #include "chrome/browser/ui/webui/extensions/extensions_ui.h" #include "extensions/browser/permissions_manager.h" +#include "extensions/browser/pref_names.h" #endif -#include "libcef/browser/ohos_safe_browsing/ohos_sb_prefs.h" +#if defined(OHOS_NWEB_EX) +#include "chrome/common/pref_names.h" +#include "content/public/common/content_switches.h" +#endif + +#include "libcef/browser/safe_browsing/sb_prefs.h" + +#ifdef OHOS_EX_UA +#include "ohos_nweb_ex/overrides/cef/libcef/browser/alloy/alloy_browser_ua_config.h" +#endif #ifdef OHOS_ARKWEB_ADBLOCK #include "components/subresource_filter/content/browser/ruleset_version.h" @@ -215,6 +225,23 @@ std::unique_ptr CreatePrefService(Profile* profile, profile ? kUserPrefsFileName : kLocalPrefsFileName); PrefNameSet persistent_prefs; persistent_prefs.insert(predictor::kVisitedUrls); +#if defined(OHOS_ARKWEB_EXTENSIONS) + RegisterExtensionPersistentPrefs(persistent_prefs); +#endif + RegisterSubresourceFilterPersistentPrefs(persistent_prefs); + +#if defined(OHOS_NWEB_EX) + if (base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kForBrowser)) { + persistent_prefs.insert(prefs::kPartitionDefaultZoomLevel); + persistent_prefs.insert(prefs::kPartitionPerHostZoomLevels); +#ifdef OHOS_EX_UA + persistent_prefs.insert(nweb_ex::kUACloudConfigInfo); +#endif // OHOS_EX_UA + } +#endif +#ifdef OHOS_CLOUD_CONTROL + RegisterCloudControlPersistentPrefs(persistent_prefs); +#endif factory.set_user_prefs(base::MakeRefCounted( base::MakeRefCounted(), base::MakeRefCounted(pref_path), @@ -293,6 +320,10 @@ std::unique_ptr CreatePrefService(Profile* profile, SSLConfigServiceManager::RegisterPrefs(registry.get()); update_client::RegisterPrefs(registry.get()); +#if defined(OHOS_EX_EXCEPTION_LIST) + HostContentSettingsMap::RegisterProfilePrefs(registry.get()); +#endif + if (!profile) { component_updater::RegisterComponentUpdateServicePrefs(registry.get()); domain_reliability::RegisterPrefs(registry.get()); @@ -345,7 +376,16 @@ std::unique_ptr CreatePrefService(Profile* profile, #endif #if BUILDFLAG(IS_OHOS) ohos_safe_browsing::RegisterProfilePrefs(registry.get()); - #endif +#endif +#ifdef OHOS_EX_UA + if (base::CommandLine::ForCurrentProcess()->HasSwitch( + switches::kForBrowser)) { + nweb_ex::AlloyBrowserUAConfig::RegisterProfilePrefs(registry.get()); + } +#endif +#ifdef OHOS_CLOUD_CONTROL + RegisterCloudControlProfilePrefs(registry.get()); +#endif HostContentSettingsMap::RegisterProfilePrefs(registry.get()); language::LanguagePrefs::RegisterProfilePrefs(registry.get()); media_router::RegisterProfilePrefs(registry.get()); @@ -399,6 +439,11 @@ std::unique_ptr CreatePrefService(Profile* profile, // Based on browser_prefs::RegisterProfilePrefs. registry->RegisterBooleanPref(prefs::kAccessibilityPdfOcrAlwaysActive, false); +#if defined(OHOS_EDM_POLICY) + // Currently OriginAgentCluster is not enabled by default on OHOS. + registry->RegisterBooleanPref(prefs::kOriginAgentClusterDefaultEnabled, + false); +#endif // Spell checking preferences. // Modify defaults from SpellcheckServiceFactory::RegisterProfilePrefs. @@ -464,6 +509,71 @@ std::string GetAcceptLanguageList(CefBrowserContext* browser_context, return std::string(); } +#if defined(OHOS_ARKWEB_EXTENSIONS) +void RegisterExtensionPersistentPrefs(PrefNameSet& pref_name_set) { + // See extensions::ExtensionPrefs::RegisterProfilePrefs + pref_name_set.insert(extensions::pref_names::kExtensions); + pref_name_set.insert(extensions::pref_names::kPinnedExtensions); + pref_name_set.insert(extensions::pref_names::kDeletedComponentExtensions); + pref_name_set.insert(extensions::pref_names::kExtensionsBlocklistUpdate); + pref_name_set.insert(extensions::pref_names::kInstallAllowList); + pref_name_set.insert(extensions::pref_names::kInstallDenyList); + pref_name_set.insert(extensions::pref_names::kInstallForceList); + pref_name_set.insert(extensions::pref_names::kAllowedTypes); + pref_name_set.insert(extensions::pref_names::kManifestV2Availability); + pref_name_set.insert(extensions::pref_names::kStorageGarbageCollect); + pref_name_set.insert(extensions::pref_names::kAllowedInstallSites); + pref_name_set.insert(extensions::pref_names::kLastChromeVersion); + pref_name_set.insert(extensions::pref_names::kInstallSignature); + pref_name_set.insert(extensions::pref_names::kExternalUninstalls); + pref_name_set.insert(extensions::pref_names::kExtendedBackgroundLifetimeForPortConnectionsToUrls); + pref_name_set.insert(extensions::pref_names::kChromeAppsWebViewPermissiveBehaviorAllowed); + pref_name_set.insert(extensions::pref_names::kNativeMessagingBlocklist); + pref_name_set.insert(extensions::pref_names::kNativeMessagingAllowlist); + pref_name_set.insert(extensions::pref_names::kNativeMessagingUserLevelHosts); + pref_name_set.insert(extensions::kCorruptedDisableCount.name); + pref_name_set.insert(extensions::pref_names::kAppFullscreenAllowed); + pref_name_set.insert(extensions::pref_names::kBlockExternalExtensions); + pref_name_set.insert(extensions::pref_names::kExtensionUnpublishedAvailability); + + // See extensions::ExtensionsUI::RegisterProfilePrefs + pref_name_set.insert(prefs::kExtensionsUIDeveloperMode); + + // See DevToolsWindow::RegisterProfilePrefs + pref_name_set.insert(prefs::kDevToolsEditedFiles); + pref_name_set.insert(prefs::kDevToolsFileSystemPaths); + pref_name_set.insert(prefs::kDevToolsAdbKey); + pref_name_set.insert(prefs::kDevToolsDiscoverUsbDevicesEnabled); + pref_name_set.insert(prefs::kDevToolsPortForwardingEnabled); + pref_name_set.insert(prefs::kDevToolsPortForwardingDefaultSet); + pref_name_set.insert(prefs::kDevToolsPortForwardingConfig); + pref_name_set.insert(prefs::kDevToolsDiscoverTCPTargetsEnabled); + pref_name_set.insert(prefs::kDevToolsTCPDiscoveryConfig); + pref_name_set.insert(prefs::kDevToolsPreferences); + pref_name_set.insert(prefs::kDevToolsSyncPreferences); + pref_name_set.insert(prefs::kDevToolsSyncedPreferencesSyncEnabled); + pref_name_set.insert(prefs::kDevToolsSyncedPreferencesSyncDisabled); + + // See extensions::CommandService::RegisterProfilePrefs + pref_name_set.insert(prefs::kExtensionCommands); + + // See extensions::PermissionsManager::RegisterProfilePrefs + pref_name_set.insert(extensions::kUserPermissions.name); + + // See ExtensionWebUI::RegisterProfilePrefs + pref_name_set.insert(ExtensionWebUI::kExtensionURLOverrides); + + // See preinstalled_apps::RegisterProfilePrefs + pref_name_set.insert(prefs::kPreinstalledAppsInstallState); +} +#endif + +#if defined(OHOS_CLOUD_CONTROL) && !defined(OHOS_NWEB_EX) + void RegisterCloudControlProfilePrefs(user_prefs::PrefRegistrySyncable* registry) {} + + void RegisterCloudControlPersistentPrefs(PrefNameSet& pref_name_set) {} +#endif + #ifdef OHOS_ARKWEB_ADBLOCK void RegisterSubresourceFilterPersistentPrefs(PrefNameSet& pref_name_set) { pref_name_set.insert( diff --git a/libcef/browser/prefs/browser_prefs.h b/libcef/browser/prefs/browser_prefs.h index 1985f9afe..465f51e81 100644 --- a/libcef/browser/prefs/browser_prefs.h +++ b/libcef/browser/prefs/browser_prefs.h @@ -11,6 +11,13 @@ #include +#if defined(OHOS_ARKWEB_EXTENSIONS) +#include "components/prefs/pref_name_set.h" +#endif +#ifdef OHOS_CLOUD_CONTROL +#include "components/pref_registry/pref_registry_syncable.h" +#endif + namespace base { class FilePath; } @@ -30,6 +37,20 @@ extern const char kUserPrefsFileName[]; void RegisterLocalStatePrefs(PrefRegistrySimple* registry); void RegisterProfilePrefs(PrefRegistrySimple* registry); +#if defined(OHOS_ARKWEB_EXTENSIONS) +void RegisterExtensionPersistentPrefs(PrefNameSet& pref_name_set); +#endif + +#ifdef OHOS_ARKWEB_ADBLOCK +void RegisterSubresourceFilterPersistentPrefs(PrefNameSet& pref_name_set); +#endif + +#ifdef OHOS_CLOUD_CONTROL +void RegisterCloudControlProfilePrefs(user_prefs::PrefRegistrySyncable* registry); + +void RegisterCloudControlPersistentPrefs(PrefNameSet& pref_name_set); +#endif + // Create the PrefService used to manage pref registration and storage. // |profile| will be nullptr for the system-level PrefService. Used with the // Alloy runtime only. diff --git a/libcef/browser/prefs/renderer_prefs.cc b/libcef/browser/prefs/renderer_prefs.cc index 8d1af2370..256fc5919 100755 --- a/libcef/browser/prefs/renderer_prefs.cc +++ b/libcef/browser/prefs/renderer_prefs.cc @@ -44,10 +44,19 @@ #include "ui/native_theme/native_theme.h" #if BUILDFLAG(IS_OHOS) +#include "base/ohos/sys_info_utils.h" #include "content/public/browser/render_widget_host.h" #include "libcef/browser/osr/render_widget_host_view_osr.h" #endif +#if defined(OHOS_EX_EXCEPTION_LIST) +#include "chrome/browser/content_settings/host_content_settings_map_factory.h" +#include "components/content_settings/core/browser/host_content_settings_map.h" +#include "components/content_settings/core/common/content_settings.h" +#include "components/content_settings/core/common/content_settings_types.h" +#include "content/public/common/content_switches.h" +#endif + namespace renderer_prefs { namespace { @@ -261,12 +270,11 @@ void SetCefSpecialPrefs(content::RenderViewHost* rvh, if (rwhvb && rwhvb->IsRenderWidgetHostViewChildFrame()) { return; } - CefRenderWidgetHostViewOSR* view = - static_cast(rwhvb); - if (view) { - view->SetDoubleTapSupportEnabled( + + if (rwhvb) { + rwhvb->SetDoubleTapSupportEnabled( browser->settings().supports_double_tap_zoom); - view->SetMultiTouchZoomSupportEnabled( + rwhvb->SetMultiTouchZoomSupportEnabled( browser->settings().supports_multi_touch_zoom); } } @@ -310,6 +318,27 @@ void SetDefaultPrefs(blink::web_pref::WebPreferences& web) { command_line->HasSwitch(switches::kImageShrinkStandaloneToFit); web.text_areas_are_resizable = !command_line->HasSwitch(switches::kDisableTextAreaResize); + +#if BUILDFLAG(IS_OHOS) + // These OHOS default prefs defined in web_preferences.cc is only used for + // none PC device, PC device has different prefs as below. + if (base::ohos::IsPcDevice()) { + web.viewport_meta_enabled = false; + web.auto_zoom_focused_editable_to_legible_scale = false; + web.shrinks_viewport_contents_to_fit = false; + web.viewport_style = blink::mojom::ViewportStyle::kDefault; + web.always_show_context_menu_on_touch = true; + web.smooth_scroll_for_find_enabled = false; + web.main_frame_resizes_are_orientation_changes = false; + + web.double_tap_to_zoom_enabled = false; + + web.text_autosizing_enabled = false; + + web.default_minimum_page_scale_factor = 1.f; + web.default_maximum_page_scale_factor = 4.f; + } +#endif } // Helper macro for setting a WebPreferences variable based on the value of a @@ -421,6 +450,7 @@ void SetCefPrefs(const CefBrowserSettings& cef, web.embed_tag_type = CefString(&cef.embed_tag_type); web.draw_mode = cef.draw_mode; SET_STATE(cef.text_autosizing_enabled, web.text_autosizing_enabled); + web.force_zero_layout_height = cef.force_zero_layout_height; #if defined(OHOS_DARKMODE) if (cef.dark_prefer_color_scheme_enabled == STATE_ENABLED) { web.preferred_color_scheme = blink::mojom::PreferredColorScheme::kDark; @@ -446,10 +476,6 @@ void SetCefPrefs(const CefBrowserSettings& cef, #endif // OHOS_SCROLLBAR #ifdef OHOS_EX_FREE_COPY web.contextmenu_customization_enabled = cef.contextmenu_customization_enabled; -#endif -#ifdef OHOS_EX_BLANK_TARGET_POPUP_INTERCEPT - web.blank_target_popup_intercept_enabled = - cef.blank_target_popup_intercept_enabled; #endif if (cef.viewport_meta_enabled.has_value()) web.viewport_meta_enabled = cef.viewport_meta_enabled.value(); @@ -466,18 +492,22 @@ void SetCefPrefs(const CefBrowserSettings& cef, web.custom_video_player_enable = cef.custom_video_player_enable; web.custom_video_player_overlay = cef.custom_video_player_overlay; #endif // OHOS_CUSTOM_VIDEO_PLAYER +#if defined(OHOS_MULTI_WINDOW) + web.supports_multiple_windows = cef.supports_multiple_windows; +#endif // OHOS_MULTI_WINDOW #if defined(OHOS_SOFTWARE_COMPOSITOR) web.record_whole_document = cef.record_whole_document; #endif -#if defined(OHOS_MULTI_WINDOW) - web.supports_multiple_windows = cef.supports_multiple_windows; -#endif // OHOS_MULTI_WINDOW - #ifdef OHOS_NETWORK_LOAD SET_STATE(cef.universal_access_from_file_urls, web.allow_universal_access_from_file_urls); #endif + +#ifdef OHOS_MEDIA_NETWORK_TRAFFIC_PROMPT + web.enable_media_network_traffic_prompt = + cef.enable_media_network_traffic_prompt; +#endif // OHOS_MEDIA_NETWORK_TRAFFIC_PROMPT } void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry, @@ -569,6 +599,28 @@ void PopulateWebPreferences(content::RenderViewHost* rvh, SetCefSpecialPrefs(rvh, browser, web); #endif +#if defined(OHOS_EX_EXCEPTION_LIST) + const base::CommandLine* command_line = + base::CommandLine::ForCurrentProcess(); + if (command_line->HasSwitch(switches::kForBrowser)) { + bool javascript_enabled = web.javascript_enabled; + + // Update content setting default value + ContentSetting setting = + javascript_enabled ? CONTENT_SETTING_ALLOW : CONTENT_SETTING_BLOCK; + if (!web_contents) + return; + HostContentSettingsMap* host_content_settings_map = + HostContentSettingsMapFactory::GetForProfile( + web_contents->GetBrowserContext()); + host_content_settings_map->SetDefaultContentSetting( + ContentSettingsType::JAVASCRIPT, setting); + DVLOG(0) + << "ExceptionList Update default content setting for JavaScript: " + << int(setting); + } +#endif // defined(OHOS_EX_EXCEPTION_LIST) + web.picture_in_picture_enabled = browser->IsPictureInPictureSupported(); // Set the background color for the WebView. diff --git a/libcef/browser/printing/ohos_print_manager.cc b/libcef/browser/printing/ohos_print_manager.cc index 1cfdc8bf7..fb91ac026 100755 --- a/libcef/browser/printing/ohos_print_manager.cc +++ b/libcef/browser/printing/ohos_print_manager.cc @@ -30,8 +30,8 @@ #include "base/numerics/safe_conversions.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" -#include "chrome/browser/printing/print_view_manager_common.h" #include "chrome/browser/pdf/pdf_frame_util.h" +#include "chrome/browser/printing/print_view_manager_common.h" #include "chrome/common/chrome_switches.h" #include "components/printing/browser/print_manager_utils.h" #include "components/printing/common/print.mojom.h" @@ -50,6 +50,7 @@ constexpr int PRINT_JOB_CREATE_FILE_COMPLETED_SUCCESS = 0; constexpr int PRINT_JOB_CREATE_FILE_COMPLETED_FAILED = 1; constexpr int PRINT_JOB_SPOOLER_CLOSED_FOR_CANCELED = 5; + constexpr int LIMITED_PRINT_RANGE = 5; constexpr int LIMITED_PRINT_DURATION = 10000; const std::string PROTOCOL_PATH = "://"; @@ -201,13 +202,13 @@ void OhosPrintManager::BindPrintManagerHost( // static content::RenderFrameHost* OhosPrintManager::GetRenderFrameHostToUse( - content::WebContents* contents) { + content::WebContents* contents) { + // Pick the plugin frame if `contents` is a PDF viewer guest. content::RenderFrameHost* full_page_plugin = GetFullPagePlugin(contents); content::RenderFrameHost* pdf_rfh = pdf_frame_util::FindPdfChildFrame( full_page_plugin ? full_page_plugin : contents->GetPrimaryMainFrame()); - if (pdf_rfh) { + if (pdf_rfh) return pdf_rfh; - } return printing::GetFrameToPrint(contents); } @@ -261,13 +262,13 @@ void OhosPrintManager::DidDispatchPrintEvent(bool isBefore) { weak_ptr_web_contents_, isBefore)); } -void OhosPrintManager::DidDispatchPrintEventImpl(base::WeakPtr webcontents, - bool isBefore) { - if (!webcontents) { - LOG(ERROR) << "DidDispatchPrintEventImpl webcontents is nullptr."; +void OhosPrintManager::DidDispatchPrintEventImpl(base::WeakPtr web_contents, + bool isBefore) { + if (!web_contents) { + LOG(ERROR) << "DidDispatchPrintEventImpl webContents is nullptr."; return; } - auto* rfh = webcontents->GetPrimaryMainFrame(); + auto* rfh = web_contents->GetPrimaryMainFrame(); if (!rfh || !rfh->IsRenderFrameLive()) { LOG(ERROR) << "rfh is nullptr."; return; @@ -290,13 +291,13 @@ void OhosPrintManager::PrintPage(bool isApplication) { weak_ptr_web_contents_, isApplication)); } -void OhosPrintManager::PrintPageImpl(base::WeakPtr webcontents, +void OhosPrintManager::PrintPageImpl(base::WeakPtr web_contents, bool isApplication) { - if (!webcontents) { - LOG(ERROR) << "PrintPageImpl webcontents is nullptr."; + if (!web_contents) { + LOG(ERROR) << "PrintPageImpl webContents is nullptr."; return; } - auto* rfh = webcontents->GetPrimaryMainFrame(); + auto* rfh = web_contents->GetPrimaryMainFrame(); if (!rfh || !rfh->IsRenderFrameLive()) { LOG(ERROR) << "rfh is nullptr."; if (printAttrsMap_.find(print_job_id_) != printAttrsMap_.end()) { @@ -317,8 +318,9 @@ void OhosPrintManager::PrintPageImpl(base::WeakPtr webcont GetPrintRenderFrame(pdf_rfh_)->ApplicationPrintRequestedPages(); return; } + if (isApplication) { - auto* app_rfh = GetRenderFrameHostToUse(webcontents.get()); + auto* app_rfh = GetRenderFrameHostToUse(web_contents.get()); if (app_rfh) { GetPrintRenderFrame(app_rfh)->ApplicationPrintRequestedPages(); } @@ -357,6 +359,7 @@ void OhosPrintManager::UpdateParam( DCHECK(callback); settings_ = std::move(settings); fd_ = file_descriptor; + set_pdf_writing_done_callback(std::move(callback)); // Set a valid dummy cookie value. set_cookie(1); @@ -424,7 +427,6 @@ void OhosPrintManager::DidPrintDocument( } DCHECK(pdf_writing_done_callback()); - task_runner_->PostTaskAndReplyWithResult( FROM_HERE, base::BindOnce(&SaveDataToFd, fd_, number_pages(), data), base::BindOnce(&OhosPrintManager::OnDidPrintDocumentWritingDone, @@ -609,7 +611,6 @@ void OhosPrintManager::SetPrintStatus(bool is_print_now, uint32_t state) { is_print_now_ = true; is_print_disable_ = true; } - is_print_now_ = is_print_now; } void OhosPrintManager::CreateWebPrintDocumentAdapter( @@ -617,11 +618,10 @@ void OhosPrintManager::CreateWebPrintDocumentAdapter( void** webPrintDocumentAdapter) { if (is_print_now_) { LOG(ERROR) << "Application printing in progress."; - *webPrintDocumentAdapter = nullptr; return; } - is_print_now_ = true; cancel_ = false; + is_print_now_ = true; *webPrintDocumentAdapter = static_cast(new ApplicationPrintDocumentAdapterImpl(this)); } diff --git a/libcef/browser/printing/ohos_print_manager.h b/libcef/browser/printing/ohos_print_manager.h index 2819ffbf9..f25c092d6 100755 --- a/libcef/browser/printing/ohos_print_manager.h +++ b/libcef/browser/printing/ohos_print_manager.h @@ -51,10 +51,8 @@ class OhosPrintManager : public printing::PrintManager, mojo::PendingAssociatedReceiver receiver, content::RenderFrameHost* rfh); - static content::RenderFrameHost* GetRenderFrameHostToUse( content::WebContents* contents); - // printing::PrintManager: void PdfWritingDone(int page_count) override; @@ -66,18 +64,20 @@ class OhosPrintManager : public printing::PrintManager, PdfWritingDoneCallback callback); bool PrintNow(); void PrintPage(bool isApplication); - void PrintPageImpl(base::WeakPtr webcontents, + void PrintPageImpl(base::WeakPtr web_contents, bool isApplication); void DidDispatchPrintEvent(bool isBefore); - void DidDispatchPrintEventImpl(base::WeakPtr webcontents, + void DidDispatchPrintEventImpl(base::WeakPtr web_contents, bool isBefore); void SetPrintAttrs(const PrintAttrs printAttrs); void RunPrintRequestedCallback(const std::string& jobId); void RunPrintRequestedCallbackImpl(const std::string& jobId); void SetToken(void* token); - void SetPrintStatus(bool is_print_now, uint32_t status); + void SetPrintStatus(bool is_print_now, uint32_t state); void CreateWebPrintDocumentAdapter(const CefString& jobName, void** webPrintDocumentAdapter); + void SetPrintBackground(bool enable); + bool GetPrintBackground(); void CheckForCancel(int32_t preview_ui_id, int32_t request_id, CheckForCancelCallback callback) override; @@ -90,8 +90,6 @@ class OhosPrintManager : public printing::PrintManager, void ShowScriptedPrintPreview(bool source_is_modifiable) override; void UpdatePrintSettings(base::Value::Dict job_settings, UpdatePrintSettingsCallback callback) override; - void SetPrintBackground(bool enable); - bool GetPrintBackground(); private: friend class content::WebContentsUserData; diff --git a/libcef/browser/request_context_impl.cc b/libcef/browser/request_context_impl.cc index f7950ff15..32ba7184c 100644 --- a/libcef/browser/request_context_impl.cc +++ b/libcef/browser/request_context_impl.cc @@ -633,7 +633,13 @@ CefRequestContextImpl::GetOrCreateRequestContext(const Config& config) { CefRequestContextImpl::CefRequestContextImpl( const CefRequestContextImpl::Config& config) - : config_(config) {} + : config_(config) { +#if defined(OHOS_ARKWEB_EXTENSIONS) + if (config.is_global && !config_.settings.global_request_context) { + config_.settings.global_request_context = this; + } +#endif + } void CefRequestContextImpl::Initialize() { CEF_REQUIRE_UIT(); @@ -673,7 +679,7 @@ void CefRequestContextImpl::Initialize() { if (config_.incognito_mode) { browser_context_ = CefAppManager::Get()->CreateNewIncognitoBrowserContext( - config_.settings, std::move(initialized_cb)); + config_.settings, std::move(initialized_cb)); } else { browser_context_ = CefAppManager::Get()->CreateNewBrowserContext( config_.settings, std::move(initialized_cb)); diff --git a/libcef/browser/request_context_impl.h b/libcef/browser/request_context_impl.h index 30c081b0c..67f31ba24 100644 --- a/libcef/browser/request_context_impl.h +++ b/libcef/browser/request_context_impl.h @@ -60,7 +60,7 @@ class CefRequestContextImpl : public CefRequestContext { ); #if defined(OHOS_INCOGNITO_MODE) -bool IsOffTheRecord() { return config_.incognito_mode; } + bool IsOffTheRecord() { return config_.incognito_mode; } #endif // Verify that the browser context can be directly accessed (e.g. on the UI diff --git a/libcef/browser/res_reporter.cc b/libcef/browser/res_reporter.cc index 6d6b377e3..46f45814f 100644 --- a/libcef/browser/res_reporter.cc +++ b/libcef/browser/res_reporter.cc @@ -32,7 +32,7 @@ void ResReporter::Init() { int ret = LoadLibrary(); if (!ret) { - LOG(WARNING) << "ResReporter:[Init] dlopen libframe_ui_intf.so failed!"; + LOG(DEBUG) << "ResReporter:[Init] dlopen libframe_ui_intf.so failed!"; return; } LOG(INFO) << "ResReporter::[Init] dlopen libframe_ui_intf.so success!"; @@ -47,7 +47,7 @@ bool ResReporter::LoadLibrary() if (!resSchedSoLoaded_) { resSchedHandle_ = dlopen(FRAME_AWARE_SO_PATH.c_str(), RTLD_LAZY); if (resSchedHandle_ == nullptr) { - LOG(WARNING) << "ResReporter:[LoadLibrary]dlopen libframe_ui_intf.so failed!"; + LOG(DEBUG) << "ResReporter:[LoadLibrary]dlopen libframe_ui_intf.so failed!"; return false; } resSchedSoLoaded_ = true; @@ -59,7 +59,7 @@ bool ResReporter::LoadLibrary() void ResReporter::CloseLibrary() { if (dlclose(resSchedHandle_) != 0) { - LOG(WARNING) << "ResReporter:[CloseLibrary]dlclose libframe_ui_intf.so failed!"; + LOG(DEBUG) << "ResReporter:[CloseLibrary]dlclose libframe_ui_intf.so failed!"; return; } resSchedHandle_ = nullptr; @@ -70,13 +70,13 @@ void ResReporter::CloseLibrary() void *ResReporter::LoadSymbol(const char *symName) { if (!resSchedSoLoaded_) { - LOG(WARNING) << "ResReporter:[LoadSymbol]libframe_ui_intf.so not loaded."; + LOG(DEBUG) << "ResReporter:[LoadSymbol]libframe_ui_intf.so not loaded."; return nullptr; } void *funcSym = dlsym(resSchedHandle_, symName); if (funcSym == nullptr) { - LOG(WARNING) << "ResReporter:[LoadSymbol]Get symbol failed: " << symName; + LOG(DEBUG) << "ResReporter:[LoadSymbol]Get symbol failed: " << symName; return nullptr; } return funcSym; @@ -93,7 +93,7 @@ void ResReporter::AddRtg(std::vector tids) if (resAddRtgFunc_ != nullptr) { return resAddRtgFunc_(tids); } else { - LOG(WARNING) << "ResReporter:[AddRtg]load WebviewAddRtg function failed!"; + LOG(DEBUG) << "ResReporter:[AddRtg]load WebviewAddRtg function failed!"; return; } } @@ -109,7 +109,7 @@ void ResReporter::FetchBegin() if (resFetchBeginFunc_ != nullptr) { return resFetchBeginFunc_(); } else { - LOG(WARNING) << "ResReporter:[FetchBegin]load WebResFetchBegin function failed!"; + LOG(DEBUG) << "ResReporter:[FetchBegin]load WebResFetchBegin function failed!"; return; } } @@ -125,7 +125,7 @@ void ResReporter::FetchEnd() if (resFetchEndFunc_ != nullptr) { return resFetchEndFunc_(); } else { - LOG(WARNING) << "ResReporter:[FetchEnd]load WebResFetchEnd function failed!"; + LOG(DEBUG) << "ResReporter:[FetchEnd]load WebResFetchEnd function failed!"; return; } } \ No newline at end of file diff --git a/libcef/browser/storage/web_storage_impl.cc b/libcef/browser/storage/web_storage_impl.cc index 7165aa071..bd1705ffa 100644 --- a/libcef/browser/storage/web_storage_impl.cc +++ b/libcef/browser/storage/web_storage_impl.cc @@ -621,7 +621,7 @@ CefRefPtr CefWebStorage::GetGlobalManager( // static CefRefPtr CefWebStorage::GetGlobalIncognitoManager( CefRefPtr callback) { - LOG(INFO) << "CefWebStorage::GetGlobalIncognitoManager."; + LOG(INFO) << "CefWebStorage::GetGlobalIncognitoManage."; CefRefPtr context = CefRequestContext::GetGlobalOTRContext(); return context ? context->GetWebStorage(callback) : nullptr; } diff --git a/libcef/common/app_manager.cc b/libcef/common/app_manager.cc index 24f9b13cd..ba1d2fbc8 100644 --- a/libcef/common/app_manager.cc +++ b/libcef/common/app_manager.cc @@ -100,7 +100,6 @@ void CefAppManager::AddAdditionalSchemes( application->OnRegisterCustomSchemes(&schemeRegistrar); schemeRegistrar.GetSchemes(schemes); } - #ifdef OHOS_SCHEME_HANDLER { CefSchemeRegistrarImpl schemeRegistrar; @@ -108,7 +107,7 @@ void CefAppManager::AddAdditionalSchemes( if (cmdLine && cmdLine->HasSwitch(switches::kOhSchemeHandlerCustomScheme)) { std::string cmdlineSchemes = cmdLine->GetSwitchValueASCII(switches::kOhSchemeHandlerCustomScheme); - LOG(INFO) << "render scheme_handler cmdlineScheme:" << cmdlineSchemes; + LOG(INFO) << "scheme_handler cmdlineScheme:" << cmdlineSchemes; absl::optional schemeInfos = base::JSONReader::Read(cmdlineSchemes); if (schemeInfos && schemeInfos->is_dict()) { for (auto kv : schemeInfos->GetDict()) { diff --git a/libcef/common/extensions/api/_api_features.json b/libcef/common/extensions/api/_api_features.json index 7f44cd43f..720c230e5 100644 --- a/libcef/common/extensions/api/_api_features.json +++ b/libcef/common/extensions/api/_api_features.json @@ -43,8 +43,8 @@ "contexts": ["blessed_extension"], "disallow_for_service_workers": false }, - // OHOS_ARKWEB_EXTENSIONS - "developerPrivate": [{ + // OHOS_ARKWEB_EXTENSIONS + "developerPrivate": [{ "dependencies": ["permission:developerPrivate", "permission:management"], "contexts": ["blessed_extension"] }, { @@ -54,5 +54,14 @@ "chrome://extensions/*", "arkweb://extensions/*" ] - }] + }], + "extension": { + "channel": "stable", + "extension_types": ["extension", "legacy_packaged_app"], + "contexts": ["blessed_extension"] + }, + "extension.getURL": { + "contexts": ["blessed_extension", "unblessed_extension", "content_script"], + "max_manifest_version": 2 + } } diff --git a/libcef/common/mojom/cef.mojom b/libcef/common/mojom/cef.mojom index 37fa14fc7..698ba05a8 100644 --- a/libcef/common/mojom/cef.mojom +++ b/libcef/common/mojom/cef.mojom @@ -130,7 +130,7 @@ interface RenderFrame { PutZoomingForTextFactor(float factor); [EnableIf=is_ohos] - GetImageForContextNode(); + GetImageForContextNode(int32 command_id); [EnableIf=is_ohos] GetImagesWithResponse() => (bool response); @@ -164,11 +164,11 @@ interface RenderFrame { [EnableIf=ohos_input_events] SetOverscrollMode(int32 mode); - [EnableIf=is_ohos] - TerminateRenderProcess(); + [EnableIf=ohos_input_events] + UpdateDrawRect(); [EnableIf=is_ohos] - UpdateDrawRect(); + TerminateRenderProcess(); }; // Interface for communicating with a frame in the browser process. @@ -187,10 +187,10 @@ interface BrowserFrame { UpdateDraggableRegions(array? regions); [EnableIf=is_ohos] - OnGetImageForContextNode(GetImageForContextNodeParams params); + OnGetImageForContextNode(GetImageForContextNodeParams params, int32 command_id); [EnableIf=is_ohos] - OnGetImageForContextNodeNull(); + OnGetImageForContextNodeNull(int32 command_id); // Give the application a chance to decide whether to override loading the url. [EnableIf=is_ohos, Sync] diff --git a/libcef/common/request_impl.cc b/libcef/common/request_impl.cc index e172463c6..be55afe7a 100644 --- a/libcef/common/request_impl.cc +++ b/libcef/common/request_impl.cc @@ -46,7 +46,6 @@ #if defined(OHOS_SCHEME_HANDLER) #include "base/datashare_uri_utils.h" -#include "base/task/thread_pool.h" #include "base/files/file.h" #include "net/base/io_buffer.h" #include "services/network/chunked_data_pipe_upload_data_stream.h" @@ -225,7 +224,7 @@ std::unique_ptr CreateUploadDataStream( const bool has_null_source = element.read_only_once().value(); auto upload_data_stream = std::make_unique( - body, element.ReleaseChunkedDataPipeGetter(), has_null_source); + body, element.ReleaseChunkedDataPipeGetter(), has_null_source, true); if (element.read_only_once()) { upload_data_stream->EnableCache(); } @@ -1062,10 +1061,12 @@ CefRefPtr CefPostDataStream::Create() { // CefPostDataStreamImpl ------------------------------------------------------ CefPostDataStreamImpl::CefPostDataStreamImpl() { - } CefPostDataStreamImpl::~CefPostDataStreamImpl() { + if (is_data_pipe_ && upload_stream_) { + content::GetIOThreadTaskRunner({})->DeleteSoon(FROM_HERE, std::move(upload_stream_)); + } } void CefPostDataStreamImpl::Reset() { @@ -1073,6 +1074,17 @@ void CefPostDataStreamImpl::Reset() { init_callback_ = nullptr; } +void CefPostDataStreamImpl::GetChunkedDataPipeGetter( + network::ResourceRequestBody* body) { + LOG(INFO) << "scheme_handler get chunked data pip getter initialated_: " << initialated_; + if (body && upload_stream_ && !initialated_) { + body->SetToChunkedDataPipe( + static_cast(upload_stream_.get()) + ->ReleaseChunkedDataPipeGetter(), + network::ResourceRequestBody::ReadOnlyOnce(HasNullSource())); + } +} + void CefPostDataStreamImpl::Set(network::ResourceRequestBody* body) { std::vector open_files; if (body) { @@ -1083,7 +1095,13 @@ void CefPostDataStreamImpl::Set(network::ResourceRequestBody* body) { LOG(INFO) << "scheme_handler file path: " << file_element.path() << " real path: " << real_path; open_files.push_back(base::File(base::FilePath(real_path), base::File::FLAG_OPEN | base::File::FLAG_READ)); } + + if (element.type() == network::DataElement::Tag::kDataPipe || + element.type() == network::DataElement::Tag::kChunkedDataPipe) { + is_data_pipe_ = true; + } } + scoped_refptr task_runner = base::ThreadPool::CreateSequencedTaskRunner( {base::MayBlock(), base::TaskPriority::USER_VISIBLE}); @@ -1105,6 +1123,7 @@ void CefPostDataStreamImpl::OnStreamInitialized(int rv) { } void CefPostDataStreamImpl::Init(CefRefPtr init_callback) { + initialated_ = true; init_callback_ = init_callback; if (upload_stream_) { int rv = upload_stream_->Init( @@ -1120,7 +1139,31 @@ void CefPostDataStreamImpl::Init(CefRefPtr init_c } } -void CefPostDataStreamImpl::Read( +void CefPostDataStreamImpl::ReadOnTaskRunner( + void* buffer, + int buf_len, + base::WaitableEvent* event) { + scoped_refptr upload_buffer = + base::MakeRefCounted( + reinterpret_cast(buffer)); + if (upload_stream_) { + int rv = upload_stream_->Read( + upload_buffer.get(),buf_len, + base::BindOnce(&CefPostDataStreamImpl::OnStreamRead, + base::Unretained(this), upload_buffer, event)); + if (rv == net::ERR_IO_PENDING) { + last_read_rv_ = rv; + return; + } + last_read_rv_ = rv; + event->Signal(); + } else { + last_read_rv_ = -2; + event->Signal(); + } +} + +void CefPostDataStreamImpl::ReadAsync( void* buffer, int buf_len, CefRefPtr read_callback) { @@ -1130,23 +1173,54 @@ void CefPostDataStreamImpl::Read( if (upload_stream_) { int rv = upload_stream_->Read( upload_buffer.get(),buf_len, - base::BindOnce(&CefPostDataStreamImpl::OnStreamRead, + base::BindOnce(&CefPostDataStreamImpl::OnStreamReadAsync, base::Unretained(this), upload_buffer, read_callback)); - if (rv == net::ERR_IO_PENDING) + if (rv == net::ERR_IO_PENDING) { return; - OnStreamRead(upload_buffer, read_callback, rv); + } + OnStreamReadAsync(upload_buffer, read_callback, rv); } else { - OnStreamRead(upload_buffer, read_callback, -2); + OnStreamReadAsync(upload_buffer, read_callback, -2); } } -void CefPostDataStreamImpl::OnStreamRead( - scoped_refptr buffer, - CefRefPtr read_callback, int rv) { - LOG(INFO) << "scheme_handler CefPostDataStreamImpl::OnStreamRead rv: " << rv; +void CefPostDataStreamImpl::Read( + void* buffer, + int buf_len, + CefRefPtr read_callback) { + if (base::SequencedTaskRunner::HasCurrentDefault() || IsInMemory() || IsChunked()) { + ReadAsync(buffer, buf_len, read_callback); + } else { + if (sequenced_task_runner_) { + base::WaitableEvent* completion = new base::WaitableEvent(); + sequenced_task_runner_->PostTask( + FROM_HERE, base::BindOnce(&CefPostDataStreamImpl::ReadOnTaskRunner, + this, buffer, buf_len, completion)); + completion->Wait(); + delete completion; + read_callback->OnReadComplete((char*)buffer, last_read_rv_); + } else { + read_callback->OnReadComplete((char*)buffer, -2); + } + } +} +void CefPostDataStreamImpl::OnStreamReadAsync( + scoped_refptr buffer, + CefRefPtr read_callback, + int rv) { if (read_callback) { - read_callback->OnReadComplete(buffer->data(), rv); + read_callback->OnReadComplete(buffer->data(), rv); + } +} + +void CefPostDataStreamImpl::OnStreamRead( + scoped_refptr buffer, + base::WaitableEvent* event, + int rv) { + last_read_rv_ = rv; + if (event) { + event->Signal(); } } diff --git a/libcef/common/request_impl.h b/libcef/common/request_impl.h index f24d58f33..23dd69063 100644 --- a/libcef/common/request_impl.h +++ b/libcef/common/request_impl.h @@ -19,8 +19,12 @@ #include "url/gurl.h" #if defined(OHOS_SCHEME_HANDLER) +#include "base/synchronization/waitable_event.h" +#include "base/task/thread_pool.h" #include "net/base/io_buffer.h" #include "net/base/upload_data_stream.h" +#include "services/network/chunked_data_pipe_upload_data_stream.h" +#include "services/network/public/mojom/chunked_data_pipe_getter.mojom.h" #endif namespace blink { @@ -230,17 +234,32 @@ class CefPostDataStreamImpl : public CefPostDataStream { void Set(network::ResourceRequestBody* body); void Reset() override; + void GetChunkedDataPipeGetter(network::ResourceRequestBody* body); + private: void OnStreamInitialized(int rv); void OnStreamRead(scoped_refptr buffer, - CefRefPtr read_callback, + base::WaitableEvent* event, int rv); + void ReadAsync(void* buffer, + int buf_len, + CefRefPtr read_callback); + void OnStreamReadAsync(scoped_refptr buffer, + CefRefPtr read_callback, + int rv); + void ReadOnTaskRunner(void* buffer, + int buf_len, + base::WaitableEvent* event); CefRefPtr read_callback_; CefRefPtr init_callback_; std::unique_ptr upload_stream_; - + bool initialated_{false}; + bool is_data_pipe_{false}; + scoped_refptr sequenced_task_runner_ = + base::ThreadPool::CreateSequencedTaskRunner({}); + int last_read_rv_ = -2; mutable base::Lock lock_; IMPLEMENT_REFCOUNTING(CefPostDataStreamImpl); }; diff --git a/libcef/common/response_impl.cc b/libcef/common/response_impl.cc index 2127045e6..0dc331316 100644 --- a/libcef/common/response_impl.cc +++ b/libcef/common/response_impl.cc @@ -120,6 +120,11 @@ void CefResponseImpl::SetHeaderByName(const CefString& name, std::string nameLower = name; HttpHeaderUtils::MakeASCIILower(&nameLower); + if (!overwrite) { + header_map_.insert(std::make_pair(name, value)); + return; + } + // There may be multiple values, so remove any first. for (auto it = header_map_.begin(); it != header_map_.end();) { if (base::EqualsCaseInsensitiveASCII(it->first.ToString(), nameLower)) { diff --git a/libcef/common/values_impl.cc b/libcef/common/values_impl.cc index 7951809ea..a2ffb7c8d 100644 --- a/libcef/common/values_impl.cc +++ b/libcef/common/values_impl.cc @@ -334,7 +334,7 @@ double CefValueImpl::GetDouble() { return ret_value; } -CefString CefValueImpl::GetString() { +std::string CefValueImpl::GetStdString() { base::AutoLock lock_scope(lock_); std::string ret_value; @@ -344,7 +344,7 @@ CefString CefValueImpl::GetString() { return ret_value; } -std::string CefValueImpl::GetStdString() { +CefString CefValueImpl::GetString() { base::AutoLock lock_scope(lock_); std::string ret_value; diff --git a/libcef/renderer/alloy/alloy_content_renderer_client.cc b/libcef/renderer/alloy/alloy_content_renderer_client.cc index 9f35ac314..ef3b0f121 100644 --- a/libcef/renderer/alloy/alloy_content_renderer_client.cc +++ b/libcef/renderer/alloy/alloy_content_renderer_client.cc @@ -143,7 +143,7 @@ #include "printing/metafile_agent.h" #endif -#include "libcef/renderer/alloy/ohos_safe_browsing_error_page_controller_delegate_impl.h" +#include "libcef/renderer/alloy/alloy_safe_browsing_error_page_controller_delegate_impl.h" AlloyContentRendererClient::AlloyContentRendererClient() : main_entry_time_(base::TimeTicks::Now()), @@ -246,7 +246,6 @@ void AlloyContentRendererClient::RenderThreadStarted() { subresource_filter_ruleset_dealer_ = std::make_unique(); thread->AddObserver(subresource_filter_ruleset_dealer_.get()); - subresource_filter_user_ruleset_dealer_.reset( new subresource_filter::UserUnverifiedRulesetDealer()); thread->AddObserver(subresource_filter_user_ruleset_dealer_.get()); @@ -349,10 +348,11 @@ void AlloyContentRendererClient::PrepareErrorPage( alternative_error_page_info, std::string* error_html) { AlloySafeBrowsingErrorPageControllerDelegateImpl::Get(render_frame) - ->PrepareForErrorPage(); + ->PrepareForErrorPage(); } #endif + void AlloyContentRendererClient::RenderFrameCreated( content::RenderFrame* render_frame) { #if defined(OHOS_FCP) || defined(OHOS_ARKWEB_ADBLOCK) @@ -399,6 +399,17 @@ void AlloyContentRendererClient::RenderFrameCreated( #endif auto render_frame_observer = new CefRenderFrameObserver(render_frame); +#if BUILDFLAG(IS_OHOS) && defined(OHOS_EX_EXCEPTION_LIST) + AlloyContentSettingsClient* alloy_content_settings_client = + new AlloyContentSettingsClient(render_frame); + if (base::CommandLine::ForCurrentProcess()->HasSwitch( + switches::kForBrowser) && + observer_.get() && alloy_content_settings_client) { + alloy_content_settings_client->SetContentSettingRules( + observer_->content_setting_rules()); + } +#endif + #if defined(OHOS_NO_STATE_PREFETCH) new prerender::PrerenderRenderFrameObserver(render_frame); if (!render_frame->IsMainFrame()) { @@ -1010,20 +1021,20 @@ void AlloyContentRendererClient::TriggerElementHidingInFrame(int routing_id) { if (web_frame->GetHasDocumentTypeOption()) { LOG(WARNING) << "[AdBlock] Match $document for " - << document.Url().GetString().Utf8(); + << "***"; return; } if (web_frame->GetHasElemHideTypeOption()) { LOG(WARNING) << "[AdBlock] Match selemhide for " - << document.Url().GetString().Utf8(); + << "***"; return; } bool has_generichide = web_frame->GetHasGenericHideTypeOption(); if (has_generichide) { LOG(WARNING) << "[AdBlock] Match sgenerichide for " - << document.Url().GetString().Utf8(); + << "***"; } base::TimeTicks start = base::TimeTicks::Now(); @@ -1038,7 +1049,7 @@ void AlloyContentRendererClient::TriggerElementHidingInFrame(int routing_id) { blink::WebDocument::StyleSheetType::kAdBlock); base::TimeDelta duration = base::TimeTicks::Now() - start; LOG(WARNING) << "[AdBlock] Element hiding for " - << document.Url().GetString().Utf8() << "assumming " + << "***" << "assumming " << duration.InMicroseconds() << "microseconds"; return; } @@ -1080,7 +1091,7 @@ void AlloyContentRendererClient::TriggerUserElementHidingInFrame( blink::WebDocument::StyleSheetType::kUserAdBlock); base::TimeDelta duration = base::TimeTicks::Now() - start; LOG(WARNING) << "[User AdBlock] Element hiding for " - << document.Url().GetString().Utf8() << " assumming " + << "***" << " assumming " << duration.InMicroseconds() << " microseconds"; return; } diff --git a/libcef/renderer/alloy/alloy_content_settings_client.cc b/libcef/renderer/alloy/alloy_content_settings_client.cc index 031ea46a4..4024b15e7 100644 --- a/libcef/renderer/alloy/alloy_content_settings_client.cc +++ b/libcef/renderer/alloy/alloy_content_settings_client.cc @@ -8,6 +8,56 @@ #include "third_party/blink/public/common/web_preferences/web_preferences.h" #include "third_party/blink/public/web/web_local_frame.h" +#if defined(OHOS_EX_EXCEPTION_LIST) +#include "base/command_line.h" +#include "components/content_settings/core/common/content_settings_pattern.h" +#include "content/public/common/content_switches.h" +#include "content/public/common/url_constants.h" +#include "third_party/blink/public/platform/web_string.h" +#include "third_party/blink/public/web/web_document.h" +#include "url/origin.h" + +namespace { +GURL GetOriginOrURL(const blink::WebFrame* frame) { + url::Origin top_origin = url::Origin(frame->Top()->GetSecurityOrigin()); + // The |top_origin| is unique ("null") e.g., for file:// URLs. Use the + // document URL as the primary URL in those cases. + // TODO(alexmos): This is broken for --site-per-process, since top() can be a + // WebRemoteFrame which does not have a document(), and the WebRemoteFrame's + // URL is not replicated. See https://crbug.com/628759. + if (top_origin.opaque() && frame->Top()->IsWebLocalFrame()) + return frame->Top()->ToWebLocalFrame()->GetDocument().Url(); + return top_origin.GetURL(); +} + +// Allow passing both WebURL and GURL here, so that we can early return +// without allocating a new backing string if only the default rule matches. +template +ContentSetting GetContentSettingFromRules( + const ContentSettingsForOneType& rules, + const blink::WebFrame* frame, + const URL& secondary_url) { + // If there is only one rule, it's the default rule and we don't need to match + // the patterns. + if (rules.size() == 1) { + DCHECK(rules[0].primary_pattern == ContentSettingsPattern::Wildcard()); + DCHECK(rules[0].secondary_pattern == ContentSettingsPattern::Wildcard()); + return rules[0].GetContentSetting(); + } + const GURL& primary_url = GetOriginOrURL(frame); + const GURL& secondary_gurl = secondary_url; + for (const auto& rule : rules) { + if (rule.primary_pattern.Matches(primary_url) && + rule.secondary_pattern.Matches(secondary_gurl)) { + return rule.GetContentSetting(); + } + } + NOTREACHED(); + return CONTENT_SETTING_DEFAULT; +} +} // namespace +#endif + AlloyContentSettingsClient::AlloyContentSettingsClient( content::RenderFrame* render_frame) : content::RenderFrameObserver(render_frame) { @@ -23,3 +73,103 @@ bool AlloyContentSettingsClient::ShouldAutoupgradeMixedContent() { void AlloyContentSettingsClient::OnDestruct() { delete this; } + +#if defined(OHOS_EX_EXCEPTION_LIST) +bool AlloyContentSettingsClient::ShouldAllowlistForContentSettings() const { + return render_frame()->GetWebFrame()->GetDocument().Url().GetString() == + content::kUnreachableWebDataURL; +} + +bool AlloyContentSettingsClient::AllowScript(bool enabled_per_settings) { + if (!base::CommandLine::ForCurrentProcess()->HasSwitch( + switches::kForBrowser)) { + return enabled_per_settings; + } + + if (render_frame() && render_frame()->GetWebFrame()) { + blink::WebLocalFrame* frame = render_frame()->GetWebFrame(); + const auto it = cached_script_permissions_.find(frame); + if (it != cached_script_permissions_.end()) + return it->second; + + // Evaluate the content setting rules before + // IsWhitelistedForContentSettings(); if there is only the default rule + // allowing all scripts, it's quicker this way. + bool allow = true; + if (content_setting_rules_) { + ContentSetting setting = GetContentSettingFromRules( + content_setting_rules_->script_rules, frame, + url::Origin(frame->GetDocument().GetSecurityOrigin()).GetURL()); + allow = setting != CONTENT_SETTING_BLOCK; + } + allow = allow || IsWhitelistedForContentSettings(); + + cached_script_permissions_[frame] = allow; + return allow; + } + if (ShouldAllowlistForContentSettings()) { + return true; + } + return blink::WebContentSettingsClient::AllowScript(enabled_per_settings); +} + +void AlloyContentSettingsClient::SetContentSettingRules( + const RendererContentSettingRules* content_setting_rules) { + content_setting_rules_ = content_setting_rules; +} + +const RendererContentSettingRules* +AlloyContentSettingsClient::GetContentSettingRules() { + return content_setting_rules_; +} + +void AlloyContentSettingsClient::DidCommitProvisionalLoad( + ui::PageTransition transition) { + if (!render_frame()) { + return; + } + + blink::WebLocalFrame* frame = render_frame()->GetWebFrame(); + if (!frame || frame->Parent()) + return; // Not a top-level navigation. + + cached_script_permissions_.clear(); +} + +// static +bool AlloyContentSettingsClient::IsWhitelistedForContentSettings() const { + if (!render_frame() || !render_frame()->GetWebFrame()) { + return false; + } + const blink::WebDocument& document = + render_frame()->GetWebFrame()->GetDocument(); + return IsWhitelistedForContentSettings(document.GetSecurityOrigin(), + document.Url()); +} + +bool AlloyContentSettingsClient::IsWhitelistedForContentSettings( + const blink::WebSecurityOrigin& origin, + const blink::WebURL& document_url) { + if (document_url.GetString() == content::kUnreachableWebDataURL) + return true; + + if (origin.IsOpaque()) + return false; // Uninitialized document? + + blink::WebString protocol = origin.Protocol(); + + if (protocol == content::kChromeUIScheme) + return true; // Browser UI elements should still work. + + if (protocol == content::kChromeDevToolsScheme) + return true; // DevTools UI elements should still work. + + // If the scheme is file:, an empty file name indicates a directory listing, + // which requires JavaScript to function properly. + if (protocol == url::kFileScheme && + document_url.ProtocolIs(url::kFileScheme)) { + return GURL(document_url).ExtractFileName().empty(); + } + return false; +} +#endif \ No newline at end of file diff --git a/libcef/renderer/alloy/alloy_content_settings_client.h b/libcef/renderer/alloy/alloy_content_settings_client.h index c5c7bc2d1..300d48199 100644 --- a/libcef/renderer/alloy/alloy_content_settings_client.h +++ b/libcef/renderer/alloy/alloy_content_settings_client.h @@ -8,6 +8,15 @@ #include "content/public/renderer/render_frame_observer.h" #include "third_party/blink/public/platform/web_content_settings_client.h" +#if defined(OHOS_EX_EXCEPTION_LIST) +#include "base/containers/flat_map.h" +#include "components/content_settings/core/common/content_settings.h" +#include "third_party/blink/public/platform/web_security_origin.h" +#include "third_party/blink/public/platform/web_url.h" +#include "third_party/blink/public/web/web_frame.h" +#include "ui/base/page_transition_types.h" +#endif + // NWeb implementation of blink::WebContentSettingsClient. class AlloyContentSettingsClient : public content::RenderFrameObserver, public blink::WebContentSettingsClient { @@ -18,6 +27,15 @@ class AlloyContentSettingsClient : public content::RenderFrameObserver, explicit AlloyContentSettingsClient(content::RenderFrame* render_view); +#if defined(OHOS_EX_EXCEPTION_LIST) + // Sets the content setting rules which back |allowScript()| and + // |allowScriptFromSource()|. |content_setting_rules| + // must outlive this |AwContentSettingsClient|. + void SetContentSettingRules( + const RendererContentSettingRules* content_setting_rules); + const RendererContentSettingRules* GetContentSettingRules(); +#endif + private: ~AlloyContentSettingsClient() override; @@ -25,6 +43,35 @@ class AlloyContentSettingsClient : public content::RenderFrameObserver, void OnDestruct() override; bool ShouldAutoupgradeMixedContent() override; + +#if defined(OHOS_EX_EXCEPTION_LIST) + bool ShouldAllowlistForContentSettings() const; + + // blink::WebContentSettingsClient implementation. + bool AllowScript(bool enabled_per_settings) override; + + // content::RenderFrameObserver implementation. + void DidCommitProvisionalLoad(ui::PageTransition transition) override; + + // Helpers. + // True if |render_frame()| contains content that is white-listed for content + // settings. + bool IsWhitelistedForContentSettings() const; + + // Exposed for unit tests. + static bool IsWhitelistedForContentSettings( + const blink::WebSecurityOrigin& origin, + const blink::WebURL& document_url); + + // A pointer to content setting rules stored by the renderer. Normally, the + // |RendererContentSettingRules| object is owned by + // |ChromeRenderThreadObserver|. In the tests it is owned by the caller of + // |SetContentSettingRules|. + const RendererContentSettingRules* content_setting_rules_ = nullptr; + + // Caches the result of AllowScript. + base::flat_map cached_script_permissions_; +#endif }; #endif // CEF_LIBCEF_RENDERER_ALLOY_ALLOY_CONTENT_SETTINGS_CLIENT_H_ diff --git a/libcef/renderer/alloy/alloy_render_thread_observer.cc b/libcef/renderer/alloy/alloy_render_thread_observer.cc index 37c6e3505..79145080d 100644 --- a/libcef/renderer/alloy/alloy_render_thread_observer.cc +++ b/libcef/renderer/alloy/alloy_render_thread_observer.cc @@ -61,8 +61,22 @@ void AlloyRenderThreadObserver::SetConfiguration( dynamic_params_ = std::move(params); } +#if defined(OHOS_EX_EXCEPTION_LIST) +void AlloyRenderThreadObserver::SetContentSettingRules( + const RendererContentSettingRules& rules) { + content_setting_rules_ = rules; +} +#endif // defined(OHOS_EX_EXCEPTION_LIST) + void AlloyRenderThreadObserver::OnRendererConfigurationAssociatedRequest( mojo::PendingAssociatedReceiver receiver) { renderer_configuration_receivers_.Add(this, std::move(receiver)); } + +#if defined(OHOS_EX_EXCEPTION_LIST) +const RendererContentSettingRules* +AlloyRenderThreadObserver::content_setting_rules() const { + return &content_setting_rules_; +} +#endif // defined(OHOS_EX_EXCEPTION_LIST) \ No newline at end of file diff --git a/libcef/renderer/alloy/alloy_render_thread_observer.h b/libcef/renderer/alloy/alloy_render_thread_observer.h index 2b4ed4494..9a33af805 100644 --- a/libcef/renderer/alloy/alloy_render_thread_observer.h +++ b/libcef/renderer/alloy/alloy_render_thread_observer.h @@ -15,6 +15,10 @@ #include "content/public/renderer/render_thread_observer.h" #include "mojo/public/cpp/bindings/associated_receiver_set.h" +#if defined(OHOS_EX_EXCEPTION_LIST) +#include "third_party/blink/public/common/associated_interfaces/associated_interface_registry.h" +#endif + // This class sends and receives control messages in the renderer process. class AlloyRenderThreadObserver : public content::RenderThreadObserver, public chrome::mojom::RendererConfiguration { @@ -33,6 +37,10 @@ class AlloyRenderThreadObserver : public content::RenderThreadObserver, // render process is running. chrome::mojom::DynamicParamsPtr GetDynamicParams() const; +#if defined(OHOS_EX_EXCEPTION_LIST) + const RendererContentSettingRules* content_setting_rules() const; +#endif + private: // content::RenderThreadObserver: void RegisterMojoInterfaces( @@ -55,8 +63,14 @@ class AlloyRenderThreadObserver : public content::RenderThreadObserver, mojo::PendingAssociatedReceiver receiver); +#if defined(OHOS_EX_EXCEPTION_LIST) + void SetContentSettingRules(const RendererContentSettingRules& rules) override; +#endif // defined(OHOS_EX_EXCEPTION_LIST) + bool is_incognito_process_ = false; + RendererContentSettingRules content_setting_rules_; + mojo::AssociatedReceiverSet renderer_configuration_receivers_; diff --git a/libcef/renderer/alloy/ohos_safe_browsing_error_page_controller_delegate_impl.cc b/libcef/renderer/alloy/alloy_safe_browsing_error_page_controller_delegate_impl.cc similarity index 60% rename from libcef/renderer/alloy/ohos_safe_browsing_error_page_controller_delegate_impl.cc rename to libcef/renderer/alloy/alloy_safe_browsing_error_page_controller_delegate_impl.cc index ed357959c..257fc3643 100644 --- a/libcef/renderer/alloy/ohos_safe_browsing_error_page_controller_delegate_impl.cc +++ b/libcef/renderer/alloy/alloy_safe_browsing_error_page_controller_delegate_impl.cc @@ -1,19 +1,8 @@ -/* - * Copyright (c) 2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "libcef/renderer/alloy/ohos_safe_browsing_error_page_controller_delegate_impl.h" +// Copyright (c) 2022 Huawei Device Co., Ltd. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/renderer/alloy/alloy_safe_browsing_error_page_controller_delegate_impl.h" #include "content/public/renderer/render_frame.h" @@ -46,4 +35,4 @@ void AlloySafeBrowsingErrorPageControllerDelegateImpl::DidFinishLoad() { security_interstitials::SecurityInterstitialPageController::Install( render_frame()); } -} \ No newline at end of file +} diff --git a/libcef/renderer/alloy/ohos_safe_browsing_error_page_controller_delegate_impl.h b/libcef/renderer/alloy/alloy_safe_browsing_error_page_controller_delegate_impl.h similarity index 71% rename from libcef/renderer/alloy/ohos_safe_browsing_error_page_controller_delegate_impl.h rename to libcef/renderer/alloy/alloy_safe_browsing_error_page_controller_delegate_impl.h index af0ba7d8a..f52aa58c7 100644 --- a/libcef/renderer/alloy/ohos_safe_browsing_error_page_controller_delegate_impl.h +++ b/libcef/renderer/alloy/alloy_safe_browsing_error_page_controller_delegate_impl.h @@ -1,17 +1,6 @@ -/* - * Copyright (c) 2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +// Copyright (c) 2022 Huawei Device Co., Ltd. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. #include "components/security_interstitials/content/renderer/security_interstitial_page_controller.h" #include "components/security_interstitials/core/controller_client.h" diff --git a/libcef/renderer/browser_impl.cc b/libcef/renderer/browser_impl.cc index 4c026df60..4d71ad6bf 100644 --- a/libcef/renderer/browser_impl.cc +++ b/libcef/renderer/browser_impl.cc @@ -28,6 +28,9 @@ #include "third_party/blink/public/web/web_local_frame.h" #include "third_party/blink/public/web/web_security_policy.h" #include "third_party/blink/public/web/web_view.h" +#if defined(OHOS_EX_NAVIGATION) +#include "content/public/browser/navigation_controller.h" +#endif #if BUILDFLAG(IS_OHOS) const char* CONTENT_SIZE_MESSAGE = "ContentSize.Message"; @@ -488,6 +491,29 @@ bool CefBrowserImpl::ShouldShowLoadingUI() { } // #endif // defined(OHOS_NWEB_EX) +#if defined(OHOS_EX_NAVIGATION) +int CefBrowserImpl::InsertBackForwardEntry(int index, const CefString& url) { + return static_cast( + content::NavigationController::NavigationEntryUpdateError::ERR_OTHER); +} + +int CefBrowserImpl::UpdateNavigationEntryUrl(int index, const CefString& url) { + return static_cast( + content::NavigationController::NavigationEntryUpdateError::ERR_OTHER); +} + +void CefBrowserImpl::ClearForwardList() {} +#endif + +#if defined(OHOS_ARKWEB_EXTENSIONS) +void CefBrowserImpl::SetTabId(int32_t tab_id) { + tab_id_ = tab_id; +} +int32_t CefBrowserImpl::GetTabId() { + return tab_id_; +} +#endif + #if BUILDFLAG(IS_OHOS) void CefBrowserImpl::DidUpdateMainFrameLayout() { needs_contents_size_update_ = true; @@ -502,26 +528,35 @@ void CefBrowserImpl::DidCommitCompositorFrame() { blink::WebFrame* main_frame = GetWebView()->MainFrame(); blink::WebLocalFrame* web_local_frame = main_frame->ToWebLocalFrame(); - gfx::Size contents_size = blink_glue::GetContentSize(web_local_frame); + gfx::Size contents_size = main_frame->ToWebLocalFrame()->DocumentSize(); + + if (contents_size.IsEmpty()) { + contents_size = GetWebView()->ContentsPreferredMinimumSize(); + } + int content_width = contents_size.width(); int content_height = contents_size.height(); gfx::Size viewport_size = blink_glue::GetVisualViewportSize(web_local_frame); - if (content_width != content_width_ || content_height != content_height_) { + if (content_width != content_width_ || content_height != content_height_ || + viewport_size.width() != viewport_width_ || + viewport_size.height() != viewport_height_) { content_width_ = content_width; content_height_ = content_height; + viewport_width_ = viewport_size.width(); + viewport_height_ = viewport_size.height(); CefRefPtr message = CefProcessMessage::Create(CONTENT_SIZE_MESSAGE); message->GetArgumentList()->SetInt(0, content_width_); message->GetArgumentList()->SetInt(1, content_height_); message->GetArgumentList()->SetInt(2, viewport_size.width()); message->GetArgumentList()->SetInt(3, viewport_size.height()); auto web_frame = GetMainFrame(); + web_frame->SendProcessMessage(PID_BROWSER, message); LOG(DEBUG) << "Fit content SendProcessMessage Content width: " << content_width << ",height: " << content_height << ". Viewport width:" << viewport_size.width() << ",height:" << viewport_size.height(); - web_frame->SendProcessMessage(PID_BROWSER, message); } } -#endif \ No newline at end of file +#endif diff --git a/libcef/renderer/browser_impl.h b/libcef/renderer/browser_impl.h index 5ed5af4b1..971bdafdd 100644 --- a/libcef/renderer/browser_impl.h +++ b/libcef/renderer/browser_impl.h @@ -96,6 +96,11 @@ class CefBrowserImpl : public CefBrowser, public blink::WebViewObserver { void DidUpdateMainFrameLayout() override; #endif +#if defined(OHOS_ARKWEB_EXTENSIONS) + void SetTabId(int32_t tab_id) override; + int32_t GetTabId() override; +#endif + #if BUILDFLAG(IS_OHOS) bool CanGoBackOrForward(int num_steps) override; void GoBackOrForward(int num_steps) override; @@ -122,12 +127,10 @@ class CefBrowserImpl : public CefBrowser, public blink::WebViewObserver { void PasswordSuggestionSelected(int list_index) override{} // #endif // #ifdefined(OHOS_EX_FREE_COPY) - void SelectAndCopy() override{} - bool ShouldShowFreeCopy() override { return false; } + void ShowFreeCopyMenu() override{} + bool ShouldShowFreeCopyMenu() override { return false; } // #endif int GetNWebId() override { return -1; } - void SetEnableBlankTargetPopupIntercept( - bool enableBlankTargetPopup) override {} #if defined(OHOS_NO_STATE_PREFETCH) void PrefetchPage(CefString& url, CefString& additionalHttpHeaders) override { } @@ -140,6 +143,7 @@ class CefBrowserImpl : public CefBrowser, public blink::WebViewObserver { // #if defined(OHOS_SECURITY_STATE) int GetSecurityLevel() override{ return 0; } // #endif + #endif #if BUILDFLAG(IS_OHOS) @@ -169,6 +173,14 @@ class CefBrowserImpl : public CefBrowser, public blink::WebViewObserver { void UpdateBrowserControlsHeight(int height, bool animate) override {} // #endif // defined(OHOS_NWEB_EX) +#if defined(OHOS_EX_NAVIGATION) + int InsertBackForwardEntry(int index, const CefString& url) override; + + int UpdateNavigationEntryUrl(int index, const CefString& url) override; + + void ClearForwardList() override; +#endif + #ifdef OHOS_BFCACHE void SetBackForwardCacheOptions(int32_t size, int32_t timeToLive) override {} #endif @@ -214,6 +226,12 @@ class CefBrowserImpl : public CefBrowser, public blink::WebViewObserver { int content_width_ = 0; int content_height_ = 0; bool needs_contents_size_update_ = true; + int viewport_width_ = 0; + int viewport_height_ = 0; +#endif + +#if defined(OHOS_ARKWEB_EXTENSIONS) + int tab_id_; #endif IMPLEMENT_REFCOUNTING(CefBrowserImpl); diff --git a/libcef/renderer/extensions/extensions_dispatcher_delegate.cc b/libcef/renderer/extensions/extensions_dispatcher_delegate.cc index 51d3751ef..c73f4ae77 100644 --- a/libcef/renderer/extensions/extensions_dispatcher_delegate.cc +++ b/libcef/renderer/extensions/extensions_dispatcher_delegate.cc @@ -9,6 +9,10 @@ #include "extensions/common/extension_features.h" #include "extensions/renderer/resource_bundle_source_map.h" +#if defined(OHOS_ARKWEB_EXTENSIONS) +#include "chrome/renderer/extensions/api/extension_hooks_delegate.h" +#endif + namespace extensions { CefExtensionsDispatcherDelegate::CefExtensionsDispatcherDelegate() {} @@ -18,4 +22,15 @@ CefExtensionsDispatcherDelegate::~CefExtensionsDispatcherDelegate() {} void CefExtensionsDispatcherDelegate::PopulateSourceMap( extensions::ResourceBundleSourceMap* source_map) {} +#if defined(OHOS_ARKWEB_EXTENSIONS) +void CefExtensionsDispatcherDelegate::InitializeBindingsSystem( + extensions::Dispatcher* dispatcher, + extensions::NativeExtensionBindingsSystem* bindings_system) { + extensions::APIBindingsSystem* bindings = bindings_system->api_system(); + bindings->RegisterHooksDelegate( + "extension", std::make_unique( + bindings_system->messaging_service())); +} +#endif + } // namespace extensions diff --git a/libcef/renderer/extensions/extensions_dispatcher_delegate.h b/libcef/renderer/extensions/extensions_dispatcher_delegate.h index 5ccebb6d5..3ee3574d4 100644 --- a/libcef/renderer/extensions/extensions_dispatcher_delegate.h +++ b/libcef/renderer/extensions/extensions_dispatcher_delegate.h @@ -6,6 +6,10 @@ #define CEF_LIBCEF_RENDERER_EXTENSIONS_EXTENSIONS_DISPATCHER_DELEGATE_H_ #include "extensions/renderer/dispatcher_delegate.h" +#if defined(OHOS_ARKWEB_EXTENSIONS) +#include "extensions/renderer/dispatcher.h" +#include "extensions/renderer/native_extension_bindings_system.h" +#endif namespace extensions { @@ -22,6 +26,11 @@ class CefExtensionsDispatcherDelegate : public DispatcherDelegate { void PopulateSourceMap( extensions::ResourceBundleSourceMap* source_map) override; +#if defined(OHOS_ARKWEB_EXTENSIONS) + void InitializeBindingsSystem( + Dispatcher* dispatcher, + NativeExtensionBindingsSystem* bindings_system) override; +#endif }; } // namespace extensions diff --git a/libcef/renderer/frame_impl.cc b/libcef/renderer/frame_impl.cc index 9adb578e2..f9e789d9d 100644 --- a/libcef/renderer/frame_impl.cc +++ b/libcef/renderer/frame_impl.cc @@ -932,17 +932,16 @@ std::string CefFrameImpl::GetDebugString() const { #if BUILDFLAG(IS_OHOS) void CefFrameImpl::TerminateRenderProcess() { - base::ProcessId realPid = base::GetCurrentRealPid(); LOG(INFO) << "TerminateRenderProcess start in render side, pid: " - << getpid() <<", propid: " << realPid; + << getpid() <<", propid: " << getprocpid(); // try to kill render process by pid if (kill(getpid(), SIGTERM) != 0) { LOG(ERROR) << "Unable to terminate pid: " << getpid(); return; } // if not, kill by procpid - if (kill(realPid, SIGTERM) != 0) { - LOG(ERROR) << "Unable to terminate getprocpid: " << realPid; + if (kill(getprocpid(), SIGTERM) != 0) { + LOG(ERROR) << "Unable to terminate getprocpid: " << getprocpid(); return; } LOG(INFO) << "TerminateRenderProcess end in render side"; @@ -988,7 +987,6 @@ void CefFrameImpl::OnFocusedNodeChanged(const blink::WebElement& element) { return; } #endif // defined(OHOS_INPUT_EVENTS) - cef::mojom::HitDataParamsPtr data = cef::mojom::HitDataParams::New(); data->href = element.GetAttribute("href").Utf16(); data->anchor_text = element.TextContent().Utf16(); @@ -1073,7 +1071,7 @@ void CefFrameImpl::PutZoomingForTextFactor(float factor) { render_frame->GetWebFrame()->FrameWidget()->SetTextZoomFactor(factor); } -void CefFrameImpl::GetImageForContextNode() { +void CefFrameImpl::GetImageForContextNode(int command_id) { if (!frame_) { LOG(ERROR) << "GetImageForContextNode frame is nullptr"; return; @@ -1084,19 +1082,20 @@ void CefFrameImpl::GetImageForContextNode() { cef::mojom::GetImageForContextNodeParamsPtr params = cef::mojom::GetImageForContextNodeParams::New(); - blink::WebNode context_node = frame_->ContextMenuImageNode(); + blink::WebNode context_node = frame_->ContextMenuNode(); std::vector image_data; gfx::Size original_size; std::string image_extension; if (context_node.IsNull() || !context_node.IsElementNode()) { + LOG(WARNING) << "Context node is null or is not element node"; SendToBrowserFrame(__FUNCTION__, base::BindOnce( - [](cef::mojom::GetImageForContextNodeParamsPtr data, + [](cef::mojom::GetImageForContextNodeParamsPtr data,int command_id, const BrowserFrameType& browser_frame) { - browser_frame->OnGetImageForContextNodeNull(); + browser_frame->OnGetImageForContextNodeNull(command_id); }, - std::move(params))); + std::move(params), command_id)); return; } @@ -1110,14 +1109,16 @@ void CefFrameImpl::GetImageForContextNode() { params->height = resize_image.height(); params->image = resize_image; params->image_extension = image_extension; + LOG(DEBUG) << "GetImageForContextNode, image width: " << resize_image.width() + << ", height: " << resize_image.height(); SendToBrowserFrame( __FUNCTION__, base::BindOnce( - [](cef::mojom::GetImageForContextNodeParamsPtr data, + [](cef::mojom::GetImageForContextNodeParamsPtr data,int command_id, const BrowserFrameType& browser_frame) { - browser_frame->OnGetImageForContextNode(std::move(data)); + browser_frame->OnGetImageForContextNode(std::move(data), command_id); }, - std::move(params))); + std::move(params), command_id)); } GURL CefFrameImpl::GetAbsoluteUrl(const blink::WebNode& node, @@ -1365,7 +1366,7 @@ void CefFrameImpl::UpdateDrawRect() { DCHECK(render_frame->IsMainFrame()); blink::WebView* webview = render_frame->GetWebView(); if (!webview) { - LOG(ERROR) << "UpdateDrawRect get webview failed"; + LOG(ERROR) << "SetDrawRect get webview failed"; return; } webview->UpdateDrawRect(); diff --git a/libcef/renderer/frame_impl.h b/libcef/renderer/frame_impl.h index 3dbbdc473..058b67c05 100644 --- a/libcef/renderer/frame_impl.h +++ b/libcef/renderer/frame_impl.h @@ -203,7 +203,7 @@ class CefFrameImpl void SetJsOnlineProperty(bool network_up) override; #endif void PutZoomingForTextFactor(float factor) override; - void GetImageForContextNode() override; + void GetImageForContextNode(int command_id) override; #ifdef OHOS_I18N void UpdateLocale(const std::string& locale) override; #endif // #ifdef OHOS_I18N diff --git a/libcef/renderer/javascript/oh_gin_javascript_function_invocation_helper.cc b/libcef/renderer/javascript/oh_gin_javascript_function_invocation_helper.cc index 23b9c87ba..c724af526 100644 --- a/libcef/renderer/javascript/oh_gin_javascript_function_invocation_helper.cc +++ b/libcef/renderer/javascript/oh_gin_javascript_function_invocation_helper.cc @@ -206,7 +206,7 @@ OhGinJavascriptFunctionInvocationHelper::InvokeJavascriptMethodFlowbuf( gin::Arguments* args, OhGinJavascriptBridgeObject* object) { if (dispatcher_->IsAsyncMethod(object->object_id(), method_name_)) { - return dispatcher_->InvokeJavascriptMethodAsync(object->object_id(), method_name_, arguments); + return InvokeJavascriptMethod(arguments, error, args, object); } auto flowbufferAdapter = OHOS::NWeb::OhosAdapterHelper::GetInstance().CreateFlowbufferAdapter(); diff --git a/libcef_dll/wrapper_types.h b/libcef_dll/wrapper_types.h index 7c8f51c53..f4fc059fc 100644 --- a/libcef_dll/wrapper_types.h +++ b/libcef_dll/wrapper_types.h @@ -9,7 +9,7 @@ // implementations. See the translator.README.txt file in the tools directory // for more information. // -// $hash=07332c4b5860fe074e76179d4ed8c094d66abc86$ +// $hash=3d5dccd3b2c88a430cc79b9105a6969a01e82b86$ // #ifndef CEF_LIBCEF_DLL_WRAPPER_TYPES_H_ @@ -40,6 +40,7 @@ enum CefWrapperType { WT_CALLBACK, WT_CLIENT, WT_COMMAND_HANDLER, + WT_FIRST_MEANINGFUL_PAINT_DETAILS, WT_COMMAND_LINE, WT_COMPLETION_CALLBACK, WT_CONTEXT_MENU_HANDLER, @@ -70,7 +71,6 @@ enum CefWrapperType { WT_FILE_DIALOG_CALLBACK, WT_FILL_LAYOUT, WT_FIND_HANDLER, - WT_FIRST_MEANINGFUL_PAINT_DETAILS, WT_FOCUS_HANDLER, WT_FORM_HANDLER, WT_FRAME, @@ -203,6 +203,7 @@ enum CefWrapperType { WT_VIEW, WT_VIEW_DELEGATE, WT_WAITABLE_EVENT, + WT_WEB_EXTENSION_API_HANDLER, WT_WEB_MESSAGE_RECEIVER, WT_WEB_STORAGE, WT_WINDOW, -- Gitee